@mastra/code-sdk 1.16.0-alpha.8 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAE,sBAAsB,EAAiC,MAAM,uBAAuB,CAAC;AAI9F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AA2MpD,OAAO,EAAE,sBAAsB,EAAE,CAAC;AA8BlC;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,GAAG,OAAO,CAE/E;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,EAAE,KAAK,EAAE,eAAe,GAAG,SAAS,GAAG,OAAO,CAElH;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,oBAAoB,EAC7B,MAAM,CAAC,EAAE,YAAY,EACrB,YAAY,CAAC,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE;IAAE,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAAE,EAC7C,SAAS,CAAC,EAAE,SAAS,yBAsBsB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE;IA8J3E;;;OAGG;eACc,OAAO,CAAC,IAAI,CAAC;EAKjC"}
1
+ {"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../../src/agents/memory.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,MAAM,EAAgB,MAAM,gBAAgB,CAAC;AAEtD,OAAO,EAAE,sBAAsB,EAAiC,MAAM,uBAAuB,CAAC;AAI9F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AA2MpD,OAAO,EAAE,sBAAsB,EAAE,CAAC;AA8BlC;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,GAAG,OAAO,CAE/E;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,SAAS,EAAE,KAAK,EAAE,eAAe,GAAG,SAAS,GAAG,OAAO,CAElH;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,oBAAoB,EAC7B,MAAM,CAAC,EAAE,YAAY,EACrB,YAAY,CAAC,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE;IAAE,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAAE,EAC7C,SAAS,CAAC,EAAE,SAAS,yBAsBsB;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE;IAgK3E;;;OAGG;eACc,OAAO,CAAC,IAAI,CAAC;EAKjC"}
@@ -1,4 +1,4 @@
1
- import "../constants.js";
1
+ import { MIN_OBSERVATION_THRESHOLD } from "../constants.js";
2
2
  import { getOmScope } from "../utils/project.js";
3
3
  import { MASTRACODE_AUTO_OM_MODELS, resolveAutoOMModelId } from "../onboarding/packs.js";
4
4
  import { loadSettings } from "../onboarding/settings.js";
@@ -196,16 +196,17 @@ function getDynamicMemory(storage, vector, settingsPath, options, knowledge) {
196
196
  }
197
197
  const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;
198
198
  const omScope = isFactory ? "thread" : state?.omScope ?? getOmScope(state?.projectPath);
199
+ const isResourceScope = omScope === "resource";
199
200
  const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);
200
201
  const factorySettings = isFactoryMemorySettingsUnavailable(factorySettingsContext) || factorySettingsContext === void 0 && isFactory ? null : factorySettingsContext;
201
- const obsThreshold = factorySettings !== void 0 ? factorySettings?.observationThreshold ?? 3e4 : state?.observationThreshold ?? 3e4;
202
+ const storedObsThreshold = factorySettings !== void 0 ? factorySettings?.observationThreshold ?? 3e4 : state?.observationThreshold ?? 3e4;
203
+ const obsThreshold = isResourceScope ? storedObsThreshold : Math.max(storedObsThreshold, MIN_OBSERVATION_THRESHOLD);
202
204
  const refThreshold = factorySettings !== void 0 ? factorySettings?.reflectionThreshold ?? 4e4 : state?.reflectionThreshold ?? 4e4;
203
205
  const caveman = state?.cavemanObservations ?? false;
204
206
  const observerPreviousObservationTokens = 1e3;
205
207
  const observeAttachments = factorySettings !== void 0 ? factorySettings?.observeAttachments ?? "auto" : state?.observeAttachments;
206
208
  const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;
207
209
  if (cachedMemory && cachedMemoryKey === cacheKey) return cachedMemory;
