feat(setup)!: expand agent integrations and verify updates (#577)
* feat(setup)!: expand agent integrations and simplify onboarding Add native configuration formats for OpenCode, Antigravity, GitHub Copilot CLI, VS Code, and Devin. Preserve JSONC comments and unrelated settings while making setup and uninstall ownership-aware and idempotent. Select agent targets before planning, separate discovery from intent, and keep agent-only setup independent of optional provider prerequisites. Cover configuration boundaries and interactive behavior in packaged checks. BREAKING CHANGE: unscoped setup refreshes only existing REA-owned registrations. Use --all-detected to configure every detected client. Setup JSON contains a compact doctor summary; use rea doctor for full diagnostics. Cancellation and successful dry runs now exit successfully. * feat(cli)!: replace upgrade with verified updates Resolve an exact release through npm's configured registry, update only the identified installation, and verify its new executable before reporting success. Return a read-only maintenance plan for existing enabled REA integrations. BREAKING CHANGE: replace rea upgrade with rea update; no alias is retained. Successful update JSON uses status "updated", reports the verified installed version, and returns an unapplied maintenance plan instead of opening setup.
This commit is contained in:
@@ -1,14 +1,24 @@
|
||||
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import {
|
||||
applyEdits,
|
||||
modify,
|
||||
parse as parseJsonc,
|
||||
printParseErrorCode,
|
||||
type ParseError,
|
||||
} from "jsonc-parser";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
export type ClientConfigurationFormat = NonNullable<SetupClient["format"]>;
|
||||
export type ClientServersKey = "mcp_servers" | "mcpServers" | "mcp" | "servers";
|
||||
|
||||
/** Validated client document and its server table, preserving unrelated settings. */
|
||||
export interface ClientConfigurationDocument {
|
||||
readonly document: Record<string, unknown>;
|
||||
readonly servers: Record<string, unknown>;
|
||||
readonly serversKey: "mcp_servers" | "mcpServers";
|
||||
readonly serversKey: ClientServersKey;
|
||||
}
|
||||
|
||||
const objectSchema = z.record(z.string(), z.unknown());
|
||||
@@ -34,25 +44,117 @@ const normalizeConfigurationValue = (value: unknown): unknown => {
|
||||
);
|
||||
};
|
||||
|
||||
/** Parse the client format and reject malformed root or server-table values. */
|
||||
/** Return the top-level object used for MCP server registrations by a client. */
|
||||
export const clientConfigurationServersKey = (
|
||||
format: ClientConfigurationFormat,
|
||||
): ClientServersKey => {
|
||||
switch (format) {
|
||||
case "toml":
|
||||
return "mcp_servers";
|
||||
case "opencode":
|
||||
return "mcp";
|
||||
case "vscode":
|
||||
return "servers";
|
||||
default:
|
||||
return "mcpServers";
|
||||
}
|
||||
};
|
||||
|
||||
const parseDocument = (
|
||||
text: string,
|
||||
format: ClientConfigurationFormat,
|
||||
): Record<string, unknown> => {
|
||||
if (format === "toml") return objectSchema.parse(parseToml(text));
|
||||
const errors: ParseError[] = [];
|
||||
const document = parseJsonc(text, errors, { allowTrailingComma: true });
|
||||
const firstError = errors[0];
|
||||
if (firstError !== undefined)
|
||||
throw new SyntaxError(
|
||||
`Invalid JSON/JSONC at offset ${firstError.offset}: ${printParseErrorCode(firstError.error)}`,
|
||||
);
|
||||
return objectSchema.parse(document);
|
||||
};
|
||||
|
||||
/** Parse a client document and reject malformed roots or MCP server tables. */
|
||||
export const parseClientConfiguration = (
|
||||
text: string,
|
||||
format: SetupClient["format"],
|
||||
format: ClientConfigurationFormat | undefined,
|
||||
): ClientConfigurationDocument => {
|
||||
const document = objectSchema.parse(
|
||||
format === "toml" ? parseToml(text) : JSON.parse(text),
|
||||
);
|
||||
const serversKey = format === "toml" ? "mcp_servers" : "mcpServers";
|
||||
if (format === undefined || format === "unsupported")
|
||||
throw new TypeError("client does not have a supported MCP config format");
|
||||
const document = parseDocument(text, format);
|
||||
const serversKey = clientConfigurationServersKey(format);
|
||||
const value = document[serversKey];
|
||||
const servers = value === undefined ? {} : objectSchema.parse(value);
|
||||
return { document, servers, serversKey };
|
||||
};
|
||||
|
||||
/** Serialize a validated client document using the selected format. */
|
||||
/** Serialize a validated client document, retaining JSONC comments. */
|
||||
export const serializeClientConfiguration = (
|
||||
document: Record<string, unknown>,
|
||||
format: SetupClient["format"],
|
||||
): string =>
|
||||
format === "toml"
|
||||
? stringifyToml(document)
|
||||
: `${JSON.stringify(document, null, 2)}\n`;
|
||||
format: ClientConfigurationFormat | undefined,
|
||||
originalText?: string,
|
||||
editedServerName?: string,
|
||||
): string => {
|
||||
if (format === undefined || format === "unsupported")
|
||||
throw new TypeError("client does not have a supported MCP config format");
|
||||
if (format === "toml") return stringifyToml(document);
|
||||
if (originalText !== undefined && editedServerName !== undefined) {
|
||||
const serversKey = clientConfigurationServersKey(format);
|
||||
const servers = objectSchema.parse(document[serversKey] ?? {});
|
||||
const editedValue = Object.hasOwn(servers, editedServerName)
|
||||
? servers[editedServerName]
|
||||
: undefined;
|
||||
const edits = modify(
|
||||
originalText,
|
||||
[serversKey, editedServerName],
|
||||
editedValue,
|
||||
{
|
||||
formattingOptions: { insertSpaces: true, tabSize: 2, eol: "\n" },
|
||||
},
|
||||
);
|
||||
return applyEdits(originalText, edits);
|
||||
}
|
||||
return `${JSON.stringify(document, null, 2)}\n`;
|
||||
};
|
||||
|
||||
/** Build the stdio entry shape expected by one client's configuration dialect. */
|
||||
export const clientRegistrationEntry = (
|
||||
format: ClientConfigurationFormat,
|
||||
command: readonly string[],
|
||||
environment: Readonly<Record<string, string>>,
|
||||
): Record<string, unknown> => {
|
||||
const [executable = "rea", ...args] = command;
|
||||
switch (format) {
|
||||
case "opencode":
|
||||
return {
|
||||
type: "local",
|
||||
command: [...command],
|
||||
enabled: true,
|
||||
...(Object.keys(environment).length === 0
|
||||
? {}
|
||||
: { environment: { ...environment } }),
|
||||
};
|
||||
case "vscode":
|
||||
return {
|
||||
type: "stdio",
|
||||
command: executable,
|
||||
args,
|
||||
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
|
||||
};
|
||||
case "copilot_cli":
|
||||
return {
|
||||
type: "stdio",
|
||||
command: executable,
|
||||
args,
|
||||
tools: ["*"],
|
||||
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
|
||||
};
|
||||
default:
|
||||
return {
|
||||
command: executable,
|
||||
args,
|
||||
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { basename, isAbsolute, resolve } from "node:path";
|
||||
import { valid } from "semver";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
|
||||
/** Check that one parsed command points to REA's MCP entry point. */
|
||||
export const isOwnedClientRegistrationCommand = (
|
||||
command: readonly string[],
|
||||
currentCommandPath: string = resolve(process.argv[1] ?? "unknown"),
|
||||
): boolean => {
|
||||
if (
|
||||
command.length === 3 &&
|
||||
command[2] === "mcp" &&
|
||||
resolve(command[0] ?? "") === resolve(process.execPath) &&
|
||||
resolve(command[1] ?? "") === currentCommandPath
|
||||
)
|
||||
return true;
|
||||
|
||||
if (command.length === 2 && command[1] === "mcp") {
|
||||
const executable = command[0] ?? "";
|
||||
if (
|
||||
executable === PRODUCT_IDENTITY.cliBinary ||
|
||||
(isAbsolute(executable) &&
|
||||
basename(executable) === PRODUCT_IDENTITY.cliBinary) ||
|
||||
resolve(executable) === currentCommandPath
|
||||
)
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
command.length !== 4 ||
|
||||
command[0] !== "npx" ||
|
||||
command[1] !== "-y" ||
|
||||
command[3] !== "mcp"
|
||||
)
|
||||
return false;
|
||||
|
||||
const packageReference = command[2] ?? "";
|
||||
if (
|
||||
packageReference === PRODUCT_IDENTITY.packageName ||
|
||||
packageReference === PRODUCT_IDENTITY.packageSpecifier ||
|
||||
packageReference === PRODUCT_IDENTITY.registrationPackageSpecifier
|
||||
)
|
||||
return true;
|
||||
const versionPrefix = `${PRODUCT_IDENTITY.packageName}@`;
|
||||
return (
|
||||
packageReference.startsWith(versionPrefix) &&
|
||||
valid(packageReference.slice(versionPrefix.length)) !== null
|
||||
);
|
||||
};
|
||||
@@ -6,7 +6,9 @@ import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { supportedClients } from "./SupportedClients.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
interface ClientRegistrationStatusBase {
|
||||
readonly client: string;
|
||||
@@ -44,6 +46,10 @@ const registrationSchema = z
|
||||
command: z.string().min(1),
|
||||
args: z.array(z.string()).default([]),
|
||||
startup_timeout_sec: z.number().positive().optional(),
|
||||
type: z.string().optional(),
|
||||
tools: z.array(z.string()).optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
@@ -54,7 +60,10 @@ export const readClientRegistrationStatuses = async (
|
||||
): Promise<readonly ClientRegistrationStatus[]> => {
|
||||
const statuses: ClientRegistrationStatus[] = [];
|
||||
for (const client of supportedClients(home)) {
|
||||
if (client.format === "unsupported" || !(await exists(client.markerPath)))
|
||||
if (
|
||||
client.format === "unsupported" ||
|
||||
(!(await exists(client.markerPath)) && !(await exists(client.configPath)))
|
||||
)
|
||||
continue;
|
||||
try {
|
||||
const content = await readFile(client.configPath, "utf8");
|
||||
@@ -66,7 +75,7 @@ export const readClientRegistrationStatuses = async (
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const registration = registrationSchema.parse(raw);
|
||||
const registration = parseRegistration(raw, client);
|
||||
const command: RegistrationCommand = [
|
||||
registration.command,
|
||||
...registration.args,
|
||||
@@ -76,7 +85,7 @@ export const readClientRegistrationStatuses = async (
|
||||
client.name,
|
||||
client.configPath,
|
||||
command,
|
||||
registrationAligned(registration, client.name, currentCommandPath)
|
||||
registrationAligned(registration, client, currentCommandPath)
|
||||
? "aligned"
|
||||
: "stale",
|
||||
),
|
||||
@@ -98,16 +107,34 @@ export const readClientRegistrationStatuses = async (
|
||||
|
||||
const registrationAligned = (
|
||||
registration: z.output<typeof registrationSchema>,
|
||||
client: string,
|
||||
client: SetupClient,
|
||||
currentCommandPath: string,
|
||||
): boolean => {
|
||||
const command = [registration.command, ...registration.args];
|
||||
if (registration.disabled === true || registration.enabled === false)
|
||||
return false;
|
||||
if (!isOwnedClientRegistrationCommand(command, currentCommandPath))
|
||||
return false;
|
||||
if (
|
||||
client === "codex" &&
|
||||
command.length === 3 &&
|
||||
command[2] === "mcp" &&
|
||||
resolve(command[0] ?? "") === resolve(process.execPath) &&
|
||||
resolve(command[1] ?? "") === currentCommandPath
|
||||
)
|
||||
return true;
|
||||
if (
|
||||
client.name === "codex" &&
|
||||
registration.startup_timeout_sec !==
|
||||
MCP_STARTUP_POLICY.codexStartupTimeoutSeconds
|
||||
)
|
||||
return false;
|
||||
if (client.format === "vscode" && registration.type !== "stdio") return false;
|
||||
if (
|
||||
client.format === "copilot_cli" &&
|
||||
(registration.type !== "stdio" ||
|
||||
JSON.stringify(registration.tools) !== JSON.stringify(["*"]))
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
command.length === 4 &&
|
||||
command[0] === "npx" &&
|
||||
@@ -123,6 +150,35 @@ const registrationAligned = (
|
||||
);
|
||||
};
|
||||
|
||||
const parseRegistration = (
|
||||
value: unknown,
|
||||
client: SetupClient,
|
||||
): z.output<typeof registrationSchema> => {
|
||||
if (client.format === "opencode") {
|
||||
const entry = z
|
||||
.object({
|
||||
type: z.literal("local"),
|
||||
command: z.array(z.string()).min(1),
|
||||
environment: z.record(z.string(), z.string()).optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.parse(value);
|
||||
const [command = "", ...args] = entry.command;
|
||||
return registrationSchema.parse({
|
||||
...entry,
|
||||
command,
|
||||
args,
|
||||
});
|
||||
}
|
||||
const registration = registrationSchema.parse(value);
|
||||
if (
|
||||
(client.format === "vscode" || client.format === "copilot_cli") &&
|
||||
registration.type !== "stdio"
|
||||
)
|
||||
throw new TypeError("Expected an stdio registration");
|
||||
return registration;
|
||||
};
|
||||
|
||||
const remediation =
|
||||
"Run rea setup to refresh this registration, then restart the client.";
|
||||
|
||||
|
||||
@@ -264,6 +264,46 @@ describe("doctor scoped readiness", () => {
|
||||
expect(staleSelected.healthy).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps agent readiness independent of Hopper host requirements", async () => {
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
platform: "linux",
|
||||
linuxDistribution: () =>
|
||||
Promise.resolve({
|
||||
id: "debian",
|
||||
versionId: "13",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
}),
|
||||
clientRegistrations: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/home/user/.codex/config.toml",
|
||||
command: ["rea", "mcp"],
|
||||
state: "aligned",
|
||||
remediation: null,
|
||||
},
|
||||
]),
|
||||
}),
|
||||
{ clients: ["codex"] },
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
healthy: true,
|
||||
environment_healthy: false,
|
||||
scope: { mode: "explicit", clients: ["codex"], providers: [] },
|
||||
});
|
||||
expect(result.scope_checks.map(({ name }) => name)).toEqual([
|
||||
"node",
|
||||
"registration:codex",
|
||||
]);
|
||||
expect(result.informational_checks).toContainEqual(
|
||||
expect.objectContaining({ name: "host", ok: false }),
|
||||
);
|
||||
});
|
||||
|
||||
it("requires explicitly selected providers instead of any available provider", async () => {
|
||||
const ghidra = {
|
||||
id: "ghidra",
|
||||
|
||||
@@ -7,7 +7,6 @@ import type {
|
||||
DoctorProviderInspection,
|
||||
DoctorScope,
|
||||
} from "./Doctor.js";
|
||||
import { doctorHealthy } from "./DoctorDiagnostics.js";
|
||||
|
||||
/** Normalized readiness boundary included in every doctor response. */
|
||||
export interface DoctorScopeReport {
|
||||
@@ -57,9 +56,7 @@ export const scopeDoctorChecks = (
|
||||
);
|
||||
const coreChecks = input.checks.filter(
|
||||
({ name }) =>
|
||||
!isProviderCheck(name, input.providers.providerInspections) &&
|
||||
name !== "skill:identity" &&
|
||||
!name.startsWith("registration:"),
|
||||
name === "node" || (input.scope.target !== null && name === "target"),
|
||||
);
|
||||
const clientChecks = input.scope.clients.map((client) =>
|
||||
selectedRegistrationCheck(
|
||||
@@ -70,36 +67,27 @@ export const scopeDoctorChecks = (
|
||||
const skillChecks = input.scope.skill
|
||||
? [selectedSkillCheck(input.skillState, input.checks)]
|
||||
: [];
|
||||
const selectedProviderChecks =
|
||||
input.scope.providers.length === 0
|
||||
? configuredProviderChecks(providerChecks, input.providers)
|
||||
: input.scope.providers.flatMap((providerId) =>
|
||||
selectedProviderChecksFor(
|
||||
providerId,
|
||||
providerChecks,
|
||||
input.providers,
|
||||
),
|
||||
);
|
||||
const selectedProviderChecks = input.scope.providers.flatMap((providerId) =>
|
||||
selectedProviderChecksFor(providerId, providerChecks, input.providers),
|
||||
);
|
||||
const hopperHostChecks = input.scope.providers.includes("hopper")
|
||||
? input.checks.filter(({ name }) => name === "host")
|
||||
: [];
|
||||
const scopeChecks = [
|
||||
...coreChecks,
|
||||
...hopperHostChecks,
|
||||
...selectedProviderChecks,
|
||||
...clientChecks,
|
||||
...skillChecks,
|
||||
];
|
||||
const providerHealthy =
|
||||
input.scope.providers.length === 0
|
||||
? doctorHealthy(
|
||||
[...coreChecks, ...providerChecks, ...clientChecks, ...skillChecks],
|
||||
input.providers,
|
||||
)
|
||||
: selectedProviderChecks.every(({ ok }) => ok);
|
||||
const selectedNames = new Set(scopeChecks.map(({ name }) => name));
|
||||
return {
|
||||
healthy:
|
||||
coreChecks.every(({ ok }) => ok) &&
|
||||
hopperHostChecks.every(({ ok }) => ok) &&
|
||||
clientChecks.every(({ ok }) => ok) &&
|
||||
skillChecks.every(({ ok }) => ok) &&
|
||||
providerHealthy,
|
||||
selectedProviderChecks.every(({ ok }) => ok),
|
||||
scopeChecks,
|
||||
informationalChecks: input.checks.filter(
|
||||
({ name }) => !selectedNames.has(name),
|
||||
@@ -114,19 +102,6 @@ const isProviderCheck = (
|
||||
name.startsWith("hopper") ||
|
||||
inspections?.some(({ id }) => doctorProviderCheckName(id, name)) === true;
|
||||
|
||||
const configuredProviderChecks = (
|
||||
checks: readonly DoctorCheck[],
|
||||
providers: DoctorProviderState,
|
||||
): readonly DoctorCheck[] =>
|
||||
checks.filter(({ name }) =>
|
||||
name.startsWith("hopper")
|
||||
? providers.hopperConfigured
|
||||
: providers.providerInspections?.some(
|
||||
({ id, configured }) =>
|
||||
configured && doctorProviderCheckName(id, name),
|
||||
) === true,
|
||||
);
|
||||
|
||||
const selectedProviderChecksFor = (
|
||||
providerId: string,
|
||||
checks: readonly DoctorCheck[],
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { FakeSetupHost, options } from "./Setup.fixture.js";
|
||||
import { runSetup } from "./Setup.js";
|
||||
import { runSetup, setupRegistrationCommand } from "./Setup.js";
|
||||
|
||||
describe("setup workflow", () => {
|
||||
it("omits an aligned managed skill from an otherwise empty plan", async () => {
|
||||
@@ -48,9 +49,14 @@ describe("setup workflow", () => {
|
||||
host.hopper = "/custom/Hopper";
|
||||
host.unsupportedHopperVersion = true;
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
{
|
||||
...options(true),
|
||||
clientIds: [],
|
||||
installSkill: false,
|
||||
proposeHopper: false,
|
||||
readinessScope: { providers: ["hopper"] },
|
||||
},
|
||||
host,
|
||||
() => Promise.resolve(true),
|
||||
);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
@@ -63,7 +69,10 @@ describe("setup workflow", () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopperInstallSucceeds = false;
|
||||
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
|
||||
const result = await runSetup(options(true, true), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(true, true), clientIds: [] },
|
||||
host,
|
||||
);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.code).toBe("download_failed");
|
||||
expect(result.remediation).toBe("Download failed.");
|
||||
@@ -80,7 +89,10 @@ describe("setup workflow", () => {
|
||||
remediation: "Repair the existing TOML.",
|
||||
});
|
||||
|
||||
const result = await runSetup(options(true, true), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(true, true), clientIds: ["codex"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe("Codex: Repair the existing TOML.");
|
||||
@@ -92,6 +104,7 @@ describe("setup workflow", () => {
|
||||
it("blocks malformed configuration before unrelated writes with an existing provider", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
host.clients = [
|
||||
{
|
||||
name: "claude_desktop",
|
||||
@@ -105,7 +118,10 @@ describe("setup workflow", () => {
|
||||
remediation: "Repair the existing JSON.",
|
||||
});
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(true), clientIds: ["claude_desktop"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe(
|
||||
@@ -122,7 +138,10 @@ describe("setup workflow", () => {
|
||||
];
|
||||
host.clientInspections.set("codex", { status: "already_current" });
|
||||
|
||||
const result = await runSetup(options(false), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(false, true), clientIds: ["codex"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(
|
||||
result.plannedActions.map(({ id, operation }) => ({
|
||||
@@ -141,6 +160,7 @@ describe("setup workflow action selection", () => {
|
||||
it("executes only actions selected by the interactive adapter", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
host.clients = [
|
||||
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
|
||||
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
|
||||
@@ -164,6 +184,83 @@ describe("setup workflow action selection", () => {
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
});
|
||||
|
||||
it("preflights only selected clients and offers supported clients without markers", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
host.clients = [];
|
||||
host.availableClients = [
|
||||
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
|
||||
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
|
||||
];
|
||||
host.clientInspections.set("cursor", {
|
||||
status: "invalid",
|
||||
remediation: "Repair the deselected Cursor configuration.",
|
||||
});
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(true), clientIds: ["codex"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.plannedActions.map(({ id }) => id)).toEqual([
|
||||
"configure_client:codex",
|
||||
]);
|
||||
expect(host.configurations).toBe(1);
|
||||
expect(result.clientStates).toMatchObject([
|
||||
{ client: { name: "codex" }, detected: false, status: "missing" },
|
||||
{ client: { name: "cursor" }, detected: false, status: "missing" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not default to a foreign command registered under the rea key", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
host.productRegistrations = [
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/codex.toml",
|
||||
command: ["unrelated-agent", "serve"],
|
||||
state: "stale",
|
||||
remediation: "Refresh this registration.",
|
||||
},
|
||||
];
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.plannedActions).toEqual([]);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(result.clientStates).toMatchObject([
|
||||
{ client: { name: "codex" }, configured: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses a Windows-safe executable command for an explicit client", async () => {
|
||||
const host = new FakeSetupHost("win32");
|
||||
host.scopedDoctorHealthy = true;
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "C:\\config\\codex.toml" }];
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(true), clientIds: ["codex"], installSkill: false },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.status).toBe("ready");
|
||||
expect(host.configuredCommands).toEqual([
|
||||
setupRegistrationCommand("win32"),
|
||||
]);
|
||||
expect(setupRegistrationCommand("win32", false)).toEqual([
|
||||
process.execPath,
|
||||
resolve(process.argv[1] ?? "rea"),
|
||||
"mcp",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"path",
|
||||
@@ -186,7 +283,10 @@ describe("setup workflow action selection", () => {
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [{ name: "internal_client_key", configPath: "/agent.json" }];
|
||||
host.clientResults.set("internal_client_key", { status: "failed", reason });
|
||||
const result = await runSetup(options(true), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(true), clientIds: ["internal_client_key"] },
|
||||
host,
|
||||
);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe(message);
|
||||
expect(result.remediation).not.toContain("internal_client_key");
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { detectClients } from "./Setup.js";
|
||||
|
||||
describe("setup client discovery", () => {
|
||||
let temporaryHome: string | undefined;
|
||||
|
||||
afterEach(async () => {
|
||||
if (temporaryHome !== undefined)
|
||||
await rm(temporaryHome, { recursive: true, force: true });
|
||||
temporaryHome = undefined;
|
||||
});
|
||||
|
||||
it("detects an existing config even when the marker directory is absent", async () => {
|
||||
temporaryHome = await mkdtemp(join(tmpdir(), "rea-setup-discovery-"));
|
||||
await writeFile(join(temporaryHome, ".claude.json"), "{}\n");
|
||||
|
||||
expect(
|
||||
(await detectClients(temporaryHome)).map(({ name }) => name),
|
||||
).toContain("claude_code");
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,9 @@ import {
|
||||
} from "./Setup.js";
|
||||
import type { DoctorCheck, DoctorReport, DoctorScope } from "./Doctor.js";
|
||||
import type { LinuxDistribution } from "./LinuxHopper.js";
|
||||
import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../identity.js";
|
||||
import { CATALOG_IDENTITY } from "../catalogIdentity.js";
|
||||
import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js";
|
||||
|
||||
/** Recording setup host for service-level planning and recovery tests. */
|
||||
export class FakeSetupHost implements SetupHost {
|
||||
@@ -22,6 +25,8 @@ export class FakeSetupHost implements SetupHost {
|
||||
hopperInstallSucceeds = true;
|
||||
skill: "installed" | "unchanged" | "failed" = "installed";
|
||||
clients: readonly SetupClient[] = [];
|
||||
availableClients: readonly SetupClient[] | undefined;
|
||||
productRegistrations: readonly ClientRegistrationStatus[] = [];
|
||||
clientResults = new Map<string, ClientConfigurationResult>();
|
||||
clientInspections = new Map<string, ClientConfigurationInspection>();
|
||||
hopperInstalls = 0;
|
||||
@@ -32,6 +37,7 @@ export class FakeSetupHost implements SetupHost {
|
||||
doctorScopes: Array<DoctorScope | undefined> = [];
|
||||
checkedHopperPaths: Array<string | undefined> = [];
|
||||
configuredProviderEnvironments: SetupProviderEnvironment[] = [];
|
||||
configuredCommands: Array<readonly string[]> = [];
|
||||
doctorHealthy: boolean | undefined;
|
||||
scopedDoctorHealthy: boolean | undefined;
|
||||
linuxDemoRuntimeMissing = false;
|
||||
@@ -75,12 +81,16 @@ export class FakeSetupHost implements SetupHost {
|
||||
};
|
||||
detectedClients = (): Promise<readonly SetupClient[]> =>
|
||||
Promise.resolve(this.clients);
|
||||
supportedClients = (): Promise<readonly SetupClient[]> =>
|
||||
Promise.resolve(this.availableClients ?? this.clients);
|
||||
configureClient = (
|
||||
client: SetupClient,
|
||||
providerEnvironment: SetupProviderEnvironment,
|
||||
command: readonly string[],
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
this.configurations += 1;
|
||||
this.configuredProviderEnvironments.push(providerEnvironment);
|
||||
this.configuredCommands.push(command);
|
||||
return Promise.resolve(
|
||||
this.clientResults.get(client.name) ?? { status: "configured" },
|
||||
);
|
||||
@@ -138,7 +148,11 @@ export class FakeSetupHost implements SetupHost {
|
||||
const healthy =
|
||||
scope === undefined
|
||||
? environmentHealthy
|
||||
: (this.scopedDoctorHealthy ?? environmentHealthy);
|
||||
: (scope.clients?.length ?? 0) === 0 &&
|
||||
(scope.providers?.length ?? 0) === 0 &&
|
||||
scope.skill !== true
|
||||
? true
|
||||
: (this.scopedDoctorHealthy ?? environmentHealthy);
|
||||
return Promise.resolve({
|
||||
healthy,
|
||||
environment_healthy: environmentHealthy,
|
||||
@@ -153,6 +167,25 @@ export class FakeSetupHost implements SetupHost {
|
||||
informational_checks: [],
|
||||
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
|
||||
checks,
|
||||
identity: {
|
||||
cli_package_version: PRODUCT_IDENTITY.packageVersion,
|
||||
expected_skill_version: PRODUCT_IDENTITY.skillVersion,
|
||||
sdk: SDK_IDENTITY,
|
||||
catalog: CATALOG_IDENTITY,
|
||||
live_server: {
|
||||
state: "unknown",
|
||||
remediation: "Inspect the running server.",
|
||||
},
|
||||
installations: { paths: [], state: "unknown" },
|
||||
skill: {
|
||||
installed_version: null,
|
||||
installed_tool_count: null,
|
||||
installed_catalog_digest: null,
|
||||
state: this.skill === "unchanged" ? "aligned" : "missing",
|
||||
remediation: null,
|
||||
},
|
||||
registrations: this.productRegistrations,
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,10 +7,12 @@ describe("setup workflow", () => {
|
||||
it("returns a complete plan without mutation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
|
||||
const result = await runSetup(options(false), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(false), clientIds: ["cursor"] },
|
||||
host,
|
||||
);
|
||||
expect(result.status).toBe("needs_confirmation");
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
|
||||
"install_hopper",
|
||||
"configure_client",
|
||||
"install_skill",
|
||||
]);
|
||||
@@ -61,7 +63,7 @@ describe("setup workflow", () => {
|
||||
host,
|
||||
() => Promise.resolve(false),
|
||||
);
|
||||
expect(result.status).toBe("planned");
|
||||
expect(result.status).toBe("cancelled");
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.doctorCalls).toBe(1);
|
||||
@@ -77,24 +79,40 @@ describe("setup workflow", () => {
|
||||
() => Promise.resolve({ approved: false, selectedActionIds: [] }),
|
||||
);
|
||||
|
||||
expect(result.status).toBe("planned");
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.plannedActions).toEqual([]);
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.doctorCalls).toBe(1);
|
||||
expect(host.doctorCalls).toBe(2);
|
||||
});
|
||||
|
||||
it("requires the Hopper flag for unattended setup", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.status).toBe("ready");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(result.appliedActions).toEqual(["installed_skill"]);
|
||||
expect(result.remediation).toBe(
|
||||
"Hopper is optional for non-Hopper providers. Rerun with --yes --install-hopper for deep native analysis.",
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns an approved planning outcome for explicit dry runs", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(false), dryRun: true, clientIds: ["codex"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.status).toBe("planned");
|
||||
expect(result.plannedActions.map(({ id }) => id)).toEqual([
|
||||
"configure_client:codex",
|
||||
]);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configurations).toBe(0);
|
||||
});
|
||||
|
||||
it("installs Hopper when unattended authorization is explicit", async () => {
|
||||
@@ -106,16 +124,13 @@ describe("setup workflow", () => {
|
||||
supported: true,
|
||||
};
|
||||
const result = await runSetup(options(true, true), host);
|
||||
expect(result.appliedActions).toEqual([
|
||||
"installed_hopper",
|
||||
"installed_skill",
|
||||
]);
|
||||
expect(result.appliedActions).toEqual(["installed_hopper"]);
|
||||
expect(host.hopperInstalls).toBe(1);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.remediation).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reuses existing Hopper and configures detected clients", async () => {
|
||||
it("reuses existing Hopper without selecting every detected client", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
@@ -124,11 +139,7 @@ describe("setup workflow", () => {
|
||||
];
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.appliedActions).toEqual([
|
||||
"configured_claude",
|
||||
"configured_cursor",
|
||||
"installed_skill",
|
||||
]);
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -144,6 +155,24 @@ describe("setup workflow lifecycle and provider planning", () => {
|
||||
configPath: "/codex.toml",
|
||||
},
|
||||
];
|
||||
host.productRegistrations = [
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/codex.toml",
|
||||
command: ["rea", "mcp"],
|
||||
state: "aligned",
|
||||
remediation: null,
|
||||
},
|
||||
];
|
||||
host.productRegistrations = [
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/codex.toml",
|
||||
command: ["rea", "mcp"],
|
||||
state: "aligned",
|
||||
remediation: null,
|
||||
},
|
||||
];
|
||||
const progress: SetupProgressEvent[] = [];
|
||||
await runSetup(
|
||||
{ ...options(true), onProgress: (event) => progress.push(event) },
|
||||
@@ -183,7 +212,10 @@ describe("setup workflow lifecycle and provider planning", () => {
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
|
||||
|
||||
const plan = await runSetup(options(false), host);
|
||||
const plan = await runSetup(
|
||||
{ ...options(false), clientIds: ["cursor"] },
|
||||
host,
|
||||
);
|
||||
expect(plan.plannedActions.map(({ kind }) => kind)).toEqual([
|
||||
"configure_client",
|
||||
]);
|
||||
@@ -196,7 +228,10 @@ describe("setup workflow lifecycle and provider planning", () => {
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configurations).toBe(0);
|
||||
|
||||
const applied = await runSetup(options(true), host);
|
||||
const applied = await runSetup(
|
||||
{ ...options(true), clientIds: ["cursor"] },
|
||||
host,
|
||||
);
|
||||
expect(applied.status).toBe("ready");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configuredProviderEnvironments).toContainEqual({
|
||||
@@ -212,7 +247,10 @@ describe("setup workflow lifecycle and provider planning", () => {
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
host.clientResults.set("codex", { status: "unchanged" });
|
||||
|
||||
const result = await runSetup(options(true, true), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(true, true), clientIds: ["codex"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
|
||||
"install_hopper",
|
||||
|
||||
@@ -16,7 +16,10 @@ describe("setup workflow", () => {
|
||||
host.clientResults.set("second", { status: "configured" });
|
||||
host.clientResults.set("third", { status: "failed", reason: "readback" });
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(true), clientIds: ["first", "second", "third"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(host.configurations).toBe(3);
|
||||
expect(result.clients).toEqual({
|
||||
@@ -33,7 +36,10 @@ describe("setup workflow", () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "failed";
|
||||
const result = await runSetup(options(true), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(true), installSkill: true, clientIds: [] },
|
||||
host,
|
||||
);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe(
|
||||
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
|
||||
@@ -44,7 +50,10 @@ describe("setup workflow", () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.doctorHealthy = false;
|
||||
const result = await runSetup(options(true), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(true), readinessScope: { providers: ["hopper"] } },
|
||||
host,
|
||||
);
|
||||
expect(result.remediation).toBe(
|
||||
"Run rea doctor and apply each reported remediation.",
|
||||
);
|
||||
@@ -55,6 +64,7 @@ describe("setup workflow", () => {
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.doctorHealthy = false;
|
||||
host.scopedDoctorHealthy = true;
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
const readinessScope = {
|
||||
clients: ["codex"],
|
||||
providers: [] as string[],
|
||||
@@ -77,12 +87,20 @@ describe("setup workflow", () => {
|
||||
});
|
||||
expect(host.doctorScopes).toEqual(expect.arrayContaining([readinessScope]));
|
||||
});
|
||||
});
|
||||
|
||||
it("explains unsupported Node and macOS recovery", async () => {
|
||||
describe("setup scoped readiness", () => {
|
||||
it("limits Hopper host checks to workflows that request Hopper", async () => {
|
||||
const platformHost = new FakeSetupHost("win32");
|
||||
expect((await runSetup(options(true), platformHost)).remediation).toBe(
|
||||
"REA supports Hopper on macOS and selected 64-bit Linux distributions.",
|
||||
platformHost.hopper = "/Applications/Hopper";
|
||||
platformHost.skill = "unchanged";
|
||||
platformHost.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
const windowsAgent = await runSetup(
|
||||
{ ...options(true), clientIds: ["codex"] },
|
||||
platformHost,
|
||||
);
|
||||
expect(windowsAgent.status).toBe("ready");
|
||||
expect(platformHost.configurations).toBe(1);
|
||||
|
||||
const nodeHost = new FakeSetupHost();
|
||||
nodeHost.nodeVersion = "20.0.0";
|
||||
@@ -92,11 +110,60 @@ describe("setup workflow", () => {
|
||||
|
||||
const macHost = new FakeSetupHost();
|
||||
macHost.version = "11.7";
|
||||
expect((await runSetup(options(true), macHost)).remediation).toBe(
|
||||
expect((await runSetup(options(true), macHost)).status).toBe("ready");
|
||||
expect((await runSetup(options(true, true), macHost)).remediation).toBe(
|
||||
"Upgrade to macOS 12 or newer.",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps an unchanged selected client in final readiness checks", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
host.productRegistrations = [
|
||||
{
|
||||
client: "codex",
|
||||
config_path: "/codex.toml",
|
||||
command: ["rea", "mcp"],
|
||||
state: "aligned",
|
||||
remediation: null,
|
||||
},
|
||||
];
|
||||
host.clientInspections.set("codex", { status: "already_current" });
|
||||
host.scopedDoctorHealthy = true;
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.plannedActions).toEqual([]);
|
||||
expect(host.doctorScopes.at(-1)).toEqual({
|
||||
clients: ["codex"],
|
||||
providers: [],
|
||||
skill: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not advertise an unhealthy Hopper in the selected readiness summary", async () => {
|
||||
const host = new FakeSetupHost("win32");
|
||||
host.hopper = "C:\\Hopper\\Hopper.exe";
|
||||
host.unsupportedHopperVersion = true;
|
||||
host.clients = [{ name: "codex", configPath: "C:\\codex.toml" }];
|
||||
host.scopedDoctorHealthy = true;
|
||||
|
||||
const result = await runSetup(
|
||||
{
|
||||
...options(true),
|
||||
clientIds: ["codex"],
|
||||
installSkill: false,
|
||||
},
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.doctor.availableProviders).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects unsupported hosts before mutation", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
@@ -127,7 +194,10 @@ describe("setup workflow", () => {
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
const result = await runSetup(
|
||||
{ ...options(true), clientIds: ["codex"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.status).toBe("ready");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
|
||||
+321
-104
@@ -8,6 +8,7 @@ import {
|
||||
runDoctor,
|
||||
systemDoctorHost,
|
||||
type DoctorHost,
|
||||
type DoctorReport,
|
||||
type DoctorScope,
|
||||
} from "./Doctor.js";
|
||||
import {
|
||||
@@ -23,9 +24,10 @@ import {
|
||||
canonicalSkillNeedsInstall,
|
||||
installCanonicalSkill,
|
||||
} from "./SetupSkill.js";
|
||||
import { discoverSetupActions } from "./SetupPlan.js";
|
||||
import { discoverSetupState, planSetupActions } from "./SetupPlan.js";
|
||||
import {
|
||||
clientConfigurationAligned,
|
||||
configureClientConfiguration,
|
||||
configureJsonClient,
|
||||
configureTomlClient,
|
||||
inspectClientConfiguration,
|
||||
@@ -44,10 +46,20 @@ export type SetupProviderEnvironment = Readonly<Record<string, string>>;
|
||||
|
||||
export { canonicalSkillNeedsInstall, installCanonicalSkill };
|
||||
|
||||
const registrationCommand = (): readonly string[] =>
|
||||
process.env.npm_command === "exec"
|
||||
/** Resolve the executable and arguments used in a managed MCP registration. */
|
||||
export const setupRegistrationCommand = (
|
||||
platform: NodeJS.Platform,
|
||||
useNpmRunner: boolean = process.env.npm_command === "exec",
|
||||
): readonly string[] =>
|
||||
useNpmRunner
|
||||
? PRODUCT_IDENTITY.mcpCommand.split(" ")
|
||||
: [resolve(process.argv[1] ?? PRODUCT_IDENTITY.cliBinary), "mcp"];
|
||||
: platform === "win32"
|
||||
? [
|
||||
process.execPath,
|
||||
resolve(process.argv[1] ?? PRODUCT_IDENTITY.cliBinary),
|
||||
"mcp",
|
||||
]
|
||||
: [resolve(process.argv[1] ?? PRODUCT_IDENTITY.cliBinary), "mcp"];
|
||||
|
||||
/** Result of one backup/write/readback transaction. */
|
||||
export type ClientConfigurationResult =
|
||||
@@ -81,6 +93,7 @@ export interface SetupHost {
|
||||
installHopper(replaceExisting: boolean): Promise<SetupHopperInstallResult>;
|
||||
providerEnvironment?(): Promise<SetupProviderEnvironment>;
|
||||
detectedClients(): Promise<readonly SetupClient[]>;
|
||||
supportedClients?(): Promise<readonly SetupClient[]>;
|
||||
configureClient(
|
||||
client: SetupClient,
|
||||
providerEnvironment: SetupProviderEnvironment,
|
||||
@@ -102,15 +115,44 @@ export interface SetupHost {
|
||||
}
|
||||
/** Structured setup outcome carrying remediation instead of prompting. */
|
||||
export interface SetupResult {
|
||||
readonly status: "planned" | "needs_confirmation" | "ready" | "needs_human";
|
||||
readonly status:
|
||||
| "planned"
|
||||
| "cancelled"
|
||||
| "needs_confirmation"
|
||||
| "ready"
|
||||
| "needs_human";
|
||||
readonly plannedActions: readonly SetupAction[];
|
||||
readonly appliedActions: readonly string[];
|
||||
readonly clients: Readonly<Record<string, ClientConfigurationResult>>;
|
||||
readonly doctor: Awaited<ReturnType<typeof runDoctor>>;
|
||||
readonly doctor: SetupDoctorSummary;
|
||||
/** Supported-client discovery state captured before setup mutations. */
|
||||
readonly clientStates: readonly SetupClientState[];
|
||||
readonly remediation?: string;
|
||||
readonly code?: SetupFailureCode;
|
||||
}
|
||||
|
||||
/** Relevant health and identity evidence for the selected setup scope. */
|
||||
export interface SetupDoctorSummary {
|
||||
readonly healthy: boolean;
|
||||
readonly environment_healthy: boolean;
|
||||
readonly scope: DoctorReport["scope"];
|
||||
readonly hopperPath?: string;
|
||||
readonly availableProviders: readonly string[];
|
||||
readonly providerInspections?: DoctorReport["providerInspections"];
|
||||
readonly identity?: Pick<
|
||||
NonNullable<DoctorReport["identity"]>,
|
||||
"skill" | "registrations"
|
||||
>;
|
||||
}
|
||||
|
||||
/** Read-only state for one supported client location. */
|
||||
export interface SetupClientState {
|
||||
readonly client: SetupClient;
|
||||
readonly detected: boolean;
|
||||
readonly configured: boolean;
|
||||
readonly status: "configured" | "missing" | "needs_configuration" | "invalid";
|
||||
}
|
||||
|
||||
/** One concrete setup mutation disclosed before approval. */
|
||||
export interface SetupAction {
|
||||
readonly id: string;
|
||||
@@ -135,6 +177,8 @@ export interface SetupOptions {
|
||||
readonly clientIds?: readonly string[];
|
||||
readonly installSkill?: boolean;
|
||||
readonly readinessScope?: DoctorScope;
|
||||
readonly dryRun?: boolean;
|
||||
readonly allDetectedClients?: boolean;
|
||||
readonly onProgress?: (event: SetupProgressEvent) => void;
|
||||
}
|
||||
|
||||
@@ -150,11 +194,21 @@ export interface SetupProgressEvent {
|
||||
export interface SetupConfirmationDecision {
|
||||
readonly approved: boolean;
|
||||
readonly selectedActionIds: readonly string[];
|
||||
readonly cancelled?: boolean;
|
||||
}
|
||||
|
||||
/** Adapter-owned interactive confirmation for a fully discovered setup plan. */
|
||||
/** Read-only context shown while selecting clients or reviewing exact actions. */
|
||||
export interface SetupConfirmationContext {
|
||||
readonly stage: "select" | "confirm";
|
||||
readonly clientStates: readonly SetupClientState[];
|
||||
readonly selectedClientIds: readonly string[];
|
||||
readonly clientSelectionAllowed: boolean;
|
||||
}
|
||||
|
||||
/** Adapter-owned selection and confirmation for the setup workflow. */
|
||||
export type SetupConfirmation = (
|
||||
actions: readonly SetupAction[],
|
||||
context?: SetupConfirmationContext,
|
||||
) => Promise<boolean | SetupConfirmationDecision>;
|
||||
|
||||
/** Discover, approve, and apply setup actions idempotently. */
|
||||
@@ -166,44 +220,179 @@ export const runSetup = async (
|
||||
const appliedActions: string[] = [];
|
||||
let plannedActions: readonly SetupAction[] = [];
|
||||
const clients: Record<string, ClientConfigurationResult> = {};
|
||||
let clientStates: readonly SetupClientState[] = [];
|
||||
let readinessScope = options.readinessScope;
|
||||
const fail = (remediation: string) =>
|
||||
setupFailure(
|
||||
remediation,
|
||||
[host, plannedActions, appliedActions, clients],
|
||||
options.readinessScope,
|
||||
[host, plannedActions, appliedActions, clients, clientStates],
|
||||
readinessScope,
|
||||
);
|
||||
const unsupported = await hostRemediation(host, options.installHopper);
|
||||
const unsupported = await hostRemediation(host, false);
|
||||
if (unsupported !== undefined) return fail(unsupported);
|
||||
let hopperPath = await host.hopperPath();
|
||||
let providerEnvironment = await initialProviderEnvironment(host, hopperPath);
|
||||
const discovery = await discoverSetupActions({
|
||||
const discovery = await discoverSetupState({
|
||||
host,
|
||||
providerEnvironment,
|
||||
command: registrationCommand(),
|
||||
forceHopperInstall: options.installHopper,
|
||||
proposeHopper: options.proposeHopper ?? true,
|
||||
selectedClientIds: options.clientIds,
|
||||
installSkillSelection: options.installSkill,
|
||||
proposeHopper:
|
||||
options.proposeHopper ?? (confirm !== undefined && !options.structured),
|
||||
doctorScope: options.readinessScope,
|
||||
});
|
||||
if (discovery.blocker !== undefined) return fail(discovery.blocker);
|
||||
const selection = await resolveSetupSelection(options, discovery, confirm);
|
||||
plannedActions = selection.plannedActions;
|
||||
if (!selection.approved)
|
||||
clientStates = discovery.clientStates;
|
||||
const clientSelectionAllowed =
|
||||
options.clientIds === undefined &&
|
||||
options.readinessScope?.clients === undefined &&
|
||||
options.allDetectedClients !== true &&
|
||||
options.installHopper !== true &&
|
||||
options.installSkill === undefined;
|
||||
const interactiveSelection =
|
||||
confirm !== undefined && !options.structured && clientSelectionAllowed;
|
||||
let selectedClientIds = options.allDetectedClients
|
||||
? discovery.detectedClientIds
|
||||
: (options.clientIds ??
|
||||
options.readinessScope?.clients ??
|
||||
discovery.defaultClientIds);
|
||||
let skillSelected =
|
||||
options.installSkill === true ||
|
||||
(options.installSkill !== false && selectedClientIds.length > 0);
|
||||
let installSkill = skillSelected && discovery.skillNeedsInstall;
|
||||
let planDiscovery = discovery;
|
||||
if (interactiveSelection) {
|
||||
const offerSkillAction =
|
||||
options.installSkill !== false && discovery.skillNeedsInstall;
|
||||
const selectionActions = await planSetupActions({
|
||||
discovery,
|
||||
host,
|
||||
providerEnvironment,
|
||||
command: setupRegistrationCommand(host.platform),
|
||||
clientIds: [],
|
||||
installSkill: offerSkillAction,
|
||||
});
|
||||
const decision = await confirm(selectionActions.plannedActions, {
|
||||
stage: "select",
|
||||
clientStates,
|
||||
selectedClientIds: discovery.defaultClientIds,
|
||||
clientSelectionAllowed,
|
||||
});
|
||||
if (isSetupDecisionCancelled(decision))
|
||||
return setupCancelled(
|
||||
selectionActions.plannedActions,
|
||||
clients,
|
||||
clientStates,
|
||||
discovery.initialDoctor,
|
||||
);
|
||||
const selectedActionIds = new Set(
|
||||
typeof decision === "boolean"
|
||||
? decision
|
||||
? [
|
||||
...selectionActions.plannedActions.map(({ id }) => id),
|
||||
...discovery.defaultClientIds.map(
|
||||
(id) => `configure_client:${id}`,
|
||||
),
|
||||
]
|
||||
: []
|
||||
: decision.selectedActionIds,
|
||||
);
|
||||
selectedClientIds = [...selectedActionIds]
|
||||
.filter((id) => id.startsWith("configure_client:"))
|
||||
.map((id) => id.slice("configure_client:".length));
|
||||
const proposedInstallAction = selectionActions.plannedActions.some(
|
||||
({ id }) => id === "install_hopper",
|
||||
);
|
||||
planDiscovery = {
|
||||
...discovery,
|
||||
installHopper:
|
||||
options.installHopper ||
|
||||
(proposedInstallAction && selectedActionIds.has("install_hopper")),
|
||||
};
|
||||
skillSelected =
|
||||
options.installSkill === true ||
|
||||
(selectedActionIds.has("install_skill") &&
|
||||
selectedClientIds.length === 0) ||
|
||||
(options.installSkill !== false && selectedClientIds.length > 0);
|
||||
installSkill = skillSelected && discovery.skillNeedsInstall;
|
||||
}
|
||||
const planned = await planSetupActions({
|
||||
discovery: planDiscovery,
|
||||
host,
|
||||
providerEnvironment,
|
||||
command: setupRegistrationCommand(host.platform),
|
||||
clientIds: selectedClientIds,
|
||||
installSkill,
|
||||
});
|
||||
plannedActions = planned.plannedActions;
|
||||
if (planned.blocker !== undefined) return fail(planned.blocker);
|
||||
const hopperBlocker = await hostRemediation(
|
||||
host,
|
||||
planDiscovery.installHopper,
|
||||
);
|
||||
if (hopperBlocker !== undefined) return fail(hopperBlocker);
|
||||
const planSelection = {
|
||||
installHopper: planDiscovery.installHopper,
|
||||
installSkill,
|
||||
skillSelected,
|
||||
selectedClients: planned.selectedClients,
|
||||
clientsToConfigure: planned.clientsToConfigure,
|
||||
};
|
||||
readinessScope = resolvedReadinessScope(
|
||||
options.readinessScope,
|
||||
planSelection,
|
||||
);
|
||||
|
||||
if (options.dryRun === true)
|
||||
return {
|
||||
status: confirm === undefined ? "needs_confirmation" : "planned",
|
||||
status: "planned",
|
||||
plannedActions,
|
||||
appliedActions,
|
||||
clients,
|
||||
doctor: discovery.initialDoctor,
|
||||
remediation:
|
||||
"Review the setup plan, then rerun interactively or with --yes.",
|
||||
doctor: summarizeDoctor(discovery.initialDoctor),
|
||||
clientStates,
|
||||
};
|
||||
|
||||
let detectedClients: readonly SetupClient[] = selection.detectedClients;
|
||||
let approved = options.approved || plannedActions.length === 0;
|
||||
let interactiveApproval = false;
|
||||
if (!approved && confirm !== undefined && !options.structured) {
|
||||
const decision = await confirm?.(plannedActions, {
|
||||
stage: "confirm",
|
||||
clientStates,
|
||||
selectedClientIds,
|
||||
clientSelectionAllowed: false,
|
||||
});
|
||||
if (decision !== undefined) {
|
||||
if (isSetupDecisionCancelled(decision))
|
||||
return setupCancelled(
|
||||
plannedActions,
|
||||
clients,
|
||||
clientStates,
|
||||
discovery.initialDoctor,
|
||||
);
|
||||
approved = typeof decision === "boolean" ? decision : decision.approved;
|
||||
interactiveApproval = approved;
|
||||
}
|
||||
}
|
||||
if (!approved)
|
||||
return {
|
||||
status: confirm === undefined ? "needs_confirmation" : "cancelled",
|
||||
plannedActions,
|
||||
appliedActions,
|
||||
clients,
|
||||
doctor: summarizeDoctor(discovery.initialDoctor),
|
||||
clientStates,
|
||||
...(confirm === undefined
|
||||
? {
|
||||
remediation:
|
||||
"Review the setup plan, then rerun interactively or with --yes.",
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
let selectedClients: readonly SetupClient[] =
|
||||
planSelection.clientsToConfigure;
|
||||
if (
|
||||
selection.installHopper &&
|
||||
(selection.interactiveApproval || options.installHopper)
|
||||
planSelection.installHopper &&
|
||||
(interactiveApproval || options.installHopper)
|
||||
) {
|
||||
const install = await installHopperAction({
|
||||
host,
|
||||
@@ -211,18 +400,19 @@ export const runSetup = async (
|
||||
plannedActions,
|
||||
appliedActions,
|
||||
clients,
|
||||
detectedClients,
|
||||
selectedClients,
|
||||
providerEnvironment,
|
||||
doctorScope: options.readinessScope,
|
||||
doctorScope: readinessScope,
|
||||
clientStates,
|
||||
});
|
||||
if ("failure" in install) return install.failure;
|
||||
({ hopperPath, providerEnvironment, detectedClients } = install);
|
||||
({ hopperPath, providerEnvironment, selectedClients } = install);
|
||||
}
|
||||
const clientFailure = await configureDetectedClients({
|
||||
host,
|
||||
detectedClients,
|
||||
detectedClients: selectedClients,
|
||||
providerEnvironment,
|
||||
command: registrationCommand(),
|
||||
command: setupRegistrationCommand(host.platform),
|
||||
clients,
|
||||
appliedActions,
|
||||
...(options.onProgress === undefined
|
||||
@@ -231,13 +421,13 @@ export const runSetup = async (
|
||||
});
|
||||
if (clientFailure !== undefined) return fail(clientFailure);
|
||||
if (
|
||||
selection.installSkill &&
|
||||
planSelection.installSkill &&
|
||||
!(await installSkillAction(host, options, appliedActions))
|
||||
)
|
||||
return fail(
|
||||
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
|
||||
);
|
||||
const doctor = await host.doctor(options.readinessScope);
|
||||
const doctor = summarizeDoctor(await host.doctor(readinessScope));
|
||||
const remediation = finalSetupRemediation(
|
||||
host.platform,
|
||||
appliedActions.includes("installed_hopper"),
|
||||
@@ -250,59 +440,21 @@ export const runSetup = async (
|
||||
appliedActions,
|
||||
clients,
|
||||
doctor,
|
||||
clientStates,
|
||||
...(remediation === undefined ? {} : { remediation }),
|
||||
};
|
||||
};
|
||||
|
||||
const resolveSetupSelection = async (
|
||||
options: SetupOptions,
|
||||
discovery: Awaited<ReturnType<typeof discoverSetupActions>>,
|
||||
confirm: SetupConfirmation | undefined,
|
||||
) => {
|
||||
let { installHopper, installSkill, detectedClients, plannedActions } =
|
||||
discovery;
|
||||
let approved = options.approved || plannedActions.length === 0;
|
||||
let interactiveApproval = false;
|
||||
if (!approved && confirm !== undefined && !options.structured) {
|
||||
const decision = await confirm(plannedActions);
|
||||
if (typeof decision === "boolean") {
|
||||
interactiveApproval = decision;
|
||||
approved = decision;
|
||||
} else {
|
||||
const selected = new Set(decision.selectedActionIds);
|
||||
plannedActions = plannedActions.filter(({ id }) => selected.has(id));
|
||||
installHopper = plannedActions.some(
|
||||
({ kind }) => kind === "install_hopper",
|
||||
);
|
||||
installSkill = plannedActions.some(
|
||||
({ kind }) => kind === "install_skill",
|
||||
);
|
||||
detectedClients = detectedClients.filter((client) =>
|
||||
selected.has(`configure_client:${client.name}`),
|
||||
);
|
||||
interactiveApproval = decision.approved;
|
||||
approved = decision.approved;
|
||||
}
|
||||
}
|
||||
return {
|
||||
approved,
|
||||
interactiveApproval,
|
||||
installHopper,
|
||||
installSkill,
|
||||
detectedClients,
|
||||
plannedActions,
|
||||
};
|
||||
};
|
||||
|
||||
const installHopperAction = async (input: {
|
||||
readonly host: SetupHost;
|
||||
readonly options: SetupOptions;
|
||||
readonly plannedActions: readonly SetupAction[];
|
||||
readonly appliedActions: string[];
|
||||
readonly clients: Readonly<Record<string, ClientConfigurationResult>>;
|
||||
readonly detectedClients: readonly SetupClient[];
|
||||
readonly selectedClients: readonly SetupClient[];
|
||||
readonly providerEnvironment: SetupProviderEnvironment;
|
||||
readonly doctorScope: DoctorScope | undefined;
|
||||
readonly clientStates: readonly SetupClientState[];
|
||||
}) => {
|
||||
const label = "Hopper deep-analysis provider";
|
||||
emitProgress(input.options, {
|
||||
@@ -324,7 +476,8 @@ const installHopperAction = async (input: {
|
||||
plannedActions: input.plannedActions,
|
||||
appliedActions: input.appliedActions,
|
||||
clients: input.clients,
|
||||
doctor: await input.host.doctor(input.doctorScope),
|
||||
doctor: summarizeDoctor(await input.host.doctor(input.doctorScope)),
|
||||
clientStates: input.clientStates,
|
||||
code: installed.code,
|
||||
remediation: installed.remediation,
|
||||
},
|
||||
@@ -344,11 +497,11 @@ const installHopperAction = async (input: {
|
||||
return {
|
||||
hopperPath: installed.launcherPath,
|
||||
providerEnvironment,
|
||||
detectedClients: await filterClientsNeedingConfigure(
|
||||
selectedClients: await filterClientsNeedingConfigure(
|
||||
input.host,
|
||||
input.detectedClients,
|
||||
input.selectedClients,
|
||||
providerEnvironment,
|
||||
registrationCommand(),
|
||||
setupRegistrationCommand(input.host.platform),
|
||||
),
|
||||
};
|
||||
};
|
||||
@@ -385,21 +538,25 @@ const installSkillAction = async (
|
||||
|
||||
const setupFailure = async (
|
||||
remediation: string,
|
||||
[host, plannedActions, appliedActions, clients]: readonly [
|
||||
[host, plannedActions, appliedActions, clients, clientStates]: readonly [
|
||||
SetupHost,
|
||||
readonly SetupAction[],
|
||||
readonly string[],
|
||||
Readonly<Record<string, ClientConfigurationResult>>,
|
||||
readonly SetupClientState[],
|
||||
],
|
||||
scope?: DoctorScope,
|
||||
): Promise<SetupResult> => ({
|
||||
status: "needs_human",
|
||||
plannedActions,
|
||||
appliedActions,
|
||||
clients,
|
||||
doctor: await host.doctor(scope),
|
||||
remediation,
|
||||
});
|
||||
): Promise<SetupResult> => {
|
||||
return {
|
||||
status: "needs_human",
|
||||
plannedActions,
|
||||
appliedActions,
|
||||
clients,
|
||||
doctor: summarizeDoctor(await host.doctor(scope)),
|
||||
clientStates,
|
||||
remediation,
|
||||
};
|
||||
};
|
||||
|
||||
const emitProgress = (options: SetupOptions, event: SetupProgressEvent): void =>
|
||||
options.onProgress?.(event);
|
||||
@@ -440,14 +597,78 @@ const finalSetupRemediation = (
|
||||
: "Run rea doctor and apply each reported remediation.";
|
||||
};
|
||||
|
||||
const isSetupDecisionCancelled = (
|
||||
decision: boolean | SetupConfirmationDecision,
|
||||
): boolean =>
|
||||
typeof decision === "boolean" ? !decision : decision.cancelled === true;
|
||||
|
||||
const setupCancelled = (
|
||||
plannedActions: readonly SetupAction[],
|
||||
clients: Readonly<Record<string, ClientConfigurationResult>>,
|
||||
clientStates: readonly SetupClientState[],
|
||||
doctor: DoctorReport,
|
||||
): SetupResult => ({
|
||||
status: "cancelled",
|
||||
plannedActions,
|
||||
appliedActions: [],
|
||||
clients,
|
||||
doctor: summarizeDoctor(doctor),
|
||||
clientStates,
|
||||
});
|
||||
|
||||
const resolvedReadinessScope = (
|
||||
requested: DoctorScope | undefined,
|
||||
selection: {
|
||||
readonly selectedClients: readonly SetupClient[];
|
||||
readonly installHopper: boolean;
|
||||
readonly skillSelected?: boolean;
|
||||
},
|
||||
): DoctorScope => ({
|
||||
clients: selection.selectedClients.map(({ name }) => name),
|
||||
providers: selection.installHopper
|
||||
? ["hopper"]
|
||||
: (requested?.providers ?? []),
|
||||
skill: selection.skillSelected === true || requested?.skill === true,
|
||||
});
|
||||
|
||||
const summarizeDoctor = (report: DoctorReport): SetupDoctorSummary => ({
|
||||
healthy: report.healthy,
|
||||
environment_healthy: report.environment_healthy,
|
||||
scope: report.scope,
|
||||
availableProviders: [
|
||||
...(report.hopperPath !== undefined &&
|
||||
report.checks
|
||||
.filter(({ name }) => name.startsWith("hopper"))
|
||||
.every(({ ok }) => ok)
|
||||
? ["hopper"]
|
||||
: []),
|
||||
...(report.providerInspections ?? [])
|
||||
.filter(({ available }) => available)
|
||||
.map(({ id }) => id),
|
||||
],
|
||||
...(report.hopperPath === undefined ? {} : { hopperPath: report.hopperPath }),
|
||||
...(report.providerInspections === undefined
|
||||
? {}
|
||||
: { providerInspections: report.providerInspections }),
|
||||
...(report.identity === undefined
|
||||
? {}
|
||||
: {
|
||||
identity: {
|
||||
skill: report.identity.skill,
|
||||
registrations: report.identity.registrations,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const hostRemediation = async (
|
||||
host: SetupHost,
|
||||
forceHopperInstall: boolean,
|
||||
installHopper: boolean,
|
||||
): Promise<string | undefined> => {
|
||||
if (host.platform !== "darwin" && host.platform !== "linux")
|
||||
return "REA supports Hopper on macOS and selected 64-bit Linux distributions.";
|
||||
if (!supportsNodeVersion(host.nodeVersion))
|
||||
return "Install Node.js 22.19+ or 24.11+ and rerun setup.";
|
||||
if (!installHopper) return undefined;
|
||||
if (host.platform !== "darwin" && host.platform !== "linux")
|
||||
return "REA supports Hopper on macOS and selected 64-bit Linux distributions.";
|
||||
if (host.platform === "darwin") {
|
||||
const version = await host.macosVersion();
|
||||
return version === undefined || major(version) < 12
|
||||
@@ -455,13 +676,6 @@ const hostRemediation = async (
|
||||
: undefined;
|
||||
}
|
||||
if ((await host.linuxDistribution())?.supported === true) return undefined;
|
||||
const providerEnvironment = await host.providerEnvironment?.();
|
||||
if (
|
||||
!forceHopperInstall &&
|
||||
providerEnvironment !== undefined &&
|
||||
Object.keys(providerEnvironment).length > 0
|
||||
)
|
||||
return undefined;
|
||||
return "Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.";
|
||||
};
|
||||
|
||||
@@ -493,12 +707,11 @@ export const systemSetupHost = (
|
||||
return setupInstallFailure(result.reason);
|
||||
},
|
||||
detectedClients: () => detectClients(homedir()),
|
||||
supportedClients: () => Promise.resolve(supportedClients(homedir())),
|
||||
configureClient: (client, providerEnvironment, command) =>
|
||||
client.format === "unsupported"
|
||||
? Promise.resolve({ status: "skipped" })
|
||||
: client.format === "toml"
|
||||
? configureTomlClient(client, providerEnvironment, command)
|
||||
: configureJsonClient(client, providerEnvironment, command),
|
||||
: configureClientConfiguration(client, providerEnvironment, command),
|
||||
clientNeedsConfigure: (client, providerEnvironment, command) =>
|
||||
clientConfigurationAligned(client, providerEnvironment, command).then(
|
||||
(aligned) => !aligned,
|
||||
@@ -510,14 +723,18 @@ export const systemSetupHost = (
|
||||
};
|
||||
};
|
||||
|
||||
/** Detect supported agents from stable per-user installation markers. */
|
||||
/** Detect supported agents from their config files or stable installation markers. */
|
||||
export const detectClients = async (
|
||||
home: string,
|
||||
): Promise<readonly SetupClient[]> => {
|
||||
const detected: SetupClient[] = [];
|
||||
for (const candidate of supportedClients(home))
|
||||
if (await exists(candidate.markerPath ?? candidate.configPath))
|
||||
detected.push(candidate);
|
||||
for (const candidate of supportedClients(home)) {
|
||||
const [hasConfig, hasMarker] = await Promise.all([
|
||||
exists(candidate.configPath),
|
||||
candidate.markerPath === undefined ? false : exists(candidate.markerPath),
|
||||
]);
|
||||
if (hasConfig || hasMarker) detected.push(candidate);
|
||||
}
|
||||
return detected;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
clientRegistrationEntry,
|
||||
clientConfigurationValuesEqual,
|
||||
parseClientConfiguration,
|
||||
serializeClientConfiguration,
|
||||
@@ -42,11 +43,22 @@ export const configureTomlClient = (
|
||||
): Promise<ClientConfigurationResult> =>
|
||||
configureClientDocument(client, environment, command, "toml");
|
||||
|
||||
/** Configure one supported client's native stdio MCP registration shape. */
|
||||
export const configureClientConfiguration = (
|
||||
client: SetupClient,
|
||||
environment: SetupProviderEnvironment = {},
|
||||
command: readonly string[] = defaultCommand(),
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
if (client.format === undefined || client.format === "unsupported")
|
||||
return Promise.resolve({ status: "failed", reason: "readback" });
|
||||
return configureClientDocument(client, environment, command, client.format);
|
||||
};
|
||||
|
||||
const configureClientDocument = async (
|
||||
client: SetupClient,
|
||||
environment: SetupProviderEnvironment,
|
||||
command: readonly string[],
|
||||
format: "json" | "toml",
|
||||
format: NonNullable<SetupClient["format"]>,
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
const transactionPath = await resolveClientConfigTransactionPath(
|
||||
client.configPath,
|
||||
@@ -69,7 +81,12 @@ const configureClientDocument = async (
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
const { document, servers, serversKey } = parsed;
|
||||
const desired = clientConfigurationDesired(client, environment, command);
|
||||
const desired = clientConfigurationDesired(
|
||||
client,
|
||||
environment,
|
||||
command,
|
||||
format,
|
||||
);
|
||||
if (
|
||||
clientConfigurationValuesEqual(
|
||||
servers[PRODUCT_IDENTITY.mcpServerKey],
|
||||
@@ -92,7 +109,12 @@ const configureClientDocument = async (
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
await writeFileAtomic(
|
||||
transactionPath,
|
||||
serializeClientConfiguration(document, format),
|
||||
serializeClientConfiguration(
|
||||
document,
|
||||
format,
|
||||
original,
|
||||
PRODUCT_IDENTITY.mcpServerKey,
|
||||
),
|
||||
{
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
@@ -135,6 +157,7 @@ export const clientConfigurationAligned = async (
|
||||
client,
|
||||
providerEnvironment,
|
||||
command,
|
||||
client.format,
|
||||
);
|
||||
try {
|
||||
const original = await readFile(client.configPath, "utf8");
|
||||
@@ -179,6 +202,7 @@ export const inspectClientConfiguration = async (
|
||||
client,
|
||||
providerEnvironment,
|
||||
command,
|
||||
client.format,
|
||||
);
|
||||
try {
|
||||
const { servers } = parseClientConfiguration(original, client.format);
|
||||
@@ -232,20 +256,24 @@ const clientConfigurationDesired = (
|
||||
client: SetupClient,
|
||||
providerEnvironment: SetupProviderEnvironment,
|
||||
command: readonly string[],
|
||||
format: NonNullable<SetupClient["format"]> | undefined,
|
||||
) => {
|
||||
const environment = Object.fromEntries(
|
||||
Object.entries(providerEnvironment).sort(([left], [right]) =>
|
||||
left.localeCompare(right),
|
||||
),
|
||||
);
|
||||
const registration = clientRegistrationEntry(
|
||||
format ?? "json",
|
||||
command.length === 0 ? [PRODUCT_IDENTITY.cliBinary, "mcp"] : command,
|
||||
environment,
|
||||
);
|
||||
return {
|
||||
command: command[0] ?? PRODUCT_IDENTITY.cliBinary,
|
||||
args: command.slice(1),
|
||||
...registration,
|
||||
...(client.name === "codex"
|
||||
? {
|
||||
startup_timeout_sec: MCP_STARTUP_POLICY.codexStartupTimeoutSeconds,
|
||||
}
|
||||
: {}),
|
||||
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
|
||||
};
|
||||
};
|
||||
|
||||
+214
-153
@@ -2,6 +2,7 @@ import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import {
|
||||
linuxHopperInstallDisclosure,
|
||||
type LinuxPackageFamily,
|
||||
@@ -10,30 +11,211 @@ import { macHopperInstallDisclosure } from "./MacHopper.js";
|
||||
import type {
|
||||
SetupAction,
|
||||
SetupClient,
|
||||
SetupClientState,
|
||||
SetupHost,
|
||||
SetupProviderEnvironment,
|
||||
} from "./Setup.js";
|
||||
import type { DoctorScope } from "./Doctor.js";
|
||||
|
||||
/** Preflighted client mutation admitted into the setup plan. */
|
||||
type SetupClientPlan = Readonly<{
|
||||
client: SetupClient;
|
||||
operation: "create" | "update";
|
||||
backupPath?: string;
|
||||
}>;
|
||||
|
||||
/** Inputs used to build the setup mutation plan. */
|
||||
interface SetupPlanOptions {
|
||||
readonly platform: NodeJS.Platform;
|
||||
/** Read-only setup facts shared by client selection and preflight. */
|
||||
export interface SetupDiscovery {
|
||||
readonly initialDoctor: Awaited<ReturnType<SetupHost["doctor"]>>;
|
||||
readonly installHopper: boolean;
|
||||
readonly installSkill: boolean;
|
||||
readonly clients: readonly SetupClientPlan[];
|
||||
readonly providerEnvironment: SetupProviderEnvironment;
|
||||
readonly skillNeedsInstall: boolean;
|
||||
readonly clients: readonly SetupClient[];
|
||||
readonly detectedClientIds: readonly string[];
|
||||
readonly defaultClientIds: readonly string[];
|
||||
readonly clientStates: readonly SetupClientState[];
|
||||
readonly linuxPackageFamily?: LinuxPackageFamily;
|
||||
}
|
||||
|
||||
/** Build the complete setup mutation plan before approval. */
|
||||
const setupPlan = (input: SetupPlanOptions): readonly SetupAction[] => [
|
||||
/** Discover supported clients and current registrations without mutation. */
|
||||
export const discoverSetupState = async (input: {
|
||||
readonly host: SetupHost;
|
||||
readonly providerEnvironment: SetupProviderEnvironment;
|
||||
readonly forceHopperInstall: boolean;
|
||||
readonly proposeHopper: boolean;
|
||||
readonly doctorScope: DoctorScope | undefined;
|
||||
}): Promise<SetupDiscovery> => {
|
||||
const initialDoctor = await input.host.doctor(input.doctorScope);
|
||||
const linuxHopperRepairNeeded = initialDoctor.checks.some(
|
||||
({ name, ok, detail }) =>
|
||||
!ok &&
|
||||
(name === "hopper-demo-runtime" ||
|
||||
(name === "hopper-version" && detail === "/opt/hopper/bin/Hopper")),
|
||||
);
|
||||
const linuxDistribution =
|
||||
input.host.platform === "linux"
|
||||
? await input.host.linuxDistribution()
|
||||
: undefined;
|
||||
const hopperInstallSupported =
|
||||
(input.host.platform === "darwin" &&
|
||||
majorVersion((await input.host.macosVersion()) ?? "0") >= 12) ||
|
||||
(input.host.platform === "linux" && linuxDistribution?.supported === true);
|
||||
const installHopper =
|
||||
input.forceHopperInstall ||
|
||||
(hopperInstallSupported &&
|
||||
input.proposeHopper &&
|
||||
(Object.keys(input.providerEnvironment).length === 0 ||
|
||||
linuxHopperRepairNeeded));
|
||||
const [clients, detectedClients, skillNeedsInstall] = await Promise.all([
|
||||
input.host.supportedClients?.() ?? input.host.detectedClients(),
|
||||
input.host.detectedClients(),
|
||||
input.host.skillNeedsInstall(),
|
||||
]);
|
||||
const detectedIds = new Set(detectedClients.map(({ name }) => name));
|
||||
const registrations = initialDoctor.identity?.registrations ?? [];
|
||||
const registrationByClient = new Map(
|
||||
registrations.map((registration) => [registration.client, registration]),
|
||||
);
|
||||
const clientStates = clients.map((client): SetupClientState => {
|
||||
const registration = registrationByClient.get(client.name);
|
||||
const ownedRegistration =
|
||||
(registration?.state === "aligned" || registration?.state === "stale") &&
|
||||
isOwnedClientRegistrationCommand(registration.command);
|
||||
const configured = ownedRegistration;
|
||||
const status: SetupClientState["status"] =
|
||||
registration?.state === "invalid"
|
||||
? "invalid"
|
||||
: ownedRegistration && registration.state === "aligned"
|
||||
? "configured"
|
||||
: ownedRegistration && registration.state === "stale"
|
||||
? "needs_configuration"
|
||||
: detectedIds.has(client.name)
|
||||
? "needs_configuration"
|
||||
: "missing";
|
||||
return {
|
||||
client,
|
||||
detected: detectedIds.has(client.name),
|
||||
configured,
|
||||
status,
|
||||
};
|
||||
});
|
||||
const defaultClientIds = registrations
|
||||
.filter(
|
||||
(registration) =>
|
||||
(registration.state === "aligned" || registration.state === "stale") &&
|
||||
isOwnedClientRegistrationCommand(registration.command),
|
||||
)
|
||||
.map(({ client }) => client);
|
||||
return {
|
||||
initialDoctor,
|
||||
installHopper,
|
||||
skillNeedsInstall,
|
||||
clients,
|
||||
detectedClientIds: [...detectedIds],
|
||||
defaultClientIds,
|
||||
clientStates,
|
||||
...(linuxDistribution?.packageFamily === undefined
|
||||
? {}
|
||||
: { linuxPackageFamily: linuxDistribution.packageFamily }),
|
||||
};
|
||||
};
|
||||
|
||||
/** Preflight exactly the selected clients and produce their concrete actions. */
|
||||
export const planSetupActions = async (input: {
|
||||
readonly discovery: SetupDiscovery;
|
||||
readonly host: SetupHost;
|
||||
readonly providerEnvironment: SetupProviderEnvironment;
|
||||
readonly command: readonly string[];
|
||||
readonly clientIds: readonly string[];
|
||||
readonly installSkill: boolean;
|
||||
}): Promise<{
|
||||
readonly plannedActions: readonly SetupAction[];
|
||||
readonly selectedClients: readonly SetupClient[];
|
||||
readonly clientsToConfigure: readonly SetupClient[];
|
||||
readonly blocker?: string;
|
||||
}> => {
|
||||
const byId = new Map(
|
||||
input.discovery.clients.map((client) => [client.name, client]),
|
||||
);
|
||||
const unknownClient = input.clientIds.find((id) => !byId.has(id));
|
||||
if (unknownClient !== undefined) {
|
||||
return {
|
||||
plannedActions: [],
|
||||
selectedClients: [],
|
||||
clientsToConfigure: [],
|
||||
blocker: `Unsupported setup client: ${unknownClient}.`,
|
||||
};
|
||||
}
|
||||
const selectedClients = input.clientIds.flatMap((id) => {
|
||||
const client = byId.get(id);
|
||||
return client === undefined ? [] : [client];
|
||||
});
|
||||
const inspections = await Promise.all(
|
||||
selectedClients.map(async (client) => ({
|
||||
client,
|
||||
inspection:
|
||||
(await input.host.inspectClientConfiguration?.(
|
||||
client,
|
||||
input.providerEnvironment,
|
||||
input.command,
|
||||
)) ?? ({ status: "update" } as const),
|
||||
})),
|
||||
);
|
||||
const invalid = inspections.find(
|
||||
({ inspection }) => inspection.status === "invalid",
|
||||
);
|
||||
if (invalid?.inspection.status === "invalid") {
|
||||
return {
|
||||
plannedActions: [],
|
||||
selectedClients,
|
||||
clientsToConfigure: [],
|
||||
blocker: `${invalid.client.displayName ?? invalid.client.name}: ${invalid.inspection.remediation}`,
|
||||
};
|
||||
}
|
||||
const clientPlans = inspections.flatMap(({ client, inspection }) =>
|
||||
inspection.status === "create" ||
|
||||
inspection.status === "update" ||
|
||||
(input.discovery.installHopper && inspection.status === "already_current")
|
||||
? [
|
||||
{
|
||||
client,
|
||||
operation:
|
||||
inspection.status === "already_current"
|
||||
? ("update" as const)
|
||||
: inspection.status,
|
||||
...(inspection.status !== "already_current" &&
|
||||
inspection.backupPath !== undefined
|
||||
? { backupPath: inspection.backupPath }
|
||||
: {}),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
return {
|
||||
plannedActions: setupPlan({
|
||||
platform: input.host.platform,
|
||||
installHopper: input.discovery.installHopper,
|
||||
installSkill: input.installSkill,
|
||||
clients: clientPlans,
|
||||
providerEnvironment: input.providerEnvironment,
|
||||
...(input.discovery.linuxPackageFamily === undefined
|
||||
? {}
|
||||
: { linuxPackageFamily: input.discovery.linuxPackageFamily }),
|
||||
command: input.command,
|
||||
}),
|
||||
selectedClients,
|
||||
clientsToConfigure: selectedClients.filter((client) =>
|
||||
clientPlans.some(({ client: planned }) => planned.name === client.name),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
/** Describe every selected setup mutation before user approval. */
|
||||
const setupPlan = (input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly installHopper: boolean;
|
||||
readonly installSkill: boolean;
|
||||
readonly clients: readonly {
|
||||
readonly client: SetupClient;
|
||||
readonly operation: "create" | "update";
|
||||
readonly backupPath?: string;
|
||||
}[];
|
||||
readonly providerEnvironment: SetupProviderEnvironment;
|
||||
readonly linuxPackageFamily?: LinuxPackageFamily;
|
||||
readonly command: readonly string[];
|
||||
}): readonly SetupAction[] => [
|
||||
...(input.installHopper
|
||||
? [
|
||||
{
|
||||
@@ -71,7 +253,9 @@ const setupPlan = (input: SetupPlanOptions): readonly SetupAction[] => [
|
||||
target: client.configPath,
|
||||
detail: clientConfigurationDetail(
|
||||
client.displayName ?? client.name,
|
||||
input.command,
|
||||
input.providerEnvironment,
|
||||
input.installHopper,
|
||||
),
|
||||
external: false,
|
||||
operation,
|
||||
@@ -94,141 +278,6 @@ const setupPlan = (input: SetupPlanOptions): readonly SetupAction[] => [
|
||||
: []),
|
||||
];
|
||||
|
||||
/** Discover and preflight the complete set of selectable setup actions. */
|
||||
export const discoverSetupActions = async (input: {
|
||||
readonly host: SetupHost;
|
||||
readonly providerEnvironment: SetupProviderEnvironment;
|
||||
readonly command: readonly string[];
|
||||
readonly forceHopperInstall: boolean;
|
||||
readonly proposeHopper: boolean;
|
||||
readonly selectedClientIds: readonly string[] | undefined;
|
||||
readonly installSkillSelection: boolean | undefined;
|
||||
readonly doctorScope: DoctorScope | undefined;
|
||||
}) => {
|
||||
const { host, providerEnvironment, command } = input;
|
||||
const initialDoctor = await host.doctor(input.doctorScope);
|
||||
const linuxHopperRepairNeeded = initialDoctor.checks.some(
|
||||
({ name, ok, detail }) =>
|
||||
!ok &&
|
||||
(name === "hopper-demo-runtime" ||
|
||||
(name === "hopper-version" && detail === "/opt/hopper/bin/Hopper")),
|
||||
);
|
||||
const installHopper =
|
||||
input.forceHopperInstall ||
|
||||
(input.proposeHopper &&
|
||||
(Object.keys(providerEnvironment).length === 0 ||
|
||||
linuxHopperRepairNeeded));
|
||||
const [allDetectedClients, skillNeedsInstall] = await Promise.all([
|
||||
host.detectedClients(),
|
||||
host.skillNeedsInstall(),
|
||||
]);
|
||||
const selectedClientIdSet =
|
||||
input.selectedClientIds === undefined
|
||||
? undefined
|
||||
: new Set(input.selectedClientIds);
|
||||
const detectedClients = allDetectedClients.filter(
|
||||
({ name }) =>
|
||||
selectedClientIdSet === undefined || selectedClientIdSet.has(name),
|
||||
);
|
||||
const installSkill =
|
||||
input.installSkillSelection === false ? false : skillNeedsInstall;
|
||||
const clients = installHopper
|
||||
? detectedClients
|
||||
: await filterClientsNeedingConfigure({
|
||||
host,
|
||||
clients: detectedClients,
|
||||
providerEnvironment,
|
||||
command,
|
||||
});
|
||||
const inspections = await inspectClients({
|
||||
host,
|
||||
clients,
|
||||
providerEnvironment,
|
||||
command,
|
||||
});
|
||||
const invalid = inspections.find(
|
||||
({ inspection }) => inspection.status === "invalid",
|
||||
);
|
||||
const blocker =
|
||||
invalid?.inspection.status === "invalid"
|
||||
? `${invalid.client.displayName ?? invalid.client.name}: ${invalid.inspection.remediation}`
|
||||
: undefined;
|
||||
const clientPlans = inspections.flatMap(({ client, inspection }) =>
|
||||
inspection.status === "create" ||
|
||||
inspection.status === "update" ||
|
||||
(installHopper && inspection.status === "already_current")
|
||||
? [
|
||||
{
|
||||
client,
|
||||
operation:
|
||||
inspection.status === "already_current"
|
||||
? ("update" as const)
|
||||
: inspection.status,
|
||||
...(inspection.status !== "already_current" &&
|
||||
inspection.backupPath !== undefined
|
||||
? { backupPath: inspection.backupPath }
|
||||
: {}),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
const linuxDistribution =
|
||||
host.platform === "linux" ? await host.linuxDistribution() : undefined;
|
||||
return {
|
||||
initialDoctor,
|
||||
installHopper,
|
||||
installSkill,
|
||||
detectedClients: clientPlans.map(({ client }) => client),
|
||||
plannedActions: setupPlan({
|
||||
platform: host.platform,
|
||||
installHopper,
|
||||
installSkill,
|
||||
clients: clientPlans,
|
||||
providerEnvironment,
|
||||
...(linuxDistribution?.packageFamily === undefined
|
||||
? {}
|
||||
: { linuxPackageFamily: linuxDistribution.packageFamily }),
|
||||
}),
|
||||
blocker,
|
||||
};
|
||||
};
|
||||
|
||||
const inspectClients = async (input: {
|
||||
readonly host: SetupHost;
|
||||
readonly clients: readonly SetupClient[];
|
||||
readonly providerEnvironment: SetupProviderEnvironment;
|
||||
readonly command: readonly string[];
|
||||
}) =>
|
||||
Promise.all(
|
||||
input.clients.map(async (client) => ({
|
||||
client,
|
||||
inspection:
|
||||
(await input.host.inspectClientConfiguration?.(
|
||||
client,
|
||||
input.providerEnvironment,
|
||||
input.command,
|
||||
)) ?? ({ status: "update" } as const),
|
||||
})),
|
||||
);
|
||||
|
||||
const filterClientsNeedingConfigure = async (input: {
|
||||
readonly host: SetupHost;
|
||||
readonly clients: readonly SetupClient[];
|
||||
readonly providerEnvironment: SetupProviderEnvironment;
|
||||
readonly command: readonly string[];
|
||||
}): Promise<readonly SetupClient[]> => {
|
||||
const needs = await Promise.all(
|
||||
input.clients.map((client) =>
|
||||
input.host.clientNeedsConfigure(
|
||||
client,
|
||||
input.providerEnvironment,
|
||||
input.command,
|
||||
),
|
||||
),
|
||||
);
|
||||
return input.clients.filter((_, index) => needs[index]);
|
||||
};
|
||||
|
||||
const linuxDisclosure = (family: LinuxPackageFamily) => {
|
||||
const disclosure = linuxHopperInstallDisclosure(
|
||||
family,
|
||||
@@ -241,14 +290,26 @@ const linuxDisclosure = (family: LinuxPackageFamily) => {
|
||||
};
|
||||
};
|
||||
|
||||
const majorVersion = (version: string): number =>
|
||||
Number.parseInt(version.split(".")[0] ?? "0", 10);
|
||||
|
||||
const clientConfigurationDetail = (
|
||||
client: string,
|
||||
command: readonly string[],
|
||||
environment: SetupProviderEnvironment,
|
||||
installHopper: boolean,
|
||||
): string => {
|
||||
const entries = Object.entries(environment)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([name, value]) => `${name}=${value}`);
|
||||
const suffix =
|
||||
entries.length === 0 ? "" : ` Environment: ${entries.join(", ")}.`;
|
||||
return `Add the REA MCP registration for ${client}; preserve unrelated configuration.${suffix}`;
|
||||
const environmentDetail =
|
||||
entries.length === 0
|
||||
? " No additional environment variables."
|
||||
: ` Environment: ${entries.join(", ")}.`;
|
||||
const hopperDetail = installHopper
|
||||
? environment.HOPPER_LAUNCHER_PATH === undefined
|
||||
? " If this plan installs Hopper, REA will add HOPPER_LAUNCHER_PATH using the launcher path reported by that installation."
|
||||
: " The HOPPER_LAUNCHER_PATH value shown above is the current fallback; if this plan installs Hopper, REA will replace it with the launcher path reported by that installation."
|
||||
: "";
|
||||
return `Add the REA MCP registration for ${client}; preserve unrelated configuration. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${hopperDetail}`;
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { join } from "node:path";
|
||||
import { lstatSync } from "node:fs";
|
||||
|
||||
/** One supported client configuration location. */
|
||||
export interface SetupClient {
|
||||
@@ -6,35 +7,138 @@ export interface SetupClient {
|
||||
readonly displayName?: string;
|
||||
readonly configPath: string;
|
||||
readonly markerPath?: string;
|
||||
readonly format?: "json" | "toml" | "unsupported";
|
||||
readonly format?:
|
||||
| "json"
|
||||
| "toml"
|
||||
| "vscode"
|
||||
| "copilot_cli"
|
||||
| "opencode"
|
||||
| "unsupported";
|
||||
}
|
||||
|
||||
type ClientPath = readonly string[] | ((paths: ClientPathContext) => string);
|
||||
|
||||
interface ClientPathContext {
|
||||
readonly home: string;
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: {
|
||||
readonly APPDATA?: string | undefined;
|
||||
readonly CLAUDE_CONFIG_DIR?: string | undefined;
|
||||
readonly CODEX_HOME?: string | undefined;
|
||||
readonly COPILOT_HOME?: string | undefined;
|
||||
readonly OPENCODE_CONFIG?: string | undefined;
|
||||
readonly XDG_CONFIG_HOME?: string | undefined;
|
||||
};
|
||||
}
|
||||
|
||||
interface ClientDefinition {
|
||||
readonly name: string;
|
||||
readonly displayName: string;
|
||||
readonly configPath: ClientPath;
|
||||
readonly markerPath: ClientPath;
|
||||
readonly format: NonNullable<SetupClient["format"]>;
|
||||
}
|
||||
|
||||
const vscodeUserDirectory = ({
|
||||
home,
|
||||
platform,
|
||||
env,
|
||||
}: ClientPathContext): string => {
|
||||
if (platform === "win32")
|
||||
return join(
|
||||
env.APPDATA ?? join(home, "AppData", "Roaming"),
|
||||
"Code",
|
||||
"User",
|
||||
);
|
||||
if (platform === "darwin")
|
||||
return join(home, "Library", "Application Support", "Code", "User");
|
||||
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Code", "User");
|
||||
};
|
||||
|
||||
const claudeDesktopDirectory = ({
|
||||
home,
|
||||
platform,
|
||||
env,
|
||||
}: ClientPathContext): string => {
|
||||
if (platform === "win32")
|
||||
return join(env.APPDATA ?? join(home, "AppData", "Roaming"), "Claude");
|
||||
if (platform === "linux")
|
||||
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Claude");
|
||||
return join(home, "Library", "Application Support", "Claude");
|
||||
};
|
||||
|
||||
const claudeCodeConfigDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.CLAUDE_CONFIG_DIR ?? home;
|
||||
|
||||
const claudeCodeMarkerDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.CLAUDE_CONFIG_DIR ?? join(home, ".claude");
|
||||
|
||||
const codexDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.CODEX_HOME ?? join(home, ".codex");
|
||||
|
||||
const copilotDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
env.COPILOT_HOME ?? join(home, ".copilot");
|
||||
|
||||
const opencodeDirectory = ({ home, env }: ClientPathContext): string =>
|
||||
join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "opencode");
|
||||
|
||||
const existingOpenCodeConfigPath = (context: ClientPathContext): string => {
|
||||
if (context.env.OPENCODE_CONFIG !== undefined)
|
||||
return context.env.OPENCODE_CONFIG;
|
||||
const directory = opencodeDirectory(context);
|
||||
const candidates = [
|
||||
"opencode.json",
|
||||
"opencode.jsonc",
|
||||
".opencode.json",
|
||||
".opencode.jsonc",
|
||||
].map((filename) => join(directory, filename));
|
||||
return (
|
||||
candidates.find((path) => {
|
||||
try {
|
||||
lstatSync(path);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
return !(
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT"
|
||||
);
|
||||
}
|
||||
}) ??
|
||||
candidates[0] ??
|
||||
join(directory, "opencode.json")
|
||||
);
|
||||
};
|
||||
|
||||
const devinDirectory = ({ home, platform, env }: ClientPathContext): string =>
|
||||
platform === "win32"
|
||||
? join(env.APPDATA ?? join(home, "AppData", "Roaming"), "devin")
|
||||
: join(home, ".config", "devin");
|
||||
|
||||
/** Stable product metadata used to derive setup discovery and documentation. */
|
||||
export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
{
|
||||
name: "claude_code",
|
||||
displayName: "Claude Code",
|
||||
configPath: [".claude.json"],
|
||||
markerPath: [".claude"],
|
||||
configPath: (context: ClientPathContext) =>
|
||||
join(claudeCodeConfigDirectory(context), ".claude.json"),
|
||||
markerPath: claudeCodeMarkerDirectory,
|
||||
format: "json",
|
||||
},
|
||||
{
|
||||
name: "claude_desktop",
|
||||
displayName: "Claude Desktop",
|
||||
configPath: [
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Claude",
|
||||
"claude_desktop_config.json",
|
||||
],
|
||||
markerPath: ["Library", "Application Support", "Claude"],
|
||||
configPath: (context: ClientPathContext) =>
|
||||
join(claudeDesktopDirectory(context), "claude_desktop_config.json"),
|
||||
markerPath: claudeDesktopDirectory,
|
||||
format: "json",
|
||||
},
|
||||
{
|
||||
name: "codex",
|
||||
displayName: "Codex",
|
||||
configPath: [".codex", "config.toml"],
|
||||
markerPath: [".codex"],
|
||||
configPath: (context: ClientPathContext) =>
|
||||
join(codexDirectory(context), "config.toml"),
|
||||
markerPath: codexDirectory,
|
||||
format: "toml",
|
||||
},
|
||||
{
|
||||
@@ -61,18 +165,65 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
|
||||
{
|
||||
name: "devin",
|
||||
displayName: "Devin",
|
||||
configPath: [".devin"],
|
||||
markerPath: [".devin"],
|
||||
format: "unsupported",
|
||||
configPath: ({ home, platform, env }: ClientPathContext) =>
|
||||
join(devinDirectory({ home, platform, env }), "mcp_config.json"),
|
||||
markerPath: devinDirectory,
|
||||
format: "json",
|
||||
},
|
||||
] as const;
|
||||
{
|
||||
name: "opencode",
|
||||
displayName: "OpenCode",
|
||||
configPath: existingOpenCodeConfigPath,
|
||||
markerPath: opencodeDirectory,
|
||||
format: "opencode",
|
||||
},
|
||||
{
|
||||
name: "antigravity",
|
||||
displayName: "Antigravity",
|
||||
configPath: [".gemini", "config", "mcp_config.json"],
|
||||
markerPath: [".gemini", "config"],
|
||||
format: "json",
|
||||
},
|
||||
{
|
||||
name: "copilot_cli",
|
||||
displayName: "GitHub Copilot CLI",
|
||||
configPath: (context: ClientPathContext) =>
|
||||
join(copilotDirectory(context), "mcp-config.json"),
|
||||
markerPath: copilotDirectory,
|
||||
format: "copilot_cli",
|
||||
},
|
||||
{
|
||||
name: "vscode",
|
||||
displayName: "VS Code",
|
||||
configPath: (context: ClientPathContext) =>
|
||||
join(vscodeUserDirectory(context), "mcp.json"),
|
||||
markerPath: vscodeUserDirectory,
|
||||
format: "vscode",
|
||||
},
|
||||
] as const satisfies readonly ClientDefinition[];
|
||||
|
||||
const resolvePath = (path: ClientPath, context: ClientPathContext): string =>
|
||||
typeof path === "function" ? path(context) : join(context.home, ...path);
|
||||
|
||||
/** Describe every client location that setup, doctor, or uninstall may inspect. */
|
||||
export const supportedClients = (home: string): readonly SetupClient[] =>
|
||||
SUPPORTED_CLIENT_DEFINITIONS.map((definition) => ({
|
||||
export const supportedClients = (
|
||||
home: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: ClientPathContext["env"] = {
|
||||
APPDATA: process.env.APPDATA,
|
||||
CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR,
|
||||
CODEX_HOME: process.env.CODEX_HOME,
|
||||
COPILOT_HOME: process.env.COPILOT_HOME,
|
||||
OPENCODE_CONFIG: process.env.OPENCODE_CONFIG,
|
||||
XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
|
||||
},
|
||||
): readonly SetupClient[] => {
|
||||
const context = { home, platform, env };
|
||||
return SUPPORTED_CLIENT_DEFINITIONS.map((definition) => ({
|
||||
name: definition.name,
|
||||
displayName: definition.displayName,
|
||||
configPath: join(home, ...definition.configPath),
|
||||
markerPath: join(home, ...definition.markerPath),
|
||||
configPath: resolvePath(definition.configPath, context),
|
||||
markerPath: resolvePath(definition.markerPath, context),
|
||||
format: definition.format,
|
||||
}));
|
||||
};
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import {
|
||||
parseClientConfiguration,
|
||||
serializeClientConfiguration,
|
||||
type ClientServersKey,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { copyFile, lstat, readFile, realpath, rm } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, isAbsolute, join } from "node:path";
|
||||
import { join } from "node:path";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
||||
import { supportedClients, type SetupClient } from "./SupportedClients.js";
|
||||
|
||||
@@ -123,7 +125,7 @@ const removeClient = async (
|
||||
);
|
||||
}
|
||||
let document: Record<string, unknown>;
|
||||
let key: "mcp_servers" | "mcpServers";
|
||||
let key: ClientServersKey;
|
||||
let servers: Record<string, unknown>;
|
||||
try {
|
||||
({
|
||||
@@ -135,13 +137,13 @@ const removeClient = async (
|
||||
return item(
|
||||
client.name,
|
||||
"failed",
|
||||
`Configuration is not valid ${client.format === "toml" ? "TOML" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
|
||||
`Configuration is not valid ${client.format === "toml" ? "TOML" : client.format === "opencode" ? "JSONC" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
|
||||
);
|
||||
}
|
||||
const registration = servers[PRODUCT_IDENTITY.mcpServerKey];
|
||||
if (registration === undefined)
|
||||
return item(client.name, "skipped", "REA registration is absent.");
|
||||
if (!isOwnedRegistration(registration))
|
||||
if (!isOwnedRegistration(registration, client))
|
||||
return item(
|
||||
client.name,
|
||||
"retained",
|
||||
@@ -163,7 +165,12 @@ const removeClient = async (
|
||||
try {
|
||||
await fileSystem.writeText(
|
||||
transactionPath,
|
||||
serializeClientConfiguration(document, client.format),
|
||||
serializeClientConfiguration(
|
||||
document,
|
||||
client.format,
|
||||
original,
|
||||
PRODUCT_IDENTITY.mcpServerKey,
|
||||
),
|
||||
);
|
||||
const readback = parseClientConfiguration(
|
||||
await fileSystem.readText(transactionPath),
|
||||
@@ -215,27 +222,20 @@ const resolveUninstallConfigPath = async (
|
||||
};
|
||||
|
||||
/** Ownership rule for persistent MCP registrations created by REA setup. */
|
||||
const isOwnedRegistration = (value: unknown): boolean => {
|
||||
const isOwnedRegistration = (value: unknown, client: SetupClient): boolean => {
|
||||
if (client.format === "opencode") {
|
||||
const parsed = z
|
||||
.object({ type: z.literal("local"), command: z.array(z.string()).min(1) })
|
||||
.passthrough()
|
||||
.safeParse(value);
|
||||
if (!parsed.success) return false;
|
||||
const command = parsed.data.command;
|
||||
return isOwnedClientRegistrationCommand(command);
|
||||
}
|
||||
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.registrationPackageSpecifier,
|
||||
"mcp",
|
||||
]) ||
|
||||
JSON.stringify(args) ===
|
||||
JSON.stringify(["-y", PRODUCT_IDENTITY.packageSpecifier, "mcp"]) ||
|
||||
JSON.stringify(args) ===
|
||||
JSON.stringify(["-y", PRODUCT_IDENTITY.packageName, "mcp"])))
|
||||
);
|
||||
return isOwnedClientRegistrationCommand([command, ...args]);
|
||||
};
|
||||
|
||||
const removeManagedPath = async (
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
runUpdate,
|
||||
type UpdateHost,
|
||||
type UpdateOutput,
|
||||
type NpmInstallation,
|
||||
} from "./Update.js";
|
||||
import {
|
||||
detectNpmInstallation,
|
||||
type NpmInstallationHost,
|
||||
} from "./UpdateRuntime.js";
|
||||
import type { IntegrationMaintenance } from "./UpdateMaintenance.js";
|
||||
|
||||
class FakeUpdateHost implements UpdateHost {
|
||||
release: Result<string, string> = ok("3.3.0");
|
||||
installationResult: NpmInstallation | undefined = {
|
||||
prefix: "/fixture",
|
||||
packageRoot: "/fixture/lib/node_modules/rea-agents",
|
||||
};
|
||||
installResult: Result<void, string> = ok(undefined);
|
||||
verified: Result<string, string> = ok("3.3.0");
|
||||
maintenance: IntegrationMaintenance = {
|
||||
status: "current",
|
||||
plannedActions: [],
|
||||
};
|
||||
installedVersions: string[] = [];
|
||||
installationInspected = false;
|
||||
verifiedInstallation: NpmInstallation | undefined;
|
||||
maintenanceInspected = false;
|
||||
output: UpdateOutput | undefined;
|
||||
|
||||
installation = (): Promise<NpmInstallation | undefined> => {
|
||||
this.installationInspected = true;
|
||||
return Promise.resolve(this.installationResult);
|
||||
};
|
||||
latestVersion = (): Promise<Result<string, string>> =>
|
||||
Promise.resolve(this.release);
|
||||
installVersion = (
|
||||
_installation: NpmInstallation,
|
||||
version: string,
|
||||
output: UpdateOutput,
|
||||
): Promise<Result<void, string>> => {
|
||||
this.installedVersions.push(version);
|
||||
this.output = output;
|
||||
return Promise.resolve(this.installResult);
|
||||
};
|
||||
installedVersion = (
|
||||
installation: NpmInstallation,
|
||||
): Promise<Result<string, string>> => {
|
||||
this.verifiedInstallation = installation;
|
||||
return Promise.resolve(this.verified);
|
||||
};
|
||||
planMaintenance = (): Promise<IntegrationMaintenance> => {
|
||||
this.maintenanceInspected = true;
|
||||
return Promise.resolve(this.maintenance);
|
||||
};
|
||||
}
|
||||
|
||||
describe("REA update", () => {
|
||||
it("identifies an already-current installation without mutation", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
expect(await runUpdate("3.3.0", host)).toEqual({
|
||||
status: "current",
|
||||
currentVersion: "3.3.0",
|
||||
latestVersion: "3.3.0",
|
||||
installMethod: "npm",
|
||||
});
|
||||
expect(host.installationInspected).toBe(true);
|
||||
expect(host.installedVersions).toEqual([]);
|
||||
expect(host.maintenanceInspected).toBe(false);
|
||||
});
|
||||
|
||||
it("reports an unknown current installation honestly", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.installationResult = undefined;
|
||||
expect(await runUpdate("3.3.0", host)).toMatchObject({
|
||||
status: "current",
|
||||
installMethod: "unknown",
|
||||
});
|
||||
expect(host.installedVersions).toEqual([]);
|
||||
});
|
||||
|
||||
it("installs the resolved release and verifies the same package root", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
expect(await runUpdate("3.2.1", host, "structured")).toMatchObject({
|
||||
status: "updated",
|
||||
previousVersion: "3.2.1",
|
||||
latestVersion: "3.3.0",
|
||||
installedVersion: "3.3.0",
|
||||
command: [
|
||||
"npm",
|
||||
"install",
|
||||
"--global",
|
||||
"--ignore-scripts",
|
||||
"--prefix",
|
||||
"/fixture",
|
||||
"rea-agents@3.3.0",
|
||||
],
|
||||
});
|
||||
expect(host.installedVersions).toEqual(["3.3.0"]);
|
||||
expect(host.verifiedInstallation).toEqual(host.installationResult);
|
||||
expect(host.output).toBe("structured");
|
||||
});
|
||||
|
||||
it("does not report success or plan maintenance when the installed version differs", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.verified = ok("3.4.0");
|
||||
expect(await runUpdate("3.2.1", host)).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "verification",
|
||||
latestVersion: "3.3.0",
|
||||
installedVersion: "3.4.0",
|
||||
});
|
||||
expect(host.maintenanceInspected).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves executable verification diagnostics after npm succeeded", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.verified = err("ENOENT /fixture/scripts/rea.mjs");
|
||||
const result = await runUpdate("3.2.1", host);
|
||||
expect(result).toMatchObject({ status: "failed", reason: "verification" });
|
||||
expect(result).toHaveProperty(
|
||||
"remediation",
|
||||
expect.stringContaining("ENOENT /fixture/scripts/rea.mjs"),
|
||||
);
|
||||
expect(host.maintenanceInspected).toBe(false);
|
||||
});
|
||||
|
||||
it("returns integration maintenance without applying it", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.maintenance = {
|
||||
status: "planned",
|
||||
scope: { clients: ["codex"], skill: false },
|
||||
command: ["rea", "setup", "--client", "codex", "--skill=false"],
|
||||
plannedActions: [
|
||||
{
|
||||
id: "configure_client:codex",
|
||||
kind: "configure_client",
|
||||
label: "Codex",
|
||||
target: "/home/.codex/config.toml",
|
||||
detail: "Refresh REA",
|
||||
external: false,
|
||||
operation: "update",
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(await runUpdate("3.2.1", host)).toMatchObject({
|
||||
status: "updated",
|
||||
maintenance: host.maintenance,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a verified update successful when maintenance planning fails", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.maintenance = {
|
||||
status: "unavailable",
|
||||
remediation: "EACCES /home/.codex/config.toml",
|
||||
};
|
||||
expect(await runUpdate("3.2.1", host)).toMatchObject({
|
||||
status: "updated",
|
||||
installedVersion: "3.3.0",
|
||||
maintenance: host.maintenance,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("update failures and version boundaries", () => {
|
||||
it("normalizes accepted release metadata before installing and comparing versions", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.release = ok("v3.3.0");
|
||||
expect(await runUpdate("3.2.1", host)).toMatchObject({
|
||||
status: "updated",
|
||||
latestVersion: "3.3.0",
|
||||
installedVersion: "3.3.0",
|
||||
});
|
||||
expect(host.installedVersions).toEqual(["3.3.0"]);
|
||||
});
|
||||
|
||||
it("preserves registry errors without installation", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.release = err("npm registry returned HTTP 503");
|
||||
const result = await runUpdate("3.2.1", host);
|
||||
expect(result).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "version-check",
|
||||
latestVersion: null,
|
||||
});
|
||||
expect(result).toHaveProperty(
|
||||
"remediation",
|
||||
expect.stringContaining("HTTP 503"),
|
||||
);
|
||||
expect(host.installedVersions).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["latest", "", "3.3", "$(echo bad)"])(
|
||||
"rejects invalid release metadata %s before installation",
|
||||
async (version) => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.release = ok(version);
|
||||
expect(await runUpdate("3.2.1", host)).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "version-check",
|
||||
});
|
||||
expect(host.installedVersions).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["3.4.0", "3.3.0"],
|
||||
["3.3.0", "3.3.0-rc.1"],
|
||||
])("does not downgrade %s to %s", async (currentVersion, release) => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.release = ok(release);
|
||||
expect(await runUpdate(currentVersion, host)).toMatchObject({
|
||||
status: "current",
|
||||
});
|
||||
expect(host.installedVersions).toEqual([]);
|
||||
});
|
||||
|
||||
it("updates a prerelease to its final release", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
expect(await runUpdate("3.3.0-rc.1", host)).toMatchObject({
|
||||
status: "updated",
|
||||
installedVersion: "3.3.0",
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses to create a global installation for an unrelated invocation", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.installationResult = undefined;
|
||||
const result = await runUpdate("3.2.1", host);
|
||||
expect(result).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "unknown-install-method",
|
||||
});
|
||||
expect(result).toHaveProperty(
|
||||
"remediation",
|
||||
expect.not.stringContaining("npm install --global"),
|
||||
);
|
||||
expect(host.installedVersions).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports actual npm failures and skips verification", async () => {
|
||||
const host = new FakeUpdateHost();
|
||||
host.installResult = err("EACCES /fixture/lib/node_modules/rea-agents");
|
||||
const result = await runUpdate("3.2.1", host);
|
||||
expect(result).toMatchObject({ status: "failed", reason: "install" });
|
||||
expect(result).toHaveProperty(
|
||||
"remediation",
|
||||
expect.stringContaining("EACCES /fixture/lib/node_modules/rea-agents"),
|
||||
);
|
||||
expect(host.verifiedInstallation).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("npm installation ownership", () => {
|
||||
const host = (root: string, prefix = "/usr/local"): NpmInstallationHost => ({
|
||||
canonicalPath: (path) => Promise.resolve(path),
|
||||
globalRoot: () => Promise.resolve(root),
|
||||
globalPrefix: () => Promise.resolve(prefix),
|
||||
});
|
||||
|
||||
it("identifies the global prefix and package root", async () => {
|
||||
const packageRoot = "/usr/local/lib/node_modules/rea-agents";
|
||||
await expect(
|
||||
detectNpmInstallation(packageRoot, host("/usr/local/lib/node_modules")),
|
||||
).resolves.toEqual({ prefix: "/usr/local", packageRoot });
|
||||
});
|
||||
|
||||
it("retains the curl installer's custom Unix prefix", async () => {
|
||||
const packageRoot = "/home/user/.local/lib/node_modules/rea-agents";
|
||||
await expect(
|
||||
detectNpmInstallation(packageRoot, host("/usr/local/lib/node_modules")),
|
||||
).resolves.toEqual({ prefix: "/home/user/.local", packageRoot });
|
||||
});
|
||||
|
||||
it.each([
|
||||
"/work/rea",
|
||||
"/work/node_modules/rea-agents",
|
||||
"/cache/_npx/abc/node_modules/rea-agents",
|
||||
])("rejects unrelated invocation %s", async (packageRoot) => {
|
||||
await expect(
|
||||
detectNpmInstallation(packageRoot, host("/usr/local/lib/node_modules")),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not trust an unresolvable installation path", async () => {
|
||||
const failing = {
|
||||
...host("/usr/local/lib/node_modules"),
|
||||
canonicalPath: (): Promise<string> => Promise.reject(new Error("EACCES")),
|
||||
};
|
||||
await expect(
|
||||
detectNpmInstallation(
|
||||
"/home/.local/lib/node_modules/rea-agents",
|
||||
failing,
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import { gt, valid } from "semver";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type { IntegrationMaintenance } from "./UpdateMaintenance.js";
|
||||
|
||||
/** Global npm installation that owns the running package and its entry point. */
|
||||
export interface NpmInstallation {
|
||||
readonly prefix: string;
|
||||
readonly packageRoot: string;
|
||||
}
|
||||
|
||||
/** Output policy for the package manager subprocess. */
|
||||
export type UpdateOutput = "human" | "structured";
|
||||
|
||||
/** Effects used to update and verify one identified REA installation. */
|
||||
export interface UpdateHost {
|
||||
installation(): Promise<NpmInstallation | undefined>;
|
||||
latestVersion(
|
||||
installation: NpmInstallation | undefined,
|
||||
): Promise<Result<string, string>>;
|
||||
installVersion(
|
||||
installation: NpmInstallation,
|
||||
version: string,
|
||||
output: UpdateOutput,
|
||||
): Promise<Result<void, string>>;
|
||||
installedVersion(
|
||||
installation: NpmInstallation,
|
||||
): Promise<Result<string, string>>;
|
||||
planMaintenance(
|
||||
installation: NpmInstallation,
|
||||
): Promise<IntegrationMaintenance>;
|
||||
}
|
||||
|
||||
/** Verified update outcome, separate from the unapplied integration plan. */
|
||||
export type UpdateResult =
|
||||
| {
|
||||
readonly status: "current";
|
||||
readonly currentVersion: string;
|
||||
readonly latestVersion: string;
|
||||
readonly installMethod: "npm" | "unknown";
|
||||
}
|
||||
| {
|
||||
readonly status: "updated";
|
||||
readonly previousVersion: string;
|
||||
readonly latestVersion: string;
|
||||
readonly installedVersion: string;
|
||||
readonly installMethod: "npm";
|
||||
readonly command: readonly string[];
|
||||
readonly maintenance: IntegrationMaintenance;
|
||||
readonly remediation: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly currentVersion: string;
|
||||
readonly latestVersion: string | null;
|
||||
readonly reason:
|
||||
| "unknown-install-method"
|
||||
| "version-check"
|
||||
| "install"
|
||||
| "verification";
|
||||
readonly installedVersion?: string;
|
||||
readonly remediation: string;
|
||||
};
|
||||
|
||||
/** Resolve the exact npm command for the identified prefix and release. */
|
||||
export const updateInstallCommand = (
|
||||
installation: NpmInstallation,
|
||||
version: string,
|
||||
): readonly string[] => [
|
||||
"npm",
|
||||
"install",
|
||||
"--global",
|
||||
"--ignore-scripts",
|
||||
"--prefix",
|
||||
installation.prefix,
|
||||
`${PRODUCT_IDENTITY.packageName}@${version}`,
|
||||
];
|
||||
|
||||
/** Identify, resolve, install, and verify REA without applying setup changes. */
|
||||
export const runUpdate = async (
|
||||
currentVersion: string,
|
||||
host: UpdateHost,
|
||||
output: UpdateOutput = "human",
|
||||
): Promise<UpdateResult> => {
|
||||
const installation = await host.installation();
|
||||
const release = await host.latestVersion(installation);
|
||||
const latestVersion = release.ok ? release.value : null;
|
||||
const targetVersion = release.ok ? valid(release.value) : null;
|
||||
if (!release.ok || valid(currentVersion) === null || targetVersion === null)
|
||||
return {
|
||||
status: "failed",
|
||||
currentVersion,
|
||||
latestVersion,
|
||||
reason: "version-check",
|
||||
remediation: release.ok
|
||||
? "REA received invalid version metadata. Check the installed version and npm registry, then rerun rea update."
|
||||
: `REA could not resolve the latest release: ${release.error}. Retry rea update when registry access is available.`,
|
||||
};
|
||||
if (!gt(targetVersion, currentVersion))
|
||||
return {
|
||||
status: "current",
|
||||
currentVersion,
|
||||
latestVersion: targetVersion,
|
||||
installMethod: installation === undefined ? "unknown" : "npm",
|
||||
};
|
||||
if (installation === undefined)
|
||||
return {
|
||||
status: "failed",
|
||||
currentVersion,
|
||||
latestVersion: targetVersion,
|
||||
reason: "unknown-install-method",
|
||||
remediation:
|
||||
"Update this installation with the package manager or source checkout that owns it. For a one-off latest invocation, use npx rea-agents@latest.",
|
||||
};
|
||||
const installed = await host.installVersion(
|
||||
installation,
|
||||
targetVersion,
|
||||
output,
|
||||
);
|
||||
if (!installed.ok)
|
||||
return {
|
||||
status: "failed",
|
||||
currentVersion,
|
||||
latestVersion: targetVersion,
|
||||
reason: "install",
|
||||
remediation: `REA could not install ${targetVersion} in ${installation.prefix}: ${installed.error}. Repair this npm installation, then rerun rea update.`,
|
||||
};
|
||||
const verified = await host.installedVersion(installation);
|
||||
if (!verified.ok || verified.value !== targetVersion)
|
||||
return {
|
||||
status: "failed",
|
||||
currentVersion,
|
||||
latestVersion: targetVersion,
|
||||
reason: "verification",
|
||||
...(verified.ok ? { installedVersion: verified.value } : {}),
|
||||
remediation: `npm completed, but REA could not verify ${targetVersion} in ${installation.packageRoot}: ${verified.ok ? `the executable reported ${verified.value}` : verified.error}. The installation may have changed; repair it before retrying.`,
|
||||
};
|
||||
const maintenance = await host.planMaintenance(installation);
|
||||
return {
|
||||
status: "updated",
|
||||
previousVersion: currentVersion,
|
||||
latestVersion: targetVersion,
|
||||
installedVersion: verified.value,
|
||||
installMethod: "npm",
|
||||
command: updateInstallCommand(installation, targetVersion),
|
||||
maintenance,
|
||||
remediation:
|
||||
maintenance.status === "planned"
|
||||
? "REA is updated. Run the maintenance command to review and approve changes to existing REA integrations, then restart affected agents."
|
||||
: maintenance.status === "unavailable"
|
||||
? "REA is updated. Integration maintenance could not be planned; inspect the maintenance diagnostic before changing configuration."
|
||||
: "REA is updated. Restart agents running this installation to load the new version.",
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,148 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { readClientRegistrationStatuses } from "./ClientRegistrationStatus.js";
|
||||
import { parseClientConfiguration } from "./ClientConfigurationDocument.js";
|
||||
import { supportedClients } from "./SupportedClients.js";
|
||||
import type { SetupAction } from "./Setup.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
|
||||
/** Existing REA integrations selected for maintenance, without discovering new targets. */
|
||||
export interface MaintenanceScope {
|
||||
readonly clients: readonly string[];
|
||||
readonly skill: boolean;
|
||||
}
|
||||
|
||||
/** Unapplied maintenance evidence produced by the updated setup executable. */
|
||||
export type IntegrationMaintenance =
|
||||
| { readonly status: "current"; readonly plannedActions: readonly [] }
|
||||
| {
|
||||
readonly status: "planned";
|
||||
readonly scope: MaintenanceScope;
|
||||
readonly command: readonly string[];
|
||||
readonly plannedActions: readonly SetupAction[];
|
||||
}
|
||||
| { readonly status: "unavailable"; readonly remediation: string };
|
||||
|
||||
const setupPlanSchema = z.object({
|
||||
status: z.literal("planned"),
|
||||
plannedActions: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
kind: z.enum(["configure_client", "install_skill"]),
|
||||
label: z.string(),
|
||||
target: z.string(),
|
||||
detail: z.string(),
|
||||
external: z.literal(false),
|
||||
operation: z.enum(["create", "update", "install"]),
|
||||
backupPath: z.string().optional(),
|
||||
commands: z.array(z.string()).optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
/** Discover owned registrations and an existing REA skill without writes. */
|
||||
export const existingMaintenanceScope = async (
|
||||
home: string,
|
||||
entryPoint: string,
|
||||
): Promise<MaintenanceScope> => {
|
||||
const registrations = await readClientRegistrationStatuses(home, entryPoint);
|
||||
const supported = supportedClients(home);
|
||||
const clients: string[] = [];
|
||||
for (const registration of registrations) {
|
||||
if (
|
||||
(registration.state !== "aligned" && registration.state !== "stale") ||
|
||||
!isOwnedClientRegistrationCommand(registration.command, entryPoint)
|
||||
)
|
||||
continue;
|
||||
const client = supported.find(({ name }) => name === registration.client);
|
||||
if (client === undefined) continue;
|
||||
const { servers } = parseClientConfiguration(
|
||||
await readFile(client.configPath, "utf8"),
|
||||
client.format,
|
||||
);
|
||||
const enabled = z
|
||||
.object({
|
||||
enabled: z.boolean().optional(),
|
||||
disabled: z.boolean().optional(),
|
||||
})
|
||||
.parse(servers[PRODUCT_IDENTITY.mcpServerKey]);
|
||||
if (enabled.enabled !== false && enabled.disabled !== true)
|
||||
clients.push(client.name);
|
||||
}
|
||||
let skill = false;
|
||||
try {
|
||||
const content = await readFile(
|
||||
join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName, "SKILL.md"),
|
||||
"utf8",
|
||||
);
|
||||
skill =
|
||||
content.startsWith(`---\nname: ${PRODUCT_IDENTITY.skillName}\n`) ||
|
||||
content.startsWith(`---\r\nname: ${PRODUCT_IDENTITY.skillName}\r\n`);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT"))
|
||||
throw cause;
|
||||
}
|
||||
return { clients, skill };
|
||||
};
|
||||
|
||||
/** Ask the verified new executable to plan only existing REA integrations. */
|
||||
export const planIntegrationMaintenance = async (
|
||||
home: string,
|
||||
entryPoint: string,
|
||||
execute: (command: readonly string[]) => Promise<Result<string, string>>,
|
||||
): Promise<IntegrationMaintenance> => {
|
||||
try {
|
||||
const scope = await existingMaintenanceScope(home, entryPoint);
|
||||
if (scope.clients.length === 0 && !scope.skill)
|
||||
return { status: "current", plannedActions: [] };
|
||||
const command = [
|
||||
process.execPath,
|
||||
entryPoint,
|
||||
"setup",
|
||||
...scope.clients.flatMap((client) => ["--client", client]),
|
||||
`--skill=${String(scope.skill)}`,
|
||||
];
|
||||
const execution = await execute([...command, "--dry-run", "--json"]);
|
||||
if (!execution.ok)
|
||||
return { status: "unavailable", remediation: execution.error };
|
||||
const plan = setupPlanSchema.safeParse(JSON.parse(execution.value));
|
||||
if (!plan.success)
|
||||
return {
|
||||
status: "unavailable",
|
||||
remediation: `The updated setup executable returned an invalid maintenance plan: ${plan.error.message}`,
|
||||
};
|
||||
if (plan.data.plannedActions.length === 0)
|
||||
return { status: "current", plannedActions: [] };
|
||||
const allowedIds = new Set([
|
||||
...scope.clients.map((client) => `configure_client:${client}`),
|
||||
...(scope.skill ? ["install_skill"] : []),
|
||||
]);
|
||||
if (plan.data.plannedActions.some(({ id }) => !allowedIds.has(id)))
|
||||
return {
|
||||
status: "unavailable",
|
||||
remediation:
|
||||
"The updated setup plan included an integration outside the existing REA maintenance scope.",
|
||||
};
|
||||
return {
|
||||
status: "planned",
|
||||
scope,
|
||||
command,
|
||||
plannedActions: plan.data.plannedActions.map(
|
||||
({ backupPath, commands, ...action }) => ({
|
||||
...action,
|
||||
...(backupPath === undefined ? {} : { backupPath }),
|
||||
...(commands === undefined ? {} : { commands }),
|
||||
}),
|
||||
),
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
return {
|
||||
status: "unavailable",
|
||||
remediation: cause instanceof Error ? cause.message : String(cause),
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,168 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import spawn from "cross-spawn";
|
||||
import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
updateInstallCommand,
|
||||
type NpmInstallation,
|
||||
type UpdateHost,
|
||||
type UpdateOutput,
|
||||
} from "./Update.js";
|
||||
import { planIntegrationMaintenance } from "./UpdateMaintenance.js";
|
||||
|
||||
/** npm filesystem queries used to identify the installation being updated. */
|
||||
export interface NpmInstallationHost {
|
||||
canonicalPath(path: string): Promise<string>;
|
||||
globalRoot(): Promise<string>;
|
||||
globalPrefix(): Promise<string>;
|
||||
}
|
||||
|
||||
/** Run an updater subprocess with complete diagnostics and isolated machine output. */
|
||||
export const runUpdateCommand = (
|
||||
command: readonly string[],
|
||||
output: UpdateOutput = "structured",
|
||||
): Promise<Result<string, string>> =>
|
||||
new Promise((resolveResult) => {
|
||||
const [executable, ...args] = command;
|
||||
if (executable === undefined) {
|
||||
resolveResult(err("No executable supplied."));
|
||||
return;
|
||||
}
|
||||
const environment = { ...process.env };
|
||||
// A fresh installed entry point must not inherit npx's invocation identity.
|
||||
delete environment.npm_command;
|
||||
const child = spawn(executable, args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: environment,
|
||||
windowsHide: true,
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stderr?.setEncoding("utf8");
|
||||
child.stdout?.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
if (output === "human") process.stderr.write(chunk);
|
||||
});
|
||||
child.stderr?.on("data", (chunk: string) => {
|
||||
stderr += chunk;
|
||||
if (output === "human") process.stderr.write(chunk);
|
||||
});
|
||||
child.once("error", (cause) => resolveResult(err(cause.message)));
|
||||
child.once("close", (code, signal) =>
|
||||
resolveResult(
|
||||
code === 0
|
||||
? ok(stdout.trim())
|
||||
: err(
|
||||
stderr.trim() ||
|
||||
stdout.trim() ||
|
||||
(signal === null
|
||||
? `Process exited with code ${String(code)}.`
|
||||
: `Process terminated by ${signal}.`),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const requireCommandOutput = async (
|
||||
command: readonly string[],
|
||||
): Promise<string> => {
|
||||
const result = await runUpdateCommand(command);
|
||||
if (!result.ok) throw new Error(result.error);
|
||||
return result.value;
|
||||
};
|
||||
|
||||
/** Resolve the global prefix only when it owns the running package. */
|
||||
export const detectNpmInstallation = async (
|
||||
packageRoot: string,
|
||||
host: NpmInstallationHost,
|
||||
): Promise<NpmInstallation | undefined> => {
|
||||
let canonicalPackageRoot: string;
|
||||
try {
|
||||
canonicalPackageRoot = await host.canonicalPath(packageRoot);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const npmRoot = await host.globalRoot();
|
||||
const globalPackageRoot = await host.canonicalPath(
|
||||
resolve(npmRoot, PRODUCT_IDENTITY.packageName),
|
||||
);
|
||||
if (canonicalPackageRoot === globalPackageRoot) {
|
||||
const prefix = await host.globalPrefix();
|
||||
return prefix.length === 0
|
||||
? undefined
|
||||
: { prefix, packageRoot: canonicalPackageRoot };
|
||||
}
|
||||
} catch {
|
||||
// The curl installer uses a Unix prefix that may differ from npm's current default.
|
||||
}
|
||||
const nodeModules = dirname(canonicalPackageRoot);
|
||||
const library = dirname(nodeModules);
|
||||
if (
|
||||
basename(canonicalPackageRoot) !== PRODUCT_IDENTITY.packageName ||
|
||||
basename(nodeModules) !== "node_modules" ||
|
||||
basename(library) !== "lib"
|
||||
)
|
||||
return undefined;
|
||||
return { prefix: dirname(library), packageRoot: canonicalPackageRoot };
|
||||
};
|
||||
|
||||
/** Create npm, registry, verification, and read-only maintenance effects. */
|
||||
export const systemUpdateHost = (
|
||||
packageRoot = fileURLToPath(new URL("../..", import.meta.url)),
|
||||
home = homedir(),
|
||||
): UpdateHost => ({
|
||||
installation: () =>
|
||||
detectNpmInstallation(packageRoot, {
|
||||
canonicalPath: realpath,
|
||||
globalRoot: () => requireCommandOutput(["npm", "root", "--global"]),
|
||||
globalPrefix: () => requireCommandOutput(["npm", "prefix", "--global"]),
|
||||
}),
|
||||
latestVersion: async (installation) => {
|
||||
const response = await runUpdateCommand([
|
||||
"npm",
|
||||
"view",
|
||||
"--global",
|
||||
...(installation === undefined ? [] : ["--prefix", installation.prefix]),
|
||||
PRODUCT_IDENTITY.packageName,
|
||||
"dist-tags.latest",
|
||||
"--json",
|
||||
"--fetch-retries=0",
|
||||
"--fetch-timeout=10000",
|
||||
]);
|
||||
if (!response.ok) return response;
|
||||
try {
|
||||
const parsed = z.string().min(1).safeParse(JSON.parse(response.value));
|
||||
return parsed.success
|
||||
? ok(parsed.data)
|
||||
: err(`Invalid npm release metadata: ${parsed.error.message}`);
|
||||
} catch (cause: unknown) {
|
||||
return err(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
},
|
||||
installVersion: async (installation, version, output) => {
|
||||
const result = await runUpdateCommand(
|
||||
updateInstallCommand(installation, version),
|
||||
output,
|
||||
);
|
||||
return result.ok ? ok(undefined) : result;
|
||||
},
|
||||
installedVersion: (installation) =>
|
||||
runUpdateCommand([
|
||||
process.execPath,
|
||||
join(installation.packageRoot, "scripts", "rea.mjs"),
|
||||
"--version",
|
||||
]),
|
||||
planMaintenance: (installation) =>
|
||||
planIntegrationMaintenance(
|
||||
home,
|
||||
join(installation.packageRoot, "scripts", "rea.mjs"),
|
||||
runUpdateCommand,
|
||||
),
|
||||
});
|
||||
@@ -1,201 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
detectNpmInstallation,
|
||||
runUpgrade,
|
||||
type UpgradeHost,
|
||||
type UpgradeOutput,
|
||||
type NpmInstallationHost,
|
||||
} from "./Upgrade.js";
|
||||
|
||||
class FakeUpgradeHost implements UpgradeHost {
|
||||
latest: string | undefined = "0.6.0";
|
||||
installationResult: { readonly prefix: string } | undefined = {
|
||||
prefix: "/fixture",
|
||||
};
|
||||
installSucceeds = true;
|
||||
installs = 0;
|
||||
output: UpgradeOutput | undefined;
|
||||
syncResult: boolean | undefined = true;
|
||||
syncs = 0;
|
||||
|
||||
latestVersion = (): Promise<string | undefined> =>
|
||||
Promise.resolve(this.latest);
|
||||
installation = (): Promise<{ readonly prefix: string } | undefined> =>
|
||||
Promise.resolve(this.installationResult);
|
||||
installLatest = (
|
||||
_installation: { readonly prefix: string },
|
||||
output: UpgradeOutput,
|
||||
): Promise<boolean> => {
|
||||
this.installs += 1;
|
||||
this.output = output;
|
||||
return Promise.resolve(this.installSucceeds);
|
||||
};
|
||||
syncAgentIntegration = (
|
||||
_output: UpgradeOutput,
|
||||
): Promise<boolean | undefined> => {
|
||||
this.syncs += 1;
|
||||
return Promise.resolve(this.syncResult);
|
||||
};
|
||||
}
|
||||
|
||||
describe("CLI upgrade", () => {
|
||||
it("reports an already-current release without mutation", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
|
||||
expect(await runUpgrade("0.6.0", host)).toEqual({
|
||||
status: "current",
|
||||
currentVersion: "0.6.0",
|
||||
latestVersion: "0.6.0",
|
||||
installMethod: "npm",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
});
|
||||
|
||||
it("upgrades an outdated global npm installation", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
|
||||
expect(await runUpgrade("0.5.0", host)).toEqual({
|
||||
status: "upgraded",
|
||||
previousVersion: "0.5.0",
|
||||
latestVersion: "0.6.0",
|
||||
versionCheck: "available",
|
||||
installMethod: "npm",
|
||||
command: "npm install --global rea-agents@latest",
|
||||
integrationSync: "setup_invoked",
|
||||
clientRestartRequired: true,
|
||||
remediation:
|
||||
"The updated setup journey was opened to align registrations and the skill. Restart clients whose approved registration changed.",
|
||||
});
|
||||
expect(host.installs).toBe(1);
|
||||
expect(host.syncs).toBe(1);
|
||||
});
|
||||
|
||||
it("does not mutate when the registry check is unavailable", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.latest = undefined;
|
||||
|
||||
expect(await runUpgrade("0.5.0", host)).toMatchObject({
|
||||
status: "failed",
|
||||
latestVersion: null,
|
||||
reason: "version-check",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["1.10.0", "1.9.0"],
|
||||
["1.0.0", "1.0.0-rc.1"],
|
||||
])(
|
||||
"does not downgrade installed version %s to registry version %s",
|
||||
async (currentVersion, latestVersion) => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.latest = latestVersion;
|
||||
|
||||
expect(await runUpgrade(currentVersion, host)).toEqual({
|
||||
status: "current",
|
||||
currentVersion,
|
||||
latestVersion,
|
||||
installMethod: "npm",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("upgrades a prerelease when the final release is available", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.latest = "1.0.0";
|
||||
|
||||
expect(await runUpgrade("1.0.0-rc.1", host)).toMatchObject({
|
||||
status: "upgraded",
|
||||
previousVersion: "1.0.0-rc.1",
|
||||
latestVersion: "1.0.0",
|
||||
});
|
||||
expect(host.installs).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects invalid registry version metadata without mutation", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.latest = "latest";
|
||||
|
||||
expect(await runUpgrade("1.0.0", host)).toMatchObject({
|
||||
status: "failed",
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: "latest",
|
||||
reason: "version-check",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
});
|
||||
|
||||
it("preserves stdout for an explicitly structured CLI response", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.syncResult = undefined;
|
||||
|
||||
expect(await runUpgrade("0.5.0", host, "structured")).toMatchObject({
|
||||
status: "upgraded",
|
||||
integrationSync: "deferred",
|
||||
remediation:
|
||||
"Run rea setup --all-detected to align registrations and the skill, then restart clients that may retain an older MCP server.",
|
||||
});
|
||||
|
||||
expect(host.output).toBe("structured");
|
||||
});
|
||||
|
||||
it("refuses to mutate an unrelated installation", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.installationResult = undefined;
|
||||
|
||||
expect(await runUpgrade("0.5.0", host)).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "unknown-install-method",
|
||||
remediation:
|
||||
"Update manually with: npm install --global rea-agents@latest",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
});
|
||||
|
||||
it("reports npm installation failure", async () => {
|
||||
const host = new FakeUpgradeHost();
|
||||
host.installSucceeds = false;
|
||||
|
||||
expect(await runUpgrade("0.5.0", host)).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "install",
|
||||
remediation:
|
||||
"REA could not update through npm. Check npm registry access and global install permissions, then run: npm install --global rea-agents@latest",
|
||||
});
|
||||
expect(host.installs).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("npm installation detection", () => {
|
||||
const host = (root: string, prefix = "/usr/local"): NpmInstallationHost => ({
|
||||
canonicalPath: (path) => Promise.resolve(path),
|
||||
globalRoot: () => Promise.resolve(root),
|
||||
globalPrefix: () => Promise.resolve(prefix),
|
||||
});
|
||||
|
||||
it("returns the prefix for the global package that owns the running CLI", async () => {
|
||||
await expect(
|
||||
detectNpmInstallation(
|
||||
"/usr/local/lib/node_modules/rea-agents",
|
||||
host("/usr/local/lib/node_modules"),
|
||||
),
|
||||
).resolves.toEqual({ prefix: "/usr/local" });
|
||||
});
|
||||
|
||||
it("infers the prefix used by the curl installer's custom npm layout", async () => {
|
||||
await expect(
|
||||
detectNpmInstallation(
|
||||
"/home/user/.local/lib/node_modules/rea-agents",
|
||||
host("/usr/local/lib/node_modules"),
|
||||
),
|
||||
).resolves.toEqual({ prefix: "/home/user/.local" });
|
||||
});
|
||||
|
||||
it("rejects a source checkout when a different global copy exists", async () => {
|
||||
await expect(
|
||||
detectNpmInstallation("/work/rea", host("/usr/local/lib/node_modules")),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,240 +0,0 @@
|
||||
import { execFile, spawn } from "node:child_process";
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { basename, dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { gt, valid } from "semver";
|
||||
import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const registryResponseSchema = z.object({ version: z.string().min(1) });
|
||||
const UPGRADE_COMMAND = "npm install --global rea-agents@latest";
|
||||
const CLI_SCRIPT_PATH = fileURLToPath(
|
||||
new URL("../../scripts/rea.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
/** Location of the global npm installation that owns the running CLI. */
|
||||
export interface NpmInstallation {
|
||||
readonly prefix: string;
|
||||
}
|
||||
|
||||
/** npm filesystem queries used to identify the installation being updated. */
|
||||
export interface NpmInstallationHost {
|
||||
canonicalPath(path: string): Promise<string>;
|
||||
globalRoot(): Promise<string>;
|
||||
globalPrefix(): Promise<string>;
|
||||
}
|
||||
|
||||
/** Output channel policy for the package manager subprocess. */
|
||||
export type UpgradeOutput = "human" | "structured";
|
||||
|
||||
/** Effects required to inspect and update the installed CLI. */
|
||||
export interface UpgradeHost {
|
||||
latestVersion(): Promise<string | undefined>;
|
||||
installation(): Promise<NpmInstallation | undefined>;
|
||||
installLatest(
|
||||
installation: NpmInstallation,
|
||||
output: UpgradeOutput,
|
||||
): Promise<boolean>;
|
||||
syncAgentIntegration(output: UpgradeOutput): Promise<boolean | undefined>;
|
||||
}
|
||||
|
||||
/** Caller-visible outcome of checking and updating the REA CLI. */
|
||||
export type UpgradeResult =
|
||||
| {
|
||||
readonly status: "current";
|
||||
readonly currentVersion: string;
|
||||
readonly latestVersion: string;
|
||||
readonly installMethod: "npm";
|
||||
}
|
||||
| {
|
||||
readonly status: "upgraded";
|
||||
readonly previousVersion: string;
|
||||
readonly latestVersion: string | null;
|
||||
readonly versionCheck: "available" | "unavailable";
|
||||
readonly installMethod: "npm";
|
||||
readonly command: typeof UPGRADE_COMMAND;
|
||||
readonly integrationSync: "setup_invoked" | "deferred" | "failed";
|
||||
readonly clientRestartRequired: true;
|
||||
readonly remediation: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly currentVersion: string;
|
||||
readonly latestVersion: string | null;
|
||||
readonly reason: "unknown-install-method" | "version-check" | "install";
|
||||
readonly remediation: string;
|
||||
};
|
||||
|
||||
/** Check the npm registry and update the same global REA installation. */
|
||||
export const runUpgrade = async (
|
||||
currentVersion: string,
|
||||
host: UpgradeHost = systemUpgradeHost(),
|
||||
output: UpgradeOutput = "human",
|
||||
): Promise<UpgradeResult> => {
|
||||
const latestVersion = await host.latestVersion();
|
||||
const currentIsValid = valid(currentVersion) !== null;
|
||||
const latestIsValid =
|
||||
latestVersion !== undefined && valid(latestVersion) !== null;
|
||||
if (!currentIsValid || !latestIsValid)
|
||||
return {
|
||||
status: "failed",
|
||||
currentVersion,
|
||||
latestVersion: latestVersion ?? null,
|
||||
reason: "version-check",
|
||||
remediation:
|
||||
"REA could not verify a newer registry release. Check npm registry access and version metadata, then rerun rea upgrade.",
|
||||
};
|
||||
|
||||
if (!gt(latestVersion, currentVersion))
|
||||
return {
|
||||
status: "current",
|
||||
currentVersion,
|
||||
latestVersion,
|
||||
installMethod: "npm",
|
||||
};
|
||||
|
||||
const installation = await host.installation();
|
||||
if (installation === undefined)
|
||||
return {
|
||||
status: "failed",
|
||||
currentVersion,
|
||||
latestVersion: latestVersion ?? null,
|
||||
reason: "unknown-install-method",
|
||||
remediation: `Update manually with: ${UPGRADE_COMMAND}`,
|
||||
};
|
||||
|
||||
if (!(await host.installLatest(installation, output)))
|
||||
return {
|
||||
status: "failed",
|
||||
currentVersion,
|
||||
latestVersion: latestVersion ?? null,
|
||||
reason: "install",
|
||||
remediation: `REA could not update through npm. Check npm registry access and global install permissions, then run: ${UPGRADE_COMMAND}`,
|
||||
};
|
||||
|
||||
const integrationSyncResult = await host.syncAgentIntegration(output);
|
||||
const integrationSync =
|
||||
integrationSyncResult === undefined
|
||||
? "deferred"
|
||||
: integrationSyncResult
|
||||
? "setup_invoked"
|
||||
: "failed";
|
||||
return {
|
||||
status: "upgraded",
|
||||
previousVersion: currentVersion,
|
||||
latestVersion,
|
||||
versionCheck: "available",
|
||||
installMethod: "npm",
|
||||
command: UPGRADE_COMMAND,
|
||||
integrationSync,
|
||||
clientRestartRequired: true,
|
||||
remediation:
|
||||
integrationSync === "setup_invoked"
|
||||
? "The updated setup journey was opened to align registrations and the skill. Restart clients whose approved registration changed."
|
||||
: "Run rea setup --all-detected to align registrations and the skill, then restart clients that may retain an older MCP server.",
|
||||
};
|
||||
};
|
||||
|
||||
/** Create the npm registry and subprocess effects for a production upgrade. */
|
||||
export const systemUpgradeHost = (): UpgradeHost => ({
|
||||
latestVersion: async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://registry.npmjs.org/${PRODUCT_IDENTITY.packageName}/latest`,
|
||||
{ signal: AbortSignal.timeout(10_000) },
|
||||
);
|
||||
if (!response.ok) return undefined;
|
||||
const parsed = registryResponseSchema.safeParse(await response.json());
|
||||
return parsed.success ? parsed.data.version : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
installation: () =>
|
||||
detectNpmInstallation(
|
||||
fileURLToPath(new URL("../..", import.meta.url)),
|
||||
systemNpmInstallationHost,
|
||||
),
|
||||
installLatest: ({ prefix }, output) =>
|
||||
runCommand(
|
||||
"npm",
|
||||
[
|
||||
"install",
|
||||
"--global",
|
||||
"--prefix",
|
||||
prefix,
|
||||
`${PRODUCT_IDENTITY.packageName}@latest`,
|
||||
],
|
||||
output,
|
||||
),
|
||||
syncAgentIntegration: (output) =>
|
||||
output === "structured" ||
|
||||
process.stdin.isTTY !== true ||
|
||||
process.stderr.isTTY !== true
|
||||
? Promise.resolve(undefined)
|
||||
: runCommand(
|
||||
process.execPath,
|
||||
[CLI_SCRIPT_PATH, "setup", "--all-detected"],
|
||||
"human",
|
||||
),
|
||||
});
|
||||
|
||||
const systemNpmInstallationHost: NpmInstallationHost = {
|
||||
canonicalPath: realpath,
|
||||
globalRoot: async () =>
|
||||
(await execFileAsync("npm", ["root", "--global"])).stdout.trim(),
|
||||
globalPrefix: async () =>
|
||||
(await execFileAsync("npm", ["prefix", "--global"])).stdout.trim(),
|
||||
};
|
||||
|
||||
/** Identify the npm prefix only when it owns the running package. */
|
||||
export const detectNpmInstallation = async (
|
||||
packageRoot: string,
|
||||
host: NpmInstallationHost,
|
||||
): Promise<NpmInstallation | undefined> => {
|
||||
try {
|
||||
const canonicalPackageRoot = await host.canonicalPath(packageRoot);
|
||||
const npmRoot = await host.globalRoot();
|
||||
const globalPackageRoot = await host.canonicalPath(
|
||||
resolve(npmRoot, PRODUCT_IDENTITY.packageName),
|
||||
);
|
||||
if (canonicalPackageRoot === globalPackageRoot) {
|
||||
const prefix = await host.globalPrefix();
|
||||
return prefix.length === 0 ? undefined : { prefix };
|
||||
}
|
||||
return inferUnixGlobalPrefix(canonicalPackageRoot);
|
||||
} catch {
|
||||
return inferUnixGlobalPrefix(packageRoot);
|
||||
}
|
||||
};
|
||||
|
||||
const inferUnixGlobalPrefix = (
|
||||
packageRoot: string,
|
||||
): NpmInstallation | undefined => {
|
||||
const nodeModules = dirname(packageRoot);
|
||||
const library = dirname(nodeModules);
|
||||
if (
|
||||
basename(packageRoot) !== PRODUCT_IDENTITY.packageName ||
|
||||
basename(nodeModules) !== "node_modules" ||
|
||||
basename(library) !== "lib"
|
||||
)
|
||||
return undefined;
|
||||
return { prefix: dirname(library) };
|
||||
};
|
||||
|
||||
const runCommand = (
|
||||
command: string,
|
||||
arguments_: readonly string[],
|
||||
output: UpgradeOutput,
|
||||
): Promise<boolean> =>
|
||||
new Promise((resolveResult) => {
|
||||
const child = spawn(command, [...arguments_], {
|
||||
stdio: output === "human" ? "inherit" : ["inherit", "ignore", "inherit"],
|
||||
});
|
||||
child.once("error", () => resolveResult(false));
|
||||
child.once("exit", (code) => resolveResult(code === 0));
|
||||
});
|
||||
Reference in New Issue
Block a user