import { clientProjectConfigurationPaths, isKiroAgentConfigurationPath, } from "./SupportedClientLocations.js"; import { err, ok, type Result } from "../domain/result.js"; import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { readRegularFileText } from "../process/RegularFileRead.js"; import { clientServerRowsReplace, effectiveClientServer, parseClientConfiguration, type ClientConfigurationDocument, type ClientConfigurationFormat, type ClientInlineConfiguration, type ClientRegistrationDialect, } from "./ClientConfigurationDocument.js"; import { clientConfigurationValuesEqual } from "./ClientConfigurationValues.js"; import type { SetupClient } from "./SupportedClients.js"; import { ClientRegistrationEnvironmentShapeError, clientRegistrationEnvironment, } from "./ClientRegistrationEnvironment.js"; import type { ArtifactResourceScope } from "../resources/index.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { isRecord } from "../kernel/isRecord.js"; import { errorMessage } from "../kernel/errorMessage.js"; import { lstat, realpath, stat } from "node:fs/promises"; import { posix, win32 } from "node:path"; import { isQualifiedCallerPath } from "../filesystem/callerPath.js"; import { canonicalCallerPath } from "../filesystem/canonicalCallerPath.js"; import { isAbsentClientConfigPath, isEnoentError } from "./ClientConfigPath.js"; import { gitWorktreeRootOrCwd } from "./McpRegistrationGit.js"; export type ClientRegistrationScope = "user" | "project"; /** * A parsed layer retains its path so rereading the write target replaces only * that layer. An inline layer has no path, so nothing can select it for writing. */ export type ClientConfigurationSource = ClientConfigurationDocument & ( | { readonly sourcePath: string; readonly inlineOrigin?: undefined; readonly scope?: ClientRegistrationScope; } | { readonly sourcePath?: undefined; readonly inlineOrigin: ClientInlineConfiguration["origin"]; readonly scope?: undefined; readonly caution?: string; } ); type ProjectConfigurationSource = ClientConfigurationSource & { readonly sourcePath: string; readonly scope: "project"; }; const invalidEnvironment = ( path: string, error: ConfigurationError, overrides: Readonly> | undefined, platform: NodeJS.Platform, ): ClientConfigurationFileError => { const constraints = error.settings .map(({ setting, constraint }) => `${setting}: ${constraint}`) .join("; "); const overrideNames = new Set( Object.keys(overrides ?? {}).map((name) => platform === "win32" ? name.toUpperCase() : name, ), ); const overrideSettings = error.settings .map(({ setting }) => setting) .filter((setting) => overrideNames.has(platform === "win32" ? setting.toUpperCase() : setting), ); const location = overrideSettings.length > 0 ? `The proposed registration environment includes launch overrides (${overrideSettings.join(", ")}) that do not satisfy the effective REA configuration constraints` : overrideNames.size > 0 ? `The effective REA server environment for ${path} is invalid; check the client configuration and proposed launch overrides` : `Configuration ${path} has an invalid REA server environment`; return { kind: "malformed", path, detail: `${location}: ${constraints}${constraints.endsWith(".") ? "" : "."} ${overrideNames.size === 0 ? "Repair it" : "Check the launch environment and any existing registration settings"} before retrying.`, }; }; /** A named source failure that setup can explain without losing the bad path. */ export interface ClientConfigurationFileError { readonly kind: | "unreadable" | "malformed" | "unresolved" | "unknown_project_root"; readonly path: string; readonly detail: string; readonly cleanupFailure?: RegularFileCleanupFailure; readonly scope?: ClientRegistrationScope; } type ClientConfigurationLocation = Pick< SetupClient, | "name" | "registrationProfile" | "configPath" | "configPaths" | "configPathError" | "readOnlyLowerLayers" | "inlineConfiguration" | "readUpperLayers" > & { readonly format?: ClientConfigurationFormat }; interface ClientConfigurationReadOptions { readonly writeOverrides?: Readonly>; /** The writer's verified snapshot of the selected path, which must not be reopened here. */ readonly targetDocument?: ClientConfigurationDocument; } const configurationEnvironmentFailure = ( client: ClientConfigurationLocation, platform: NodeJS.Platform, { path, document, validation, overrides, }: { readonly path: string; readonly document: ClientConfigurationDocument | undefined; readonly validation: "fragment" | "effective"; readonly overrides?: Readonly> | undefined; }, ): ClientConfigurationFileError | undefined => { const environment = clientRegistrationEnvironment( document, client, platform, overrides, validation, ); return environment.ok ? undefined : invalidEnvironment(path, environment.error, overrides, platform); }; /** Preserve named read failures and distinguish a missing source from an empty file. */ export const readConfigurationText = async ( path: string, resources?: ArtifactResourceScope, ): Promise> => { try { return ok( await readRegularFileText( path, resources === undefined ? {} : { resources }, ), ); } catch (cause: unknown) { if (isEnoentError(cause)) return ok(undefined); return err({ kind: "unreadable", path, detail: `Configuration ${path} could not be read: ${errorMessage(cause)}`, ...(cause instanceof RegularFileCleanupFailure ? { cleanupFailure: cause } : {}), }); } }; /** Read and parse one configuration at its source boundary. */ export const readConfigurationFile = async ( path: string, format: ClientConfigurationFormat | undefined, resources?: ArtifactResourceScope, ): Promise< Result > => { const source = await readConfigurationText(path, resources); if (!source.ok) return source; const content = source.value; if (content === undefined) return ok(undefined); const parsed = parseClientConfiguration(content, format); return parsed.ok ? parsed : err({ kind: "malformed", path, detail: `Configuration ${path} is malformed: ${parsed.error.detail}`, }); }; /** Read each layer; setup may validate its writable layer with proposed overrides. */ export const readClientConfigurationFiles = async ( client: ClientConfigurationLocation, resources: ArtifactResourceScope | undefined, platform: NodeJS.Platform, { writeOverrides, targetDocument }: ClientConfigurationReadOptions = {}, ): Promise< Result > => { const validateFragment = ( path: string, document: ClientConfigurationDocument, ) => configurationEnvironmentFailure(client, platform, { path, document, validation: "fragment", overrides: path === client.configPath ? writeOverrides : undefined, }); const deferFragmentValidation = client.format === "opencode" || client.name === "kiro"; const documents = await readUserConfigurationSources( client, resources, targetDocument, deferFragmentValidation ? undefined : (path, document) => // Goose can replace the environment of a read-only lower layer as a whole map. path === client.configPath || client.readOnlyLowerLayers !== true ? validateFragment(path, document) : undefined, ); if (!documents.ok) return documents; const effective = mergeClientConfigurationDocuments( documents.value, platform, client.name === "kiro", ); const upperAmbiguity = ambiguousOpenCodeUpperRow(effective, documents.value); if (upperAmbiguity !== undefined) return err(upperAmbiguity); if (deferFragmentValidation) { // A native row replaces its peers. Only a write target needs separate // fragment validation in that dialect. const replacesRows = client.name === "kiro" || clientServerRowsReplace(effective?.dialect); const writing = targetDocument !== undefined || writeOverrides !== undefined; for (const source of documents.value) { const path = source.sourcePath; if ( path === undefined || (replacesRows && !(writing && path === client.configPath)) ) continue; const failure = validateFragment(path, source); if (failure !== undefined) return err(failure); } } const failure = configurationEnvironmentFailure(client, platform, { path: client.configPath, document: effective, validation: "effective", overrides: writeOverrides, }); return failure === undefined ? documents : err(failure); }; /** The read-only layers above a client's files, as merge sources. */ export const inlineSources = ({ inlineConfiguration, }: Pick): readonly Extract< ClientConfigurationSource, { readonly inlineOrigin: string } >[] => inlineConfiguration?.documents.map((document) => ({ ...document, inlineOrigin: inlineConfiguration.origin, ...(inlineConfiguration.caution === undefined ? {} : { caution: inlineConfiguration.caution }), })) ?? []; /** A sentence to follow a message that relies on the read-only layers. */ export const inlineCaution = ({ inlineConfiguration, }: Pick): string => inlineConfiguration?.caution === undefined ? "" : ` ${inlineConfiguration.caution}`; /** The first path that is, or links to, a file REA may only read. */ export const reachedReadOnlyFile = async ( paths: readonly string[], readOnlyFiles: readonly string[], platform: NodeJS.Platform, ): Promise< { readonly path: string; readonly readOnlyFile: string } | undefined > => { // An unresolvable path keeps its spelling; reading it reports the cause. const destination = (path: string) => canonicalCallerPath(path).catch(() => path); const identity = (path: string) => stat(path, { bigint: true }).catch(() => undefined); const protectedFiles = await Promise.all( readOnlyFiles.map(async (path) => ({ path, destination: await destination(path), identity: await identity(path), })), ); for (const path of paths) { const canonical = await destination(path); const stat = await identity(path); const matched = protectedFiles.find( (file) => filesystemPathKey(file.destination, platform) === filesystemPathKey(canonical, platform) || (stat !== undefined && stat.ino !== 0n && file.identity?.ino === stat.ino && file.identity.dev === stat.dev), ); if (matched !== undefined) return { path, readOnlyFile: matched.path }; } return undefined; }; export const reachedReadOnlyFileDetail = ({ path, readOnlyFile, }: { readonly path: string; readonly readOnlyFile: string; }): string => `${path} reaches the system configuration file ${readOnlyFile}, which REA does not edit. Select a file that does not reach it.`; /** The client with its file-backed upper layers as they are now. */ export const currentUpperLayers = async < Client extends Pick< SetupClient, "configPath" | "inlineConfiguration" | "readUpperLayers" >, >( client: Client, resources?: ArtifactResourceScope, ): Promise> => { if (client.readUpperLayers === undefined) return ok(client); const read = await client.readUpperLayers(resources); if (!read.ok) return err({ kind: "unreadable", path: read.error.path, detail: read.error.message, }); const { inlineConfiguration: _selected, ...rest } = client; return ok({ ...(rest as Client), ...(read.value === undefined ? {} : { inlineConfiguration: read.value }), }); }; const readUserConfigurationSources = async ( client: ClientConfigurationLocation, resources: ArtifactResourceScope | undefined, targetDocument?: ClientConfigurationDocument, validate?: ( path: string, document: ClientConfigurationDocument, ) => ClientConfigurationFileError | undefined, ): Promise< Result > => { if (client.configPathError !== undefined) return err({ kind: "unreadable", path: client.configPath, detail: client.configPathError, }); const paths = client.configPaths ?? [client.configPath]; if (targetDocument !== undefined && !paths.includes(client.configPath)) return err({ kind: "unreadable", path: client.configPath, detail: "The selected configuration is missing from the native load order.", }); const documents: ClientConfigurationSource[] = []; for (const path of paths) { const document = path === client.configPath && targetDocument !== undefined ? ok(targetDocument) : await readConfigurationFile(path, client.format, resources); if (!document.ok) return document; if (document.value === undefined) continue; const failure = validate?.(path, document.value); if (failure !== undefined) return err(failure); documents.push({ ...document.value, sourcePath: path }); } // The inline layer is read-only and can replace lower file values. const upper = await currentUpperLayers(client, resources); if (!upper.ok) return upper; documents.push(...inlineSources(upper.value)); return ok(documents); }; /** Reuse admitted peers and substitute the candidate at every occurrence of the write target. */ export const admitClientConfigurationCandidate = ( client: ClientConfigurationLocation, sources: readonly ClientConfigurationSource[], candidate: ClientConfigurationDocument, platform: NodeJS.Platform, ): Result< ClientConfigurationDocument | undefined, ClientConfigurationFileError > => { const path = client.configPath; const fragment = configurationEnvironmentFailure(client, platform, { path, document: candidate, validation: "fragment", }); if (fragment !== undefined) return err(fragment); const effective = mergeClientConfigurationDocuments( sources.map((source) => (source.sourcePath === path ? candidate : source)), platform, ); const failure = configurationEnvironmentFailure(client, platform, { path, document: effective, validation: "effective", }); return failure === undefined ? ok(effective) : err(failure); }; /** Legacy layered configurations merge objects and replace arrays and scalars. */ const mergeConfigurationValue = (previous: unknown, next: unknown): unknown => { if (!isRecord(previous) || !isRecord(next)) return next; return Object.fromEntries( [...new Set([...Object.keys(previous), ...Object.keys(next)])].map( (key) => [ key, Object.hasOwn(next, key) ? mergeConfigurationValue(previous[key], next[key]) : previous[key], ], ), ); }; /** Native OpenCode dialect applies across all selected configuration layers. */ export const clientWriteDialect = ( dialect: ClientRegistrationDialect, sources: readonly ClientConfigurationDocument[], ): ClientRegistrationDialect => dialect === "opencode" && sources.some(({ dialect }) => dialect === "opencode_v2") ? "opencode_v2" : dialect; /** Interpret the write fragment using the effective client dialect, preserving peers. */ export const clientConfigurationForWrite = ( parsed: ClientConfigurationDocument, sources: readonly ClientConfigurationDocument[], ): Result => { if ( parsed.dialect !== "opencode" || clientWriteDialect(parsed.dialect, sources) !== "opencode_v2" ) return ok(parsed); if (Object.hasOwn(parsed.servers, "servers")) return err( new ConfigurationError( "A legacy OpenCode server named servers conflicts with the effective native server table. Repair this ambiguity before rerunning setup.", ), ); return ok({ ...parsed, dialect: "opencode_v2", serversPath: ["mcp", "servers"], servers: {}, legacyServers: parsed.servers, }); }; /** Project a client's effective user registration without modifying its source files. */ export const effectiveClientConfiguration = ( sources: readonly ClientConfigurationSource[], target: | { readonly client: Pick; readonly document: ClientConfigurationDocument | undefined; } | undefined, platform: NodeJS.Platform, ): ClientConfigurationDocument | undefined => { const documents = target === undefined ? sources : [ ...(target.client.configPaths ?? [target.client.configPath]).flatMap( (path) => { const document = path === target.client.configPath ? target.document : sources.find(({ sourcePath }) => sourcePath === path); return document === undefined ? [] : [document]; }, ), ...sources.filter(({ inlineOrigin }) => inlineOrigin !== undefined), ]; return mergeClientConfigurationDocuments(documents, platform); }; /** The client's read-only inline layers that set REA's entry. */ export const inlineRegistrationOrigins = ( client: Pick, ): readonly ClientInlineConfiguration["origin"][] => { const inline = client.inlineConfiguration; const name = PRODUCT_IDENTITY.mcpServerKey; return inline !== undefined && inline.documents.some( ({ servers, legacyServers }) => Object.hasOwn(servers, name) || Object.hasOwn(legacyServers, name), ) ? [inline.origin] : []; }; const upperLayerCaution = (sources: readonly ClientConfigurationSource[]) => { const caution = sources.find( ({ inlineOrigin }) => inlineOrigin !== undefined, ); return caution?.inlineOrigin !== undefined && caution.caution !== undefined ? { upperLayerCaution: caution.caution } : {}; }; const readOnlySourcePath = ( source: ClientConfigurationSource | undefined, ): string | undefined => source !== undefined && "readOnlyPath" in source && typeof source.readOnlyPath === "string" ? source.readOnlyPath : undefined; const overridingFileFact = ( active: readonly ServerDeclaration[], ): Pick< EffectiveClientRegistrationConfiguration, "overridingConfigPath" | "overridingLauncherPath" | "overridingActivationPath" > => { const path = readOnlySourcePath(active.at(-1)?.source); if (path === undefined) return {}; const launcher = readOnlySourcePath( active.findLast(declaresLauncher)?.source, ); const activation = readOnlySourcePath( active.findLast(declaresActivation)?.source, ); return { overridingConfigPath: path, ...(launcher === undefined ? {} : { overridingLauncherPath: launcher }), ...(activation === undefined ? {} : { overridingActivationPath: activation }), }; }; const ambiguousOpenCodeUpperRow = ( document: ClientConfigurationDocument | undefined, sources: readonly ClientConfigurationSource[], ): ClientConfigurationFileError | undefined => { if (document?.dialect !== "opencode") return undefined; const selected = serverDeclarations(sources).at(-1); const path = readOnlySourcePath(selected?.source); if ( selected === undefined || path === undefined || !declaresLauncher(selected) ) return undefined; const merged = effectiveClientServer(document, PRODUCT_IDENTITY.mcpServerKey); if (clientConfigurationValuesEqual(merged, selected.entry)) return undefined; return { kind: "unresolved", path, detail: `OpenCode V1 and V2 select different MCP settings from these legacy rows. Confirm the running OpenCode version and use its native server layout before changing the REA registration. The highest row is in ${path}.`, }; }; const declaresActivation = ({ entry }: ServerDeclaration): boolean => isRecord(entry) && ["disabled", "enabled", "enable"].some((key) => Object.hasOwn(entry, key)); /** * The inline layer that would change the REA registration setup writes as * `desired` into the write target, which setup cannot edit around. */ export const inlineRegistrationOverride = ( client: Pick, sources: readonly ClientConfigurationSource[], desired: unknown, platform: NodeJS.Platform, target?: ClientConfigurationDocument, ): ClientInlineConfiguration["origin"] | undefined => { const name = PRODUCT_IDENTITY.mcpServerKey; const inline = sources.filter( ({ inlineOrigin }) => inlineOrigin !== undefined, ); const declaring = inline.findLast( (layer) => Object.hasOwn(layer.servers, name) || Object.hasOwn(layer.legacyServers, name), ); if (declaring?.inlineOrigin === undefined) return undefined; const files = sources.filter(({ sourcePath }) => sourcePath !== undefined); const written = effectiveClientConfiguration( files, { client, document: { ...(target ?? declaring), servers: { [name]: desired }, legacyServers: {}, }, }, platform, ); const effective = mergeClientConfigurationDocuments( [...(written === undefined ? [] : [written]), ...inline], platform, ); const launched = (document: ClientConfigurationDocument | undefined) => document === undefined ? undefined : launchedRegistrationEntry( effectiveClientServer(document, name), document.environmentKey, platform, ); return clientConfigurationValuesEqual(launched(written), launched(effective)) ? undefined : declaring.inlineOrigin; }; /** * The string settings the inline layer declares in REA's entry environment, * or an empty record when no inline layer sets REA's entry. */ export const inlineRegistrationEnvironment = ( sources: readonly ClientConfigurationSource[], platform: NodeJS.Platform, ): Readonly> => { const upper = sources.filter( ({ inlineOrigin }) => inlineOrigin !== undefined, ); const document = mergeClientConfigurationDocuments(upper, platform); if (document === undefined) return {}; const entry = effectiveClientServer(document, PRODUCT_IDENTITY.mcpServerKey); const environment = isRecord(entry) ? entry[document.environmentKey] : undefined; return isRecord(environment) ? Object.fromEntries( Object.entries(environment).filter( (setting): setting is [string, string] => typeof setting[1] === "string", ), ) : {}; }; /** * An entry as the client launches it: Windows environment names are one name * whatever their case, so `PATH` and an equal `Path` start the same server. */ export const launchedRegistrationEntry = ( entry: unknown, environmentKey: string, platform: NodeJS.Platform, ): unknown => { if (platform !== "win32" || !isRecord(entry)) return entry; const environment = entry[environmentKey]; if (!isRecord(environment)) return entry; return { ...entry, [environmentKey]: Object.fromEntries( Object.entries(mergeEnvironmentOverrides({}, environment, platform)).map( ([key, value]) => [key.toUpperCase(), value], ), ), }; }; /** Merge admitted layers without re-reading or changing their source documents. */ export const mergeClientConfigurationDocuments = ( documents: readonly ClientConfigurationDocument[], platform: NodeJS.Platform, replaceRows = false, ): ClientConfigurationDocument | undefined => { const last = documents.at(-1); if (last === undefined) return undefined; if (documents.length === 1) return last; const dialect = clientWriteDialect(last.dialect, documents); if (replaceRows || clientServerRowsReplace(dialect)) return replacedServerConfiguration(documents); const servers: Record = Object.create(null); for (const document of documents) { const names = new Set([ ...Object.keys(document.legacyServers), ...Object.keys(document.servers), ]); for (const name of names) { const previous = servers[name]; const next = effectiveClientServer(document, name); // Goose overlays each extension one field deep (`merge_nested_entries`), // replacing nested values such as `envs` whole. const goose = document.dialect === "goose"; const merged = goose ? isRecord(previous) && isRecord(next) ? { ...previous, ...next } : next : mergeConfigurationValue(previous, next); const key = document.environmentKey; if ( !goose && name === PRODUCT_IDENTITY.mcpServerKey && isRecord(merged) && isRecord(merged[key]) ) { const before = isRecord(previous) && isRecord(previous[key]) ? previous[key] : {}; const after = isRecord(next) && isRecord(next[key]) ? next[key] : {}; servers[name] = { ...merged, [key]: mergeEnvironmentOverrides(before, after, platform), }; } else servers[name] = merged; } } return { ...last, dialect, servers, legacyServers: {}, }; }; export interface EffectiveClientRegistrationConfiguration { readonly document: ClientConfigurationDocument | undefined; readonly configPath: string; readonly scope?: ClientRegistrationScope; readonly launcherScope?: ClientRegistrationScope; readonly launcherConfigPath?: string; readonly activationScope?: ClientRegistrationScope; readonly activationConfigPath?: string; readonly declarations: readonly ServerDeclaration[]; readonly projectInspection?: "evaluated" | "untrusted"; /** * The read-only file above the writable layers that sets REA's entry, so the * client runs that definition rather than the one in `configPath`. */ readonly overridingConfigPath?: string; readonly overridingLauncherPath?: string; readonly overridingActivationPath?: string; readonly upperLayerCaution?: string; /** One source per admitted project pathname, ordered by its final native occurrence. */ readonly projectSources?: readonly ProjectConfigurationSource[]; /** Readiness can fail while parsed launcher identity remains available. */ readonly environmentError?: ClientConfigurationFileError; /** Project candidate spellings paired with their read-only user snapshots. */ readonly projectUserAliases?: readonly { readonly path: string; readonly source: ClientConfigurationSource; }[]; /** Whether proposed project edits leave the original selected row in effect. */ readonly preservesOriginalRegistration?: true; } /** Reading an effective registration does not authorize probes from project settings. */ export const hasProjectRegistrationContribution = ({ declarations, }: EffectiveClientRegistrationConfiguration): boolean => declarations.some(({ source }) => source.scope === "project"); export interface ProjectConfigurationReadOptions { /** Directory selected by the client's native project location rule. */ readonly projectDirectory: string; /** The registration transaction must still select a native project source. */ readonly writeTarget?: { readonly path: string; readonly transactionPath: string; readonly allowMissing: boolean; }; readonly mode?: "ownership"; /** Original and proposed layers from the transaction owner's snapshots. */ readonly candidates?: readonly { readonly path: string; readonly original: ClientConfigurationDocument; readonly replacement: ClientConfigurationDocument; }[]; } /** Apply the same native location rule to discovery, registration and provider reads. */ export const resolveClientProjectConfiguration = async ( client: Pick, cwd: string | undefined, context: Parameters[0], ): Promise => { if (cwd === undefined) return undefined; const projectDirectory = client.format === "mastracode" && isQualifiedCallerPath(cwd, context.platform) ? await gitWorktreeRootOrCwd(context, cwd) : cwd; return { projectDirectory }; }; /** Clients whose effective registration includes native project layers. */ const supportsProjectConfigurationWalk = ( client: Pick, ): boolean => client.format === "opencode" || client.format === "pi" || client.format === "mastracode" || client.name === "antigravity" || client.format === "amp" || client.name === "devin" || client.name === "copilot_cli" || client.name === "codex" || client.name === "kiro"; /** Read actual user layers, with a project view only when a directory is expressly supplied. */ export const readEffectiveClientRegistrationConfiguration = async ( client: SetupClient, resources: ArtifactResourceScope | undefined, platform: NodeJS.Platform, project?: ProjectConfigurationReadOptions, ): Promise< Result > => { if (project === undefined || !supportsProjectConfigurationWalk(client)) return readEffectiveUserConfiguration(client, resources, platform); if (client.configPathError !== undefined) return readEffectiveUserConfiguration(client, resources, platform); if (!isQualifiedCallerPath(project.projectDirectory, platform)) return err({ kind: "unreadable", path: project.projectDirectory, scope: "project", detail: "Project configuration inspection requires an absolute directory.", }); const paths = await presentProjectSources( client, project.projectDirectory, platform, project.writeTarget, ); if (!paths.ok) return paths; const target = project.writeTarget; // A project link into a system folder must not become writable. if (target !== undefined || project.mode === "ownership") { const reached = await reachedReadOnlyFile( [ ...(target === undefined ? [] : [target.path, target.transactionPath]), ...paths.value.flatMap(({ path, userPath }) => userPath === undefined ? [path] : [], ), ], client.readOnlyFiles ?? [], platform, ); if (reached !== undefined) return err({ kind: "unreadable", path: reached.path, scope: "project", detail: reachedReadOnlyFileDetail(reached), }); } if (target !== undefined) { const selected = paths.value.find(({ path }) => path === target.path); if (selected?.userPath !== undefined) return err({ kind: "unreadable", path: target.path, scope: "project", detail: `Project configuration ${target.path} aliases the user configuration at ${selected.userPath}. Select a project-only file.`, }); if (selected?.aliasesWriteTarget !== true) return err({ kind: "unreadable", path: target.path, scope: "project", detail: "The selected file could not be verified in the native project configuration load order.", }); } const candidates = new Map< string, NonNullable[number] >(); const userOverrides = new Set(client.openCodeUserOverridePaths); const layers = paths.value.filter( // These clients also load a user file at its native project position. // Kiro profile agent files are user files and still outrank workspace // settings, which appear earlier in the same walk. ({ userPath }) => userPath === undefined || client.name === "devin" || client.name === "kiro" || client.format === "mastracode" || userOverrides.has(userPath), ); const userAliasPaths = new Map( project.mode === "ownership" ? paths.value.flatMap(({ path, userPath }) => userPath === undefined ? [] : [[path, userPath] as const], ) : [], ); const admitted = new Set( layers.flatMap(({ path, userPath }) => userPath === undefined ? [path] : [], ), ); for (const candidate of project.candidates ?? []) { const { path } = candidate; if (candidates.has(path)) return err({ kind: "unreadable", path, scope: "project", detail: "A proposed project file appears more than once.", }); if (!admitted.has(path)) return err({ kind: "unreadable", path, scope: "project", detail: "The selected file is missing from the native project configuration load order.", }); candidates.set(path, candidate); } const publication = target === undefined ? undefined : candidates.get(target.path); if (publication !== undefined) for (const { path, userPath, aliasesWriteTarget } of layers) { // An atomic replacement updates what symlinks to the destination read. if (aliasesWriteTarget && userPath === undefined) candidates.set(path, publication); } if (layers.length === 0 && userAliasPaths.size === 0) return readEffectiveUserConfiguration(client, resources, platform); if (client.format === "pi" && layers.length > 0) { const trust = await isPiProjectTrusted( client.piSettings, project.projectDirectory, platform, resources, ); if (!trust.ok) return err({ ...trust.error, scope: "project" }); if (!trust.value) { const replacementPath = candidates.keys().next().value; if (replacementPath !== undefined) return err({ kind: "unreadable", path: replacementPath, scope: "project", detail: "Pi does not load MCP configuration from this untrusted project.", }); const user = await readEffectiveUserConfiguration( client, resources, platform, ); return user.ok ? ok(projectViewOfUserRegistration(user.value, "untrusted")) : user; } } const user = await readUserConfigurationSources(client, resources); if (!user.ok) return user; const selectedLayers = await codexTrustedProjectLayers( client, user.value, layers, platform, ); if (!selectedLayers.ok) return selectedLayers; if (client.name === "codex") for (const path of candidates.keys()) if (!selectedLayers.value.some((layer) => layer.path === path)) { const directory = codexProjectDirectory(path, platform); return err({ kind: "unreadable", path, scope: "project", detail: directory === undefined ? `Codex project configuration ${path} is not a .codex/config.toml file.` : `Codex has not trusted ${directory}. Set trust_level = "trusted" for that directory in ${client.configPath} before changing its project registration.`, }); } const userByPath = new Map( user.value.map((source) => [source.sourcePath, source]), ); const userAliases = [...userAliasPaths].flatMap(([path, userPath]) => { const source = userByPath.get(userPath); return source === undefined ? [] : [{ path, source }]; }); const sources = user.value.filter( ({ inlineOrigin }) => inlineOrigin === undefined, ); const upper = user.value.filter( ({ inlineOrigin }) => inlineOrigin !== undefined, ); const projectSources = new Map< string, ProjectConfigurationSource | undefined >(); for (const { path, userPath } of selectedLayers.value) { if (userPath !== undefined) { // Preserve this occurrence in native order while retaining the user // file's parsed snapshot and ownership. const source = userByPath.get(userPath); if (source?.sourcePath !== undefined) sources.push( client.name === "devin" ? { ...source, sourcePath: path, scope: "project" } : source, ); continue; } let source = projectSources.get(path); if (!projectSources.has(path)) { const original = candidates.get(path)?.original; const configuration = original === undefined ? await readConfigurationFile( path, projectDocumentFormat(client), resources, ) : ok(original); if (!configuration.ok) return err({ ...configuration.error, scope: "project" }); if (configuration.value !== undefined) source = { ...configuration.value, sourcePath: path, scope: "project", }; } // Read the pathname once, replay its snapshot in native order, and keep // only the final occurrence for ownership and mutation. projectSources.delete(path); projectSources.set(path, source); if (source === undefined) continue; sources.push(source); } sources.push(...upper); if (client.name === "kiro" && project.mode !== "ownership") { const ambiguous = kiroAmbiguousAgentFailure(sources, client, platform); if (ambiguous !== undefined) return err(ambiguous); } const original = projectRegistration(sources, client, platform); if (!original.ok) return original; const proposed = candidates.size === 0 ? original : projectRegistration( sources.map((source) => { if (source.scope !== "project" || source.sourcePath === undefined) return source; const candidate = candidates.get(source.sourcePath)?.replacement; return candidate === undefined ? source : { ...source, ...candidate }; }), client, platform, ); if (!proposed.ok) return proposed; const { active, document } = proposed.value; const last = active.at(-1); const baseline = original.value.document; const preservesOriginalRegistration = candidates.size > 0 && baseline !== undefined && document !== undefined && last !== undefined && baseline.dialect === document.dialect && original.value.active.at(-1)?.source.sourcePath === last.source.sourcePath && clientConfigurationValuesEqual( effectiveClientServer(baseline, PRODUCT_IDENTITY.mcpServerKey), effectiveClientServer(document, PRODUCT_IDENTITY.mcpServerKey), ); const environment = clientRegistrationEnvironment(document, client, platform); let environmentError: ClientConfigurationFileError | undefined; if (!environment.ok) { const source = contributingEnvironmentSource(active, environment.error, platform) ?? last?.source; environmentError = { ...invalidEnvironment( source?.sourcePath ?? client.configPath, environment.error, undefined, platform, ), ...(source?.scope === "project" ? { scope: "project" } : {}), }; if (project.mode !== "ownership") return err(environmentError); } const projectFacts = { ...overridingFileFact(active), ...upperLayerCaution(upper), declarations: active, projectInspection: "evaluated" as const, ...(project.mode === "ownership" ? { projectSources: [...projectSources.values()].filter( (source) => source !== undefined, ), } : {}), ...(preservesOriginalRegistration ? { preservesOriginalRegistration: true as const } : {}), ...(environmentError === undefined ? {} : { environmentError }), ...(userAliases.length === 0 ? {} : { projectUserAliases: userAliases }), }; if (last === undefined) return ok( projectViewOfUserRegistration( { document, configPath: client.configPath, ...projectFacts }, "evaluated", ), ); const launcher = active.findLast(declaresLauncher) ?? last; const activation = active.findLast(declaresActivation) ?? last; return ok({ document, configPath: last.source.sourcePath ?? client.configPath, scope: last.source.scope ?? "user", launcherScope: launcher.source.scope ?? "user", launcherConfigPath: launcher.source.sourcePath ?? client.configPath, activationScope: activation.source.scope ?? "user", activationConfigPath: activation.source.sourcePath ?? client.configPath, ...projectFacts, }); }; /** Resolve the native merge for a single set of parsed layers. */ const projectRegistration = ( sources: readonly ClientConfigurationSource[], client: Pick, platform: NodeJS.Platform, ): Result< { readonly document: ClientConfigurationDocument | undefined; readonly active: readonly ServerDeclaration[]; }, ClientConfigurationFileError > => { const declarations = serverDeclarations(sources); const winning = declarations.at(-1); if ( client.format === "pi" && winning?.source.scope === "project" && isPiPartialServerOverride(winning.entry) ) { const active = activeDeclarations(declarations, false); const override = piProjectOverride(active, winning); return override.ok ? ok({ document: withPiOverride(sources, active), active }) : override; } // OpenCode can overlay fields across layers. The other clients select // one whole server definition per name. const document = client.format === "opencode" ? mergeClientConfigurationDocuments(sources, platform) : replacedServerConfiguration(sources); const upperAmbiguity = ambiguousOpenCodeUpperRow(document, sources); if (upperAmbiguity !== undefined) return err(upperAmbiguity); return ok({ active: activeDeclarations( declarations, client.format !== "opencode" || clientServerRowsReplace(document?.dialect), ), document, }); }; const projectViewOfUserRegistration = ( user: EffectiveClientRegistrationConfiguration, projectInspection: NonNullable< EffectiveClientRegistrationConfiguration["projectInspection"] >, ): EffectiveClientRegistrationConfiguration => { const source = user.declarations.at(-1)?.source.sourcePath; const launcher = user.declarations.findLast(declaresLauncher)?.source.sourcePath; return { ...user, scope: "user", configPath: source ?? user.configPath, projectInspection, ...(launcher === undefined ? {} : { launcherScope: "user", launcherConfigPath: launcher, }), }; }; const kiroAmbiguousAgentFailure = ( sources: readonly ClientConfigurationSource[], client: Pick, platform: NodeJS.Platform, ): ClientConfigurationFileError | undefined => { const distinctAgents = [ ...new Set( sources.flatMap((source) => { if ( source.sourcePath === undefined || !isKiroAgentConfigurationPath(source.sourcePath, platform) ) return []; return effectiveClientServer(source, PRODUCT_IDENTITY.mcpServerKey) === undefined ? [] : [source.sourcePath]; }), ), ]; if (distinctAgents.length <= 1) return undefined; return { kind: "malformed", path: distinctAgents[0] ?? client.configPath, scope: "user", detail: `Kiro defines ${PRODUCT_IDENTITY.mcpServerKey} in more than one agent file (${distinctAgents.join(", ")}). Kiro loads the selected agent, so the registration stays unchanged until one agent file defines it.`, }; }; const readEffectiveUserConfiguration = async ( client: SetupClient, resources: ArtifactResourceScope | undefined, platform: NodeJS.Platform, ): Promise< Result > => { const nativeSources = await readClientConfigurationFiles( client, resources, platform, ); if (!nativeSources.ok) return nativeSources; if (client.name === "kiro") { const ambiguous = kiroAmbiguousAgentFailure( nativeSources.value, client, platform, ); if (ambiguous !== undefined) return err(ambiguous); } const nativeDocument = mergeClientConfigurationDocuments( nativeSources.value, platform, client.name === "kiro", ); const declarations = activeDeclarations( serverDeclarations(nativeSources.value), client.name === "kiro" || clientServerRowsReplace(nativeDocument?.dialect), ); const native = { ...overridingFileFact(declarations), ...upperLayerCaution(nativeSources.value), document: nativeDocument, configPath: client.configPath, declarations, }; const fallbackPath = client.format === "zcode" ? client.zcodeFallbackPath : undefined; if ( fallbackPath === undefined || (nativeDocument !== undefined && Object.keys(nativeDocument.servers).length > 0) ) return ok(native); const fallbackClient: SetupClient = { ...client, configPath: fallbackPath, configPaths: [fallbackPath], format: "zcode_fallback", }; const fallbackSources = await readClientConfigurationFiles( fallbackClient, resources, platform, ); if (!fallbackSources.ok) return fallbackSources; const document = mergeClientConfigurationDocuments( fallbackSources.value, platform, ); return ok( document === undefined ? native : { document, configPath: fallbackPath, declarations: activeDeclarations( serverDeclarations(fallbackSources.value), false, ), }, ); }; const filesystemPathKey = (path: string, platform: NodeJS.Platform): string => platform === "win32" ? win32.normalize(path).toLowerCase() : posix.normalize(path); export const projectDocumentFormat = ( client: Pick, ): ClientConfigurationFormat | undefined => client.name === "copilot_cli" ? "copilot_cli_project" : client.format; const codexProjectDirectory = ( configPath: string, platform: NodeJS.Platform, ): string | undefined => { const paths = platform === "win32" ? win32 : posix; if (paths.basename(configPath) !== "config.toml") return undefined; const folder = paths.dirname(configPath); if (paths.basename(folder) !== ".codex") return undefined; return paths.dirname(folder); }; /** Directories the user Codex file marks trust_level = "trusted", in both spellings. */ const codexTrustedDirectoryKeys = async ( sources: readonly ClientConfigurationSource[], configPath: string, candidateKeys: ReadonlySet, platform: NodeJS.Platform, ): Promise, ClientConfigurationFileError>> => { const projects = sources.find((source) => source.sourcePath === configPath) ?.document.projects; if (projects === undefined) return ok(new Set()); if (!isRecord(projects)) return err({ kind: "malformed", path: configPath, scope: "user", detail: `Codex project trust in ${configPath} must be a [projects] table.`, }); const trusted = new Set(); for (const [directory, entry] of Object.entries(projects)) { if (!isRecord(entry)) return err({ kind: "malformed", path: configPath, scope: "user", detail: `Codex project trust for ${directory} in ${configPath} must be a table.`, }); if (entry.trust_level !== "trusted") continue; if (!isQualifiedCallerPath(directory, platform)) continue; const lexicalKey = filesystemPathKey(directory, platform); trusted.add(lexicalKey); if (candidateKeys.size === 0 || candidateKeys.has(lexicalKey)) continue; try { trusted.add(filesystemPathKey(await realpath(directory), platform)); } catch { // Unrelated or inaccessible old project directories must not block current inspection. } } return ok(trusted); }; /** Keep Codex project files only for directories the user configuration trusts. */ const codexTrustedProjectLayers = async ( client: Pick, sources: readonly ClientConfigurationSource[], layers: readonly PresentProjectSource[], platform: NodeJS.Platform, ): Promise< Result > => { if (client.name !== "codex") return ok(layers); const layerEntries: { readonly layer: PresentProjectSource; readonly keys?: readonly string[]; }[] = []; const candidateKeys = new Set(); for (const layer of layers) { if (layer.userPath !== undefined) { layerEntries.push({ layer }); continue; } const directory = codexProjectDirectory(layer.path, platform); if (directory === undefined) continue; const keys = [filesystemPathKey(directory, platform)]; try { keys.push(filesystemPathKey(await realpath(directory), platform)); } catch (cause: unknown) { if (!isEnoentError(cause)) return err({ kind: "unreadable", path: directory, scope: "project", detail: `Codex project directory ${directory} could not be inspected: ${errorMessage(cause)}.`, }); } for (const key of keys) candidateKeys.add(key); layerEntries.push({ layer, keys }); } const trusted = await codexTrustedDirectoryKeys( sources, client.configPath, candidateKeys, platform, ); if (!trusted.ok) return trusted; const selected: PresentProjectSource[] = []; for (const { layer, keys } of layerEntries) { if (keys === undefined || keys.some((key) => trusted.value.has(key))) selected.push(layer); } return ok(selected); }; interface PresentProjectSource { readonly path: string; readonly userPath?: string; readonly aliasesWriteTarget?: true; } /** Project discovery cannot reclassify the current user's physical settings file. */ const presentProjectSources = async ( client: SetupClient, projectDirectory: string, platform: NodeJS.Platform, writeTarget?: ProjectConfigurationReadOptions["writeTarget"], ): Promise< Result > => { const physicalPath = writeTarget === undefined ? realpath : canonicalCallerPath; const keyOf = async (path: string) => filesystemPathKey(await physicalPath(path).catch(() => path), platform); const targetKey = writeTarget === undefined ? undefined : filesystemPathKey(writeTarget.transactionPath, platform); const userPaths = client.configPaths ?? [client.configPath]; const user = new Map(); const userKeys = await Promise.all( userPaths.map(async (path) => { try { return { path, key: filesystemPathKey(await physicalPath(path), platform), }; } catch (cause: unknown) { // A dangling user link might become active when the project file is // created. A non-directory ancestor cannot lead to that destination. if ( writeTarget?.allowMissing === true && !( cause instanceof Error && "code" in cause && cause.code === "ENOTDIR" ) ) return { path, cause }; return { path, key: filesystemPathKey(path, platform) }; } }), ); for (const { path, key, cause } of userKeys) { if (key === undefined) return err({ kind: "unreadable", path, scope: "user", detail: `User configuration path ${path} could not be verified before creating project settings: ${errorMessage(cause)}.`, }); user.set(key, path); } const nativePaths = clientProjectConfigurationPaths( client, projectDirectory, platform, ); if (!nativePaths.ok) return nativePaths; const project = new Map(); for (const candidate of new Set(nativePaths.value)) { try { await lstat(candidate); } catch (cause: unknown) { if (!isAbsentClientConfigPath(cause)) return err({ kind: "unreadable", path: candidate, scope: "project", detail: `Project configuration ${candidate} could not be inspected: ${errorMessage(cause)}`, }); if (writeTarget?.allowMissing !== true || candidate !== writeTarget.path) continue; } const key = await keyOf(candidate); const userPath = user.get(key); project.set(candidate, { path: candidate, ...(userPath === undefined ? {} : { userPath }), ...(key === targetKey ? { aliasesWriteTarget: true } : {}), }); } return ok( nativePaths.value.flatMap((path) => { const source = project.get(path); return source === undefined ? [] : [source]; }), ); }; const readPiTrustDocument = async ( path: string, resources: ArtifactResourceScope | undefined, ): Promise< Result | undefined, ClientConfigurationFileError> > => { const text = await readConfigurationText(path, resources); if (!text.ok) return text; if (text.value === undefined) return ok(undefined); try { const parsed: unknown = JSON.parse(text.value.replace(/^\uFEFF/u, "")); if (isRecord(parsed)) return ok(parsed); throw new TypeError("expected a JSON object"); } catch (cause: unknown) { return err({ kind: "malformed", path, scope: "project", detail: `Pi trust configuration in ${path} is malformed: ${errorMessage(cause)}`, }); } }; const isPiProjectTrusted = async ( settings: SetupClient["piSettings"], projectDirectory: string, platform: NodeJS.Platform, resources: ArtifactResourceScope | undefined, ): Promise> => { if (settings === undefined) return ok(false); const trust = await readPiTrustDocument(settings.trustPath, resources); if (!trust.ok) return trust; const paths = platform === "win32" ? win32 : posix; // Pi canonicalizes the current project and walks its physical ancestors. // Persisted keys already use that identity and Windows compares case-insensitively. let current = await realpath(projectDirectory).catch(() => projectDirectory); if (trust.value !== undefined) { const records = Object.entries(trust.value); for (;;) { const identity = filesystemPathKey(current, platform); const entry = records.find( ([path, decision]) => typeof decision === "boolean" && isQualifiedCallerPath(path, platform) && filesystemPathKey(path, platform) === identity, ); if (entry !== undefined) return ok(entry[1] === true); const parent = paths.dirname(current); if (parent === current) break; current = parent; } } const configuration = await readPiTrustDocument( settings.settingsPath, resources, ); return configuration.ok ? ok(configuration.value?.defaultProjectTrust === "always") : configuration; }; interface ServerDeclaration { readonly source: ClientConfigurationSource; readonly entry: unknown; } const declaresLauncher = ({ entry }: ServerDeclaration): boolean => isRecord(entry) && (Object.hasOwn(entry, "command") || Object.hasOwn(entry, "url")); const serverDeclarations = ( sources: readonly ClientConfigurationSource[], ): readonly ServerDeclaration[] => sources.flatMap((source) => { const entry = effectiveClientServer(source, PRODUCT_IDENTITY.mcpServerKey); return entry === undefined ? [] : [{ source, entry }]; }); const activeDeclarations = ( declarations: readonly ServerDeclaration[], wholeRows: boolean, ): readonly ServerDeclaration[] => wholeRows ? declarations.slice(-1) : declarations.slice( Math.max( 0, declarations.findLastIndex(({ entry }) => !isRecord(entry)), ), ); /** Report the active source of a registration schema failure. */ export const contributingRegistrationSource = ( { declarations }: EffectiveClientRegistrationConfiguration, error: ConfigurationError, ): ClientConfigurationSource | undefined => { const last = declarations.at(-1); if (last === undefined || !isRecord(last.entry)) return last?.source; const fields = new Set( error.settings.map(({ setting }) => setting.split(".")[0]), ); return ( declarations.findLast( ({ entry }) => isRecord(entry) && Object.keys(entry).some((key) => fields.has(key)), ) ?? declarations.findLast(declaresLauncher) ?? last ).source; }; const contributingEnvironmentSource = ( declarations: readonly ServerDeclaration[], error: ConfigurationError, platform: NodeJS.Platform, ): ClientConfigurationSource | undefined => { const normalize = (name: string): string => platform === "win32" ? name.toUpperCase() : name; const keys = error instanceof ClientRegistrationEnvironmentShapeError ? error.invalidKeys : error.settings.map(({ setting }) => setting); const rejected = new Set(keys.map(normalize)); const invalidMap = error instanceof ClientRegistrationEnvironmentShapeError && keys.length === 0; return declarations.findLast(({ source, entry }) => { if (!isRecord(entry) || !Object.hasOwn(entry, source.environmentKey)) return false; if (invalidMap) return true; const environment = entry[source.environmentKey]; return ( isRecord(environment) && Object.keys(environment).some((key) => rejected.has(normalize(key))) ); })?.source; }; const replacedServerConfiguration = ( sources: readonly ClientConfigurationDocument[], ): ClientConfigurationDocument | undefined => { const last = sources.at(-1); if (last === undefined) return undefined; const servers = Object.fromEntries( sources.flatMap((source) => [ ...new Set([ ...Object.keys(source.legacyServers), ...Object.keys(source.servers), ]), ].map((name) => [name, effectiveClientServer(source, name)]), ), ); return { ...last, dialect: clientWriteDialect(last.dialect, sources), servers, legacyServers: {}, }; }; const isPiPartialServerOverride = ( entry: unknown, ): entry is Record => isRecord(entry) && !["command", "url", "type"].some((key) => Object.hasOwn(entry, key)); const piProjectOverride = ( active: readonly ServerDeclaration[], project: ServerDeclaration, ): Result => { if (!isRecord(project.entry) || project.source.sourcePath === undefined) return ok(undefined); const allowed = ["enabled", "exposure", "toolExposure"]; const invalid = Object.keys(project.entry).filter( (key) => !allowed.includes(key), ); let reason: string | undefined; if (invalid.length > 0) reason = `a flags-only override may only set ${allowed.join(", ")}; found ${invalid.join(", ")}`; else if (!isRecord(active.at(-2)?.entry)) reason = "a flags-only override requires an existing user-level server"; if (reason === undefined) return ok(undefined); return err({ kind: "malformed", path: project.source.sourcePath, scope: "project", detail: `Invalid Pi project REA server in ${project.source.sourcePath}: ${reason}.`, }); }; const withPiOverride = ( sources: readonly ClientConfigurationSource[], declarations: readonly ServerDeclaration[], ): ClientConfigurationDocument | undefined => { const document = replacedServerConfiguration(sources); if (document === undefined) return document; const base = declarations.at(-2)?.entry; const project = declarations.at(-1)?.entry; if (!isRecord(base) || !isRecord(project)) return document; return { ...document, servers: { ...document.servers, [PRODUCT_IDENTITY.mcpServerKey]: { ...base, ...project }, }, }; };