@mastra/code-sdk 0.1.0-alpha.1 → 0.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @mastra/code-sdk
2
2
 
3
+ ## 0.1.0-alpha.3
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`177010f`](https://github.com/mastra-ai/mastra/commit/177010ff096d2e4b28d89803be5b1a4cad2a0d6b), [`54a51e0`](https://github.com/mastra-ai/mastra/commit/54a51e0a484fe1ebad3fb1f7ef5282a075709eb7)]:
8
+ - @mastra/core@1.51.0-alpha.3
9
+
10
+ ## 0.1.0-alpha.2
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [[`e955965`](https://github.com/mastra-ai/mastra/commit/e955965dce575a903e37cf054d28ea99aa48785e), [`bc1121a`](https://github.com/mastra-ai/mastra/commit/bc1121a7bb98f7cd73e82e3a7913a667a9fa9911), [`860ef7e`](https://github.com/mastra-ai/mastra/commit/860ef7e77d92b63469cbe5857aa1e626197e43e9), [`17e818c`](https://github.com/mastra-ai/mastra/commit/17e818c51a958ba90641b1a959dc38faf8c034e9), [`4451dfe`](https://github.com/mastra-ai/mastra/commit/4451dfe857428e7abcc0261a507a2e186dae6d47), [`4451dfe`](https://github.com/mastra-ai/mastra/commit/4451dfe857428e7abcc0261a507a2e186dae6d47), [`1d39058`](https://github.com/mastra-ai/mastra/commit/1d39058e548efd691799985d5c8af2737f1c3bd2)]:
15
+ - @mastra/core@1.51.0-alpha.2
16
+ - @mastra/schema-compat@1.3.4-alpha.1
17
+ - @mastra/libsql@1.16.0-alpha.0
18
+ - @mastra/mcp@1.13.1
19
+ - @mastra/memory@1.23.0-alpha.2
20
+
3
21
  ## 0.1.0-alpha.1
4
22
 
5
23
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -14,6 +14,7 @@ import type { McpServerConfig } from './mcp/index.js';
14
14
  import { PluginManager } from './plugins/manager.js';
15
15
  import type { MastraCodeState } from './schema.js';
16
16
  import type { StorageConfig } from './utils/project.js';
17
+ import type { StorageMaintenance } from './utils/storage-maintenance.js';
17
18
  export interface MastraCodeConfig {
18
19
  /** Working directory for project detection. Default: process.cwd() */
19
20
  cwd?: string;
@@ -91,6 +92,7 @@ export declare function createAuthStorage(): AuthStorage;
91
92
  export declare function createMastraCodeAgentController(config?: MastraCodeConfig): Promise<{
92
93
  controller: AgentController<MastraCodeState>;
93
94
  storage: MastraCompositeStore;
95
+ storageMaintenance: StorageMaintenance;
94
96
  observability: Observability;
95
97
  memory: import("@mastra/core/types").DynamicArgument<import("@mastra/core/memory").MastraMemory> | (({ requestContext }: {
96
98
  requestContext: RequestContext;
@@ -137,6 +139,7 @@ export declare function bootLocalAgentController(config?: MastraCodeConfig): Pro
137
139
  session: Session<MastraCodeState>;
138
140
  controller: AgentController<MastraCodeState>;
139
141
  storage: MastraCompositeStore;
142
+ storageMaintenance: StorageMaintenance;
140
143
  observability: Observability;
141
144
  memory: import("@mastra/core/types").DynamicArgument<import("@mastra/core/memory").MastraMemory> | (({ requestContext }: {
142
145
  requestContext: RequestContext;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EAErB,mBAAmB,EACnB,uBAAuB,EAEvB,OAAO,EACR,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAQ7C,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAmB,oBAAoB,EAAE,M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;IACjH,iBAAiB,CAAC,EAAE,CAAC,IAAI,EAAE;QACzB,UAAU,EAAE,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC5C,WAAW,EAAE,WAAW,CAAC;KAC1B,KAAK,IAAI,CAAC,WAAW,CAAC,qBAAqB,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,WAAW,CAAC,CAAC;CACzF,GACA,OAAO,CAAC;IACT,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,+BAA+B,CAAC,CAAC,CAAC;IAClE,UAAU,EAAE,WAAW,CAAC,qBAAqB,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjE,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B,CAAC,CAuBD;AAED;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,iCAA2B,CAAC;AAEzD;;;;GAIG;AACH,OAAO,EACL,KAAK,EACL,QAAQ,EACR,eAAe,EACf,iBAAiB,EACjB,UAAU,EACV,sBAAsB,EACtB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EACV,YAAY,EACZ,WAAW,EACX,WAAW,EACX,UAAU,EACV,aAAa,EACb,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,KAAK,EACL,gBAAgB,EAChB,cAAc,GACf,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -18,6 +18,7 @@ import { InMemoryHarness, MastraCompositeStore } from "@mastra/core/storage";
18
18
  import { DEFAULT_GOAL_JUDGE_PROMPT } from "@mastra/core/tools";
19
19
  import { DuckDBStore } from "@mastra/duckdb";
20
20
  import { GithubSignals } from "@mastra/github-signals";
21
+ import { LibSQLVector } from "@mastra/libsql";
21
22
  import {
22
23
  Observability,
23
24
  MastraStorageExporter,
@@ -66,6 +67,7 @@ import {
66
67
  } from "./utils/project.js";
67
68
  import { createSignalsPubSub } from "./utils/signals-pubsub.js";
68
69
  import { createStorage, createVectorStore } from "./utils/storage-factory.js";
70
+ import { createStorageMaintenance, DEFAULT_RETENTION, resolveLocalDbFiles } from "./utils/storage-maintenance.js";
69
71
  import { acquireThreadLock, releaseThreadLock } from "./utils/thread-lock.js";
70
72
  const CODE_AGENT_ID = "code-agent";
71
73
  const MASTRACODE_ECONNRESET_MAX_RETRIES = 2;
@@ -218,7 +220,9 @@ async function createMastraCodeAgentController(config) {
218
220
  id: "mastra-code-storage",
219
221
  default: storageResult.storage,
220
222
  domains: {
221
- ...observabilityDomain ? { observability: observabilityDomain } : {},
223
+ // When local tracing is off, disable the observability domain entirely so
224
+ // trace/score/feedback writes never fall through to the default libsql store.
225
+ observability: observabilityDomain ?? false,
222
226
  harness: harnessStorage
223
227
  }
224
228
  });
@@ -277,6 +281,13 @@ async function createMastraCodeAgentController(config) {
277
281
  }
278
282
  });
279
283
  const vectorStore = await createVectorStore(storageConfig, storageResult.backend);
284
+ const storageMaintenance = createStorageMaintenance({
285
+ storage: storageResult.storage,
286
+ backend: storageResult.backend,
287
+ retention: DEFAULT_RETENTION,
288
+ localDbFiles: resolveLocalDbFiles(storageConfig, storageResult.backend),
289
+ closeVector: vectorStore instanceof LibSQLVector ? () => vectorStore.close() : void 0
290
+ });
280
291
  const memory = config?.memory === false ? void 0 : config?.memory ?? getDynamicMemory(storage, vectorStore);
281
292
  const mcpManager = config?.disableMcp ? void 0 : createMcpManager(project.rootPath, configDir, config?.mcpServers);
282
293
  const hookManager = config?.disableHooks ? void 0 : new HookManager(project.rootPath, "session-init", configDir, homeDir);
@@ -568,6 +579,7 @@ async function createMastraCodeAgentController(config) {
568
579
  return {
569
580
  controller,
570
581
  storage,
582
+ storageMaintenance,
571
583
  observability,
572
584
  memory,
573
585
  mcpManager,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { hostname } from 'node:os';\nimport path from 'node:path';\n\nimport type { Agent } from '@mastra/core/agent';\nimport { AgentController } from '@mastra/core/agent-controller';\nimport type {\n IntervalHandler,\n AgentControllerConfig,\n AgentControllerEvent,\n AgentControllerMode,\n AgentControllerSubagent,\n AgentControllerRequestContext,\n Session,\n} from '@mastra/core/agent-controller';\nimport { createCodingAgent } from '@mastra/core/coding-agent';\nimport type { PubSub } from '@mastra/core/events';\nimport { PROVIDER_REGISTRY } from '@mastra/core/llm';\nimport type { ProviderConfig } from '@mastra/core/llm';\nimport { Mastra } from '@mastra/core/mastra';\nimport {\n AgentsMDInjector,\n isBadRequestError,\n PrefillErrorHandler,\n ProviderHistoryCompat,\n StreamErrorRetryProcessor,\n} from '@mastra/core/processors';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { PublicSchema } from '@mastra/core/schema';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { TaskSignalProvider } from '@mastra/core/signals';\nimport { InMemoryHarness, MastraCompositeStore } from '@mastra/core/storage';\nimport { DEFAULT_GOAL_JUDGE_PROMPT } from '@mastra/core/tools';\nimport { DuckDBStore } from '@mastra/duckdb';\n\nimport { GithubSignals } from '@mastra/github-signals';\nimport {\n Observability,\n MastraStorageExporter,\n MastraPlatformExporter,\n SensitiveDataFilter,\n} from '@mastra/observability';\n\nimport { getDynamicInstructions } from './agents/instructions.js';\nimport { getDynamicMemory } from './agents/memory.js';\nimport { createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel } from './agents/model.js';\nimport { buildMode } from './agents/modes/build.js';\nimport { fastMode } from './agents/modes/explore.js';\nimport { planMode } from './agents/modes/plan.js';\nimport { getStaticallyLoadedInstructionPaths } from './agents/prompts/agent-instructions.js';\n// import { executeSubagent } from './agents/subagents/execute.js';\n// import { exploreSubagent } from './agents/subagents/explore.js';\n// import { planSubagent } from './agents/subagents/plan.js';\nimport { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from './agents/thread-caveman-state.js';\nimport { createDynamicTools, createToolHooks } from './agents/tools.js';\n\nimport { getDynamicWorkspace, getGoalJudgeTools } from './agents/workspace.js';\nimport { AuthStorage } from './auth/storage.js';\nimport { DEFAULT_CONFIG_DIR, validateConfigDirName } from './constants.js';\nimport { createOutcomeScorer, createEfficiencyScorer } from './evals/scorers/index.js';\nimport { HookManager } from './hooks/index.js';\nimport { createMcpManager } from './mcp/index.js';\nimport type { McpServerConfig } from './mcp/index.js';\nimport type { ProviderAccess } from './onboarding/packs.js';\nimport { getAvailableModePacks, getAvailableOmPacks } from './onboarding/packs.js';\nimport {\n loadSettings,\n MEMORY_GATEWAY_PROVIDER,\n OBSERVABILITY_AUTH_PREFIX,\n resolveModelDefaults,\n resolveOmRoleModel,\n saveSettings,\n} from './onboarding/settings.js';\nimport { getToolCategory } from './permissions.js';\nimport { PluginManager } from './plugins/manager.js';\nimport { PlanRejectionAbortProcessor } from './processors/plan-rejection-abort.js';\nimport { createAmazonBedrockGateway } from './providers/amazon-bedrock-gateway.js';\nimport { setAuthStorage } from './providers/claude-max.js';\nimport { setAuthStorage as setGitHubCopilotAuthStorage } from './providers/github-copilot.js';\nimport { setAuthStorage as setOpenAIAuthStorage } from './providers/openai-codex.js';\n\nimport { stateSchema } from './schema.js';\nimport type { MastraCodeState } from './schema.js';\n\nimport { mastraBrand } from './theme-palette.js';\nimport { syncGateways } from './utils/gateway-sync.js';\nimport {\n detectProject,\n getObservabilityDatabasePath,\n getStorageConfig,\n getResourceIdOverride,\n} from './utils/project.js';\nimport type { StorageConfig } from './utils/project.js';\nimport { createSignalsPubSub } from './utils/signals-pubsub.js';\nimport { createStorage, createVectorStore } from './utils/storage-factory.js';\nimport { acquireThreadLock, releaseThreadLock } from './utils/thread-lock.js';\n\nconst CODE_AGENT_ID = 'code-agent';\n\n// Global retry policy for transient network resets (e.g. provider sockets dropping mid-stream).\n// Applied centrally to every model call via StreamErrorRetryProcessor, independent of model-pack\n// settings, so all modes/subagents benefit from a short wait before retrying an ECONNRESET.\n// Delay uses exponential backoff: initialDelay * 2^retryCount, capped at maxDelay.\nconst MASTRACODE_ECONNRESET_MAX_RETRIES = 2;\nconst MASTRACODE_ECONNRESET_RETRY_INITIAL_DELAY_MS = 1000;\nconst MASTRACODE_ECONNRESET_RETRY_MAX_DELAY_MS = 30000;\n\nconst ECONNRESET_MESSAGE_PATTERN = /econnreset|socket hang up/i;\n\n/**\n * Matcher for transient network-reset failures. Checks the immediate error for\n * an `ECONNRESET` code or a `socket hang up` message. Cause-chain traversal is\n * handled by `StreamErrorRetryProcessor.isRetryableStreamError`, which calls\n * each matcher at every level of the cause chain.\n */\nfunction isECONNRESETError(error: unknown): boolean {\n if (!error) return false;\n\n const code = typeof error === 'object' && 'code' in error ? (error as { code?: unknown }).code : undefined;\n if (typeof code === 'string' && code.toUpperCase() === 'ECONNRESET') return true;\n\n const message = error instanceof Error ? error.message : undefined;\n if (typeof message === 'string' && ECONNRESET_MESSAGE_PATTERN.test(message)) return true;\n\n return false;\n}\n\n/** Short deterministic hash (sha256, first 12 hex chars) matching project.ts shortHash style. */\nfunction shortHash(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 12);\n}\n\nfunction applyEffectiveDefaultsToModes(\n modes: AgentControllerMode[],\n effectiveDefaults: Record<string, string>,\n): AgentControllerMode[] {\n return modes.map(mode => {\n const savedModel = effectiveDefaults[mode.id];\n if (!savedModel) {\n return mode;\n }\n return {\n ...mode,\n defaultModelId: savedModel,\n };\n });\n}\n\nfunction addPluginToolsToModeAllowlists(\n modes: AgentControllerMode[],\n pluginToolNames: string[],\n): AgentControllerMode[] {\n if (pluginToolNames.length === 0) return modes;\n return modes.map(mode => {\n if (!mode.availableTools) return mode;\n return {\n ...mode,\n availableTools: Array.from(new Set([...mode.availableTools, ...pluginToolNames])),\n };\n });\n}\n\nexport interface MastraCodeConfig {\n /** Working directory for project detection. Default: process.cwd() */\n cwd?: string;\n /** Home directory for global config discovery. Default: os.homedir() */\n homeDir?: string;\n /** Override modes (model IDs, colors, which modes exist). Default: build/plan/fast */\n modes?: AgentControllerMode[];\n /** Override or extend subagent definitions. Default: explore/plan/execute */\n subagents?: AgentControllerSubagent[];\n /** Extra tools merged into the dynamic tool set. Can be a static record or a function that receives requestContext. */\n extraTools?:\n | Record<\n string,\n { execute?: (input: unknown, context?: unknown) => Promise<unknown> | unknown; [key: string]: unknown }\n >\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<\n string,\n { execute?: (input: unknown, context?: unknown) => Promise<unknown> | unknown; [key: string]: unknown }\n >);\n /** Tools removed from the dynamic tool set before exposure to the model */\n disabledTools?: string[];\n /** Custom storage config instead of auto-detected default */\n storage?: StorageConfig;\n /** Observational memory scope. Default: auto-detected from env/config files, falls back to 'thread' */\n omScope?: 'thread' | 'resource';\n /** Path to a custom settings.json file. Default: global settings */\n settingsPath?: string;\n /** Initial state overrides (yolo, thinkingLevel, etc.) */\n initialState?: Partial<MastraCodeState>;\n /** Override id generation for threads/messages. Primarily useful for deterministic tests. */\n idGenerator?: AgentControllerConfig<MastraCodeState>['idGenerator'];\n /** Override interval handlers. Default: gateway-sync */\n intervalHandlers?: IntervalHandler[];\n /** Override the workspace. Default: local filesystem + local sandbox based on detected project */\n workspace?: AgentControllerConfig<MastraCodeState>['workspace'];\n /** Override the config directory name. Default: '.mastracode'. Replaces '.mastracode' in all project-level and global config paths (MCP, hooks, commands, database, skills, agent instructions). */\n configDir?: string;\n /** Programmatic MCP server configurations, merged with (and overriding) file-based configs. */\n mcpServers?: Record<string, McpServerConfig>;\n /** Disable MCP server discovery. Default: false */\n disableMcp?: boolean;\n /** Disable hooks. Default: false */\n disableHooks?: boolean;\n /** Disable plugin discovery/loading. Default: false */\n disablePlugins?: boolean;\n /** Override the plugin manager. Primarily useful for tests or embedding. */\n pluginManager?: PluginManager;\n /**\n * Override the memory instance (or dynamic factory) passed to the AgentController.\n * When provided, this replaces the default `getDynamicMemory(storage, vectorStore)` which\n * uses mastracode's built-in model gateway (Anthropic OAuth, OpenAI Codex,\n * custom providers, and models.dev fallback).\n *\n * Use this when you need to override memory model behavior completely.\n */\n memory?: AgentControllerConfig<MastraCodeState>['memory'] | false;\n /** Browser provider for browser automation tools. When set, the agent gains access to browser tools. */\n browser?: AgentControllerConfig<MastraCodeState>['browser'];\n /** PubSub for signal routing. When crossProcessPubSub is true, thread locks are disabled. */\n pubsub?: PubSub;\n /** Use Mastra Code's built-in Unix socket PubSub for local cross-process signal routing. */\n unixSocketPubSub?: boolean;\n /** Marks the configured PubSub as cross-process-safe, allowing Mastra Code to skip file thread locks. */\n crossProcessPubSub?: boolean;\n}\n\nexport function createAuthStorage() {\n const authStorage = new AuthStorage();\n setAuthStorage(authStorage);\n setOpenAIAuthStorage(authStorage);\n setGitHubCopilotAuthStorage(authStorage);\n return authStorage;\n}\n\n/**\n * Resolve cloud observability credentials for the MastraPlatformExporter.\n * Priority: per-resource settings > environment variables > disabled.\n */\nfunction resolveCloudObservabilityConfig(\n settings: ReturnType<typeof loadSettings>,\n authStorage: AuthStorage,\n resourceId: string,\n): { accessToken?: string; projectId?: string } {\n const resourceConfig = settings.observability.resources[resourceId];\n if (resourceConfig) {\n const token = authStorage.getStoredApiKey(`${OBSERVABILITY_AUTH_PREFIX}${resourceId}`);\n if (token) {\n return { accessToken: token, projectId: resourceConfig.projectId };\n }\n }\n // Fall back to environment variables for backwards compatibility\n return {\n accessToken: process.env.MASTRA_CLOUD_ACCESS_TOKEN,\n projectId: process.env.MASTRA_PROJECT_ID,\n };\n}\n\n/**\n * Base factory: builds every shared MastraCode resource (storage, observability,\n * memory, MCP, providers, gateways, agent, modes) and the {@link AgentController}, but\n * does NOT call `init()` or create a session. The controller is returned inert so\n * the composition layer can decide its Mastra ownership and session model.\n *\n * See {@link bootLocalAgentController} (Case 3) and `mountAgentControllerOnMastra` (Cases 1 & 2).\n */\nexport async function createMastraCodeAgentController(config?: MastraCodeConfig) {\n const cwd = config?.cwd ?? process.cwd();\n const homeDir = config?.homeDir ?? config?.initialState?.homeDir;\n const configDir = config?.configDir ?? DEFAULT_CONFIG_DIR;\n // The single session for this process, assigned once `createSession()` runs\n // below. Config callbacks defined before then (e.g. notification stream\n // options) read it lazily through this holder.\n let activeSession: Session<MastraCodeState> | undefined;\n if (configDir !== DEFAULT_CONFIG_DIR) {\n validateConfigDirName(configDir);\n }\n\n // Load .env file from cwd if present (for observability API keys, etc.)\n try {\n process.loadEnvFile(path.join(cwd, '.env'));\n } catch {\n // No .env file — that's fine, keys may be in shell environment\n }\n\n // Auth storage (shared with Claude Max / OpenAI providers and AgentController)\n const authStorage = createAuthStorage();\n const globalSettings = loadSettings(config?.settingsPath);\n const storedGatewayKey = authStorage.getStoredApiKey(MEMORY_GATEWAY_PROVIDER);\n const storedGatewayUrl = globalSettings.memoryGateway?.baseUrl;\n\n if (storedGatewayKey) {\n process.env['MASTRA_GATEWAY_API_KEY'] ??= storedGatewayKey;\n }\n\n if (storedGatewayUrl) {\n process.env['MASTRA_GATEWAY_URL'] ??= storedGatewayUrl;\n }\n\n // Load user-entered API keys from auth.json into process.env\n // (only sets env vars that aren't already present — env vars take precedence)\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n const providerEnvVars: Record<string, string | undefined> = {};\n for (const [provider, cfg] of Object.entries(registry)) {\n const envVars = cfg?.apiKeyEnvVar;\n providerEnvVars[provider] = Array.isArray(envVars) ? envVars[0] : envVars;\n }\n providerEnvVars[MEMORY_GATEWAY_PROVIDER] ??= 'MASTRA_GATEWAY_API_KEY';\n authStorage.loadStoredApiKeysIntoEnv(providerEnvVars);\n } catch {\n // Registry unavailable — load well-known provider keys so non-gateway flows still work\n authStorage.loadStoredApiKeysIntoEnv({\n [MEMORY_GATEWAY_PROVIDER]: 'MASTRA_GATEWAY_API_KEY',\n anthropic: 'ANTHROPIC_API_KEY',\n openai: 'OPENAI_API_KEY',\n google: 'GOOGLE_GENERATIVE_AI_API_KEY',\n cerebras: 'CEREBRAS_API_KEY',\n deepseek: 'DEEPSEEK_API_KEY',\n });\n }\n\n const mgApiKey = process.env['MASTRA_GATEWAY_API_KEY'] ?? storedGatewayKey;\n const mastraGatewayBaseUrl = (\n process.env['MASTRA_GATEWAY_URL'] ??\n storedGatewayUrl ??\n 'https://gateway-api.mastra.ai'\n )\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n const mastraCodeGateway = createMastraCodeGateway({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: false,\n settingsPath: config?.settingsPath,\n });\n const amazonBedrockGateway = createAmazonBedrockGateway();\n\n // Project detection\n const project = detectProject(cwd);\n\n const resourceIdOverride = getResourceIdOverride(project.rootPath, configDir);\n if (resourceIdOverride) {\n project.resourceId = resourceIdOverride;\n project.resourceIdOverride = true;\n }\n\n // Stable session id unique to this project/resource, and a machine-bound owner\n // id. resourceId encodes root path + git identity and honors overrides, so it\n // is the right input for scoping the session to the cwd/project.\n const sessionId = `mastracode-session-${shortHash(project.resourceId)}`;\n const ownerId = `mastracode-${shortHash(`${hostname()}\\0${project.rootPath}`)}`;\n\n const configuredPubSub = config?.pubsub;\n const useUnixSocketPubSub =\n (config?.unixSocketPubSub ?? globalSettings.signals?.unixSocketPubSub ?? false) && process.platform !== 'win32';\n const signalsPubSub = configuredPubSub ?? (useUnixSocketPubSub ? createSignalsPubSub(project.resourceId) : undefined);\n const crossProcessPubSub = config?.crossProcessPubSub ?? (!configuredPubSub && useUnixSocketPubSub);\n if (crossProcessPubSub && !signalsPubSub) {\n throw new Error('crossProcessPubSub requires a pubsub instance');\n }\n\n // Storage\n const storageConfig = config?.storage ?? getStorageConfig(project.rootPath, globalSettings.storage, configDir);\n const storageResult = await createStorage(storageConfig);\n const storageWarning = storageResult.warning;\n\n // Observability storage (DuckDB — separate file for OLAP-style trace/score/feedback queries).\n // Local tracing is opt-in via `/observability local on`. When disabled, the\n // MastraStorageExporter is omitted entirely so traces never fall through to\n // the default libsql backend.\n let observabilityDomain: DuckDBStore['observability'] | undefined;\n let observabilityWarning: string | undefined;\n if (globalSettings.observability.localTracing) {\n try {\n const observabilityDuckDB = new DuckDBStore({\n id: 'mastra-code-observability',\n path: getObservabilityDatabasePath(),\n });\n // Force an early connection attempt so the lock error surfaces now, not mid-session.\n await observabilityDuckDB.db.getConnection();\n observabilityDomain = observabilityDuckDB.observability;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const isLockError = /lock|locked|busy/i.test(message);\n if (isLockError) {\n observabilityWarning =\n 'Observability unavailable — another MastraCode instance holds the database lock. Traces, scores, and feedback will not be recorded in this session.';\n } else {\n observabilityWarning = `Observability unavailable — DuckDB initialization failed: ${message}`;\n }\n }\n }\n\n const harnessStorage = new InMemoryHarness();\n\n const storage = new MastraCompositeStore({\n id: 'mastra-code-storage',\n default: storageResult.storage,\n domains: {\n ...(observabilityDomain ? { observability: observabilityDomain } : {}),\n harness: harnessStorage,\n },\n });\n\n // Observability (tracing, scoring, feedback)\n const observability = new Observability({\n configs: {\n default: {\n serviceName: 'mastracode',\n // Only these requestContext keys are stored on spans — prevents leaking\n // large objects (controller state, workspace, env vars) into trace data.\n // Use dot-notation because these are nested inside the 'controller' key.\n //\n // Session identifiers:\n // threadId, resourceId, session.modeId, agentControllerId\n // Environment & project:\n // state.projectName, state.gitBranch\n // Model configuration:\n // session.modelId, state.subagentModelId\n // Agent settings:\n // state.yolo, state.thinkingLevel, state.smartEditing\n // Observational memory settings:\n // state.omScope, state.observerModelId, state.reflectorModelId,\n // state.observationThreshold, state.reflectionThreshold\n requestContextKeys: [\n // Session identifiers\n 'controller.threadId',\n 'controller.resourceId',\n 'controller.session.modeId',\n 'controller.controllerId',\n // Environment & project\n 'controller.state.projectName',\n 'controller.state.gitBranch',\n // Model configuration\n 'controller.session.modelId',\n 'controller.state.subagentModelId',\n // Agent settings\n 'controller.state.yolo',\n 'controller.state.thinkingLevel',\n 'controller.state.smartEditing',\n // Observational memory settings\n 'controller.state.omScope',\n 'controller.state.observerModelId',\n 'controller.state.reflectorModelId',\n 'controller.state.observationThreshold',\n 'controller.state.reflectionThreshold',\n ],\n exporters: [\n // Only persist traces locally when DuckDB observability is available\n // (via `/observability local on`). Without this guard the storage\n // exporter falls through to the default libsql backend and silently\n // fills the main database with gigabytes of span data.\n ...(observabilityDomain ? [new MastraStorageExporter({ strategy: 'event-sourced' })] : []),\n new MastraPlatformExporter(resolveCloudObservabilityConfig(globalSettings, authStorage, project.resourceId)),\n ],\n spanOutputProcessors: [new SensitiveDataFilter()],\n },\n },\n });\n\n // Vector store for recall search (separate DB file to avoid bloating main storage)\n const vectorStore = await createVectorStore(storageConfig, storageResult.backend);\n\n const memory = config?.memory === false ? undefined : (config?.memory ?? getDynamicMemory(storage, vectorStore));\n\n // MCP\n const mcpManager = config?.disableMcp ? undefined : createMcpManager(project.rootPath, configDir, config?.mcpServers);\n\n // Hooks\n const hookManager = config?.disableHooks\n ? undefined\n : new HookManager(project.rootPath, 'session-init', configDir, homeDir);\n\n const pluginManager = config?.disablePlugins\n ? undefined\n : (config?.pluginManager ?? new PluginManager({ projectRoot: project.rootPath, configDir, homeDir }));\n const loadedPlugins = pluginManager ? await pluginManager.reload() : [];\n const pluginTools = pluginManager?.getPluginTools() ?? {};\n\n // Scorers (live evaluation with sampling)\n const outcomeScorer = createOutcomeScorer();\n const efficiencyScorer = createEfficiencyScorer();\n\n // Agent — githubSignals is created before `controller` but the closure below\n // captures `controller` by reference; it is only invoked at notification time,\n // well after controller is constructed (line ~692). Explicit type annotations\n // on githubSignals, codeAgent, modes, and controller break the circular\n // inference chain this forward reference would otherwise create.\n const githubSignals: GithubSignals | undefined = globalSettings.signals?.experimentalGithubSignals\n ? new GithubSignals({\n cwd: project.rootPath,\n gitcrawlCommand:\n process.env.MASTRACODE_GITCRAWL_BIN ??\n process.env.GITCRAWL_BIN ??\n process.env.MASTRACODE_GITCRAWL_COMMAND ??\n process.env.GITCRAWL_COMMAND,\n getNotificationStreamOptions: async ({ resourceId, threadId }) => {\n // Run the woken notification as the session that owns the target\n // resource so it uses that session's model/mode/state. Fall back to\n // the current session only when no session owns the resource yet.\n const session = (await controller.getSessionByResource(resourceId)) ?? activeSession!;\n // A long-running system must be able to drive work unattended, so a\n // target session without an explicit model selection falls back to a\n // real model rather than failing the run: the current session's live\n // selection (what the user actually picked), then the mode's default.\n const modeId = session.mode.get();\n const defaultModeModelId = controller.listModes().find(mode => mode.id === modeId)?.defaultModelId;\n const modelId = session.model.get() || activeSession?.model.get() || defaultModeModelId || '';\n const requestContext = new RequestContext();\n const agentControllerContext: AgentControllerRequestContext = {\n controllerId: controller.id,\n state: session.state.get(),\n getState: () => session.state.get(),\n setState: updates => session.state.set(updates),\n threadId,\n resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modeId,\n modelId,\n state: {\n get: () => session.state.get(),\n set: updates => session.state.set(updates),\n update: updater => session.state.update(updater),\n },\n },\n workspace: controller.getWorkspace(),\n getSubagentModelId: params => session.subagents.model.get(params ?? {}),\n };\n requestContext.set('controller', agentControllerContext);\n\n return {\n memory: { thread: threadId, resource: resourceId },\n requestContext,\n maxSteps: 1000,\n savePerStep: false,\n requireToolApproval: (session.state.get() as Record<string, unknown>).yolo !== true,\n modelSettings: { temperature: 1 },\n };\n },\n })\n : undefined;\n const codeAgent: Agent = createCodingAgent({\n id: CODE_AGENT_ID,\n name: 'Code Agent',\n // Workspace is wired per-request at the AgentController level (see\n // `config.workspace` below), so opt out of the factory's default local\n // workspace. An explicit `undefined` is required: the factory only builds a\n // default when the `workspace` key is absent.\n workspace: undefined,\n instructions: getDynamicInstructions,\n model: getDynamicModel,\n tools: createDynamicTools(mcpManager, config?.extraTools, config?.disabledTools, storage, pluginTools),\n hooks: createToolHooks(hookManager),\n scorers: {\n outcome: {\n scorer: outcomeScorer,\n sampling: { type: 'none' },\n },\n efficiency: {\n scorer: efficiencyScorer,\n sampling: { type: 'ratio', rate: 0.3 },\n },\n },\n // TaskSignalProvider bundles the task tools + TaskStateProcessor: it merges\n // the tools into the toolset and registers the task state-signal processor,\n // so the task list persists across turns and survives OM truncation.\n signals: [new TaskSignalProvider(), ...(githubSignals ? [githubSignals] : [])],\n // Native goal mechanism: the in-loop goal step judges the thread's active\n // objective each qualifying iteration. The judge model is required for any\n // gating to occur; when unset the goal step is a complete no-op. A6 auto-wires\n // the GoalStateProcessor so the `<current-objective>` signal persists across\n // turns. Per-thread overrides live in the ThreadState `goal` record and win\n // over these defaults.\n goal: {\n // Resolve the judge model through mastracode's gateway (a model-resolver\n // function) so provider credentials are injected; returns undefined when no\n // judge model is configured, keeping the goal step a no-op. Bind the same\n // `settingsPath` used above so the judge model and `maxRuns` come from one\n // config (a custom settings file would otherwise diverge).\n judge: ctx => getGoalJudgeModel(ctx, config?.settingsPath),\n maxRuns: globalSettings.models.goalMaxTurns ?? 50,\n maxSteps: 1000,\n prompt: DEFAULT_GOAL_JUDGE_PROMPT,\n // Read-only workspace tools the default goal judge may call to verify the\n // agent's work against the actual filesystem (view, search_content,\n // find_files, file_stat, lsp_inspect) rather than grading prose alone —\n // restoring the original MastraCode judge's verification ability. Resolved\n // per-request from the active workspace (mirrors `judge`).\n tools: getGoalJudgeTools,\n },\n inputProcessors: [\n new PlanRejectionAbortProcessor(),\n new AgentsMDInjector({\n getIgnoredInstructionPaths: ({ requestContext }) => {\n const agentControllerContext = requestContext?.get('controller') as\n | AgentControllerRequestContext<{ projectPath?: string }>\n | undefined;\n const state = agentControllerContext?.getState();\n return getStaticallyLoadedInstructionPaths(state?.projectPath ?? project.rootPath);\n },\n }),\n new ProviderHistoryCompat(),\n ],\n errorProcessors: [\n new StreamErrorRetryProcessor({\n matchers: [\n { match: isBadRequestError, maxRetries: 1, delayMs: 2000 },\n {\n match: isECONNRESETError,\n maxRetries: MASTRACODE_ECONNRESET_MAX_RETRIES,\n delayMs: ({ retryCount }) =>\n Math.min(\n MASTRACODE_ECONNRESET_RETRY_INITIAL_DELAY_MS * Math.pow(2, retryCount),\n MASTRACODE_ECONNRESET_RETRY_MAX_DELAY_MS,\n ),\n },\n ],\n }),\n new PrefillErrorHandler(),\n new ProviderHistoryCompat(),\n ],\n });\n\n // const defaultSubAgents: Array<AgentControllerSubagent> = [];\n // const defaultSubagents = [exploreSubagent, planSubagent, executeSubagent];\n\n const defaultModes: AgentControllerMode[] = [\n {\n ...buildMode,\n metadata: {\n ...buildMode.metadata,\n color: mastraBrand.green,\n },\n },\n {\n ...planMode,\n metadata: {\n ...planMode.metadata,\n color: mastraBrand.purple,\n },\n },\n {\n ...fastMode,\n metadata: {\n ...fastMode.metadata,\n color: mastraBrand.orange,\n },\n },\n ];\n\n const defaultIntervalHandlers: IntervalHandler[] = [\n {\n id: 'gateway-sync',\n intervalMs: 5 * 60 * 1000,\n immediate: false,\n handler: () => syncGateways(),\n },\n ];\n const intervalHandlers = config?.intervalHandlers ?? defaultIntervalHandlers;\n\n // Build lightweight provider access for resolving built-in packs at startup.\n // Anthropic/OpenAI use AuthStorage; other providers use env API keys.\n // Also scan the full provider registry so configured API keys satisfy access checks.\n const anthropicCred = authStorage.get('anthropic');\n const openaiCred = authStorage.get('openai-codex');\n const githubCopilotCred = authStorage.get('github-copilot');\n const startupAccess: ProviderAccess = {\n anthropic:\n anthropicCred?.type === 'oauth'\n ? 'oauth'\n : anthropicCred?.type === 'api_key' && anthropicCred.key.trim().length > 0\n ? 'apikey'\n : false,\n openai:\n openaiCred?.type === 'oauth'\n ? 'oauth'\n : openaiCred?.type === 'api_key' && openaiCred.key.trim().length > 0\n ? 'apikey'\n : false,\n cerebras: process.env.CEREBRAS_API_KEY ? 'apikey' : false,\n google: process.env.GOOGLE_GENERATIVE_AI_API_KEY ? 'apikey' : false,\n deepseek: process.env.DEEPSEEK_API_KEY ? 'apikey' : false,\n 'github-copilot': githubCopilotCred?.type === 'oauth' ? 'oauth' : false,\n };\n // Gateway covers all providers — ensure Anthropic/OpenAI packs are visible\n if (mgApiKey) {\n if (!startupAccess.anthropic) startupAccess.anthropic = 'apikey';\n if (!startupAccess.openai) startupAccess.openai = 'apikey';\n }\n // Check all providers in the registry for API keys\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n for (const [provider, config] of Object.entries(registry)) {\n if (startupAccess[provider] === 'oauth' || startupAccess[provider] === 'apikey') continue; // Already enabled above\n if (provider === 'anthropic' || provider === 'openai') continue;\n const envVars = config?.apiKeyEnvVar;\n const envVarList = Array.isArray(envVars) ? envVars : envVars ? [envVars] : [];\n if (envVarList.some(envVar => process.env[envVar])) {\n startupAccess[provider] = 'apikey';\n }\n }\n } catch {\n // Registry may not be loaded yet; the 5 hardcoded providers are sufficient fallback\n }\n const builtinPacks = getAvailableModePacks(startupAccess);\n const builtinOmPacks = getAvailableOmPacks(startupAccess);\n const effectiveDefaults = resolveModelDefaults(globalSettings, builtinPacks);\n const effectiveObserverModel = resolveOmRoleModel(globalSettings, 'observer', builtinOmPacks);\n const effectiveReflectorModel = resolveOmRoleModel(globalSettings, 'reflector', builtinOmPacks);\n const effectiveObservationThreshold = globalSettings.models.omObservationThreshold ?? undefined;\n const effectiveReflectionThreshold = globalSettings.models.omReflectionThreshold ?? undefined;\n const effectiveCavemanObservations = globalSettings.models.omCavemanObservations ?? undefined;\n const effectiveObserveAttachments = globalSettings.models.omObserveAttachments ?? 'auto';\n\n const modes = addPluginToolsToModeAllowlists(\n applyEffectiveDefaultsToModes(config?.modes ? config.modes : defaultModes, effectiveDefaults),\n Object.keys(pluginTools),\n );\n const defaultModeId =\n modes.find(mode => mode.metadata?.default === true)?.id ??\n modes.find(mode => mode.id === 'build')?.id ??\n modes[0]?.id;\n if (!defaultModeId) {\n throw new Error('MastraCode requires at least one mode');\n }\n\n // Map subagent types to mode models: explore→fast, plan→plan, execute→build\n // const subagentModeMap: Record<string, string> = { explore: 'fast', plan: 'plan', execute: 'build' };\n // Subagents inherit workspace tools from the parent agent's workspace automatically.\n // Apply disabledTools filter to both default and custom subagents.\n // const subagents = [];\n\n // Build initial state with global preferences\n const globalInitialState: Partial<MastraCodeState> = {};\n if (effectiveObserverModel) {\n globalInitialState.observerModelId = effectiveObserverModel;\n }\n if (effectiveReflectorModel) {\n globalInitialState.reflectorModelId = effectiveReflectorModel;\n }\n if (effectiveObservationThreshold !== undefined) {\n globalInitialState.observationThreshold = effectiveObservationThreshold;\n }\n if (effectiveReflectionThreshold !== undefined) {\n globalInitialState.reflectionThreshold = effectiveReflectionThreshold;\n }\n if (effectiveCavemanObservations !== undefined) {\n globalInitialState.cavemanObservations = effectiveCavemanObservations;\n }\n if (effectiveObserveAttachments !== undefined) {\n globalInitialState.observeAttachments = effectiveObserveAttachments;\n }\n if (globalSettings.preferences.yolo !== null) {\n globalInitialState.yolo = globalSettings.preferences.yolo;\n }\n globalInitialState.thinkingLevel = globalSettings.preferences.thinkingLevel;\n if (config?.omScope) {\n globalInitialState.omScope = config.omScope;\n }\n // Seed subagent models from global settings\n for (const [key, modelId] of Object.entries(globalSettings.models.subagentModels)) {\n if (key === 'default' || key === '_default') {\n globalInitialState.subagentModelId = modelId;\n } else {\n globalInitialState[`subagentModelId_${key}`] = modelId;\n }\n }\n\n const typedStateSchema = stateSchema as PublicSchema<MastraCodeState>;\n const controller: AgentController<MastraCodeState> = new AgentController<MastraCodeState>({\n id: 'mastra-code',\n resourceId: project.resourceId,\n storage,\n observability,\n memory,\n pubsub: signalsPubSub,\n stateSchema: typedStateSchema,\n agent: codeAgent,\n subagents: config?.subagents ?? [],\n gateways: [amazonBedrockGateway, mastraCodeGateway],\n workspace: config?.workspace ?? (args => getDynamicWorkspace(args)),\n browser: config?.browser,\n idGenerator: config?.idGenerator,\n toolCategoryResolver: getToolCategory,\n initialState: {\n projectPath: project.rootPath,\n projectName: project.name,\n gitBranch: project.gitBranch,\n pluginSkillPaths: loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : [])),\n pluginCommandPaths: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' ? (plugin.commandPaths ?? []) : [],\n ),\n pluginInstructions: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n ),\n yolo: true,\n ...globalInitialState,\n ...config?.initialState,\n // configDir must always win over initialState spreads to stay in sync\n // with MCP/hooks/storage which were already initialized with this value.\n configDir,\n },\n modes,\n intervalHandlers,\n modelUseCountProvider: () => loadSettings().modelUseCounts,\n modelUseCountTracker: modelId => {\n try {\n const settings = loadSettings();\n settings.modelUseCounts[modelId] = (settings.modelUseCounts[modelId] ?? 0) + 1;\n saveSettings(settings);\n } catch (error) {\n console.error('Failed to persist model usage count', error);\n }\n },\n threadLock: crossProcessPubSub\n ? undefined\n : {\n acquire: acquireThreadLock,\n release: releaseThreadLock,\n },\n });\n\n // The AgentController is fully constructed but intentionally NOT inited here. Init and\n // session creation are deferred to the composition layer (see below) so the\n // controller can be wired in three ways:\n //\n // 1. Server + Web — registered on a server Mastra, then inited; sessions\n // minted per browser client over HTTP.\n // 2. Server + TUI — same server composition; the TUI drives a session\n // (in-process today; remote transport is future work).\n // 3. Local + TUI — controller builds its own internal Mastra on init() and\n // mints one eager session for the whole process.\n //\n // Cases 1 & 2 use `mountAgentControllerOnMastra` (register-before-init, no eager\n // session). Case 3 uses `bootLocalAgentController` (init + one wired session).\n return {\n controller: controller,\n storage,\n observability,\n memory,\n mcpManager,\n hookManager,\n pluginManager,\n loadedPlugins,\n pluginTools,\n signalsPubSub,\n authStorage,\n resolveModel,\n storageWarning,\n observabilityWarning,\n builtinPacks,\n builtinOmPacks,\n effectiveDefaults,\n githubSignals,\n // Identity for the single local session (Case 3). Servers ignore these and\n // mint per-request sessions with client-supplied resourceIds instead.\n sessionId,\n ownerId,\n // Lets the composition layer publish the created session back into the\n // config closures (e.g. notification stream options read it lazily).\n setActiveSession: (session: Session<MastraCodeState>) => {\n activeSession = session;\n },\n };\n}\n\n/**\n * Result of {@link createMastraCodeAgentController}: every shared resource plus the\n * inert AgentController, ready to be either booted locally or mounted on a server\n * Mastra.\n */\nexport type MastraCodeAgentController = Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n\n/**\n * Wires the session-scoped concerns MastraCode layers on top of a Session:\n * hookManager thread-id sync, GitHub PR polling for the current thread, and\n * per-thread persistence of the mastracode-only `/om` settings.\n *\n * Used by {@link bootLocalAgentController} for the single local session. A server can\n * call this for any session it mints if it wants the same background wiring.\n */\nexport async function wireSessionConcerns(\n base: Pick<MastraCodeAgentController, 'hookManager' | 'githubSignals' | 'setActiveSession'>,\n session: Session<MastraCodeState>,\n): Promise<void> {\n const { hookManager, githubSignals } = base;\n base.setActiveSession(session);\n\n // Sync hookManager session ID on thread changes\n if (hookManager) {\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') {\n hookManager.setSessionId(event.threadId);\n } else if (event.type === 'thread_created') {\n hookManager.setSessionId(event.thread.id);\n }\n });\n }\n\n if (githubSignals) {\n const startGithubPollingForCurrentThread = async (threadId?: string | null) => {\n if (!threadId) return;\n githubSignals.stopAllPolling();\n try {\n const threads = await session.thread.list({ allResources: true });\n const thread = threads.find((item: { id: string }) => item.id === threadId);\n await githubSignals.startPollingForThread(\n {\n threadId,\n resourceId: thread?.resourceId ?? session.identity.getResourceId(),\n },\n { pollImmediately: true },\n );\n } catch (error) {\n console.warn('Failed to start GitHub PR polling:', error);\n }\n };\n\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') void startGithubPollingForCurrentThread(event.threadId);\n else if (event.type === 'thread_created') void startGithubPollingForCurrentThread(event.thread.id);\n });\n void startGithubPollingForCurrentThread(session.thread.getId());\n }\n\n // Persist MastraCode-owned /om settings per-thread (mastracode-only concern;\n // intentionally not in core's controller loadThreadMetadata).\n const omThreadStateSession = session as unknown as Session<Record<string, unknown>>;\n attachOMThreadStatePersistence(omThreadStateSession);\n await restoreOMThreadStateForCurrentThread(omThreadStateSession).catch(() => {\n // Persistence is best-effort; don't crash startup if storage hiccups.\n });\n}\n\n/**\n * Case 3 (AgentController local + TUI/headless): build the controller, let it stand up its\n * own internal Mastra via `init()`, and mint the single eager session that all\n * work in this process runs through. The AgentController owns no session of its own.\n */\nexport async function bootLocalAgentController(config?: MastraCodeConfig) {\n const base = await createMastraCodeAgentController(config);\n const { controller, sessionId, ownerId } = base;\n\n await controller.init();\n await controller.getMastra()?.startWorkers();\n const session = await controller.createSession({ id: sessionId, ownerId });\n await wireSessionConcerns(base, session);\n\n return { ...base, session };\n}\n\n/** Result of {@link mountAgentControllerOnMastra}: shared handles plus the owning Mastra. */\nexport type MountedMastraCode = MastraCodeAgentController & { mastra: Mastra };\n\n/**\n * Cases 1 & 2 (AgentController in Server + Web/TUI): build the controller, register it on a\n * server-owned Mastra, THEN init it. Registering before `init()` is what makes\n * the controller inherit the server's Mastra (storage, agents, gateways) instead of\n * spinning up its own internal one — there is a single shared Mastra.\n *\n * No eager session is minted: each client (browser or terminal) creates/resumes\n * its own isolated session via `controller.createSession({ resourceId })`, so one\n * server can drive many concurrent users.\n *\n * Pass an existing `mastra` to mount onto a Mastra that already hosts other\n * primitives; otherwise a Mastra is created that owns the controller's storage so\n * durability is configured in one place.\n */\nexport async function mountAgentControllerOnMastra(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n /**\n * Additional `server` config to fold onto the constructed Mastra alongside\n * the assembled `apiRoutes` (e.g. `middleware`, `cors`). Used by the\n * platform entry (`src/mastra/index.ts`) to own the WorkOS gate + tenant\n * dispatcher + CORS on the instance the deployer generates its server from.\n * Ignored when `mastra` is provided (mounting onto a caller-owned instance).\n */\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<MountedMastraCode> {\n const prepared = await prepareAgentControllerMount(config);\n if (config?.mastra) {\n // Mounting onto a Mastra the caller already built. Ensure the controller's\n // back-reference points at it (idempotent — only sets #externalMastra).\n prepared.base.controller.__registerMastra(config.mastra);\n await prepared.finalize();\n return { ...prepared.base, mastra: config.mastra };\n }\n const mastra = new Mastra(prepared.mastraArgs);\n await prepared.finalize();\n return { ...prepared.base, mastra };\n}\n\n/**\n * Assemble everything needed to construct the server-owned Mastra WITHOUT\n * constructing it, so a caller (the platform entry `src/mastra/index.ts`) can\n * run the `new Mastra(...)` literal in its own module. The deployer's\n * `checkConfigExport` Babel plugin only marks the config valid when it finds a\n * top-level `new Mastra(...)` exported as `mastra` in the ENTRY file; hiding the\n * construction inside this helper would trip the \"Invalid Mastra config\" warning.\n *\n * Returns the constructor args plus a `finalize()` that runs the post-construct\n * boot (`controller.init()` + `startWorkers()`). The controller is registered on\n * the Mastra via the `agentControllers` arg at construction time.\n */\nexport async function prepareAgentControllerMount(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<{\n base: Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n mastraArgs: NonNullable<ConstructorParameters<typeof Mastra>[0]>;\n finalize: () => Promise<void>;\n}> {\n const base = await createMastraCodeAgentController(config);\n const { controller, storage, authStorage } = base;\n const controllerId = config?.controllerId ?? controller.id;\n const apiRoutes = config?.buildApiRoutes?.({ controller, authStorage });\n const extraServerConfig = config?.buildServerConfig?.({ controller, authStorage });\n\n const serverConfig = {\n ...extraServerConfig,\n ...(apiRoutes?.length ? { apiRoutes } : {}),\n };\n const mastraArgs = {\n agentControllers: { [controllerId]: controller },\n storage,\n ...(Object.keys(serverConfig).length ? { server: serverConfig } : {}),\n };\n\n const finalize = async () => {\n await controller.init();\n await controller.getMastra()?.startWorkers();\n };\n\n return { base, mastraArgs, finalize };\n}\n\n/**\n * Back-compat alias. Historically `createMastraCode` built and booted a local\n * controller with a single session; that behavior now lives in\n * {@link bootLocalAgentController}. New code should call the explicit factory for its\n * case: `bootLocalAgentController` (local) or {@link mountAgentControllerOnMastra} (server).\n */\nexport const createMastraCode = bootLocalAgentController;\n\n/**\n * Programmatic headless API. `runMC` runs an already-built controller/session\n * (from {@link createMastraCode}) as an async-iterable run that also resolves to\n * a typed result. Also available via the `mastracode/headless` subpath.\n */\nexport {\n runMC,\n runMCCli,\n hasHeadlessFlag,\n autoApprovePolicy,\n denyPolicy,\n permissionModeToPolicy,\n formatHuman,\n formatJsonl,\n renderTextResult,\n renderJsonResult,\n} from './headless/index.js';\nexport type {\n RunMCOptions,\n RunMCResult,\n RunMCStatus,\n RunMCUsage,\n RunMCToolCall,\n RunMCToolResult,\n RunMCError,\n RunMCThreadOptions,\n MCRun,\n ResolutionPolicy,\n PermissionMode,\n} from './headless/index.js';\n"],"mappings":"AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,OAAO,UAAU;AAGjB,SAAS,uBAAuB;AAUhC,SAAS,yBAAyB;AAElC,SAAS,yBAAyB;AAElC,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAG/B,SAAS,0BAA0B;AACnC,SAAS,iBAAiB,4BAA4B;AACtD,SAAS,iCAAiC;AAC1C,SAAS,mBAAmB;AAE5B,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,8BAA8B;AACvC,SAAS,wBAAwB;AACjC,SAAS,yBAAyB,iBAAiB,mBAAmB,oBAAoB;AAC1F,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,SAAS,2CAA2C;AAIpD,SAAS,gCAAgC,4CAA4C;AAC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G;AAAA,IACH,GAAI,WAAW,SAAS,EAAE,UAAU,IAAI,CAAC;AAAA,EAC3C;AACA,QAAM,aAAa;AAAA,IACjB,kBAAkB,EAAE,CAAC,YAAY,GAAG,WAAW;AAAA,IAC/C;AAAA,IACA,GAAI,OAAO,KAAK,YAAY,EAAE,SAAS,EAAE,QAAQ,aAAa,IAAI,CAAC;AAAA,EACrE;AAEA,QAAM,WAAW,YAAY;AAC3B,UAAM,WAAW,KAAK;AACtB,UAAM,WAAW,UAAU,GAAG,aAAa;AAAA,EAC7C;AAEA,SAAO,EAAE,MAAM,YAAY,SAAS;AACtC;AAQO,MAAM,mBAAmB;AAOhC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["config"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { hostname } from 'node:os';\nimport path from 'node:path';\n\nimport type { Agent } from '@mastra/core/agent';\nimport { AgentController } from '@mastra/core/agent-controller';\nimport type {\n IntervalHandler,\n AgentControllerConfig,\n AgentControllerEvent,\n AgentControllerMode,\n AgentControllerSubagent,\n AgentControllerRequestContext,\n Session,\n} from '@mastra/core/agent-controller';\nimport { createCodingAgent } from '@mastra/core/coding-agent';\nimport type { PubSub } from '@mastra/core/events';\nimport { PROVIDER_REGISTRY } from '@mastra/core/llm';\nimport type { ProviderConfig } from '@mastra/core/llm';\nimport { Mastra } from '@mastra/core/mastra';\nimport {\n AgentsMDInjector,\n isBadRequestError,\n PrefillErrorHandler,\n ProviderHistoryCompat,\n StreamErrorRetryProcessor,\n} from '@mastra/core/processors';\nimport { RequestContext } from '@mastra/core/request-context';\nimport type { PublicSchema } from '@mastra/core/schema';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { TaskSignalProvider } from '@mastra/core/signals';\nimport { InMemoryHarness, MastraCompositeStore } from '@mastra/core/storage';\nimport { DEFAULT_GOAL_JUDGE_PROMPT } from '@mastra/core/tools';\nimport { DuckDBStore } from '@mastra/duckdb';\n\nimport { GithubSignals } from '@mastra/github-signals';\nimport { LibSQLVector } from '@mastra/libsql';\nimport {\n Observability,\n MastraStorageExporter,\n MastraPlatformExporter,\n SensitiveDataFilter,\n} from '@mastra/observability';\n\nimport { getDynamicInstructions } from './agents/instructions.js';\nimport { getDynamicMemory } from './agents/memory.js';\nimport { createMastraCodeGateway, getDynamicModel, getGoalJudgeModel, resolveModel } from './agents/model.js';\nimport { buildMode } from './agents/modes/build.js';\nimport { fastMode } from './agents/modes/explore.js';\nimport { planMode } from './agents/modes/plan.js';\nimport { getStaticallyLoadedInstructionPaths } from './agents/prompts/agent-instructions.js';\n// import { executeSubagent } from './agents/subagents/execute.js';\n// import { exploreSubagent } from './agents/subagents/explore.js';\n// import { planSubagent } from './agents/subagents/plan.js';\nimport { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from './agents/thread-caveman-state.js';\nimport { createDynamicTools, createToolHooks } from './agents/tools.js';\n\nimport { getDynamicWorkspace, getGoalJudgeTools } from './agents/workspace.js';\nimport { AuthStorage } from './auth/storage.js';\nimport { DEFAULT_CONFIG_DIR, validateConfigDirName } from './constants.js';\nimport { createOutcomeScorer, createEfficiencyScorer } from './evals/scorers/index.js';\nimport { HookManager } from './hooks/index.js';\nimport { createMcpManager } from './mcp/index.js';\nimport type { McpServerConfig } from './mcp/index.js';\nimport type { ProviderAccess } from './onboarding/packs.js';\nimport { getAvailableModePacks, getAvailableOmPacks } from './onboarding/packs.js';\nimport {\n loadSettings,\n MEMORY_GATEWAY_PROVIDER,\n OBSERVABILITY_AUTH_PREFIX,\n resolveModelDefaults,\n resolveOmRoleModel,\n saveSettings,\n} from './onboarding/settings.js';\nimport { getToolCategory } from './permissions.js';\nimport { PluginManager } from './plugins/manager.js';\nimport { PlanRejectionAbortProcessor } from './processors/plan-rejection-abort.js';\nimport { createAmazonBedrockGateway } from './providers/amazon-bedrock-gateway.js';\nimport { setAuthStorage } from './providers/claude-max.js';\nimport { setAuthStorage as setGitHubCopilotAuthStorage } from './providers/github-copilot.js';\nimport { setAuthStorage as setOpenAIAuthStorage } from './providers/openai-codex.js';\n\nimport { stateSchema } from './schema.js';\nimport type { MastraCodeState } from './schema.js';\n\nimport { mastraBrand } from './theme-palette.js';\nimport { syncGateways } from './utils/gateway-sync.js';\nimport {\n detectProject,\n getObservabilityDatabasePath,\n getStorageConfig,\n getResourceIdOverride,\n} from './utils/project.js';\nimport type { StorageConfig } from './utils/project.js';\nimport { createSignalsPubSub } from './utils/signals-pubsub.js';\nimport { createStorage, createVectorStore } from './utils/storage-factory.js';\nimport { createStorageMaintenance, DEFAULT_RETENTION, resolveLocalDbFiles } from './utils/storage-maintenance.js';\nimport type { StorageMaintenance } from './utils/storage-maintenance.js';\nimport { acquireThreadLock, releaseThreadLock } from './utils/thread-lock.js';\n\nconst CODE_AGENT_ID = 'code-agent';\n\n// Global retry policy for transient network resets (e.g. provider sockets dropping mid-stream).\n// Applied centrally to every model call via StreamErrorRetryProcessor, independent of model-pack\n// settings, so all modes/subagents benefit from a short wait before retrying an ECONNRESET.\n// Delay uses exponential backoff: initialDelay * 2^retryCount, capped at maxDelay.\nconst MASTRACODE_ECONNRESET_MAX_RETRIES = 2;\nconst MASTRACODE_ECONNRESET_RETRY_INITIAL_DELAY_MS = 1000;\nconst MASTRACODE_ECONNRESET_RETRY_MAX_DELAY_MS = 30000;\n\nconst ECONNRESET_MESSAGE_PATTERN = /econnreset|socket hang up/i;\n\n/**\n * Matcher for transient network-reset failures. Checks the immediate error for\n * an `ECONNRESET` code or a `socket hang up` message. Cause-chain traversal is\n * handled by `StreamErrorRetryProcessor.isRetryableStreamError`, which calls\n * each matcher at every level of the cause chain.\n */\nfunction isECONNRESETError(error: unknown): boolean {\n if (!error) return false;\n\n const code = typeof error === 'object' && 'code' in error ? (error as { code?: unknown }).code : undefined;\n if (typeof code === 'string' && code.toUpperCase() === 'ECONNRESET') return true;\n\n const message = error instanceof Error ? error.message : undefined;\n if (typeof message === 'string' && ECONNRESET_MESSAGE_PATTERN.test(message)) return true;\n\n return false;\n}\n\n/** Short deterministic hash (sha256, first 12 hex chars) matching project.ts shortHash style. */\nfunction shortHash(input: string): string {\n return createHash('sha256').update(input).digest('hex').slice(0, 12);\n}\n\nfunction applyEffectiveDefaultsToModes(\n modes: AgentControllerMode[],\n effectiveDefaults: Record<string, string>,\n): AgentControllerMode[] {\n return modes.map(mode => {\n const savedModel = effectiveDefaults[mode.id];\n if (!savedModel) {\n return mode;\n }\n return {\n ...mode,\n defaultModelId: savedModel,\n };\n });\n}\n\nfunction addPluginToolsToModeAllowlists(\n modes: AgentControllerMode[],\n pluginToolNames: string[],\n): AgentControllerMode[] {\n if (pluginToolNames.length === 0) return modes;\n return modes.map(mode => {\n if (!mode.availableTools) return mode;\n return {\n ...mode,\n availableTools: Array.from(new Set([...mode.availableTools, ...pluginToolNames])),\n };\n });\n}\n\nexport interface MastraCodeConfig {\n /** Working directory for project detection. Default: process.cwd() */\n cwd?: string;\n /** Home directory for global config discovery. Default: os.homedir() */\n homeDir?: string;\n /** Override modes (model IDs, colors, which modes exist). Default: build/plan/fast */\n modes?: AgentControllerMode[];\n /** Override or extend subagent definitions. Default: explore/plan/execute */\n subagents?: AgentControllerSubagent[];\n /** Extra tools merged into the dynamic tool set. Can be a static record or a function that receives requestContext. */\n extraTools?:\n | Record<\n string,\n { execute?: (input: unknown, context?: unknown) => Promise<unknown> | unknown; [key: string]: unknown }\n >\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<\n string,\n { execute?: (input: unknown, context?: unknown) => Promise<unknown> | unknown; [key: string]: unknown }\n >);\n /** Tools removed from the dynamic tool set before exposure to the model */\n disabledTools?: string[];\n /** Custom storage config instead of auto-detected default */\n storage?: StorageConfig;\n /** Observational memory scope. Default: auto-detected from env/config files, falls back to 'thread' */\n omScope?: 'thread' | 'resource';\n /** Path to a custom settings.json file. Default: global settings */\n settingsPath?: string;\n /** Initial state overrides (yolo, thinkingLevel, etc.) */\n initialState?: Partial<MastraCodeState>;\n /** Override id generation for threads/messages. Primarily useful for deterministic tests. */\n idGenerator?: AgentControllerConfig<MastraCodeState>['idGenerator'];\n /** Override interval handlers. Default: gateway-sync */\n intervalHandlers?: IntervalHandler[];\n /** Override the workspace. Default: local filesystem + local sandbox based on detected project */\n workspace?: AgentControllerConfig<MastraCodeState>['workspace'];\n /** Override the config directory name. Default: '.mastracode'. Replaces '.mastracode' in all project-level and global config paths (MCP, hooks, commands, database, skills, agent instructions). */\n configDir?: string;\n /** Programmatic MCP server configurations, merged with (and overriding) file-based configs. */\n mcpServers?: Record<string, McpServerConfig>;\n /** Disable MCP server discovery. Default: false */\n disableMcp?: boolean;\n /** Disable hooks. Default: false */\n disableHooks?: boolean;\n /** Disable plugin discovery/loading. Default: false */\n disablePlugins?: boolean;\n /** Override the plugin manager. Primarily useful for tests or embedding. */\n pluginManager?: PluginManager;\n /**\n * Override the memory instance (or dynamic factory) passed to the AgentController.\n * When provided, this replaces the default `getDynamicMemory(storage, vectorStore)` which\n * uses mastracode's built-in model gateway (Anthropic OAuth, OpenAI Codex,\n * custom providers, and models.dev fallback).\n *\n * Use this when you need to override memory model behavior completely.\n */\n memory?: AgentControllerConfig<MastraCodeState>['memory'] | false;\n /** Browser provider for browser automation tools. When set, the agent gains access to browser tools. */\n browser?: AgentControllerConfig<MastraCodeState>['browser'];\n /** PubSub for signal routing. When crossProcessPubSub is true, thread locks are disabled. */\n pubsub?: PubSub;\n /** Use Mastra Code's built-in Unix socket PubSub for local cross-process signal routing. */\n unixSocketPubSub?: boolean;\n /** Marks the configured PubSub as cross-process-safe, allowing Mastra Code to skip file thread locks. */\n crossProcessPubSub?: boolean;\n}\n\nexport function createAuthStorage() {\n const authStorage = new AuthStorage();\n setAuthStorage(authStorage);\n setOpenAIAuthStorage(authStorage);\n setGitHubCopilotAuthStorage(authStorage);\n return authStorage;\n}\n\n/**\n * Resolve cloud observability credentials for the MastraPlatformExporter.\n * Priority: per-resource settings > environment variables > disabled.\n */\nfunction resolveCloudObservabilityConfig(\n settings: ReturnType<typeof loadSettings>,\n authStorage: AuthStorage,\n resourceId: string,\n): { accessToken?: string; projectId?: string } {\n const resourceConfig = settings.observability.resources[resourceId];\n if (resourceConfig) {\n const token = authStorage.getStoredApiKey(`${OBSERVABILITY_AUTH_PREFIX}${resourceId}`);\n if (token) {\n return { accessToken: token, projectId: resourceConfig.projectId };\n }\n }\n // Fall back to environment variables for backwards compatibility\n return {\n accessToken: process.env.MASTRA_CLOUD_ACCESS_TOKEN,\n projectId: process.env.MASTRA_PROJECT_ID,\n };\n}\n\n/**\n * Base factory: builds every shared MastraCode resource (storage, observability,\n * memory, MCP, providers, gateways, agent, modes) and the {@link AgentController}, but\n * does NOT call `init()` or create a session. The controller is returned inert so\n * the composition layer can decide its Mastra ownership and session model.\n *\n * See {@link bootLocalAgentController} (Case 3) and `mountAgentControllerOnMastra` (Cases 1 & 2).\n */\nexport async function createMastraCodeAgentController(config?: MastraCodeConfig) {\n const cwd = config?.cwd ?? process.cwd();\n const homeDir = config?.homeDir ?? config?.initialState?.homeDir;\n const configDir = config?.configDir ?? DEFAULT_CONFIG_DIR;\n // The single session for this process, assigned once `createSession()` runs\n // below. Config callbacks defined before then (e.g. notification stream\n // options) read it lazily through this holder.\n let activeSession: Session<MastraCodeState> | undefined;\n if (configDir !== DEFAULT_CONFIG_DIR) {\n validateConfigDirName(configDir);\n }\n\n // Load .env file from cwd if present (for observability API keys, etc.)\n try {\n process.loadEnvFile(path.join(cwd, '.env'));\n } catch {\n // No .env file — that's fine, keys may be in shell environment\n }\n\n // Auth storage (shared with Claude Max / OpenAI providers and AgentController)\n const authStorage = createAuthStorage();\n const globalSettings = loadSettings(config?.settingsPath);\n const storedGatewayKey = authStorage.getStoredApiKey(MEMORY_GATEWAY_PROVIDER);\n const storedGatewayUrl = globalSettings.memoryGateway?.baseUrl;\n\n if (storedGatewayKey) {\n process.env['MASTRA_GATEWAY_API_KEY'] ??= storedGatewayKey;\n }\n\n if (storedGatewayUrl) {\n process.env['MASTRA_GATEWAY_URL'] ??= storedGatewayUrl;\n }\n\n // Load user-entered API keys from auth.json into process.env\n // (only sets env vars that aren't already present — env vars take precedence)\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n const providerEnvVars: Record<string, string | undefined> = {};\n for (const [provider, cfg] of Object.entries(registry)) {\n const envVars = cfg?.apiKeyEnvVar;\n providerEnvVars[provider] = Array.isArray(envVars) ? envVars[0] : envVars;\n }\n providerEnvVars[MEMORY_GATEWAY_PROVIDER] ??= 'MASTRA_GATEWAY_API_KEY';\n authStorage.loadStoredApiKeysIntoEnv(providerEnvVars);\n } catch {\n // Registry unavailable — load well-known provider keys so non-gateway flows still work\n authStorage.loadStoredApiKeysIntoEnv({\n [MEMORY_GATEWAY_PROVIDER]: 'MASTRA_GATEWAY_API_KEY',\n anthropic: 'ANTHROPIC_API_KEY',\n openai: 'OPENAI_API_KEY',\n google: 'GOOGLE_GENERATIVE_AI_API_KEY',\n cerebras: 'CEREBRAS_API_KEY',\n deepseek: 'DEEPSEEK_API_KEY',\n });\n }\n\n const mgApiKey = process.env['MASTRA_GATEWAY_API_KEY'] ?? storedGatewayKey;\n const mastraGatewayBaseUrl = (\n process.env['MASTRA_GATEWAY_URL'] ??\n storedGatewayUrl ??\n 'https://gateway-api.mastra.ai'\n )\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n const mastraCodeGateway = createMastraCodeGateway({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: false,\n settingsPath: config?.settingsPath,\n });\n const amazonBedrockGateway = createAmazonBedrockGateway();\n\n // Project detection\n const project = detectProject(cwd);\n\n const resourceIdOverride = getResourceIdOverride(project.rootPath, configDir);\n if (resourceIdOverride) {\n project.resourceId = resourceIdOverride;\n project.resourceIdOverride = true;\n }\n\n // Stable session id unique to this project/resource, and a machine-bound owner\n // id. resourceId encodes root path + git identity and honors overrides, so it\n // is the right input for scoping the session to the cwd/project.\n const sessionId = `mastracode-session-${shortHash(project.resourceId)}`;\n const ownerId = `mastracode-${shortHash(`${hostname()}\\0${project.rootPath}`)}`;\n\n const configuredPubSub = config?.pubsub;\n const useUnixSocketPubSub =\n (config?.unixSocketPubSub ?? globalSettings.signals?.unixSocketPubSub ?? false) && process.platform !== 'win32';\n const signalsPubSub = configuredPubSub ?? (useUnixSocketPubSub ? createSignalsPubSub(project.resourceId) : undefined);\n const crossProcessPubSub = config?.crossProcessPubSub ?? (!configuredPubSub && useUnixSocketPubSub);\n if (crossProcessPubSub && !signalsPubSub) {\n throw new Error('crossProcessPubSub requires a pubsub instance');\n }\n\n // Storage\n const storageConfig = config?.storage ?? getStorageConfig(project.rootPath, globalSettings.storage, configDir);\n const storageResult = await createStorage(storageConfig);\n const storageWarning = storageResult.warning;\n\n // Observability storage (DuckDB — separate file for OLAP-style trace/score/feedback queries).\n // Local tracing is opt-in via `/observability local on`. When disabled, the\n // MastraStorageExporter is omitted entirely so traces never fall through to\n // the default libsql backend.\n let observabilityDomain: DuckDBStore['observability'] | undefined;\n let observabilityWarning: string | undefined;\n if (globalSettings.observability.localTracing) {\n try {\n const observabilityDuckDB = new DuckDBStore({\n id: 'mastra-code-observability',\n path: getObservabilityDatabasePath(),\n });\n // Force an early connection attempt so the lock error surfaces now, not mid-session.\n await observabilityDuckDB.db.getConnection();\n observabilityDomain = observabilityDuckDB.observability;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const isLockError = /lock|locked|busy/i.test(message);\n if (isLockError) {\n observabilityWarning =\n 'Observability unavailable — another MastraCode instance holds the database lock. Traces, scores, and feedback will not be recorded in this session.';\n } else {\n observabilityWarning = `Observability unavailable — DuckDB initialization failed: ${message}`;\n }\n }\n }\n\n const harnessStorage = new InMemoryHarness();\n\n const storage = new MastraCompositeStore({\n id: 'mastra-code-storage',\n default: storageResult.storage,\n domains: {\n // When local tracing is off, disable the observability domain entirely so\n // trace/score/feedback writes never fall through to the default libsql store.\n observability: observabilityDomain ?? false,\n harness: harnessStorage,\n },\n });\n\n // Observability (tracing, scoring, feedback)\n const observability = new Observability({\n configs: {\n default: {\n serviceName: 'mastracode',\n // Only these requestContext keys are stored on spans — prevents leaking\n // large objects (controller state, workspace, env vars) into trace data.\n // Use dot-notation because these are nested inside the 'controller' key.\n //\n // Session identifiers:\n // threadId, resourceId, session.modeId, agentControllerId\n // Environment & project:\n // state.projectName, state.gitBranch\n // Model configuration:\n // session.modelId, state.subagentModelId\n // Agent settings:\n // state.yolo, state.thinkingLevel, state.smartEditing\n // Observational memory settings:\n // state.omScope, state.observerModelId, state.reflectorModelId,\n // state.observationThreshold, state.reflectionThreshold\n requestContextKeys: [\n // Session identifiers\n 'controller.threadId',\n 'controller.resourceId',\n 'controller.session.modeId',\n 'controller.controllerId',\n // Environment & project\n 'controller.state.projectName',\n 'controller.state.gitBranch',\n // Model configuration\n 'controller.session.modelId',\n 'controller.state.subagentModelId',\n // Agent settings\n 'controller.state.yolo',\n 'controller.state.thinkingLevel',\n 'controller.state.smartEditing',\n // Observational memory settings\n 'controller.state.omScope',\n 'controller.state.observerModelId',\n 'controller.state.reflectorModelId',\n 'controller.state.observationThreshold',\n 'controller.state.reflectionThreshold',\n ],\n exporters: [\n // Only persist traces locally when DuckDB observability is available\n // (via `/observability local on`). Without this guard the storage\n // exporter falls through to the default libsql backend and silently\n // fills the main database with gigabytes of span data.\n ...(observabilityDomain ? [new MastraStorageExporter({ strategy: 'event-sourced' })] : []),\n new MastraPlatformExporter(resolveCloudObservabilityConfig(globalSettings, authStorage, project.resourceId)),\n ],\n spanOutputProcessors: [new SensitiveDataFilter()],\n },\n },\n });\n\n // Vector store for recall search (separate DB file to avoid bloating main storage)\n const vectorStore = await createVectorStore(storageConfig, storageResult.backend);\n\n // Maintenance handle for /prune: prunes via the inner store (whose retention\n // config covers every domain, including legacy libsql observability spans)\n // and can compact local libsql files to reclaim disk. The vector store's\n // connection must close alongside storage — the compaction's file swap\n // refuses to run while any connection is open.\n const storageMaintenance: StorageMaintenance = createStorageMaintenance({\n storage: storageResult.storage,\n backend: storageResult.backend,\n retention: DEFAULT_RETENTION,\n localDbFiles: resolveLocalDbFiles(storageConfig, storageResult.backend),\n closeVector: vectorStore instanceof LibSQLVector ? () => vectorStore.close() : undefined,\n });\n\n const memory = config?.memory === false ? undefined : (config?.memory ?? getDynamicMemory(storage, vectorStore));\n\n // MCP\n const mcpManager = config?.disableMcp ? undefined : createMcpManager(project.rootPath, configDir, config?.mcpServers);\n\n // Hooks\n const hookManager = config?.disableHooks\n ? undefined\n : new HookManager(project.rootPath, 'session-init', configDir, homeDir);\n\n const pluginManager = config?.disablePlugins\n ? undefined\n : (config?.pluginManager ?? new PluginManager({ projectRoot: project.rootPath, configDir, homeDir }));\n const loadedPlugins = pluginManager ? await pluginManager.reload() : [];\n const pluginTools = pluginManager?.getPluginTools() ?? {};\n\n // Scorers (live evaluation with sampling)\n const outcomeScorer = createOutcomeScorer();\n const efficiencyScorer = createEfficiencyScorer();\n\n // Agent — githubSignals is created before `controller` but the closure below\n // captures `controller` by reference; it is only invoked at notification time,\n // well after controller is constructed (line ~692). Explicit type annotations\n // on githubSignals, codeAgent, modes, and controller break the circular\n // inference chain this forward reference would otherwise create.\n const githubSignals: GithubSignals | undefined = globalSettings.signals?.experimentalGithubSignals\n ? new GithubSignals({\n cwd: project.rootPath,\n gitcrawlCommand:\n process.env.MASTRACODE_GITCRAWL_BIN ??\n process.env.GITCRAWL_BIN ??\n process.env.MASTRACODE_GITCRAWL_COMMAND ??\n process.env.GITCRAWL_COMMAND,\n getNotificationStreamOptions: async ({ resourceId, threadId }) => {\n // Run the woken notification as the session that owns the target\n // resource so it uses that session's model/mode/state. Fall back to\n // the current session only when no session owns the resource yet.\n const session = (await controller.getSessionByResource(resourceId)) ?? activeSession!;\n // A long-running system must be able to drive work unattended, so a\n // target session without an explicit model selection falls back to a\n // real model rather than failing the run: the current session's live\n // selection (what the user actually picked), then the mode's default.\n const modeId = session.mode.get();\n const defaultModeModelId = controller.listModes().find(mode => mode.id === modeId)?.defaultModelId;\n const modelId = session.model.get() || activeSession?.model.get() || defaultModeModelId || '';\n const requestContext = new RequestContext();\n const agentControllerContext: AgentControllerRequestContext = {\n controllerId: controller.id,\n state: session.state.get(),\n getState: () => session.state.get(),\n setState: updates => session.state.set(updates),\n threadId,\n resourceId,\n session: {\n id: session.identity.getId(),\n ownerId: session.identity.getOwnerId(),\n modeId,\n modelId,\n state: {\n get: () => session.state.get(),\n set: updates => session.state.set(updates),\n update: updater => session.state.update(updater),\n },\n },\n workspace: controller.getWorkspace(),\n getSubagentModelId: params => session.subagents.model.get(params ?? {}),\n };\n requestContext.set('controller', agentControllerContext);\n\n return {\n memory: { thread: threadId, resource: resourceId },\n requestContext,\n maxSteps: 1000,\n savePerStep: false,\n requireToolApproval: (session.state.get() as Record<string, unknown>).yolo !== true,\n modelSettings: { temperature: 1 },\n };\n },\n })\n : undefined;\n const codeAgent: Agent = createCodingAgent({\n id: CODE_AGENT_ID,\n name: 'Code Agent',\n // Workspace is wired per-request at the AgentController level (see\n // `config.workspace` below), so opt out of the factory's default local\n // workspace. An explicit `undefined` is required: the factory only builds a\n // default when the `workspace` key is absent.\n workspace: undefined,\n instructions: getDynamicInstructions,\n model: getDynamicModel,\n tools: createDynamicTools(mcpManager, config?.extraTools, config?.disabledTools, storage, pluginTools),\n hooks: createToolHooks(hookManager),\n scorers: {\n outcome: {\n scorer: outcomeScorer,\n sampling: { type: 'none' },\n },\n efficiency: {\n scorer: efficiencyScorer,\n sampling: { type: 'ratio', rate: 0.3 },\n },\n },\n // TaskSignalProvider bundles the task tools + TaskStateProcessor: it merges\n // the tools into the toolset and registers the task state-signal processor,\n // so the task list persists across turns and survives OM truncation.\n signals: [new TaskSignalProvider(), ...(githubSignals ? [githubSignals] : [])],\n // Native goal mechanism: the in-loop goal step judges the thread's active\n // objective each qualifying iteration. The judge model is required for any\n // gating to occur; when unset the goal step is a complete no-op. A6 auto-wires\n // the GoalStateProcessor so the `<current-objective>` signal persists across\n // turns. Per-thread overrides live in the ThreadState `goal` record and win\n // over these defaults.\n goal: {\n // Resolve the judge model through mastracode's gateway (a model-resolver\n // function) so provider credentials are injected; returns undefined when no\n // judge model is configured, keeping the goal step a no-op. Bind the same\n // `settingsPath` used above so the judge model and `maxRuns` come from one\n // config (a custom settings file would otherwise diverge).\n judge: ctx => getGoalJudgeModel(ctx, config?.settingsPath),\n maxRuns: globalSettings.models.goalMaxTurns ?? 50,\n maxSteps: 1000,\n prompt: DEFAULT_GOAL_JUDGE_PROMPT,\n // Read-only workspace tools the default goal judge may call to verify the\n // agent's work against the actual filesystem (view, search_content,\n // find_files, file_stat, lsp_inspect) rather than grading prose alone —\n // restoring the original MastraCode judge's verification ability. Resolved\n // per-request from the active workspace (mirrors `judge`).\n tools: getGoalJudgeTools,\n },\n inputProcessors: [\n new PlanRejectionAbortProcessor(),\n new AgentsMDInjector({\n getIgnoredInstructionPaths: ({ requestContext }) => {\n const agentControllerContext = requestContext?.get('controller') as\n | AgentControllerRequestContext<{ projectPath?: string }>\n | undefined;\n const state = agentControllerContext?.getState();\n return getStaticallyLoadedInstructionPaths(state?.projectPath ?? project.rootPath);\n },\n }),\n new ProviderHistoryCompat(),\n ],\n errorProcessors: [\n new StreamErrorRetryProcessor({\n matchers: [\n { match: isBadRequestError, maxRetries: 1, delayMs: 2000 },\n {\n match: isECONNRESETError,\n maxRetries: MASTRACODE_ECONNRESET_MAX_RETRIES,\n delayMs: ({ retryCount }) =>\n Math.min(\n MASTRACODE_ECONNRESET_RETRY_INITIAL_DELAY_MS * Math.pow(2, retryCount),\n MASTRACODE_ECONNRESET_RETRY_MAX_DELAY_MS,\n ),\n },\n ],\n }),\n new PrefillErrorHandler(),\n new ProviderHistoryCompat(),\n ],\n });\n\n // const defaultSubAgents: Array<AgentControllerSubagent> = [];\n // const defaultSubagents = [exploreSubagent, planSubagent, executeSubagent];\n\n const defaultModes: AgentControllerMode[] = [\n {\n ...buildMode,\n metadata: {\n ...buildMode.metadata,\n color: mastraBrand.green,\n },\n },\n {\n ...planMode,\n metadata: {\n ...planMode.metadata,\n color: mastraBrand.purple,\n },\n },\n {\n ...fastMode,\n metadata: {\n ...fastMode.metadata,\n color: mastraBrand.orange,\n },\n },\n ];\n\n const defaultIntervalHandlers: IntervalHandler[] = [\n {\n id: 'gateway-sync',\n intervalMs: 5 * 60 * 1000,\n immediate: false,\n handler: () => syncGateways(),\n },\n ];\n const intervalHandlers = config?.intervalHandlers ?? defaultIntervalHandlers;\n\n // Build lightweight provider access for resolving built-in packs at startup.\n // Anthropic/OpenAI use AuthStorage; other providers use env API keys.\n // Also scan the full provider registry so configured API keys satisfy access checks.\n const anthropicCred = authStorage.get('anthropic');\n const openaiCred = authStorage.get('openai-codex');\n const githubCopilotCred = authStorage.get('github-copilot');\n const startupAccess: ProviderAccess = {\n anthropic:\n anthropicCred?.type === 'oauth'\n ? 'oauth'\n : anthropicCred?.type === 'api_key' && anthropicCred.key.trim().length > 0\n ? 'apikey'\n : false,\n openai:\n openaiCred?.type === 'oauth'\n ? 'oauth'\n : openaiCred?.type === 'api_key' && openaiCred.key.trim().length > 0\n ? 'apikey'\n : false,\n cerebras: process.env.CEREBRAS_API_KEY ? 'apikey' : false,\n google: process.env.GOOGLE_GENERATIVE_AI_API_KEY ? 'apikey' : false,\n deepseek: process.env.DEEPSEEK_API_KEY ? 'apikey' : false,\n 'github-copilot': githubCopilotCred?.type === 'oauth' ? 'oauth' : false,\n };\n // Gateway covers all providers — ensure Anthropic/OpenAI packs are visible\n if (mgApiKey) {\n if (!startupAccess.anthropic) startupAccess.anthropic = 'apikey';\n if (!startupAccess.openai) startupAccess.openai = 'apikey';\n }\n // Check all providers in the registry for API keys\n try {\n const registry = PROVIDER_REGISTRY as Record<string, ProviderConfig>;\n for (const [provider, config] of Object.entries(registry)) {\n if (startupAccess[provider] === 'oauth' || startupAccess[provider] === 'apikey') continue; // Already enabled above\n if (provider === 'anthropic' || provider === 'openai') continue;\n const envVars = config?.apiKeyEnvVar;\n const envVarList = Array.isArray(envVars) ? envVars : envVars ? [envVars] : [];\n if (envVarList.some(envVar => process.env[envVar])) {\n startupAccess[provider] = 'apikey';\n }\n }\n } catch {\n // Registry may not be loaded yet; the 5 hardcoded providers are sufficient fallback\n }\n const builtinPacks = getAvailableModePacks(startupAccess);\n const builtinOmPacks = getAvailableOmPacks(startupAccess);\n const effectiveDefaults = resolveModelDefaults(globalSettings, builtinPacks);\n const effectiveObserverModel = resolveOmRoleModel(globalSettings, 'observer', builtinOmPacks);\n const effectiveReflectorModel = resolveOmRoleModel(globalSettings, 'reflector', builtinOmPacks);\n const effectiveObservationThreshold = globalSettings.models.omObservationThreshold ?? undefined;\n const effectiveReflectionThreshold = globalSettings.models.omReflectionThreshold ?? undefined;\n const effectiveCavemanObservations = globalSettings.models.omCavemanObservations ?? undefined;\n const effectiveObserveAttachments = globalSettings.models.omObserveAttachments ?? 'auto';\n\n const modes = addPluginToolsToModeAllowlists(\n applyEffectiveDefaultsToModes(config?.modes ? config.modes : defaultModes, effectiveDefaults),\n Object.keys(pluginTools),\n );\n const defaultModeId =\n modes.find(mode => mode.metadata?.default === true)?.id ??\n modes.find(mode => mode.id === 'build')?.id ??\n modes[0]?.id;\n if (!defaultModeId) {\n throw new Error('MastraCode requires at least one mode');\n }\n\n // Map subagent types to mode models: explore→fast, plan→plan, execute→build\n // const subagentModeMap: Record<string, string> = { explore: 'fast', plan: 'plan', execute: 'build' };\n // Subagents inherit workspace tools from the parent agent's workspace automatically.\n // Apply disabledTools filter to both default and custom subagents.\n // const subagents = [];\n\n // Build initial state with global preferences\n const globalInitialState: Partial<MastraCodeState> = {};\n if (effectiveObserverModel) {\n globalInitialState.observerModelId = effectiveObserverModel;\n }\n if (effectiveReflectorModel) {\n globalInitialState.reflectorModelId = effectiveReflectorModel;\n }\n if (effectiveObservationThreshold !== undefined) {\n globalInitialState.observationThreshold = effectiveObservationThreshold;\n }\n if (effectiveReflectionThreshold !== undefined) {\n globalInitialState.reflectionThreshold = effectiveReflectionThreshold;\n }\n if (effectiveCavemanObservations !== undefined) {\n globalInitialState.cavemanObservations = effectiveCavemanObservations;\n }\n if (effectiveObserveAttachments !== undefined) {\n globalInitialState.observeAttachments = effectiveObserveAttachments;\n }\n if (globalSettings.preferences.yolo !== null) {\n globalInitialState.yolo = globalSettings.preferences.yolo;\n }\n globalInitialState.thinkingLevel = globalSettings.preferences.thinkingLevel;\n if (config?.omScope) {\n globalInitialState.omScope = config.omScope;\n }\n // Seed subagent models from global settings\n for (const [key, modelId] of Object.entries(globalSettings.models.subagentModels)) {\n if (key === 'default' || key === '_default') {\n globalInitialState.subagentModelId = modelId;\n } else {\n globalInitialState[`subagentModelId_${key}`] = modelId;\n }\n }\n\n const typedStateSchema = stateSchema as PublicSchema<MastraCodeState>;\n const controller: AgentController<MastraCodeState> = new AgentController<MastraCodeState>({\n id: 'mastra-code',\n resourceId: project.resourceId,\n storage,\n observability,\n memory,\n pubsub: signalsPubSub,\n stateSchema: typedStateSchema,\n agent: codeAgent,\n subagents: config?.subagents ?? [],\n gateways: [amazonBedrockGateway, mastraCodeGateway],\n workspace: config?.workspace ?? (args => getDynamicWorkspace(args)),\n browser: config?.browser,\n idGenerator: config?.idGenerator,\n toolCategoryResolver: getToolCategory,\n initialState: {\n projectPath: project.rootPath,\n projectName: project.name,\n gitBranch: project.gitBranch,\n pluginSkillPaths: loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : [])),\n pluginCommandPaths: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' ? (plugin.commandPaths ?? []) : [],\n ),\n pluginInstructions: loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n ),\n yolo: true,\n ...globalInitialState,\n ...config?.initialState,\n // configDir must always win over initialState spreads to stay in sync\n // with MCP/hooks/storage which were already initialized with this value.\n configDir,\n },\n modes,\n intervalHandlers,\n modelUseCountProvider: () => loadSettings().modelUseCounts,\n modelUseCountTracker: modelId => {\n try {\n const settings = loadSettings();\n settings.modelUseCounts[modelId] = (settings.modelUseCounts[modelId] ?? 0) + 1;\n saveSettings(settings);\n } catch (error) {\n console.error('Failed to persist model usage count', error);\n }\n },\n threadLock: crossProcessPubSub\n ? undefined\n : {\n acquire: acquireThreadLock,\n release: releaseThreadLock,\n },\n });\n\n // The AgentController is fully constructed but intentionally NOT inited here. Init and\n // session creation are deferred to the composition layer (see below) so the\n // controller can be wired in three ways:\n //\n // 1. Server + Web — registered on a server Mastra, then inited; sessions\n // minted per browser client over HTTP.\n // 2. Server + TUI — same server composition; the TUI drives a session\n // (in-process today; remote transport is future work).\n // 3. Local + TUI — controller builds its own internal Mastra on init() and\n // mints one eager session for the whole process.\n //\n // Cases 1 & 2 use `mountAgentControllerOnMastra` (register-before-init, no eager\n // session). Case 3 uses `bootLocalAgentController` (init + one wired session).\n return {\n controller: controller,\n storage,\n storageMaintenance,\n observability,\n memory,\n mcpManager,\n hookManager,\n pluginManager,\n loadedPlugins,\n pluginTools,\n signalsPubSub,\n authStorage,\n resolveModel,\n storageWarning,\n observabilityWarning,\n builtinPacks,\n builtinOmPacks,\n effectiveDefaults,\n githubSignals,\n // Identity for the single local session (Case 3). Servers ignore these and\n // mint per-request sessions with client-supplied resourceIds instead.\n sessionId,\n ownerId,\n // Lets the composition layer publish the created session back into the\n // config closures (e.g. notification stream options read it lazily).\n setActiveSession: (session: Session<MastraCodeState>) => {\n activeSession = session;\n },\n };\n}\n\n/**\n * Result of {@link createMastraCodeAgentController}: every shared resource plus the\n * inert AgentController, ready to be either booted locally or mounted on a server\n * Mastra.\n */\nexport type MastraCodeAgentController = Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n\n/**\n * Wires the session-scoped concerns MastraCode layers on top of a Session:\n * hookManager thread-id sync, GitHub PR polling for the current thread, and\n * per-thread persistence of the mastracode-only `/om` settings.\n *\n * Used by {@link bootLocalAgentController} for the single local session. A server can\n * call this for any session it mints if it wants the same background wiring.\n */\nexport async function wireSessionConcerns(\n base: Pick<MastraCodeAgentController, 'hookManager' | 'githubSignals' | 'setActiveSession'>,\n session: Session<MastraCodeState>,\n): Promise<void> {\n const { hookManager, githubSignals } = base;\n base.setActiveSession(session);\n\n // Sync hookManager session ID on thread changes\n if (hookManager) {\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') {\n hookManager.setSessionId(event.threadId);\n } else if (event.type === 'thread_created') {\n hookManager.setSessionId(event.thread.id);\n }\n });\n }\n\n if (githubSignals) {\n const startGithubPollingForCurrentThread = async (threadId?: string | null) => {\n if (!threadId) return;\n githubSignals.stopAllPolling();\n try {\n const threads = await session.thread.list({ allResources: true });\n const thread = threads.find((item: { id: string }) => item.id === threadId);\n await githubSignals.startPollingForThread(\n {\n threadId,\n resourceId: thread?.resourceId ?? session.identity.getResourceId(),\n },\n { pollImmediately: true },\n );\n } catch (error) {\n console.warn('Failed to start GitHub PR polling:', error);\n }\n };\n\n session.subscribe((event: AgentControllerEvent) => {\n if (event.type === 'thread_changed') void startGithubPollingForCurrentThread(event.threadId);\n else if (event.type === 'thread_created') void startGithubPollingForCurrentThread(event.thread.id);\n });\n void startGithubPollingForCurrentThread(session.thread.getId());\n }\n\n // Persist MastraCode-owned /om settings per-thread (mastracode-only concern;\n // intentionally not in core's controller loadThreadMetadata).\n const omThreadStateSession = session as unknown as Session<Record<string, unknown>>;\n attachOMThreadStatePersistence(omThreadStateSession);\n await restoreOMThreadStateForCurrentThread(omThreadStateSession).catch(() => {\n // Persistence is best-effort; don't crash startup if storage hiccups.\n });\n}\n\n/**\n * Case 3 (AgentController local + TUI/headless): build the controller, let it stand up its\n * own internal Mastra via `init()`, and mint the single eager session that all\n * work in this process runs through. The AgentController owns no session of its own.\n */\nexport async function bootLocalAgentController(config?: MastraCodeConfig) {\n const base = await createMastraCodeAgentController(config);\n const { controller, sessionId, ownerId } = base;\n\n await controller.init();\n await controller.getMastra()?.startWorkers();\n const session = await controller.createSession({ id: sessionId, ownerId });\n await wireSessionConcerns(base, session);\n\n return { ...base, session };\n}\n\n/** Result of {@link mountAgentControllerOnMastra}: shared handles plus the owning Mastra. */\nexport type MountedMastraCode = MastraCodeAgentController & { mastra: Mastra };\n\n/**\n * Cases 1 & 2 (AgentController in Server + Web/TUI): build the controller, register it on a\n * server-owned Mastra, THEN init it. Registering before `init()` is what makes\n * the controller inherit the server's Mastra (storage, agents, gateways) instead of\n * spinning up its own internal one — there is a single shared Mastra.\n *\n * No eager session is minted: each client (browser or terminal) creates/resumes\n * its own isolated session via `controller.createSession({ resourceId })`, so one\n * server can drive many concurrent users.\n *\n * Pass an existing `mastra` to mount onto a Mastra that already hosts other\n * primitives; otherwise a Mastra is created that owns the controller's storage so\n * durability is configured in one place.\n */\nexport async function mountAgentControllerOnMastra(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n /**\n * Additional `server` config to fold onto the constructed Mastra alongside\n * the assembled `apiRoutes` (e.g. `middleware`, `cors`). Used by the\n * platform entry (`src/mastra/index.ts`) to own the WorkOS gate + tenant\n * dispatcher + CORS on the instance the deployer generates its server from.\n * Ignored when `mastra` is provided (mounting onto a caller-owned instance).\n */\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<MountedMastraCode> {\n const prepared = await prepareAgentControllerMount(config);\n if (config?.mastra) {\n // Mounting onto a Mastra the caller already built. Ensure the controller's\n // back-reference points at it (idempotent — only sets #externalMastra).\n prepared.base.controller.__registerMastra(config.mastra);\n await prepared.finalize();\n return { ...prepared.base, mastra: config.mastra };\n }\n const mastra = new Mastra(prepared.mastraArgs);\n await prepared.finalize();\n return { ...prepared.base, mastra };\n}\n\n/**\n * Assemble everything needed to construct the server-owned Mastra WITHOUT\n * constructing it, so a caller (the platform entry `src/mastra/index.ts`) can\n * run the `new Mastra(...)` literal in its own module. The deployer's\n * `checkConfigExport` Babel plugin only marks the config valid when it finds a\n * top-level `new Mastra(...)` exported as `mastra` in the ENTRY file; hiding the\n * construction inside this helper would trip the \"Invalid Mastra config\" warning.\n *\n * Returns the constructor args plus a `finalize()` that runs the post-construct\n * boot (`controller.init()` + `startWorkers()`). The controller is registered on\n * the Mastra via the `agentControllers` arg at construction time.\n */\nexport async function prepareAgentControllerMount(\n config?: MastraCodeConfig & {\n mastra?: Mastra;\n controllerId?: string;\n buildApiRoutes?: (deps: { controller: MountedMastraCode['controller']; authStorage: AuthStorage }) => ApiRoute[];\n buildServerConfig?: (deps: {\n controller: MountedMastraCode['controller'];\n authStorage: AuthStorage;\n }) => Omit<NonNullable<ConstructorParameters<typeof Mastra>[0]>['server'], 'apiRoutes'>;\n },\n): Promise<{\n base: Awaited<ReturnType<typeof createMastraCodeAgentController>>;\n mastraArgs: NonNullable<ConstructorParameters<typeof Mastra>[0]>;\n finalize: () => Promise<void>;\n}> {\n const base = await createMastraCodeAgentController(config);\n const { controller, storage, authStorage } = base;\n const controllerId = config?.controllerId ?? controller.id;\n const apiRoutes = config?.buildApiRoutes?.({ controller, authStorage });\n const extraServerConfig = config?.buildServerConfig?.({ controller, authStorage });\n\n const serverConfig = {\n ...extraServerConfig,\n ...(apiRoutes?.length ? { apiRoutes } : {}),\n };\n const mastraArgs = {\n agentControllers: { [controllerId]: controller },\n storage,\n ...(Object.keys(serverConfig).length ? { server: serverConfig } : {}),\n };\n\n const finalize = async () => {\n await controller.init();\n await controller.getMastra()?.startWorkers();\n };\n\n return { base, mastraArgs, finalize };\n}\n\n/**\n * Back-compat alias. Historically `createMastraCode` built and booted a local\n * controller with a single session; that behavior now lives in\n * {@link bootLocalAgentController}. New code should call the explicit factory for its\n * case: `bootLocalAgentController` (local) or {@link mountAgentControllerOnMastra} (server).\n */\nexport const createMastraCode = bootLocalAgentController;\n\n/**\n * Programmatic headless API. `runMC` runs an already-built controller/session\n * (from {@link createMastraCode}) as an async-iterable run that also resolves to\n * a typed result. Also available via the `mastracode/headless` subpath.\n */\nexport {\n runMC,\n runMCCli,\n hasHeadlessFlag,\n autoApprovePolicy,\n denyPolicy,\n permissionModeToPolicy,\n formatHuman,\n formatJsonl,\n renderTextResult,\n renderJsonResult,\n} from './headless/index.js';\nexport type {\n RunMCOptions,\n RunMCResult,\n RunMCStatus,\n RunMCUsage,\n RunMCToolCall,\n RunMCToolResult,\n RunMCError,\n RunMCThreadOptions,\n MCRun,\n ResolutionPolicy,\n PermissionMode,\n} from './headless/index.js';\n"],"mappings":"AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,OAAO,UAAU;AAGjB,SAAS,uBAAuB;AAUhC,SAAS,yBAAyB;AAElC,SAAS,yBAAyB;AAElC,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAG/B,SAAS,0BAA0B;AACnC,SAAS,iBAAiB,4BAA4B;AACtD,SAAS,iCAAiC;AAC1C,SAAS,mBAAmB;AAE5B,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,8BAA8B;AACvC,SAAS,wBAAwB;AACjC,SAAS,yBAAyB,iBAAiB,mBAAmB,oBAAoB;AAC1F,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,SAAS,2CAA2C;AAIpD,SAAS,gCAAgC,4CAA4C;AACrF,SAAS,oBAAoB,uBAAuB;AAEpD,SAAS,qBAAqB,yBAAyB;AACvD,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB,6BAA6B;AAC1D,SA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AAiB,EAAE,YAAY,YAAY,CAAC;AACtE,QAAM,oBAAoB,QAAQ,oBAAoB,EAAE,YAAY,YAAY,CAAC;AAEjF,QAAM,eAAe;AAAA,IACnB,GAAG;AAAA,IACH,GAAI,WAAW,SAAS,EAAE,UAAU,IAAI,CAAC;AAAA,EAC3C;AACA,QAAM,aAAa;AAAA,IACjB,kBAAkB,EAAE,CAAC,YAAY,GAAG,WAAW;AAAA,IAC/C;AAAA,IACA,GAAI,OAAO,KAAK,YAAY,EAAE,SAAS,EAAE,QAAQ,aAAa,IAAI,CAAC;AAAA,EACrE;AAEA,QAAM,WAAW,YAAY;AAC3B,UAAM,WAAW,KAAK;AACtB,UAAM,WAAW,UAAU,GAAG,aAAa;AAAA,EAC7C;AAEA,SAAO,EAAE,MAAM,YAAY,SAAS;AACtC;AAQO,MAAM,mBAAmB;AAOhC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["config"]}
@@ -4,7 +4,7 @@
4
4
  * If PG is selected but fails to connect, falls back to LibSQL so the TUI
5
5
  * can start and the user can fix the connection via /settings.
6
6
  */
7
- import type { MastraCompositeStore } from '@mastra/core/storage';
7
+ import type { MastraCompositeStore, RetentionConfig } from '@mastra/core/storage';
8
8
  import type { MastraVector } from '@mastra/core/vector';
9
9
  import type { StorageConfig } from './project.js';
10
10
  export declare const MASTRA_CODE_LOCAL_PRAGMAS: {
@@ -20,6 +20,7 @@ export declare function buildLibSQLStore(opts: {
20
20
  id?: string;
21
21
  url: string;
22
22
  authToken?: string;
23
+ retention?: RetentionConfig;
23
24
  }): MastraCompositeStore;
24
25
  /** Construct a LibSQL vector store for an arbitrary url/authToken. */
25
26
  export declare function buildLibSQLVector(opts: {
@@ -1 +1 @@
1
- {"version":3,"file":"storage-factory.d.ts","sourceRoot":"","sources":["../../src/utils/storage-factory.ts"],"names":[],"mappings":"AAA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qBAAqB,CAAC;AAIxD,OAAO,KAAK,EAAE,aAAa,EAAmB,MAAM,cAAc,CAAC;AAInE,eAAO,MAAM,yBAAyB;;;CAGrC,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE;IACrC,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,eAAe,CAAC;CAC7B,GAAG,oBAAoB,CAQvB;AAED,sEAAsE;AACtE,wBAAgB,iBAAiB,CAAC,IAAI,EAAE;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,YAAY,CAMtG;AAED,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,oBAAoB,CAAC;IAC9B,8DAA8D;IAC9D,OAAO,EAAE,QAAQ,GAAG,IAAI,CAAC;IACzB,kFAAkF;IAClF,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAMD;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAUjF;AAyDD;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,aAAa,EACrB,gBAAgB,GAAE,QAAQ,GAAG,IAAqB,GACjD,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC,CAuBnC"}
@@ -1,6 +1,7 @@
1
1
  import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
2
2
  import { PostgresStore } from "@mastra/pg";
3
3
  import { getDatabasePath, getVectorDatabasePath } from "./project.js";
4
+ import { DEFAULT_RETENTION } from "./storage-maintenance.js";
4
5
  const MASTRA_CODE_LOCAL_PRAGMAS = {
5
6
  cacheSize: -128e3,
6
7
  mmapSize: 536870912
@@ -10,6 +11,7 @@ function buildLibSQLStore(opts) {
10
11
  id: opts.id ?? "mastra-code-storage",
11
12
  url: opts.url,
12
13
  ...opts.authToken ? { authToken: opts.authToken } : {},
14
+ ...opts.retention ? { retention: opts.retention } : {},
13
15
  localPragmas: MASTRA_CODE_LOCAL_PRAGMAS
14
16
  });
15
17
  }
@@ -21,14 +23,14 @@ function buildLibSQLVector(opts) {
21
23
  });
22
24
  }
23
25
  function createFallbackLibSQL() {
24
- return buildLibSQLStore({ url: `file:${getDatabasePath()}` });
26
+ return buildLibSQLStore({ url: `file:${getDatabasePath()}`, retention: DEFAULT_RETENTION });
25
27
  }
26
28
  async function createStorage(config) {
27
29
  if (config.backend === "pg") {
28
30
  return createPgStorage(config);
29
31
  }
30
32
  return {
31
- storage: buildLibSQLStore({ url: config.url, authToken: config.authToken }),
33
+ storage: buildLibSQLStore({ url: config.url, authToken: config.authToken, retention: DEFAULT_RETENTION }),
32
34
  backend: "libsql"
33
35
  };
34
36
  }
@@ -42,6 +44,7 @@ async function createPgStorage(config) {
42
44
  }
43
45
  const base = {
44
46
  id: "mastra-code-storage",
47
+ retention: DEFAULT_RETENTION,
45
48
  ...config.schemaName ? { schemaName: config.schemaName } : {},
46
49
  ...config.disableInit ? { disableInit: config.disableInit } : {},
47
50
  ...config.skipDefaultIndexes ? { skipDefaultIndexes: config.skipDefaultIndexes } : {}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/storage-factory.ts"],"sourcesContent":["/**\n * Storage factory — creates the appropriate storage backend based on resolved config.\n *\n * If PG is selected but fails to connect, falls back to LibSQL so the TUI\n * can start and the user can fix the connection via /settings.\n */\n\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport { PostgresStore } from '@mastra/pg';\n\nimport type { StorageConfig, PgStorageConfig } from './project.js';\nimport { getDatabasePath, getVectorDatabasePath } from './project.js';\n\nexport const MASTRA_CODE_LOCAL_PRAGMAS = {\n cacheSize: -128000,\n mmapSize: 536870912,\n};\n\n/**\n * Construct a LibSQL store for an arbitrary url/authToken, applying the same\n * local pragmas the default factory uses. Shared so per-tenant storage\n * (see `web/tenant-storage.ts`) doesn't duplicate the construction.\n */\nexport function buildLibSQLStore(opts: { id?: string; url: string; authToken?: string }): MastraCompositeStore {\n return new LibSQLStore({\n id: opts.id ?? 'mastra-code-storage',\n url: opts.url,\n ...(opts.authToken ? { authToken: opts.authToken } : {}),\n localPragmas: MASTRA_CODE_LOCAL_PRAGMAS,\n });\n}\n\n/** Construct a LibSQL vector store for an arbitrary url/authToken. */\nexport function buildLibSQLVector(opts: { id?: string; url: string; authToken?: string }): MastraVector {\n return new LibSQLVector({\n id: opts.id ?? 'mastra-code-vectors',\n url: opts.url,\n ...(opts.authToken ? { authToken: opts.authToken } : {}),\n });\n}\n\nexport interface StorageResult {\n storage: MastraCompositeStore;\n /** The effective backend after any fallback logic has run. */\n backend: 'libsql' | 'pg';\n /** Non-null when PG was requested but failed — contains a user-facing warning. */\n warning?: string;\n}\n\nfunction createFallbackLibSQL(): MastraCompositeStore {\n return buildLibSQLStore({ url: `file:${getDatabasePath()}` });\n}\n\n/**\n * Create a storage instance from the resolved config.\n *\n * - `libsql` backend → LibSQLStore (always available)\n * - `pg` backend → PostgresStore, falls back to LibSQL on connection failure\n */\nexport async function createStorage(config: StorageConfig): Promise<StorageResult> {\n if (config.backend === 'pg') {\n return createPgStorage(config);\n }\n\n // Default: LibSQL\n return {\n storage: buildLibSQLStore({ url: config.url, authToken: config.authToken }),\n backend: 'libsql',\n };\n}\n\nasync function createPgStorage(config: PgStorageConfig): Promise<StorageResult> {\n // No connection info → fall back with guidance\n if (!config.connectionString && !config.host) {\n return {\n storage: createFallbackLibSQL(),\n backend: 'libsql',\n warning:\n 'PostgreSQL backend selected but no connection info configured. ' +\n 'Using LibSQL fallback. Set a connection string via /settings.',\n };\n }\n\n const base = {\n id: 'mastra-code-storage' as const,\n ...(config.schemaName ? { schemaName: config.schemaName } : {}),\n ...(config.disableInit ? { disableInit: config.disableInit } : {}),\n ...(config.skipDefaultIndexes ? { skipDefaultIndexes: config.skipDefaultIndexes } : {}),\n };\n\n const store = config.connectionString\n ? new PostgresStore({ ...base, connectionString: config.connectionString })\n : new PostgresStore({\n ...base,\n host: config.host!,\n port: config.port,\n database: config.database,\n user: config.user,\n password: config.password,\n });\n\n // Test the connection before committing — if it fails, fall back to LibSQL\n // so the user can fix the config via /settings.\n try {\n await store.init();\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const target = config.connectionString ?? `${config.host}:${config.port ?? 5432}`;\n try {\n await store.close();\n } catch {\n // ignore cleanup errors\n }\n return {\n storage: createFallbackLibSQL(),\n backend: 'libsql',\n warning:\n `Failed to connect to PostgreSQL at ${target}: ${msg}\\n` +\n 'Using LibSQL fallback. Fix the connection via /settings.',\n };\n }\n\n return { storage: store, backend: 'pg' };\n}\n\n/**\n * Create a vector store for recall search.\n * Uses a separate LibSQL file to avoid bloating the main storage DB with embedding data.\n * For PG backends, reuses the same connection (PG handles the extra tables fine).\n */\nexport async function createVectorStore(\n config: StorageConfig,\n effectiveBackend: 'libsql' | 'pg' = config.backend,\n): Promise<MastraVector | undefined> {\n if (effectiveBackend === 'pg') {\n // PG can handle vector tables in the same database\n const pgConfig = config as PgStorageConfig;\n if (!pgConfig.connectionString && !pgConfig.host) return undefined;\n\n const { PgVector } = await import('@mastra/pg');\n return new PgVector({\n id: 'mastra-code-vectors',\n connectionString:\n pgConfig.connectionString ??\n `postgresql://${pgConfig.user}:${pgConfig.password}@${pgConfig.host}:${pgConfig.port ?? 5432}/${pgConfig.database}`,\n });\n }\n\n // LibSQL: separate file for vectors. Per-tenant configs supply an explicit\n // vectorUrl so each tenant's recall vectors are isolated; otherwise use the\n // shared default file.\n const libsqlConfig = config as { vectorUrl?: string; vectorAuthToken?: string };\n return buildLibSQLVector({\n url: libsqlConfig.vectorUrl ?? `file:${getVectorDatabasePath()}`,\n authToken: libsqlConfig.vectorAuthToken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AAsB,CAAC;AAAA,IAC9D,WAAW,aAAa;AAAA,EAC1B,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/utils/storage-factory.ts"],"sourcesContent":["/**\n * Storage factory — creates the appropriate storage backend based on resolved config.\n *\n * If PG is selected but fails to connect, falls back to LibSQL so the TUI\n * can start and the user can fix the connection via /settings.\n */\n\nimport type { MastraCompositeStore, RetentionConfig } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport { PostgresStore } from '@mastra/pg';\n\nimport type { StorageConfig, PgStorageConfig } from './project.js';\nimport { getDatabasePath, getVectorDatabasePath } from './project.js';\nimport { DEFAULT_RETENTION } from './storage-maintenance.js';\n\nexport const MASTRA_CODE_LOCAL_PRAGMAS = {\n cacheSize: -128000,\n mmapSize: 536870912,\n};\n\n/**\n * Construct a LibSQL store for an arbitrary url/authToken, applying the same\n * local pragmas the default factory uses. Shared so per-tenant storage\n * (see `web/tenant-storage.ts`) doesn't duplicate the construction.\n */\nexport function buildLibSQLStore(opts: {\n id?: string;\n url: string;\n authToken?: string;\n retention?: RetentionConfig;\n}): MastraCompositeStore {\n return new LibSQLStore({\n id: opts.id ?? 'mastra-code-storage',\n url: opts.url,\n ...(opts.authToken ? { authToken: opts.authToken } : {}),\n ...(opts.retention ? { retention: opts.retention } : {}),\n localPragmas: MASTRA_CODE_LOCAL_PRAGMAS,\n });\n}\n\n/** Construct a LibSQL vector store for an arbitrary url/authToken. */\nexport function buildLibSQLVector(opts: { id?: string; url: string; authToken?: string }): MastraVector {\n return new LibSQLVector({\n id: opts.id ?? 'mastra-code-vectors',\n url: opts.url,\n ...(opts.authToken ? { authToken: opts.authToken } : {}),\n });\n}\n\nexport interface StorageResult {\n storage: MastraCompositeStore;\n /** The effective backend after any fallback logic has run. */\n backend: 'libsql' | 'pg';\n /** Non-null when PG was requested but failed — contains a user-facing warning. */\n warning?: string;\n}\n\nfunction createFallbackLibSQL(): MastraCompositeStore {\n return buildLibSQLStore({ url: `file:${getDatabasePath()}`, retention: DEFAULT_RETENTION });\n}\n\n/**\n * Create a storage instance from the resolved config.\n *\n * - `libsql` backend → LibSQLStore (always available)\n * - `pg` backend → PostgresStore, falls back to LibSQL on connection failure\n */\nexport async function createStorage(config: StorageConfig): Promise<StorageResult> {\n if (config.backend === 'pg') {\n return createPgStorage(config);\n }\n\n // Default: LibSQL\n return {\n storage: buildLibSQLStore({ url: config.url, authToken: config.authToken, retention: DEFAULT_RETENTION }),\n backend: 'libsql',\n };\n}\n\nasync function createPgStorage(config: PgStorageConfig): Promise<StorageResult> {\n // No connection info → fall back with guidance\n if (!config.connectionString && !config.host) {\n return {\n storage: createFallbackLibSQL(),\n backend: 'libsql',\n warning:\n 'PostgreSQL backend selected but no connection info configured. ' +\n 'Using LibSQL fallback. Set a connection string via /settings.',\n };\n }\n\n const base = {\n id: 'mastra-code-storage' as const,\n retention: DEFAULT_RETENTION,\n ...(config.schemaName ? { schemaName: config.schemaName } : {}),\n ...(config.disableInit ? { disableInit: config.disableInit } : {}),\n ...(config.skipDefaultIndexes ? { skipDefaultIndexes: config.skipDefaultIndexes } : {}),\n };\n\n const store = config.connectionString\n ? new PostgresStore({ ...base, connectionString: config.connectionString })\n : new PostgresStore({\n ...base,\n host: config.host!,\n port: config.port,\n database: config.database,\n user: config.user,\n password: config.password,\n });\n\n // Test the connection before committing — if it fails, fall back to LibSQL\n // so the user can fix the config via /settings.\n try {\n await store.init();\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const target = config.connectionString ?? `${config.host}:${config.port ?? 5432}`;\n try {\n await store.close();\n } catch {\n // ignore cleanup errors\n }\n return {\n storage: createFallbackLibSQL(),\n backend: 'libsql',\n warning:\n `Failed to connect to PostgreSQL at ${target}: ${msg}\\n` +\n 'Using LibSQL fallback. Fix the connection via /settings.',\n };\n }\n\n return { storage: store, backend: 'pg' };\n}\n\n/**\n * Create a vector store for recall search.\n * Uses a separate LibSQL file to avoid bloating the main storage DB with embedding data.\n * For PG backends, reuses the same connection (PG handles the extra tables fine).\n */\nexport async function createVectorStore(\n config: StorageConfig,\n effectiveBackend: 'libsql' | 'pg' = config.backend,\n): Promise<MastraVector | undefined> {\n if (effectiveBackend === 'pg') {\n // PG can handle vector tables in the same database\n const pgConfig = config as PgStorageConfig;\n if (!pgConfig.connectionString && !pgConfig.host) return undefined;\n\n const { PgVector } = await import('@mastra/pg');\n return new PgVector({\n id: 'mastra-code-vectors',\n connectionString:\n pgConfig.connectionString ??\n `postgresql://${pgConfig.user}:${pgConfig.password}@${pgConfig.host}:${pgConfig.port ?? 5432}/${pgConfig.database}`,\n });\n }\n\n // LibSQL: separate file for vectors. Per-tenant configs supply an explicit\n // vectorUrl so each tenant's recall vectors are isolated; otherwise use the\n // shared default file.\n const libsqlConfig = config as { vectorUrl?: string; vectorAuthToken?: string };\n return buildLibSQLVector({\n url: libsqlConfig.vectorUrl ?? `file:${getVectorDatabasePath()}`,\n authToken: libsqlConfig.vectorAuthToken,\n });\n}\n"],"mappings":"AASA,SAAS,aAAa,oBAAoB;AAC1C,SAAS,qBAAqB;AAG9B,SAAS,iBAAiB,6BAA6B;AACvD,SAAS,yBAAyB;AAE3B,MAAM,4BAA4B;AAAA,EACvC,WAAW;AAAA,EACX,UAAU;AACZ;AAOO,SAAS,iBAAiB,MAKR;AACvB,SAAO,IAAI,YAAY;AAAA,IACrB,IAAI,KAAK,MAAM;AAAA,IACf,KAAK,KAAK;AAAA,IACV,GAAI,KAAK,YAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,IACtD,GAAI,KAAK,YAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,IACtD,cAAc;AAAA,EAChB,CAAC;AACH;AAGO,SAAS,kBAAkB,MAAsE;AACtG,SAAO,IAAI,aAAa;AAAA,IACtB,IAAI,KAAK,MAAM;AAAA,IACf,KAAK,KAAK;AAAA,IACV,GAAI,KAAK,YAAY,EAAE,W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,GAAG,OAAO,IAAI,IAAI,OAAO,QAAQ,IAAI;AAC/E,QAAI;AACF,YAAM,MAAM,MAAM;AAAA,IACpB,QAAQ;AAAA,IAER;AACA,WAAO;AAAA,MACL,SAAS,qBAAqB;AAAA,MAC9B,SAAS;AAAA,MACT,SACE,sCAAsC,MAAM,KAAK,GAAG;AAAA;AAAA,IAExD;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,OAAO,SAAS,KAAK;AACzC;AAOA,eAAsB,kBACpB,QACA,mBAAoC,OAAO,SACR;AACnC,MAAI,qBAAqB,MAAM;AAE7B,UAAM,WAAW;AACjB,QAAI,CAAC,SAAS,oBAAoB,CAAC,SAAS,KAAM,QAAO;AAEzD,UAAM,EAAE,SAAS,IAAI,MAAM,OAAO,YAAY;AAC9C,WAAO,IAAI,SAAS;AAAA,MAClB,IAAI;AAAA,MACJ,kBACE,SAAS,oBACT,gBAAgB,SAAS,IAAI,IAAI,SAAS,QAAQ,IAAI,SAAS,IAAI,IAAI,SAAS,QAAQ,IAAI,IAAI,SAAS,QAAQ;AAAA,IACrH,CAAC;AAAA,EACH;AAKA,QAAM,eAAe;AACrB,SAAO,kBAAkB;AAAA,IACvB,KAAK,aAAa,aAAa,QAAQ,sBAAsB,CAAC;AAAA,IAC9D,WAAW,aAAa;AAAA,EAC1B,CAAC;AACH;","names":[]}
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Storage maintenance — retention defaults and disk reclamation for mastracode.
3
+ *
4
+ * Retention (`DEFAULT_RETENTION`) is wired into the inner store by the storage
5
+ * factory so `storage.prune()` can delete aged rows across every domain,
6
+ * including the legacy libsql observability spans table.
7
+ *
8
+ * `prune()` only deletes rows — SQLite keeps the freed pages inside the file.
9
+ * `reclaimLibSQLDisk()` returns that space to the OS by streaming a
10
+ * `VACUUM INTO` copy of each file and swapping it into place. It requires all
11
+ * connections to be closed first, so it only runs from the post-TUI
12
+ * maintenance flow. We deliberately do NOT expose VACUUM as a public API on
13
+ * LibSQLStore.
14
+ */
15
+ import type { MastraCompositeStore, PruneOptions, PruneResult, RetentionConfig } from '@mastra/core/storage';
16
+ import type { StorageConfig } from './project.js';
17
+ /**
18
+ * Default retention for mastracode's own storage. Tables not listed are kept
19
+ * forever. Ages chosen for a local dev tool where observability data dwarfs
20
+ * everything else (spans have been observed at 17+ GB):
21
+ * - spans/logs: short-lived debugging telemetry → 14d
22
+ * - scorer results & workflow snapshots: medium-lived run records → 30d
23
+ * - chat history (messages/threads): long-lived, user-visible → 90d
24
+ */
25
+ export declare const DEFAULT_RETENTION: RetentionConfig;
26
+ /** Result of reclaiming disk for one database file (sizes include the WAL). */
27
+ export interface ReclaimResult {
28
+ file: string;
29
+ bytesBefore: number;
30
+ bytesAfter: number;
31
+ }
32
+ /** Handle the TUI uses to run storage maintenance without reaching into store internals. */
33
+ export interface StorageMaintenance {
34
+ backend: 'libsql' | 'pg';
35
+ /** Retention policies in effect (for display in /prune output). */
36
+ retention: RetentionConfig;
37
+ /** Delete rows older than the retention policies. Safe to re-run; batched and cancellable. `options.retention` replaces the standing policies for this call only. */
38
+ prune: (options?: PruneOptions) => Promise<PruneResult[]>;
39
+ /** Close the long-lived storage connection (checkpoints WAL for local libsql). Nothing can use the store afterwards. */
40
+ closeStorage?: () => Promise<void>;
41
+ /** Compact local libsql files (VACUUM INTO + swap) to return freed pages to the OS. Only set for local libsql backends. */
42
+ reclaimDisk?: (onFileStart?: (file: string, bytesBefore: number, liveBytes: number) => void) => Promise<ReclaimResult[]>;
43
+ }
44
+ /** Free bytes required before compacting: the compacted copy plus 20% + 256 MB headroom. */
45
+ export declare function requiredFreeBytes(liveBytes: number): number;
46
+ /**
47
+ * Compact each local libsql db file by streaming a `VACUUM INTO` copy next to
48
+ * it, then swapping the copy into place. Reports before/after sizes.
49
+ *
50
+ * Deliberately NOT an in-place `VACUUM`: that copies all live content into a
51
+ * temp store (held in memory by libsql builds with `temp_store=MEMORY`) and
52
+ * then rewrites the entire database back through the WAL — on multi-GB
53
+ * databases that has frozen whole machines via memory/IO exhaustion.
54
+ * `VACUUM INTO` reads the logical database once and writes the compacted copy
55
+ * sequentially with bounded memory, and the WAL never grows.
56
+ *
57
+ * Each file is preflighted: live bytes are estimated from
58
+ * `page_count - freelist_count` and the copy is refused unless the volume has
59
+ * `requiredFreeBytes()` available.
60
+ *
61
+ * MUST run with every connection to these files closed (the swap replaces the
62
+ * inode — a surviving connection would keep writing to the unlinked old file).
63
+ * `runStorageMaintenance()` closes storage before calling this.
64
+ */
65
+ export declare function reclaimLibSQLDisk(dbFiles: string[], onFileStart?: (file: string, bytesBefore: number, liveBytes: number) => void): Promise<ReclaimResult[]>;
66
+ /**
67
+ * Resolve the local libsql db files eligible for checkpoint + VACUUM.
68
+ * Returns [] for remote (turso) urls and PG backends. When PG was requested
69
+ * but the factory fell back to libsql, the fallback uses the default files.
70
+ */
71
+ export declare function resolveLocalDbFiles(config: StorageConfig, effectiveBackend: 'libsql' | 'pg'): string[];
72
+ /**
73
+ * Build the maintenance handle for the effective storage backend.
74
+ * `localDbFiles` are the local libsql file paths eligible for VACUUM;
75
+ * pass an empty array for remote (turso) or PG backends.
76
+ */
77
+ export declare function createStorageMaintenance(opts: {
78
+ storage: MastraCompositeStore;
79
+ backend: 'libsql' | 'pg';
80
+ retention: RetentionConfig;
81
+ localDbFiles: string[];
82
+ /** Closes the vector store's connection; required for local libsql so the compaction swap isn't blocked by our own handle. */
83
+ closeVector?: () => Promise<void>;
84
+ }): StorageMaintenance;
85
+ export declare function formatBytes(bytes: number): string;
86
+ /**
87
+ * Run storage maintenance with exclusive access to the database, reporting
88
+ * progress through `log` (one line per pass so large deletes are visible).
89
+ *
90
+ * Must run AFTER the TUI is stopped and background writers are quiesced —
91
+ * batched deletes and VACUUM contend with live writes (SQLITE_BUSY) and can
92
+ * starve the event loop that renders the TUI. The storage connection is
93
+ * closed at the end (checkpointing the WAL for local libsql), so the process
94
+ * must exit afterwards.
95
+ */
96
+ export declare function runStorageMaintenance(opts: {
97
+ maintenance: StorageMaintenance;
98
+ vacuum: boolean;
99
+ /** Skip the memory domain (messages/threads) so chat history is preserved. */
100
+ keepMemory?: boolean;
101
+ log: (line: string) => void;
102
+ }): Promise<void>;
103
+ //# sourceMappingURL=storage-maintenance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-maintenance.d.ts","sourceRoot":"","sources":["../../src/utils/storage-maintenance.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAKH,OAAO,KAAK,EAAE,oBAAoB,EAAE,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAQ7G,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAGlD;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,EAAE,eAe/B,CAAC;AAEF,+EAA+E;AAC/E,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,4FAA4F;AAC5F,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,QAAQ,GAAG,IAAI,CAAC;IACzB,mEAAmE;IACnE,SAAS,EAAE,eAAe,CAAC;IAC3B,qKAAqK;IACrK,KAAK,EAAE,CAAC,OAAO,CAAC,EAAE,YAAY,KAAK,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IAC1D,wHAAwH;IACxH,YAAY,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IACnC,2HAA2H;IAC3H,WAAW,CAAC,EAAE,CACZ,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,IAAI,KACzE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;CAC/B;AAeD,4FAA4F;AAC5F,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE3D;AA0BD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,MAAM,EAAE,EACjB,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,IAAI,GAC3E,OAAO,CAAC,aAAa,EAAE,CAAC,CA0G1B;AAQD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,aAAa,EAAE,gBAAgB,EAAE,QAAQ,GAAG,IAAI,GAAG,MAAM,EAAE,CAatG;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE;IAC7C,OAAO,EAAE,oBAAoB,CAAC;IAC9B,OAAO,EAAE,QAAQ,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,eAAe,CAAC;IAC3B,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,8HAA8H;IAC9H,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACnC,GAAG,kBAAkB,CAiBrB;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAWjD;AAKD;;;;;;;;;GASG;AACH,wBAAsB,qBAAqB,CAAC,IAAI,EAAE;IAChD,WAAW,EAAE,kBAAkB,CAAC;IAChC,MAAM,EAAE,OAAO,CAAC;IAChB,8EAA8E;IAC9E,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7B,GAAG,OAAO,CAAC,IAAI,CAAC,CA2EhB"}
@@ -0,0 +1,236 @@
1
+ import { closeSync, existsSync, openSync, readSync, renameSync, rmSync, statSync, statfsSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import Database from "libsql";
4
+ import { getDatabasePath, getVectorDatabasePath } from "./project.js";
5
+ const DEFAULT_RETENTION = {
6
+ memory: {
7
+ messages: { maxAge: "90d" },
8
+ threads: { maxAge: "90d" }
9
+ },
10
+ observability: {
11
+ spans: { maxAge: "14d" },
12
+ logs: { maxAge: "14d" }
13
+ },
14
+ scores: {
15
+ scorers: { maxAge: "30d" }
16
+ },
17
+ workflows: {
18
+ workflowSnapshot: { maxAge: "30d" }
19
+ }
20
+ };
21
+ function fileSizeWithWal(dbFile) {
22
+ let total = 0;
23
+ for (const candidate of [dbFile, `${dbFile}-wal`]) {
24
+ try {
25
+ total += statSync(candidate).size;
26
+ } catch {
27
+ }
28
+ }
29
+ return total;
30
+ }
31
+ function requiredFreeBytes(liveBytes) {
32
+ return Math.ceil(liveBytes * 1.2) + 256 * 1024 * 1024;
33
+ }
34
+ function pragmaNumber(db, pragma) {
35
+ const rows = db.pragma(pragma);
36
+ const row = rows?.[0];
37
+ return row ? Number(Object.values(row)[0]) : 0;
38
+ }
39
+ function journalModeFromHeader(file) {
40
+ const fd = openSync(file, "r");
41
+ try {
42
+ const buf = Buffer.alloc(2);
43
+ if (readSync(fd, buf, 0, 2, 18) !== 2) return "unknown";
44
+ if (buf[0] === 2 && buf[1] === 2) return "wal";
45
+ if (buf[0] === 1 && buf[1] === 1) return "delete";
46
+ return "unknown";
47
+ } finally {
48
+ closeSync(fd);
49
+ }
50
+ }
51
+ async function reclaimLibSQLDisk(dbFiles, onFileStart) {
52
+ const results = [];
53
+ for (const file of dbFiles) {
54
+ if (!existsSync(file) || statSync(file).size < 100) continue;
55
+ const bytesBefore = fileSizeWithWal(file);
56
+ const tmp = `${file}.vacuum-tmp`;
57
+ rmSync(tmp, { force: true });
58
+ const probe = new Database(file);
59
+ try {
60
+ probe.exec("PRAGMA busy_timeout = 2000");
61
+ probe.exec("PRAGMA journal_mode = WAL");
62
+ probe.exec("PRAGMA journal_mode = DELETE");
63
+ } catch {
64
+ } finally {
65
+ probe.close();
66
+ }
67
+ if (journalModeFromHeader(file) !== "delete") {
68
+ throw new Error(
69
+ `${file} is in use by another process \u2014 is another Mastra Code session running? Close other sessions and run /prune vacuum again.`
70
+ );
71
+ }
72
+ const db = new Database(file);
73
+ try {
74
+ db.exec("PRAGMA busy_timeout = 2000");
75
+ const pageSize = pragmaNumber(db, "page_size");
76
+ const pageCount = pragmaNumber(db, "page_count");
77
+ const freelistCount = pragmaNumber(db, "freelist_count");
78
+ const liveBytes = Math.max(0, pageCount - freelistCount) * pageSize;
79
+ const { bsize, bavail } = statfsSync(dirname(file));
80
+ const freeBytes = bsize * bavail;
81
+ if (freeBytes < requiredFreeBytes(liveBytes)) {
82
+ throw new Error(
83
+ `Not enough free disk space to compact ${file}: need ${formatBytes(requiredFreeBytes(liveBytes))} for a ${formatBytes(liveBytes)} compacted copy, but only ${formatBytes(freeBytes)} is free.`
84
+ );
85
+ }
86
+ onFileStart?.(file, bytesBefore, liveBytes);
87
+ db.exec(`VACUUM INTO '${tmp.replace(/'/g, "''")}'`);
88
+ } catch (err) {
89
+ rmSync(tmp, { force: true });
90
+ throw err;
91
+ } finally {
92
+ db.close();
93
+ }
94
+ if (journalModeFromHeader(file) !== "delete") {
95
+ rmSync(tmp, { force: true });
96
+ throw new Error(
97
+ `${file} was opened by another process during compaction \u2014 is another Mastra Code session running? Close other sessions and run /prune vacuum again.`
98
+ );
99
+ }
100
+ renameSync(file, `${file}.old`);
101
+ try {
102
+ rmSync(`${file}-wal`, { force: true });
103
+ rmSync(`${file}-shm`, { force: true });
104
+ renameSync(tmp, file);
105
+ } catch (err) {
106
+ try {
107
+ renameSync(`${file}.old`, file);
108
+ } catch {
109
+ throw new Error(
110
+ `Failed to swap compacted copy into place AND failed to restore the original \u2014 your data is intact at ${file}.old; rename it back to ${file} manually. Original error: ${err instanceof Error ? err.message : String(err)}`
111
+ );
112
+ }
113
+ rmSync(tmp, { force: true });
114
+ throw err;
115
+ }
116
+ rmSync(`${file}.old`, { force: true });
117
+ results.push({ file, bytesBefore, bytesAfter: fileSizeWithWal(file) });
118
+ }
119
+ return results;
120
+ }
121
+ function fileUrlToPath(url) {
122
+ if (!url.startsWith("file:")) return void 0;
123
+ return url.replace(/^file:\/\//, "").replace(/^file:/, "");
124
+ }
125
+ function resolveLocalDbFiles(config, effectiveBackend) {
126
+ if (effectiveBackend !== "libsql") return [];
127
+ if (config.backend === "pg") {
128
+ return [getDatabasePath(), getVectorDatabasePath()];
129
+ }
130
+ if (config.isRemote) return [];
131
+ const files = [];
132
+ const main = fileUrlToPath(config.url);
133
+ if (main) files.push(main);
134
+ const vector = config.vectorUrl ? fileUrlToPath(config.vectorUrl) : getVectorDatabasePath();
135
+ if (vector) files.push(vector);
136
+ return files;
137
+ }
138
+ function createStorageMaintenance(opts) {
139
+ const { storage, backend, retention, localDbFiles, closeVector } = opts;
140
+ return {
141
+ backend,
142
+ retention,
143
+ prune: (options) => storage.prune(options),
144
+ closeStorage: async () => {
145
+ await storage.close?.();
146
+ await closeVector?.();
147
+ },
148
+ ...backend === "libsql" && localDbFiles.length > 0 ? {
149
+ reclaimDisk: (onFileStart) => reclaimLibSQLDisk(localDbFiles, onFileStart)
150
+ } : {}
151
+ };
152
+ }
153
+ function formatBytes(bytes) {
154
+ if (bytes < 1024) return `${bytes} B`;
155
+ const units = ["KB", "MB", "GB", "TB"];
156
+ let value = bytes;
157
+ let unit = "B";
158
+ for (const next of units) {
159
+ if (value < 1024) break;
160
+ value /= 1024;
161
+ unit = next;
162
+ }
163
+ return `${value.toFixed(1)} ${unit}`;
164
+ }
165
+ const PASS_MAX_BATCHES = 20;
166
+ async function runStorageMaintenance(opts) {
167
+ const { maintenance, vacuum, keepMemory = false, log } = opts;
168
+ const { memory: _memory, ...withoutMemory } = maintenance.retention;
169
+ const retentionForRun = keepMemory ? { retention: withoutMemory } : {};
170
+ log("Pruning rows older than the retention policies:");
171
+ for (const [domain, tables] of Object.entries(maintenance.retention)) {
172
+ for (const [table, policy] of Object.entries(tables ?? {})) {
173
+ const kept = keepMemory && domain === "memory";
174
+ log(` ${domain}.${table}: ${kept ? "kept (keep-memory)" : policy.maxAge}`);
175
+ }
176
+ }
177
+ const totals = /* @__PURE__ */ new Map();
178
+ for (; ; ) {
179
+ const results = await maintenance.prune({ maxBatches: PASS_MAX_BATCHES, ...retentionForRun });
180
+ if (results.length === 0) break;
181
+ let remaining = false;
182
+ let deletedThisPass = 0;
183
+ for (const r of results) {
184
+ const key = `${r.domain}.${r.table}`;
185
+ totals.set(key, (totals.get(key) ?? 0) + r.deleted);
186
+ deletedThisPass += r.deleted;
187
+ if (!r.done) remaining = true;
188
+ if (r.deleted > 0) {
189
+ log(` ${key}: ${totals.get(key)} rows deleted${r.done ? "" : " so far\u2026"}`);
190
+ }
191
+ }
192
+ if (!remaining) break;
193
+ if (deletedThisPass === 0) {
194
+ log(" stopping: no progress in the last pass.");
195
+ break;
196
+ }
197
+ }
198
+ const totalDeleted = [...totals.values()].reduce((sum, n) => sum + n, 0);
199
+ log(
200
+ totalDeleted === 0 ? "Nothing to prune \u2014 no retention-eligible rows found." : `Prune complete: ${totalDeleted} rows deleted.`
201
+ );
202
+ await maintenance.closeStorage?.();
203
+ if (!vacuum) {
204
+ if (maintenance.reclaimDisk) {
205
+ log("Deleted rows free pages inside the db file but not on disk. Run /prune vacuum to reclaim disk space.");
206
+ }
207
+ return;
208
+ }
209
+ if (!maintenance.reclaimDisk) {
210
+ log("Disk reclamation (VACUUM) is only available for local libsql storage.");
211
+ return;
212
+ }
213
+ log("Reclaiming disk (compacting database files)\u2026 this can take several minutes on large databases.");
214
+ const reclaimed = await maintenance.reclaimDisk((file, bytesBefore, liveBytes) => {
215
+ log(` vacuuming ${file} (${formatBytes(bytesBefore)}, ~${formatBytes(liveBytes)} live)\u2026`);
216
+ });
217
+ if (reclaimed.length === 0) {
218
+ log("No local database files found to vacuum.");
219
+ return;
220
+ }
221
+ for (const r of reclaimed) {
222
+ log(` ${r.file}: ${formatBytes(r.bytesBefore)} \u2192 ${formatBytes(r.bytesAfter)}`);
223
+ }
224
+ const saved = reclaimed.reduce((sum, r) => sum + Math.max(0, r.bytesBefore - r.bytesAfter), 0);
225
+ log(`Reclaimed ${formatBytes(saved)}.`);
226
+ }
227
+ export {
228
+ DEFAULT_RETENTION,
229
+ createStorageMaintenance,
230
+ formatBytes,
231
+ reclaimLibSQLDisk,
232
+ requiredFreeBytes,
233
+ resolveLocalDbFiles,
234
+ runStorageMaintenance
235
+ };
236
+ //# sourceMappingURL=storage-maintenance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/storage-maintenance.ts"],"sourcesContent":["/**\n * Storage maintenance — retention defaults and disk reclamation for mastracode.\n *\n * Retention (`DEFAULT_RETENTION`) is wired into the inner store by the storage\n * factory so `storage.prune()` can delete aged rows across every domain,\n * including the legacy libsql observability spans table.\n *\n * `prune()` only deletes rows — SQLite keeps the freed pages inside the file.\n * `reclaimLibSQLDisk()` returns that space to the OS by streaming a\n * `VACUUM INTO` copy of each file and swapping it into place. It requires all\n * connections to be closed first, so it only runs from the post-TUI\n * maintenance flow. We deliberately do NOT expose VACUUM as a public API on\n * LibSQLStore.\n */\n\nimport { closeSync, existsSync, openSync, readSync, renameSync, rmSync, statSync, statfsSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\nimport type { MastraCompositeStore, PruneOptions, PruneResult, RetentionConfig } from '@mastra/core/storage';\n// Native `libsql` driver, deliberately alongside `@libsql/client` (used by the\n// stores): maintenance needs deterministic connection close for the\n// exclusivity probe, and the wrapper's close() can leave the file lock held\n// until GC finalizes cached statements. Don't \"clean up\" either dependency.\n// Upstream report: https://github.com/tursodatabase/libsql-js/issues/228\nimport Database from 'libsql';\n\nimport type { StorageConfig } from './project.js';\nimport { getDatabasePath, getVectorDatabasePath } from './project.js';\n\n/**\n * Default retention for mastracode's own storage. Tables not listed are kept\n * forever. Ages chosen for a local dev tool where observability data dwarfs\n * everything else (spans have been observed at 17+ GB):\n * - spans/logs: short-lived debugging telemetry → 14d\n * - scorer results & workflow snapshots: medium-lived run records → 30d\n * - chat history (messages/threads): long-lived, user-visible → 90d\n */\nexport const DEFAULT_RETENTION: RetentionConfig = {\n memory: {\n messages: { maxAge: '90d' },\n threads: { maxAge: '90d' },\n },\n observability: {\n spans: { maxAge: '14d' },\n logs: { maxAge: '14d' },\n },\n scores: {\n scorers: { maxAge: '30d' },\n },\n workflows: {\n workflowSnapshot: { maxAge: '30d' },\n },\n};\n\n/** Result of reclaiming disk for one database file (sizes include the WAL). */\nexport interface ReclaimResult {\n file: string;\n bytesBefore: number;\n bytesAfter: number;\n}\n\n/** Handle the TUI uses to run storage maintenance without reaching into store internals. */\nexport interface StorageMaintenance {\n backend: 'libsql' | 'pg';\n /** Retention policies in effect (for display in /prune output). */\n retention: RetentionConfig;\n /** Delete rows older than the retention policies. Safe to re-run; batched and cancellable. `options.retention` replaces the standing policies for this call only. */\n prune: (options?: PruneOptions) => Promise<PruneResult[]>;\n /** Close the long-lived storage connection (checkpoints WAL for local libsql). Nothing can use the store afterwards. */\n closeStorage?: () => Promise<void>;\n /** Compact local libsql files (VACUUM INTO + swap) to return freed pages to the OS. Only set for local libsql backends. */\n reclaimDisk?: (\n onFileStart?: (file: string, bytesBefore: number, liveBytes: number) => void,\n ) => Promise<ReclaimResult[]>;\n}\n\n/** db file size + its WAL sidecar, in bytes. Missing files count as 0. */\nfunction fileSizeWithWal(dbFile: string): number {\n let total = 0;\n for (const candidate of [dbFile, `${dbFile}-wal`]) {\n try {\n total += statSync(candidate).size;\n } catch {\n // file may not exist (e.g. WAL already truncated)\n }\n }\n return total;\n}\n\n/** Free bytes required before compacting: the compacted copy plus 20% + 256 MB headroom. */\nexport function requiredFreeBytes(liveBytes: number): number {\n return Math.ceil(liveBytes * 1.2) + 256 * 1024 * 1024;\n}\n\n/** First column of the first row of a PRAGMA result, as a number. */\nfunction pragmaNumber(db: InstanceType<typeof Database>, pragma: string): number {\n const rows = db.pragma(pragma) as Array<Record<string, unknown>> | undefined;\n const row = rows?.[0];\n return row ? Number(Object.values(row)[0]) : 0;\n}\n\n/**\n * Journal mode straight from the SQLite file header (bytes 18/19:\n * 1 = rollback journal, 2 = WAL) — readable without opening a connection.\n */\nfunction journalModeFromHeader(file: string): 'wal' | 'delete' | 'unknown' {\n const fd = openSync(file, 'r');\n try {\n const buf = Buffer.alloc(2);\n if (readSync(fd, buf, 0, 2, 18) !== 2) return 'unknown';\n if (buf[0] === 2 && buf[1] === 2) return 'wal';\n if (buf[0] === 1 && buf[1] === 1) return 'delete';\n return 'unknown';\n } finally {\n closeSync(fd);\n }\n}\n\n/**\n * Compact each local libsql db file by streaming a `VACUUM INTO` copy next to\n * it, then swapping the copy into place. Reports before/after sizes.\n *\n * Deliberately NOT an in-place `VACUUM`: that copies all live content into a\n * temp store (held in memory by libsql builds with `temp_store=MEMORY`) and\n * then rewrites the entire database back through the WAL — on multi-GB\n * databases that has frozen whole machines via memory/IO exhaustion.\n * `VACUUM INTO` reads the logical database once and writes the compacted copy\n * sequentially with bounded memory, and the WAL never grows.\n *\n * Each file is preflighted: live bytes are estimated from\n * `page_count - freelist_count` and the copy is refused unless the volume has\n * `requiredFreeBytes()` available.\n *\n * MUST run with every connection to these files closed (the swap replaces the\n * inode — a surviving connection would keep writing to the unlinked old file).\n * `runStorageMaintenance()` closes storage before calling this.\n */\nexport async function reclaimLibSQLDisk(\n dbFiles: string[],\n onFileStart?: (file: string, bytesBefore: number, liveBytes: number) => void,\n): Promise<ReclaimResult[]> {\n const results: ReclaimResult[] = [];\n for (const file of dbFiles) {\n // Skip missing files and files too small to have a SQLite header — nothing to reclaim\n if (!existsSync(file) || statSync(file).size < 100) continue;\n const bytesBefore = fileSizeWithWal(file);\n const tmp = `${file}.vacuum-tmp`;\n rmSync(tmp, { force: true });\n // Prove we're the only connection before the swap: every open WAL-mode\n // connection (all Mastra Code sessions run WAL) holds a shared-memory\n // lock, so switching WAL -> DELETE only succeeds with exclusive access.\n // A surviving connection would keep writing to the unlinked old inode\n // after the swap and silently lose data.\n //\n // The probe uses exec() only and verifies the outcome from the SQLite\n // file header: prepared statements (including db.pragma()) pin a libsql\n // connection open past close(), so a failed in-connection probe would\n // itself hold the WAL lock and poison every retry in this process.\n // Upstream bug (libsql 0.5.x / @libsql/client 0.17.x): Database.close()\n // does not finalize outstanding statements — they are only finalized by\n // GC, so lock release after close() is nondeterministic. Reported as\n // https://github.com/tursodatabase/libsql-js/issues/228 (fix in flight in\n // PR #214). Once that lands, the header check can become a plain\n // journal_mode query.\n const probe = new Database(file);\n try {\n probe.exec('PRAGMA busy_timeout = 2000');\n // Round-trip through WAL so the probe also works when a clean shutdown\n // already left the file in rollback mode.\n probe.exec('PRAGMA journal_mode = WAL');\n probe.exec('PRAGMA journal_mode = DELETE');\n } catch {\n // busy — the header check below reports the failure\n } finally {\n probe.close();\n }\n if (journalModeFromHeader(file) !== 'delete') {\n throw new Error(\n `${file} is in use by another process — is another Mastra Code session running? ` +\n `Close other sessions and run /prune vacuum again.`,\n );\n }\n // Native `libsql` driver, not `@libsql/client`: the wrapper's close() can\n // leave the file lock held in-process (cached statements), which would\n // block other connections afterwards. This connection stays in rollback\n // mode, so even a pinned statement holds no lock once we're done.\n const db = new Database(file);\n try {\n db.exec('PRAGMA busy_timeout = 2000');\n const pageSize = pragmaNumber(db, 'page_size');\n const pageCount = pragmaNumber(db, 'page_count');\n const freelistCount = pragmaNumber(db, 'freelist_count');\n const liveBytes = Math.max(0, pageCount - freelistCount) * pageSize;\n const { bsize, bavail } = statfsSync(dirname(file));\n const freeBytes = bsize * bavail;\n if (freeBytes < requiredFreeBytes(liveBytes)) {\n throw new Error(\n `Not enough free disk space to compact ${file}: need ${formatBytes(requiredFreeBytes(liveBytes))} ` +\n `for a ${formatBytes(liveBytes)} compacted copy, but only ${formatBytes(freeBytes)} is free.`,\n );\n }\n onFileStart?.(file, bytesBefore, liveBytes);\n db.exec(`VACUUM INTO '${tmp.replace(/'/g, \"''\")}'`);\n } catch (err) {\n rmSync(tmp, { force: true });\n throw err;\n } finally {\n db.close();\n }\n // Re-probe right before the swap: `VACUUM INTO` can take tens of seconds\n // on multi-GB files, and a session started in that window reopens the db\n // in WAL mode (flipping the header back). Swapping under it would orphan\n // that session's inode and silently lose its writes.\n if (journalModeFromHeader(file) !== 'delete') {\n rmSync(tmp, { force: true });\n throw new Error(\n `${file} was opened by another process during compaction — is another Mastra Code session running? ` +\n `Close other sessions and run /prune vacuum again.`,\n );\n }\n // Swap the compacted copy into place. The old WAL/SHM sidecars belong to\n // the old inode — they must never be paired with the new file. If any step\n // after the first rename fails, restore the original so the db path is\n // never left empty (a naive restart would otherwise create a fresh db).\n renameSync(file, `${file}.old`);\n try {\n rmSync(`${file}-wal`, { force: true });\n rmSync(`${file}-shm`, { force: true });\n renameSync(tmp, file);\n } catch (err) {\n try {\n renameSync(`${file}.old`, file);\n } catch {\n throw new Error(\n `Failed to swap compacted copy into place AND failed to restore the original — ` +\n `your data is intact at ${file}.old; rename it back to ${file} manually. ` +\n `Original error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n rmSync(tmp, { force: true });\n throw err;\n }\n rmSync(`${file}.old`, { force: true });\n results.push({ file, bytesBefore, bytesAfter: fileSizeWithWal(file) });\n }\n return results;\n}\n\n/** `file:/path` or `file:///path` → filesystem path; undefined for non-file urls. */\nfunction fileUrlToPath(url: string): string | undefined {\n if (!url.startsWith('file:')) return undefined;\n return url.replace(/^file:\\/\\//, '').replace(/^file:/, '');\n}\n\n/**\n * Resolve the local libsql db files eligible for checkpoint + VACUUM.\n * Returns [] for remote (turso) urls and PG backends. When PG was requested\n * but the factory fell back to libsql, the fallback uses the default files.\n */\nexport function resolveLocalDbFiles(config: StorageConfig, effectiveBackend: 'libsql' | 'pg'): string[] {\n if (effectiveBackend !== 'libsql') return [];\n if (config.backend === 'pg') {\n // PG requested but fell back to the default local libsql files\n return [getDatabasePath(), getVectorDatabasePath()];\n }\n if (config.isRemote) return [];\n const files: string[] = [];\n const main = fileUrlToPath(config.url);\n if (main) files.push(main);\n const vector = config.vectorUrl ? fileUrlToPath(config.vectorUrl) : getVectorDatabasePath();\n if (vector) files.push(vector);\n return files;\n}\n\n/**\n * Build the maintenance handle for the effective storage backend.\n * `localDbFiles` are the local libsql file paths eligible for VACUUM;\n * pass an empty array for remote (turso) or PG backends.\n */\nexport function createStorageMaintenance(opts: {\n storage: MastraCompositeStore;\n backend: 'libsql' | 'pg';\n retention: RetentionConfig;\n localDbFiles: string[];\n /** Closes the vector store's connection; required for local libsql so the compaction swap isn't blocked by our own handle. */\n closeVector?: () => Promise<void>;\n}): StorageMaintenance {\n const { storage, backend, retention, localDbFiles, closeVector } = opts;\n return {\n backend,\n retention,\n prune: options => storage.prune(options),\n closeStorage: async () => {\n await storage.close?.();\n await closeVector?.();\n },\n ...(backend === 'libsql' && localDbFiles.length > 0\n ? {\n reclaimDisk: (onFileStart?: (file: string, bytesBefore: number, liveBytes: number) => void) =>\n reclaimLibSQLDisk(localDbFiles, onFileStart),\n }\n : {}),\n };\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n const units = ['KB', 'MB', 'GB', 'TB'];\n let value = bytes;\n let unit = 'B';\n for (const next of units) {\n if (value < 1024) break;\n value /= 1024;\n unit = next;\n }\n return `${value.toFixed(1)} ${unit}`;\n}\n\n/** Rows deleted per table per pass: default batchSize (1000) × 20 batches. */\nconst PASS_MAX_BATCHES = 20;\n\n/**\n * Run storage maintenance with exclusive access to the database, reporting\n * progress through `log` (one line per pass so large deletes are visible).\n *\n * Must run AFTER the TUI is stopped and background writers are quiesced —\n * batched deletes and VACUUM contend with live writes (SQLITE_BUSY) and can\n * starve the event loop that renders the TUI. The storage connection is\n * closed at the end (checkpointing the WAL for local libsql), so the process\n * must exit afterwards.\n */\nexport async function runStorageMaintenance(opts: {\n maintenance: StorageMaintenance;\n vacuum: boolean;\n /** Skip the memory domain (messages/threads) so chat history is preserved. */\n keepMemory?: boolean;\n log: (line: string) => void;\n}): Promise<void> {\n const { maintenance, vacuum, keepMemory = false, log } = opts;\n\n // keep-memory: prune with the standing policies minus the memory domain,\n // for this run only. The configured retention is untouched.\n const { memory: _memory, ...withoutMemory } = maintenance.retention;\n const retentionForRun = keepMemory ? { retention: withoutMemory } : {};\n\n log('Pruning rows older than the retention policies:');\n for (const [domain, tables] of Object.entries(maintenance.retention)) {\n for (const [table, policy] of Object.entries(tables ?? {})) {\n const kept = keepMemory && domain === 'memory';\n log(` ${domain}.${table}: ${kept ? 'kept (keep-memory)' : (policy as { maxAge: string | number }).maxAge}`);\n }\n }\n\n const totals = new Map<string, number>();\n for (;;) {\n const results = await maintenance.prune({ maxBatches: PASS_MAX_BATCHES, ...retentionForRun });\n if (results.length === 0) break;\n let remaining = false;\n let deletedThisPass = 0;\n for (const r of results) {\n const key = `${r.domain}.${r.table}`;\n totals.set(key, (totals.get(key) ?? 0) + r.deleted);\n deletedThisPass += r.deleted;\n if (!r.done) remaining = true;\n if (r.deleted > 0) {\n log(` ${key}: ${totals.get(key)} rows deleted${r.done ? '' : ' so far…'}`);\n }\n }\n if (!remaining) break;\n // Safety valve: a table reported more eligible rows but nothing was\n // deleted this pass — bail instead of spinning forever.\n if (deletedThisPass === 0) {\n log(' stopping: no progress in the last pass.');\n break;\n }\n }\n const totalDeleted = [...totals.values()].reduce((sum, n) => sum + n, 0);\n log(\n totalDeleted === 0\n ? 'Nothing to prune — no retention-eligible rows found.'\n : `Prune complete: ${totalDeleted} rows deleted.`,\n );\n\n // Release the long-lived connection: checkpoints the WAL for local libsql\n // and guarantees VACUUM below isn't blocked by our own open handles.\n await maintenance.closeStorage?.();\n\n if (!vacuum) {\n if (maintenance.reclaimDisk) {\n log('Deleted rows free pages inside the db file but not on disk. Run /prune vacuum to reclaim disk space.');\n }\n return;\n }\n\n if (!maintenance.reclaimDisk) {\n log('Disk reclamation (VACUUM) is only available for local libsql storage.');\n return;\n }\n\n log('Reclaiming disk (compacting database files)… this can take several minutes on large databases.');\n const reclaimed = await maintenance.reclaimDisk((file, bytesBefore, liveBytes) => {\n log(` vacuuming ${file} (${formatBytes(bytesBefore)}, ~${formatBytes(liveBytes)} live)…`);\n });\n if (reclaimed.length === 0) {\n log('No local database files found to vacuum.');\n return;\n }\n for (const r of reclaimed) {\n log(` ${r.file}: ${formatBytes(r.bytesBefore)} → ${formatBytes(r.bytesAfter)}`);\n }\n const saved = reclaimed.reduce((sum, r) => sum + Math.max(0, r.bytesBefore - r.bytesAfter), 0);\n log(`Reclaimed ${formatBytes(saved)}.`);\n}\n"],"mappings":"AAeA,SAAS,WAAW,YAAY,UAAU,UAAU,YAAY,QAAQ,UAAU,kBAAkB;AACpG,SAAS,eAAe;AAQxB,OAAO,cAAc;AAGrB,SAAS,iBAAiB,6BAA6B;AAUhD,MAAM,oBAAqC;AAAA,EAChD,QAAQ;AAAA,IACN,UAAU,EAAE,QAAQ,MAAM;AAAA,IAC1B,SAAS,EAAE,QAAQ,MAAM;AAAA,EAC3B;AAAA,EACA,eAAe;AAAA,IACb,OAAO,EAAE,QAAQ,MAAM;AAAA,IACvB,MAAM,EAAE,QAAQ,MAAM;AAAA,EACxB;AAAA,EACA,QAAQ;AAAA,IACN,SAAS,EAAE,QAAQ,MAAM;AAAA,EAC3B;AAAA,EACA,WAAW;AAAA,IACT,kBAAkB,EAAE,QAAQ,MAAM;AAAA,EACpC;AACF;AAyBA,SAAS,gBAAgB,QAAwB;AAC/C,MAAI,QAAQ;AACZ,aAAW,aAAa,CAAC,QAAQ,GAAG,MAAM,MAAM,GAAG;AACjD,QAAI;AACF,eAAS,SAAS,SAAS,EAAE;AAAA,IAC/B,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,kBAAkB,WAA2B;AAC3D,SAAO,KAAK,KAAK,YAAY,GAAG,IAAI,MAAM,OAAO;AACnD;AAGA,SAAS,aAAa,IAAmC,QAAwB;AAC/E,QAAM,OAAO,GAAG,OAAO,MAAM;AAC7B,QAAM,MAAM,OAAO,CAAC;AACpB,SAAO,MAAM,OAAO,OAAO,OAAO,GAAG,EAAE,CAAC,CAAC,IAAI;AAC/C;AAMA,SAAS,sBAAsB,MAA4C;A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,IACb,8DACA,mBAAmB,YAAY;AAAA,EACrC;AAIA,QAAM,YAAY,eAAe;AAEjC,MAAI,CAAC,QAAQ;AACX,QAAI,YAAY,aAAa;AAC3B,UAAI,sGAAsG;AAAA,IAC5G;AACA;AAAA,EACF;AAEA,MAAI,CAAC,YAAY,aAAa;AAC5B,QAAI,uEAAuE;AAC3E;AAAA,EACF;AAEA,MAAI,qGAAgG;AACpG,QAAM,YAAY,MAAM,YAAY,YAAY,CAAC,MAAM,aAAa,cAAc;AAChF,QAAI,eAAe,IAAI,KAAK,YAAY,WAAW,CAAC,MAAM,YAAY,SAAS,CAAC,cAAS;AAAA,EAC3F,CAAC;AACD,MAAI,UAAU,WAAW,GAAG;AAC1B,QAAI,0CAA0C;AAC9C;AAAA,EACF;AACA,aAAW,KAAK,WAAW;AACzB,QAAI,KAAK,EAAE,IAAI,KAAK,YAAY,EAAE,WAAW,CAAC,WAAM,YAAY,EAAE,UAAU,CAAC,EAAE;AAAA,EACjF;AACA,QAAM,QAAQ,UAAU,OAAO,CAAC,KAAK,MAAM,MAAM,KAAK,IAAI,GAAG,EAAE,cAAc,EAAE,UAAU,GAAG,CAAC;AAC7F,MAAI,aAAa,YAAY,KAAK,CAAC,GAAG;AACxC;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/code-sdk",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.3",
4
4
  "description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -49,27 +49,29 @@
49
49
  "@aws-sdk/credential-providers": "^3.864.0",
50
50
  "ai": "^6.0.176",
51
51
  "execa": "^9.6.1",
52
+ "libsql": "^0.5.29",
52
53
  "posthog-node": "^5.37.0",
53
54
  "tokenx": "^1.3.0",
54
55
  "vscode-jsonrpc": "^8.2.1",
55
56
  "vscode-languageserver-protocol": "^3.17.5",
56
57
  "yaml": "^2.7.1",
57
58
  "zod": "^4.3.6",
58
- "@mastra/agent-browser": "0.4.1",
59
59
  "@mastra/duckdb": "1.5.1",
60
60
  "@mastra/fastembed": "1.2.0",
61
61
  "@mastra/github-signals": "0.2.2",
62
- "@mastra/core": "1.50.2-alpha.1",
62
+ "@mastra/core": "1.51.0-alpha.3",
63
+ "@mastra/agent-browser": "0.4.1",
64
+ "@mastra/libsql": "1.16.0-alpha.0",
65
+ "@mastra/memory": "1.23.0-alpha.2",
63
66
  "@mastra/mcp": "1.13.1",
64
- "@mastra/memory": "1.23.0-alpha.1",
65
67
  "@mastra/observability": "1.16.0",
66
68
  "@mastra/pg": "1.15.1",
67
- "@mastra/schema-compat": "1.3.4-alpha.0",
68
- "@mastra/libsql": "1.15.1",
69
+ "@mastra/schema-compat": "1.3.4-alpha.1",
69
70
  "@mastra/stagehand": "0.3.0",
70
71
  "@mastra/tavily": "1.1.0"
71
72
  },
72
73
  "devDependencies": {
74
+ "@libsql/client": "^0.17.4",
73
75
  "@types/node": "22.19.21",
74
76
  "eslint": "^10.4.1",
75
77
  "tsup": "^8.5.1",
@@ -77,8 +79,8 @@
77
79
  "typescript": "^6.0.3",
78
80
  "typescript-eslint": "^8.57.0",
79
81
  "vitest": "4.1.9",
80
- "@internal/lint": "0.0.113",
81
- "@internal/types-builder": "0.0.88"
82
+ "@internal/types-builder": "0.0.88",
83
+ "@internal/lint": "0.0.113"
82
84
  },
83
85
  "engines": {
84
86
  "node": ">=22.19.0"