mirror of
https://github.com/morluto/rea.git
synced 2026-12-06 18:23:08 +08:00
* fix(setup): name the analysis tool to add when none is ready When no native analysis tool is ready, setup names the one to add for this operating system and links its guide, and automatic provider selection says so plainly. Its recovery lists only providers this host can run, explains each, asks the agent to get the person's agreement before setting one up, and says what REA can still do without one. Fixes #17292 * fix(providers): explain missing tools and ask before setting them up Each external tool's repair for a missing installation now starts with what the tool is and what setting it up installs, from one domain table, and tells the agent to ask the person before installing it. The no-ready-provider recovery skips providers this host refuses or that refused the target, Kuna reports an unsupported host before its unset command, and IDA's repair carries its description in remediationAction. AGENTS.md notes that agents are the primary users, with a person behind them who may not know what is missing. * fix(android): keep JADX release metadata loadable from source Pre-install fixture scripts import JadxRelease.ts directly, so it stays dependency-free. JadxConfiguration adds the tool description where it reports a missing JAR. * fix(pcap): keep the tool refusal reason in the repair action pcapToolUnavailable had set remediationAction to the shared tshark setup text alone, so the projected action dropped the refusal reason while the message kept only the bare steps. adb and apktool still project both as `${reason}. ${toolSetupRemediation(...)}` through providerConfigurationRefusal. The helper now puts that same combined text in userMessage and leaves remediationAction unset, so the projection copies it into the action. The pcap CLI tests assert the reason, the Wireshark steps, and the tshark setup prefix in both fields. * fix(pcap): carry the tool-setup repair on the refusal itself The recovery guide requires each refusal to carry its remediation; shared projection formats those facts and must not fill them in. pcapToolUnavailable had left remediationAction unset so the action was copied from the message. The helper now sets remediationAction to PCAP_TOOL_REMEDIATION and keeps the reason in userMessage. providerConfigurationRefusal, which adb and apktool use, does the same with the configuration's own repair. CLI tests check the reason and the repair separately. * test(android): expect the tool repair in remediation, not the message
1262 lines
41 KiB
TypeScript
1262 lines
41 KiB
TypeScript
import { createVerifierCommands } from "../../../scripts/lib/verify-commands.mjs";
|
|
import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs";
|
|
import {
|
|
access,
|
|
lstat,
|
|
mkdir,
|
|
readFile,
|
|
readdir,
|
|
rm,
|
|
symlink,
|
|
writeFile,
|
|
} from "node:fs/promises";
|
|
import { dirname, join, resolve } from "node:path";
|
|
import { spawn } from "@lydell/node-pty";
|
|
import { describe, expect, it, onTestFinished } from "vitest";
|
|
import { z } from "zod";
|
|
import { parse as parseToml } from "smol-toml";
|
|
|
|
import { manualRegistrationRemediation } from "../../../src/application/SupportedClients.js";
|
|
import type {
|
|
SetupClientState,
|
|
SetupResult,
|
|
} from "../../../src/application/SetupTypes.js";
|
|
import { supportedClientRegistrationProfile } from "../../fixtures/clientRegistrationProfile.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
|
|
|
|
const execute = async (
|
|
command: string,
|
|
arguments_: readonly string[],
|
|
options: { readonly cwd: string; readonly env: NodeJS.ProcessEnv },
|
|
) => {
|
|
const commands = await createVerifierCommands();
|
|
onTestFinished(() => commands.close());
|
|
return withVerifierCleanup(
|
|
() => commands.exec(command, arguments_, { ...options, timeout: 15_000 }),
|
|
[() => commands.close()],
|
|
);
|
|
};
|
|
const decisionMarker = "REA_SETUP_DECISION:";
|
|
const isolatedSetupEnvironment = (home: string) => ({
|
|
HOME: home,
|
|
USERPROFILE: home,
|
|
CODEX_HOME: join(home, ".codex"),
|
|
XDG_CONFIG_HOME: join(home, ".config"),
|
|
XDG_DATA_HOME: join(home, ".local", "share"),
|
|
XDG_CACHE_HOME: join(home, ".cache"),
|
|
});
|
|
const runSetup = (cli: TestCli, home: string, dryRun: string) =>
|
|
cli.run({
|
|
arguments: [
|
|
"setup",
|
|
"--yes",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
dryRun,
|
|
"--format",
|
|
"json",
|
|
],
|
|
cwd: home,
|
|
environment: isolatedSetupEnvironment(home),
|
|
});
|
|
const decisionSchema = z.object({
|
|
approved: z.boolean(),
|
|
selectedActionIds: z.array(z.string()),
|
|
cancelled: z.boolean().optional(),
|
|
});
|
|
|
|
const actions = [
|
|
{
|
|
id: "configure_client:codex",
|
|
kind: "configure_client",
|
|
label: "Codex",
|
|
target: "/isolated/.codex/config.toml",
|
|
detail: "Add the REA MCP registration for Codex.",
|
|
external: false,
|
|
operation: "create",
|
|
},
|
|
{
|
|
id: "install_skill",
|
|
kind: "install_skill",
|
|
label: "REA reverse-engineering skill",
|
|
target: "/isolated/.agents/skills/reverse-engineering/SKILL.md",
|
|
detail: "Install the bundled reverse-engineering skill.",
|
|
external: false,
|
|
operation: "install",
|
|
},
|
|
{
|
|
id: "install_hopper",
|
|
kind: "install_hopper",
|
|
label: "Hopper deep-analysis provider",
|
|
target: "/isolated/Applications/Hopper Disassembler.app",
|
|
detail: "Install the verified Hopper package.",
|
|
external: true,
|
|
operation: "install",
|
|
},
|
|
] as const;
|
|
|
|
const clientStates = [
|
|
{
|
|
client: {
|
|
name: "codex",
|
|
registrationProfile: supportedClientRegistrationProfile("codex"),
|
|
format: "toml",
|
|
configPath: join(".codex", "config.toml"),
|
|
markerPath: ".codex",
|
|
},
|
|
detected: true,
|
|
configured: false,
|
|
status: "needs_configuration",
|
|
},
|
|
{
|
|
client: {
|
|
name: "opencode",
|
|
registrationProfile: supportedClientRegistrationProfile("opencode"),
|
|
format: "opencode",
|
|
configPath: join(".config", "opencode", "opencode.json"),
|
|
markerPath: join(".config", "opencode"),
|
|
},
|
|
detected: false,
|
|
configured: false,
|
|
status: "missing",
|
|
},
|
|
] as const satisfies readonly SetupClientState[];
|
|
|
|
const agentActions = actions.filter(({ kind }) => kind !== "install_hopper");
|
|
|
|
cliTest.for(["--dry-run=abc", "--dry-run=", "--dry-run=ab\ncd"] as const)(
|
|
"rejects malformed setup dry-run value %s before approved changes are written",
|
|
async (dryRun, { cli }) => {
|
|
const home = await createTestTempDirectory("rea-cli-invalid-dry-run-");
|
|
const config = join(home, ".codex", "config.toml");
|
|
const result = await runSetup(cli, home, dryRun);
|
|
|
|
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(result.exitCode).not.toBe(0);
|
|
expect(result.json).toMatchObject({
|
|
code: "PARSE_ERROR",
|
|
message: "Invalid --dry-run value; use true or false.",
|
|
});
|
|
expect(`${result.stdout}\n${result.stderr}`).not.toMatch(/^ +at /mu);
|
|
},
|
|
);
|
|
|
|
cliTest.for(["--dry-run=true", "--dry-run=false"] as const)(
|
|
"accepts explicit setup dry-run value %s",
|
|
async (dryRun, { cli }) => {
|
|
const home = await createTestTempDirectory("rea-cli-explicit-dry-run-");
|
|
const config = join(home, ".codex", "config.toml");
|
|
const result = await runSetup(cli, home, dryRun);
|
|
|
|
expect(result.exitCode, result.stderr).toBe(0);
|
|
if (dryRun === "--dry-run=true") {
|
|
expect(result.json).toMatchObject({ status: "planned" });
|
|
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
|
|
} else {
|
|
expect(result.json).toMatchObject({ status: "ready" });
|
|
await expect(access(config)).resolves.toBeUndefined();
|
|
}
|
|
},
|
|
);
|
|
|
|
cliTest(
|
|
"shows setup help even when a malformed dry-run value is present",
|
|
async ({ cli }) => {
|
|
const home = await createTestTempDirectory("rea-cli-help-invalid-dry-run-");
|
|
const config = join(home, ".codex", "config.toml");
|
|
const result = await cli.run({
|
|
arguments: ["setup", "--dry-run=abc", "--help"],
|
|
cwd: home,
|
|
environment: isolatedSetupEnvironment(home),
|
|
});
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.stdout).toContain("Usage: rea setup");
|
|
expect(result.stdout).not.toContain("Invalid --dry-run value");
|
|
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
|
|
},
|
|
);
|
|
|
|
cliTest(
|
|
"rejects an overridden malformed dry-run before changing existing Codex configuration",
|
|
async ({ cli }) => {
|
|
const selectedHome = await createTestTempDirectory(
|
|
"rea-cli-existing-dry-run-",
|
|
);
|
|
const config = join(selectedHome, ".codex", "config.toml");
|
|
const original = 'model = "retained-evidence"\n';
|
|
await mkdir(dirname(config), { recursive: true });
|
|
await writeFile(config, original);
|
|
const before = await lstat(config);
|
|
const result = await cli.run({
|
|
arguments: [
|
|
"setup",
|
|
"--yes",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
"--dry-run=abc",
|
|
"--dry-run=false",
|
|
"--json",
|
|
],
|
|
cwd: selectedHome,
|
|
environment: isolatedSetupEnvironment(selectedHome),
|
|
});
|
|
expect(result.exitCode, result.stderr).toBe(1);
|
|
expect(result.json).toMatchObject({
|
|
code: "PARSE_ERROR",
|
|
message: "Invalid --dry-run value; use true or false.",
|
|
});
|
|
expect(await readFile(config, "utf8")).toBe(original);
|
|
expect((await lstat(config)).mtimeMs).toBe(before.mtimeMs);
|
|
expect(await readdir(dirname(config))).toEqual(["config.toml"]);
|
|
},
|
|
);
|
|
|
|
/**
|
|
* Approval asks about one change, or names the count when the host can also
|
|
* install Hopper. Either question is the consent prompt.
|
|
*/
|
|
const setupApprovalQuestion = /Apply this change\?|Apply these \d+ changes\?/u;
|
|
|
|
const runSetupInTty = async (
|
|
home: string,
|
|
arguments_: readonly string[],
|
|
approval?: boolean,
|
|
environment: NodeJS.ProcessEnv = {},
|
|
{ terminalStdin = true }: { readonly terminalStdin?: boolean } = {},
|
|
): Promise<{ readonly exitCode: number; readonly output: string }> => {
|
|
// Without a terminal stdin, only stdout and stderr stay on the terminal.
|
|
const command = terminalStdin
|
|
? { file: process.execPath, args: ["scripts/rea.mjs", "setup"] }
|
|
: {
|
|
file: "/bin/sh",
|
|
args: [
|
|
"-c",
|
|
'exec "$0" scripts/rea.mjs setup "$@" < /dev/null',
|
|
process.execPath,
|
|
],
|
|
};
|
|
const terminal = spawn(command.file, [...command.args, ...arguments_], {
|
|
cwd: process.cwd(),
|
|
// Client locations such as CODEX_HOME must follow the temporary home.
|
|
env: {
|
|
...process.env,
|
|
...isolatedSetupEnvironment(home),
|
|
REA_LOG_LEVEL: "silent",
|
|
NO_COLOR: "1",
|
|
...environment,
|
|
},
|
|
name: "xterm-256color",
|
|
cols: 120,
|
|
rows: 40,
|
|
});
|
|
let output = "";
|
|
let answered = false;
|
|
terminal.onData((data) => {
|
|
output += data;
|
|
if (
|
|
approval !== undefined &&
|
|
!answered &&
|
|
setupApprovalQuestion.test(output)
|
|
) {
|
|
answered = true;
|
|
terminal.write(approval ? "\r" : "\u001b[C\r");
|
|
}
|
|
});
|
|
const exitCode = await new Promise<number>((resolvePromise, reject) => {
|
|
const timeout = setTimeout(() => {
|
|
terminal.kill();
|
|
reject(new Error(`TTY setup timed out after output:\n${output}`));
|
|
}, 15_000);
|
|
terminal.onExit(({ exitCode: code }) => {
|
|
clearTimeout(timeout);
|
|
resolvePromise(code);
|
|
});
|
|
});
|
|
return { exitCode, output };
|
|
};
|
|
|
|
const manualConnectorFixture = async (): Promise<{
|
|
readonly home: string;
|
|
readonly environment: NodeJS.ProcessEnv;
|
|
}> => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-manual-");
|
|
const bin = join(home, "bin");
|
|
await mkdir(bin);
|
|
const hopper = join(bin, "hopper");
|
|
await writeFile(hopper, "#!/bin/sh\necho 'Hopper Disassembler v6.0.0'\n", {
|
|
mode: 0o755,
|
|
});
|
|
// Linux's executable probe runs ldd before accepting this inert launcher.
|
|
await writeFile(join(bin, "ldd"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
|
|
for (const runner of ["npx", "npm", "bun"])
|
|
await writeFile(join(bin, runner), "#!/bin/sh\nexit 99\n", {
|
|
mode: 0o755,
|
|
});
|
|
return {
|
|
home,
|
|
environment: {
|
|
PATH: `${bin}:${process.env.PATH ?? ""}`,
|
|
HOPPER_LAUNCHER_PATH: hopper,
|
|
DSH_HOME: join(home, ".dsh"),
|
|
DSH_AGENTS_HOME: join(home, ".dsh-agents"),
|
|
XDG_DATA_HOME: join(home, ".local/share"),
|
|
XDG_CACHE_HOME: join(home, ".cache"),
|
|
XDG_STATE_HOME: join(home, ".local/state"),
|
|
},
|
|
};
|
|
};
|
|
|
|
describe("manual connector approval", () => {
|
|
it.skipIf(process.platform === "win32").each([true, false])(
|
|
"discloses the manual step before approval (apply: %s)",
|
|
async (approved) => {
|
|
const { home, environment } = await manualConnectorFixture();
|
|
const { output, exitCode } = await runSetupInTty(
|
|
home,
|
|
["--client", "grok_bot"],
|
|
approved,
|
|
environment,
|
|
);
|
|
const prompt = output.indexOf("Apply this change?");
|
|
const remediation = manualRegistrationRemediation("grok_bot");
|
|
expect(remediation).toBeDefined();
|
|
expect(prompt, output).toBeGreaterThan(0);
|
|
expect(output.slice(0, prompt)).toContain(remediation);
|
|
const skill = join(
|
|
home,
|
|
".agents/skills/reverse-engineer-anything/SKILL.md",
|
|
);
|
|
if (approved) {
|
|
expect(exitCode, output).toBe(1);
|
|
expect(await readFile(skill, "utf8")).not.toBe("");
|
|
} else {
|
|
expect(exitCode, output).toBe(0);
|
|
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
|
|
}
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"shows the manual step in a TTY dry run",
|
|
async () => {
|
|
const { home, environment } = await manualConnectorFixture();
|
|
const { output, exitCode } = await runSetupInTty(
|
|
home,
|
|
["--dry-run", "--client", "grok_bot"],
|
|
undefined,
|
|
environment,
|
|
);
|
|
const remediation = manualRegistrationRemediation("grok_bot");
|
|
expect(remediation).toBeDefined();
|
|
expect(exitCode, output).toBe(0);
|
|
expect(output).toContain(remediation);
|
|
expect(output).toContain("Dry run complete. No changes were made.");
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("TTY setup dry run", () => {
|
|
it("prints the plan and no-mutation notice for a TTY dry run", async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-dry-run-");
|
|
const { exitCode, output } = await runSetupInTty(home, [
|
|
"--dry-run",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
]);
|
|
|
|
expect(exitCode, output).toBe(0);
|
|
expect(output).toContain("Connect REA to Codex");
|
|
expect(output).toContain(join(home, ".codex/config.toml"));
|
|
expect(output).toContain("Dry run complete. No changes were made.");
|
|
await expect(
|
|
access(join(home, ".codex/config.toml")),
|
|
).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
});
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"shows the unapproved plan it asks a terminal reader to review",
|
|
async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-unapproved-");
|
|
const { exitCode, output } = await runSetupInTty(
|
|
home,
|
|
["--client", "codex", "--skill=false"],
|
|
undefined,
|
|
{},
|
|
{ terminalStdin: false },
|
|
);
|
|
|
|
expect(output).toContain(
|
|
"Review the setup plan, then rerun interactively or with --yes.",
|
|
);
|
|
expect(output).toContain("Connect REA to Codex");
|
|
expect(output).toContain(join(home, ".codex/config.toml"));
|
|
expect(output).toContain("No changes were made.");
|
|
expect(exitCode, output).not.toBe(0);
|
|
await expect(
|
|
access(join(home, ".codex/config.toml")),
|
|
).rejects.toMatchObject({ code: "ENOENT" });
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
{ flag: "--full-output", document: /plannedActions/u },
|
|
{ flag: "--token-count", document: /^\d+$/u },
|
|
])(
|
|
"writes only the requested document for a TTY dry run with $flag",
|
|
async ({ flag, document }) => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-document-");
|
|
const { exitCode, output } = await runSetupInTty(home, [
|
|
"--dry-run",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
flag,
|
|
]);
|
|
|
|
expect(exitCode, output).toBe(0);
|
|
expect(output.trim()).toMatch(document);
|
|
expect(output).not.toContain("Dry run complete. No changes were made.");
|
|
},
|
|
);
|
|
|
|
it("opens the setup rail once when a scoped run starts at approval", async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-scoped-");
|
|
const { output } = await runSetupInTty(
|
|
home,
|
|
["--client", "codex", "--skill=false"],
|
|
false,
|
|
);
|
|
|
|
const prompt = output.search(setupApprovalQuestion);
|
|
expect(prompt, output).toBeGreaterThanOrEqual(0);
|
|
const beforePrompt = output.slice(0, prompt);
|
|
expect(beforePrompt.split("REA setup").length - 1, output).toBe(1);
|
|
});
|
|
|
|
it("prints the applied result for a non-interactive TTY setup", async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-yes-");
|
|
const { exitCode, output } = await runSetupInTty(home, [
|
|
"--yes",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
]);
|
|
|
|
expect(exitCode, output).toBe(0);
|
|
expect(output).toContain(
|
|
"Next: Restart Codex to load REA, then ask it to use REA.",
|
|
);
|
|
await expect(
|
|
access(join(home, ".codex/config.toml")),
|
|
).resolves.toBeUndefined();
|
|
});
|
|
|
|
it("shows the refusal instead of a blocked skill plan for a TTY dry run", async () => {
|
|
const home = await createTestTempDirectory("rea-cli-setup-linked-dry-run-");
|
|
const managed = join(home, "managed-skill");
|
|
const linked = join(home, ".claude/skills/reverse-engineer-anything");
|
|
const original = "user-managed skill bytes\n";
|
|
await mkdir(managed);
|
|
await writeFile(join(managed, "SKILL.md"), original);
|
|
await mkdir(dirname(linked), { recursive: true });
|
|
await symlink(
|
|
managed,
|
|
linked,
|
|
process.platform === "win32" ? "junction" : "dir",
|
|
);
|
|
|
|
const { exitCode, output } = await runSetupInTty(home, [
|
|
"--dry-run",
|
|
"--client",
|
|
"claude_code",
|
|
]);
|
|
|
|
expect(exitCode, output).toBe(1);
|
|
expect(output).toContain("Skill directory is a symbolic link.");
|
|
expect(output).toContain(linked);
|
|
expect(output).toContain("--skill=false");
|
|
expect(output).not.toContain("REA setup plan");
|
|
expect(output).not.toContain("Install or update the REA skill");
|
|
expect((await lstat(linked)).isSymbolicLink()).toBe(true);
|
|
expect(await readFile(join(managed, "SKILL.md"), "utf8")).toBe(original);
|
|
expect(await readdir(managed)).toEqual(["SKILL.md"]);
|
|
await expect(access(join(home, ".claude.json"))).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
});
|
|
});
|
|
|
|
cliTest.skipIf(process.platform === "win32")(
|
|
"repairs a Codex timeout without replacing an equivalent caller-selected launcher",
|
|
async ({ cli }) => {
|
|
const home = await createTestTempDirectory("rea-codex-alias-repair-");
|
|
const codexHome = join(home, ".codex");
|
|
const config = join(codexHome, "config.toml");
|
|
const backup = `${config}.rea.backup`;
|
|
const alias = join(home, "rea-launcher-alias.mjs");
|
|
await mkdir(codexHome);
|
|
await symlink(resolve("scripts/rea.mjs"), alias, "file");
|
|
const original = [
|
|
"# Caller-owned Codex approval policy",
|
|
'approval_policy = "on-request"',
|
|
'sandbox_mode = "read-only"',
|
|
"",
|
|
"[mcp_servers.rea]",
|
|
`command = ${JSON.stringify(process.execPath)}`,
|
|
`args = ${JSON.stringify([alias, "mcp"])}`,
|
|
"startup_timeout_sec = 0",
|
|
"tool_timeout_sec = 900",
|
|
'default_tools_approval_mode = "prompt"',
|
|
"",
|
|
"[mcp_servers.rea.tools.open_binary]",
|
|
'approval_mode = "approve"',
|
|
"output_token_limit = 2048",
|
|
"",
|
|
].join("\n");
|
|
await writeFile(config, original);
|
|
const setup = (approval: "--dry-run" | "--yes") =>
|
|
cli.run({
|
|
arguments: [
|
|
"setup",
|
|
"--client",
|
|
"codex",
|
|
"--no-skill",
|
|
approval,
|
|
"--json",
|
|
],
|
|
cwd: home,
|
|
environment: {
|
|
HOME: home,
|
|
USERPROFILE: home,
|
|
CODEX_HOME: codexHome,
|
|
XDG_CONFIG_HOME: join(home, ".config"),
|
|
XDG_DATA_HOME: join(home, ".local", "share"),
|
|
XDG_CACHE_HOME: join(home, ".cache"),
|
|
},
|
|
});
|
|
|
|
const planned = await setup("--dry-run");
|
|
expect(planned.exitCode, planned.stderr).toBe(0);
|
|
expect(planned.json).toMatchObject({
|
|
status: "planned",
|
|
plannedActions: [
|
|
expect.objectContaining({
|
|
id: "configure_client:codex",
|
|
operation: "update",
|
|
target: config,
|
|
backupPath: backup,
|
|
}),
|
|
],
|
|
});
|
|
expect(await readFile(config, "utf8")).toBe(original);
|
|
await expect(access(backup)).rejects.toMatchObject({ code: "ENOENT" });
|
|
|
|
const applied = await setup("--yes");
|
|
expect(applied.exitCode, applied.stderr).toBe(0);
|
|
expect(applied.json).toMatchObject({ status: "ready" });
|
|
const repaired = await readFile(config, "utf8");
|
|
expect(parseToml(repaired)).toMatchObject({
|
|
approval_policy: "on-request",
|
|
sandbox_mode: "read-only",
|
|
mcp_servers: {
|
|
rea: {
|
|
command: process.execPath,
|
|
args: [alias, "mcp"],
|
|
startup_timeout_sec: 30,
|
|
tool_timeout_sec: 900,
|
|
default_tools_approval_mode: "prompt",
|
|
tools: {
|
|
open_binary: { approval_mode: "approve", output_token_limit: 2048 },
|
|
},
|
|
},
|
|
},
|
|
});
|
|
expect(await readFile(backup, "utf8")).toBe(original);
|
|
expect((await lstat(alias)).isSymbolicLink()).toBe(true);
|
|
|
|
const repeated = await setup("--yes");
|
|
expect(repeated.exitCode, repeated.stderr).toBe(0);
|
|
expect(repeated.json).toMatchObject({
|
|
status: "ready",
|
|
plannedActions: [],
|
|
appliedActions: [],
|
|
});
|
|
expect(await readFile(config, "utf8")).toBe(repaired);
|
|
expect(await readFile(backup, "utf8")).toBe(original);
|
|
},
|
|
);
|
|
|
|
describe("interactive setup journey", () => {
|
|
it("shows detected and absent clients", async () => {
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", "\u001b[B"),
|
|
step("Not detected · configuration is still available", "\r"),
|
|
step(noAgentQuestion, "\u001b[D\r"),
|
|
],
|
|
false,
|
|
[actions[0]],
|
|
);
|
|
expect(result.output).toContain("Detected: Codex");
|
|
expect(result.output).toContain(
|
|
"Not detected · configuration is still available",
|
|
);
|
|
expect(result.output).toContain("Which agents should use REA?");
|
|
expect(result.output).not.toContain("What should REA set up?");
|
|
expect(result.decision.selectedActionIds).toEqual([]);
|
|
});
|
|
|
|
it("selects an absent OpenCode client and bundles its skill", async () => {
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", "\u001b[B \r"),
|
|
step("Apply these 2 changes?", "\r"),
|
|
],
|
|
false,
|
|
[
|
|
{
|
|
...actions[0],
|
|
id: "configure_client:opencode",
|
|
label: "OpenCode",
|
|
target: "/isolated/.config/opencode/opencode.json",
|
|
},
|
|
actions[1],
|
|
],
|
|
);
|
|
expect(result.output).toContain("Connect REA to OpenCode");
|
|
expect(result.decision.selectedActionIds).toEqual([
|
|
"configure_client:opencode",
|
|
"install_skill",
|
|
]);
|
|
expect(result.decision.approved).toBe(true);
|
|
});
|
|
|
|
it("shows the selected changes before consent and leaves Hopper unselected", async () => {
|
|
const approvalPrompt = "Apply these 2 changes?";
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", " \r"),
|
|
step("Install Hopper for deep binary analysis?", "\r"),
|
|
step(approvalPrompt, "\r"),
|
|
],
|
|
false,
|
|
[
|
|
{
|
|
...actions[0],
|
|
operation: "update",
|
|
backupPath: "/isolated/.codex/config.toml.bak",
|
|
commands: ["npx -y rea-agents@3.2.1 mcp"],
|
|
},
|
|
actions[1],
|
|
actions[2],
|
|
],
|
|
);
|
|
const preflight = result.output.split(approvalPrompt, 1)[0];
|
|
expect(preflight).toContain("Connect REA to Codex");
|
|
expect(preflight).toContain(
|
|
"Changes /isolated/.codex/config.toml (a backup is kept at /isolated/.codex/config.toml.bak)",
|
|
);
|
|
expect(preflight).toContain("Runs: npx -y rea-agents@3.2.1 mcp");
|
|
expect(preflight).toContain("Add REA's guide for your AI agents");
|
|
expect(preflight).not.toContain(actions[0].detail);
|
|
expect(preflight).not.toContain("Install Hopper, a tool");
|
|
expect(result.decision).toEqual({
|
|
approved: true,
|
|
selectedActionIds: ["configure_client:codex", "install_skill"],
|
|
});
|
|
});
|
|
|
|
it("shows where external software comes from without its integrity detail", async () => {
|
|
const approvalPrompt = "Apply these 3 changes?";
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", " \r"),
|
|
step("Install Hopper for deep binary analysis?", "\u001b[D\r"),
|
|
step(approvalPrompt, "\r"),
|
|
],
|
|
false,
|
|
[
|
|
actions[0],
|
|
actions[1],
|
|
{
|
|
...actions[2],
|
|
networkOrigins: ["https://www.hopperapp.com"],
|
|
commands: [
|
|
"/usr/sbin/installer -pkg Hopper.pkg -target CurrentUserHomeDirectory",
|
|
],
|
|
integrity: "sha256:0123456789abcdef",
|
|
},
|
|
],
|
|
);
|
|
const preflight = result.output.split(approvalPrompt, 1)[0];
|
|
expect(preflight).toContain(
|
|
"Install Hopper, a tool for analyzing compiled programs",
|
|
);
|
|
expect(preflight).toContain(
|
|
"Adds or updates /isolated/Applications/Hopper Disassembler.app",
|
|
);
|
|
expect(preflight).toContain("Downloads from: https://www.hopperapp.com");
|
|
expect(preflight).toContain(
|
|
"Runs: /usr/sbin/installer -pkg Hopper.pkg -target CurrentUserHomeDirectory",
|
|
);
|
|
expect(preflight).not.toContain("sha256:0123456789abcdef");
|
|
expect(preflight).not.toContain(actions[2].detail);
|
|
expect(result.decision.selectedActionIds).toContain("install_hopper");
|
|
});
|
|
|
|
it("treats final No as cancellation", async () => {
|
|
const result = await runJourney([
|
|
step("Which agents should use REA?", " \r"),
|
|
step("Apply these 2 changes?", "\u001b[D\r"),
|
|
]);
|
|
expect(result.output).toContain("Setup cancelled. No changes were made.");
|
|
expect(result.decision.cancelled).toBe(true);
|
|
expect(result.decision.approved).toBe(false);
|
|
});
|
|
|
|
it("restores the terminal after Ctrl-C during selection", async () => {
|
|
const result = await runJourney([
|
|
step("Which agents should use REA?", "\u0003"),
|
|
]);
|
|
expect(result.output).toContain("\u001b[?25h");
|
|
expect(result.decision.cancelled).toBe(true);
|
|
});
|
|
|
|
it("returns to the agent list when an empty choice is not confirmed", async () => {
|
|
const result = await runJourney([
|
|
step("Which agents should use REA?", "\r"),
|
|
step(noAgentQuestion, "\r"),
|
|
step("Which agents should use REA?", " \r"),
|
|
step("Apply these 2 changes?", "\r"),
|
|
]);
|
|
expect(result.decision.selectedActionIds).toEqual([
|
|
"configure_client:codex",
|
|
"install_skill",
|
|
]);
|
|
});
|
|
|
|
it("can install the skill for CLI use without an agent registration", async () => {
|
|
const result = await runJourney([
|
|
step("Which agents should use REA?", "\r"),
|
|
step(noAgentQuestion, "\u001b[D\r"),
|
|
step(
|
|
"Add REA's guide for AI agents that run REA from the terminal?",
|
|
"\u001b[D\r",
|
|
),
|
|
step("Apply this change?", "\r"),
|
|
]);
|
|
expect(result.decision.selectedActionIds).toEqual(["install_skill"]);
|
|
expect(result.decision.approved).toBe(true);
|
|
});
|
|
|
|
it("uses sequential prompts in accessible mode", async () => {
|
|
const result = await runJourney(
|
|
[
|
|
step("Configure Codex?", "\r"),
|
|
step("Configure OpenCode?", "\u001b[A\r"),
|
|
step("Apply this change?", "\r"),
|
|
],
|
|
true,
|
|
[{ ...actions[0], id: "configure_client:opencode", label: "OpenCode" }],
|
|
);
|
|
expect(result.decision.selectedActionIds).toEqual([
|
|
"configure_client:opencode",
|
|
]);
|
|
});
|
|
|
|
it("starts from the clients setup preselects", async () => {
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", "\r"),
|
|
step("Apply these 2 changes?", "\r"),
|
|
],
|
|
false,
|
|
agentActions,
|
|
{ initialClientIds: ["codex"] },
|
|
);
|
|
expect(result.decision.selectedActionIds).toEqual([
|
|
"configure_client:codex",
|
|
"install_skill",
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe("interactive setup client hints", () => {
|
|
const manual =
|
|
"Found migrated Claude Desktop storage. Register REA manually in the active file.";
|
|
const repairOverride =
|
|
"Invalid PI_CODING_AGENT_DIR: encoded slash. Repair the override before configuring Pi.";
|
|
const repairConfiguration =
|
|
"Existing configuration needs repair before setup";
|
|
it.for([
|
|
{
|
|
name: "claude_desktop",
|
|
format: "json",
|
|
status: "unknown",
|
|
configPathError: manual,
|
|
expected: manual,
|
|
},
|
|
{
|
|
name: "claude_desktop",
|
|
format: "json",
|
|
status: "invalid",
|
|
configPathError: manual,
|
|
expected: manual,
|
|
},
|
|
{
|
|
name: "pi",
|
|
format: "pi",
|
|
status: "unknown",
|
|
configPathError: repairOverride,
|
|
expected: repairOverride,
|
|
},
|
|
{
|
|
name: "codex",
|
|
format: "toml",
|
|
status: "invalid",
|
|
configPathError: undefined,
|
|
expected: repairConfiguration,
|
|
},
|
|
{
|
|
name: "codex",
|
|
format: "toml",
|
|
status: "foreign",
|
|
configPathError: undefined,
|
|
expected:
|
|
"Another program uses the name rea here · rename or remove it first",
|
|
},
|
|
] as const)(
|
|
"shows the recovery for $name when setup reports $status",
|
|
async ({ name, format, status, configPathError, expected }) => {
|
|
const state: SetupClientState = {
|
|
client: {
|
|
name,
|
|
registrationProfile: supportedClientRegistrationProfile(name),
|
|
format,
|
|
configPath: join(name, "config"),
|
|
...(configPathError === undefined ? {} : { configPathError }),
|
|
},
|
|
detected: true,
|
|
configured: false,
|
|
status,
|
|
};
|
|
const result = await runJourney(
|
|
[
|
|
step("Which agents should use REA?", "\r"),
|
|
step(noAgentQuestion, "\u001b[D\r"),
|
|
],
|
|
false,
|
|
[actions[0]],
|
|
{ states: [state, clientStates[1]] },
|
|
);
|
|
expect(result.output).toContain(expected);
|
|
expect(result.decision.selectedActionIds).toEqual([]);
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("setup review", () => {
|
|
it("shows a client's prerequisite and names what each action does", async () => {
|
|
const plan = [
|
|
{
|
|
id: "configure_client:claude_desktop",
|
|
kind: "configure_client",
|
|
label: "Claude Desktop",
|
|
target: "/isolated/claude_desktop_config.json",
|
|
detail: "Add the REA MCP registration for Claude Desktop.",
|
|
external: false,
|
|
operation: "update",
|
|
prerequisite:
|
|
"Quit Claude Desktop fully before you approve (closing its window isn't enough), then start it again after setup.",
|
|
},
|
|
{ ...actions[1] },
|
|
{
|
|
id: "pack_build_runtime",
|
|
kind: "pack_build_runtime",
|
|
label: "REA build-computer runtime",
|
|
target: "/isolated/rea-runtime.tar.xz",
|
|
detail: "Pack this REA checkout.",
|
|
external: true,
|
|
operation: "create",
|
|
commands: ["npm run pack:build-computer-runtime"],
|
|
},
|
|
];
|
|
const { stderr } = await execute(
|
|
process.execPath,
|
|
[
|
|
"--input-type=module",
|
|
"--eval",
|
|
'import { renderSetupPlan } from "./dist/cli/interactiveSetup.js";\n' +
|
|
`renderSetupPlan(${JSON.stringify(plan)}, undefined, "Dry run complete.");`,
|
|
],
|
|
{ cwd: process.cwd(), env: { ...process.env, NO_COLOR: "1" } },
|
|
);
|
|
|
|
const lines = stderr.split(/\r?\n/u).map((line) => line.trim());
|
|
const desktop = lines.indexOf("│ Connect REA to Claude Desktop");
|
|
expect(lines.slice(desktop + 1, desktop + 3)).toEqual([
|
|
"│ Before you approve: Quit Claude Desktop fully before you approve (closing its window isn't enough), then start it again after setup.",
|
|
"│ Changes /isolated/claude_desktop_config.json",
|
|
]);
|
|
expect(stderr).toContain(`Adds or updates ${actions[1].target}`);
|
|
expect(stderr).toContain("Create REA's build-computer archive");
|
|
expect(stderr).toContain("Adds /isolated/rea-runtime.tar.xz");
|
|
expect(stderr).not.toContain("Install REA build-computer runtime");
|
|
});
|
|
});
|
|
|
|
describe("interactive setup completion", () => {
|
|
const renderReady = (
|
|
clients: Record<string, { status: string }>,
|
|
registrations: readonly { client: string; state: string }[],
|
|
environment: Readonly<Record<string, string>> = {},
|
|
host: {
|
|
readonly providers: readonly string[];
|
|
readonly platform: NodeJS.Platform;
|
|
} = { providers: ["hopper", "ghidra"], platform: "linux" },
|
|
) =>
|
|
execute(
|
|
process.execPath,
|
|
[
|
|
"--input-type=module",
|
|
"--eval",
|
|
[
|
|
'import { renderInteractiveSetupResult } from "./dist/cli/interactiveSetup.js";',
|
|
'import { setupNextStep } from "./dist/application/SetupNextStep.js";',
|
|
`const result = ${JSON.stringify({
|
|
status: "ready",
|
|
plannedActions: [],
|
|
appliedActions: [],
|
|
clients,
|
|
doctor: {
|
|
healthy: true,
|
|
availableProviders: host.providers,
|
|
checks: [],
|
|
identity: { skill: { state: "aligned" }, registrations },
|
|
},
|
|
})};`,
|
|
`renderInteractiveSetupResult({ ...result, nextStep: setupNextStep(result.clients, result.doctor, ${JSON.stringify(host.platform)}) });`,
|
|
].join("\n"),
|
|
],
|
|
{
|
|
cwd: process.cwd(),
|
|
env: {
|
|
...Object.fromEntries(
|
|
Object.entries(process.env).filter(
|
|
([key]) =>
|
|
!["npm_command", "npm_config_user_agent"].includes(
|
|
key.toLowerCase(),
|
|
),
|
|
),
|
|
),
|
|
...environment,
|
|
NO_COLOR: "1",
|
|
},
|
|
},
|
|
);
|
|
|
|
it("tells a person to restart a changed agent and what to ask it", async () => {
|
|
const { stderr } = await renderReady({ codex: { status: "configured" } }, [
|
|
{ client: "codex", state: "aligned" },
|
|
]);
|
|
|
|
expect(stderr).toContain("Agents that can use REA: Codex");
|
|
expect(stderr).toContain("Deep analysis: Hopper and Ghidra");
|
|
expect(stderr).toContain(
|
|
'"Use REA to find out how [a feature] works in [an app on this computer]."',
|
|
);
|
|
expect(stderr).toContain(
|
|
"Next: Restart Codex to load REA, then ask it to use REA.",
|
|
);
|
|
});
|
|
|
|
it("names a native analysis tool for this operating system only when none is ready", async () => {
|
|
const connected = [{ client: "codex", state: "aligned" }];
|
|
const windows = await renderReady(
|
|
{},
|
|
connected,
|
|
{},
|
|
{
|
|
providers: ["jadx"],
|
|
platform: "win32",
|
|
},
|
|
);
|
|
expect(windows.stderr).toContain(
|
|
"To look inside programs such as .exe files, add Ghidra, a free tool that turns compiled programs into readable code: rea.tools/get-started/#ghidra. You can ask your agent to set it up.",
|
|
);
|
|
expect(windows.stderr).not.toContain("Hopper");
|
|
|
|
const mac = await renderReady(
|
|
{},
|
|
connected,
|
|
{},
|
|
{
|
|
providers: [],
|
|
platform: "darwin",
|
|
},
|
|
);
|
|
expect(mac.stderr).toContain(
|
|
"add Hopper (its free demo mode works with REA) or Ghidra: rea.tools/get-started/#native.",
|
|
);
|
|
|
|
const ready = await renderReady(
|
|
{},
|
|
connected,
|
|
{},
|
|
{
|
|
providers: ["ghidra"],
|
|
platform: "win32",
|
|
},
|
|
);
|
|
expect(ready.stderr).not.toContain("rea.tools/get-started");
|
|
});
|
|
|
|
it("tells a person to open an agent that was already connected", async () => {
|
|
const { stderr } = await renderReady({}, [
|
|
{ client: "codex", state: "aligned" },
|
|
]);
|
|
|
|
expect(stderr).toContain("Next: Open Codex and ask it to use REA.");
|
|
expect(stderr).not.toContain("restart");
|
|
});
|
|
|
|
it.each([
|
|
{ npmCommand: "", userAgent: "", launcher: "rea" },
|
|
{
|
|
npmCommand: "exec",
|
|
userAgent: "npm/10.9.0 node/v24.11.0 linux x64",
|
|
launcher: "npx rea-agents",
|
|
},
|
|
{
|
|
npmCommand: "exec",
|
|
userAgent: "bun/1.4.2 npm/? node/v26.3.0 linux x64",
|
|
launcher: "bunx rea-agents",
|
|
},
|
|
])(
|
|
"names the $launcher setup command when no agent is connected",
|
|
async ({ npmCommand, userAgent, launcher }) => {
|
|
const { stderr } = await renderReady({}, [], {
|
|
npm_command: npmCommand,
|
|
npm_config_user_agent: userAgent,
|
|
});
|
|
|
|
expect(stderr).toContain("No AI agent is connected to REA yet.");
|
|
expect(stderr).toContain(
|
|
`Next: to use REA from your AI agent, run \`${launcher} setup\` again, make sure your agent is selected, then press Enter.`,
|
|
);
|
|
expect(stderr).not.toContain("Ask your agent");
|
|
},
|
|
);
|
|
|
|
it("prints IDA and JADX with their product spellings", async () => {
|
|
const { stderr } = await execute(
|
|
process.execPath,
|
|
[
|
|
"--input-type=module",
|
|
"--eval",
|
|
[
|
|
'import { renderInteractiveSetupResult } from "./dist/cli/interactiveSetup.js";',
|
|
"renderInteractiveSetupResult({",
|
|
' status: "ready",',
|
|
" plannedActions: [],",
|
|
" appliedActions: [],",
|
|
" clients: {},",
|
|
" doctor: {",
|
|
" healthy: true,",
|
|
' availableProviders: ["hopper", "ghidra", "ida", "jadx", "kuna"],',
|
|
" checks: [],",
|
|
" },",
|
|
"}, {});",
|
|
].join("\n"),
|
|
],
|
|
{ cwd: process.cwd(), env: { ...process.env, NO_COLOR: "1" } },
|
|
);
|
|
|
|
expect(stderr).toContain(
|
|
"Deep analysis: Hopper, Ghidra, IDA, JADX, and Kuna",
|
|
);
|
|
expect(stderr).not.toContain("Ida");
|
|
expect(stderr).not.toContain("Jadx");
|
|
});
|
|
|
|
it("prints retained cleanup resources without relying on paths in remediation", async () => {
|
|
const resources = ["/fixture/owned backup", "/fixture/临时目录"];
|
|
const result: SetupResult = {
|
|
status: "needs_human",
|
|
code: "cleanup_failed",
|
|
plannedActions: [],
|
|
appliedActions: [],
|
|
clients: {},
|
|
clientStates: [],
|
|
doctor: {
|
|
healthy: true,
|
|
environment_healthy: true,
|
|
availableProviders: [],
|
|
scope: {
|
|
mode: "explicit",
|
|
clients: [],
|
|
providers: [],
|
|
skill: false,
|
|
target: null,
|
|
},
|
|
},
|
|
remediation: "Owned descriptor remains busy",
|
|
cleanup: { reason: "Owned descriptor remains busy", resources },
|
|
};
|
|
const { stderr } = await execute(
|
|
process.execPath,
|
|
[
|
|
"--input-type=module",
|
|
"--eval",
|
|
'import { renderInteractiveSetupResult } from "./dist/cli/interactiveSetup.js";\n' +
|
|
`renderInteractiveSetupResult(${JSON.stringify(result)}, {});`,
|
|
],
|
|
{ cwd: process.cwd(), env: { ...process.env, NO_COLOR: "1" } },
|
|
);
|
|
expect(stderr).toContain(result.remediation);
|
|
for (const resource of resources) expect(stderr).toContain(resource);
|
|
});
|
|
});
|
|
|
|
interface JourneyStep {
|
|
readonly prompt: string;
|
|
readonly input: string;
|
|
}
|
|
|
|
interface JourneyResult {
|
|
readonly output: string;
|
|
readonly decision: z.infer<typeof decisionSchema>;
|
|
}
|
|
|
|
const noAgentQuestion = "No agent selected";
|
|
|
|
const step = (prompt: string, input: string): JourneyStep => ({
|
|
prompt,
|
|
input,
|
|
});
|
|
|
|
const runJourney = async (
|
|
steps: readonly JourneyStep[],
|
|
accessible = false,
|
|
journeyActions: readonly object[] = agentActions,
|
|
{
|
|
initialClientIds = [],
|
|
states = clientStates,
|
|
}: {
|
|
readonly initialClientIds?: readonly string[];
|
|
readonly states?: readonly SetupClientState[];
|
|
} = {},
|
|
): Promise<JourneyResult> => {
|
|
const isolatedHome = await createTestTempDirectory("rea-cli-setup-test-");
|
|
const script = [
|
|
'import { confirmInteractiveSetup, createSetupJourney } from "./dist/cli/interactiveSetup.js";',
|
|
"const journey = createSetupJourney();",
|
|
`const actions = ${JSON.stringify(journeyActions)};`,
|
|
`const context = ${JSON.stringify({ stage: "select", clientStates: states, selectedClientIds: initialClientIds, clientSelectionAllowed: true })};`,
|
|
`let decision = await confirmInteractiveSetup(actions, ${JSON.stringify(accessible)}, context, undefined, journey);`,
|
|
"if (!decision.cancelled && decision.selectedActionIds.length > 0) {",
|
|
" const selected = new Set(decision.selectedActionIds);",
|
|
` decision = await confirmInteractiveSetup(actions.filter(({ id }) => selected.has(id)), ${JSON.stringify(accessible)}, { ...context, stage: "confirm", clientSelectionAllowed: false }, undefined, journey);`,
|
|
"}",
|
|
`process.stdout.write(${JSON.stringify(`\n${decisionMarker}`)} + JSON.stringify(decision) + "\\n");`,
|
|
].join("\n");
|
|
|
|
return new Promise<JourneyResult>((resolvePromise, reject) => {
|
|
let output = "";
|
|
let nextStep = 0;
|
|
// Each step waits for its prompt after the previous one, so a prompt
|
|
// that renders again is matched at its new appearance.
|
|
let searchFrom = 0;
|
|
let settled = false;
|
|
const terminal = spawn(
|
|
process.execPath,
|
|
["--input-type=module", "--eval", script],
|
|
{
|
|
cwd: process.cwd(),
|
|
env: {
|
|
...process.env,
|
|
HOME: isolatedHome,
|
|
USERPROFILE: isolatedHome,
|
|
NO_COLOR: "1",
|
|
TERM: "xterm-256color",
|
|
},
|
|
name: "xterm-256color",
|
|
cols: 120,
|
|
rows: 40,
|
|
},
|
|
);
|
|
const timeout = setTimeout(() => {
|
|
terminal.kill();
|
|
finish(new Error(`Timed out after output:\n${output}`));
|
|
}, 10_000);
|
|
|
|
terminal.onData((data) => {
|
|
output += data;
|
|
const pending = steps[nextStep];
|
|
const found =
|
|
pending === undefined ? -1 : output.indexOf(pending.prompt, searchFrom);
|
|
if (pending !== undefined && found !== -1) {
|
|
searchFrom = found + pending.prompt.length;
|
|
nextStep += 1;
|
|
terminal.write(pending.input);
|
|
}
|
|
});
|
|
terminal.onExit(({ exitCode }) => {
|
|
if (exitCode !== 0) {
|
|
finish(
|
|
new Error(`Setup journey exited ${String(exitCode)}:\n${output}`),
|
|
);
|
|
return;
|
|
}
|
|
if (nextStep !== steps.length) {
|
|
finish(new Error(`Setup journey missed an interaction:\n${output}`));
|
|
return;
|
|
}
|
|
const markerIndex = output.lastIndexOf(decisionMarker);
|
|
if (markerIndex === -1) {
|
|
finish(new Error(`Setup journey returned no decision:\n${output}`));
|
|
return;
|
|
}
|
|
const raw = output.slice(markerIndex + decisionMarker.length);
|
|
const jsonStart = raw.indexOf("{");
|
|
const jsonEnd = raw.lastIndexOf("}");
|
|
const serialized =
|
|
jsonStart !== -1 && jsonEnd !== -1 && jsonEnd > jsonStart
|
|
? raw.slice(jsonStart, jsonEnd + 1)
|
|
: raw.split(/\r?\n/u, 1)[0];
|
|
if (serialized === undefined) {
|
|
finish(
|
|
new Error(`Setup journey returned an empty decision:\n${output}`),
|
|
);
|
|
return;
|
|
}
|
|
try {
|
|
finish(undefined, {
|
|
output,
|
|
decision: decisionSchema.parse(JSON.parse(serialized)),
|
|
});
|
|
} catch (cause: unknown) {
|
|
finish(cause instanceof Error ? cause : new Error(String(cause)));
|
|
}
|
|
});
|
|
|
|
function finish(error?: Error, result?: JourneyResult): void {
|
|
if (settled) return;
|
|
settled = true;
|
|
clearTimeout(timeout);
|
|
void rm(isolatedHome, { recursive: true, force: true }).finally(() => {
|
|
if (error !== undefined) reject(error);
|
|
else if (result !== undefined) resolvePromise(result);
|
|
else reject(new Error("Setup journey completed without a result"));
|
|
});
|
|
}
|
|
});
|
|
};
|