diff --git a/docs/getting-started/client-configuration.md b/docs/getting-started/client-configuration.md index 774a3f3622..a6c8f01c9d 100644 --- a/docs/getting-started/client-configuration.md +++ b/docs/getting-started/client-configuration.md @@ -17,8 +17,11 @@ the client can launch it. For JavaScript installations, setup registers the selected runtime executable and REA script by absolute path. On POSIX, it prefers executable `node` or `bun` and REA aliases on setup's `PATH` only when they resolve to the -same selected files. This preserves manager-owned aliases across version updates; -otherwise setup uses the selected paths directly. This also applies when setup +same selected files. Setup skips paths that pass through fnm multishell +directories or `XDG_RUNTIME_DIR`, including through another symlink. +This preserves durable manager aliases across +version updates. When no eligible alias exists, setup uses the selected +installation paths. This also applies when setup runs through a package runner: retain the selected cache entry and runtime while the registration uses them. Clearing either makes startup fail without resolving another package from the client's project. Restore the same installation before @@ -31,6 +34,9 @@ without `--dry-run` and approve the displayed changes. Setup preserves unrelated settings, backs up changed configuration and leaves an aligned registration unchanged. Restart the client after applying the update. +If doctor reports a saved session path that still resolves, run setup to +refresh that registration before the session directory is removed. + If a runtime manager removes the registered executable and no surviving alias was available, doctor reports its identity as unknown and setup retains the registration. REA does not infer that an arbitrary missing executable was Node @@ -311,8 +317,9 @@ read it. From that redirected view, setup and uninstall refuse to change other clients' files there (VS Code, Trae, Devin and Hermes) and skill directories there. `npm install -g` run from such a process installs into the package's `LocalCache\Roaming\npm`, which other processes cannot see at the `%APPDATA%` -path. Setup refuses to register a launcher stored in any MSIX package's -private storage. Install REA from an ordinary terminal and rerun setup there. +path. Setup and the default `rea mcp add` launcher reject runtimes and REA +scripts stored in any MSIX package's private storage. Install REA from an +ordinary terminal and retry the registration there. Uninstall removes REA's entry from both the private copy and the `%APPDATA%` file, including registrations that earlier releases wrote to `%APPDATA%`. @@ -567,7 +574,7 @@ the diagnostic identifies the setting to repair. See the for the supported policy values. When direct launcher paths prove the same executable or Node entrypoint, -setup retains the existing caller-selected spelling. An otherwise aligned +setup retains an existing spelling outside known session directories. An otherwise aligned registration therefore needs no rewrite or recovery backup merely because REA was invoked through another symlink. Setup also retains that spelling when another field, such as an invalid timeout, needs repair. Unresolved identity diff --git a/src/application/ClientRegistration.ts b/src/application/ClientRegistration.ts index ff5670998c..451a051f65 100644 --- a/src/application/ClientRegistration.ts +++ b/src/application/ClientRegistration.ts @@ -4,6 +4,7 @@ import { gooseEnvironmentField, } from "./ClientRegistrationSource.js"; import { PRODUCT_IDENTITY } from "../identity.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { jsonRecordSchema } from "../domain/jsonRecord.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; @@ -452,6 +453,8 @@ export const refreshClientRegistration = ( environment: Readonly>, previous: unknown, timeoutInputs: McpToolTimeoutInputs, + launcherEnvironment: Readonly = process.env, + platform: NodeJS.Platform = HOST_PLATFORM.platform, ): Result, ConfigurationError> => { const target = { dialect, profile: client.registrationProfile }; const facts = clientRegistrationSourceFacts(target, command, previous); @@ -465,7 +468,12 @@ export const refreshClientRegistration = ( : undefined; const launcher = priorCommand !== undefined && - equivalentClientRegistrationCommands(priorCommand, command) + equivalentClientRegistrationCommands( + priorCommand, + command, + launcherEnvironment, + platform, + ) ? priorCommand : command; const defaults = clientRegistrationEntry(dialect, launcher, environment); diff --git a/src/application/ClientRegistrationIdentity.ts b/src/application/ClientRegistrationIdentity.ts index 4f88da87c2..4e1a153924 100644 --- a/src/application/ClientRegistrationIdentity.ts +++ b/src/application/ClientRegistrationIdentity.ts @@ -1,6 +1,12 @@ import { HOST_PLATFORM } from "../platform/HostPlatform.js"; -import { accessSync, constants, realpathSync } from "node:fs"; -import { isAbsolute } from "node:path"; +import { + accessSync, + constants, + lstatSync, + readlinkSync, + realpathSync, +} from "node:fs"; +import { isAbsolute, posix } from "node:path"; import { CURRENT_ENTRYPOINT_PATH, normalizeEntrypointPath, @@ -12,7 +18,15 @@ import { type JavaScriptRuntime, } from "../domain/runtimeVersion.js"; import { posixPathCandidates } from "../process/executableSearch.js"; +import { + absoluteCallerPath, + appendCallerPath, +} from "../filesystem/callerPath.js"; import { PRODUCT_IDENTITY } from "../identity.js"; +import { + msixPackagesDirectory, + packagePrivateLauncherBlocker, +} from "./MsixPackageStorage.js"; /** Package runners recognized for invocation guidance and legacy registrations. */ type PackageRunner = "npx" | "bunx"; @@ -61,6 +75,23 @@ export const withoutPackageRunnerIdentity = ( ), ); +/** Restrictions on the automatically selected launcher shared by setup and mcp add. */ +export const defaultClientRegistrationBlocker = ( + command: readonly string[], + platform: NodeJS.Platform, + home: string, + environment: Readonly, +): string | undefined => { + if (command.length === 0) + return "REA could not determine persistent paths for the current runtime and REA entrypoint. Run the installed REA CLI from outside the session directory, then retry."; + if (platform === "win32") + return packagePrivateLauncherBlocker( + command, + msixPackagesDirectory(home, environment), + ); + return undefined; +}; + /** Bind the selected REA entrypoint to the runtime already executing setup. */ export const currentClientRegistrationCommand = ( selection: { @@ -76,16 +107,20 @@ export const currentClientRegistrationCommand = ( ? selection.entrypointPath : CURRENT_ENTRYPOINT_PATH; if (entrypointPath === undefined || entrypointPath.length === 0) return []; - return [ - registrationRuntimePath( - process.execPath, - javaScriptRuntime(process.versions).id, - environment, - platform, - ), - registrationEntrypointPath(entrypointPath, environment, platform), - "mcp", - ]; + const runtime = registrationRuntimePath( + process.execPath, + javaScriptRuntime(process.versions).id, + environment, + platform, + ); + const script = registrationEntrypointPath( + entrypointPath, + environment, + platform, + ); + return runtime === undefined || script === undefined + ? [] + : [runtime, script, "mcp"]; }; const unwrapCmdCommand = (command: readonly string[]): readonly string[] => { @@ -168,13 +203,28 @@ const sameFileExecutableAlias = ( name: string, environment: Readonly, identify: typeof entrypointIdentity, -): string => { +): string | undefined => { + const roots = transientLauncherRoots(environment); + let fallback = selected; + if (usesTransientLauncherPath(selected, roots)) { + try { + fallback = realpathSync.native(selected); + if ( + transientLauncherPath(fallback, roots) || + identify(fallback, selected) !== "owned" + ) + return undefined; + } catch { + return undefined; + } + } for (const { path: candidate } of posixPathCandidates( name, environment.PATH ?? "", { relativeEntries: "skip" }, )) { if (identify(candidate, selected) !== "owned") continue; + if (usesTransientLauncherPath(candidate, roots)) continue; try { accessSync(candidate, constants.X_OK); return candidate; @@ -182,7 +232,104 @@ const sameFileExecutableAlias = ( // An unexecutable alias cannot launch the selected program. } } - return selected; + return fallback; +}; + +/** Follow directory and file links in POSIX lookup order, before realpath can erase a session hop. */ +const usesTransientLauncherPath = ( + path: string, + roots: readonly string[], +): boolean => { + if (!posix.isAbsolute(path)) return false; + const activeLinks = new Set(); + const transient = Symbol("transient"); + const walk = ( + target: string, + directory: string, + ): string | typeof transient | undefined => { + const absolute = posix.isAbsolute(target); + const spelled = absolute + ? target + : appendCallerPath(directory, target, "linux"); + if (transientLauncherPath(spelled, roots)) return transient; + let current = absolute ? "/" : directory; + for (const component of target.split("/")) { + if (component === "" || component === ".") continue; + if (component === "..") { + current = posix.dirname(current); + continue; + } + const next = posix.join(current, component); + if (transientLauncherPath(next, roots)) return transient; + if (!lstatSync(next).isSymbolicLink()) { + current = next; + continue; + } + if (activeLinks.has(next)) return undefined; + activeLinks.add(next); + const destination = walk(readlinkSync(next), current); + activeLinks.delete(next); + if (typeof destination !== "string") return destination; + current = destination; + } + return current; + }; + try { + return walk(path, "/") === transient; + } catch { + // A missing or unreadable component is not evidence of a session hop. + // Ownership and launch readiness are checked independently. + return false; + } +}; + +const transientLauncherRoots = ( + environment: Readonly, +): readonly string[] => { + const { FNM_MULTISHELL_PATH, XDG_RUNTIME_DIR } = environment; + const roots = [FNM_MULTISHELL_PATH, XDG_RUNTIME_DIR]; + if (XDG_RUNTIME_DIR !== undefined && posix.isAbsolute(XDG_RUNTIME_DIR)) { + try { + roots.push(realpathSync.native(XDG_RUNTIME_DIR)); + } catch { + // Its spelling is still useful when the runtime directory is already gone. + } + } + // fnm's session directory is itself a link to the installed version. + return roots.flatMap((root) => { + if (root === undefined || !posix.isAbsolute(root)) return []; + const directory = absoluteCallerPath(root, { platform: "linux" }).replace( + /\/$/u, + "", + ); + return directory === "" ? [] : [directory]; + }); +}; + +/** A fnm session path can outlive its shell environment but still be transient. */ +const transientLauncherPath = ( + path: string, + roots: readonly string[], +): boolean => { + const absolute = absoluteCallerPath(path, { platform: "linux" }); + if (/(?:^|\/)fnm_multishells\/\d+_\d+(?:\/|$)/u.test(absolute)) return true; + return roots.some( + (directory) => + absolute === directory || absolute.startsWith(`${directory}/`), + ); +}; + +export const transientClientLauncherPaths = ( + command: readonly string[], + environment: Readonly, + platform: NodeJS.Platform, +): readonly string[] => { + if (platform === "win32" || command.length !== 3 || command[2] !== "mcp") + return []; + const roots = transientLauncherRoots(environment); + return command + .slice(0, 2) + .filter((path) => usesTransientLauncherPath(path, roots)); }; /** Prefer an executable PATH alias that proves the same selected REA file. */ @@ -190,7 +337,7 @@ const registrationEntrypointPath = ( entrypoint: string, environment: Readonly, platform: NodeJS.Platform, -): string => +): string | undefined => // A Windows command shim is a different program; file identity cannot prove // its script target. Keep that platform's existing Node/script registration. platform === "win32" @@ -208,7 +355,7 @@ export const registrationRuntimePath = ( runtime: JavaScriptRuntime["id"], environment: Readonly, platform: NodeJS.Platform, -): string => +): string | undefined => platform === "win32" ? executable : sameFileExecutableAlias( @@ -222,7 +369,11 @@ export const registrationRuntimePath = ( export const equivalentClientRegistrationCommands = ( previous: readonly string[], requested: readonly string[], + environment: Readonly, + platform: NodeJS.Platform, ): boolean => { + if (transientClientLauncherPaths(previous, environment, platform).length > 0) + return false; if ( previous.length === requested.length && previous.every((value, index) => value === requested[index]) diff --git a/src/application/ClientRegistrationStatus.ts b/src/application/ClientRegistrationStatus.ts index f769763b79..ab2852e2c9 100644 --- a/src/application/ClientRegistrationStatus.ts +++ b/src/application/ClientRegistrationStatus.ts @@ -24,6 +24,7 @@ import { } from "../config/mcpStartupPolicy.js"; import { inspectClientRegistrationCommand, + transientClientLauncherPaths, type ClientRegistrationCommandFacts, type ClientRegistrationCommandIdentity, } from "./ClientRegistrationIdentity.js"; @@ -340,6 +341,11 @@ export const readClientRegistrationInspections = async ( command, currentCommandPath, ); + const transientPaths = transientClientLauncherPaths( + command, + options.environment ?? process.env, + options.platform, + ); const nativeApplicability = admitClientStdioConnection(raw, { dialect: parsed.dialect, profile: client.registrationProfile, @@ -419,17 +425,25 @@ export const readClientRegistrationInspections = async ( : activation === "enabled" && !packageVersionDrift && alignment === "aligned" && + transientPaths.length === 0 && (parsed.dialect !== "dsh" || dshDocument(parsed.document).ready) && policyBlock === undefined ? "aligned" : "stale", - (parsed.dialect !== "dsh" && commandFacts.identity !== "owned" - ? clientRegistrationOwnershipRemediation(commandFacts.identity, [ - configPath, - ...inlineRegistrationOrigins(client), - ]) + (nativeApplicability.ok + ? await missingTransientLauncherRemediation( + transientPaths, + commandFacts.identity, + effectiveClient, + ) : undefined) ?? + (parsed.dialect !== "dsh" && commandFacts.identity !== "owned" + ? clientRegistrationOwnershipRemediation(commandFacts.identity, [ + configPath, + ...inlineRegistrationOrigins(client), + ]) + : undefined) ?? (!nativeApplicability.ok ? nativeApplicability.error.cause.message : undefined) ?? @@ -441,6 +455,9 @@ export const readClientRegistrationInspections = async ( : undefined) ?? (sharedDisabledConflict ? sharedDisabledActivationRemediation() + : undefined) ?? + (transientPaths.length > 0 && commandFacts.identity === "owned" + ? `The saved launcher uses a session path (${transientPaths.join(", ")}). ${remediation(effectiveClient)}` : undefined), packageReference, registrationEnvironment?.ok === true @@ -594,6 +611,27 @@ const inlineRegistrationRemediation = (client: SetupClient): string => { const unknownEntryPointRemediation = (): string => "The existing registration was retained because its executable identity cannot be verified. Check the registered launcher path, symlink targets and access permissions. Run the installed REA CLI or a supported package runner, then rerun rea doctor; no registration was changed."; +const missingTransientLauncherRemediation = async ( + paths: readonly string[], + identity: ClientRegistrationCommandIdentity, + client: SetupClient, +): Promise => { + if (identity !== "unknown") return undefined; + for (const path of paths) { + try { + await stat(path); + } catch (cause) { + if (isMissing(cause)) { + const detail = `The saved session launcher path ${path} is missing.`; + return client.format === "dsh" + ? `${detail} Run rea setup --client dsh to review and refresh the installed REA registration, then restart the client.` + : `${detail} Launcher ownership is unknown. Back up the client configuration and replace that path with the verified installed interpreter or REA script, then rerun rea doctor and restart the client.`; + } + } + } + return undefined; +}; + const configuredStatus = ( client: SetupClient, command: RegistrationCommand, diff --git a/src/application/MsixPackageStorage.ts b/src/application/MsixPackageStorage.ts index 00c8b24e05..a3a8cdf7a8 100644 --- a/src/application/MsixPackageStorage.ts +++ b/src/application/MsixPackageStorage.ts @@ -71,7 +71,7 @@ const packagePrivateStorageFamily = ( }; /** - * Explain why setup must not register a launcher that exists only in one + * Explain why automatic registration must skip a launcher that exists only in one * package's private storage. Other clients could not start it, and doctor * outside that package could not verify it. */ @@ -101,7 +101,7 @@ export const packagePrivateLauncherBlocker = ( } const family = packagePrivateStorageFamily(resolved, packages); if (family !== undefined) - return `The REA launcher ${part} is stored at ${resolved}, inside the private storage of MSIX package ${family}. Only processes started by that app can see it at ${part}, and Windows removes it with the package, so other clients could not start this registration. Install REA from a terminal that the app did not start (for example with \`npm install -g rea-agents\`), then rerun setup from that terminal.`; + return `The REA launcher ${part} is stored at ${resolved}, inside the private storage of MSIX package ${family}. Only processes started by that app can see it at ${part}, and Windows removes it with the package, so other clients could not start this registration. Install REA from a terminal that the app did not start (for example with \`npm install -g rea-agents\`), then retry the registration from that terminal.`; } return undefined; }; diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.ts index ea0e147e61..de8445d521 100644 --- a/src/application/SetupClientConfiguration.ts +++ b/src/application/SetupClientConfiguration.ts @@ -114,6 +114,7 @@ export const configureClientConfiguration = async ( resolveProviderRequestBudget?: ProviderRequestBudgetResolver, // Setup writes the running host's client files unless its host selects one. platform: NodeJS.Platform = HOST_PLATFORM.platform, + launcherEnvironment: Readonly = process.env, ): Promise => { if (command.length === 0) return { @@ -132,7 +133,7 @@ export const configureClientConfiguration = async ( try { return await withClientConfigurationTransaction(transactionPath, () => configureClientDocument( - { client, transactionPath, platform }, + { client, transactionPath, platform, launcherEnvironment }, environment, command, resolveProviderRequestBudget, @@ -154,10 +155,12 @@ const configureClientDocument = async ( client, transactionPath, platform, + launcherEnvironment, }: { readonly client: SetupClient; readonly transactionPath: string; readonly platform: NodeJS.Platform; + readonly launcherEnvironment: Readonly; }, environment: SetupProviderEnvironment, command: readonly string[], @@ -232,6 +235,7 @@ const configureClientDocument = async ( parsed, files.value, platform, + launcherEnvironment, resolveProviderRequestBudget, ), ); @@ -269,6 +273,7 @@ const configureClientDocument = async ( }, files.value, platform, + launcherEnvironment, resolveProviderRequestBudget, ); // The settings written now can differ from the ones inspection admitted, @@ -546,10 +551,12 @@ const readClientRefresh = async ( resolveProviderRequestBudget, resources, currentCommandPath, + launcherEnvironment, }: { readonly platform: NodeJS.Platform; readonly resolveProviderRequestBudget?: ProviderRequestBudgetResolver; readonly resources?: ArtifactResourceScope; + readonly launcherEnvironment: Readonly; /** The entry point whose registrations setup owns; update names the new one. */ readonly currentCommandPath?: string; }, @@ -587,6 +594,7 @@ const readClientRefresh = async ( parsed, files.value, platform, + launcherEnvironment, resolveProviderRequestBudget, ); const target = @@ -655,6 +663,7 @@ export const clientConfigurationAligned = async ( resolveProviderRequestBudget?: ProviderRequestBudgetResolver, // Setup reads the running host's client files unless its host selects one. platform: NodeJS.Platform = HOST_PLATFORM.platform, + launcherEnvironment: Readonly = process.env, ): Promise => { if (client.configPathError !== undefined) return false; try { @@ -663,8 +672,8 @@ export const clientConfigurationAligned = async ( providerEnvironment, command, resolveProviderRequestBudget === undefined - ? { platform } - : { platform, resolveProviderRequestBudget }, + ? { platform, launcherEnvironment } + : { platform, launcherEnvironment, resolveProviderRequestBudget }, ); return ( refresh.ok && @@ -708,8 +717,10 @@ export const clientRefreshRefusal = async ( platform, currentCommandPath, resources, + launcherEnvironment = process.env, }: { readonly platform: NodeJS.Platform; + readonly launcherEnvironment?: Readonly; /** The entry point the refreshing setup runs from. */ readonly currentCommandPath: string; readonly resources?: ArtifactResourceScope; @@ -729,6 +740,7 @@ export const clientRefreshRefusal = async ( { platform, currentCommandPath, + launcherEnvironment, ...(resources === undefined ? {} : { resources }), }, ); @@ -741,6 +753,7 @@ export const clientRefreshRefusal = async ( command, refresh.value, platform, + launcherEnvironment, ); if (discovered !== undefined) return { @@ -777,6 +790,7 @@ const discoveredInlineSettings = async ( command: readonly string[], refresh: ClientRefresh, platform: NodeJS.Platform, + launcherEnvironment: Readonly, ): Promise< | { readonly origin: ClientInlineConfiguration["origin"]; @@ -813,6 +827,7 @@ const discoveredInlineSettings = async ( refresh.parsed, refresh.sources, platform, + launcherEnvironment, ); return inlineRegistrationOverride( client, @@ -832,6 +847,7 @@ export const inspectClientConfiguration = async ( resolveProviderRequestBudget?: ProviderRequestBudgetResolver, // Setup reads the running host's client files unless its host selects one. platform: NodeJS.Platform = HOST_PLATFORM.platform, + launcherEnvironment: Readonly = process.env, ): Promise => { let inspection: ClientConfigurationInspection; try { @@ -840,6 +856,7 @@ export const inspectClientConfiguration = async ( providerEnvironment, command, platform, + launcherEnvironment, resolveProviderRequestBudget, ); } catch (cause: unknown) { @@ -863,6 +880,7 @@ const inspectClientDocument = async ( providerEnvironment: SetupProviderEnvironment, command: readonly string[], platform: NodeJS.Platform, + launcherEnvironment: Readonly, resolveProviderRequestBudget?: ProviderRequestBudgetResolver, ): Promise => { if (client.configPathError !== undefined) @@ -915,6 +933,7 @@ const inspectClientDocument = async ( undefined, files.value, platform, + launcherEnvironment, resolveProviderRequestBudget, ); const override = inlineOverrideBlocker( @@ -970,6 +989,7 @@ const inspectClientDocument = async ( parsed, files.value, platform, + launcherEnvironment, resolveProviderRequestBudget, ); const override = inlineOverrideBlocker( @@ -1333,6 +1353,7 @@ const clientConfigurationDesired = async ( parsed: ClientConfigurationDocument | undefined, sources: readonly ClientConfigurationSource[], platform: NodeJS.Platform, + launcherEnvironment: Readonly, resolveProviderRequestBudget?: ProviderRequestBudgetResolver, ): Promise => { const effective = effectiveClientConfiguration( @@ -1403,6 +1424,8 @@ const clientConfigurationDesired = async ( ? undefined : effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey), validated.value.timeoutInputs, + launcherEnvironment, + platform, ); if (!registration.ok) throw registration.error; return withInheritedGooseSettings( diff --git a/src/application/SetupHost.ts b/src/application/SetupHost.ts index 7c3ddfc0ee..c820711c7e 100644 --- a/src/application/SetupHost.ts +++ b/src/application/SetupHost.ts @@ -12,7 +12,10 @@ import { type AnalysisCleanupLease, } from "../resources/index.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; -import { currentClientRegistrationCommand } from "./ClientRegistrationIdentity.js"; +import { + currentClientRegistrationCommand, + defaultClientRegistrationBlocker, +} from "./ClientRegistrationIdentity.js"; import { SUPPORTED_NODE_VERSION_PROSE, supportsNodeVersion, @@ -56,10 +59,6 @@ import { explicitSetupRegistrationEnvironment, providerRegistrationEnvironment, } from "./SetupRegistrationEnvironment.js"; -import { - msixPackagesDirectory, - packagePrivateLauncherBlocker, -} from "./MsixPackageStorage.js"; import type { SetupHost, SetupInitialState, @@ -87,15 +86,12 @@ const setupRegistration = ( entrypointPath: CURRENT_ENTRYPOINT_PATH, environment, }); - const registrationCommandBlocker = - registrationCommand.length === 0 - ? "REA could not determine the current executable entrypoint. Run setup through the installed REA CLI or a supported package runner before configuring clients." - : platform === "win32" - ? packagePrivateLauncherBlocker( - registrationCommand, - msixPackagesDirectory(homeDirectory, environment), - ) - : undefined; + const registrationCommandBlocker = defaultClientRegistrationBlocker( + registrationCommand, + platform, + homeDirectory, + environment, + ); return registrationCommandBlocker === undefined ? { registrationCommand } : { registrationCommand, registrationCommandBlocker }; @@ -305,6 +301,7 @@ export const systemSetupHost = ( resources, doctorHost.resolveProviderRequestBudget, platform, + environment, ), skillNeedsInstall: (clientIds) => canonicalSkillNeedsInstall( @@ -366,6 +363,7 @@ const clientConfigurationOperations = ( resources: ArtifactResourceScope, resolveProviderRequestBudget: DoctorHost["resolveProviderRequestBudget"], platform: NodeJS.Platform, + launcherEnvironment: Readonly, ) => ({ configureClient: ( client: SetupClient, @@ -381,6 +379,7 @@ const clientConfigurationOperations = ( command, resolveProviderRequestBudget, platform, + launcherEnvironment, ), ), clientNeedsConfigure: ( @@ -397,6 +396,7 @@ const clientConfigurationOperations = ( command, resolveProviderRequestBudget, platform, + launcherEnvironment, )), ), inspectClientConfiguration: ( @@ -411,6 +411,7 @@ const clientConfigurationOperations = ( command, resolveProviderRequestBudget, platform, + launcherEnvironment, ), ), }); diff --git a/src/application/UpdateMaintenance.ts b/src/application/UpdateMaintenance.ts index d2acc0552d..baec69d433 100644 --- a/src/application/UpdateMaintenance.ts +++ b/src/application/UpdateMaintenance.ts @@ -148,6 +148,7 @@ export const existingMaintenanceScope = async ( // The launcher and explicitly selected settings the maintenance setup run // registers; provider defaults doctor discovers there are not known here. const command = currentClientRegistrationCommand({ + platform, entrypointPath: entryPoint, environment, }); @@ -172,6 +173,7 @@ export const existingMaintenanceScope = async ( const refusal = await clientRefreshRefusal(client, settings, command, { platform, currentCommandPath: entryPoint, + launcherEnvironment: environment, ...(resources === undefined ? {} : { resources }), }); if (refusal !== undefined) { diff --git a/src/cli/cliShell.ts b/src/cli/cliShell.ts index 1e769265bd..956ab8d790 100644 --- a/src/cli/cliShell.ts +++ b/src/cli/cliShell.ts @@ -1,11 +1,9 @@ import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import type { FridaInstrumentationPort } from "../ports/frida/FridaInstrumentationPort.js"; -import { currentClientRegistrationCommand } from "../application/ClientRegistrationIdentity.js"; import { parseCliGlobalArguments } from "../cliBuiltinArguments.js"; import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { parseLogLevel } from "../config/processStart.js"; -import { parseClientRegistrationCommand } from "../domain/clientRegistrationCommand.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { createLogger } from "../logger.js"; import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; @@ -68,9 +66,6 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { options.selectedEnvironment, HOST_PLATFORM.platform, ); - const defaultRegistration = parseClientRegistrationCommand( - currentClientRegistrationCommand({ environment }), - ); // The executable reports an invalid level before every command except doctor. // Doctor keeps going so its readiness report can name REA_LOG_LEVEL. const level = @@ -114,7 +109,6 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { const registration = serveMcpRegistration( global, environment, - defaultRegistration, serveOptions ?? {}, ); if (registration !== undefined) return registration; diff --git a/src/cli/mcpRegistration.ts b/src/cli/mcpRegistration.ts index dd4d88fdf5..dbec0cba6c 100644 --- a/src/cli/mcpRegistration.ts +++ b/src/cli/mcpRegistration.ts @@ -8,6 +8,10 @@ import { registerMcpClients, type McpClientRegistrationOutcome, } from "../application/McpClientRegistration.js"; +import { + currentClientRegistrationCommand, + defaultClientRegistrationBlocker, +} from "../application/ClientRegistrationIdentity.js"; import { resolveMcpRegistrationClients, type McpRegistrationClient, @@ -41,7 +45,6 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { parseClientRegistrationCommand, type ClientRegistrationCommand, - type ClientRegistrationCommandIssue, } from "../domain/clientRegistrationCommand.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { redactExplicitText } from "../domain/explicitSensitiveValues.js"; @@ -100,10 +103,6 @@ const precedingFlags = [ export const serveMcpRegistration = ( global: CliGlobalArguments, environment: Readonly, - defaultCommand: Result< - ClientRegistrationCommand, - ClientRegistrationCommandIssue - >, options: ServeOptions, ): Promise | undefined => { const offset = global.command[0] === PRODUCT_IDENTITY.cliBinary ? 1 : 0; @@ -122,7 +121,7 @@ export const serveMcpRegistration = ( return Promise.resolve(); const request = readRegistrationRequest( global.command.slice(offset + 2), - defaultCommand, + environment, ); if (!request.ok) { await presentation.validation( @@ -259,10 +258,7 @@ const serveRegistrationDiscovery = async ( const readRegistrationRequest = ( arguments_: readonly string[], - defaultCommand: Result< - ClientRegistrationCommand, - ClientRegistrationCommandIssue - >, + environment: Readonly, ): Result => { const request = readMcpAddArguments(arguments_); if (!request.validation.ok) { @@ -276,10 +272,22 @@ const readRegistrationRequest = ( field: issue.kind === "missing_value" ? issue.field : "arguments", }); } - const launcher = - request.commandText === undefined - ? defaultCommand - : parseClientRegistrationCommand(request.commandText); + let command: string | readonly string[]; + if (request.commandText === undefined) { + const { platform } = HOST_PLATFORM; + command = currentClientRegistrationCommand({ platform, environment }); + const blocker = defaultClientRegistrationBlocker( + command, + platform, + homeDirectoryFromEnvironment(environment, platform), + environment, + ); + if (blocker !== undefined) + return err({ code: "invalid_value", field: "command", message: blocker }); + } else { + command = request.commandText; + } + const launcher = parseClientRegistrationCommand(command); return launcher.ok ? ok({ agents: request.agents, diff --git a/src/cliMcpRegistration.test.ts b/src/cliMcpRegistration.test.ts index a0baea1607..3684477f3f 100644 --- a/src/cliMcpRegistration.test.ts +++ b/src/cliMcpRegistration.test.ts @@ -17,7 +17,7 @@ const require = createRequire(import.meta.url); const CHILD_PROGRAM = ` import { homedir } from 'node:os'; import { join, relative, isAbsolute, delimiter } from 'node:path'; - import { mkdir, writeFile, readFile, readdir, realpath, stat } from 'node:fs/promises'; + import { mkdir, writeFile, readFile, readdir, realpath, stat, symlink } from 'node:fs/promises'; const ambient = process.env.HOME; if (!ambient || await realpath(ambient) !== await realpath(homedir())) throw Error('Actual temporary HOME was not selected before importing writers.'); const root = process.env.REA_REGISTRATION_FIXTURE_ROOT; @@ -76,6 +76,18 @@ const CHILD_PROGRAM = ` let result; try { const defaultsEnvironment = await environmentFor('defaults'); + if (process.platform !== 'win32') { + const runtimeDirectory = join(defaultsEnvironment.HOME, 'runtime'); + const runtimeAlias = join(defaultsEnvironment.HOME, 'runtime-alias'); + const outsideBin = join(defaultsEnvironment.HOME, 'outside-bin'); + const sessionBin = join(runtimeDirectory, 'bin'); + await mkdir(sessionBin, { recursive: true }); + await symlink(process.execPath, join(sessionBin, 'node')); + await symlink(runtimeDirectory, runtimeAlias, 'dir'); + await symlink(sessionBin, outsideBin, 'dir'); + defaultsEnvironment.PATH = outsideBin + delimiter + defaultsEnvironment.PATH; + defaultsEnvironment.XDG_RUNTIME_DIR = runtimeAlias; + } const schema = await serve(defaultsEnvironment, ['mcp','add','--schema','--json']); const all = await invoke(defaultsEnvironment, [], undefined); const native = []; diff --git a/tests/acceptance/setup/launcherAliasesCli.test.ts b/tests/acceptance/setup/launcherAliasesCli.test.ts index 423c206ce2..2f72ec6324 100644 --- a/tests/acceptance/setup/launcherAliasesCli.test.ts +++ b/tests/acceptance/setup/launcherAliasesCli.test.ts @@ -1,6 +1,7 @@ import { artifactMcpCall } from "../../../scripts/lib/artifact-e2e.mjs"; -import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; -import { join, resolve } from "node:path"; +import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { join, relative, resolve } from "node:path"; +import { parse as parseToml, stringify as stringifyToml } from "smol-toml"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; @@ -20,6 +21,192 @@ const registrationPathWithoutRuntime = async (root: string) => { return restrictedPath; }; +const savedLaunchers = z.record( + z.string(), + z + .object({ command: z.string(), args: z.array(z.string()).optional() }) + .passthrough(), +); + +const sessionLaunchers = async (home: string) => { + const runtimeDirectory = join(home, "run"); + const session = join(runtimeDirectory, "fnm_multishells/123_456"); + const bin = join(session, "bin"); + const installedBin = join(home, "fnm-install", "bin"); + const outsideBin = join(home, "outside-bin"); + const durableBin = join(home, "manager", "bin"); + const persistentScript = resolve("scripts/rea.mjs"); + await mkdir(join(runtimeDirectory, "fnm_multishells"), { recursive: true }); + await mkdir(installedBin, { recursive: true }); + await mkdir(durableBin, { recursive: true }); + await symlink(process.execPath, join(installedBin, "node")); + await symlink(persistentScript, join(installedBin, "rea")); + await symlink(join(installedBin, ".."), session, "dir"); + await symlink(relative(home, bin), outsideBin, "dir"); + await symlink(process.execPath, join(durableBin, "node")); + return { + runtimeDirectory, + session, + bin, + outsideBin, + durableBin, + persistentScript, + }; +}; + +cliTest.skipIf(process.platform === "win32").for([ + { clientId: "codex", relativeConfig: ".codex/config.toml" }, + { clientId: "claude_code", relativeConfig: ".claude.json" }, +] as const)( + "registers and repairs a persistent MCP launcher for $clientId", + async ({ clientId, relativeConfig }, { cli }) => { + const home = await createTestTempDirectory("rea-session-launcher-"); + const config = join(home, relativeConfig); + const { + runtimeDirectory, + session, + bin, + outsideBin, + durableBin, + persistentScript, + } = await sessionLaunchers(home); + const codex = clientId === "codex"; + const sessionBin = codex ? bin : outsideBin; + const interpreter = join(sessionBin, "node"); + const script = join(sessionBin, "rea"); + const rootKey = codex ? "mcp_servers" : "mcpServers"; + const parse = codex + ? parseToml + : (source: string): unknown => JSON.parse(source); + const serialize = codex ? stringifyToml : JSON.stringify; + const unrelated = { command: "unrelated", args: ["keep"] }; + const read = async () => { + const document = z + .record(z.string(), z.unknown()) + .parse(parse(await readFile(config, "utf8"))); + return savedLaunchers.parse(document[rootKey]); + }; + await mkdir(join(home, ".codex")); + await writeFile(config, serialize({ [rootKey]: { unrelated } })); + const subprocessPath = await registrationPathWithoutRuntime(home); + const freshEnvironment = { + HOME: home, + USERPROFILE: home, + CODEX_HOME: join(home, ".codex"), + CLAUDE_CONFIG_DIR: home, + XDG_CONFIG_HOME: join(home, ".config"), + FNM_MULTISHELL_PATH: undefined, + XDG_RUNTIME_DIR: undefined, + PATH: subprocessPath, + }; + const setup = ["setup", "--client", clientId, "--skill=false", "--json"]; + const doctorArgs = [ + "doctor", + "--client", + clientId, + "--skill=false", + "--json", + ]; + const run = ( + arguments_: readonly string[], + environment: NodeJS.ProcessEnv = freshEnvironment, + ) => + cli.run({ + arguments: arguments_, + cwd: home, + environment, + freshProcess: true, + }); + const initial = await run([...setup, "--yes"], { + ...freshEnvironment, + XDG_RUNTIME_DIR: runtimeDirectory, + FNM_MULTISHELL_PATH: session, + PATH: [sessionBin, durableBin, subprocessPath].join(":"), + }); + expect(initial.exitCode, initial.stdout).toBe(0); + const installed = await read(); + expect(installed.rea).toMatchObject({ + command: join(durableBin, "node"), + args: [persistentScript, "mcp"], + }); + expect(installed.unrelated).toEqual(unrelated); + + // Older REA versions accepted both live session paths as equivalent. + const legacy = serialize({ + [rootKey]: { + ...installed, + rea: { ...installed.rea, command: interpreter, args: [script, "mcp"] }, + }, + }); + await writeFile(config, legacy); + expect((await run(doctorArgs)).json).toMatchObject({ + scope_checks: expect.arrayContaining([ + expect.objectContaining({ + name: `registration:${clientId}`, + classification: "config_drift", + remediation: expect.stringContaining("uses a session path"), + }), + ]), + }); + const preview = await run([...setup, "--dry-run"]); + expect(preview.exitCode, preview.stdout).toBe(0); + expect((await read()).rea?.command).toBe(interpreter); + const refresh = await run([...setup, "--yes"]); + expect(refresh.exitCode, refresh.stdout).toBe(0); + const repaired = await read(); + expect(repaired.rea).toMatchObject({ + command: process.execPath, + args: [persistentScript, "mcp"], + }); + expect(repaired.unrelated).toEqual(unrelated); + + await rm(runtimeDirectory, { recursive: true }); + const transport = new StdioClientTransport({ + command: repaired.rea!.command, + args: repaired.rea!.args!, + cwd: home, + env: { PATH: subprocessPath }, + stderr: "pipe", + }); + const client = new Client( + { name: "persistent-launcher", version: "1" }, + { jsonSchemaValidator: createMcpSchemaValidation() }, + ); + try { + await client.connect(transport); + expect( + (await client.listTools()).tools.map(({ name }) => name), + ).toContain("list_unknowns"); + expect( + ( + await artifactMcpCall(client, { + name: "list_unknowns", + arguments: {}, + }) + ).isError, + ).not.toBe(true); + } finally { + await client.close(); + await transport.close(); + } + + await writeFile(config, legacy); + const doctor = await run(doctorArgs); + expect(doctor.json).toMatchObject({ + scope_checks: expect.arrayContaining([ + expect.objectContaining({ + name: `registration:${clientId}`, + classification: "unknown", + remediation: expect.stringContaining(`${interpreter} is missing`), + }), + ]), + }); + const blocked = await run([...setup, "--yes"]); + expect(blocked.exitCode, blocked.stdout).toBe(1); + expect(await readFile(config, "utf8")).toBe(legacy); + }, +); + cliTest.skipIf(process.platform === "win32")( "migrates an owned shebang registration and starts its generated MCP command without a runtime on PATH", async ({ cli }) => { diff --git a/tests/boundary/cli/packageRunnerRegistration.test.ts b/tests/boundary/cli/packageRunnerRegistration.test.ts index eb7952962e..91f609ac26 100644 --- a/tests/boundary/cli/packageRunnerRegistration.test.ts +++ b/tests/boundary/cli/packageRunnerRegistration.test.ts @@ -1,6 +1,7 @@ import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; import { mkdir, readFile, writeFile } from "node:fs/promises"; -import { delimiter, join, resolve } from "node:path"; +import { delimiter, dirname, join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; import { expect } from "vitest"; import { z } from "zod"; @@ -15,6 +16,77 @@ const ompConfigurationSchema = z.object({ }), }); +cliTest.skipIf(process.platform !== "win32")( + "mcp add blocks an implicit MSIX-private launcher before writing client files", + async ({ processes }) => { + const home = await createTestTempDirectory("rea-msix-mcp-add-"); + const environment = await registrationEnvironment(home, { + CLAUDE_CONFIG_DIR: home, + }); + const isolatedConfig = join(home, ".claude.json"); + const installed = join(home, "installed", "rea.mjs"); + const privateEntry = join( + home, + "localappdata", + "Packages", + "Fixture_123", + "LocalCache", + "rea.mjs", + ); + const original = '{"mcpServers":{"other":{"command":"unchanged"}}}\n'; + const launcher = `import ${JSON.stringify(pathToFileURL(resolve("scripts/rea.mjs")).href)};\n`; + for (const entry of [installed, privateEntry]) { + await mkdir(dirname(entry), { recursive: true }); + await writeFile(entry, launcher); + } + await writeFile(isolatedConfig, original); + const run = (entry: string, args: readonly string[] = []) => + processes.run( + process.execPath, + [entry, "mcp", "add", "--agent", "claude-code", "--json", ...args], + { + cwd: home, + env: environment, + }, + ); + + const blocked = await run(privateEntry); + expect(blocked.exitCode, blocked.stderr).toBe(1); + expect(JSON.parse(blocked.stdout)).toMatchObject({ + code: "VALIDATION_ERROR", + message: expect.stringContaining( + "inside the private storage of MSIX package Fixture_123", + ), + fieldErrors: [expect.objectContaining({ path: "command" })], + }); + expect(await readFile(isolatedConfig, "utf8")).toBe(original); + await expect( + readFile(`${isolatedConfig}.rea.backup`, "utf8"), + ).rejects.toMatchObject({ code: "ENOENT" }); + + const allowed = await run(installed); + expect(allowed.exitCode, allowed.stderr).toBe(0); + expect(JSON.parse(await readFile(isolatedConfig, "utf8"))).toMatchObject({ + mcpServers: { + rea: { command: process.execPath, args: [installed, "mcp"] }, + other: { command: "unchanged" }, + }, + }); + expect(await readFile(`${isolatedConfig}.rea.backup`, "utf8")).toBe( + original, + ); + + const explicit = await run(privateEntry, [ + "--command", + '"custom executable" mcp', + ]); + expect(explicit.exitCode, explicit.stderr).toBe(0); + expect(JSON.parse(await readFile(isolatedConfig, "utf8"))).toMatchObject({ + mcpServers: { rea: { command: "custom executable", args: ["mcp"] } }, + }); + }, +); + const controlledRunnerFixture = async (home: string) => { const bin = join(home, "bin"); const script = join(home, "runner-fixture.cjs"); diff --git a/tests/boundary/filesystem/setupLauncherAlias.test.ts b/tests/boundary/filesystem/setupLauncherAlias.test.ts index 33c3f3b5a1..c8c58ec50c 100644 --- a/tests/boundary/filesystem/setupLauncherAlias.test.ts +++ b/tests/boundary/filesystem/setupLauncherAlias.test.ts @@ -89,14 +89,13 @@ it.skipIf(process.platform === "win32").each(["node", "bun"] as const)( "linux", ); expect(selected).toBe(alias); - expect(await realpath(selected)).toBe(executable); + expect(await realpath(alias)).toBe(executable); await rm(latest); await symlink(next, latest, "dir"); await rm(old, { recursive: true }); await expect(access(executable)).rejects.toMatchObject({ code: "ENOENT" }); - await access(selected); - expect(await realpath(selected)).toBe(join(next, runtime)); + expect(await realpath(alias)).toBe(join(next, runtime)); expect( registrationRuntimePath( join(next, runtime), @@ -108,6 +107,33 @@ it.skipIf(process.platform === "win32").each(["node", "bun"] as const)( }, ); +it.skipIf(process.platform === "win32")( + "resolves an explicitly selected session script to the installed file", + async () => { + const root = await createTestTempDirectory("rea-session-entrypoint-"); + const directory = join(root, "custom-session"); + await mkdir(directory); + const script = join(root, "rea.mjs"); + const entrypoint = join(directory, "rea"); + await writeFile(script, "// installed REA script\n"); + await symlink(script, entrypoint); + const command = () => + currentClientRegistrationCommand({ + platform: "linux", + entrypointPath: entrypoint, + environment: { FNM_MULTISHELL_PATH: directory, PATH: directory }, + }); + expect(command()).toEqual([process.execPath, script, "mcp"]); + + await rm(entrypoint); + await writeFile( + entrypoint, + "// script installed only inside the session\n", + ); + expect(command()).toEqual([]); + }, +); + it.skipIf(process.platform === "win32")( "does not replace the selected runtime with a foreign executable or manager shim", async () => {