208
- const isResourceScope = omScope === "resource";
209
210
  const observerInstruction = caveman ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\n\n${CAVEMAN_OM_INSTRUCTION}` : DYNAMIC_AGENTS_MD_INSTRUCTION;
210
211
  const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : void 0;
211
212
  if (cachedMemory) {
@@ -1 +1 @@
1
- {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Knowledge } from '@mastra/core/knowledge';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport type { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport { DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { MASTRACODE_AUTO_OM_MODELS, resolveAutoOMModelId } from '../onboarding/packs.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport { ANTHROPIC_PROMPT_CACHE_TTL } from '../providers/anthropic-prompt-cache.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { canUseProvider, getActiveMemoryRoute, resolveModel } from './model.js';\n\n/**\n * `fastembed.small`, loaded on the first embedding. Importing `@mastra/fastembed` up front loads ONNX\n * Runtime and a native tokenizer (~11 MB) into every session, including ones that never embed.\n */\nconst lazyFastembedSmall: typeof fastembed.small = {\n specificationVersion: 'v3',\n provider: 'fastembed',\n modelId: 'bge-small-en-v1.5',\n maxEmbeddingsPerCall: 256,\n supportsParallelCalls: true,\n async doEmbed(options) {\n const { fastembed } = await import('@mastra/fastembed');\n return fastembed.small.doEmbed(options);\n },\n};\n\n/** Route-backed OM fallback entry. */\ntype MemoryModelRouteEntry = { id: string; model: ReturnType<typeof resolveModel> };\n\n/**\n * Resolve the active model route's memory models, starting at a same-thread\n * pending fallback hop. Returns `'auto'` when the route's first memory model is\n * Auto, and `undefined` when the route sets no memory model.\n */\nfunction resolveRouteMemoryModels(\n state: MastraCodeState | undefined,\n threadId: string | null | undefined,\n resolve: (modelId: string) => ReturnType<typeof resolveModel>,\n): MemoryModelRouteEntry[] | 'auto' | undefined {\n const memoryRoute = getActiveMemoryRoute(state, threadId);\n if (memoryRoute[0]?.memoryModelId === 'auto') return 'auto';\n const seenModelIds = new Set<string>();\n const appearances = new Map<string, number>();\n const entries: MemoryModelRouteEntry[] = [];\n for (const entry of memoryRoute) {\n if (!entry.memoryModelId || entry.memoryModelId === 'auto' || seenModelIds.has(entry.memoryModelId)) continue;\n seenModelIds.add(entry.memoryModelId);\n const occurrence = (appearances.get(entry.id) ?? 0) + 1;\n appearances.set(entry.id, occurrence);\n try {\n entries.push({\n id: `${entry.id}:memory${occurrence === 1 ? '' : `#${occurrence}`}`,\n model: resolve(entry.memoryModelId),\n });\n } catch {\n break;\n }\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/**\n * The authoritative per-caller Factory memory-settings row, placed on the request\n * context before Factory's model-dependent processors run. `null` means the row\n * exists but is empty (every role auto). An unavailable sentinel or a missing\n * value on a Factory-owned session falls back to Auto roles and default\n * thresholds/attachments, so memory keeps working while Factory reports the error.\n */\ninterface FactoryMemorySettings {\n observerModelId: string | null;\n reflectorModelId: string | null;\n observationThreshold: number | null;\n reflectionThreshold: number | null;\n observeAttachments: 'auto' | boolean | null;\n}\n\ntype FactoryMemorySettingsContext =\n | FactoryMemorySettings\n | null\n | { status: 'unavailable'; reason: string }\n | undefined;\n\nfunction getFactoryMemorySettingsContext(requestContext: RequestContext): FactoryMemorySettingsContext {\n return requestContext.get('mastra__factoryMemorySettings') as FactoryMemorySettingsContext;\n}\n\nfunction isFactoryMemorySettingsUnavailable(\n settings: FactoryMemorySettingsContext,\n): settings is { status: 'unavailable'; reason: string } {\n return settings !== null && typeof settings === 'object' && 'status' in settings && settings.status === 'unavailable';\n}\n\nfunction getMainModelId(requestContext: RequestContext): string | undefined {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return controller?.session.modelId || (controller?.getState()?.currentModelId as string | undefined);\n}\n\n/**\n * Resolve one OM role's model for this invocation. Returns `'auto'` for Memory's\n * auto policy, or a concrete model. Factory's DB row is authoritative for\n * Factory sessions (an unreadable row falls back to auto). Otherwise the active\n * model route's memory models win, then the per-role selection, then legacy\n * concrete settings.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n): 'auto' | ReturnType<typeof resolveModel> | MemoryModelRouteEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const resolveOptions = { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' } as const;\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const isFactory = typeof state?.factoryProjectId === 'string';\n\n const useModel = (modelId: string) => {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, modelId);\n return resolveModel(modelId, resolveOptions);\n };\n const useAuto = () => {\n requestContext.set(`om.${role}.selectionMode`, 'auto');\n // These two keys are declared in the span-context allowlist\n // (`mastracode/sdk/src/index.ts`), so traces can report intent separately from\n // the effective concrete model without either being mistaken for a model ID.\n requestContext.set(\n `om.${role}.effectiveModelId`,\n resolveAutoOMModelId(getMainModelId(requestContext), providerId =>\n canUseProvider(providerId, { requestContext }),\n ),\n );\n return 'auto' as const;\n };\n\n if (\n isFactoryMemorySettingsUnavailable(factorySettingsContext) ||\n (factorySettingsContext === undefined && isFactory)\n ) {\n return useAuto();\n }\n if (factorySettingsContext !== undefined) {\n const factoryModelId = factorySettingsContext?.[`${role}ModelId`];\n return factoryModelId ? useModel(factoryModelId) : useAuto();\n }\n\n // The configured settings file, not the default one: a caller that points the\n // agent at another settings path must get the same override resolution for\n // observational memory as it does for the main model. Hosts that disable the\n // settings seed never read it.\n const settings = options?.disableSettingsOmSeed ? undefined : loadSettings(settingsPath);\n const routeMemory = resolveRouteMemoryModels(state, controller?.threadId, modelId =>\n resolveModel(modelId, resolveOptions),\n );\n if (routeMemory === 'auto') return useAuto();\n if (routeMemory) {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, routeMemory[0]?.model.modelId);\n return routeMemory.length === 1 ? routeMemory[0]!.model : routeMemory;\n }\n\n const selection: unknown = state?.[`${role}ModelSelection`];\n if (selection === 'auto') return useAuto();\n if (typeof selection === 'string' && selection) return useModel(selection);\n if (\n selection &&\n typeof selection === 'object' &&\n 'modelId' in selection &&\n typeof selection.modelId === 'string' &&\n selection.modelId\n ) {\n return useModel(selection.modelId);\n }\n\n const roleOverride =\n role === 'observer' ? settings?.models?.observerModelOverride : settings?.models?.reflectorModelOverride;\n if (roleOverride) return useModel(roleOverride);\n const legacyModelId = state?.[`${role}ModelId`];\n if (typeof legacyModelId === 'string' && legacyModelId) return useModel(legacyModelId);\n return useAuto();\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\nšŸ”“ 14:31 user asks why React component rerenders\n🟔 14:32 saw inline object prop create new ref each render, cause rerender\nāœ… 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟔 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\nexport { LOCAL_KNOWLEDGE_ORG_ID };\n\n// One error per session, not per memory resolution. Keyed on the session id\n// rather than the controller object: the controller is read off the request\n// context on every resolution, so it is a fresh object per request and would\n// dedupe nothing. Bounded so a long-running Factory process cannot grow this\n// without limit — refusing sessions are rare, and losing the oldest ids only\n// costs one extra log line.\nconst REPORTED_ORG_UNRESOLVED_LIMIT = 500;\nconst reportedOrgUnresolved = new Set<string>();\n\nfunction reportOrgUnresolved(\n controller: AgentControllerRequestContext<MastraCodeState> | undefined,\n factoryProjectId: string | undefined,\n reason?: string,\n) {\n const sessionId = controller?.session?.id;\n if (sessionId) {\n if (reportedOrgUnresolved.has(sessionId)) return;\n if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) {\n reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value as string);\n }\n reportedOrgUnresolved.add(sessionId);\n }\n const session = controller?.session;\n console.error(\n `[Subconscious] Knowledge curation disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'})${reason ? `: ${reason}` : ''}. Knowledge is not written rather than written where it cannot be read.`,\n );\n}\n\n/**\n * Whether the experimental subconscious (knowledge graph + reminder sidekick)\n * is switched on for this process: it needs a vector store and the opt-in flag.\n */\nexport function isSubconsciousEnabled(vector: MastraVector | undefined): boolean {\n return Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n}\n\n/**\n * Whether the subconscious tools (`knowledge_*`, `ask_memory`) are registered\n * for a given session. Beyond the process-level switch, a Factory-owned\n * session that cannot resolve its org refuses the subconscious entirely (see\n * `getDynamicMemory`, which applies the same two checks inline because it also\n * needs the resolved identity). The system prompt's tool guidance calls here so\n * it never advertises tools that `getDynamicMemory` did not register.\n */\nexport function hasSubconsciousTools(vector: MastraVector | undefined, state: MastraCodeState | undefined): boolean {\n return isSubconsciousEnabled(vector) && resolveKnowledgeScopeIdentity(state).resolved;\n}\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(\n storage: MastraCompositeStore,\n vector?: MastraVector,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n knowledge?: Knowledge,\n) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n // Instances replaced by a config change may still have background work in flight.\n const retiredMemories = new Set<Memory>();\n\n // Observer/reflector model functions — read the current model ID from\n // controller state via requestContext (propagated by OM's agent.generate).\n // Bound here so the configured settings path reaches role overrides and pack\n // memory-model resolution.\n const getObserverModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('observer', requestContext, settingsPath, options);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath, options);\n // Routes the concrete model Memory's `'auto'` picks through Mastra Code's\n // credential-aware resolver, like every other Mastra Code model.\n const resolveMemoryModel = (modelId: string, { requestContext }: { requestContext?: RequestContext }) =>\n resolveModel(modelId, { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' });\n\n const resolveMemory = ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const subconsciousEnabled = isSubconsciousEnabled(vector);\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n // A Factory-owned session that could not resolve its org refuses to curate:\n // writing under a substituted identity produces knowledge the fail-closed\n // read path can never see.\n let orgUnresolvedRefusal = false;\n\n if (subconsciousEnabled) {\n const identity = resolveKnowledgeScopeIdentity(state);\n if (identity.resolved) {\n requestContext.set('organizationId', identity.organizationId);\n } else {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, identity.knowledgeResourceId, identity.reason);\n }\n if (identity.knowledgeResourceId) {\n requestContext.set('knowledgeResourceId', identity.knowledgeResourceId);\n }\n }\n\n const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;\n\n // Factory sessions share a memory resource across a Factory's runs and a\n // user's sessions, so their scope is fixed to thread: one shared record would\n // hand every run the others' work and invalidate their prompt caches. Recall\n // search still reaches the whole resource. Neither session state, the env\n // var, nor a repository's database.json can switch it.\n const omScope = isFactory ? 'thread' : (state?.omScope ?? getOmScope(state?.projectPath));\n\n // The Factory row is authoritative and read per invocation, so a stored\n // threshold/attachment change reaches the running Memory without a session.\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const factorySettingsUnavailable =\n isFactoryMemorySettingsUnavailable(factorySettingsContext) || (factorySettingsContext === undefined && isFactory);\n const factorySettings = factorySettingsUnavailable ? null : factorySettingsContext;\n const obsThreshold =\n factorySettings !== undefined\n ? (factorySettings?.observationThreshold ?? DEFAULT_OBS_THRESHOLD)\n : (state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD);\n const refThreshold =\n factorySettings !== undefined\n ? (factorySettings?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD)\n : (state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD);\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n // The row is authoritative: an absent value means the user left it on Auto,\n // which the config API reports as 'auto' and Memory resolves by model\n // capability.\n const observeAttachments =\n factorySettings !== undefined ? (factorySettings?.observeAttachments ?? 'auto') : state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries Factory presence and settings availability to keep those configs\n // from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n // Async buffering is not supported with resource scope — disable it\n const isResourceScope = omScope === 'resource';\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n if (cachedMemory) {\n const retired = cachedMemory;\n retiredMemories.add(retired);\n // settled() rejects if the instance's OM engine failed to start; that must not surface as\n // an unhandled rejection from a background retirement.\n void retired\n .settled()\n .catch(() => {})\n .finally(() => retiredMemories.delete(retired));\n }\n\n cachedMemory = new Memory({\n storage,\n ...(knowledge ? { knowledge } : {}),\n vector: vector || false,\n embedder: vector ? lazyFastembedSmall : undefined,\n options: {\n // Generate a durable title from the first user message. Every client uses\n // the same title in its thread list and active-session chrome. Title\n // generation takes the primary OM model only — its model field does not\n // accept fallback arrays.\n generateTitle:\n process.env.MASTRACODE_DISABLE_TITLE_GENERATION === '1'\n ? false\n : {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n if (resolved === 'auto') {\n return resolveMemoryModel(\n resolveAutoOMModelId(getMainModelId(requestContext), providerId =>\n canUseProvider(providerId, { requestContext }),\n ),\n { requestContext },\n );\n }\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory:\n process.env.MASTRACODE_DISABLE_OBSERVATIONAL_MEMORY === '1'\n ? false\n : {\n enabled: true,\n autoModels: MASTRACODE_AUTO_OM_MODELS,\n canUseProvider,\n resolveModel: resolveMemoryModel,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: 'resource',\n pins: true,\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n // The main agent writes Anthropic cache entries with this TTL; 'auto' can't see it.\n activateAfterIdle: { default: 'auto', anthropic: ANTHROPIC_PROMPT_CACHE_TTL },\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n\n return Object.assign(resolveMemory, {\n /**\n * Wait for background memory work (buffered observations, reflections, indexing) in every\n * instance this factory created. Await before closing storage.\n */\n async settled(): Promise<void> {\n // Drain every instance even if one rejects, so teardown can still close storage.\n await Promise.allSettled([cachedMemory?.settled(), ...[...retiredMemories].map(memory => memory.settled())]);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,MAAM,qBAA6C;CACjD,sBAAsB;CACtB,UAAU;CACV,SAAS;CACT,sBAAsB;CACtB,uBAAuB;CACvB,MAAM,QAAQ,SAAS;EACrB,MAAM,EAAE,cAAc,MAAM,OAAO;EACnC,OAAO,UAAU,MAAM,QAAQ,OAAO;CACxC;AACF;;;;;;AAUA,SAAS,yBACP,OACA,UACA,SAC8C;CAC9C,MAAM,cAAc,qBAAqB,OAAO,QAAQ;CACxD,IAAI,YAAY,EAAE,EAAE,kBAAkB,QAAQ,OAAO;CACrD,MAAM,+BAAe,IAAI,IAAY;CACrC,MAAM,8BAAc,IAAI,IAAoB;CAC5C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AC,CAAC,KAAI,WAAU,OAAO,QAAQ,CAAC,CAAC,CAAC;CAC7G,EACF,CAAC;AACH"}
1
+ {"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Knowledge } from '@mastra/core/knowledge';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport type { fastembed } from '@mastra/fastembed';\nimport { Memory, Subconscious } from '@mastra/memory';\nimport { DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD, MIN_OBSERVATION_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID, resolveKnowledgeScopeIdentity } from '../knowledge-scope.js';\nimport { MASTRACODE_AUTO_OM_MODELS, resolveAutoOMModelId } from '../onboarding/packs.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport { ANTHROPIC_PROMPT_CACHE_TTL } from '../providers/anthropic-prompt-cache.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { canUseProvider, getActiveMemoryRoute, resolveModel } from './model.js';\n\n/**\n * `fastembed.small`, loaded on the first embedding. Importing `@mastra/fastembed` up front loads ONNX\n * Runtime and a native tokenizer (~11 MB) into every session, including ones that never embed.\n */\nconst lazyFastembedSmall: typeof fastembed.small = {\n specificationVersion: 'v3',\n provider: 'fastembed',\n modelId: 'bge-small-en-v1.5',\n maxEmbeddingsPerCall: 256,\n supportsParallelCalls: true,\n async doEmbed(options) {\n const { fastembed } = await import('@mastra/fastembed');\n return fastembed.small.doEmbed(options);\n },\n};\n\n/** Route-backed OM fallback entry. */\ntype MemoryModelRouteEntry = { id: string; model: ReturnType<typeof resolveModel> };\n\n/**\n * Resolve the active model route's memory models, starting at a same-thread\n * pending fallback hop. Returns `'auto'` when the route's first memory model is\n * Auto, and `undefined` when the route sets no memory model.\n */\nfunction resolveRouteMemoryModels(\n state: MastraCodeState | undefined,\n threadId: string | null | undefined,\n resolve: (modelId: string) => ReturnType<typeof resolveModel>,\n): MemoryModelRouteEntry[] | 'auto' | undefined {\n const memoryRoute = getActiveMemoryRoute(state, threadId);\n if (memoryRoute[0]?.memoryModelId === 'auto') return 'auto';\n const seenModelIds = new Set<string>();\n const appearances = new Map<string, number>();\n const entries: MemoryModelRouteEntry[] = [];\n for (const entry of memoryRoute) {\n if (!entry.memoryModelId || entry.memoryModelId === 'auto' || seenModelIds.has(entry.memoryModelId)) continue;\n seenModelIds.add(entry.memoryModelId);\n const occurrence = (appearances.get(entry.id) ?? 0) + 1;\n appearances.set(entry.id, occurrence);\n try {\n entries.push({\n id: `${entry.id}:memory${occurrence === 1 ? '' : `#${occurrence}`}`,\n model: resolve(entry.memoryModelId),\n });\n } catch {\n break;\n }\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/**\n * The authoritative per-caller Factory memory-settings row, placed on the request\n * context before Factory's model-dependent processors run. `null` means the row\n * exists but is empty (every role auto). An unavailable sentinel or a missing\n * value on a Factory-owned session falls back to Auto roles and default\n * thresholds/attachments, so memory keeps working while Factory reports the error.\n */\ninterface FactoryMemorySettings {\n observerModelId: string | null;\n reflectorModelId: string | null;\n observationThreshold: number | null;\n reflectionThreshold: number | null;\n observeAttachments: 'auto' | boolean | null;\n}\n\ntype FactoryMemorySettingsContext =\n | FactoryMemorySettings\n | null\n | { status: 'unavailable'; reason: string }\n | undefined;\n\nfunction getFactoryMemorySettingsContext(requestContext: RequestContext): FactoryMemorySettingsContext {\n return requestContext.get('mastra__factoryMemorySettings') as FactoryMemorySettingsContext;\n}\n\nfunction isFactoryMemorySettingsUnavailable(\n settings: FactoryMemorySettingsContext,\n): settings is { status: 'unavailable'; reason: string } {\n return settings !== null && typeof settings === 'object' && 'status' in settings && settings.status === 'unavailable';\n}\n\nfunction getMainModelId(requestContext: RequestContext): string | undefined {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return controller?.session.modelId || (controller?.getState()?.currentModelId as string | undefined);\n}\n\n/**\n * Resolve one OM role's model for this invocation. Returns `'auto'` for Memory's\n * auto policy, or a concrete model. Factory's DB row is authoritative for\n * Factory sessions (an unreadable row falls back to auto). Otherwise the active\n * model route's memory models win, then the per-role selection, then legacy\n * concrete settings.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n): 'auto' | ReturnType<typeof resolveModel> | MemoryModelRouteEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const resolveOptions = { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' } as const;\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const isFactory = typeof state?.factoryProjectId === 'string';\n\n const useModel = (modelId: string) => {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, modelId);\n return resolveModel(modelId, resolveOptions);\n };\n const useAuto = () => {\n requestContext.set(`om.${role}.selectionMode`, 'auto');\n // These two keys are declared in the span-context allowlist\n // (`mastracode/sdk/src/index.ts`), so traces can report intent separately from\n // the effective concrete model without either being mistaken for a model ID.\n requestContext.set(\n `om.${role}.effectiveModelId`,\n resolveAutoOMModelId(getMainModelId(requestContext), providerId =>\n canUseProvider(providerId, { requestContext }),\n ),\n );\n return 'auto' as const;\n };\n\n if (\n isFactoryMemorySettingsUnavailable(factorySettingsContext) ||\n (factorySettingsContext === undefined && isFactory)\n ) {\n return useAuto();\n }\n if (factorySettingsContext !== undefined) {\n const factoryModelId = factorySettingsContext?.[`${role}ModelId`];\n return factoryModelId ? useModel(factoryModelId) : useAuto();\n }\n\n // The configured settings file, not the default one: a caller that points the\n // agent at another settings path must get the same override resolution for\n // observational memory as it does for the main model. Hosts that disable the\n // settings seed never read it.\n const settings = options?.disableSettingsOmSeed ? undefined : loadSettings(settingsPath);\n const routeMemory = resolveRouteMemoryModels(state, controller?.threadId, modelId =>\n resolveModel(modelId, resolveOptions),\n );\n if (routeMemory === 'auto') return useAuto();\n if (routeMemory) {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, routeMemory[0]?.model.modelId);\n return routeMemory.length === 1 ? routeMemory[0]!.model : routeMemory;\n }\n\n const selection: unknown = state?.[`${role}ModelSelection`];\n if (selection === 'auto') return useAuto();\n if (typeof selection === 'string' && selection) return useModel(selection);\n if (\n selection &&\n typeof selection === 'object' &&\n 'modelId' in selection &&\n typeof selection.modelId === 'string' &&\n selection.modelId\n ) {\n return useModel(selection.modelId);\n }\n\n const roleOverride =\n role === 'observer' ? settings?.models?.observerModelOverride : settings?.models?.reflectorModelOverride;\n if (roleOverride) return useModel(roleOverride);\n const legacyModelId = state?.[`${role}ModelId`];\n if (typeof legacyModelId === 'string' && legacyModelId) return useModel(legacyModelId);\n return useAuto();\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\nšŸ”“ 14:31 user asks why React component rerenders\n🟔 14:32 saw inline object prop create new ref each render, cause rerender\nāœ… 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟔 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\nexport { LOCAL_KNOWLEDGE_ORG_ID };\n\n// One error per session, not per memory resolution. Keyed on the session id\n// rather than the controller object: the controller is read off the request\n// context on every resolution, so it is a fresh object per request and would\n// dedupe nothing. Bounded so a long-running Factory process cannot grow this\n// without limit — refusing sessions are rare, and losing the oldest ids only\n// costs one extra log line.\nconst REPORTED_ORG_UNRESOLVED_LIMIT = 500;\nconst reportedOrgUnresolved = new Set<string>();\n\nfunction reportOrgUnresolved(\n controller: AgentControllerRequestContext<MastraCodeState> | undefined,\n factoryProjectId: string | undefined,\n reason?: string,\n) {\n const sessionId = controller?.session?.id;\n if (sessionId) {\n if (reportedOrgUnresolved.has(sessionId)) return;\n if (reportedOrgUnresolved.size >= REPORTED_ORG_UNRESOLVED_LIMIT) {\n reportedOrgUnresolved.delete(reportedOrgUnresolved.values().next().value as string);\n }\n reportedOrgUnresolved.add(sessionId);\n }\n const session = controller?.session;\n console.error(\n `[Subconscious] Knowledge curation disabled: no organization resolved for session ${session?.id ?? 'unknown'} (project ${factoryProjectId ?? 'none'})${reason ? `: ${reason}` : ''}. Knowledge is not written rather than written where it cannot be read.`,\n );\n}\n\n/**\n * Whether the experimental subconscious (knowledge graph + reminder sidekick)\n * is switched on for this process: it needs a vector store and the opt-in flag.\n */\nexport function isSubconsciousEnabled(vector: MastraVector | undefined): boolean {\n return Boolean(vector) && process.env.MASTRACODE_EXPERIMENTAL_SUBCONSCIOUS === '1';\n}\n\n/**\n * Whether the subconscious tools (`knowledge_*`, `ask_memory`) are registered\n * for a given session. Beyond the process-level switch, a Factory-owned\n * session that cannot resolve its org refuses the subconscious entirely (see\n * `getDynamicMemory`, which applies the same two checks inline because it also\n * needs the resolved identity). The system prompt's tool guidance calls here so\n * it never advertises tools that `getDynamicMemory` did not register.\n */\nexport function hasSubconsciousTools(vector: MastraVector | undefined, state: MastraCodeState | undefined): boolean {\n return isSubconsciousEnabled(vector) && resolveKnowledgeScopeIdentity(state).resolved;\n}\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(\n storage: MastraCompositeStore,\n vector?: MastraVector,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n knowledge?: Knowledge,\n) {\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n // Instances replaced by a config change may still have background work in flight.\n const retiredMemories = new Set<Memory>();\n\n // Observer/reflector model functions — read the current model ID from\n // controller state via requestContext (propagated by OM's agent.generate).\n // Bound here so the configured settings path reaches role overrides and pack\n // memory-model resolution.\n const getObserverModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('observer', requestContext, settingsPath, options);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath, options);\n // Routes the concrete model Memory's `'auto'` picks through Mastra Code's\n // credential-aware resolver, like every other Mastra Code model.\n const resolveMemoryModel = (modelId: string, { requestContext }: { requestContext?: RequestContext }) =>\n resolveModel(modelId, { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' });\n\n const resolveMemory = ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const subconsciousEnabled = isSubconsciousEnabled(vector);\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n // A Factory-owned session that could not resolve its org refuses to curate:\n // writing under a substituted identity produces knowledge the fail-closed\n // read path can never see.\n let orgUnresolvedRefusal = false;\n\n if (subconsciousEnabled) {\n const identity = resolveKnowledgeScopeIdentity(state);\n if (identity.resolved) {\n requestContext.set('organizationId', identity.organizationId);\n } else {\n orgUnresolvedRefusal = true;\n reportOrgUnresolved(controller, identity.knowledgeResourceId, identity.reason);\n }\n if (identity.knowledgeResourceId) {\n requestContext.set('knowledgeResourceId', identity.knowledgeResourceId);\n }\n }\n\n const subconsciousAvailable = subconsciousEnabled && !orgUnresolvedRefusal;\n\n // Factory sessions share a memory resource across a Factory's runs and a\n // user's sessions, so their scope is fixed to thread: one shared record would\n // hand every run the others' work and invalidate their prompt caches. Recall\n // search still reaches the whole resource. Neither session state, the env\n // var, nor a repository's database.json can switch it.\n const omScope = isFactory ? 'thread' : (state?.omScope ?? getOmScope(state?.projectPath));\n const isResourceScope = omScope === 'resource';\n\n // The Factory row is authoritative and read per invocation, so a stored\n // threshold/attachment change reaches the running Memory without a session.\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const factorySettingsUnavailable =\n isFactoryMemorySettingsUnavailable(factorySettingsContext) || (factorySettingsContext === undefined && isFactory);\n const factorySettings = factorySettingsUnavailable ? null : factorySettingsContext;\n // Rows saved before validation can still hold a thread-scope threshold that\n // @mastra/memory refuses because it does not exceed the activation buffer.\n // Resource scope has no activation buffer and keeps its saved value.\n const storedObsThreshold =\n factorySettings !== undefined\n ? (factorySettings?.observationThreshold ?? DEFAULT_OBS_THRESHOLD)\n : (state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD);\n const obsThreshold = isResourceScope ? storedObsThreshold : Math.max(storedObsThreshold, MIN_OBSERVATION_THRESHOLD);\n const refThreshold =\n factorySettings !== undefined\n ? (factorySettings?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD)\n : (state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD);\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n // The row is authoritative: an absent value means the user left it on Auto,\n // which the config API reports as 'auto' and Memory resolves by model\n // capability.\n const observeAttachments =\n factorySettings !== undefined ? (factorySettings?.observeAttachments ?? 'auto') : state?.observeAttachments;\n // Factory sessions get a factory-only Subconscious config, so the cache key\n // carries Factory presence and settings availability to keep those configs\n // from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}:${subconsciousAvailable ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n if (cachedMemory) {\n const retired = cachedMemory;\n retiredMemories.add(retired);\n // settled() rejects if the instance's OM engine failed to start; that must not surface as\n // an unhandled rejection from a background retirement.\n void retired\n .settled()\n .catch(() => {})\n .finally(() => retiredMemories.delete(retired));\n }\n\n cachedMemory = new Memory({\n storage,\n ...(knowledge ? { knowledge } : {}),\n vector: vector || false,\n embedder: vector ? lazyFastembedSmall : undefined,\n options: {\n // Generate a durable title from the first user message. Every client uses\n // the same title in its thread list and active-session chrome. Title\n // generation takes the primary OM model only — its model field does not\n // accept fallback arrays.\n generateTitle:\n process.env.MASTRACODE_DISABLE_TITLE_GENERATION === '1'\n ? false\n : {\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n if (resolved === 'auto') {\n return resolveMemoryModel(\n resolveAutoOMModelId(getMainModelId(requestContext), providerId =>\n canUseProvider(providerId, { requestContext }),\n ),\n { requestContext },\n );\n }\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory:\n process.env.MASTRACODE_DISABLE_OBSERVATIONAL_MEMORY === '1'\n ? false\n : {\n enabled: true,\n autoModels: MASTRACODE_AUTO_OM_MODELS,\n canUseProvider,\n resolveModel: resolveMemoryModel,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n experimental_subconscious: subconsciousAvailable\n ? new Subconscious({\n defaultScope: 'resource',\n pins: true,\n ...(isFactory ? { maxSteps: 25 } : {}),\n })\n : undefined,\n scope: omScope,\n // The main agent writes Anthropic cache entries with this TTL; 'auto' can't see it.\n activateAfterIdle: { default: 'auto', anthropic: ANTHROPIC_PROMPT_CACHE_TTL },\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n\n return Object.assign(resolveMemory, {\n /**\n * Wait for background memory work (buffered observations, reflections, indexing) in every\n * instance this factory created. Await before closing storage.\n */\n async settled(): Promise<void> {\n // Drain every instance even if one rejects, so teardown can still close storage.\n await Promise.allSettled([cachedMemory?.settled(), ...[...retiredMemories].map(memory => memory.settled())]);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAoBA,MAAM,qBAA6C;CACjD,sBAAsB;CACtB,UAAU;CACV,SAAS;CACT,sBAAsB;CACtB,uBAAuB;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,IAAY;MAChD,OAAO;MACP,eAAe;MACf,YAAY;MACZ,wBAAwB;MACxB,aAAa;MACb,aAAa;MACb;KACF;KACA,YAAY;MACV,kBAAkB,kBAAkB,KAAA,IAAY,IAAI;MACpD,YAAY;MACZ,OAAO;MACP,mBAAmB;MACnB,aAAa;KACf;IACF;GACR;EACF,CAAC;EACD,kBAAkB;EAElB,OAAO;CACT;CAEA,OAAO,OAAO,OAAO,eAAe;;;;;AAKlC,MAAM,UAAyB;EAE7B,MAAM,QAAQ,WAAW,CAAC,cAAc,QAAQ,GAAG,GAAG,CAAC,GAAG,eAAe,CAAC,CAAC,KAAI,WAAU,OAAO,QAAQ,CAAC,CAAC,CAAC;CAC7G,EACF,CAAC;AACH"}
@@ -9,4 +9,19 @@ export declare const MODEL_ROUTE_MAX_FIELD_LENGTH = 512;
9
9
  export declare const DEFAULT_OM_MODEL_ID: string;
