mirror of
https://github.com/morluto/rea.git
synced 2026-12-03 21:46:01 +00:00
* fix(setup): own REA scripts when the registered Node path is gone When a saved node/script/mcp launcher pointed at a missing interpreter, ownership stayed unknown and setup refused to refresh after nvm/fnm moved Node. Check the script whenever a current entrypoint is available, not only when the interpreter path still resolves as a foreign binary. Fixes #15024 * fix(setup): own vanished Node only for verified rea-agents scripts Narrow the missing-interpreter path: keep a disappeared runtime unknown unless its basename is node/bun and the script verifies as an installed rea-agents package. Preserve the existing foreign-runtime script check and the maintainer invariant that a matching non-package script stays unknown after the executable vanishes. Merge upstream/main for ownedPackageCommand OpenCode fixtures.
1037 lines
34 KiB
TypeScript
1037 lines
34 KiB
TypeScript
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
|
|
import {
|
|
accessSync,
|
|
constants,
|
|
lstatSync,
|
|
readFileSync,
|
|
readlinkSync,
|
|
realpathSync,
|
|
statSync,
|
|
} from "node:fs";
|
|
import { dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
|
|
import {
|
|
CURRENT_ENTRYPOINT_PATH,
|
|
normalizeEntrypointPath,
|
|
} from "../process/CurrentEntrypointPath.js";
|
|
import { valid } from "semver";
|
|
|
|
import {
|
|
javaScriptRuntime,
|
|
type JavaScriptRuntime,
|
|
} from "../domain/runtimeVersion.js";
|
|
import {
|
|
posixPathCandidates,
|
|
windowsPathCandidates,
|
|
} from "../process/executableSearch.js";
|
|
import {
|
|
absoluteCallerPath,
|
|
appendCallerPath,
|
|
hasParentTraversal,
|
|
} from "../filesystem/callerPath.js";
|
|
import { PRODUCT_IDENTITY } from "../identity.js";
|
|
import {
|
|
aubeShimLauncher,
|
|
aubeShimRegistration,
|
|
inspectAubeShim,
|
|
type AubeShimInspection,
|
|
type AubeShimLauncher,
|
|
registeredAubeShim,
|
|
} from "../process/AubeBinShim.js";
|
|
import {
|
|
msixPackagesDirectory,
|
|
packagePrivateLauncherBlocker,
|
|
} from "./MsixPackageStorage.js";
|
|
import {
|
|
installedReaPackageEvidence,
|
|
removedNpxReaScript,
|
|
} from "./InstalledReaPackage.js";
|
|
|
|
/** Package runners recognized for invocation guidance and legacy registrations. */
|
|
type PackageRunner = "npx" | "bunx";
|
|
|
|
/** Read one variable; Windows variable names are case-insensitive. */
|
|
const environmentValue = (
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
name: string,
|
|
platform: NodeJS.Platform,
|
|
): string | undefined => {
|
|
if (platform !== "win32") return environment[name];
|
|
const target = name.toLowerCase();
|
|
const key = Object.keys(environment).findLast(
|
|
(candidate) => candidate.toLowerCase() === target,
|
|
);
|
|
return key === undefined ? undefined : environment[key];
|
|
};
|
|
|
|
/** Identify the package runner that launched this process, if any. */
|
|
export const invokingPackageRunner = (
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
platform: NodeJS.Platform,
|
|
): PackageRunner | undefined => {
|
|
if (environmentValue(environment, "npm_command", platform) !== "exec")
|
|
return undefined;
|
|
// `bunx` and `bun x` also report npm_command=exec, with a bun user agent.
|
|
return environmentValue(
|
|
environment,
|
|
"npm_config_user_agent",
|
|
platform,
|
|
)?.startsWith("bun/") === true
|
|
? "bunx"
|
|
: "npx";
|
|
};
|
|
|
|
/** Copy an environment without the variable that marks a package-runner launch. */
|
|
export const withoutPackageRunnerIdentity = (
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
platform: NodeJS.Platform,
|
|
): NodeJS.ProcessEnv =>
|
|
Object.fromEntries(
|
|
Object.entries(environment).filter(([key]) =>
|
|
platform === "win32"
|
|
? key.toLowerCase() !== "npm_command"
|
|
: key !== "npm_command",
|
|
),
|
|
);
|
|
|
|
/** A supported managed shim owns both the script and interpreter. */
|
|
export const managedClientLauncher = (
|
|
entrypoint: string | undefined,
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
platform: NodeJS.Platform,
|
|
): AubeShimLauncher | undefined => {
|
|
if (
|
|
platform === "win32" ||
|
|
entrypoint === undefined ||
|
|
javaScriptRuntime(process.versions).id !== "node"
|
|
)
|
|
return undefined;
|
|
const roots = transientLauncherRoots(environment);
|
|
if (
|
|
usesTransientLauncherPath(entrypoint, roots) ||
|
|
usesTransientLauncherPath(process.execPath, roots)
|
|
)
|
|
return undefined;
|
|
const launcher = aubeShimLauncher(
|
|
entrypoint,
|
|
PRODUCT_IDENTITY.cliBinary,
|
|
process.execPath,
|
|
);
|
|
if (launcher === undefined || usesTransientLauncherPath(launcher.shim, roots))
|
|
return undefined;
|
|
// A fallback that walks through the sibling fails when the sibling disappears.
|
|
const fallbackRuntime = registrationRuntimePath(
|
|
process.execPath,
|
|
"node",
|
|
environment,
|
|
platform,
|
|
launcher.siblingRuntime,
|
|
);
|
|
return fallbackRuntime === undefined
|
|
? undefined
|
|
: { shim: launcher.shim, fallbackRuntime };
|
|
};
|
|
|
|
/** 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<NodeJS.ProcessEnv>,
|
|
): 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: {
|
|
readonly platform?: NodeJS.Platform;
|
|
readonly entrypointPath?: string | undefined;
|
|
readonly environment?: Readonly<NodeJS.ProcessEnv>;
|
|
} = {},
|
|
): readonly string[] => {
|
|
// The registration names this process's runtime, so it defaults to this host.
|
|
const platform = selection.platform ?? HOST_PLATFORM.platform;
|
|
const environment = selection.environment ?? process.env;
|
|
const entrypointPath = Object.hasOwn(selection, "entrypointPath")
|
|
? selection.entrypointPath
|
|
: CURRENT_ENTRYPOINT_PATH;
|
|
if (entrypointPath === undefined || entrypointPath.length === 0) return [];
|
|
const managed = managedClientLauncher(entrypointPath, environment, platform);
|
|
if (managed !== undefined) return aubeShimRegistration(managed);
|
|
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"];
|
|
};
|
|
|
|
/** Command spelling may be path-qualified; Windows and POSIX separators both appear in fixtures. */
|
|
const commandFileName = (path: string): string =>
|
|
(path.split(/[/\\]/u).at(-1) ?? path).toLowerCase();
|
|
|
|
const unwrapCmdCommand = (command: readonly string[]): readonly string[] => {
|
|
const executable = command[0];
|
|
if (executable === undefined) return command;
|
|
const name = commandFileName(executable);
|
|
if (name !== "cmd" && name !== "cmd.exe") return command;
|
|
if (command[1]?.toLowerCase() === "/c") return command.slice(2);
|
|
if (command[1]?.toLowerCase() === "/d" && command[2]?.toLowerCase() === "/c")
|
|
return command.slice(3);
|
|
return [];
|
|
};
|
|
|
|
/**
|
|
* npm's cmd-shim is a short generated batch file. Larger files are not that
|
|
* format; refuse them before allocating their contents for ownership.
|
|
*/
|
|
const NPM_CMD_SHIM_BYTES = 64 * 1024;
|
|
|
|
const readBoundedRegularFile = (
|
|
path: string,
|
|
maximumBytes: number,
|
|
): string | undefined => {
|
|
try {
|
|
const stat = statSync(path);
|
|
if (!stat.isFile() || stat.size === 0 || stat.size > maximumBytes)
|
|
return undefined;
|
|
const contents = readFileSync(path, {
|
|
flag: constants.O_RDONLY | constants.O_NONBLOCK,
|
|
});
|
|
return contents.length <= maximumBytes
|
|
? contents.toString("utf8")
|
|
: undefined;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Exact non-empty preamble lines emitted by npm's `cmd-shim` for a Node CLI
|
|
* entrypoint (`#!/usr/bin/env node` with no extra shebang arguments).
|
|
*/
|
|
const NPM_CMD_SHIM_PREAMBLE_LINES: readonly RegExp[] = [
|
|
/^@echo off$/iu,
|
|
/^goto start$/iu,
|
|
/^:find_dp0$/iu,
|
|
/^set dp0=%~dp0$/iu,
|
|
/^exit \/b$/iu,
|
|
/^:start$/iu,
|
|
/^setlocal$/iu,
|
|
/^call :find_dp0$/iu,
|
|
/^if exist "%dp0%[\\/]node\.exe" \($/iu,
|
|
/^set "_prog=%dp0%[\\/]node\.exe"$/iu,
|
|
/^\) else \($/iu,
|
|
/^set "_prog=node"$/iu,
|
|
];
|
|
|
|
const NPM_CMD_SHIM_LAUNCH =
|
|
/^endLocal & (?:goto #_undefined_# 2>NUL \|\| title %COMSPEC% & )?(set PATHEXT=%PATHEXT:;\.JS;=;% & )?"%_prog%"\s+"%dp0%([\\/][^"%!]+)"\s+%\*$/iu;
|
|
|
|
/**
|
|
* Recover the script an npm Windows `rea.cmd` shim launches. Ownership matches
|
|
* only the generated npm `cmd-shim` wrapper verbatim so customized, commented,
|
|
* or variable-overridden batch files stay unknown.
|
|
*/
|
|
const windowsReaCmdScript = (cmdPath: string): string | undefined => {
|
|
if (commandFileName(cmdPath) !== `${PRODUCT_IDENTITY.cliBinary}.cmd`)
|
|
return undefined;
|
|
// cmd-shim expands this directory in an unquoted SET before launching Node.
|
|
// Operators and expansion characters can change that preamble's meaning.
|
|
if (/[\r\n"&|<>^%!]/u.test(cmdPath)) return undefined;
|
|
const text = readBoundedRegularFile(cmdPath, NPM_CMD_SHIM_BYTES);
|
|
if (text === undefined) return undefined;
|
|
const lines = text
|
|
.split(/\r?\n/u)
|
|
.map((line) => line.trim())
|
|
.filter((line) => line !== "");
|
|
// cmd-shim 9 moves PATHEXT from the ELSE block to the final launch line.
|
|
const legacy = lines.length === NPM_CMD_SHIM_PREAMBLE_LINES.length + 3;
|
|
if (!legacy && lines.length !== NPM_CMD_SHIM_PREAMBLE_LINES.length + 2)
|
|
return undefined;
|
|
for (let index = 0; index < NPM_CMD_SHIM_PREAMBLE_LINES.length; index++) {
|
|
if (!NPM_CMD_SHIM_PREAMBLE_LINES[index]!.test(lines[index]!))
|
|
return undefined;
|
|
}
|
|
if (lines.at(-2) !== ")") return undefined;
|
|
if (legacy && !/^set pathext=%pathext:;\.js;=;%$/iu.test(lines.at(-3)!))
|
|
return undefined;
|
|
const match = NPM_CMD_SHIM_LAUNCH.exec(lines[lines.length - 1]!);
|
|
if (match === null || (match[1] === undefined) !== legacy) return undefined;
|
|
const relative = match[2]!.replace(/^[\\/]/u, "");
|
|
const rawParts = relative.split(/[/\\]/u);
|
|
if (rawParts.slice(1).includes("..")) return undefined;
|
|
// Host path rules: Windows keeps UNC `//server/share` roots; fixtures on
|
|
// POSIX keep their own separators.
|
|
const joined =
|
|
HOST_PLATFORM.platform === "win32"
|
|
? win32.join(win32.dirname(cmdPath), relative.replace(/\//gu, "\\"))
|
|
: posix.join(posix.dirname(cmdPath), relative.replace(/\\/gu, "/"));
|
|
const joinedParts = joined.split(/[/\\]/u).map((part) => part.toLowerCase());
|
|
const modules = joinedParts.lastIndexOf("node_modules");
|
|
if (
|
|
modules < 0 ||
|
|
joinedParts[modules + 1] !== PRODUCT_IDENTITY.packageName.toLowerCase() ||
|
|
joinedParts.length <= modules + 2
|
|
)
|
|
return undefined;
|
|
return joined;
|
|
};
|
|
|
|
const isRegularFile = (path: string): boolean => {
|
|
try {
|
|
return statSync(path).isFile();
|
|
} catch {
|
|
return false;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* First PATH hit for a bare CLI name that is a regular file. A working-
|
|
* directory-dependent PATH entry reached before a hit keeps the result
|
|
* unknown: the client's cwd is not known here.
|
|
*/
|
|
const resolveBareCliOnPath = (
|
|
name: string,
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
): string | "unknown" | undefined => {
|
|
if (HOST_PLATFORM.platform === "win32") {
|
|
const search = windowsPathCandidates(name, environment, {
|
|
allowBatch: true,
|
|
cwd: "C:\\",
|
|
});
|
|
if (!search.ok) return "unknown";
|
|
for (const candidate of search.value) {
|
|
if (candidate.relativeEntry) return "unknown";
|
|
if (!isRegularFile(candidate.path)) continue;
|
|
return candidate.path;
|
|
}
|
|
return undefined;
|
|
}
|
|
for (const candidate of posixPathCandidates(name, environment.PATH ?? "", {
|
|
relativeEntries: "resolve",
|
|
unreadableWorkingDirectory: "as-written",
|
|
})) {
|
|
if (candidate.relativeEntry) return "unknown";
|
|
try {
|
|
accessSync(candidate.path, constants.X_OK);
|
|
} catch {
|
|
continue;
|
|
}
|
|
if (!isRegularFile(candidate.path)) continue;
|
|
return candidate.path;
|
|
}
|
|
return undefined;
|
|
};
|
|
|
|
/**
|
|
* True when the file selected by executable lookup belongs to this package.
|
|
* Walk from the realpath of that file (or its spelled path when realpath fails);
|
|
* do not reinterpret a native launcher as a Node script argument.
|
|
*/
|
|
const launcherBelongsToProduct = (launcher: string): boolean => {
|
|
let resolved = launcher;
|
|
try {
|
|
resolved = realpathSync.native(launcher);
|
|
} catch {
|
|
// Keep the spelled path when realpath cannot prove the leaf.
|
|
}
|
|
let directory = dirname(resolved);
|
|
for (let depth = 0; depth < 8; depth++) {
|
|
try {
|
|
const name = (
|
|
JSON.parse(readFileSync(join(directory, "package.json"), "utf8")) as {
|
|
name?: unknown;
|
|
}
|
|
).name;
|
|
if (typeof name === "string")
|
|
return name === PRODUCT_IDENTITY.packageName;
|
|
} catch {
|
|
// Climb until a package.json is readable or the root is reached.
|
|
}
|
|
const parent = dirname(directory);
|
|
if (parent === directory) break;
|
|
directory = parent;
|
|
}
|
|
return false;
|
|
};
|
|
|
|
/** The script a PATH hit launches: npm `rea.cmd` unwrap, else the file itself. */
|
|
const bareCliLaunchTarget = (resolved: string): string | undefined => {
|
|
if (commandFileName(resolved) === `${PRODUCT_IDENTITY.cliBinary}.cmd`)
|
|
return windowsReaCmdScript(resolved);
|
|
return resolved;
|
|
};
|
|
|
|
/** Preserve the package argument from a supported package-runner command. */
|
|
const clientRegistrationPackageReference = (
|
|
command: readonly string[],
|
|
): string | undefined => {
|
|
const arguments_ = unwrapCmdCommand(command);
|
|
if (
|
|
arguments_.length === 4 &&
|
|
arguments_[0] === "npx" &&
|
|
arguments_[1] === "-y" &&
|
|
arguments_[3] === "mcp"
|
|
)
|
|
return arguments_[2];
|
|
if (
|
|
arguments_.length === 3 &&
|
|
arguments_[0] === "bunx" &&
|
|
arguments_[2] === "mcp"
|
|
)
|
|
return arguments_[1];
|
|
return undefined;
|
|
};
|
|
|
|
/** Check that one parsed command points to REA's MCP entry point. */
|
|
export type ClientRegistrationCommandIdentity = "owned" | "foreign" | "unknown";
|
|
|
|
/** Compare entrypoint paths without turning failed resolution into a foreign identity. */
|
|
const entrypointIdentity = (
|
|
candidate: string,
|
|
current: string,
|
|
): ClientRegistrationCommandIdentity => {
|
|
if (!isAbsolute(candidate) || !isAbsolute(current)) return "unknown";
|
|
if (candidate === current) return "owned";
|
|
// Bun's realpath can normalize parent segments differently from its launcher.
|
|
// Without matching traversal semantics it cannot prove ownership of an alias.
|
|
// The comparison resolves paths on this host's filesystem.
|
|
if (
|
|
HOST_PLATFORM.platform !== "win32" &&
|
|
javaScriptRuntime(process.versions).id === "bun" &&
|
|
[candidate, current].some(hasParentTraversal)
|
|
)
|
|
return "unknown";
|
|
try {
|
|
return realpathSync.native(candidate) === realpathSync.native(current)
|
|
? "owned"
|
|
: "foreign";
|
|
} catch {
|
|
return "unknown";
|
|
}
|
|
};
|
|
|
|
/** Ownership of an absolute REA entry and which installation it selects. */
|
|
type EntrypointOwnership = Pick<
|
|
ClientRegistrationCommandFacts,
|
|
"identity" | "installation"
|
|
>;
|
|
|
|
/**
|
|
* Another installed REA package still owns the registration, so setup can
|
|
* refresh it; it does not select this installation. Unresolved package
|
|
* evidence leaves ownership unknown.
|
|
*/
|
|
const entrypointOwnership = (
|
|
identity: ClientRegistrationCommandIdentity,
|
|
candidate: string,
|
|
): EntrypointOwnership => {
|
|
if (identity === "owned") return { identity, installation: "current" };
|
|
if (identity !== "foreign") return { identity };
|
|
const evidence = installedReaPackageEvidence(candidate);
|
|
if (evidence === "verified")
|
|
return { identity: "owned", installation: "other" };
|
|
return evidence === "unknown" ? { identity: "unknown" } : { identity };
|
|
};
|
|
|
|
/**
|
|
* A launcher under another runtime never selects this installation, but its
|
|
* script may still be this installation's or another installed REA package's.
|
|
* That runtime may follow Node's lexical `..` or native traversal, so both
|
|
* spellings must select the current script.
|
|
*/
|
|
const otherRuntimeScriptOwnership = (
|
|
script: string,
|
|
currentCommandPath: string,
|
|
): EntrypointOwnership => {
|
|
const current = [...new Set([script, resolve(script)])].map(
|
|
(spelling) => entrypointIdentity(spelling, currentCommandPath) === "owned",
|
|
);
|
|
if (current.every(Boolean))
|
|
return { identity: "owned", installation: "other" };
|
|
if (current.some(Boolean)) return { identity: "unknown" };
|
|
return entrypointOwnership("foreign", script);
|
|
};
|
|
|
|
/**
|
|
* A shim that starts another runtime cannot select this installation, but its
|
|
* target may still be this installation's script or another installed REA
|
|
* package. Undefined proves nothing.
|
|
*/
|
|
const aubeShimOwnership = (
|
|
shim: AubeShimInspection | undefined,
|
|
currentCommandPath: string | undefined,
|
|
): EntrypointOwnership | undefined => {
|
|
if (
|
|
shim === undefined ||
|
|
currentCommandPath === undefined ||
|
|
currentCommandPath.length === 0
|
|
)
|
|
return undefined;
|
|
if (shim.runtime === "current")
|
|
return entrypointOwnership(
|
|
entrypointIdentity(shim.target, currentCommandPath),
|
|
shim.target,
|
|
);
|
|
const ownership = otherRuntimeScriptOwnership(
|
|
shim.target,
|
|
currentCommandPath,
|
|
);
|
|
return ownership.identity === "foreign" ? undefined : ownership;
|
|
};
|
|
|
|
/** A direct launcher may be a native executable or a Node shebang script. */
|
|
const directEntrypointIdentity = (
|
|
candidate: string,
|
|
current: string,
|
|
): ClientRegistrationCommandIdentity => {
|
|
const nativeIdentity = entrypointIdentity(candidate, current);
|
|
const scriptPath = normalizeEntrypointPath(candidate, "node");
|
|
if (scriptPath === candidate) return nativeIdentity;
|
|
// A shebang can pass the original spelling to Node, which selects its script
|
|
// lexically. Without executing the launcher, divergent interpretations are unknown.
|
|
return scriptPath !== undefined &&
|
|
entrypointIdentity(scriptPath, current) === nativeIdentity
|
|
? nativeIdentity
|
|
: "unknown";
|
|
};
|
|
|
|
/** Preserve a manager-owned executable alias only when it selects the same file. */
|
|
const sameFileExecutableAlias = (
|
|
selected: string,
|
|
name: string,
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
identify: typeof entrypointIdentity,
|
|
excludedPath?: string,
|
|
): string | undefined => {
|
|
const roots = transientLauncherRoots(environment);
|
|
const excluded = (path: string) =>
|
|
launcherPathWalksThrough(
|
|
path,
|
|
(hop) => hop === excludedPath || transientLauncherPath(hop, roots),
|
|
);
|
|
let fallback = selected;
|
|
if (excluded(selected)) {
|
|
try {
|
|
fallback = realpathSync.native(selected);
|
|
if (excluded(fallback) || 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 (excluded(candidate)) continue;
|
|
try {
|
|
accessSync(candidate, constants.X_OK);
|
|
return candidate;
|
|
} catch {
|
|
// An unexecutable alias cannot launch the selected program.
|
|
}
|
|
}
|
|
return fallback;
|
|
};
|
|
|
|
/** Follow directory and file links in POSIX order before realpath erases the hops. */
|
|
const launcherPathWalksThrough = (
|
|
path: string,
|
|
matches: (hop: string) => boolean,
|
|
): boolean => {
|
|
if (!posix.isAbsolute(path)) return false;
|
|
const activeLinks = new Set<string>();
|
|
const matched = Symbol("matched");
|
|
const walk = (
|
|
target: string,
|
|
directory: string,
|
|
): string | typeof matched | undefined => {
|
|
const absolute = posix.isAbsolute(target);
|
|
const spelled = absolute
|
|
? target
|
|
: appendCallerPath(directory, target, "linux");
|
|
if (matches(spelled)) return matched;
|
|
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 (matches(next)) return matched;
|
|
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, "/") === matched;
|
|
} catch {
|
|
// Missing evidence cannot prove that a path goes through the matched hop.
|
|
// Ownership and launch readiness are checked independently.
|
|
return false;
|
|
}
|
|
};
|
|
|
|
const usesTransientLauncherPath = (
|
|
path: string,
|
|
roots: readonly string[],
|
|
): boolean =>
|
|
launcherPathWalksThrough(path, (hop) => transientLauncherPath(hop, roots));
|
|
|
|
const transientLauncherRoots = (
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
): 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<NodeJS.ProcessEnv>,
|
|
platform: NodeJS.Platform,
|
|
): readonly string[] => {
|
|
if (platform === "win32") return [];
|
|
const shim = registeredAubeShim(command);
|
|
const paths =
|
|
shim !== undefined
|
|
? [shim.shim, shim.fallbackRuntime]
|
|
: command.length === 3 && command[2] === "mcp"
|
|
? command.slice(0, 2)
|
|
: [];
|
|
if (paths.length === 0) return [];
|
|
const roots = transientLauncherRoots(environment);
|
|
return paths.filter((path) => usesTransientLauncherPath(path, roots));
|
|
};
|
|
|
|
/** Prefer an executable PATH alias that proves the same selected REA file. */
|
|
const registrationEntrypointPath = (
|
|
entrypoint: string,
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
platform: NodeJS.Platform,
|
|
): 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"
|
|
? entrypoint
|
|
: sameFileExecutableAlias(
|
|
entrypoint,
|
|
PRODUCT_IDENTITY.cliBinary,
|
|
environment,
|
|
directEntrypointIdentity,
|
|
);
|
|
|
|
/** Prefer a same-file runtime alias that can survive its manager's version switch. */
|
|
export const registrationRuntimePath = (
|
|
executable: string,
|
|
runtime: JavaScriptRuntime["id"],
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
platform: NodeJS.Platform,
|
|
excludedPath?: string,
|
|
): string | undefined =>
|
|
platform === "win32"
|
|
? executable
|
|
: sameFileExecutableAlias(
|
|
executable,
|
|
runtime,
|
|
environment,
|
|
entrypointIdentity,
|
|
excludedPath,
|
|
);
|
|
|
|
/** Preserve aliases only when the execution form and selected file agree. */
|
|
export const equivalentClientRegistrationCommands = (
|
|
previous: readonly string[],
|
|
requested: readonly string[],
|
|
environment: Readonly<NodeJS.ProcessEnv>,
|
|
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])
|
|
)
|
|
return true;
|
|
const requestedFacts = inspectClientRegistrationCommand(requested, undefined);
|
|
const current = requestedFacts.entrypoint;
|
|
if (current === undefined) return false;
|
|
const prior = inspectClientRegistrationCommand(previous, current);
|
|
return (
|
|
prior.entrypoint !== undefined &&
|
|
prior.identity === "owned" &&
|
|
prior.installation === "current" &&
|
|
prior.launch === requestedFacts.launch &&
|
|
(prior.launch !== "managed_shim" || prior.independentFallback === true)
|
|
);
|
|
};
|
|
|
|
export interface ClientRegistrationCommandFacts {
|
|
readonly identity: ClientRegistrationCommandIdentity;
|
|
/** Execution form is separate from ownership of the selected REA file. */
|
|
readonly launch:
|
|
| "runtime_script"
|
|
| "managed_shim"
|
|
| "direct"
|
|
| "package_runner"
|
|
| "unknown";
|
|
/** Selected absolute launcher/script path; excludes package and unresolved PATH commands. */
|
|
readonly entrypoint: string | undefined;
|
|
/**
|
|
* Whether an owned absolute launcher selects this installation (runtime and
|
|
* REA entry) or another installed REA package or runtime. Absent when no
|
|
* owned absolute launcher was resolved.
|
|
*/
|
|
readonly installation?: "current" | "other";
|
|
/** The owned launcher is REA's script in an npx cache entry npm has removed. */
|
|
readonly removedNpxCache?: true;
|
|
/** The fallback must reach the current interpreter without the shim's sibling. */
|
|
readonly independentFallback?: boolean;
|
|
readonly package:
|
|
| {
|
|
readonly reference: string;
|
|
readonly exactVersion: string | undefined;
|
|
}
|
|
| undefined;
|
|
}
|
|
|
|
/** Optional lookup context for bare PATH commands. */
|
|
export interface ClientRegistrationCommandLookup {
|
|
/** Effective environment for PATH resolution; defaults to `process.env`. */
|
|
readonly environment?: Readonly<NodeJS.ProcessEnv>;
|
|
/**
|
|
* True when the registration's PATH is an expression the client expands
|
|
* (for example Qwen `${PATH}`), so this process cannot name the launcher.
|
|
*/
|
|
readonly unresolvedPath?: boolean;
|
|
}
|
|
|
|
/** Parse package identity once, retaining exact source spelling and version facts. */
|
|
export const inspectClientRegistrationCommand = (
|
|
command: readonly string[],
|
|
currentCommandPath: string | undefined,
|
|
lookup: ClientRegistrationCommandLookup = {},
|
|
): ClientRegistrationCommandFacts => {
|
|
const reference = clientRegistrationPackageReference(command);
|
|
if (reference !== undefined) {
|
|
const prefix = `${PRODUCT_IDENTITY.packageName}@`;
|
|
const version = reference.startsWith(prefix)
|
|
? reference.slice(prefix.length)
|
|
: undefined;
|
|
const normalized = version === undefined ? null : valid(version);
|
|
const owned =
|
|
reference === PRODUCT_IDENTITY.packageName ||
|
|
reference === PRODUCT_IDENTITY.packageSpecifier ||
|
|
reference === PRODUCT_IDENTITY.registrationPackageSpecifier ||
|
|
normalized !== null;
|
|
return {
|
|
identity: owned ? "owned" : "foreign",
|
|
launch: "package_runner",
|
|
entrypoint: undefined,
|
|
package: {
|
|
reference,
|
|
exactVersion: normalized === version ? version : undefined,
|
|
},
|
|
};
|
|
}
|
|
return inspectDirectRegistrationCommand(command, currentCommandPath, lookup);
|
|
};
|
|
|
|
/** Ownership-only consumers share the same parsed command facts. */
|
|
export const classifyClientRegistrationCommand = (
|
|
command: readonly string[],
|
|
currentCommandPath: string | undefined,
|
|
lookup: ClientRegistrationCommandLookup = {},
|
|
): ClientRegistrationCommandIdentity =>
|
|
inspectClientRegistrationCommand(command, currentCommandPath, lookup)
|
|
.identity;
|
|
|
|
/** A saved wrapper around an Aube shim, with its fallback runtime. */
|
|
const inspectManagedShimCommand = (
|
|
managed: NonNullable<ReturnType<typeof registeredAubeShim>>,
|
|
currentCommandPath: string | undefined,
|
|
): ClientRegistrationCommandFacts => {
|
|
const shim =
|
|
HOST_PLATFORM.platform === "win32"
|
|
? undefined
|
|
: inspectAubeShim(managed.shim, process.execPath, managed);
|
|
return {
|
|
launch: "managed_shim",
|
|
...(aubeShimOwnership(shim, currentCommandPath) ?? { identity: "unknown" }),
|
|
entrypoint: shim?.target,
|
|
independentFallback:
|
|
shim?.runtime === "current" &&
|
|
shim.durableWrapper &&
|
|
entrypointIdentity(managed.fallbackRuntime, process.execPath) ===
|
|
"owned" &&
|
|
!launcherPathWalksThrough(
|
|
managed.fallbackRuntime,
|
|
(hop) => hop === shim.siblingRuntime,
|
|
),
|
|
package: undefined,
|
|
};
|
|
};
|
|
|
|
const inspectDirectRegistrationCommand = (
|
|
command: readonly string[],
|
|
currentCommandPath: string | undefined,
|
|
lookup: ClientRegistrationCommandLookup,
|
|
): ClientRegistrationCommandFacts => {
|
|
const currentPathAvailable =
|
|
currentCommandPath !== undefined && currentCommandPath.length > 0;
|
|
const managed = registeredAubeShim(command);
|
|
if (managed !== undefined)
|
|
return inspectManagedShimCommand(managed, currentCommandPath);
|
|
if (command.length === 3 && command[2] === "mcp") {
|
|
const interpreter = command[0] ?? "";
|
|
const entrypoint = command[1] ?? "";
|
|
if (!isAbsolute(interpreter) || !isAbsolute(entrypoint))
|
|
return {
|
|
identity: "unknown",
|
|
launch: "runtime_script",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
// Setup wrote this launcher from npx, and npm has removed that cache entry.
|
|
// Its runtime may be gone too, so neither path can be compared.
|
|
if (removedNpxReaScript(entrypoint, HOST_PLATFORM.platform))
|
|
return {
|
|
identity: "owned",
|
|
installation: "other",
|
|
removedNpxCache: true,
|
|
launch: "runtime_script",
|
|
entrypoint,
|
|
package: undefined,
|
|
};
|
|
const interpreterIdentity = entrypointIdentity(
|
|
interpreter,
|
|
process.execPath,
|
|
);
|
|
if (interpreterIdentity !== "owned") {
|
|
if (!currentPathAvailable)
|
|
return {
|
|
identity: "unknown",
|
|
launch: "runtime_script",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
if (interpreterIdentity === "foreign")
|
|
return {
|
|
...otherRuntimeScriptOwnership(entrypoint, currentCommandPath),
|
|
launch: "runtime_script",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
// A vanished node/bun path still owns a verified installed rea-agents script.
|
|
const runtimeName = commandFileName(interpreter);
|
|
if (
|
|
(runtimeName === "node" ||
|
|
runtimeName === "node.exe" ||
|
|
runtimeName === "bun" ||
|
|
runtimeName === "bun.exe") &&
|
|
installedReaPackageEvidence(entrypoint) === "verified"
|
|
)
|
|
return {
|
|
identity: "owned",
|
|
installation: "other",
|
|
launch: "runtime_script",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
return {
|
|
identity: "unknown",
|
|
launch: "runtime_script",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
}
|
|
// The proven current runtime owns script selection: Node normalizes argv,
|
|
// while Bun follows native traversal through symlink/.. on POSIX.
|
|
const selectedEntrypoint = normalizeEntrypointPath(entrypoint);
|
|
return {
|
|
launch: "runtime_script",
|
|
...(selectedEntrypoint === undefined || !currentPathAvailable
|
|
? { identity: "unknown" }
|
|
: entrypointOwnership(
|
|
entrypointIdentity(selectedEntrypoint, currentCommandPath),
|
|
selectedEntrypoint,
|
|
)),
|
|
entrypoint: selectedEntrypoint,
|
|
package: undefined,
|
|
};
|
|
}
|
|
if (command.length === 2 && command[1] === "mcp") {
|
|
const executable = command[0] ?? "";
|
|
if (executable === PRODUCT_IDENTITY.cliBinary) {
|
|
if (lookup.unresolvedPath === true)
|
|
return {
|
|
identity: "unknown",
|
|
launch: "direct",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
const resolved = resolveBareCliOnPath(
|
|
executable,
|
|
lookup.environment ?? process.env,
|
|
);
|
|
if (resolved === undefined || resolved === "unknown")
|
|
return {
|
|
identity: "unknown",
|
|
launch: "direct",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
const target = bareCliLaunchTarget(resolved);
|
|
if (target === undefined)
|
|
return {
|
|
identity: "unknown",
|
|
launch: "direct",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
if (currentPathAvailable) {
|
|
const pathIdentity = directEntrypointIdentity(
|
|
target,
|
|
currentCommandPath,
|
|
);
|
|
if (pathIdentity === "owned" || launcherBelongsToProduct(target))
|
|
return {
|
|
launch: "direct",
|
|
identity: "owned",
|
|
entrypoint: target,
|
|
package: undefined,
|
|
};
|
|
return {
|
|
launch: "direct",
|
|
identity: pathIdentity,
|
|
entrypoint: target,
|
|
package: undefined,
|
|
};
|
|
}
|
|
return {
|
|
launch: "direct",
|
|
identity: launcherBelongsToProduct(target) ? "owned" : "unknown",
|
|
entrypoint: target,
|
|
package: undefined,
|
|
};
|
|
}
|
|
const shim =
|
|
HOST_PLATFORM.platform !== "win32" &&
|
|
javaScriptRuntime(process.versions).id === "node"
|
|
? inspectAubeShim(executable, process.execPath)
|
|
: undefined;
|
|
const ownership = aubeShimOwnership(shim, currentCommandPath);
|
|
if (shim?.runtime === "current" || ownership !== undefined)
|
|
return {
|
|
launch: "direct",
|
|
...(ownership ?? { identity: "unknown" }),
|
|
entrypoint: shim?.target,
|
|
package: undefined,
|
|
};
|
|
if (isAbsolute(executable)) {
|
|
if (commandFileName(executable) === `${PRODUCT_IDENTITY.cliBinary}.cmd`) {
|
|
const cmdScript = windowsReaCmdScript(executable);
|
|
if (cmdScript === undefined)
|
|
return {
|
|
identity: "unknown",
|
|
launch: "direct",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
return {
|
|
launch: "direct",
|
|
...(currentPathAvailable
|
|
? entrypointOwnership(
|
|
entrypointIdentity(cmdScript, currentCommandPath),
|
|
cmdScript,
|
|
)
|
|
: { identity: "unknown" }),
|
|
entrypoint: cmdScript,
|
|
package: undefined,
|
|
};
|
|
}
|
|
return {
|
|
launch: "direct",
|
|
...(currentPathAvailable
|
|
? entrypointOwnership(
|
|
directEntrypointIdentity(executable, currentCommandPath),
|
|
executable,
|
|
)
|
|
: { identity: "unknown" }),
|
|
entrypoint: executable,
|
|
package: undefined,
|
|
};
|
|
}
|
|
if (/[./\\]/u.test(executable))
|
|
return {
|
|
identity: "unknown",
|
|
launch: "direct",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
}
|
|
return {
|
|
identity: "foreign",
|
|
launch: "unknown",
|
|
entrypoint: undefined,
|
|
package: undefined,
|
|
};
|
|
};
|