feat: add cross-platform installation lifecycle
This commit is contained in:
+59
-24
@@ -8,15 +8,28 @@ import { promisify } from "node:util";
|
||||
|
||||
import { parseBinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { probeHomebrew } from "./homebrew.js";
|
||||
import {
|
||||
linuxHopperLauncherPath,
|
||||
linuxSharedLibrariesAvailable,
|
||||
readLinuxDistribution,
|
||||
type LinuxDistribution,
|
||||
} from "./LinuxHopper.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const DEFAULT_HOPPER =
|
||||
"/Applications/Hopper Disassembler.app/Contents/MacOS/hopper";
|
||||
const SYSTEM_LINUX_HOPPER = "/opt/hopper/bin/Hopper";
|
||||
|
||||
/** One actionable environment diagnostic. */
|
||||
export interface DoctorCheck {
|
||||
readonly name: string;
|
||||
readonly ok: boolean;
|
||||
readonly classification:
|
||||
| "healthy"
|
||||
| "missing_dependency"
|
||||
| "unsupported_host"
|
||||
| "missing_analysis_engine"
|
||||
| "config_drift";
|
||||
readonly detail?: string;
|
||||
readonly remediation?: string;
|
||||
}
|
||||
@@ -26,6 +39,7 @@ export interface DoctorHost {
|
||||
readonly nodeVersion: string;
|
||||
readonly configuredHopperPath?: string;
|
||||
macosVersion(): Promise<string | undefined>;
|
||||
linuxDistribution(): Promise<LinuxDistribution | undefined>;
|
||||
validTarget(path: string): Promise<boolean>;
|
||||
executable(path: string): Promise<boolean>;
|
||||
brewHopperPath(): Promise<string | undefined>;
|
||||
@@ -48,27 +62,39 @@ export const runDoctor = async (
|
||||
const checks: DoctorCheck[] = [];
|
||||
const nodeMajor = parseMajor(host.nodeVersion);
|
||||
checks.push(
|
||||
check(
|
||||
"node",
|
||||
nodeMajor >= 22,
|
||||
host.nodeVersion,
|
||||
"Install Node.js 22 or newer.",
|
||||
),
|
||||
check("node", nodeMajor >= 24, host.nodeVersion, {
|
||||
remediation: "Install Node.js 24.18 or newer.",
|
||||
classification: "missing_dependency",
|
||||
}),
|
||||
);
|
||||
const macosVersion =
|
||||
host.platform === "darwin" ? await host.macosVersion() : undefined;
|
||||
const macosMajor = macosVersion === undefined ? 0 : parseMajor(macosVersion);
|
||||
const linuxDistribution =
|
||||
host.platform === "linux" ? await host.linuxDistribution() : undefined;
|
||||
const supportedHost =
|
||||
(host.platform === "darwin" && macosMajor >= 12) ||
|
||||
(host.platform === "linux" && linuxDistribution?.supported === true);
|
||||
checks.push(
|
||||
check(
|
||||
"macos",
|
||||
host.platform === "darwin" && macosMajor >= 12,
|
||||
macosVersion ?? host.platform,
|
||||
"Hopper requires macOS 12 or newer.",
|
||||
"host",
|
||||
supportedHost,
|
||||
macosVersion ??
|
||||
(linuxDistribution === undefined
|
||||
? host.platform
|
||||
: `${linuxDistribution.id} ${linuxDistribution.versionId ?? "unknown"}`),
|
||||
{
|
||||
remediation:
|
||||
"REA supports macOS 12+, Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux.",
|
||||
classification: "unsupported_host",
|
||||
},
|
||||
),
|
||||
);
|
||||
const candidates = [
|
||||
host.configuredHopperPath,
|
||||
DEFAULT_HOPPER,
|
||||
SYSTEM_LINUX_HOPPER,
|
||||
linuxHopperLauncherPath(homedir()),
|
||||
...(await host.manualHopperPaths()),
|
||||
await host.brewHopperPath(),
|
||||
].filter((value): value is string => value !== undefined);
|
||||
@@ -79,21 +105,18 @@ export const runDoctor = async (
|
||||
break;
|
||||
}
|
||||
checks.push(
|
||||
check(
|
||||
"hopper",
|
||||
hopperPath !== undefined,
|
||||
hopperPath,
|
||||
"Install Hopper with: brew install --cask hopper-disassembler, or set HOPPER_LAUNCHER_PATH.",
|
||||
),
|
||||
check("hopper", hopperPath !== undefined, hopperPath, {
|
||||
remediation:
|
||||
"Run rea setup --yes to install Hopper, or set HOPPER_LAUNCHER_PATH.",
|
||||
classification: "missing_analysis_engine",
|
||||
}),
|
||||
);
|
||||
if (target !== undefined)
|
||||
checks.push(
|
||||
check(
|
||||
"target",
|
||||
await host.validTarget(target),
|
||||
target,
|
||||
"Supply a readable local app or program path.",
|
||||
),
|
||||
check("target", await host.validTarget(target), target, {
|
||||
remediation: "Supply a readable local app or program path.",
|
||||
classification: "config_drift",
|
||||
}),
|
||||
);
|
||||
return {
|
||||
healthy: checks.every(({ ok }) => ok),
|
||||
@@ -118,12 +141,20 @@ export const systemDoctorHost = (): DoctorHost => ({
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
linuxDistribution: readLinuxDistribution,
|
||||
async validTarget(path) {
|
||||
return (await parseBinaryTarget(path)).ok;
|
||||
},
|
||||
async executable(path) {
|
||||
try {
|
||||
await access(path, constants.X_OK);
|
||||
if (process.platform === "linux") {
|
||||
const linked = await execFileAsync("ldd", [path]);
|
||||
if (
|
||||
!linuxSharedLibrariesAvailable(`${linked.stdout}\n${linked.stderr}`)
|
||||
)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
@@ -168,10 +199,14 @@ const check = (
|
||||
name: string,
|
||||
ok: boolean,
|
||||
detail: string | undefined,
|
||||
remediation: string,
|
||||
failure: {
|
||||
readonly remediation: string;
|
||||
readonly classification: Exclude<DoctorCheck["classification"], "healthy">;
|
||||
},
|
||||
): DoctorCheck => ({
|
||||
name,
|
||||
ok,
|
||||
classification: ok ? "healthy" : failure.classification,
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
...(ok ? {} : { remediation }),
|
||||
...(ok ? {} : { remediation: failure.remediation }),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFile } from "node:child_process";
|
||||
import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const RELEASES_URL =
|
||||
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true";
|
||||
const DOWNLOAD_PREFIX = "https://www.hopperapp.com:443/downloader/public/";
|
||||
const MAX_PACKAGE_BYTES = 100_000_000;
|
||||
|
||||
export type LinuxPackageFamily = "deb" | "rpm" | "arch";
|
||||
|
||||
/** Parsed Linux distribution information used for support and package selection. */
|
||||
export interface LinuxDistribution {
|
||||
readonly id: string;
|
||||
readonly versionId?: string;
|
||||
readonly packageFamily: LinuxPackageFamily | undefined;
|
||||
readonly supported: boolean;
|
||||
}
|
||||
|
||||
/** Download response kept independent of Node's global fetch implementation. */
|
||||
export interface LinuxHopperDownload {
|
||||
readonly ok: boolean;
|
||||
readonly bytes: Uint8Array;
|
||||
}
|
||||
|
||||
/** External effects required to install the official Linux package. */
|
||||
export interface LinuxHopperInstallHost {
|
||||
distribution(): Promise<LinuxDistribution | undefined>;
|
||||
download(
|
||||
url: string,
|
||||
options: { readonly signal?: AbortSignal },
|
||||
): Promise<LinuxHopperDownload>;
|
||||
createTemporaryDirectory(): Promise<string>;
|
||||
writeArchive(path: string, bytes: Uint8Array): Promise<void>;
|
||||
installPackage(family: LinuxPackageFamily, archive: string): Promise<boolean>;
|
||||
launcherReady(path: string): Promise<boolean>;
|
||||
cleanup(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** Structured outcome for every expected Linux installation failure. */
|
||||
export type LinuxHopperInstallResult =
|
||||
| { readonly status: "installed"; readonly launcherPath: string }
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly reason:
|
||||
| "unsupported_host"
|
||||
| "release_metadata"
|
||||
| "download"
|
||||
| "integrity"
|
||||
| "authorization_or_package_manager"
|
||||
| "launcher_missing"
|
||||
| "cancelled";
|
||||
};
|
||||
|
||||
/** Parse an os-release document without executing its shell syntax. */
|
||||
export const parseLinuxDistribution = (text: string): LinuxDistribution => {
|
||||
const fields = new Map<string, string>();
|
||||
for (const line of text.split("\n")) {
|
||||
const match = /^([A-Z_]+)=(.*)$/u.exec(line.trim());
|
||||
if (match === null) continue;
|
||||
const key = match[1];
|
||||
const encoded = match[2];
|
||||
if (key === undefined || encoded === undefined) continue;
|
||||
const value =
|
||||
encoded.startsWith('"') && encoded.endsWith('"')
|
||||
? encoded.slice(1, -1).replaceAll('\\"', '"').replaceAll("\\\\", "\\")
|
||||
: encoded;
|
||||
fields.set(key, value);
|
||||
}
|
||||
const id = (fields.get("ID") ?? "unknown").toLowerCase();
|
||||
const versionId = fields.get("VERSION_ID");
|
||||
const packageFamily = packageFamilyFor(id, fields.get("ID_LIKE"));
|
||||
const supported =
|
||||
id === "arch" ||
|
||||
(id === "ubuntu" && versionAtLeast(versionId, 24)) ||
|
||||
(id === "fedora" && versionAtLeast(versionId, 41));
|
||||
return {
|
||||
id,
|
||||
...(versionId === undefined ? {} : { versionId }),
|
||||
packageFamily,
|
||||
supported,
|
||||
};
|
||||
};
|
||||
|
||||
/** Read and classify the current Linux distribution. */
|
||||
export const readLinuxDistribution = async (): Promise<
|
||||
LinuxDistribution | undefined
|
||||
> => {
|
||||
try {
|
||||
return parseLinuxDistribution(await readFile("/etc/os-release", "utf8"));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
/** Download, verify, install, and read back the official Hopper Linux package. */
|
||||
export const installLinuxHopper = async (
|
||||
host: LinuxHopperInstallHost = systemLinuxHopperInstallHost(),
|
||||
options: { readonly signal?: AbortSignal } = {},
|
||||
): Promise<LinuxHopperInstallResult> => {
|
||||
if (options.signal?.aborted === true)
|
||||
return { status: "failed", reason: "cancelled" };
|
||||
const distribution = await host.distribution();
|
||||
if (
|
||||
distribution?.supported !== true ||
|
||||
distribution.packageFamily === undefined
|
||||
)
|
||||
return { status: "failed", reason: "unsupported_host" };
|
||||
let temporary: string | undefined;
|
||||
try {
|
||||
const metadataDownload = await host.download(RELEASES_URL, options);
|
||||
if (!metadataDownload.ok)
|
||||
return { status: "failed", reason: "release_metadata" };
|
||||
const releases = parseReleases(metadataDownload.bytes);
|
||||
if (releases === undefined)
|
||||
return { status: "failed", reason: "release_metadata" };
|
||||
const release = releases[releaseKey(distribution.packageFamily)];
|
||||
if (!release.filename.startsWith(DOWNLOAD_PREFIX))
|
||||
return { status: "failed", reason: "release_metadata" };
|
||||
const archiveDownload = await host.download(release.filename, options);
|
||||
if (!archiveDownload.ok) return { status: "failed", reason: "download" };
|
||||
if (!packageIntegrityMatches(archiveDownload.bytes, release))
|
||||
return { status: "failed", reason: "integrity" };
|
||||
temporary = await host.createTemporaryDirectory();
|
||||
const archive = join(temporary, `hopper.${distribution.packageFamily}`);
|
||||
await host.writeArchive(archive, archiveDownload.bytes);
|
||||
if (!(await host.installPackage(distribution.packageFamily, archive)))
|
||||
return { status: "failed", reason: "authorization_or_package_manager" };
|
||||
const launcherPath = "/opt/hopper/bin/Hopper";
|
||||
if (!(await host.launcherReady(launcherPath)))
|
||||
return { status: "failed", reason: "launcher_missing" };
|
||||
return { status: "installed", launcherPath };
|
||||
} catch (cause: unknown) {
|
||||
if (isAbortCause(cause)) return { status: "failed", reason: "cancelled" };
|
||||
return { status: "failed", reason: "download" };
|
||||
} finally {
|
||||
if (temporary !== undefined) await host.cleanup(temporary);
|
||||
}
|
||||
};
|
||||
|
||||
/** Canonical launcher path for a legacy user-local Linux Hopper installation. */
|
||||
export const linuxHopperLauncherPath = (home: string): string =>
|
||||
join(home, ".local/share/rea/hopper/bin/Hopper");
|
||||
|
||||
const systemLinuxHopperInstallHost = (): LinuxHopperInstallHost => ({
|
||||
distribution: readLinuxDistribution,
|
||||
async download(url, options) {
|
||||
const response = await fetch(url, {
|
||||
headers: { accept: "application/json", "user-agent": "rea-installer" },
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
return {
|
||||
ok: response.ok,
|
||||
bytes: new Uint8Array(await response.arrayBuffer()),
|
||||
};
|
||||
},
|
||||
createTemporaryDirectory: () => mkdtemp(join(tmpdir(), "rea-hopper-")),
|
||||
writeArchive: (path, bytes) => writeFile(path, bytes, { mode: 0o600 }),
|
||||
installPackage: installSystemPackage,
|
||||
async launcherReady(path) {
|
||||
try {
|
||||
await access(path);
|
||||
const linked = await execFileAsync("ldd", [path]);
|
||||
return linuxSharedLibrariesAvailable(
|
||||
`${linked.stdout}\n${linked.stderr}`,
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
cleanup: (path) => rm(path, { recursive: true, force: true }),
|
||||
});
|
||||
|
||||
/** Interpret ldd output conservatively so a present but broken launcher is unhealthy. */
|
||||
export const linuxSharedLibrariesAvailable = (output: string): boolean =>
|
||||
!/(?:=>\s+not found|error while loading shared libraries)/iu.test(output);
|
||||
|
||||
const installSystemPackage = async (
|
||||
family: LinuxPackageFamily,
|
||||
archive: string,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const command = linuxPackageManagerCommand(
|
||||
family,
|
||||
archive,
|
||||
process.getuid?.() === 0,
|
||||
);
|
||||
await execFileAsync(command.executable, command.args);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** Select the native package manager and authorization boundary without shell evaluation. */
|
||||
export const linuxPackageManagerCommand = (
|
||||
family: LinuxPackageFamily,
|
||||
archive: string,
|
||||
isRoot: boolean,
|
||||
): { readonly executable: string; readonly args: readonly string[] } => {
|
||||
const command =
|
||||
family === "deb"
|
||||
? ["apt-get", "install", "-y", archive]
|
||||
: family === "rpm"
|
||||
? ["dnf", "install", "-y", archive]
|
||||
: ["pacman", "-U", "--noconfirm", archive];
|
||||
const executable = isRoot ? command[0] : "pkexec";
|
||||
if (executable === undefined) throw new Error("package command is empty");
|
||||
return { executable, args: isRoot ? command.slice(1) : command };
|
||||
};
|
||||
|
||||
const parseReleases = (
|
||||
bytes: Uint8Array,
|
||||
): z.infer<typeof releasesSchema> | undefined => {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));
|
||||
const result = releasesSchema.safeParse(parsed);
|
||||
return result.success ? result.data : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const packageIntegrityMatches = (
|
||||
bytes: Uint8Array,
|
||||
release: z.infer<typeof releaseSchema>,
|
||||
): boolean =>
|
||||
bytes.byteLength === Number(release.file_length) &&
|
||||
bytes.byteLength <= MAX_PACKAGE_BYTES &&
|
||||
createHash("sha1").update(bytes).digest("hex") === release.file_hash;
|
||||
|
||||
const packageFamilyFor = (
|
||||
id: string,
|
||||
idLike: string | undefined,
|
||||
): LinuxPackageFamily | undefined => {
|
||||
const identities = new Set([
|
||||
id,
|
||||
...(idLike?.toLowerCase().split(/\s+/u) ?? []),
|
||||
]);
|
||||
if (identities.has("ubuntu") || identities.has("debian")) return "deb";
|
||||
if (identities.has("fedora") || identities.has("rhel")) return "rpm";
|
||||
if (identities.has("arch")) return "arch";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const versionAtLeast = (
|
||||
version: string | undefined,
|
||||
minimum: number,
|
||||
): boolean =>
|
||||
version !== undefined &&
|
||||
Number.parseInt(version.split(".")[0] ?? "0", 10) >= minimum;
|
||||
const releaseKey = (
|
||||
family: LinuxPackageFamily,
|
||||
): "Ubuntu / Mint" | "Fedora" | "Arch" =>
|
||||
family === "deb" ? "Ubuntu / Mint" : family === "rpm" ? "Fedora" : "Arch";
|
||||
const isAbortCause = (cause: unknown): boolean =>
|
||||
cause instanceof Error && cause.name === "AbortError";
|
||||
const releaseSchema = z.object({
|
||||
filename: z.string().url(),
|
||||
file_length: z.string().regex(/^\d+$/u),
|
||||
file_hash: z.string().regex(/^[a-f0-9]{40}$/u),
|
||||
});
|
||||
const releasesSchema = z.object({
|
||||
"Ubuntu / Mint": releaseSchema,
|
||||
Fedora: releaseSchema,
|
||||
Arch: releaseSchema,
|
||||
});
|
||||
+192
-37
@@ -8,27 +8,40 @@ import {
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { z } from "zod";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { runDoctor, systemDoctorHost } from "./Doctor.js";
|
||||
import { probeHomebrew } from "./homebrew.js";
|
||||
import {
|
||||
installLinuxHopper,
|
||||
readLinuxDistribution,
|
||||
type LinuxDistribution,
|
||||
} from "./LinuxHopper.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const registrationCommand = (): readonly string[] =>
|
||||
process.env.npm_command === "exec"
|
||||
? ["npx", "-y", PRODUCT_IDENTITY.packageName, "mcp"]
|
||||
: [resolve(process.argv[1] ?? PRODUCT_IDENTITY.cliBinary), "mcp"];
|
||||
|
||||
/** A detected agent configuration owned by setup. */
|
||||
export interface SetupClient {
|
||||
readonly name: string;
|
||||
readonly configPath: string;
|
||||
readonly markerPath?: string;
|
||||
readonly format?: "json" | "toml" | "unsupported";
|
||||
}
|
||||
/** Result of one backup/write/readback transaction. */
|
||||
export type ClientConfigurationResult =
|
||||
| {
|
||||
readonly status: "unchanged" | "configured";
|
||||
readonly status: "unchanged" | "configured" | "skipped";
|
||||
readonly backupPath?: string;
|
||||
}
|
||||
| {
|
||||
@@ -44,6 +57,7 @@ export interface SetupHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly nodeVersion: string;
|
||||
macosVersion(): Promise<string | undefined>;
|
||||
linuxDistribution(): Promise<LinuxDistribution | undefined>;
|
||||
hasHomebrew(): Promise<boolean>;
|
||||
installHomebrew(): Promise<boolean>;
|
||||
hopperPath(): Promise<string | undefined>;
|
||||
@@ -52,6 +66,7 @@ export interface SetupHost {
|
||||
configureClient(
|
||||
client: SetupClient,
|
||||
hopperPath: string,
|
||||
command: readonly string[],
|
||||
): Promise<ClientConfigurationResult>;
|
||||
installSkill(): Promise<"installed" | "unchanged" | "failed">;
|
||||
doctor(): Promise<Awaited<ReturnType<typeof runDoctor>>>;
|
||||
@@ -87,13 +102,9 @@ export const runSetup = async (
|
||||
doctor: await host.doctor(),
|
||||
remediation,
|
||||
});
|
||||
if (host.platform !== "darwin")
|
||||
return fail("Hopper requires macOS 12 or newer.");
|
||||
const macosVersion = await host.macosVersion();
|
||||
if (macosVersion === undefined || major(macosVersion) < 12)
|
||||
return fail("Upgrade to macOS 12 or newer.");
|
||||
if (major(host.nodeVersion) < 22) return fail("Install Node.js 22 or newer.");
|
||||
if (!(await host.hasHomebrew())) {
|
||||
const unsupported = await hostRemediation(host);
|
||||
if (unsupported !== undefined) return fail(unsupported);
|
||||
if (host.platform === "darwin" && !(await host.hasHomebrew())) {
|
||||
if (!yes) return fail("Re-run with --yes to install Homebrew.");
|
||||
if (!(await host.installHomebrew()))
|
||||
return fail(
|
||||
@@ -116,7 +127,11 @@ export const runSetup = async (
|
||||
);
|
||||
}
|
||||
for (const client of await host.detectedClients()) {
|
||||
const result = await host.configureClient(client, hopperPath);
|
||||
const result = await host.configureClient(
|
||||
client,
|
||||
hopperPath,
|
||||
registrationCommand(),
|
||||
);
|
||||
clients[client.name] = result;
|
||||
if (result.status === "failed")
|
||||
return fail(
|
||||
@@ -130,19 +145,40 @@ export const runSetup = async (
|
||||
return fail("Agent skill installation or readback failed.");
|
||||
if (skill === "installed") actions.push("installed_skill");
|
||||
const doctor = await host.doctor();
|
||||
const activationRequired = actions.includes("installed_hopper");
|
||||
const ready = doctor.healthy && !activationRequired;
|
||||
return {
|
||||
status: doctor.healthy ? "ready" : "needs_human",
|
||||
status: ready ? "ready" : "needs_human",
|
||||
actions,
|
||||
clients,
|
||||
doctor,
|
||||
...(doctor.healthy
|
||||
...(ready
|
||||
? {}
|
||||
: {
|
||||
remediation: "Run rea doctor and apply each reported remediation.",
|
||||
remediation: activationRequired
|
||||
? "Open Hopper, complete its one-time activation, then rerun rea doctor --json."
|
||||
: "Run rea doctor and apply each reported remediation.",
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const hostRemediation = async (
|
||||
host: SetupHost,
|
||||
): Promise<string | undefined> => {
|
||||
if (host.platform !== "darwin" && host.platform !== "linux")
|
||||
return "REA supports Hopper on macOS and selected 64-bit Linux distributions.";
|
||||
if (major(host.nodeVersion) < 24) return "Install Node.js 24.18 or newer.";
|
||||
if (host.platform === "darwin") {
|
||||
const version = await host.macosVersion();
|
||||
return version === undefined || major(version) < 12
|
||||
? "Upgrade to macOS 12 or newer."
|
||||
: undefined;
|
||||
}
|
||||
return (await host.linuxDistribution())?.supported === true
|
||||
? undefined
|
||||
: "REA supports Hopper on Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux.";
|
||||
};
|
||||
|
||||
/** Production setup effects for macOS, Homebrew, JSON MCP clients, and the canonical skill directory. */
|
||||
const systemSetupHost = (): SetupHost => {
|
||||
const doctorHost = systemDoctorHost();
|
||||
@@ -150,6 +186,7 @@ const systemSetupHost = (): SetupHost => {
|
||||
platform: process.platform,
|
||||
nodeVersion: process.versions.node,
|
||||
macosVersion: () => doctorHost.macosVersion(),
|
||||
linuxDistribution: readLinuxDistribution,
|
||||
hasHomebrew: () => brewSucceeds(["--version"]),
|
||||
installHomebrew: () =>
|
||||
commandSucceeds(
|
||||
@@ -162,43 +199,86 @@ const systemSetupHost = (): SetupHost => {
|
||||
),
|
||||
hopperPath: async () => (await runDoctor(undefined, doctorHost)).hopperPath,
|
||||
installHopper: () =>
|
||||
brewSucceeds(["install", "--cask", "hopper-disassembler"]),
|
||||
detectedClients: () => detectJsonClients(homedir()),
|
||||
configureClient: configureJsonClient,
|
||||
process.platform === "linux"
|
||||
? installLinuxHopper().then(({ status }) => status === "installed")
|
||||
: brewSucceeds(["install", "--cask", "hopper-disassembler"]),
|
||||
detectedClients: () => detectClients(homedir()),
|
||||
configureClient: (client, hopperPath, command) =>
|
||||
client.format === "unsupported"
|
||||
? Promise.resolve({ status: "skipped" })
|
||||
: client.format === "toml"
|
||||
? configureTomlClient(client, hopperPath, command)
|
||||
: configureJsonClient(client, hopperPath, command),
|
||||
installSkill: () => installCanonicalSkill(homedir()),
|
||||
doctor: () => runDoctor(undefined, doctorHost),
|
||||
};
|
||||
};
|
||||
|
||||
const detectJsonClients = async (
|
||||
/** Detect supported coding agents from stable per-user installation markers. */
|
||||
export const detectClients = async (
|
||||
home: string,
|
||||
): Promise<readonly SetupClient[]> => {
|
||||
const candidates = [
|
||||
{
|
||||
name: "claude_desktop",
|
||||
configPath: join(
|
||||
home,
|
||||
"Library/Application Support/Claude/claude_desktop_config.json",
|
||||
),
|
||||
marker: join(home, "Library/Application Support/Claude"),
|
||||
},
|
||||
{
|
||||
name: "cursor",
|
||||
configPath: join(home, ".cursor/mcp.json"),
|
||||
marker: join(home, ".cursor"),
|
||||
},
|
||||
];
|
||||
const detected: SetupClient[] = [];
|
||||
for (const candidate of candidates)
|
||||
if (await exists(candidate.marker))
|
||||
detected.push({ name: candidate.name, configPath: candidate.configPath });
|
||||
for (const candidate of supportedClients(home))
|
||||
if (await exists(candidate.markerPath ?? candidate.configPath))
|
||||
detected.push(candidate);
|
||||
return detected;
|
||||
};
|
||||
|
||||
/** Describe every client location that setup or uninstall may own. */
|
||||
export const supportedClients = (home: string): readonly SetupClient[] => [
|
||||
{
|
||||
name: "claude_code",
|
||||
configPath: join(home, ".claude.json"),
|
||||
markerPath: join(home, ".claude"),
|
||||
},
|
||||
{
|
||||
name: "claude_desktop",
|
||||
configPath: join(
|
||||
home,
|
||||
"Library/Application Support/Claude/claude_desktop_config.json",
|
||||
),
|
||||
markerPath: join(home, "Library/Application Support/Claude"),
|
||||
},
|
||||
{
|
||||
name: "codex",
|
||||
configPath: join(home, ".codex/config.toml"),
|
||||
markerPath: join(home, ".codex"),
|
||||
format: "toml" as const,
|
||||
},
|
||||
{
|
||||
name: "cursor",
|
||||
configPath: join(home, ".cursor/mcp.json"),
|
||||
markerPath: join(home, ".cursor"),
|
||||
},
|
||||
{
|
||||
name: "gemini_cli",
|
||||
configPath: join(home, ".gemini/settings.json"),
|
||||
markerPath: join(home, ".gemini"),
|
||||
},
|
||||
{
|
||||
name: "windsurf",
|
||||
configPath: join(home, ".codeium/windsurf/mcp_config.json"),
|
||||
markerPath: join(home, ".codeium/windsurf"),
|
||||
},
|
||||
{
|
||||
name: "devin",
|
||||
configPath: join(home, ".devin"),
|
||||
markerPath: join(home, ".devin"),
|
||||
format: "unsupported" as const,
|
||||
},
|
||||
];
|
||||
|
||||
/** Back up, atomically update, and semantically read back one JSON MCP configuration. */
|
||||
export const configureJsonClient = async (
|
||||
client: SetupClient,
|
||||
hopperPath?: string,
|
||||
command: readonly string[] = [
|
||||
"npx",
|
||||
"-y",
|
||||
PRODUCT_IDENTITY.packageName,
|
||||
"mcp",
|
||||
],
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
let document: Record<string, unknown> = {};
|
||||
let original: string | undefined;
|
||||
@@ -215,8 +295,8 @@ export const configureJsonClient = async (
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
const desired = {
|
||||
command: "npx",
|
||||
args: ["-y", PRODUCT_IDENTITY.packageName, "mcp"],
|
||||
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
|
||||
args: command.slice(1),
|
||||
...(hopperPath === undefined
|
||||
? {}
|
||||
: { env: { HOPPER_LAUNCHER_PATH: hopperPath } }),
|
||||
@@ -268,6 +348,81 @@ export const configureJsonClient = async (
|
||||
};
|
||||
};
|
||||
|
||||
/** Back up, atomically update, and semantically read back Codex TOML configuration. */
|
||||
export const configureTomlClient = async (
|
||||
client: SetupClient,
|
||||
hopperPath?: string,
|
||||
command: readonly string[] = [
|
||||
"npx",
|
||||
"-y",
|
||||
PRODUCT_IDENTITY.packageName,
|
||||
"mcp",
|
||||
],
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
let document: Record<string, unknown> = {};
|
||||
let original: string | undefined;
|
||||
try {
|
||||
original = await readFile(client.configPath, "utf8");
|
||||
document = objectSchema.parse(parseToml(original));
|
||||
} catch (cause: unknown) {
|
||||
if (!isMissing(cause)) return { status: "failed", reason: "readback" };
|
||||
}
|
||||
let servers: Record<string, unknown>;
|
||||
try {
|
||||
servers = parseOptionalObject(document.mcp_servers);
|
||||
} catch {
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
const desired = {
|
||||
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
|
||||
args: command.slice(1),
|
||||
...(hopperPath === undefined
|
||||
? {}
|
||||
: { env: { HOPPER_LAUNCHER_PATH: hopperPath } }),
|
||||
};
|
||||
if (
|
||||
JSON.stringify(servers[PRODUCT_IDENTITY.mcpServerKey]) ===
|
||||
JSON.stringify(desired)
|
||||
)
|
||||
return { status: "unchanged" };
|
||||
const backupPath =
|
||||
original === undefined ? undefined : `${client.configPath}.rea.backup`;
|
||||
try {
|
||||
if (backupPath !== undefined) await copyFile(client.configPath, backupPath);
|
||||
} catch {
|
||||
return { status: "failed", reason: "backup" };
|
||||
}
|
||||
document.mcp_servers = {
|
||||
...servers,
|
||||
[PRODUCT_IDENTITY.mcpServerKey]: desired,
|
||||
};
|
||||
try {
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
await writeFileAtomic(client.configPath, stringifyToml(document), {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
});
|
||||
const readback = objectSchema.parse(
|
||||
parseToml(await readFile(client.configPath, "utf8")),
|
||||
);
|
||||
if (
|
||||
JSON.stringify(
|
||||
parseOptionalObject(readback.mcp_servers)[
|
||||
PRODUCT_IDENTITY.mcpServerKey
|
||||
],
|
||||
) !== JSON.stringify(desired)
|
||||
)
|
||||
throw new Error("TOML readback mismatch");
|
||||
} catch {
|
||||
await restoreConfig(client.configPath, original);
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
return {
|
||||
status: "configured",
|
||||
...(backupPath === undefined ? {} : { backupPath }),
|
||||
};
|
||||
};
|
||||
|
||||
/** Transactionally install or upgrade the versioned canonical REA skill. */
|
||||
export const installCanonicalSkill = async (
|
||||
home: string,
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { copyFile, lstat, readFile, rm } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, isAbsolute, join } from "node:path";
|
||||
|
||||
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { supportedClients, type SetupClient } from "./Setup.js";
|
||||
|
||||
/** One explicitly classified uninstall action. */
|
||||
export interface UninstallItem {
|
||||
readonly name: string;
|
||||
readonly status: "removed" | "retained" | "skipped" | "failed";
|
||||
readonly detail: string;
|
||||
}
|
||||
|
||||
/** Structured, idempotent result of removing REA-owned state. */
|
||||
export interface UninstallResult {
|
||||
readonly status: "complete" | "failed";
|
||||
readonly items: readonly UninstallItem[];
|
||||
}
|
||||
|
||||
/** Filesystem boundary used by the contained uninstall workflow. */
|
||||
export interface UninstallHost {
|
||||
clients(): Promise<readonly SetupClient[]>;
|
||||
removeClient(client: SetupClient): Promise<UninstallItem>;
|
||||
removeSkill(): Promise<UninstallItem>;
|
||||
purgeData(): Promise<readonly UninstallItem[]>;
|
||||
}
|
||||
|
||||
/** Remove only REA-owned registrations and managed files, optionally including local state. */
|
||||
export const runUninstall = async (
|
||||
purgeData: boolean,
|
||||
host: UninstallHost = systemUninstallHost(),
|
||||
): Promise<UninstallResult> => {
|
||||
const items: UninstallItem[] = [];
|
||||
for (const client of await host.clients())
|
||||
items.push(await host.removeClient(client));
|
||||
items.push(await host.removeSkill());
|
||||
if (purgeData) items.push(...(await host.purgeData()));
|
||||
items.push({
|
||||
name: "analysis_engine",
|
||||
status: "retained",
|
||||
detail: "Hopper is not owned by REA uninstall.",
|
||||
});
|
||||
return {
|
||||
status: items.some(({ status }) => status === "failed")
|
||||
? "failed"
|
||||
: "complete",
|
||||
items,
|
||||
};
|
||||
};
|
||||
|
||||
/** Create uninstall effects contained to detected client configs and REA-owned paths. */
|
||||
export const systemUninstallHost = (home = homedir()): UninstallHost => ({
|
||||
clients: () => Promise.resolve(supportedClients(home)),
|
||||
removeClient,
|
||||
removeSkill: () =>
|
||||
removeManagedPath(
|
||||
join(home, ".agents/skills", PRODUCT_IDENTITY.skillName),
|
||||
"skill",
|
||||
),
|
||||
purgeData: async () => [
|
||||
await removeManagedPath(join(home, ".rea/cache"), "cache"),
|
||||
await removeManagedPath(join(home, ".rea/state"), "state"),
|
||||
],
|
||||
});
|
||||
|
||||
const removeClient = async (client: SetupClient): Promise<UninstallItem> => {
|
||||
if (client.format === "unsupported")
|
||||
return item(
|
||||
client.name,
|
||||
"skipped",
|
||||
"This client has no documented local MCP configuration boundary.",
|
||||
);
|
||||
let original: string;
|
||||
try {
|
||||
original = await readFile(client.configPath, "utf8");
|
||||
} catch (cause: unknown) {
|
||||
return isMissing(cause)
|
||||
? item(client.name, "skipped", "Configuration does not exist.")
|
||||
: item(client.name, "failed", "Configuration could not be read.");
|
||||
}
|
||||
let document: Record<string, unknown>;
|
||||
let key: "mcp_servers" | "mcpServers";
|
||||
let servers: Record<string, unknown>;
|
||||
try {
|
||||
document = objectSchema.parse(
|
||||
client.format === "toml" ? parseToml(original) : JSON.parse(original),
|
||||
);
|
||||
key = client.format === "toml" ? "mcp_servers" : "mcpServers";
|
||||
servers = optionalObject(document[key]);
|
||||
} catch {
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Malformed configuration was preserved without mutation.",
|
||||
);
|
||||
}
|
||||
const registration = servers[PRODUCT_IDENTITY.mcpServerKey];
|
||||
if (registration === undefined)
|
||||
return item(client.name, "skipped", "REA registration is absent.");
|
||||
if (!isOwnedRegistration(registration))
|
||||
return item(
|
||||
client.name,
|
||||
"retained",
|
||||
"The rea-named registration is not REA-owned.",
|
||||
);
|
||||
const remaining = { ...servers };
|
||||
delete remaining[PRODUCT_IDENTITY.mcpServerKey];
|
||||
document[key] = remaining;
|
||||
const backupPath = `${client.configPath}.rea.backup`;
|
||||
try {
|
||||
await copyFile(client.configPath, backupPath);
|
||||
} catch {
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
"Configuration backup failed; no mutation was attempted.",
|
||||
);
|
||||
}
|
||||
try {
|
||||
const encoded =
|
||||
client.format === "toml"
|
||||
? stringifyToml(document)
|
||||
: `${JSON.stringify(document, null, 2)}\n`;
|
||||
await writeFileAtomic(client.configPath, encoded, { encoding: "utf8" });
|
||||
const readback = objectSchema.parse(
|
||||
client.format === "toml"
|
||||
? parseToml(await readFile(client.configPath, "utf8"))
|
||||
: JSON.parse(await readFile(client.configPath, "utf8")),
|
||||
);
|
||||
if (PRODUCT_IDENTITY.mcpServerKey in optionalObject(readback[key]))
|
||||
throw new Error("registration readback mismatch");
|
||||
return item(
|
||||
client.name,
|
||||
"removed",
|
||||
`Removed registration from ${client.configPath}.`,
|
||||
);
|
||||
} catch {
|
||||
await writeFileAtomic(client.configPath, original, {
|
||||
encoding: "utf8",
|
||||
}).catch(() => undefined);
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
`Configuration update failed; the original was restored and ${backupPath} was retained.`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Ownership rule for persistent MCP registrations created by REA setup. */
|
||||
const isOwnedRegistration = (value: unknown): boolean => {
|
||||
const parsed = registrationSchema.safeParse(value);
|
||||
if (!parsed.success) return false;
|
||||
const { command, args } = parsed.data;
|
||||
return (
|
||||
((command === "rea" ||
|
||||
(isAbsolute(command) && basename(command) === "rea")) &&
|
||||
args.length === 1 &&
|
||||
args[0] === "mcp") ||
|
||||
(command === "npx" &&
|
||||
JSON.stringify(args) ===
|
||||
JSON.stringify(["-y", PRODUCT_IDENTITY.packageName, "mcp"]))
|
||||
);
|
||||
};
|
||||
|
||||
const removeManagedPath = async (
|
||||
path: string,
|
||||
name: string,
|
||||
): Promise<UninstallItem> => {
|
||||
try {
|
||||
const stats = await lstat(path);
|
||||
if (stats.isSymbolicLink())
|
||||
return item(name, "retained", `Refused to follow symlink ${path}.`);
|
||||
await rm(path, { recursive: true });
|
||||
return item(name, "removed", `Removed ${path}.`);
|
||||
} catch (cause: unknown) {
|
||||
return isMissing(cause)
|
||||
? item(name, "skipped", `${path} does not exist.`)
|
||||
: item(name, "failed", `${path} could not be removed.`);
|
||||
}
|
||||
};
|
||||
|
||||
const item = (
|
||||
name: string,
|
||||
status: UninstallItem["status"],
|
||||
detail: string,
|
||||
): UninstallItem => ({ name, status, detail });
|
||||
const objectSchema = z.record(z.string(), z.unknown());
|
||||
const optionalObject = (value: unknown): Record<string, unknown> =>
|
||||
value === undefined ? {} : objectSchema.parse(value);
|
||||
const registrationSchema = z
|
||||
.object({ command: z.string(), args: z.array(z.string()) })
|
||||
.passthrough();
|
||||
const isMissing = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
||||
+14
-1
@@ -7,6 +7,7 @@ import {
|
||||
runProviderAnalysis,
|
||||
} from "./application/DirectAnalysis.js";
|
||||
import { runSetup } from "./application/Setup.js";
|
||||
import { runUninstall } from "./application/Uninstall.js";
|
||||
import { PRODUCT_IDENTITY } from "./identity.js";
|
||||
import { createLogger, parseLogLevel, type Logger } from "./logger.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
@@ -29,7 +30,7 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
: parseLogLevel(process.env.REA_LOG_LEVEL),
|
||||
);
|
||||
const cli = Cli.create(PRODUCT_IDENTITY.cliBinary, {
|
||||
version: "0.1.0",
|
||||
version: process.env.REA_PACKAGE_VERSION ?? "0.0.0-development",
|
||||
description:
|
||||
"Reverse engineer anything from your terminal or coding agent.",
|
||||
mcp: {
|
||||
@@ -68,6 +69,18 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
|
||||
run: ({ options }) =>
|
||||
logCliCommand(logger, "doctor", () => runDoctor(options.target)),
|
||||
});
|
||||
cli.command("uninstall", {
|
||||
description: "Remove REA-owned agent configuration and skill files",
|
||||
options: z.object({
|
||||
purgeData: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Also remove REA caches and state"),
|
||||
}),
|
||||
alias: { purgeData: "purge-data" },
|
||||
run: ({ options }) =>
|
||||
logCliCommand(logger, "uninstall", () => runUninstall(options.purgeData)),
|
||||
});
|
||||
cli.command("analyze", {
|
||||
description: "Get an overview of an app",
|
||||
args: z.object({
|
||||
|
||||
+5
-1
@@ -9,6 +9,10 @@ import type { ReferenceSourcePolicy } from "./domain/referenceSourcePolicy.js";
|
||||
|
||||
const DEFAULT_HOPPER_LAUNCHER_PATH =
|
||||
"/Applications/Hopper Disassembler.app/Contents/MacOS/hopper";
|
||||
const defaultHopperLauncherPath = (): string =>
|
||||
process.platform === "linux"
|
||||
? "/opt/hopper/bin/Hopper"
|
||||
: DEFAULT_HOPPER_LAUNCHER_PATH;
|
||||
|
||||
export interface AppConfig {
|
||||
readonly hopperLauncherPath: string;
|
||||
@@ -134,7 +138,7 @@ export const parseConfig = (
|
||||
return ok({
|
||||
hopperLauncherPath:
|
||||
parsedEnvironment.data.HOPPER_LAUNCHER_PATH ??
|
||||
DEFAULT_HOPPER_LAUNCHER_PATH,
|
||||
defaultHopperLauncherPath(),
|
||||
hopperTargetPath: parsedEnvironment.data.HOPPER_TARGET_PATH,
|
||||
hopperTargetKind: parsedEnvironment.data.HOPPER_TARGET_KIND,
|
||||
hopperLoaderArgs: parsedArgs.data,
|
||||
|
||||
Reference in New Issue
Block a user