@mastra/code-sdk 1.2.2-alpha.6 → 1.3.0-alpha.8

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,29 @@
1
1
  # @mastra/code-sdk
2
2
 
3
+ ## 1.3.0-alpha.8
4
+
5
+ ### Minor Changes
6
+
7
+ - Added opt-in discovery for MCP servers configured globally in Claude Code and Codex CLI. Enable the sources with `mcp.claudeCodeGlobal` or `mcp.codexGlobal` in Mastra Code settings. ([#21598](https://github.com/mastra-ai/mastra/pull/21598))
8
+
9
+ ### Patch Changes
10
+
11
+ - Fixed custom command discovery loading Markdown files from node_modules. ([#21680](https://github.com/mastra-ai/mastra/pull/21680))
12
+
13
+ - Updated dependencies [[`4e7a421`](https://github.com/mastra-ai/mastra/commit/4e7a421dce8a48742f785d1e93ad2f43a572b282), [`4077487`](https://github.com/mastra-ai/mastra/commit/407748777c9bc9d5795033f36220e97df5553355), [`242e324`](https://github.com/mastra-ai/mastra/commit/242e3241e73cbd5c9bb86a31ebb49ca0256488d4), [`217e967`](https://github.com/mastra-ai/mastra/commit/217e9672d8b3160eb729d8e9f0044949e88da239), [`d774e89`](https://github.com/mastra-ai/mastra/commit/d774e8930c781df8c9effe3763e6b501c099b6cc), [`9c27a53`](https://github.com/mastra-ai/mastra/commit/9c27a53cd9d3de4f3f025bc387d94ce371c33f95), [`dff25a1`](https://github.com/mastra-ai/mastra/commit/dff25a1103fa72ee082a9b6f805ebeb5ce400753), [`217e967`](https://github.com/mastra-ai/mastra/commit/217e9672d8b3160eb729d8e9f0044949e88da239), [`7f78585`](https://github.com/mastra-ai/mastra/commit/7f785857e401570e2ffb316911f126ed363aa537), [`f2a4afd`](https://github.com/mastra-ai/mastra/commit/f2a4afd7e37e809669001ed17724b341a5c1f45e), [`f2a4afd`](https://github.com/mastra-ai/mastra/commit/f2a4afd7e37e809669001ed17724b341a5c1f45e), [`d438148`](https://github.com/mastra-ai/mastra/commit/d438148e222c1e2fb3c652725ce75680962ebec4), [`ba05fe0`](https://github.com/mastra-ai/mastra/commit/ba05fe0738f70cb686777546e968237d09269142), [`d26a8d4`](https://github.com/mastra-ai/mastra/commit/d26a8d4281f28414715b333c85bedaf70d0b2890), [`677cdc6`](https://github.com/mastra-ai/mastra/commit/677cdc6af564dec29a13464d12b7ab2a4efc22e9), [`a318490`](https://github.com/mastra-ai/mastra/commit/a318490e17da32f338d50929c770d901a9b3dd72), [`763e0c6`](https://github.com/mastra-ai/mastra/commit/763e0c61e04d76ad9a9efd301aa57525ca0cbea9), [`23e0be2`](https://github.com/mastra-ai/mastra/commit/23e0be261381e49534b4ff3101c60ee64a946cbf), [`217e967`](https://github.com/mastra-ai/mastra/commit/217e9672d8b3160eb729d8e9f0044949e88da239), [`7fc8806`](https://github.com/mastra-ai/mastra/commit/7fc880627d3cbf995d31ea0e8b807bf15417e651), [`0e02eac`](https://github.com/mastra-ai/mastra/commit/0e02eacdb2e30e1697a41910b41163742a181dc1), [`4df174c`](https://github.com/mastra-ai/mastra/commit/4df174c32bddf093a82f273070b8380aef7c9e90), [`f7c25b5`](https://github.com/mastra-ai/mastra/commit/f7c25b5106ddfb48e591f98df7a51e0f2dd01dba), [`cd19e4c`](https://github.com/mastra-ai/mastra/commit/cd19e4c575e4129cd20e3d881acc75120bfcdde0), [`dc09cc1`](https://github.com/mastra-ai/mastra/commit/dc09cc1083d861cde192c1cd235324dc75b8c731), [`7f78585`](https://github.com/mastra-ai/mastra/commit/7f785857e401570e2ffb316911f126ed363aa537), [`36b4649`](https://github.com/mastra-ai/mastra/commit/36b4649045a3a380cbab8ceca866db4086223aff), [`377eb81`](https://github.com/mastra-ai/mastra/commit/377eb81ce43b964e3a6b541df172da74a8ff3716)]:
14
+ - @mastra/core@1.60.0-alpha.8
15
+ - @mastra/observability@1.17.1-alpha.2
16
+ - @mastra/memory@1.27.0-alpha.1
17
+ - @mastra/mcp@1.17.0-alpha.1
18
+ - @mastra/pg@1.20.1-alpha.1
19
+
20
+ ## 1.2.2-alpha.7
21
+
22
+ ### Patch Changes
23
+
24
+ - Updated dependencies [[`940bf5c`](https://github.com/mastra-ai/mastra/commit/940bf5ccf04f2c9ebd8a1390431733222a03b1cd)]:
25
+ - @mastra/core@1.60.0-alpha.7
26
+
3
27
  ## 1.2.2-alpha.6
4
28
 
5
29
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,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;AAS7C,OAAO,KAAK,EAAE,cAAc,EAAa,MAAM,yBAAyB,CAAC;AACzE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAmB,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE7E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGxD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD,OAAO,EACL,aAAa,EAId,MAAM,uBAAuB,CAAC;AAM/B,OAAO,EAA+D,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAc9G,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAGpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAAE,WA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ACX,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
@@ -317,7 +317,7 @@ async function createMastraCodeAgentController(config) {
317
317
  closeVector: vector instanceof LibSQLVector ? () => vector.close() : void 0
318
318
  });
319
319
  const memory = config?.memory === false ? void 0 : config?.memory ?? getDynamicMemory(storage, vector);
320
- const mcpManager = config?.disableMcp ? void 0 : createMcpManager(project.rootPath, configDir, config?.mcpServers);
320
+ const mcpManager = config?.disableMcp ? void 0 : createMcpManager(project.rootPath, configDir, config?.mcpServers, globalSettings.mcp);
321
321
  const hookManager = config?.disableHooks ? void 0 : new HookManager(project.rootPath, "session-init", configDir, homeDir, project.isWorktree ? {
322
322
  path: project.rootPath,
323
323
  branch: project.gitBranch,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"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 { defaultNotificationDeliveryDecision } from '@mastra/core/notifications';\nimport {\n AgentsMDInjector,\n isBadRequestError,\n PrefillErrorHandler,\n ProviderHistoryCompat,\n StreamErrorRetryProcessor,\n} from '@mastra/core/processors';\nimport type { InputProcessor, Processor } 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 type { MastraVector } from '@mastra/core/vector';\nimport { DuckDBStore } from '@mastra/duckdb';\n\nimport { GithubSignals } from '@mastra/github-signals';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport {\n Observability,\n MastraStorageExporter,\n MastraPlatformExporter,\n SensitiveDataFilter,\n} from '@mastra/observability';\nimport { PostgresStore } from '@mastra/pg';\n\nimport { hasCredentialStoreProvider } from './agents/credential-resolver.js';\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 {\n createGitRefInstructionReader,\n createGitRefReminderReader,\n getStaticallyLoadedInstructionPaths,\n} 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';\nimport type { PostToolObserver, ToolLike } 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 { hasExplicitOMConfiguration } from './onboarding/om-settings.js';\nimport type { ProviderAccess } from './onboarding/packs.js';\nimport { getAvailableModePacks, getAvailableOmPacks, selectPreferredOMPack } from './onboarding/packs.js';\nimport {\n loadSettings,\n MASTRA_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 { PluginSignalLane } from './plugins/signal-lane.js';\nimport type { PluginProcessorEntries } from './plugins/types.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';\nimport { setAuthStorage as setXAIAuthStorage } from './providers/xai.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 type { StorageResult } 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';\nimport { registerWorkflowBuilderPrimitives } from './workflows/register-primitives.js';\n\nconst CODE_AGENT_ID = 'code-agent';\n\n// Global retry policy for transient provider failures (e.g. dropped sockets and server errors).\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 a transient failure.\n// Delay uses exponential backoff: initialDelay * 2^retryCount, capped at maxDelay.\nconst MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES = 10;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS = 500;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS = 30000;\n\nconst TRANSIENT_CONNECTION_ERROR_CODES = new Set(['ECONNRESET', 'EPIPE']);\nconst TRANSIENT_CONNECTION_MESSAGE_PATTERN = /econnreset|socket hang up|write epipe|other side closed/i;\nconst TRANSIENT_SERVER_ERROR_STATUSES = new Set([500, 502, 503]);\nconst TRANSIENT_SERVER_ERROR_MESSAGE_PATTERN = /internal server|server error|api may be experiencing issues/i;\n\n/**\n * Matcher for transient connection failures. Cause-chain traversal is handled\n * by `StreamErrorRetryProcessor.isRetryableStreamError`, which calls each\n * matcher at every level of the cause chain.\n */\n/**\n * Read the session state fields the AgentsMDInjector callbacks need from the\n * controller request context (set by hosts like the factory review flow).\n */\nfunction getInjectorSessionState(\n requestContext: { get: (key: string) => unknown } | undefined,\n): { untrustedCheckout?: boolean; baseRef?: string; projectPath?: string } | undefined {\n const agentControllerContext = requestContext?.get('controller') as\n | AgentControllerRequestContext<{ untrustedCheckout?: boolean; baseRef?: string; projectPath?: string }>\n | undefined;\n return agentControllerContext?.getState();\n}\n\nfunction isTransientConnectionError(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' && TRANSIENT_CONNECTION_ERROR_CODES.has(code.toUpperCase())) return true;\n\n const message = error instanceof Error ? error.message : undefined;\n if (typeof message === 'string' && TRANSIENT_CONNECTION_MESSAGE_PATTERN.test(message)) return true;\n\n return false;\n}\n\nfunction isTransientServerError(error: unknown): boolean {\n if (!error) return false;\n\n const errorObj = typeof error === 'object' ? (error as { status?: unknown; statusCode?: unknown }) : undefined;\n if (\n (typeof errorObj?.status === 'number' && TRANSIENT_SERVER_ERROR_STATUSES.has(errorObj.status)) ||\n (typeof errorObj?.statusCode === 'number' && TRANSIENT_SERVER_ERROR_STATUSES.has(errorObj.statusCode))\n ) {\n return true;\n }\n\n const message = error instanceof Error ? error.message : undefined;\n return typeof message === 'string' && TRANSIENT_SERVER_ERROR_MESSAGE_PATTERN.test(message);\n}\n\nfunction getTransientRetryDelay(retryCount: number): number {\n return Math.min(\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS * Math.pow(2, retryCount),\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS,\n );\n}\n\nfunction emitTransientRetry(\n error: unknown,\n retryCount: number,\n delayMs: number,\n requestContext?: RequestContext,\n): void {\n const controllerContext = requestContext?.get('controller') as AgentControllerRequestContext | undefined;\n controllerContext?.emitEvent?.({\n type: 'error',\n error: error instanceof Error ? error : new Error(String(error)),\n retryable: true,\n retryDelay: delayMs,\n retryAttempt: retryCount + 1,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n });\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 (sync or async) function that receives requestContext. */\n extraTools?:\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n /** Observe completed tool calls without replacing or modifying the built-in tool implementation. */\n postToolObserver?: PostToolObserver;\n /**\n * Stateless input processor instances prepended before Mastra Code's mandatory processors.\n * Embedders may extend processing but cannot replace built-in safety and compatibility policy.\n */\n inputProcessors?: InputProcessor[];\n /** Tools removed from the dynamic tool set before exposure to the model */\n disabledTools?: string[];\n /**\n * Custom storage config instead of auto-detected default, or a pre-built\n * store instance. An instance is used as-is: no connection test and no\n * LibSQL fallback — if the injected store fails, that's a hard error.\n */\n storage?: StorageConfig | MastraCompositeStore;\n /** Backend for an injected custom storage instance. Inferred for LibSQLStore and PostgresStore. */\n storageBackend?: 'libsql' | 'pg';\n /** Pre-built vector store instance for recall search. Skips the default vector store creation. */\n vector?: MastraVector;\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 /** Disable the polling-based GitHub signal provider even when enabled in global settings. Default: false */\n disableGithubSignals?: boolean;\n /**\n * Skip seeding observational-memory knobs (observer/reflector models,\n * thresholds, caveman mode, attachment observation) from settings.json.\n * Server deployments that persist memory settings in their own database\n * (the factory's `memory-settings` domain) set this so the host machine's\n * TUI settings file never leaks into server sessions. Default: false.\n */\n disableSettingsOmSeed?: 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, vector)` 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 setXAIAuthStorage(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 */\n/**\n * `instanceof` checks against Mastra classes are unreliable here: published\n * packages pin exact `@mastra/core` versions, so a user's dependency graph can\n * contain multiple copies of core (and peer-keyed copies of `@mastra/libsql` /\n * `@mastra/pg`). A store built against one copy fails `instanceof` against\n * another — the injected instance then silently fell through to the\n * StorageConfig path and crashed on `config.url`. These structural checks work\n * across duplicated copies.\n */\nfunction isInjectedStorageInstance(storage: MastraCodeConfig['storage']): storage is MastraCompositeStore {\n if (!storage) return false;\n if (storage instanceof MastraCompositeStore) return true;\n // A StorageConfig is a plain data object with a string `backend`\n // discriminant; a store instance carries the MastraCompositeStore method\n // surface.\n const candidate = storage as Partial<MastraCompositeStore>;\n return typeof candidate.init === 'function' && typeof candidate.__registerMastra === 'function';\n}\n\n/** Cross-copy-safe class check: walks the prototype chain by constructor name. */\nfunction hasAncestorClassNamed(value: object, className: string): boolean {\n for (let proto = Object.getPrototypeOf(value); proto; proto = Object.getPrototypeOf(proto)) {\n if (proto.constructor?.name === className) return true;\n }\n return false;\n}\n\nfunction resolveInjectedStorageBackend(\n storage: MastraCompositeStore,\n configuredBackend?: 'libsql' | 'pg',\n): 'libsql' | 'pg' {\n if (configuredBackend) return configuredBackend;\n if (storage instanceof LibSQLStore || hasAncestorClassNamed(storage, 'LibSQLStore')) return 'libsql';\n if (storage instanceof PostgresStore || hasAncestorClassNamed(storage, 'PostgresStore')) return 'pg';\n throw new Error('storageBackend is required when injecting a custom storage instance.');\n}\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 // Same trick for the controller, which plugins reach through a lazy accessor.\n // Plugins load well before the controller is constructed, and a closure over\n // the `controller` binding itself would throw on early access rather than\n // reporting \"not ready yet\", so the accessor reads this holder instead.\n let pluginRuntimeController: AgentController<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(MASTRA_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 // Skipped in deployed multi-tenant mode: when a per-tenant credential store\n // provider is registered, provider keys are resolved per request and must\n // never leak into process-global env vars.\n if (!hasCredentialStoreProvider()) {\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[MASTRA_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 [MASTRA_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\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. An injected instance is used as-is — no connection test, no\n // LibSQL fallback: if the injected store fails, that's a hard error.\n const injectedStorage = isInjectedStorageInstance(config?.storage) ? config.storage : undefined;\n const storageConfig = injectedStorage\n ? undefined\n : ((config?.storage as StorageConfig | undefined) ??\n getStorageConfig(project.rootPath, globalSettings.storage, configDir));\n const storageResult: StorageResult = injectedStorage\n ? { storage: injectedStorage, backend: resolveInjectedStorageBackend(injectedStorage, config?.storageBackend) }\n : 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\n // storage). An injected instance is used as-is; with an injected storage\n // instance and no injected vector, recall search stays vector-less.\n const vector =\n config?.vector ?? (storageConfig ? await createVectorStore(storageConfig, storageResult.backend) : undefined);\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: storageConfig ? resolveLocalDbFiles(storageConfig, storageResult.backend) : [],\n closeVector: vector instanceof LibSQLVector ? () => vector.close() : undefined,\n });\n\n const memory = config?.memory === false ? undefined : (config?.memory ?? getDynamicMemory(storage, vector));\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(\n project.rootPath,\n 'session-init',\n configDir,\n homeDir,\n project.isWorktree\n ? { path: project.rootPath, branch: project.gitBranch, mainRepoPath: project.mainRepoPath }\n : undefined,\n );\n\n const pluginManager = config?.disablePlugins\n ? undefined\n : (config?.pluginManager ??\n new PluginManager({\n projectRoot: project.rootPath,\n configDir,\n homeDir,\n }));\n // Publish the runtime accessors to whichever manager is in play — including an\n // injected one, which would otherwise hand plugins `undefined` for\n // `getController`/`getActiveSession`. Lazy closures: both locals are assigned\n // after the controller is constructed below.\n pluginManager?.setRuntime({\n getController: () => pluginRuntimeController,\n getActiveSession: () => activeSession,\n });\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 // Shared by GithubSignals (immediate sends) and the code agent's\n // notification config (deferred sends re-dispatched by the core notification\n // dispatch workflow) — both need the target session's request context, or a\n // woken idle thread has no model to run with (\"No model selected\").\n const getNotificationStreamOptions = async ({ resourceId, threadId }: { resourceId: string; threadId: string }) => {\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 // No session owns the resource and none is active yet (e.g. a deferred\n // notification comes due before any session boots). Nothing to resolve a\n // model from; return undefined so the dispatcher sends a bare wake\n // instead of throwing mid-delivery.\n if (!session) return undefined;\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: session.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 const githubSignals: GithubSignals | undefined =\n globalSettings.signals?.experimentalGithubSignals && !config?.disableGithubSignals\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,\n })\n : undefined;\n // Mastra Code's own processors are constructed once, here, rather than inside\n // the resolver below: the resolver runs before every LLM call, and rebuilding\n // stateful processors per request would reset them.\n const mastraCodeInputProcessors: InputProcessor[] = [\n ...(config?.inputProcessors ?? []),\n new PlanRejectionAbortProcessor(),\n new AgentsMDInjector({\n // Untrusted checkouts (review sessions on PR branches) must not have\n // the working tree's instruction files injected as system reminders —\n // those files are attacker-writable content, not configuration. When\n // the session carries a trusted base ref, reminders are served from\n // that ref instead (see getReader); without one they are disabled.\n isEnabled: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n return state?.untrustedCheckout !== true || typeof state?.baseRef === 'string';\n },\n getReader: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n if (state?.untrustedCheckout !== true || typeof state?.baseRef !== 'string') return undefined;\n return createGitRefReminderReader(state?.projectPath ?? project.rootPath, state.baseRef);\n },\n getIgnoredInstructionPaths: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n const projectPath = state?.projectPath ?? project.rootPath;\n // On untrusted checkouts the static prompt loads from the base ref,\n // so compute the statically-loaded paths through the same reader to\n // keep the dedup consistent.\n const projectReader =\n state?.untrustedCheckout === true && typeof state?.baseRef === 'string'\n ? createGitRefInstructionReader(projectPath, state.baseRef)\n : undefined;\n return getStaticallyLoadedInstructionPaths(projectPath, undefined, projectReader);\n },\n }),\n new ProviderHistoryCompat(),\n ];\n\n // TaskSignalProvider bundles the task tools + TaskStateProcessor (see the\n // `signals` array below); named here so the plugin lane can reserve its id.\n const taskSignalProvider = new TaskSignalProvider();\n\n const NO_PLUGIN_PROCESSORS: PluginProcessorEntries = { input: [], output: [] };\n let pluginProcessorReadWarned = false;\n\n // Providers contributed by plugins are driven from here rather than through\n // the agent's `signals` array: the Agent constructor harvests a provider's\n // processors into a closure it can never undo, so a provider wired there\n // could not be removed when its plugin is disabled, updated or uninstalled.\n // The built-in providers are seeded as reserved ids because they are wired\n // through the constructor and are therefore invisible to the lane.\n const pluginSignalLane = pluginManager\n ? new PluginSignalLane({\n reservedProviderIds: [taskSignalProvider.id, ...(githubSignals ? [githubSignals.id] : [])],\n })\n : undefined;\n let unsubscribePluginReload: (() => void) | undefined;\n\n /**\n * Plugin processors are read through a function so that enabling, disabling or\n * updating a plugin takes effect on the next request rather than requiring a\n * new agent. This runs before every LLM call, and also outside the request\n * path when the Agent catalogues its configured processors — where a throw is\n * swallowed into a debug log. So it only reads already-resolved state: no\n * filesystem, no network, no construction, and it never throws.\n */\n const readPluginProcessors = (): PluginProcessorEntries => {\n try {\n return pluginManager?.getPluginProcessors() ?? NO_PLUGIN_PROCESSORS;\n } catch (error) {\n // Warn once: this is on the hot path, and a broken read repeats.\n if (!pluginProcessorReadWarned) {\n pluginProcessorReadWarned = true;\n console.warn('Failed to read plugin processors:', error);\n }\n return NO_PLUGIN_PROCESSORS;\n }\n };\n\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 // `settingsPath` matches the source `createMastraCode()` reads from so the\n // per-mode thinking defaults resolve against the same config file.\n model: ctx => getDynamicModel(ctx, config?.settingsPath),\n // Deferred notifications are re-dispatched by the core notification\n // dispatch workflow long after the originating send; the delivery policy\n // rebuilds the request context (model selection included) at delivery time\n // so waking an idle thread does not fail with \"No model selected\". The\n // default decision logic is kept as-is — the policy only attaches\n // streamOptions on top of it.\n notifications: {\n deliveryPolicy: {\n decide: async input => {\n const decision = defaultNotificationDeliveryDecision(input);\n // Without a resourceId there is no session to resolve options from —\n // don't fall through to the active session and wake it under an\n // empty resource binding.\n if (!input.record.resourceId) return decision;\n const streamOptions = await getNotificationStreamOptions({\n resourceId: input.record.resourceId,\n threadId: input.record.threadId,\n });\n return streamOptions ? { ...decision, streamOptions } : decision;\n },\n },\n },\n tools: createDynamicTools(mcpManager, config?.extraTools, config?.disabledTools, storage, pluginTools),\n hooks: createToolHooks(hookManager, config?.postToolObserver),\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: [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 ...mastraCodeInputProcessors,\n ...readPluginProcessors().input.map(entry => entry.value),\n ...(pluginSignalLane?.getInputProcessors() ?? []),\n ],\n // Mastra Code contributes no output processors of its own; the lane exists\n // so plugins can. Like the input lane, plugin processors sit last — after\n // the layers they customize, before the channel and memory layers the\n // Agent appends.\n outputProcessors: () => [\n ...readPluginProcessors().output.map(entry => entry.value),\n ...(pluginSignalLane?.getOutputProcessors() ?? []),\n ],\n errorProcessors: [\n // ProviderHistoryCompat must run before StreamErrorRetryProcessor: both react to\n // HTTP 400s, but ProviderHistoryCompat repairs the incompatible history (e.g.\n // sanitizing tool-call IDs) before retrying, while StreamErrorRetryProcessor's\n // isBadRequestError matcher retries the identical request. Error processors\n // short-circuit on the first `retry: true`, so a blind retry first would resend\n // the broken history and fail again.\n new ProviderHistoryCompat(),\n new StreamErrorRetryProcessor({\n matchers: [\n { match: isBadRequestError, maxRetries: 1, delayMs: 2000 },\n {\n match: isTransientConnectionError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),\n onRetry: ({ error, retryCount, delayMs, requestContext }) =>\n emitTransientRetry(error, retryCount, delayMs, requestContext),\n },\n {\n match: isTransientServerError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),\n onRetry: ({ error, retryCount, delayMs, requestContext }) =>\n emitTransientRetry(error, retryCount, delayMs, requestContext),\n },\n ],\n }),\n new PrefillErrorHandler(),\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 activeProviderId = effectiveDefaults.build?.split('/')[0];\n const preferredOmModel = hasExplicitOMConfiguration(globalSettings)\n ? undefined\n : selectPreferredOMPack(startupAccess, activeProviderId)?.modelId;\n const effectiveObserverModel = resolveOmRoleModel(globalSettings, 'observer', builtinOmPacks) || preferredOmModel;\n const effectiveReflectorModel = resolveOmRoleModel(globalSettings, 'reflector', builtinOmPacks) || preferredOmModel;\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. OM knobs are skipped when the\n // host persists memory settings elsewhere (`disableSettingsOmSeed`) so the\n // machine-local settings.json never leaks into server sessions.\n const globalInitialState: Partial<MastraCodeState> = {};\n if (!config?.disableSettingsOmSeed) {\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 }\n if (globalSettings.preferences.yolo !== null) {\n globalInitialState.yolo = globalSettings.preferences.yolo;\n }\n // Note: `thinkingLevel` is intentionally NOT seeded into session state. The\n // state slot is a session-level override; the effective level is resolved at\n // request time (per-mode defaults → global preference) in getDynamicModel so\n // settings changes apply to the next request of every session.\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 // Publish the controller to the plugin runtime accessors now that it exists.\n pluginRuntimeController = controller;\n\n if (pluginSignalLane && pluginManager) {\n // Register the plugins loaded at startup, and re-reconcile on every reload.\n // Providers are not started here: they need a Mastra instance for storage,\n // and Mastra does not exist until the composition layer boots the controller\n // (see `startPluginSignalProviders` on the returned object).\n pluginSignalLane.sync(pluginManager.getPluginSignalProviders());\n unsubscribePluginReload = pluginManager.onReload(() =>\n pluginSignalLane.sync(pluginManager.getPluginSignalProviders()),\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 // Surface the project root so boot/mount paths can wire workflow tools\n // against a workspace anchored at it without re-running detectProject().\n projectPath: project.rootPath,\n // Surface the Agent instance so registerWorkflowBuilderPrimitives can add\n // it as a plain agent on the Mastra registry. Workflows then compose it\n // as an agent step (agentId: 'code-agent') and delegate open-ended tool\n // orchestration to it — code-agent already has full workspace / MCP / web\n // access via its dynamic tool factory.\n codeAgent,\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 * Starts the signal providers contributed by plugins. Called by the\n * composition layer once the controller is inited, because that is when a\n * Mastra instance exists — a provider without one has no storage, and\n * nothing else will hand it one: the Agent propagates Mastra only to the\n * providers in its own `signals` array, which these deliberately are not in.\n */\n startPluginSignalProviders: () => {\n const mastra = controller.getMastra();\n if (!pluginSignalLane || !mastra) return;\n pluginSignalLane.setMastra(mastra, codeAgent);\n },\n /**\n * Stops every plugin-contributed signal provider and stops listening for\n * plugin reloads. The inverse of `startPluginSignalProviders`, for an\n * embedder that is done with this controller: a `pluginManager` shared\n * across controllers (`MastraCodeConfig.pluginManager`) outlives any one of\n * them, so without this its providers keep polling and its reload listener\n * keeps firing for a controller that is gone.\n */\n stopPluginSignalProviders: () => {\n unsubscribePluginReload?.();\n unsubscribePluginReload = undefined;\n pluginSignalLane?.stopAll();\n },\n /**\n * Hands Mastra to the statically configured input processors.\n *\n * The Agent does this itself, but only for processors configured as a\n * plain array (`Array.isArray` in `__registerMastra`). This lane is a\n * function so plugins can contribute to it, which takes those processors\n * out of that branch — including any an embedder passed as\n * `config.inputProcessors`, some of which need Mastra to work at all\n * (`CostGuardProcessor` reads observability storage there). Doing it here\n * keeps that unchanged.\n *\n * Plugin processors are deliberately not included: they come and go with\n * their plugin, and the registry keeps the first instance registered under\n * an id forever, which would leave a retired instance behind. Plugins\n * reach Mastra through `getController()` on the plugin context instead.\n */\n registerConfiguredProcessorsWithMastra: () => {\n const mastra = controller.getMastra();\n if (!mastra) return;\n for (const processor of mastraCodeInputProcessors) {\n mastra.addProcessor(processor as Processor);\n mastra.addProcessorConfiguration(processor as Processor, CODE_AGENT_ID, 'input');\n }\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, projectPath, codeAgent, mcpManager } = base;\n\n await controller.init();\n // Register workflow primitives (sub-agent + workspace tools + code-agent\n // + web + notification_inbox + snapshot of MCP tools) on the controller's\n // Mastra so the dynamic-workflow loading in startWorkers() can rehydrate\n // saved workflows against the right tool/agent registry.\n const mastra = controller.getMastra();\n if (mastra) await registerWorkflowBuilderPrimitives(mastra, { projectPath, codeAgent, mcpManager });\n await mastra?.startWorkers();\n base.registerConfiguredProcessorsWithMastra();\n base.startPluginSignalProviders();\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, projectPath, codeAgent, mcpManager } = base;\n const controllerId = config?.controllerId ?? controller.id;\n const apiRoutes = config?.buildApiRoutes?.({ controller, authStorage });\n const extraServerConfig = config?.buildServerConfig?.({ controller, authStorage });\n // Only register workflow primitives when we own the Mastra. If the caller\n // brought their own, they're responsible for what's registered on it.\n const weOwnTheMastra = !config?.mastra;\n\n const serverConfig = {\n ...extraServerConfig,\n ...(apiRoutes?.length ? { apiRoutes } : {}),\n };\n const mastraArgs = {\n agentControllers: { [controllerId]: controller },\n storage,\n // Mirror the controller's internal-Mastra construction (which passes\n // `config.pubsub` through): the server-owned Mastra must run its event\n // bus on the same transport so streams/workflows/signals stay\n // cross-process when a distributed PubSub (e.g. Redis Streams) is\n // configured.\n ...(base.signalsPubSub ? { pubsub: base.signalsPubSub } : {}),\n ...(Object.keys(serverConfig).length ? { server: serverConfig } : {}),\n };\n\n const finalize = async () => {\n await controller.init();\n if (weOwnTheMastra) {\n const mastra = controller.getMastra();\n if (mastra) await registerWorkflowBuilderPrimitives(mastra, { projectPath, codeAgent, mcpManager });\n }\n await controller.getMastra()?.startWorkers();\n // Anchored here rather than at a `new Mastra(...)` call site: finalize runs\n // in every mount path (caller-supplied Mastra, SDK-constructed Mastra, and\n // the platform entry that constructs its own), so plugin providers start\n // exactly once regardless of how Mastra Code was mounted.\n base.registerConfiguredProcessorsWithMastra();\n base.startPluginSignalProviders();\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoHA,MAAM,gBAAgB;AAMtB,MAAM,8CAA8C;AACpD,MAAM,yDAAyD;AAC/D,MAAM,qDAAqD;AAE3D,MAAM,mDAAmC,IAAI,IAAI,CAAC,cAAc,OAAO,CAAC;AACxE,MAAM,uCAAuC;AAC7C,MAAM,kDAAkC,IAAI,IAAI;CAAC;CAAK;CAAK;AAAG,CAAC;AAC/D,MAAM,yCAAyC;;;;;;;;;;AAW/C,SAAS,wBACP,gBACqF;CAIrF,QAH+B,gBAAgB,IAAI,YAAY,EAAA,EAGhC,SAAS;AAC1C;AAEA,SAAS,2BAA2B,OAAyB;CAC3D,IAAI,CAAC,OAAO,OAAO;CAEnB,MAAM,OAAO,OAAO,UAAU,YAAY,UAAU,QAAS,MAA6B,OAAO,KAAA;CACjG,IAAI,OAAO,SAAS,YAAY,iCAAiC,IAAI,KAAK,YAAY,CAAC,GAAG,OAAO;CAEjG,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,KAAA;CACzD,IAAI,OAAO,YAAY,YAAY,qCAAqC,KAAK,OAAO,GAAG,OAAO;CAE9F,OAAO;AACT;AAEA,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AAW,KAAK;EACtB,IAAI,gBAAgB;GAClB,MAAM,SAAS,WAAW,UAAU;GACpC,IAAI,QAAQ,MAAM,kCAAkC,QAAQ;IAAE;IAAa;IAAW;GAAW,CAAC;EACpG;EACA,MAAM,WAAW,UAAU,CAAC,EAAE,aAAa;EAK3C,KAAK,uCAAuC;EAC5C,KAAK,2BAA2B;CAClC;CAEA,OAAO;EAAE;EAAM;EAAY;CAAS;AACtC;;;;;;;AAQA,MAAa,mBAAmB"}
1
+ {"version":3,"file":"index.js","names":[],"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 { defaultNotificationDeliveryDecision } from '@mastra/core/notifications';\nimport {\n AgentsMDInjector,\n isBadRequestError,\n PrefillErrorHandler,\n ProviderHistoryCompat,\n StreamErrorRetryProcessor,\n} from '@mastra/core/processors';\nimport type { InputProcessor, Processor } 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 type { MastraVector } from '@mastra/core/vector';\nimport { DuckDBStore } from '@mastra/duckdb';\n\nimport { GithubSignals } from '@mastra/github-signals';\nimport { LibSQLStore, LibSQLVector } from '@mastra/libsql';\nimport {\n Observability,\n MastraStorageExporter,\n MastraPlatformExporter,\n SensitiveDataFilter,\n} from '@mastra/observability';\nimport { PostgresStore } from '@mastra/pg';\n\nimport { hasCredentialStoreProvider } from './agents/credential-resolver.js';\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 {\n createGitRefInstructionReader,\n createGitRefReminderReader,\n getStaticallyLoadedInstructionPaths,\n} 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';\nimport type { PostToolObserver, ToolLike } 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 { hasExplicitOMConfiguration } from './onboarding/om-settings.js';\nimport type { ProviderAccess } from './onboarding/packs.js';\nimport { getAvailableModePacks, getAvailableOmPacks, selectPreferredOMPack } from './onboarding/packs.js';\nimport {\n loadSettings,\n MASTRA_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 { PluginSignalLane } from './plugins/signal-lane.js';\nimport type { PluginProcessorEntries } from './plugins/types.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';\nimport { setAuthStorage as setXAIAuthStorage } from './providers/xai.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 type { StorageResult } 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';\nimport { registerWorkflowBuilderPrimitives } from './workflows/register-primitives.js';\n\nconst CODE_AGENT_ID = 'code-agent';\n\n// Global retry policy for transient provider failures (e.g. dropped sockets and server errors).\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 a transient failure.\n// Delay uses exponential backoff: initialDelay * 2^retryCount, capped at maxDelay.\nconst MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES = 10;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS = 500;\nconst MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS = 30000;\n\nconst TRANSIENT_CONNECTION_ERROR_CODES = new Set(['ECONNRESET', 'EPIPE']);\nconst TRANSIENT_CONNECTION_MESSAGE_PATTERN = /econnreset|socket hang up|write epipe|other side closed/i;\nconst TRANSIENT_SERVER_ERROR_STATUSES = new Set([500, 502, 503]);\nconst TRANSIENT_SERVER_ERROR_MESSAGE_PATTERN = /internal server|server error|api may be experiencing issues/i;\n\n/**\n * Matcher for transient connection failures. Cause-chain traversal is handled\n * by `StreamErrorRetryProcessor.isRetryableStreamError`, which calls each\n * matcher at every level of the cause chain.\n */\n/**\n * Read the session state fields the AgentsMDInjector callbacks need from the\n * controller request context (set by hosts like the factory review flow).\n */\nfunction getInjectorSessionState(\n requestContext: { get: (key: string) => unknown } | undefined,\n): { untrustedCheckout?: boolean; baseRef?: string; projectPath?: string } | undefined {\n const agentControllerContext = requestContext?.get('controller') as\n | AgentControllerRequestContext<{ untrustedCheckout?: boolean; baseRef?: string; projectPath?: string }>\n | undefined;\n return agentControllerContext?.getState();\n}\n\nfunction isTransientConnectionError(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' && TRANSIENT_CONNECTION_ERROR_CODES.has(code.toUpperCase())) return true;\n\n const message = error instanceof Error ? error.message : undefined;\n if (typeof message === 'string' && TRANSIENT_CONNECTION_MESSAGE_PATTERN.test(message)) return true;\n\n return false;\n}\n\nfunction isTransientServerError(error: unknown): boolean {\n if (!error) return false;\n\n const errorObj = typeof error === 'object' ? (error as { status?: unknown; statusCode?: unknown }) : undefined;\n if (\n (typeof errorObj?.status === 'number' && TRANSIENT_SERVER_ERROR_STATUSES.has(errorObj.status)) ||\n (typeof errorObj?.statusCode === 'number' && TRANSIENT_SERVER_ERROR_STATUSES.has(errorObj.statusCode))\n ) {\n return true;\n }\n\n const message = error instanceof Error ? error.message : undefined;\n return typeof message === 'string' && TRANSIENT_SERVER_ERROR_MESSAGE_PATTERN.test(message);\n}\n\nfunction getTransientRetryDelay(retryCount: number): number {\n return Math.min(\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_INITIAL_DELAY_MS * Math.pow(2, retryCount),\n MASTRACODE_TRANSIENT_CONNECTION_RETRY_MAX_DELAY_MS,\n );\n}\n\nfunction emitTransientRetry(\n error: unknown,\n retryCount: number,\n delayMs: number,\n requestContext?: RequestContext,\n): void {\n const controllerContext = requestContext?.get('controller') as AgentControllerRequestContext | undefined;\n controllerContext?.emitEvent?.({\n type: 'error',\n error: error instanceof Error ? error : new Error(String(error)),\n retryable: true,\n retryDelay: delayMs,\n retryAttempt: retryCount + 1,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n });\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 (sync or async) function that receives requestContext. */\n extraTools?:\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n /** Observe completed tool calls without replacing or modifying the built-in tool implementation. */\n postToolObserver?: PostToolObserver;\n /**\n * Stateless input processor instances prepended before Mastra Code's mandatory processors.\n * Embedders may extend processing but cannot replace built-in safety and compatibility policy.\n */\n inputProcessors?: InputProcessor[];\n /** Tools removed from the dynamic tool set before exposure to the model */\n disabledTools?: string[];\n /**\n * Custom storage config instead of auto-detected default, or a pre-built\n * store instance. An instance is used as-is: no connection test and no\n * LibSQL fallback — if the injected store fails, that's a hard error.\n */\n storage?: StorageConfig | MastraCompositeStore;\n /** Backend for an injected custom storage instance. Inferred for LibSQLStore and PostgresStore. */\n storageBackend?: 'libsql' | 'pg';\n /** Pre-built vector store instance for recall search. Skips the default vector store creation. */\n vector?: MastraVector;\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 /** Disable the polling-based GitHub signal provider even when enabled in global settings. Default: false */\n disableGithubSignals?: boolean;\n /**\n * Skip seeding observational-memory knobs (observer/reflector models,\n * thresholds, caveman mode, attachment observation) from settings.json.\n * Server deployments that persist memory settings in their own database\n * (the factory's `memory-settings` domain) set this so the host machine's\n * TUI settings file never leaks into server sessions. Default: false.\n */\n disableSettingsOmSeed?: 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, vector)` 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 setXAIAuthStorage(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 */\n/**\n * `instanceof` checks against Mastra classes are unreliable here: published\n * packages pin exact `@mastra/core` versions, so a user's dependency graph can\n * contain multiple copies of core (and peer-keyed copies of `@mastra/libsql` /\n * `@mastra/pg`). A store built against one copy fails `instanceof` against\n * another — the injected instance then silently fell through to the\n * StorageConfig path and crashed on `config.url`. These structural checks work\n * across duplicated copies.\n */\nfunction isInjectedStorageInstance(storage: MastraCodeConfig['storage']): storage is MastraCompositeStore {\n if (!storage) return false;\n if (storage instanceof MastraCompositeStore) return true;\n // A StorageConfig is a plain data object with a string `backend`\n // discriminant; a store instance carries the MastraCompositeStore method\n // surface.\n const candidate = storage as Partial<MastraCompositeStore>;\n return typeof candidate.init === 'function' && typeof candidate.__registerMastra === 'function';\n}\n\n/** Cross-copy-safe class check: walks the prototype chain by constructor name. */\nfunction hasAncestorClassNamed(value: object, className: string): boolean {\n for (let proto = Object.getPrototypeOf(value); proto; proto = Object.getPrototypeOf(proto)) {\n if (proto.constructor?.name === className) return true;\n }\n return false;\n}\n\nfunction resolveInjectedStorageBackend(\n storage: MastraCompositeStore,\n configuredBackend?: 'libsql' | 'pg',\n): 'libsql' | 'pg' {\n if (configuredBackend) return configuredBackend;\n if (storage instanceof LibSQLStore || hasAncestorClassNamed(storage, 'LibSQLStore')) return 'libsql';\n if (storage instanceof PostgresStore || hasAncestorClassNamed(storage, 'PostgresStore')) return 'pg';\n throw new Error('storageBackend is required when injecting a custom storage instance.');\n}\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 // Same trick for the controller, which plugins reach through a lazy accessor.\n // Plugins load well before the controller is constructed, and a closure over\n // the `controller` binding itself would throw on early access rather than\n // reporting \"not ready yet\", so the accessor reads this holder instead.\n let pluginRuntimeController: AgentController<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(MASTRA_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 // Skipped in deployed multi-tenant mode: when a per-tenant credential store\n // provider is registered, provider keys are resolved per request and must\n // never leak into process-global env vars.\n if (!hasCredentialStoreProvider()) {\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[MASTRA_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 [MASTRA_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\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. An injected instance is used as-is — no connection test, no\n // LibSQL fallback: if the injected store fails, that's a hard error.\n const injectedStorage = isInjectedStorageInstance(config?.storage) ? config.storage : undefined;\n const storageConfig = injectedStorage\n ? undefined\n : ((config?.storage as StorageConfig | undefined) ??\n getStorageConfig(project.rootPath, globalSettings.storage, configDir));\n const storageResult: StorageResult = injectedStorage\n ? { storage: injectedStorage, backend: resolveInjectedStorageBackend(injectedStorage, config?.storageBackend) }\n : 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\n // storage). An injected instance is used as-is; with an injected storage\n // instance and no injected vector, recall search stays vector-less.\n const vector =\n config?.vector ?? (storageConfig ? await createVectorStore(storageConfig, storageResult.backend) : undefined);\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: storageConfig ? resolveLocalDbFiles(storageConfig, storageResult.backend) : [],\n closeVector: vector instanceof LibSQLVector ? () => vector.close() : undefined,\n });\n\n const memory = config?.memory === false ? undefined : (config?.memory ?? getDynamicMemory(storage, vector));\n\n // MCP\n const mcpManager = config?.disableMcp\n ? undefined\n : createMcpManager(project.rootPath, configDir, config?.mcpServers, globalSettings.mcp);\n\n // Hooks\n const hookManager = config?.disableHooks\n ? undefined\n : new HookManager(\n project.rootPath,\n 'session-init',\n configDir,\n homeDir,\n project.isWorktree\n ? { path: project.rootPath, branch: project.gitBranch, mainRepoPath: project.mainRepoPath }\n : undefined,\n );\n\n const pluginManager = config?.disablePlugins\n ? undefined\n : (config?.pluginManager ??\n new PluginManager({\n projectRoot: project.rootPath,\n configDir,\n homeDir,\n }));\n // Publish the runtime accessors to whichever manager is in play — including an\n // injected one, which would otherwise hand plugins `undefined` for\n // `getController`/`getActiveSession`. Lazy closures: both locals are assigned\n // after the controller is constructed below.\n pluginManager?.setRuntime({\n getController: () => pluginRuntimeController,\n getActiveSession: () => activeSession,\n });\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 // Shared by GithubSignals (immediate sends) and the code agent's\n // notification config (deferred sends re-dispatched by the core notification\n // dispatch workflow) — both need the target session's request context, or a\n // woken idle thread has no model to run with (\"No model selected\").\n const getNotificationStreamOptions = async ({ resourceId, threadId }: { resourceId: string; threadId: string }) => {\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 // No session owns the resource and none is active yet (e.g. a deferred\n // notification comes due before any session boots). Nothing to resolve a\n // model from; return undefined so the dispatcher sends a bare wake\n // instead of throwing mid-delivery.\n if (!session) return undefined;\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: session.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 const githubSignals: GithubSignals | undefined =\n globalSettings.signals?.experimentalGithubSignals && !config?.disableGithubSignals\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,\n })\n : undefined;\n // Mastra Code's own processors are constructed once, here, rather than inside\n // the resolver below: the resolver runs before every LLM call, and rebuilding\n // stateful processors per request would reset them.\n const mastraCodeInputProcessors: InputProcessor[] = [\n ...(config?.inputProcessors ?? []),\n new PlanRejectionAbortProcessor(),\n new AgentsMDInjector({\n // Untrusted checkouts (review sessions on PR branches) must not have\n // the working tree's instruction files injected as system reminders —\n // those files are attacker-writable content, not configuration. When\n // the session carries a trusted base ref, reminders are served from\n // that ref instead (see getReader); without one they are disabled.\n isEnabled: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n return state?.untrustedCheckout !== true || typeof state?.baseRef === 'string';\n },\n getReader: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n if (state?.untrustedCheckout !== true || typeof state?.baseRef !== 'string') return undefined;\n return createGitRefReminderReader(state?.projectPath ?? project.rootPath, state.baseRef);\n },\n getIgnoredInstructionPaths: ({ requestContext }) => {\n const state = getInjectorSessionState(requestContext);\n const projectPath = state?.projectPath ?? project.rootPath;\n // On untrusted checkouts the static prompt loads from the base ref,\n // so compute the statically-loaded paths through the same reader to\n // keep the dedup consistent.\n const projectReader =\n state?.untrustedCheckout === true && typeof state?.baseRef === 'string'\n ? createGitRefInstructionReader(projectPath, state.baseRef)\n : undefined;\n return getStaticallyLoadedInstructionPaths(projectPath, undefined, projectReader);\n },\n }),\n new ProviderHistoryCompat(),\n ];\n\n // TaskSignalProvider bundles the task tools + TaskStateProcessor (see the\n // `signals` array below); named here so the plugin lane can reserve its id.\n const taskSignalProvider = new TaskSignalProvider();\n\n const NO_PLUGIN_PROCESSORS: PluginProcessorEntries = { input: [], output: [] };\n let pluginProcessorReadWarned = false;\n\n // Providers contributed by plugins are driven from here rather than through\n // the agent's `signals` array: the Agent constructor harvests a provider's\n // processors into a closure it can never undo, so a provider wired there\n // could not be removed when its plugin is disabled, updated or uninstalled.\n // The built-in providers are seeded as reserved ids because they are wired\n // through the constructor and are therefore invisible to the lane.\n const pluginSignalLane = pluginManager\n ? new PluginSignalLane({\n reservedProviderIds: [taskSignalProvider.id, ...(githubSignals ? [githubSignals.id] : [])],\n })\n : undefined;\n let unsubscribePluginReload: (() => void) | undefined;\n\n /**\n * Plugin processors are read through a function so that enabling, disabling or\n * updating a plugin takes effect on the next request rather than requiring a\n * new agent. This runs before every LLM call, and also outside the request\n * path when the Agent catalogues its configured processors — where a throw is\n * swallowed into a debug log. So it only reads already-resolved state: no\n * filesystem, no network, no construction, and it never throws.\n */\n const readPluginProcessors = (): PluginProcessorEntries => {\n try {\n return pluginManager?.getPluginProcessors() ?? NO_PLUGIN_PROCESSORS;\n } catch (error) {\n // Warn once: this is on the hot path, and a broken read repeats.\n if (!pluginProcessorReadWarned) {\n pluginProcessorReadWarned = true;\n console.warn('Failed to read plugin processors:', error);\n }\n return NO_PLUGIN_PROCESSORS;\n }\n };\n\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 // `settingsPath` matches the source `createMastraCode()` reads from so the\n // per-mode thinking defaults resolve against the same config file.\n model: ctx => getDynamicModel(ctx, config?.settingsPath),\n // Deferred notifications are re-dispatched by the core notification\n // dispatch workflow long after the originating send; the delivery policy\n // rebuilds the request context (model selection included) at delivery time\n // so waking an idle thread does not fail with \"No model selected\". The\n // default decision logic is kept as-is — the policy only attaches\n // streamOptions on top of it.\n notifications: {\n deliveryPolicy: {\n decide: async input => {\n const decision = defaultNotificationDeliveryDecision(input);\n // Without a resourceId there is no session to resolve options from —\n // don't fall through to the active session and wake it under an\n // empty resource binding.\n if (!input.record.resourceId) return decision;\n const streamOptions = await getNotificationStreamOptions({\n resourceId: input.record.resourceId,\n threadId: input.record.threadId,\n });\n return streamOptions ? { ...decision, streamOptions } : decision;\n },\n },\n },\n tools: createDynamicTools(mcpManager, config?.extraTools, config?.disabledTools, storage, pluginTools),\n hooks: createToolHooks(hookManager, config?.postToolObserver),\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: [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 ...mastraCodeInputProcessors,\n ...readPluginProcessors().input.map(entry => entry.value),\n ...(pluginSignalLane?.getInputProcessors() ?? []),\n ],\n // Mastra Code contributes no output processors of its own; the lane exists\n // so plugins can. Like the input lane, plugin processors sit last — after\n // the layers they customize, before the channel and memory layers the\n // Agent appends.\n outputProcessors: () => [\n ...readPluginProcessors().output.map(entry => entry.value),\n ...(pluginSignalLane?.getOutputProcessors() ?? []),\n ],\n errorProcessors: [\n // ProviderHistoryCompat must run before StreamErrorRetryProcessor: both react to\n // HTTP 400s, but ProviderHistoryCompat repairs the incompatible history (e.g.\n // sanitizing tool-call IDs) before retrying, while StreamErrorRetryProcessor's\n // isBadRequestError matcher retries the identical request. Error processors\n // short-circuit on the first `retry: true`, so a blind retry first would resend\n // the broken history and fail again.\n new ProviderHistoryCompat(),\n new StreamErrorRetryProcessor({\n matchers: [\n { match: isBadRequestError, maxRetries: 1, delayMs: 2000 },\n {\n match: isTransientConnectionError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),\n onRetry: ({ error, retryCount, delayMs, requestContext }) =>\n emitTransientRetry(error, retryCount, delayMs, requestContext),\n },\n {\n match: isTransientServerError,\n maxRetries: MASTRACODE_TRANSIENT_CONNECTION_MAX_RETRIES,\n delayMs: ({ retryCount }) => getTransientRetryDelay(retryCount),\n onRetry: ({ error, retryCount, delayMs, requestContext }) =>\n emitTransientRetry(error, retryCount, delayMs, requestContext),\n },\n ],\n }),\n new PrefillErrorHandler(),\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 activeProviderId = effectiveDefaults.build?.split('/')[0];\n const preferredOmModel = hasExplicitOMConfiguration(globalSettings)\n ? undefined\n : selectPreferredOMPack(startupAccess, activeProviderId)?.modelId;\n const effectiveObserverModel = resolveOmRoleModel(globalSettings, 'observer', builtinOmPacks) || preferredOmModel;\n const effectiveReflectorModel = resolveOmRoleModel(globalSettings, 'reflector', builtinOmPacks) || preferredOmModel;\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. OM knobs are skipped when the\n // host persists memory settings elsewhere (`disableSettingsOmSeed`) so the\n // machine-local settings.json never leaks into server sessions.\n const globalInitialState: Partial<MastraCodeState> = {};\n if (!config?.disableSettingsOmSeed) {\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 }\n if (globalSettings.preferences.yolo !== null) {\n globalInitialState.yolo = globalSettings.preferences.yolo;\n }\n // Note: `thinkingLevel` is intentionally NOT seeded into session state. The\n // state slot is a session-level override; the effective level is resolved at\n // request time (per-mode defaults → global preference) in getDynamicModel so\n // settings changes apply to the next request of every session.\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 // Publish the controller to the plugin runtime accessors now that it exists.\n pluginRuntimeController = controller;\n\n if (pluginSignalLane && pluginManager) {\n // Register the plugins loaded at startup, and re-reconcile on every reload.\n // Providers are not started here: they need a Mastra instance for storage,\n // and Mastra does not exist until the composition layer boots the controller\n // (see `startPluginSignalProviders` on the returned object).\n pluginSignalLane.sync(pluginManager.getPluginSignalProviders());\n unsubscribePluginReload = pluginManager.onReload(() =>\n pluginSignalLane.sync(pluginManager.getPluginSignalProviders()),\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 // Surface the project root so boot/mount paths can wire workflow tools\n // against a workspace anchored at it without re-running detectProject().\n projectPath: project.rootPath,\n // Surface the Agent instance so registerWorkflowBuilderPrimitives can add\n // it as a plain agent on the Mastra registry. Workflows then compose it\n // as an agent step (agentId: 'code-agent') and delegate open-ended tool\n // orchestration to it — code-agent already has full workspace / MCP / web\n // access via its dynamic tool factory.\n codeAgent,\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 * Starts the signal providers contributed by plugins. Called by the\n * composition layer once the controller is inited, because that is when a\n * Mastra instance exists — a provider without one has no storage, and\n * nothing else will hand it one: the Agent propagates Mastra only to the\n * providers in its own `signals` array, which these deliberately are not in.\n */\n startPluginSignalProviders: () => {\n const mastra = controller.getMastra();\n if (!pluginSignalLane || !mastra) return;\n pluginSignalLane.setMastra(mastra, codeAgent);\n },\n /**\n * Stops every plugin-contributed signal provider and stops listening for\n * plugin reloads. The inverse of `startPluginSignalProviders`, for an\n * embedder that is done with this controller: a `pluginManager` shared\n * across controllers (`MastraCodeConfig.pluginManager`) outlives any one of\n * them, so without this its providers keep polling and its reload listener\n * keeps firing for a controller that is gone.\n */\n stopPluginSignalProviders: () => {\n unsubscribePluginReload?.();\n unsubscribePluginReload = undefined;\n pluginSignalLane?.stopAll();\n },\n /**\n * Hands Mastra to the statically configured input processors.\n *\n * The Agent does this itself, but only for processors configured as a\n * plain array (`Array.isArray` in `__registerMastra`). This lane is a\n * function so plugins can contribute to it, which takes those processors\n * out of that branch — including any an embedder passed as\n * `config.inputProcessors`, some of which need Mastra to work at all\n * (`CostGuardProcessor` reads observability storage there). Doing it here\n * keeps that unchanged.\n *\n * Plugin processors are deliberately not included: they come and go with\n * their plugin, and the registry keeps the first instance registered under\n * an id forever, which would leave a retired instance behind. Plugins\n * reach Mastra through `getController()` on the plugin context instead.\n */\n registerConfiguredProcessorsWithMastra: () => {\n const mastra = controller.getMastra();\n if (!mastra) return;\n for (const processor of mastraCodeInputProcessors) {\n mastra.addProcessor(processor as Processor);\n mastra.addProcessorConfiguration(processor as Processor, CODE_AGENT_ID, 'input');\n }\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, projectPath, codeAgent, mcpManager } = base;\n\n await controller.init();\n // Register workflow primitives (sub-agent + workspace tools + code-agent\n // + web + notification_inbox + snapshot of MCP tools) on the controller's\n // Mastra so the dynamic-workflow loading in startWorkers() can rehydrate\n // saved workflows against the right tool/agent registry.\n const mastra = controller.getMastra();\n if (mastra) await registerWorkflowBuilderPrimitives(mastra, { projectPath, codeAgent, mcpManager });\n await mastra?.startWorkers();\n base.registerConfiguredProcessorsWithMastra();\n base.startPluginSignalProviders();\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, projectPath, codeAgent, mcpManager } = base;\n const controllerId = config?.controllerId ?? controller.id;\n const apiRoutes = config?.buildApiRoutes?.({ controller, authStorage });\n const extraServerConfig = config?.buildServerConfig?.({ controller, authStorage });\n // Only register workflow primitives when we own the Mastra. If the caller\n // brought their own, they're responsible for what's registered on it.\n const weOwnTheMastra = !config?.mastra;\n\n const serverConfig = {\n ...extraServerConfig,\n ...(apiRoutes?.length ? { apiRoutes } : {}),\n };\n const mastraArgs = {\n agentControllers: { [controllerId]: controller },\n storage,\n // Mirror the controller's internal-Mastra construction (which passes\n // `config.pubsub` through): the server-owned Mastra must run its event\n // bus on the same transport so streams/workflows/signals stay\n // cross-process when a distributed PubSub (e.g. Redis Streams) is\n // configured.\n ...(base.signalsPubSub ? { pubsub: base.signalsPubSub } : {}),\n ...(Object.keys(serverConfig).length ? { server: serverConfig } : {}),\n };\n\n const finalize = async () => {\n await controller.init();\n if (weOwnTheMastra) {\n const mastra = controller.getMastra();\n if (mastra) await registerWorkflowBuilderPrimitives(mastra, { projectPath, codeAgent, mcpManager });\n }\n await controller.getMastra()?.startWorkers();\n // Anchored here rather than at a `new Mastra(...)` call site: finalize runs\n // in every mount path (caller-supplied Mastra, SDK-constructed Mastra, and\n // the platform entry that constructs its own), so plugin providers start\n // exactly once regardless of how Mastra Code was mounted.\n base.registerConfiguredProcessorsWithMastra();\n base.startPluginSignalProviders();\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 RunM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filesystem.
3
- * Loads from:
4
- * 1. .claude/settings.local.json (Claude Code compatlowest priority)
5
- * 2. ~/.mastracode/mcp.json (global)
6
- * 3. .mcp.json (project root — Claude Code compatible)
7
- * 4. .mastracode/mcp.json (project highest priority)
3
+ * Loads from, lowest to highest priority:
4
+ * 1. ~/.claude.json (Claude Code globalopt-in)
5
+ * 2. $CODEX_HOME/config.toml (Codex CLI global — opt-in)
6
+ * 3. .claude/settings.local.json (Claude Code project compatibility)
7
+ * 4. ~/.mastracode/mcp.json (Mastra Code global)
8
+ * 5. .mcp.json (project root — Claude Code compatible)
9
+ * 6. .mastracode/mcp.json (Mastra Code project)
8
10
  *
9
11
  * Higher-priority configs override lower ones by server name. The project root
10
12
  * `.mcp.json` is read so a project that already keeps MCP servers there for
@@ -31,11 +33,17 @@ export declare const DEFAULT_OAUTH_REDIRECT_URL = "http://127.0.0.1:1458/oauth/c
31
33
  * resolve it through this helper rather than reading `redirectUrl` directly.
32
34
  */
33
35
  export declare function resolveOAuthRedirectUrl(oauth: McpHttpOAuthConfig | undefined): string;
34
- export declare function loadMcpConfig(projectDir: string, configDirName?: string): McpConfig;
36
+ export interface ExternalMcpDiscoveryOptions {
37
+ claudeCodeGlobal?: boolean;
38
+ codexGlobal?: boolean;
39
+ }
40
+ export declare function loadMcpConfig(projectDir: string, configDirName?: string, externalDiscovery?: ExternalMcpDiscoveryOptions): McpConfig;
35
41
  export declare function getProjectMcpPath(projectDir: string, configDirName?: string): string;
36
42
  export declare function getRootMcpPath(projectDir: string): string;
37
43
  export declare function getGlobalMcpPath(configDirName?: string): string;
38
44
  export declare function getClaudeSettingsPath(projectDir: string): string;
45
+ export declare function getClaudeGlobalMcpPath(): string;
46
+ export declare function getCodexGlobalMcpPath(): string;
39
47
  /**
40
48
  * Expand `${VAR}` and `${VAR:-default}` references in a string from the
41
49
  * environment, matching how Claude Code resolves values in `.mcp.json`.
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/m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