10
10
  export declare const DEFAULT_OBS_THRESHOLD = 30000;
11
11
  export declare const DEFAULT_REF_THRESHOLD = 40000;
12
+ /**
13
+ * Absolute token retention of the observation activation buffer
14
+ * (`observation.bufferActivation`) for non-resource OM. `@mastra/memory` requires
15
+ * the buffer to stay below `observation.messageTokens`, so a stored observation
16
+ * threshold at or below this value fails the next memory init.
17
+ */
18
+ export declare const OBSERVATION_ACTIVATION_TOKENS = 2000;
19
+ /**
20
+ * Smallest observation threshold the observer can actually run with: the
21
+ * activation buffer above must stay strictly below `observation.messageTokens`.
22
+ * A row saved before the settings route enforced that can hold a lower value, and
23
+ * `@mastra/memory` rejects the config at init — so reads take the value up to this
24
+ * floor rather than trusting the stored one.
25
+ */
26
+ export declare const MIN_OBSERVATION_THRESHOLD: number;
12
27
  //# sourceMappingURL=constants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,kBAAkB,gBAAgB,CAAC;AAEhD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI,CAgBjE;AAGD,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAC1C,eAAO,MAAM,4BAA4B,MAAM,CAAC;AAGhD,eAAO,MAAM,mBAAmB,QAA+D,CAAC;AAGhG,eAAO,MAAM,qBAAqB,QAAS,CAAC;AAC5C,eAAO,MAAM,qBAAqB,QAAS,CAAC"}
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,kBAAkB,gBAAgB,CAAC;AAEhD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,aAAa,EAAE,MAAM,GAAG,IAAI,CAgBjE;AAGD,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAC1C,eAAO,MAAM,4BAA4B,MAAM,CAAC;AAGhD,eAAO,MAAM,mBAAmB,QAA+D,CAAC;AAGhG,eAAO,MAAM,qBAAqB,QAAS,CAAC;AAC5C,eAAO,MAAM,qBAAqB,QAAS,CAAC;AAE5C;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD;;;;;;GAMG;AACH,eAAO,MAAM,yBAAyB,QAAoC,CAAC"}
package/dist/constants.js CHANGED
@@ -14,6 +14,21 @@ const MODEL_ROUTE_MAX_FIELD_LENGTH = 512;
14
14
  const DEFAULT_OM_MODEL_ID = process.env.DEFAULT_OM_MODEL_ID ?? "google/gemini-3.5-flash";
15
15
  const DEFAULT_OBS_THRESHOLD = 3e4;
16
16
  const DEFAULT_REF_THRESHOLD = 4e4;
17
- export { DEFAULT_CONFIG_DIR, DEFAULT_OBS_THRESHOLD, DEFAULT_OM_MODEL_ID, DEFAULT_REF_THRESHOLD, MODEL_ROUTE_MAX_ENTRIES, MODEL_ROUTE_MAX_FIELD_LENGTH, validateConfigDirName };
17
+ /**
18
+ * Absolute token retention of the observation activation buffer
19
+ * (`observation.bufferActivation`) for non-resource OM. `@mastra/memory` requires
20
+ * the buffer to stay below `observation.messageTokens`, so a stored observation
21
+ * threshold at or below this value fails the next memory init.
22
+ */
23
+ const OBSERVATION_ACTIVATION_TOKENS = 2e3;
24
+ /**
25
+ * Smallest observation threshold the observer can actually run with: the
26
+ * activation buffer above must stay strictly below `observation.messageTokens`.
27
+ * A row saved before the settings route enforced that can hold a lower value, and
28
+ * `@mastra/memory` rejects the config at init — so reads take the value up to this
29
+ * floor rather than trusting the stored one.
30
+ */
31
+ const MIN_OBSERVATION_THRESHOLD = 2001;
32
+ export { DEFAULT_CONFIG_DIR, DEFAULT_OBS_THRESHOLD, DEFAULT_OM_MODEL_ID, DEFAULT_REF_THRESHOLD, MIN_OBSERVATION_THRESHOLD, MODEL_ROUTE_MAX_ENTRIES, MODEL_ROUTE_MAX_FIELD_LENGTH, OBSERVATION_ACTIVATION_TOKENS, validateConfigDirName };
18
33
 
19
34
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","names":["path"],"sources":["../src/constants.ts"],"sourcesContent":["import * as path from 'node:path';\n\n// Default config directory name used for all project-level and global config paths.\nexport const DEFAULT_CONFIG_DIR = '.mastracode';\n\n/**\n * Validate that a configDirName is a safe single directory name.\n * Rejects absolute paths, path separators, and traversal components.\n */\nexport function validateConfigDirName(configDirName: string): void {\n if (configDirName.trim().length === 0) {\n throw new Error('configDirName must be a non-empty directory name');\n }\n\n if (\n path.isAbsolute(configDirName) ||\n configDirName.includes('/') ||\n configDirName.includes('\\\\') ||\n configDirName === '..' ||\n configDirName === '.'\n ) {\n throw new Error(\n `configDirName must be a single directory name without path separators or traversal components, got: \"${configDirName}\"`,\n );\n }\n}\n\n// Model routes are persisted host input and eagerly resolved per request.\nexport const MODEL_ROUTE_MAX_ENTRIES = 32;\nexport const MODEL_ROUTE_MAX_FIELD_LENGTH = 512;\n\n// Default OM model - using gemini-3.5-flash for efficiency\nexport const DEFAULT_OM_MODEL_ID = process.env.DEFAULT_OM_MODEL_ID ?? 'google/gemini-3.5-flash';\n\n// Default OM thresholds — per-thread overrides are loaded from thread metadata\nexport const DEFAULT_OBS_THRESHOLD = 30_000;\nexport const DEFAULT_REF_THRESHOLD = 40_000;\n"],"mappings":";;AAGA,MAAa,qBAAqB;;;;;AAMlC,SAAgB,sBAAsB,eAA6B;CACjE,IAAI,cAAc,KAAK,CAAC,CAAC,WAAW,GAClC,MAAM,IAAI,MAAM,kDAAkD;CAGpE,IACEA,OAAK,WAAW,aAAa,KAC7B,cAAc,SAAS,GAAG,KAC1B,cAAc,SAAS,IAAI,KAC3B,kBAAkB,QAClB,kBAAkB,KAElB,MAAM,IAAI,MACR,wGAAwG,cAAc,EACxH;AAEJ;AAGA,MAAa,0BAA0B;AACvC,MAAa,+BAA+B;AAG5C,MAAa,sBAAsB,QAAQ,IAAI,uBAAuB;AAGtE,MAAa,wBAAwB;AACrC,MAAa,wBAAwB"}
1
+ {"version":3,"file":"constants.js","names":["path"],"sources":["../src/constants.ts"],"sourcesContent":["import * as path from 'node:path';\n\n// Default config directory name used for all project-level and global config paths.\nexport const DEFAULT_CONFIG_DIR = '.mastracode';\n\n/**\n * Validate that a configDirName is a safe single directory name.\n * Rejects absolute paths, path separators, and traversal components.\n */\nexport function validateConfigDirName(configDirName: string): void {\n if (configDirName.trim().length === 0) {\n throw new Error('configDirName must be a non-empty directory name');\n }\n\n if (\n path.isAbsolute(configDirName) ||\n configDirName.includes('/') ||\n configDirName.includes('\\\\') ||\n configDirName === '..' ||\n configDirName === '.'\n ) {\n throw new Error(\n `configDirName must be a single directory name without path separators or traversal components, got: \"${configDirName}\"`,\n );\n }\n}\n\n// Model routes are persisted host input and eagerly resolved per request.\nexport const MODEL_ROUTE_MAX_ENTRIES = 32;\nexport const MODEL_ROUTE_MAX_FIELD_LENGTH = 512;\n\n// Default OM model - using gemini-3.5-flash for efficiency\nexport const DEFAULT_OM_MODEL_ID = process.env.DEFAULT_OM_MODEL_ID ?? 'google/gemini-3.5-flash';\n\n// Default OM thresholds — per-thread overrides are loaded from thread metadata\nexport const DEFAULT_OBS_THRESHOLD = 30_000;\nexport const DEFAULT_REF_THRESHOLD = 40_000;\n\n/**\n * Absolute token retention of the observation activation buffer\n * (`observation.bufferActivation`) for non-resource OM. `@mastra/memory` requires\n * the buffer to stay below `observation.messageTokens`, so a stored observation\n * threshold at or below this value fails the next memory init.\n */\nexport const OBSERVATION_ACTIVATION_TOKENS = 2000;\n\n/**\n * Smallest observation threshold the observer can actually run with: the\n * activation buffer above must stay strictly below `observation.messageTokens`.\n * A row saved before the settings route enforced that can hold a lower value, and\n * `@mastra/memory` rejects the config at init — so reads take the value up to this\n * floor rather than trusting the stored one.\n */\nexport const MIN_OBSERVATION_THRESHOLD = OBSERVATION_ACTIVATION_TOKENS + 1;\n"],"mappings":";;AAGA,MAAa,qBAAqB;;;;;AAMlC,SAAgB,sBAAsB,eAA6B;CACjE,IAAI,cAAc,KAAK,CAAC,CAAC,WAAW,GAClC,MAAM,IAAI,MAAM,kDAAkD;CAGpE,IACEA,OAAK,WAAW,aAAa,KAC7B,cAAc,SAAS,GAAG,KAC1B,cAAc,SAAS,IAAI,KAC3B,kBAAkB,QAClB,kBAAkB,KAElB,MAAM,IAAI,MACR,wGAAwG,cAAc,EACxH;AAEJ;AAGA,MAAa,0BAA0B;AACvC,MAAa,+BAA+B;AAG5C,MAAa,sBAAsB,QAAQ,IAAI,uBAAuB;AAGtE,MAAa,wBAAwB;AACrC,MAAa,wBAAwB;;;;;;;AAQrC,MAAa,gCAAgC;;;;;;;;AAS7C,MAAa,4BAA4B"}
@@ -1 +1 @@
1
- {"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/mcp/manager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAgBH,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAQ/D,OAAO,KAAK,EACV,SAAS,EAGT,eAAe,EACf,eAAe,EACf,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAIpB,4CAA4C;AAC5C,MAAM,WAAW,aAAa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AAC,IAAI,CAAC,CAAC;IACnC,2EAA2E;IAC3E,kBAAkB,IAAI,MAAM,EAAE,CAAC;IAC/B,mEAAmE;IACnE,qBAAqB,IAAI,OAAO,CAAC;IACjC,oDAAoD;IACpD,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B,oFAAoF;IACpF,QAAQ,IAAI,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAChC,4DAA4D;IAC5D,UAAU,IAAI,OAAO,CAAC;IACtB,iCAAiC;IACjC,iBAAiB,IAAI,eAAe,EAAE,CAAC;IACvC,2DAA2D;IAC3D,iBAAiB,IAAI,gBAAgB,EAAE,CAAC;IACxC,yCAAyC;IACzC,cAAc,IAAI;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IACtE,6BAA6B;IAC7B,SAAS,IAAI,SAAS,CAAC;IACvB,6CAA6C;IAC7C,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CACvC;AA0FD;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,UAAU,EAAE,MAAM,EAClB,aAAa,SAAqB,EAClC,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,EAC9C,iBAAiB,CAAC,EAAE,2BAA2B,GAC9C,UAAU,CA6vBZ"}
@@ -364,18 +364,17 @@ function createMcpManager(projectDir, configDirName = DEFAULT_CONFIG_DIR, extraS
364
364
  };
365
365
  serverStatuses.set(name, status);
366
366
  return status;
367
- } else {
368
- const status = {
369
- name,
370
- connected: false,
371
- toolCount: 0,
372
- toolNames: [],
373
- transport,
374
- error: "Failed to connect"
375
- };
376
- serverStatuses.set(name, status);
377
- return status;
378
367
  }
368
+ const status = {
369
+ name,
370
+ connected: false,
371
+ toolCount: 0,
372
+ toolNames: [],
373
+ transport,
374
+ error: "Failed to connect"
375
+ };
376
+ serverStatuses.set(name, status);
377
+ return status;
379
378
  } catch (error) {
380
379
  const errMsg = error instanceof Error ? error.message : String(error);
381
380
  const status = {
@@ -1 +1 @@
1
- {"version":3,"file":"manager.js","names":[],"sources":["../../src/mcp/manager.ts"],"sourcesContent":["/**\n * MCP manager — orchestrates MCP server connections using MCPClient directly.\n * Created once at startup, provides tools from connected MCP servers.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { MCPClient, MastraMCPServerDefinition, OAuthClientInformation, OAuthStorage } from '@mastra/mcp';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport {\n DEFAULT_OAUTH_REDIRECT_URL,\n MASTRA_CODE_CLIENT_METADATA_URL,\n loadMcpConfig,\n getProjectMcpPath,\n getGlobalMcpPath,\n getClaudeSettingsPath,\n resolveOAuthRedirectUrl,\n} from './config.js';\nimport type { ExternalMcpDiscoveryOptions } from './config.js';\nimport {\n loadGlobalDisableState,\n loadProjectServerOverrides,\n saveGlobalDisableState,\n saveProjectServerOverrides,\n} from './state.js';\nimport type { McpProjectServerOverride } from './state.js';\nimport type {\n McpConfig,\n McpHttpOAuthConfig,\n McpHttpServerConfig,\n McpServerConfig,\n McpServerStatus,\n McpSkippedServer,\n} from './types.js';\n\nconst MASTRACODE_MCP_TIMEOUT_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\n/** Summary of MCP initialization result. */\nexport interface McpInitResult {\n connected: McpServerStatus[];\n failed: McpServerStatus[];\n skipped: McpSkippedServer[];\n totalTools: number;\n}\n\n/** Public interface for the MCP manager returned by createMcpManager(). */\nexport interface McpManager {\n /** Connect to all configured MCP servers and collect their tools. */\n init(): Promise<void>;\n /** Start init in the background. Returns a promise that resolves with status when done. */\n initInBackground(): Promise<McpInitResult>;\n /** Disconnect all servers, reload config from disk, reconnect. */\n reload(): Promise<void>;\n /** Reconnect a single server by name. Returns updated status. */\n reconnectServer(name: string): Promise<McpServerStatus>;\n /**\n * Run the OAuth authorization-code flow for an HTTP server, then reconnect it.\n * Servers without an `oauth` config are provisioned with a zero-config default\n * that identifies Mastra Code by its Client ID Metadata Document. The\n * authorization URL is surfaced through\n * `onAuthorizationUrl` for the caller to open in a browser.\n *\n * Resolves with the resulting {@link McpServerStatus}: a connected status on\n * success, or a status carrying an `error` message on failure (including\n * cancellation) — it does not reject. Inspect the returned status rather than\n * relying on a thrown error.\n */\n authenticateServer(\n name: string,\n options?: { onAuthorizationUrl?: (url: string) => void; timeoutMs?: number },\n ): Promise<McpServerStatus>;\n /**\n * Cancel a pending {@link authenticateServer} flow for a server (e.g. the\n * user closed the browser without completing consent). The pending\n * authenticate call rejects and the server returns to the `needsAuth` state\n * so it can be retried. Returns `true` if a flow was cancelled.\n */\n cancelServerAuthentication(name: string): Promise<boolean>;\n /**\n * Disable or enable a single server by name. The change is persisted (in\n * mastracode's app data, not the user's config files) and survives restarts.\n * With `global: true`, this changes the default for every project. Otherwise\n * it records an explicit project override, which can override a global\n * per-server disable. The global all-MCP kill switch remains absolute.\n * Connections are rebuilt, so other servers reconnect — same behavior as\n * {@link reload}. Returns the server's resulting status.\n */\n setServerDisabled(name: string, disabled: boolean, options?: { global?: boolean }): Promise<McpServerStatus>;\n /** Clear a server's explicit project override so it inherits the global default. */\n inheritServer(name: string): Promise<McpServerStatus>;\n /**\n * Disable or enable all servers at once. Project scope records an explicit\n * override for every currently configured server. Global scope sets/clears a\n * persisted all-MCP kill switch (and, when enabling, also clears globally\n * disabled server names). Persisted like {@link setServerDisabled}.\n */\n setAllDisabled(disabled: boolean, options?: { global?: boolean }): Promise<void>;\n /** Clear every explicit project override so all servers inherit global defaults. */\n inheritAllServers(): Promise<void>;\n /** Names of configured servers that are currently disabled (any scope). */\n getDisabledServers(): string[];\n /** Whether all MCP is disabled globally (across every project). */\n isAllDisabledGlobally(): boolean;\n /** Disconnect from all MCP servers and clean up. */\n disconnect(): Promise<void>;\n /** Get all tools from connected MCP servers (namespaced as serverName_toolName). */\n getTools(): Record<string, any>;\n /** Check if any MCP servers are configured (or skipped). */\n hasServers(): boolean;\n /** Get status of all servers. */\n getServerStatuses(): McpServerStatus[];\n /** Get servers that were skipped during config loading. */\n getSkippedServers(): McpSkippedServer[];\n /** Get config file paths for display. */\n getConfigPaths(): { project: string; global: string; claude: string };\n /** Get the merged config. */\n getConfig(): McpConfig;\n /** Get captured stderr logs for a server. */\n getServerLogs(name: string): string[];\n}\n\nfunction getTransport(cfg: McpServerConfig): 'stdio' | 'http' {\n return 'url' in cfg ? 'http' : 'stdio';\n}\n\nclass FileOAuthStorage implements OAuthStorage {\n constructor(private filePath: string) {}\n\n get(key: string): string | undefined {\n return this.read()[key];\n }\n\n set(key: string, value: string): void {\n const data = this.read();\n data[key] = value;\n this.write(data);\n }\n\n delete(key: string): void {\n const data = this.read();\n delete data[key];\n this.write(data);\n }\n\n private read(): Record<string, string> {\n if (!existsSync(this.filePath)) return {};\n try {\n return JSON.parse(readFileSync(this.filePath, 'utf-8')) as Record<string, string>;\n } catch {\n return {};\n }\n }\n\n private write(data: Record<string, string>): void {\n const dir = dirname(this.filePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n const tmpPath = `${this.filePath}.tmp`;\n writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: 'utf-8', mode: 0o600 });\n renameSync(tmpPath, this.filePath);\n }\n}\n\n/**\n * Zero-config OAuth defaults for servers with a bare `url` entry. The client\n * identifies itself by Mastra Code's Client ID Metadata Document URL, so no\n * `clientId` is needed.\n */\nconst DEFAULT_OAUTH_CONFIG: McpHttpOAuthConfig = { redirectUrl: DEFAULT_OAUTH_REDIRECT_URL };\n\nfunction getOAuthStoragePath(projectDir: string, name: string, cfg: McpHttpServerConfig): string {\n // The fingerprint always uses the resolved redirect URL so a bare `url`\n // entry keeps the same token file before and after zero-config provisioning.\n const key = JSON.stringify({\n projectDir,\n name,\n url: cfg.url,\n redirectUrl: resolveOAuthRedirectUrl(cfg.oauth),\n clientId: cfg.oauth?.clientId,\n scopes: cfg.oauth?.scopes ?? [],\n });\n return join(getAppDataDir(), 'mcp-oauth', `${getStorageKeyFingerprint(key)}.json`);\n}\n\nfunction getStorageKeyFingerprint(value: string): string {\n let fingerprint = 0xcbf29ce484222325n;\n for (let i = 0; i < value.length; i += 1) {\n fingerprint ^= BigInt(value.charCodeAt(i));\n fingerprint = BigInt.asUintN(64, fingerprint * 0x100000001b3n);\n }\n return fingerprint.toString(16).padStart(16, '0');\n}\n\ntype McpModule = typeof import('@mastra/mcp');\nlet mcpModule: McpModule | undefined;\n\n/** `@mastra/mcp` and the MCP SDK (~12 MB) load with the first server that connects, not with every session. */\nasync function loadMcpModule(): Promise<McpModule> {\n mcpModule ??= await import('@mastra/mcp');\n return mcpModule;\n}\n\n/** For code that only runs once a client exists, so the module is already loaded. */\nfunction loadedMcpModule(): McpModule {\n if (!mcpModule) throw new Error('@mastra/mcp is not loaded yet');\n return mcpModule;\n}\n\n/**\n * Create an MCP manager that wraps MCPClient with config-file discovery\n * and per-server status tracking.\n */\nexport function createMcpManager(\n projectDir: string,\n configDirName = DEFAULT_CONFIG_DIR,\n extraServers?: Record<string, McpServerConfig>,\n externalDiscovery?: ExternalMcpDiscoveryOptions,\n): McpManager {\n /** Merge programmatic servers into a base config (highest priority). */\n const applyExtraServers = (base: McpConfig): McpConfig => {\n if (!extraServers || Object.keys(extraServers).length === 0) return base;\n return { ...base, mcpServers: { ...base.mcpServers, ...extraServers } };\n };\n\n let config = applyExtraServers(loadMcpConfig(projectDir, configDirName, externalDiscovery));\n let projectServerOverrides = new Map<string, McpProjectServerOverride>(\n Object.entries(loadProjectServerOverrides(projectDir)),\n );\n let globalDisableState = loadGlobalDisableState();\n let globallyDisabledServers = new Set(globalDisableState.disabledServers);\n\n /** Whether a server is disabled after applying the kill switch, project override, and global default. */\n const isDisabled = (name: string): boolean => {\n if (globalDisableState.allDisabled) return true;\n const projectOverride = projectServerOverrides.get(name);\n if (projectOverride) return projectOverride === 'disabled';\n return globallyDisabledServers.has(name);\n };\n\n /** Which scope currently disables a server. The global kill switch remains absolute. */\n const disabledScopeOf = (name: string): 'project' | 'global' | undefined => {\n if (globalDisableState.allDisabled) return 'global';\n const projectOverride = projectServerOverrides.get(name);\n if (projectOverride === 'disabled') return 'project';\n if (!projectOverride && globallyDisabledServers.has(name)) return 'global';\n return undefined;\n };\n let client: MCPClient | null = null;\n let serverDefs: Record<string, MastraMCPServerDefinition> = {};\n let tools: Record<string, any> = {};\n let serverStatuses = new Map<string, McpServerStatus>();\n let stderrLogs = new Map<string, string[]>();\n let initialized = false;\n\n /** Per-server handlers that receive the OAuth authorization URL during authenticateServer(). */\n const authUrlHandlers = new Map<string, (url: string) => void>();\n\n /**\n * Servers with an OAuth authorization flow currently in flight. Owned by the\n * manager (not the TUI) so the state survives a `/mcp` selector being closed\n * and reopened — the reopened selector reads it back off the server status and\n * can still offer \"Cancel authentication\".\n */\n const authenticatingServers = new Set<string>();\n\n /**\n * Servers whose in-flight authentication was cancelled by the caller. Set by\n * cancelServerAuthentication() so the resolving authenticateServer() call can\n * mark its failed status as a deliberate cancel rather than a genuine failure.\n * This lives on the manager (not the TUI selector) so the signal survives the\n * selector being closed and reopened mid-flow.\n */\n const cancelledAuthServers = new Set<string>();\n\n /** Overlay manager-owned state onto a status snapshot. */\n const withManagerState = (status: McpServerStatus): McpServerStatus => ({\n ...status,\n ...(authenticatingServers.has(status.name) ? { authenticating: true } : {}),\n ...(projectServerOverrides.has(status.name) ? { projectOverride: projectServerOverrides.get(status.name) } : {}),\n globalDefault: globallyDisabledServers.has(status.name) ? 'disabled' : 'enabled',\n globalKillSwitch: globalDisableState.allDisabled,\n });\n\n const MAX_STDERR_LINES = 200;\n\n /** Hook into a server's stderr stream and buffer its output. */\n function captureStderr(serverName: string): void {\n if (!client || typeof client.getServerStderr !== 'function') return;\n const stream = client.getServerStderr(serverName);\n if (!stream) return;\n\n let buffer = '';\n const lines = stderrLogs.get(serverName) ?? [];\n stderrLogs.set(serverName, lines);\n\n stream.on('data', (chunk: Buffer) => {\n buffer += chunk.toString();\n const parts = buffer.split('\\n');\n // Last element is incomplete line (or empty if ended with \\n)\n buffer = parts.pop()!;\n for (const line of parts) {\n if (line.trim()) {\n lines.push(line);\n if (lines.length > MAX_STDERR_LINES) {\n lines.shift();\n }\n }\n }\n });\n\n stream.on('end', () => {\n if (buffer.trim()) {\n lines.push(buffer);\n if (lines.length > MAX_STDERR_LINES) {\n lines.shift();\n }\n }\n });\n }\n\n function createOAuthProvider(name: string, cfg: McpHttpServerConfig) {\n // Bare `url` entries get no eager provider — auth is provisioned lazily\n // when the user authenticates — unless a previous session already stored\n // OAuth state for this server, in which case the provider is needed to\n // attach the persisted tokens on connect.\n const oauth =\n cfg.oauth ?? (existsSync(getOAuthStoragePath(projectDir, name, cfg)) ? DEFAULT_OAUTH_CONFIG : undefined);\n if (!oauth) return undefined;\n\n // redirectUrl is optional in the user-supplied config; resolve the stable\n // default (or the `callbackPort` shorthand, for programmatically registered\n // servers that bypass config parsing) so provider metadata always carries\n // a concrete URL.\n const redirectUrl = resolveOAuthRedirectUrl(oauth);\n\n // Without a pre-registered clientId the client is identified by Mastra\n // Code's Client ID Metadata Document: the document URL is the client_id and\n // the authorization server fetches it, so nothing is registered per server.\n const clientInformation = oauth.clientId\n ? ({\n client_id: oauth.clientId,\n ...(oauth.clientSecret ? { client_secret: oauth.clientSecret } : {}),\n } satisfies OAuthClientInformation)\n : undefined;\n const clientMetadataUrl = clientInformation ? undefined : MASTRA_CODE_CLIENT_METADATA_URL;\n\n const { MCPOAuthClientProvider } = loadedMcpModule();\n return new MCPOAuthClientProvider({\n redirectUrl,\n clientMetadata: {\n ...(clientMetadataUrl ? { client_id: clientMetadataUrl } : {}),\n redirect_uris: [redirectUrl],\n client_name: oauth.clientName ?? (clientMetadataUrl ? 'Mastra Code' : `Mastra Code MCP ${name}`),\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n ...(oauth.scopes?.length ? { scope: oauth.scopes.join(' ') } : {}),\n },\n clientInformation,\n clientMetadataUrl,\n storage: new FileOAuthStorage(getOAuthStoragePath(projectDir, name, cfg)),\n onRedirectToAuthorization: url => {\n authUrlHandlers.get(name)?.(url.toString());\n },\n });\n }\n\n function buildServerDefs(servers: Record<string, McpServerConfig>): Record<string, MastraMCPServerDefinition> {\n const defs: Record<string, MastraMCPServerDefinition> = {};\n for (const [name, cfg] of Object.entries(servers)) {\n if ('url' in cfg) {\n const httpCfg = cfg as McpHttpServerConfig;\n defs[name] = {\n url: new URL(httpCfg.url),\n requestInit: httpCfg.headers ? { headers: httpCfg.headers } : undefined,\n authProvider: createOAuthProvider(name, httpCfg),\n };\n } else {\n defs[name] = {\n command: cfg.command,\n args: cfg.args,\n env: cfg.env,\n ...(cfg.cwd ? { cwd: cfg.cwd } : {}),\n stderr: 'pipe',\n };\n }\n }\n return defs;\n }\n\n /** Seed a `disabled` status for every disabled server so it stays visible. */\n function setDisabledStatuses(): void {\n for (const [name, cfg] of Object.entries(config.mcpServers ?? {})) {\n const scope = disabledScopeOf(name);\n if (!scope) continue;\n serverStatuses.set(name, {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(cfg),\n disabled: true,\n disabledScope: scope,\n });\n }\n }\n\n async function connectAndCollectTools(): Promise<void> {\n setDisabledStatuses();\n\n const servers = Object.fromEntries(Object.entries(config.mcpServers ?? {}).filter(([name]) => !isDisabled(name)));\n if (Object.keys(servers).length === 0) {\n return;\n }\n\n // Pre-populate statuses as \"connecting\" so callers can see in-progress state\n const serverNames = Object.keys(servers);\n for (const name of serverNames) {\n serverStatuses.set(name, {\n name,\n connected: false,\n connecting: true,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(servers[name]!),\n });\n }\n\n const { MCPClient } = await loadMcpModule();\n serverDefs = buildServerDefs(servers);\n client = new MCPClient({\n id: 'mastra-code-mcp',\n servers: serverDefs,\n timeout: MASTRACODE_MCP_TIMEOUT_MS,\n });\n\n // Use listToolsetsWithErrors() to get tools grouped by server name,\n // plus per-server error messages for servers that failed to connect.\n\n try {\n const { toolsets, errors } = await client.listToolsetsWithErrors();\n const typedToolsets = toolsets as Record<string, Record<string, any>>;\n\n // Flatten toolsets into the namespaced tools map (serverName_toolName)\n for (const [serverName, serverTools] of Object.entries(typedToolsets)) {\n for (const [toolName, toolConfig] of Object.entries(serverTools)) {\n tools[`${serverName}_${toolName}`] = toolConfig;\n }\n }\n\n for (const name of serverNames) {\n const serverTools = typedToolsets[name];\n if (serverTools && Object.keys(serverTools).length > 0) {\n const toolNames = Object.keys(serverTools).map(t => `${name}_${t}`);\n serverStatuses.set(name, {\n name,\n connected: true,\n toolCount: toolNames.length,\n toolNames,\n transport: getTransport(servers[name]!),\n });\n } else {\n // Server failed — use the real error from listToolsetsWithErrors()\n const error = errors[name] ?? 'Failed to connect';\n serverStatuses.set(name, {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(servers[name]!),\n error,\n ...(serverNeedsAuth(name, servers[name]!, error) ? { needsAuth: true } : {}),\n });\n }\n }\n\n // Capture stderr from all stdio servers (connected or failed)\n for (const name of serverNames) {\n captureStderr(name);\n }\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n\n for (const name of serverNames) {\n serverStatuses.set(name, {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(servers[name]!),\n error: errMsg,\n ...(serverNeedsAuth(name, servers[name]!, errMsg) ? { needsAuth: true } : {}),\n });\n }\n }\n }\n\n /**\n * Whether a failed HTTP server is blocked on OAuth authorization.\n *\n * Provider-backed servers report the exact state tracked by `@mastra/mcp`.\n * Bare `url` entries carry no provider until the user authenticates, so the\n * signal is a 401 in the connect error — surfaced either as the status text\n * or as the RFC 6750 `invalid_token` bearer error code in the response body.\n */\n function serverNeedsAuth(name: string, cfg: McpServerConfig, error?: string): boolean {\n if (getTransport(cfg) !== 'http') return false;\n if (client?.getServerAuthState?.(name) === 'needs-auth') return true;\n if (serverDefs[name]?.authProvider) return false;\n return error !== undefined && /\\b401\\b|unauthorized|invalid_token/i.test(error);\n }\n\n /**\n * Runs a single-server connect action (reconnect or authenticate), then\n * refreshes that server's tools and status from the client.\n */\n async function connectSingleServer(\n name: string,\n cfg: McpServerConfig,\n connect: () => Promise<unknown>,\n ): Promise<McpServerStatus> {\n const transport = getTransport(cfg);\n\n // Remove old tools for this server\n const prefix = `${name}_`;\n for (const key of Object.keys(tools)) {\n if (key.startsWith(prefix)) {\n delete tools[key];\n }\n }\n\n // Clear old logs and mark as connecting\n stderrLogs.delete(name);\n serverStatuses.set(name, {\n name,\n connected: false,\n connecting: true,\n toolCount: 0,\n toolNames: [],\n transport,\n });\n\n try {\n await connect();\n\n // Recapture stderr for the reconnected server\n captureStderr(name);\n\n // Fetch updated toolsets to get this server's tools\n const { toolsets, errors } = await client!.listToolsetsWithErrors();\n const serverTools = toolsets[name];\n const serverError = errors[name];\n\n if (serverError) {\n const status: McpServerStatus = {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport,\n error: serverError,\n ...(serverNeedsAuth(name, cfg, serverError) ? { needsAuth: true } : {}),\n };\n serverStatuses.set(name, status);\n return status;\n } else if (serverTools && Object.keys(serverTools).length > 0) {\n const toolNames = Object.keys(serverTools).map(t => `${name}_${t}`);\n for (const [toolName, toolConfig] of Object.entries(serverTools)) {\n tools[`${name}_${toolName}`] = toolConfig;\n }\n const status: McpServerStatus = {\n name,\n connected: true,\n toolCount: toolNames.length,\n toolNames,\n transport,\n };\n serverStatuses.set(name, status);\n return status;\n } else {\n const status: McpServerStatus = {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport,\n error: 'Failed to connect',\n };\n serverStatuses.set(name, status);\n return status;\n }\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n const status: McpServerStatus = {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport,\n error: errMsg,\n ...(serverNeedsAuth(name, cfg, errMsg) ? { needsAuth: true } : {}),\n };\n serverStatuses.set(name, status);\n return status;\n }\n }\n\n async function disconnect(): Promise<void> {\n if (client) {\n try {\n await client.disconnect();\n } catch {\n // Ignore disconnect errors\n }\n client = null;\n }\n }\n\n /** Tear down all connections and reconnect every enabled server. */\n async function rebuildConnections(): Promise<void> {\n await disconnect();\n tools = {};\n serverStatuses = new Map();\n stderrLogs = new Map();\n initialized = false;\n await connectAndCollectTools();\n initialized = true;\n }\n\n function disabledStatus(name: string): McpServerStatus {\n const cfg = config.mcpServers?.[name];\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: cfg ? getTransport(cfg) : 'stdio',\n disabled: true,\n disabledScope: disabledScopeOf(name),\n };\n }\n\n // Read-merge-write persistence: re-read the persisted state and apply this\n // operation's delta on top, then adopt the merged result in memory. This\n // way a concurrent mastracode process's changes (e.g. another window\n // flipping the global kill switch) are never clobbered by this manager's\n // construction-time snapshot.\n function persistProjectDelta(mutate: (overrides: Map<string, McpProjectServerOverride>) => void): void {\n const fresh = new Map<string, McpProjectServerOverride>(Object.entries(loadProjectServerOverrides(projectDir)));\n mutate(fresh);\n projectServerOverrides = fresh;\n saveProjectServerOverrides(projectDir, Object.fromEntries(fresh));\n }\n\n function persistGlobalDelta(mutate: (state: { allDisabled: boolean; disabledServers: Set<string> }) => void): void {\n const onDisk = loadGlobalDisableState();\n const fresh = { allDisabled: onDisk.allDisabled, disabledServers: new Set(onDisk.disabledServers) };\n mutate(fresh);\n globallyDisabledServers = fresh.disabledServers;\n globalDisableState = { allDisabled: fresh.allDisabled, disabledServers: Array.from(fresh.disabledServers) };\n saveGlobalDisableState(globalDisableState);\n }\n\n return {\n async init() {\n if (initialized) return;\n await connectAndCollectTools();\n initialized = true;\n },\n\n async initInBackground(): Promise<McpInitResult> {\n await this.init();\n const statuses = Array.from(serverStatuses.values(), withManagerState);\n const connected = statuses.filter(s => s.connected);\n const failed = statuses.filter(s => !s.connected && !s.disabled);\n return {\n connected,\n failed,\n skipped: [...(config.skippedServers ?? [])],\n totalTools: connected.reduce((sum, s) => sum + s.toolCount, 0),\n };\n },\n\n async reload() {\n config = applyExtraServers(loadMcpConfig(projectDir, configDirName, externalDiscovery));\n projectServerOverrides = new Map(Object.entries(loadProjectServerOverrides(projectDir)));\n globalDisableState = loadGlobalDisableState();\n globallyDisabledServers = new Set(globalDisableState.disabledServers);\n await rebuildConnections();\n },\n\n async setServerDisabled(name: string, disabled: boolean, options?: { global?: boolean }): Promise<McpServerStatus> {\n if (!config.mcpServers?.[name]) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" not found in config`,\n };\n }\n\n const wasEffectivelyDisabled = isDisabled(name);\n\n if (options?.global) {\n persistGlobalDelta(state => {\n if (disabled) {\n state.disabledServers.add(name);\n } else {\n state.disabledServers.delete(name);\n }\n });\n } else {\n persistProjectDelta(overrides => {\n overrides.set(name, disabled ? 'disabled' : 'enabled');\n });\n }\n\n // Only rebuild connections when the server's effective state actually\n // flipped. State changes that only alter an inherited default or an\n // override beneath the global kill switch leave connections alone.\n if (isDisabled(name) !== wasEffectivelyDisabled) {\n await rebuildConnections();\n return withManagerState(serverStatuses.get(name) ?? disabledStatus(name));\n }\n return withManagerState(\n isDisabled(name) ? disabledStatus(name) : (serverStatuses.get(name) ?? disabledStatus(name)),\n );\n },\n\n async inheritServer(name: string): Promise<McpServerStatus> {\n if (!config.mcpServers?.[name]) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" not found in config`,\n };\n }\n\n const wasEffectivelyDisabled = isDisabled(name);\n persistProjectDelta(overrides => {\n overrides.delete(name);\n });\n if (isDisabled(name) !== wasEffectivelyDisabled) {\n await rebuildConnections();\n }\n return withManagerState(\n isDisabled(name) ? disabledStatus(name) : (serverStatuses.get(name) ?? disabledStatus(name)),\n );\n },\n\n async setAllDisabled(disabled: boolean, options?: { global?: boolean }): Promise<void> {\n const configuredNames = Object.keys(config.mcpServers ?? {});\n const effectiveBefore = configuredNames.filter(name => isDisabled(name)).join(',');\n if (options?.global) {\n persistGlobalDelta(state => {\n state.allDisabled = disabled;\n if (!disabled) {\n // Enabling globally also clears globally disabled server names so\n // \"/mcp enable all --global\" fully restores global defaults.\n state.disabledServers.clear();\n }\n });\n } else {\n persistProjectDelta(overrides => {\n for (const name of configuredNames) {\n overrides.set(name, disabled ? 'disabled' : 'enabled');\n }\n });\n }\n const effectiveAfter = configuredNames.filter(name => isDisabled(name)).join(',');\n if (effectiveAfter !== effectiveBefore) {\n await rebuildConnections();\n }\n },\n\n async inheritAllServers(): Promise<void> {\n const configuredNames = Object.keys(config.mcpServers ?? {});\n const effectiveBefore = configuredNames.filter(name => isDisabled(name)).join(',');\n persistProjectDelta(overrides => {\n overrides.clear();\n });\n const effectiveAfter = configuredNames.filter(name => isDisabled(name)).join(',');\n if (effectiveAfter !== effectiveBefore) {\n await rebuildConnections();\n }\n },\n\n getDisabledServers() {\n return Object.keys(config.mcpServers ?? {})\n .filter(name => isDisabled(name))\n .sort();\n },\n\n isAllDisabledGlobally() {\n return globalDisableState.allDisabled;\n },\n\n async reconnectServer(name: string): Promise<McpServerStatus> {\n if (isDisabled(name)) {\n return { ...disabledStatus(name), error: `Server \"${name}\" is disabled — enable it first` };\n }\n const cfg = config.mcpServers?.[name];\n if (!cfg) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" not found in config`,\n };\n }\n\n if (!client) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(cfg),\n error: 'MCP client not initialized',\n };\n }\n\n // Use MCPClient's per-server reconnect\n return connectSingleServer(name, cfg, () => client!.reconnectServer(name));\n },\n\n async authenticateServer(\n name: string,\n options?: { onAuthorizationUrl?: (url: string) => void; timeoutMs?: number },\n ): Promise<McpServerStatus> {\n const cfg = config.mcpServers?.[name];\n if (!cfg) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" not found in config`,\n };\n }\n\n if (isDisabled(name)) {\n return { ...disabledStatus(name), error: `Server \"${name}\" is disabled — enable it first` };\n }\n\n if (!client) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(cfg),\n error: 'MCP client not initialized',\n };\n }\n\n if (getTransport(cfg) !== 'http') {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" uses stdio transport, which does not support OAuth`,\n };\n }\n\n // Zero-config provisioning: a bare `url` entry gets a provider with the\n // default redirect URL the first time the user authenticates. The Client\n // ID Metadata Document takes care of the client identity.\n //\n // NOTE: `serverDefs[name]` is the same object reference the MCPClient was\n // constructed with, and connectHttp reads `authProvider` live off it at\n // connect time, so mutating it here reaches the already-created client.\n // If MCPClient ever defensively copies its server config, zero-config auth\n // would need an explicit \"set this server's provider\" API instead.\n const def = serverDefs[name];\n if (def?.url && !def.authProvider) {\n def.authProvider = createOAuthProvider(name, { ...(cfg as McpHttpServerConfig), oauth: DEFAULT_OAUTH_CONFIG });\n }\n\n // Reject a concurrent second attempt for the same server. authUrlHandlers\n // has a single slot per server, so a second call with an onAuthorizationUrl\n // would overwrite the first caller's handler (which then never sees the\n // URL) and its finally would delete the handler out from under the other\n // in-flight call. Gate on authenticatingServers rather than authUrlHandlers\n // so callers without a URL handler are caught too. The underlying\n // client.authenticate already coalesces same-server calls into one flow.\n if (authenticatingServers.has(name)) {\n const current = serverStatuses.get(name);\n return {\n name,\n connected: current?.connected ?? false,\n connecting: current?.connecting,\n needsAuth: current?.needsAuth,\n toolCount: current?.toolCount ?? 0,\n toolNames: current?.toolNames ?? [],\n transport: current?.transport ?? getTransport(cfg),\n error: `Authentication for \"${name}\" is already in progress`,\n };\n }\n\n if (options?.onAuthorizationUrl) {\n authUrlHandlers.set(name, options.onAuthorizationUrl);\n }\n authenticatingServers.add(name);\n cancelledAuthServers.delete(name);\n try {\n const result = await connectSingleServer(name, cfg, () =>\n client!.authenticate(name, options?.timeoutMs === undefined ? undefined : { timeoutMs: options.timeoutMs }),\n );\n // A cancelled flow resolves with a failed status; mark it so callers can\n // distinguish a deliberate cancel from a genuine authentication failure.\n // Write the marker back to the durable status map (not just the returned\n // value) so a selector reopened after cancellation still sees it.\n const finalStatus =\n cancelledAuthServers.has(name) && !result.connected ? { ...result, cancelled: true } : result;\n serverStatuses.set(name, finalStatus);\n return finalStatus;\n } finally {\n authUrlHandlers.delete(name);\n authenticatingServers.delete(name);\n cancelledAuthServers.delete(name);\n }\n },\n\n async cancelServerAuthentication(name: string): Promise<boolean> {\n if (!client) {\n return false;\n }\n // Record the intent before aborting so the resolving authenticateServer()\n // call can tag its failed status as cancelled rather than failed.\n cancelledAuthServers.add(name);\n const cancelled = await client.cancelAuthentication(name);\n if (!cancelled) {\n cancelledAuthServers.delete(name);\n }\n return cancelled;\n },\n\n disconnect,\n\n getTools() {\n return { ...tools };\n },\n\n hasServers() {\n const hasConfigured = config.mcpServers !== undefined && Object.keys(config.mcpServers).length > 0;\n const hasSkipped = config.skippedServers !== undefined && config.skippedServers.length > 0;\n return hasConfigured || hasSkipped;\n },\n\n getServerStatuses() {\n return Array.from(serverStatuses.values(), withManagerState);\n },\n\n getSkippedServers() {\n return [...(config.skippedServers ?? [])];\n },\n\n getConfigPaths() {\n return {\n project: getProjectMcpPath(projectDir, configDirName),\n global: getGlobalMcpPath(configDirName),\n claude: getClaudeSettingsPath(projectDir),\n };\n },\n\n getConfig() {\n return config;\n },\n\n getServerLogs(name: string) {\n return [...(stderrLogs.get(name) ?? [])];\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAoCA,MAAM,4BAA4B;AAsFlC,SAAS,aAAa,KAAwC;CAC5D,OAAO,SAAS,MAAM,SAAS;AACjC;AAEA,IAAM,mBAAN,MAA+C;CACzB;CAApB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AE;EAC1C;EAEA,iBAAiB;GACf,OAAO;IACL,SAAS,kBAAkB,YAAY,aAAa;IACpD,QAAQ,iBAAiB,aAAa;IACtC,QAAQ,sBAAsB,UAAU;GAC1C;EACF;EAEA,YAAY;GACV,OAAO;EACT;EAEA,cAAc,MAAc;GAC1B,OAAO,CAAC,GAAI,WAAW,IAAI,IAAI,KAAK,CAAC,CAAE;EACzC;CACF;AACF"}
1
+ {"version":3,"file":"manager.js","names":[],"sources":["../../src/mcp/manager.ts"],"sourcesContent":["/**\n * MCP manager — orchestrates MCP server connections using MCPClient directly.\n * Created once at startup, provides tools from connected MCP servers.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { MCPClient, MastraMCPServerDefinition, OAuthClientInformation, OAuthStorage } from '@mastra/mcp';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport {\n DEFAULT_OAUTH_REDIRECT_URL,\n MASTRA_CODE_CLIENT_METADATA_URL,\n loadMcpConfig,\n getProjectMcpPath,\n getGlobalMcpPath,\n getClaudeSettingsPath,\n resolveOAuthRedirectUrl,\n} from './config.js';\nimport type { ExternalMcpDiscoveryOptions } from './config.js';\nimport {\n loadGlobalDisableState,\n loadProjectServerOverrides,\n saveGlobalDisableState,\n saveProjectServerOverrides,\n} from './state.js';\nimport type { McpProjectServerOverride } from './state.js';\nimport type {\n McpConfig,\n McpHttpOAuthConfig,\n McpHttpServerConfig,\n McpServerConfig,\n McpServerStatus,\n McpSkippedServer,\n} from './types.js';\n\nconst MASTRACODE_MCP_TIMEOUT_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\n/** Summary of MCP initialization result. */\nexport interface McpInitResult {\n connected: McpServerStatus[];\n failed: McpServerStatus[];\n skipped: McpSkippedServer[];\n totalTools: number;\n}\n\n/** Public interface for the MCP manager returned by createMcpManager(). */\nexport interface McpManager {\n /** Connect to all configured MCP servers and collect their tools. */\n init(): Promise<void>;\n /** Start init in the background. Returns a promise that resolves with status when done. */\n initInBackground(): Promise<McpInitResult>;\n /** Disconnect all servers, reload config from disk, reconnect. */\n reload(): Promise<void>;\n /** Reconnect a single server by name. Returns updated status. */\n reconnectServer(name: string): Promise<McpServerStatus>;\n /**\n * Run the OAuth authorization-code flow for an HTTP server, then reconnect it.\n * Servers without an `oauth` config are provisioned with a zero-config default\n * that identifies Mastra Code by its Client ID Metadata Document. The\n * authorization URL is surfaced through\n * `onAuthorizationUrl` for the caller to open in a browser.\n *\n * Resolves with the resulting {@link McpServerStatus}: a connected status on\n * success, or a status carrying an `error` message on failure (including\n * cancellation) — it does not reject. Inspect the returned status rather than\n * relying on a thrown error.\n */\n authenticateServer(\n name: string,\n options?: { onAuthorizationUrl?: (url: string) => void; timeoutMs?: number },\n ): Promise<McpServerStatus>;\n /**\n * Cancel a pending {@link authenticateServer} flow for a server (e.g. the\n * user closed the browser without completing consent). The pending\n * authenticate call rejects and the server returns to the `needsAuth` state\n * so it can be retried. Returns `true` if a flow was cancelled.\n */\n cancelServerAuthentication(name: string): Promise<boolean>;\n /**\n * Disable or enable a single server by name. The change is persisted (in\n * mastracode's app data, not the user's config files) and survives restarts.\n * With `global: true`, this changes the default for every project. Otherwise\n * it records an explicit project override, which can override a global\n * per-server disable. The global all-MCP kill switch remains absolute.\n * Connections are rebuilt, so other servers reconnect — same behavior as\n * {@link reload}. Returns the server's resulting status.\n */\n setServerDisabled(name: string, disabled: boolean, options?: { global?: boolean }): Promise<McpServerStatus>;\n /** Clear a server's explicit project override so it inherits the global default. */\n inheritServer(name: string): Promise<McpServerStatus>;\n /**\n * Disable or enable all servers at once. Project scope records an explicit\n * override for every currently configured server. Global scope sets/clears a\n * persisted all-MCP kill switch (and, when enabling, also clears globally\n * disabled server names). Persisted like {@link setServerDisabled}.\n */\n setAllDisabled(disabled: boolean, options?: { global?: boolean }): Promise<void>;\n /** Clear every explicit project override so all servers inherit global defaults. */\n inheritAllServers(): Promise<void>;\n /** Names of configured servers that are currently disabled (any scope). */\n getDisabledServers(): string[];\n /** Whether all MCP is disabled globally (across every project). */\n isAllDisabledGlobally(): boolean;\n /** Disconnect from all MCP servers and clean up. */\n disconnect(): Promise<void>;\n /** Get all tools from connected MCP servers (namespaced as serverName_toolName). */\n getTools(): Record<string, any>;\n /** Check if any MCP servers are configured (or skipped). */\n hasServers(): boolean;\n /** Get status of all servers. */\n getServerStatuses(): McpServerStatus[];\n /** Get servers that were skipped during config loading. */\n getSkippedServers(): McpSkippedServer[];\n /** Get config file paths for display. */\n getConfigPaths(): { project: string; global: string; claude: string };\n /** Get the merged config. */\n getConfig(): McpConfig;\n /** Get captured stderr logs for a server. */\n getServerLogs(name: string): string[];\n}\n\nfunction getTransport(cfg: McpServerConfig): 'stdio' | 'http' {\n return 'url' in cfg ? 'http' : 'stdio';\n}\n\nclass FileOAuthStorage implements OAuthStorage {\n constructor(private filePath: string) {}\n\n get(key: string): string | undefined {\n return this.read()[key];\n }\n\n set(key: string, value: string): void {\n const data = this.read();\n data[key] = value;\n this.write(data);\n }\n\n delete(key: string): void {\n const data = this.read();\n delete data[key];\n this.write(data);\n }\n\n private read(): Record<string, string> {\n if (!existsSync(this.filePath)) return {};\n try {\n return JSON.parse(readFileSync(this.filePath, 'utf-8')) as Record<string, string>;\n } catch {\n return {};\n }\n }\n\n private write(data: Record<string, string>): void {\n const dir = dirname(this.filePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n const tmpPath = `${this.filePath}.tmp`;\n writeFileSync(tmpPath, JSON.stringify(data, null, 2), { encoding: 'utf-8', mode: 0o600 });\n renameSync(tmpPath, this.filePath);\n }\n}\n\n/**\n * Zero-config OAuth defaults for servers with a bare `url` entry. The client\n * identifies itself by Mastra Code's Client ID Metadata Document URL, so no\n * `clientId` is needed.\n */\nconst DEFAULT_OAUTH_CONFIG: McpHttpOAuthConfig = { redirectUrl: DEFAULT_OAUTH_REDIRECT_URL };\n\nfunction getOAuthStoragePath(projectDir: string, name: string, cfg: McpHttpServerConfig): string {\n // The fingerprint always uses the resolved redirect URL so a bare `url`\n // entry keeps the same token file before and after zero-config provisioning.\n const key = JSON.stringify({\n projectDir,\n name,\n url: cfg.url,\n redirectUrl: resolveOAuthRedirectUrl(cfg.oauth),\n clientId: cfg.oauth?.clientId,\n scopes: cfg.oauth?.scopes ?? [],\n });\n return join(getAppDataDir(), 'mcp-oauth', `${getStorageKeyFingerprint(key)}.json`);\n}\n\nfunction getStorageKeyFingerprint(value: string): string {\n let fingerprint = 0xcbf29ce484222325n;\n for (let i = 0; i < value.length; i += 1) {\n fingerprint ^= BigInt(value.charCodeAt(i));\n fingerprint = BigInt.asUintN(64, fingerprint * 0x100000001b3n);\n }\n return fingerprint.toString(16).padStart(16, '0');\n}\n\ntype McpModule = typeof import('@mastra/mcp');\nlet mcpModule: McpModule | undefined;\n\n/** `@mastra/mcp` and the MCP SDK (~12 MB) load with the first server that connects, not with every session. */\nasync function loadMcpModule(): Promise<McpModule> {\n mcpModule ??= await import('@mastra/mcp');\n return mcpModule;\n}\n\n/** For code that only runs once a client exists, so the module is already loaded. */\nfunction loadedMcpModule(): McpModule {\n if (!mcpModule) throw new Error('@mastra/mcp is not loaded yet');\n return mcpModule;\n}\n\n/**\n * Create an MCP manager that wraps MCPClient with config-file discovery\n * and per-server status tracking.\n */\nexport function createMcpManager(\n projectDir: string,\n configDirName = DEFAULT_CONFIG_DIR,\n extraServers?: Record<string, McpServerConfig>,\n externalDiscovery?: ExternalMcpDiscoveryOptions,\n): McpManager {\n /** Merge programmatic servers into a base config (highest priority). */\n const applyExtraServers = (base: McpConfig): McpConfig => {\n if (!extraServers || Object.keys(extraServers).length === 0) return base;\n return { ...base, mcpServers: { ...base.mcpServers, ...extraServers } };\n };\n\n let config = applyExtraServers(loadMcpConfig(projectDir, configDirName, externalDiscovery));\n let projectServerOverrides = new Map<string, McpProjectServerOverride>(\n Object.entries(loadProjectServerOverrides(projectDir)),\n );\n let globalDisableState = loadGlobalDisableState();\n let globallyDisabledServers = new Set(globalDisableState.disabledServers);\n\n /** Whether a server is disabled after applying the kill switch, project override, and global default. */\n const isDisabled = (name: string): boolean => {\n if (globalDisableState.allDisabled) return true;\n const projectOverride = projectServerOverrides.get(name);\n if (projectOverride) return projectOverride === 'disabled';\n return globallyDisabledServers.has(name);\n };\n\n /** Which scope currently disables a server. The global kill switch remains absolute. */\n const disabledScopeOf = (name: string): 'project' | 'global' | undefined => {\n if (globalDisableState.allDisabled) return 'global';\n const projectOverride = projectServerOverrides.get(name);\n if (projectOverride === 'disabled') return 'project';\n if (!projectOverride && globallyDisabledServers.has(name)) return 'global';\n return undefined;\n };\n let client: MCPClient | null = null;\n let serverDefs: Record<string, MastraMCPServerDefinition> = {};\n let tools: Record<string, any> = {};\n let serverStatuses = new Map<string, McpServerStatus>();\n let stderrLogs = new Map<string, string[]>();\n let initialized = false;\n\n /** Per-server handlers that receive the OAuth authorization URL during authenticateServer(). */\n const authUrlHandlers = new Map<string, (url: string) => void>();\n\n /**\n * Servers with an OAuth authorization flow currently in flight. Owned by the\n * manager (not the TUI) so the state survives a `/mcp` selector being closed\n * and reopened — the reopened selector reads it back off the server status and\n * can still offer \"Cancel authentication\".\n */\n const authenticatingServers = new Set<string>();\n\n /**\n * Servers whose in-flight authentication was cancelled by the caller. Set by\n * cancelServerAuthentication() so the resolving authenticateServer() call can\n * mark its failed status as a deliberate cancel rather than a genuine failure.\n * This lives on the manager (not the TUI selector) so the signal survives the\n * selector being closed and reopened mid-flow.\n */\n const cancelledAuthServers = new Set<string>();\n\n /** Overlay manager-owned state onto a status snapshot. */\n const withManagerState = (status: McpServerStatus): McpServerStatus => ({\n ...status,\n ...(authenticatingServers.has(status.name) ? { authenticating: true } : {}),\n ...(projectServerOverrides.has(status.name) ? { projectOverride: projectServerOverrides.get(status.name) } : {}),\n globalDefault: globallyDisabledServers.has(status.name) ? 'disabled' : 'enabled',\n globalKillSwitch: globalDisableState.allDisabled,\n });\n\n const MAX_STDERR_LINES = 200;\n\n /** Hook into a server's stderr stream and buffer its output. */\n function captureStderr(serverName: string): void {\n if (!client || typeof client.getServerStderr !== 'function') return;\n const stream = client.getServerStderr(serverName);\n if (!stream) return;\n\n let buffer = '';\n const lines = stderrLogs.get(serverName) ?? [];\n stderrLogs.set(serverName, lines);\n\n stream.on('data', (chunk: Buffer) => {\n buffer += chunk.toString();\n const parts = buffer.split('\\n');\n // Last element is incomplete line (or empty if ended with \\n)\n buffer = parts.pop()!;\n for (const line of parts) {\n if (line.trim()) {\n lines.push(line);\n if (lines.length > MAX_STDERR_LINES) {\n lines.shift();\n }\n }\n }\n });\n\n stream.on('end', () => {\n if (buffer.trim()) {\n lines.push(buffer);\n if (lines.length > MAX_STDERR_LINES) {\n lines.shift();\n }\n }\n });\n }\n\n function createOAuthProvider(name: string, cfg: McpHttpServerConfig) {\n // Bare `url` entries get no eager provider — auth is provisioned lazily\n // when the user authenticates — unless a previous session already stored\n // OAuth state for this server, in which case the provider is needed to\n // attach the persisted tokens on connect.\n const oauth =\n cfg.oauth ?? (existsSync(getOAuthStoragePath(projectDir, name, cfg)) ? DEFAULT_OAUTH_CONFIG : undefined);\n if (!oauth) return undefined;\n\n // redirectUrl is optional in the user-supplied config; resolve the stable\n // default (or the `callbackPort` shorthand, for programmatically registered\n // servers that bypass config parsing) so provider metadata always carries\n // a concrete URL.\n const redirectUrl = resolveOAuthRedirectUrl(oauth);\n\n // Without a pre-registered clientId the client is identified by Mastra\n // Code's Client ID Metadata Document: the document URL is the client_id and\n // the authorization server fetches it, so nothing is registered per server.\n const clientInformation = oauth.clientId\n ? ({\n client_id: oauth.clientId,\n ...(oauth.clientSecret ? { client_secret: oauth.clientSecret } : {}),\n } satisfies OAuthClientInformation)\n : undefined;\n const clientMetadataUrl = clientInformation ? undefined : MASTRA_CODE_CLIENT_METADATA_URL;\n\n const { MCPOAuthClientProvider } = loadedMcpModule();\n return new MCPOAuthClientProvider({\n redirectUrl,\n clientMetadata: {\n ...(clientMetadataUrl ? { client_id: clientMetadataUrl } : {}),\n redirect_uris: [redirectUrl],\n client_name: oauth.clientName ?? (clientMetadataUrl ? 'Mastra Code' : `Mastra Code MCP ${name}`),\n grant_types: ['authorization_code', 'refresh_token'],\n response_types: ['code'],\n ...(oauth.scopes?.length ? { scope: oauth.scopes.join(' ') } : {}),\n },\n clientInformation,\n clientMetadataUrl,\n storage: new FileOAuthStorage(getOAuthStoragePath(projectDir, name, cfg)),\n onRedirectToAuthorization: url => {\n authUrlHandlers.get(name)?.(url.toString());\n },\n });\n }\n\n function buildServerDefs(servers: Record<string, McpServerConfig>): Record<string, MastraMCPServerDefinition> {\n const defs: Record<string, MastraMCPServerDefinition> = {};\n for (const [name, cfg] of Object.entries(servers)) {\n if ('url' in cfg) {\n const httpCfg = cfg as McpHttpServerConfig;\n defs[name] = {\n url: new URL(httpCfg.url),\n requestInit: httpCfg.headers ? { headers: httpCfg.headers } : undefined,\n authProvider: createOAuthProvider(name, httpCfg),\n };\n } else {\n defs[name] = {\n command: cfg.command,\n args: cfg.args,\n env: cfg.env,\n ...(cfg.cwd ? { cwd: cfg.cwd } : {}),\n stderr: 'pipe',\n };\n }\n }\n return defs;\n }\n\n /** Seed a `disabled` status for every disabled server so it stays visible. */\n function setDisabledStatuses(): void {\n for (const [name, cfg] of Object.entries(config.mcpServers ?? {})) {\n const scope = disabledScopeOf(name);\n if (!scope) continue;\n serverStatuses.set(name, {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(cfg),\n disabled: true,\n disabledScope: scope,\n });\n }\n }\n\n async function connectAndCollectTools(): Promise<void> {\n setDisabledStatuses();\n\n const servers = Object.fromEntries(Object.entries(config.mcpServers ?? {}).filter(([name]) => !isDisabled(name)));\n if (Object.keys(servers).length === 0) {\n return;\n }\n\n // Pre-populate statuses as \"connecting\" so callers can see in-progress state\n const serverNames = Object.keys(servers);\n for (const name of serverNames) {\n serverStatuses.set(name, {\n name,\n connected: false,\n connecting: true,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(servers[name]!),\n });\n }\n\n const { MCPClient } = await loadMcpModule();\n serverDefs = buildServerDefs(servers);\n client = new MCPClient({\n id: 'mastra-code-mcp',\n servers: serverDefs,\n timeout: MASTRACODE_MCP_TIMEOUT_MS,\n });\n\n // Use listToolsetsWithErrors() to get tools grouped by server name,\n // plus per-server error messages for servers that failed to connect.\n\n try {\n const { toolsets, errors } = await client.listToolsetsWithErrors();\n const typedToolsets = toolsets as Record<string, Record<string, any>>;\n\n // Flatten toolsets into the namespaced tools map (serverName_toolName)\n for (const [serverName, serverTools] of Object.entries(typedToolsets)) {\n for (const [toolName, toolConfig] of Object.entries(serverTools)) {\n tools[`${serverName}_${toolName}`] = toolConfig;\n }\n }\n\n for (const name of serverNames) {\n const serverTools = typedToolsets[name];\n if (serverTools && Object.keys(serverTools).length > 0) {\n const toolNames = Object.keys(serverTools).map(t => `${name}_${t}`);\n serverStatuses.set(name, {\n name,\n connected: true,\n toolCount: toolNames.length,\n toolNames,\n transport: getTransport(servers[name]!),\n });\n } else {\n // Server failed — use the real error from listToolsetsWithErrors()\n const error = errors[name] ?? 'Failed to connect';\n serverStatuses.set(name, {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(servers[name]!),\n error,\n ...(serverNeedsAuth(name, servers[name]!, error) ? { needsAuth: true } : {}),\n });\n }\n }\n\n // Capture stderr from all stdio servers (connected or failed)\n for (const name of serverNames) {\n captureStderr(name);\n }\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n\n for (const name of serverNames) {\n serverStatuses.set(name, {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(servers[name]!),\n error: errMsg,\n ...(serverNeedsAuth(name, servers[name]!, errMsg) ? { needsAuth: true } : {}),\n });\n }\n }\n }\n\n /**\n * Whether a failed HTTP server is blocked on OAuth authorization.\n *\n * Provider-backed servers report the exact state tracked by `@mastra/mcp`.\n * Bare `url` entries carry no provider until the user authenticates, so the\n * signal is a 401 in the connect error — surfaced either as the status text\n * or as the RFC 6750 `invalid_token` bearer error code in the response body.\n */\n function serverNeedsAuth(name: string, cfg: McpServerConfig, error?: string): boolean {\n if (getTransport(cfg) !== 'http') return false;\n if (client?.getServerAuthState?.(name) === 'needs-auth') return true;\n if (serverDefs[name]?.authProvider) return false;\n return error !== undefined && /\\b401\\b|unauthorized|invalid_token/i.test(error);\n }\n\n /**\n * Runs a single-server connect action (reconnect or authenticate), then\n * refreshes that server's tools and status from the client.\n */\n async function connectSingleServer(\n name: string,\n cfg: McpServerConfig,\n connect: () => Promise<unknown>,\n ): Promise<McpServerStatus> {\n const transport = getTransport(cfg);\n\n // Remove old tools for this server\n const prefix = `${name}_`;\n for (const key of Object.keys(tools)) {\n if (key.startsWith(prefix)) {\n delete tools[key];\n }\n }\n\n // Clear old logs and mark as connecting\n stderrLogs.delete(name);\n serverStatuses.set(name, {\n name,\n connected: false,\n connecting: true,\n toolCount: 0,\n toolNames: [],\n transport,\n });\n\n try {\n await connect();\n\n // Recapture stderr for the reconnected server\n captureStderr(name);\n\n // Fetch updated toolsets to get this server's tools\n const { toolsets, errors } = await client!.listToolsetsWithErrors();\n const serverTools = toolsets[name];\n const serverError = errors[name];\n\n if (serverError) {\n const status: McpServerStatus = {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport,\n error: serverError,\n ...(serverNeedsAuth(name, cfg, serverError) ? { needsAuth: true } : {}),\n };\n serverStatuses.set(name, status);\n return status;\n } else if (serverTools && Object.keys(serverTools).length > 0) {\n const toolNames = Object.keys(serverTools).map(t => `${name}_${t}`);\n for (const [toolName, toolConfig] of Object.entries(serverTools)) {\n tools[`${name}_${toolName}`] = toolConfig;\n }\n const status: McpServerStatus = {\n name,\n connected: true,\n toolCount: toolNames.length,\n toolNames,\n transport,\n };\n serverStatuses.set(name, status);\n return status;\n }\n const status: McpServerStatus = {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport,\n error: 'Failed to connect',\n };\n serverStatuses.set(name, status);\n return status;\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n const status: McpServerStatus = {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport,\n error: errMsg,\n ...(serverNeedsAuth(name, cfg, errMsg) ? { needsAuth: true } : {}),\n };\n serverStatuses.set(name, status);\n return status;\n }\n }\n\n async function disconnect(): Promise<void> {\n if (client) {\n try {\n await client.disconnect();\n } catch {\n // Ignore disconnect errors\n }\n client = null;\n }\n }\n\n /** Tear down all connections and reconnect every enabled server. */\n async function rebuildConnections(): Promise<void> {\n await disconnect();\n tools = {};\n serverStatuses = new Map();\n stderrLogs = new Map();\n initialized = false;\n await connectAndCollectTools();\n initialized = true;\n }\n\n function disabledStatus(name: string): McpServerStatus {\n const cfg = config.mcpServers?.[name];\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: cfg ? getTransport(cfg) : 'stdio',\n disabled: true,\n disabledScope: disabledScopeOf(name),\n };\n }\n\n // Read-merge-write persistence: re-read the persisted state and apply this\n // operation's delta on top, then adopt the merged result in memory. This\n // way a concurrent mastracode process's changes (e.g. another window\n // flipping the global kill switch) are never clobbered by this manager's\n // construction-time snapshot.\n function persistProjectDelta(mutate: (overrides: Map<string, McpProjectServerOverride>) => void): void {\n const fresh = new Map<string, McpProjectServerOverride>(Object.entries(loadProjectServerOverrides(projectDir)));\n mutate(fresh);\n projectServerOverrides = fresh;\n saveProjectServerOverrides(projectDir, Object.fromEntries(fresh));\n }\n\n function persistGlobalDelta(mutate: (state: { allDisabled: boolean; disabledServers: Set<string> }) => void): void {\n const onDisk = loadGlobalDisableState();\n const fresh = { allDisabled: onDisk.allDisabled, disabledServers: new Set(onDisk.disabledServers) };\n mutate(fresh);\n globallyDisabledServers = fresh.disabledServers;\n globalDisableState = { allDisabled: fresh.allDisabled, disabledServers: Array.from(fresh.disabledServers) };\n saveGlobalDisableState(globalDisableState);\n }\n\n return {\n async init() {\n if (initialized) return;\n await connectAndCollectTools();\n initialized = true;\n },\n\n async initInBackground(): Promise<McpInitResult> {\n await this.init();\n const statuses = Array.from(serverStatuses.values(), withManagerState);\n const connected = statuses.filter(s => s.connected);\n const failed = statuses.filter(s => !s.connected && !s.disabled);\n return {\n connected,\n failed,\n skipped: [...(config.skippedServers ?? [])],\n totalTools: connected.reduce((sum, s) => sum + s.toolCount, 0),\n };\n },\n\n async reload() {\n config = applyExtraServers(loadMcpConfig(projectDir, configDirName, externalDiscovery));\n projectServerOverrides = new Map(Object.entries(loadProjectServerOverrides(projectDir)));\n globalDisableState = loadGlobalDisableState();\n globallyDisabledServers = new Set(globalDisableState.disabledServers);\n await rebuildConnections();\n },\n\n async setServerDisabled(name: string, disabled: boolean, options?: { global?: boolean }): Promise<McpServerStatus> {\n if (!config.mcpServers?.[name]) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" not found in config`,\n };\n }\n\n const wasEffectivelyDisabled = isDisabled(name);\n\n if (options?.global) {\n persistGlobalDelta(state => {\n if (disabled) {\n state.disabledServers.add(name);\n } else {\n state.disabledServers.delete(name);\n }\n });\n } else {\n persistProjectDelta(overrides => {\n overrides.set(name, disabled ? 'disabled' : 'enabled');\n });\n }\n\n // Only rebuild connections when the server's effective state actually\n // flipped. State changes that only alter an inherited default or an\n // override beneath the global kill switch leave connections alone.\n if (isDisabled(name) !== wasEffectivelyDisabled) {\n await rebuildConnections();\n return withManagerState(serverStatuses.get(name) ?? disabledStatus(name));\n }\n return withManagerState(\n isDisabled(name) ? disabledStatus(name) : (serverStatuses.get(name) ?? disabledStatus(name)),\n );\n },\n\n async inheritServer(name: string): Promise<McpServerStatus> {\n if (!config.mcpServers?.[name]) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" not found in config`,\n };\n }\n\n const wasEffectivelyDisabled = isDisabled(name);\n persistProjectDelta(overrides => {\n overrides.delete(name);\n });\n if (isDisabled(name) !== wasEffectivelyDisabled) {\n await rebuildConnections();\n }\n return withManagerState(\n isDisabled(name) ? disabledStatus(name) : (serverStatuses.get(name) ?? disabledStatus(name)),\n );\n },\n\n async setAllDisabled(disabled: boolean, options?: { global?: boolean }): Promise<void> {\n const configuredNames = Object.keys(config.mcpServers ?? {});\n const effectiveBefore = configuredNames.filter(name => isDisabled(name)).join(',');\n if (options?.global) {\n persistGlobalDelta(state => {\n state.allDisabled = disabled;\n if (!disabled) {\n // Enabling globally also clears globally disabled server names so\n // \"/mcp enable all --global\" fully restores global defaults.\n state.disabledServers.clear();\n }\n });\n } else {\n persistProjectDelta(overrides => {\n for (const name of configuredNames) {\n overrides.set(name, disabled ? 'disabled' : 'enabled');\n }\n });\n }\n const effectiveAfter = configuredNames.filter(name => isDisabled(name)).join(',');\n if (effectiveAfter !== effectiveBefore) {\n await rebuildConnections();\n }\n },\n\n async inheritAllServers(): Promise<void> {\n const configuredNames = Object.keys(config.mcpServers ?? {});\n const effectiveBefore = configuredNames.filter(name => isDisabled(name)).join(',');\n persistProjectDelta(overrides => {\n overrides.clear();\n });\n const effectiveAfter = configuredNames.filter(name => isDisabled(name)).join(',');\n if (effectiveAfter !== effectiveBefore) {\n await rebuildConnections();\n }\n },\n\n getDisabledServers() {\n return Object.keys(config.mcpServers ?? {})\n .filter(name => isDisabled(name))\n .sort();\n },\n\n isAllDisabledGlobally() {\n return globalDisableState.allDisabled;\n },\n\n async reconnectServer(name: string): Promise<McpServerStatus> {\n if (isDisabled(name)) {\n return { ...disabledStatus(name), error: `Server \"${name}\" is disabled — enable it first` };\n }\n const cfg = config.mcpServers?.[name];\n if (!cfg) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" not found in config`,\n };\n }\n\n if (!client) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(cfg),\n error: 'MCP client not initialized',\n };\n }\n\n // Use MCPClient's per-server reconnect\n return connectSingleServer(name, cfg, () => client!.reconnectServer(name));\n },\n\n async authenticateServer(\n name: string,\n options?: { onAuthorizationUrl?: (url: string) => void; timeoutMs?: number },\n ): Promise<McpServerStatus> {\n const cfg = config.mcpServers?.[name];\n if (!cfg) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" not found in config`,\n };\n }\n\n if (isDisabled(name)) {\n return { ...disabledStatus(name), error: `Server \"${name}\" is disabled — enable it first` };\n }\n\n if (!client) {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: getTransport(cfg),\n error: 'MCP client not initialized',\n };\n }\n\n if (getTransport(cfg) !== 'http') {\n return {\n name,\n connected: false,\n toolCount: 0,\n toolNames: [],\n transport: 'stdio',\n error: `Server \"${name}\" uses stdio transport, which does not support OAuth`,\n };\n }\n\n // Zero-config provisioning: a bare `url` entry gets a provider with the\n // default redirect URL the first time the user authenticates. The Client\n // ID Metadata Document takes care of the client identity.\n //\n // NOTE: `serverDefs[name]` is the same object reference the MCPClient was\n // constructed with, and connectHttp reads `authProvider` live off it at\n // connect time, so mutating it here reaches the already-created client.\n // If MCPClient ever defensively copies its server config, zero-config auth\n // would need an explicit \"set this server's provider\" API instead.\n const def = serverDefs[name];\n if (def?.url && !def.authProvider) {\n def.authProvider = createOAuthProvider(name, { ...(cfg as McpHttpServerConfig), oauth: DEFAULT_OAUTH_CONFIG });\n }\n\n // Reject a concurrent second attempt for the same server. authUrlHandlers\n // has a single slot per server, so a second call with an onAuthorizationUrl\n // would overwrite the first caller's handler (which then never sees the\n // URL) and its finally would delete the handler out from under the other\n // in-flight call. Gate on authenticatingServers rather than authUrlHandlers\n // so callers without a URL handler are caught too. The underlying\n // client.authenticate already coalesces same-server calls into one flow.\n if (authenticatingServers.has(name)) {\n const current = serverStatuses.get(name);\n return {\n name,\n connected: current?.connected ?? false,\n connecting: current?.connecting,\n needsAuth: current?.needsAuth,\n toolCount: current?.toolCount ?? 0,\n toolNames: current?.toolNames ?? [],\n transport: current?.transport ?? getTransport(cfg),\n error: `Authentication for \"${name}\" is already in progress`,\n };\n }\n\n if (options?.onAuthorizationUrl) {\n authUrlHandlers.set(name, options.onAuthorizationUrl);\n }\n authenticatingServers.add(name);\n cancelledAuthServers.delete(name);\n try {\n const result = await connectSingleServer(name, cfg, () =>\n client!.authenticate(name, options?.timeoutMs === undefined ? undefined : { timeoutMs: options.timeoutMs }),\n );\n // A cancelled flow resolves with a failed status; mark it so callers can\n // distinguish a deliberate cancel from a genuine authentication failure.\n // Write the marker back to the durable status map (not just the returned\n // value) so a selector reopened after cancellation still sees it.\n const finalStatus =\n cancelledAuthServers.has(name) && !result.connected ? { ...result, cancelled: true } : result;\n serverStatuses.set(name, finalStatus);\n return finalStatus;\n } finally {\n authUrlHandlers.delete(name);\n authenticatingServers.delete(name);\n cancelledAuthServers.delete(name);\n }\n },\n\n async cancelServerAuthentication(name: string): Promise<boolean> {\n if (!client) {\n return false;\n }\n // Record the intent before aborting so the resolving authenticateServer()\n // call can tag its failed status as cancelled rather than failed.\n cancelledAuthServers.add(name);\n const cancelled = await client.cancelAuthentication(name);\n if (!cancelled) {\n cancelledAuthServers.delete(name);\n }\n return cancelled;\n },\n\n disconnect,\n\n getTools() {\n return { ...tools };\n },\n\n hasServers() {\n const hasConfigured = config.mcpServers !== undefined && Object.keys(config.mcpServers).length > 0;\n const hasSkipped = config.skippedServers !== undefined && config.skippedServers.length > 0;\n return hasConfigured || hasSkipped;\n },\n\n getServerStatuses() {\n return Array.from(serverStatuses.values(), withManagerState);\n },\n\n getSkippedServers() {\n return [...(config.skippedServers ?? [])];\n },\n\n getConfigPaths() {\n return {\n project: getProjectMcpPath(projectDir, configDirName),\n global: getGlobalMcpPath(configDirName),\n claude: getClaudeSettingsPath(projectDir),\n };\n },\n\n getConfig() {\n return config;\n },\n\n getServerLogs(name: string) {\n return [...(stderrLogs.get(name) ?? [])];\n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AiB;EAC1B;EAEA,oBAAoB;GAClB,OAAO,MAAM,KAAK,eAAe,OAAO,GAAG,gBAAgB;EAC7D;EAEA,oBAAoB;GAClB,OAAO,CAAC,GAAI,OAAO,kBAAkB,CAAC,CAAE;EAC1C;EAEA,iBAAiB;GACf,OAAO;IACL,SAAS,kBAAkB,YAAY,aAAa;IACpD,QAAQ,iBAAiB,aAAa;IACtC,QAAQ,sBAAsB,UAAU;GAC1C;EACF;EAEA,YAAY;GACV,OAAO;EACT;EAEA,cAAc,MAAc;GAC1B,OAAO,CAAC,GAAI,WAAW,IAAI,IAAI,KAAK,CAAC,CAAE;EACzC;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"request-sandbox-access.d.ts","sourceRoot":"","sources":["../../src/tools/request-sandbox-access.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2BH,eAAO,MAAM,wBAAwB,sKA6F5B,CAAC"}
1
+ {"version":3,"file":"request-sandbox-access.d.ts","sourceRoot":"","sources":["../../src/tools/request-sandbox-access.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2BH,eAAO,MAAM,wBAAwB,sKA4F5B,CAAC"}
@@ -64,7 +64,8 @@ const requestSandboxAccessTool = createTool({
64
64
  content: `Access granted: "${absolutePath}" has been added to allowed paths. You can now access files in this directory.`,
65
65
  isError: false
66
66
  };
67
- } else return {
67
+ }
68
+ return {
68
69
  content: `Access denied: The user declined access to "${absolutePath}".`,
69
70
  isError: false
70
71
  };
@@ -1 +1 @@
1
- {"version":3,"file":"request-sandbox-access.js","names":["os","path"],"sources":["../../src/tools/request-sandbox-access.ts"],"sourcesContent":["/**\n * request_access tool — requests permission to access a directory outside the project root.\n * The user can approve or deny the request via TUI dialog.\n */\n\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createTool } from '@mastra/core/tools';\nimport { LocalFilesystem } from '@mastra/core/workspace';\nimport { z } from 'zod';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathAllowed, getAllowedPathsFromContext } from './utils.js';\n\nfunction expandTilde(p: string): string {\n if (p === '~') return os.homedir();\n if (p.startsWith('~/') || p.startsWith('~\\\\')) return path.join(os.homedir(), p.slice(2));\n return p;\n}\n\ntype RequestSandboxAccessInput = {\n path: string;\n reason: string;\n};\n\nconst requestSandboxAccessInputSchema = z.object({\n path: z.string().min(1).describe('The absolute path to the directory you need access to.'),\n reason: z.string().min(1).describe('Brief explanation of why you need access to this directory.'),\n});\n\nexport const requestSandboxAccessTool = createTool({\n id: 'request_access',\n description: `Request permission to access a directory outside the current project. Use this when you need to read or write files in a directory that is not within the project root. The user will be prompted to approve or deny the request.`,\n inputSchema: requestSandboxAccessInputSchema,\n suspendSchema: z.object({\n kind: z.literal('sandbox_access_request'),\n path: z.string(),\n reason: z.string(),\n }),\n resumeSchema: z.union([z.string(), z.array(z.string())]),\n execute: async ({ path: requestedPath, reason }: RequestSandboxAccessInput, context: any) => {\n try {\n const agentControllerCtx = context?.requestContext?.get('controller') as\n | AgentControllerRequestContext<MastraCodeState>\n | undefined;\n\n // Resolve to absolute path (expand ~ first since Node path APIs don't handle it)\n const projectRoot = agentControllerCtx?.getState()?.projectPath ?? process.cwd();\n const expanded = expandTilde(requestedPath);\n const absolutePath = path.isAbsolute(expanded) ? expanded : path.resolve(projectRoot, expanded);\n\n // Check if already allowed\n const allowedPaths = getAllowedPathsFromContext(context);\n if (isPathAllowed(absolutePath, projectRoot, allowedPaths)) {\n return {\n content: `Access already granted: \"${absolutePath}\" is within the project root or allowed paths.`,\n isError: false,\n };\n }\n\n const suspend = context?.agent?.suspend ?? context?.suspend;\n const resumeData = context?.agent?.resumeData ?? context?.resumeData;\n\n // First pass: pause via the native tool-suspension primitive so the host can\n // prompt the user. The suspend payload carries the request details; the host\n // resumes with the user's answer as resume data.\n if (resumeData === undefined) {\n if (!suspend) {\n return {\n content: `Cannot request sandbox access: interactive context not available. The user should manually run /sandbox add ${absolutePath}`,\n isError: true,\n };\n }\n await suspend({ kind: 'sandbox_access_request', path: absolutePath, reason });\n return;\n }\n\n const answerText = Array.isArray(resumeData) ? resumeData.join(', ') : String(resumeData);\n const approved = answerText.toLowerCase().startsWith('y') || answerText.toLowerCase() === 'approve';\n if (approved) {\n // Persist to controller state first (and await it) so the value is\n // committed before the next tool call re-derives the workspace's\n // allowed paths from state. The workspace factory rebuilds the\n // filesystem allowlist from `sandboxAllowedPaths` on every call\n // (getDynamicWorkspace), so an unawaited setState would let that\n // rebuild clobber the in-turn widen below before the grant lands.\n const controllerState = agentControllerCtx?.getState();\n const currentAllowed = (controllerState?.sandboxAllowedPaths as string[] | undefined) ?? [];\n const nextAllowed = currentAllowed.includes(absolutePath) ? currentAllowed : [...currentAllowed, absolutePath];\n if (!currentAllowed.includes(absolutePath)) {\n await agentControllerCtx?.setState({\n sandboxAllowedPaths: nextAllowed,\n });\n }\n\n // Also update the live workspace filesystem immediately so tools in\n // the same turn (e.g. `view`) can access the path without waiting for\n // a fresh workspace build. The resolved workspace is carried on the\n // controller request context — the tool-execution context does not expose\n // it — so read the filesystem from there.\n const fs = agentControllerCtx?.workspace?.filesystem ?? context?.workspace?.filesystem;\n if (fs instanceof LocalFilesystem) {\n fs.setAllowedPaths((prev: readonly string[]) => [...prev, absolutePath]);\n }\n\n return {\n content: `Access granted: \"${absolutePath}\" has been added to allowed paths. You can now access files in this directory.`,\n isError: false,\n };\n } else {\n return {\n content: `Access denied: The user declined access to \"${absolutePath}\".`,\n isError: false,\n };\n }\n } catch (error) {\n const msg = error instanceof Error ? error.message : 'Unknown error';\n return {\n content: `Failed to request sandbox access: ${msg}`,\n isError: true,\n };\n }\n },\n} as any);\n"],"mappings":";;;;;;;;;;;AAcA,SAAS,YAAY,GAAmB;CACtC,IAAI,MAAM,KAAK,OAAOA,KAAG,QAAQ;CACjC,IAAI,EAAE,WAAW,IAAI,KAAK,EAAE,WAAW,KAAK,GAAG,OAAOC,OAAK,KAAKD,KAAG,QAAQ,GAAG,E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I,OAAO,UAAU;GAExF,IADiB,WAAW,YAAY,CAAC,CAAC,WAAW,GAAG,KAAK,WAAW,YAAY,MAAM,WAC5E;IAQZ,MAAM,kBADkB,oBAAoB,SAAS,EAAA,EACZ,uBAAgD,CAAC;IAC1F,MAAM,cAAc,eAAe,SAAS,YAAY,IAAI,iBAAiB,CAAC,GAAG,gBAAgB,YAAY;IAC7G,IAAI,CAAC,eAAe,SAAS,YAAY,GACvC,MAAM,oBAAoB,SAAS,EACjC,qBAAqB,YACvB,CAAC;IAQH,MAAM,KAAK,oBAAoB,WAAW,cAAc,SAAS,WAAW;IAC5E,IAAI,cAAc,iBAChB,GAAG,iBAAiB,SAA4B,CAAC,GAAG,MAAM,YAAY,CAAC;IAGzE,OAAO;KACL,SAAS,oBAAoB,aAAa;KAC1C,SAAS;IACX;GACF,OACE,OAAO;IACL,SAAS,+CAA+C,aAAa;IACrE,SAAS;GACX;EAEJ,SAAS,OAAO;GAEd,OAAO;IACL,SAAS,qCAFC,iBAAiB,QAAQ,MAAM,UAAU;IAGnD,SAAS;GACX;EACF;CACF;AACF,CAAQ"}
1
+ {"version":3,"file":"request-sandbox-access.js","names":["os","path"],"sources":["../../src/tools/request-sandbox-access.ts"],"sourcesContent":["/**\n * request_access tool — requests permission to access a directory outside the project root.\n * The user can approve or deny the request via TUI dialog.\n */\n\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createTool } from '@mastra/core/tools';\nimport { LocalFilesystem } from '@mastra/core/workspace';\nimport { z } from 'zod';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathAllowed, getAllowedPathsFromContext } from './utils.js';\n\nfunction expandTilde(p: string): string {\n if (p === '~') return os.homedir();\n if (p.startsWith('~/') || p.startsWith('~\\\\')) return path.join(os.homedir(), p.slice(2));\n return p;\n}\n\ntype RequestSandboxAccessInput = {\n path: string;\n reason: string;\n};\n\nconst requestSandboxAccessInputSchema = z.object({\n path: z.string().min(1).describe('The absolute path to the directory you need access to.'),\n reason: z.string().min(1).describe('Brief explanation of why you need access to this directory.'),\n});\n\nexport const requestSandboxAccessTool = createTool({\n id: 'request_access',\n description: `Request permission to access a directory outside the current project. Use this when you need to read or write files in a directory that is not within the project root. The user will be prompted to approve or deny the request.`,\n inputSchema: requestSandboxAccessInputSchema,\n suspendSchema: z.object({\n kind: z.literal('sandbox_access_request'),\n path: z.string(),\n reason: z.string(),\n }),\n resumeSchema: z.union([z.string(), z.array(z.string())]),\n execute: async ({ path: requestedPath, reason }: RequestSandboxAccessInput, context: any) => {\n try {\n const agentControllerCtx = context?.requestContext?.get('controller') as\n | AgentControllerRequestContext<MastraCodeState>\n | undefined;\n\n // Resolve to absolute path (expand ~ first since Node path APIs don't handle it)\n const projectRoot = agentControllerCtx?.getState()?.projectPath ?? process.cwd();\n const expanded = expandTilde(requestedPath);\n const absolutePath = path.isAbsolute(expanded) ? expanded : path.resolve(projectRoot, expanded);\n\n // Check if already allowed\n const allowedPaths = getAllowedPathsFromContext(context);\n if (isPathAllowed(absolutePath, projectRoot, allowedPaths)) {\n return {\n content: `Access already granted: \"${absolutePath}\" is within the project root or allowed paths.`,\n isError: false,\n };\n }\n\n const suspend = context?.agent?.suspend ?? context?.suspend;\n const resumeData = context?.agent?.resumeData ?? context?.resumeData;\n\n // First pass: pause via the native tool-suspension primitive so the host can\n // prompt the user. The suspend payload carries the request details; the host\n // resumes with the user's answer as resume data.\n if (resumeData === undefined) {\n if (!suspend) {\n return {\n content: `Cannot request sandbox access: interactive context not available. The user should manually run /sandbox add ${absolutePath}`,\n isError: true,\n };\n }\n await suspend({ kind: 'sandbox_access_request', path: absolutePath, reason });\n return;\n }\n\n const answerText = Array.isArray(resumeData) ? resumeData.join(', ') : String(resumeData);\n const approved = answerText.toLowerCase().startsWith('y') || answerText.toLowerCase() === 'approve';\n if (approved) {\n // Persist to controller state first (and await it) so the value is\n // committed before the next tool call re-derives the workspace's\n // allowed paths from state. The workspace factory rebuilds the\n // filesystem allowlist from `sandboxAllowedPaths` on every call\n // (getDynamicWorkspace), so an unawaited setState would let that\n // rebuild clobber the in-turn widen below before the grant lands.\n const controllerState = agentControllerCtx?.getState();\n const currentAllowed = (controllerState?.sandboxAllowedPaths as string[] | undefined) ?? [];\n const nextAllowed = currentAllowed.includes(absolutePath) ? currentAllowed : [...currentAllowed, absolutePath];\n if (!currentAllowed.includes(absolutePath)) {\n await agentControllerCtx?.setState({\n sandboxAllowedPaths: nextAllowed,\n });\n }\n\n // Also update the live workspace filesystem immediately so tools in\n // the same turn (e.g. `view`) can access the path without waiting for\n // a fresh workspace build. The resolved workspace is carried on the\n // controller request context — the tool-execution context does not expose\n // it — so read the filesystem from there.\n const fs = agentControllerCtx?.workspace?.filesystem ?? context?.workspace?.filesystem;\n if (fs instanceof LocalFilesystem) {\n fs.setAllowedPaths((prev: readonly string[]) => [...prev, absolutePath]);\n }\n\n return {\n content: `Access granted: \"${absolutePath}\" has been added to allowed paths. You can now access files in this directory.`,\n isError: false,\n };\n }\n return {\n content: `Access denied: The user declined access to \"${absolutePath}\".`,\n isError: false,\n };\n } catch (error) {\n const msg = error instanceof Error ? error.message : 'Unknown error';\n return {\n content: `Failed to request sandbox access: ${msg}`,\n isError: true,\n };\n }\n },\n} as any);\n"],"mappings":";;;;;;;;;;;AAcA,SAAS,YAAY,GAAmB;CACtC,IAAI,MAAM,KAAK,OAAOA,KAAG,QAAQ;CACjC,IAAI,EAAE,WAAW,IAAI,KAAK,EAAE,WAAW,KAAK,GAAG,OAAOC,OAAK,KAAKD,KAAG,QAAQ,GAAG,EAAE,MAAM,CAAC,CAAC;CACxF,OAAO;AACT;AAOA,MAAM,kCAAkC,EAAE,OAAO;CAC/C,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,wDAAwD;CACzF,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,6DAA6D;AAClG,CAAC;AAED,MAA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I,CAAC,eAAe,SAAS,YAAY,GACvC,MAAM,oBAAoB,SAAS,EACjC,qBAAqB,YACvB,CAAC;IAQH,MAAM,KAAK,oBAAoB,WAAW,cAAc,SAAS,WAAW;IAC5E,IAAI,cAAc,iBAChB,GAAG,iBAAiB,SAA4B,CAAC,GAAG,MAAM,YAAY,CAAC;IAGzE,OAAO;KACL,SAAS,oBAAoB,aAAa;KAC1C,SAAS;IACX;GACF;GACA,OAAO;IACL,SAAS,+CAA+C,aAAa;IACrE,SAAS;GACX;EACF,SAAS,OAAO;GAEd,OAAO;IACL,SAAS,qCAFC,iBAAiB,QAAQ,MAAM,UAAU;IAGnD,SAAS;GACX;EACF;CACF;AACF,CAAQ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/code-sdk",
3
- "version": "1.16.0-alpha.8",
3
+ "version": "1.16.0",
4
4
  "description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -62,20 +62,20 @@
62
62
  "vscode-languageserver-protocol": "^3.18.5",
63
63
  "yaml": "^2.9.1",
64
64
  "zod": "^4.6.7",
65
- "@mastra/agent-browser": "0.5.5-alpha.0",
66
- "@mastra/duckdb": "1.16.0-alpha.2",
67
- "@mastra/fastembed": "1.3.5-alpha.3",
65
+ "@mastra/agent-browser": "0.5.5",
66
+ "@mastra/duckdb": "1.16.0",
67
+ "@mastra/fastembed": "1.3.5",
68
+ "@mastra/libsql": "1.27.1",
68
69
  "@mastra/github-signals": "0.5.2",
69
- "@mastra/libsql": "1.27.1-alpha.1",
70
- "@mastra/client-js": "1.57.0-alpha.7",
71
- "@mastra/mcp": "2.6.0-alpha.3",
72
- "@mastra/memory": "1.39.1-alpha.3",
73
- "@mastra/observability": "1.22.0-alpha.3",
74
- "@mastra/parallel": "0.1.4-alpha.0",
75
- "@mastra/pg": "1.33.0-alpha.3",
76
- "@mastra/stagehand": "0.3.7-alpha.1",
70
+ "@mastra/mcp": "2.6.0",
71
+ "@mastra/parallel": "0.1.4",
72
+ "@mastra/memory": "1.39.1",
73
+ "@mastra/observability": "1.22.0",
74
+ "@mastra/client-js": "1.57.0",
75
+ "@mastra/pg": "1.33.0",
76
+ "@mastra/stagehand": "0.3.7",
77
77
  "@mastra/tavily": "1.1.3",
78
- "@mastra/schema-compat": "1.3.17-alpha.0"
78
+ "@mastra/schema-compat": "1.3.17"
79
79
  },
80
80
  "devDependencies": {
81
81
  "@copilotkit/aimock": "^1.46.0",
@@ -86,10 +86,10 @@
86
86
  "tsx": "^4.23.15",
87
87
  "typescript": "^6.0.3",
88
88
  "vitest": "4.1.12",
89
- "@internal/lint": "0.0.145",
90
- "@internal/types-builder": "0.0.120",
91
- "@internal/workspace-test-utils": "0.0.89",
92
- "@mastra/core": "1.80.0-alpha.7"
89
+ "@internal/types-builder": "0.0.121",
90
+ "@internal/workspace-test-utils": "0.0.90",
91
+ "@mastra/core": "1.80.0",
92
+ "@internal/lint": "0.0.146"
93
93
  },
94
94
  "peerDependencies": {
95
95
  "@mastra/core": ">=1.80.0-0 <2.0.0-0"