diff --git a/docs/installation.md b/docs/installation.md index 7afefd07f..71b7ffb7c 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -139,8 +139,36 @@ listed after the table because its connector is not one of these files: | VS Code | `vscode` | | Grok Build | `grok_build` | | OMP | `omp` | +| Pi | `pi` | | Hermes | `hermes` | +For [Pi](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/mcp.md), +setup writes a `type: "stdio"` entry under `mcpServers.rea` in the user-level +`~/.pi/agent/mcp.json` and installs the bundled skill under `~/.agents/skills`. +Use `rea setup --client pi --dry-run --json` to inspect the plan, then +`rea setup --client pi --yes --json` to approve it. Check the registration with +`rea doctor --client pi --json`. Pi reads `mcp.json` as strict JSON, like its +own loader: comments, trailing commas, a byte-order mark, or an empty existing +file are invalid, and setup reports them instead of rewriting the file. Repair +such a file to plain JSON first, then rerun setup. + +Setup follows Pi's `PI_CODING_AGENT_DIR`: unset or empty selects the default; +`~` and `~/` expand to the home directory; absolute paths and file URLs select +that directory; relative paths stay relative to the command's working directory. +On Windows, native paths, `~\`, and Git Bash/MSYS, Cygwin, and WSL drive paths +are normalized as Pi does. Run REA and Pi from the same working directory when +using a relative override. Pi has no profiles: `OMP_PROFILE`, `PI_PROFILE`, +`PI_CONFIG_DIR`, and OMP's `enabledServers`/`disabledServers` lists do not affect +Pi registration. Doctor accepts an omitted `type` for stdio but reports a +non-stdio type as invalid; `enabled: false` stays disabled. + +REA configures only the user scope. Pi also reads `.pi/mcp.json` in trusted +projects; a same-name project entry can replace the user entry or override its +enabled state and exposure. Check that file if the user registration is aligned +but unavailable in a project. An extension that registers `/mcp` can replace +Pi's built-in MCP support and use its own configuration instead. Run `/reload` +in an existing Pi session after changing servers outside the session. + For Qwen Code, setup registers `rea` in the `mcpServers` table of the user-level `~/.qwen/settings.json`, or `$QWEN_HOME/settings.json` when configured. Setup and doctor follow Qwen Code's tilde and working-directory-relative home diff --git a/src/application/ClientConfigurationDocument.ts b/src/application/ClientConfigurationDocument.ts index 34e701925..a0b7c9c1c 100644 --- a/src/application/ClientConfigurationDocument.ts +++ b/src/application/ClientConfigurationDocument.ts @@ -99,6 +99,10 @@ const parseDocument = ( ): Record => { if (format === "toml" || format === "grok") return objectSchema.parse(parseToml(text)); + // Pi loads `mcp.json` with a strict `JSON.parse` and no BOM tolerance, so + // comments, trailing commas, a BOM, or an empty existing file must be + // rejected instead of registering into a document Pi cannot load. + if (format === "pi") return objectSchema.parse(JSON.parse(text)); // Hermes stores MCP servers in `mcp_servers` inside a YAML document. if (format === "hermes") return objectSchema.parse(parseYaml(text)); // An empty file, which some clients create before any server is added, @@ -1369,6 +1373,7 @@ export const clientRegistrationEntry = ( }; case "vscode": case "omp": + case "pi": return { type: "stdio", command: executable, diff --git a/src/application/ClientRegistrationStatus.ts b/src/application/ClientRegistrationStatus.ts index 2151b00f3..73cab0a1c 100644 --- a/src/application/ClientRegistrationStatus.ts +++ b/src/application/ClientRegistrationStatus.ts @@ -80,6 +80,16 @@ export const readClientRegistrationStatuses = async ( options.platform, options.environment, )) { + if (client.configPathError !== undefined) { + statuses.push({ + client: client.name, + config_path: client.configPath, + command: [], + state: "invalid", + remediation: client.configPathError, + }); + continue; + } if ( !(await exists(client.markerPath)) && !(await exists(client.configPath)) @@ -166,9 +176,9 @@ const registrationAligned = ( ) return false; if (client.format === "vscode" && registration.type !== "stdio") return false; - // OMP infers stdio for a command entry without an explicit type. + // OMP and Pi infer stdio for a command entry without an explicit type. if ( - client.format === "omp" && + (client.format === "omp" || client.format === "pi") && registration.type !== undefined && registration.type !== "stdio" ) @@ -230,7 +240,7 @@ const parseRegistration = ( if (client.format === "commandcode" && registration.transport !== "stdio") throw new TypeError("Expected an stdio registration"); if ( - client.format === "omp" && + (client.format === "omp" || client.format === "pi") && registration.type !== undefined && registration.type !== "stdio" ) diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.ts index 951980896..eb5c01571 100644 --- a/src/application/SetupClientConfiguration.ts +++ b/src/application/SetupClientConfiguration.ts @@ -33,6 +33,8 @@ export const configureClientConfiguration = ( environment: SetupProviderEnvironment = {}, command: readonly string[] = npxRegistrationCommand(), ): Promise => { + if (client.configPathError !== undefined) + return Promise.resolve({ status: "failed", reason: "path" }); if (client.format === undefined || client.format === "unsupported") return Promise.resolve({ status: "failed", reason: "readback" }); return configureClientDocument(client, environment, command, client.format); @@ -154,6 +156,7 @@ export const clientConfigurationAligned = async ( providerEnvironment: SetupProviderEnvironment, command: readonly string[], ): Promise => { + if (client.configPathError !== undefined) return false; try { const original = await readFile(client.configPath, "utf8"); const parsed = parseClientConfiguration(original, client.format); @@ -179,6 +182,8 @@ export const inspectClientConfiguration = async ( providerEnvironment: SetupProviderEnvironment, command: readonly string[], ): Promise => { + if (client.configPathError !== undefined) + return { status: "invalid", remediation: client.configPathError }; if (client.format === "unsupported") return { status: "already_current" }; const transactionPath = await resolveClientConfigTransactionPath( client.configPath, diff --git a/src/application/SetupHost.ts b/src/application/SetupHost.ts index 9941fcf0b..87bf63aa0 100644 --- a/src/application/SetupHost.ts +++ b/src/application/SetupHost.ts @@ -167,6 +167,7 @@ export const detectClients = async ( ): Promise => { const detected: SetupClient[] = []; for (const candidate of supportedClients(home, platform, environment)) { + if (candidate.configPathError !== undefined) continue; const [hasConfig, hasMarker] = await Promise.all([ exists(candidate.configPath), candidate.markerPath === undefined ? false : exists(candidate.markerPath), diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index a6bd9914a..90cd52d0f 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -1,4 +1,5 @@ -import { isAbsolute, join, resolve } from "node:path"; +import { isAbsolute, join, resolve, win32 } from "node:path"; +import { fileURLToPath } from "node:url"; import { lstatSync } from "node:fs"; /** One supported client configuration location. */ @@ -6,6 +7,8 @@ export interface SetupClient { readonly name: string; readonly displayName?: string; readonly configPath: string; + /** Unresolved path evidence only; consumers must not perform I/O on it. */ + readonly configPathError?: string; readonly markerPath?: string; readonly format?: | "json" @@ -16,6 +19,7 @@ export interface SetupClient { | "commandcode" | "grok" | "omp" + | "pi" | "hermes" | "unsupported"; } @@ -197,6 +201,41 @@ const ompAgentDirectory = (context: ClientPathContext): string => { : join(root, "agent"); }; +/** + * Pi's public getAgentDir()/normalizePath semantics, not OMP's profiles. + * Keep relative overrides relative: filesystem consumers resolve them in cwd. + */ +const piAgentDirectory = ({ + home, + platform, + env, +}: ClientPathContext): string => { + const paths = platform === "win32" ? win32 : { join }; + let directory = env.PI_CODING_AGENT_DIR; + if (!directory) return paths.join(home, ".pi", "agent"); + if ( + platform === "win32" && + directory.startsWith("/") && + !directory.startsWith("//") && + !directory.includes("\\") + ) { + const drive = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/iu.exec( + directory, + ); + if (drive !== null) + directory = `${drive[1]?.toUpperCase()}:\\${drive[2]?.replaceAll("/", "\\") ?? ""}`; + } + if (directory === "~") return home; + if ( + directory.startsWith("~/") || + (platform === "win32" && directory.startsWith("~\\")) + ) + return paths.join(home, directory.slice(2)); + if (directory.startsWith("file://")) + return fileURLToPath(directory, { windows: platform === "win32" }); + return directory; +}; + const copilotDirectory = ({ home, env }: ClientPathContext): string => env.COPILOT_HOME ?? join(home, ".copilot"); @@ -358,6 +397,17 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [ markerPath: ompAgentDirectory, format: "omp", }, + { + name: "pi", + displayName: "Pi", + configPath: (context: ClientPathContext) => + (context.platform === "win32" ? win32 : { join }).join( + piAgentDirectory(context), + "mcp.json", + ), + markerPath: piAgentDirectory, + format: "pi", + }, { name: "hermes", displayName: "Hermes", @@ -387,13 +437,26 @@ export const supportedClients = ( env: ClientPathContext["env"] = process.env, ): readonly SetupClient[] => { const context = { home, platform, env }; - return SUPPORTED_CLIENT_DEFINITIONS.map((definition) => ({ - name: definition.name, - displayName: definition.displayName, - configPath: resolvePath(definition.configPath, context), - markerPath: resolvePath(definition.markerPath, context), - format: definition.format, - })); + return SUPPORTED_CLIENT_DEFINITIONS.map((definition) => { + try { + return { + name: definition.name, + displayName: definition.displayName, + configPath: resolvePath(definition.configPath, context), + markerPath: resolvePath(definition.markerPath, context), + format: definition.format, + }; + } catch (cause: unknown) { + if (definition.name !== "pi") throw cause; + return { + name: definition.name, + displayName: definition.displayName, + format: definition.format, + configPath: env.PI_CODING_AGENT_DIR ?? "", + configPathError: `Invalid PI_CODING_AGENT_DIR: ${cause instanceof Error ? cause.message : String(cause)}. Repair the override before configuring Pi.`, + }; + } + }); }; /** Resolve personal skill roots using the same client environment as setup. */ diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.ts index 433678ef0..c30accb38 100644 --- a/src/application/Uninstall.ts +++ b/src/application/Uninstall.ts @@ -201,6 +201,8 @@ const readClientConfiguration = async ( client: SetupClient, fileSystem: UninstallFileSystem, ): Promise => { + if (client.configPathError !== undefined) + return itemRead(item(client.name, "failed", client.configPathError)); if (client.format === "unsupported") return itemRead( item( diff --git a/tests/boundary/cli/piClientSetup.test.ts b/tests/boundary/cli/piClientSetup.test.ts new file mode 100644 index 000000000..6c586999a --- /dev/null +++ b/tests/boundary/cli/piClientSetup.test.ts @@ -0,0 +1,301 @@ +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; + +import { expect } from "vitest"; + +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; + +cliTest( + "Pi public CLI plans, requires approval, applies, diagnoses, repeats, and uninstalls only owned content", + async ({ cli }) => { + const home = await createTestTempDirectory("rea-pi-cli-"); + const agent = join(home, "custom-agent"); + const config = join(agent, "mcp.json"); + const skill = join( + home, + ".agents/skills/reverse-engineer-anything/SKILL.md", + ); + const original = + '{ "mcpServers": { "other": { "command": "other-server" } }, "autoEnableCodemode": false }\n'; + await mkdir(agent); + await writeFile(config, original); + const cliPath = resolve("scripts/rea.mjs"); + const run = (arguments_: readonly string[]) => + cli.run({ + arguments: arguments_, + cwd: home, + environment: { + HOME: home, + USERPROFILE: home, + PI_CODING_AGENT_DIR: "custom-agent", + OMP_PROFILE: "work", + PI_PROFILE: "legacy", + PI_CONFIG_DIR: ".omp-other", + }, + timeoutMs: 20_000, + }); + + const planned = await run([ + "setup", + "--client", + "pi", + "--dry-run", + "--json", + ]); + expect(planned.exitCode).toBe(0); + expect(planned.json).toMatchObject({ + status: "planned", + plannedActions: [ + { + id: "configure_client:pi", + label: "Pi", + target: join("custom-agent", "mcp.json"), + operation: "update", + }, + { id: "install_skill" }, + ], + appliedActions: [], + }); + expect(await readFile(config, "utf8")).toBe(original); + await expect(readFile(`${config}.rea.backup`)).rejects.toMatchObject({ + code: "ENOENT", + }); + await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" }); + + const unapproved = await run(["setup", "--client", "pi", "--json"]); + expect(unapproved.json).toMatchObject({ + status: "needs_confirmation", + appliedActions: [], + }); + expect(await readFile(config, "utf8")).toBe(original); + + const applied = await run(["setup", "--client", "pi", "--yes", "--json"]); + expect(applied.exitCode).toBe(0); + expect(applied.json).toMatchObject({ + status: "ready", + clients: { pi: { status: "configured" } }, + appliedActions: ["configured_pi", "installed_skill"], + }); + const configured = await readFile(config, "utf8"); + expect(JSON.parse(configured)).toMatchObject({ + mcpServers: { + other: { command: "other-server" }, + rea: { + type: "stdio", + command: process.platform === "win32" ? process.execPath : cliPath, + args: process.platform === "win32" ? [cliPath, "mcp"] : ["mcp"], + }, + }, + autoEnableCodemode: false, + }); + expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original); + expect(await readFile(skill, "utf8")).toContain( + "reverse-engineer-anything", + ); + + const doctor = await run(["doctor", "--client", "pi", "--json"]); + expect(doctor.exitCode).toBe(0); + expect(doctor.json).toMatchObject({ + healthy: true, + identity: { registrations: [{ client: "pi", state: "aligned" }] }, + }); + + const repeat = await run(["setup", "--client", "pi", "--yes", "--json"]); + expect(repeat.exitCode).toBe(0); + expect(repeat.json).toMatchObject({ + status: "ready", + plannedActions: [], + appliedActions: [], + }); + expect(await readFile(config, "utf8")).toBe(configured); + expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original); + + // Uninstall is global; there is no --client or --yes on this CLI surface. + const help = await run(["uninstall", "--help"]); + expect(help.exitCode).toBe(0); + expect(help.stdout).toContain("--purge-data"); + const removed = await run(["uninstall", "--json"]); + expect(removed.exitCode).toBe(0); + expect(JSON.parse(await readFile(config, "utf8"))).toEqual( + JSON.parse(original), + ); + expect(await readFile(`${config}.rea.backup`, "utf8")).toBe(original); + await expect(readFile(skill)).rejects.toMatchObject({ code: "ENOENT" }); + }, +); + +cliTest( + "Pi public CLI creates missing strict-JSON configuration and never repairs a malformed file", + async ({ cli }) => { + const created = await createTestTempDirectory("rea-pi-cli-strict-"); + const agent = join(created, "custom-agent"); + const config = join(agent, "mcp.json"); + await mkdir(agent); + const runIn = (home: string) => (arguments_: readonly string[]) => + cli.run({ + arguments: arguments_, + cwd: home, + environment: { + HOME: home, + USERPROFILE: home, + PI_CODING_AGENT_DIR: "custom-agent", + }, + timeoutMs: 20_000, + }); + const run = runIn(created); + const setup = await run(["setup", "--client", "pi", "--yes", "--json"]); + expect(setup.exitCode).toBe(0); + expect(setup.json).toMatchObject({ + status: "ready", + clients: { pi: { status: "configured" } }, + }); + const text = await readFile(config, "utf8"); + expect(() => JSON.parse(text)).not.toThrow(); + expect(JSON.parse(text)).toMatchObject({ + mcpServers: { rea: { type: "stdio" } }, + }); + const doctor = await run(["doctor", "--client", "pi", "--json"]); + expect(doctor.exitCode).toBe(0); + expect(doctor.json).toMatchObject({ + healthy: true, + identity: { registrations: [{ client: "pi", state: "aligned" }] }, + }); + await run(["uninstall", "--json"]); + expect( + JSON.parse(await readFile(config, "utf8")).mcpServers.rea, + ).toBeUndefined(); + + const blocked = await createTestTempDirectory("rea-pi-cli-malformed-"); + const malformedPath = join(blocked, "custom-agent", "mcp.json"); + await mkdir(join(blocked, "custom-agent")); + const malformed = `{ // Pi loads strict JSON only\n"mcpServers": { "other": { "command": "other" } }\n}\n`; + await writeFile(malformedPath, malformed); + const runMalformed = runIn(blocked); + const plan = await runMalformed([ + "setup", + "--client", + "pi", + "--dry-run", + "--json", + ]); + expect(plan.exitCode).not.toBe(0); + expect(plan.json).toMatchObject({ + status: "needs_human", + plannedActions: [], + appliedActions: [], + remediation: expect.stringContaining("malformed"), + }); + const applied = await runMalformed([ + "setup", + "--client", + "pi", + "--yes", + "--json", + ]); + expect(applied.exitCode).not.toBe(0); + expect(applied.json).toMatchObject({ + status: "needs_human", + plannedActions: [], + appliedActions: [], + }); + expect(await readFile(malformedPath, "utf8")).toBe(malformed); + await expect(readFile(`${malformedPath}.rea.backup`)).rejects.toMatchObject( + { + code: "ENOENT", + }, + ); + const doctorMalformed = await runMalformed([ + "doctor", + "--client", + "pi", + "--json", + ]); + expect(doctorMalformed.exitCode).not.toBe(0); + expect(doctorMalformed.json).toMatchObject({ + healthy: false, + identity: { + registrations: [{ client: "pi", state: "invalid" }], + }, + }); + const removed = await runMalformed(["uninstall", "--json"]); + expect(removed.exitCode).not.toBe(0); + expect(removed.json).toMatchObject({ + status: "failed", + items: expect.arrayContaining([ + expect.objectContaining({ name: "pi", status: "failed" }), + ]), + }); + expect(await readFile(malformedPath, "utf8")).toBe(malformed); + }, +); + +cliTest( + "malformed Pi overrides do not block selected Codex setup or doctor and never fall back for Pi", + async ({ cli }) => { + const home = await createTestTempDirectory("rea-pi-invalid-cli-"); + const run = (arguments_: readonly string[]) => + cli.run({ + arguments: arguments_, + cwd: home, + environment: { + HOME: home, + USERPROFILE: home, + PI_CODING_AGENT_DIR: "file:///agent%2fdir", + }, + timeoutMs: 20_000, + }); + const plan = await run([ + "setup", + "--client", + "codex", + "--dry-run", + "--json", + ]); + expect(plan.exitCode).toBe(0); + expect(plan.json).toMatchObject({ status: "planned", appliedActions: [] }); + expect(await readdir(home)).toEqual([]); + + const rejected = await run(["setup", "--client", "pi", "--yes", "--json"]); + expect(rejected.exitCode).not.toBe(0); + expect(rejected.json).toMatchObject({ + status: "needs_human", + plannedActions: [], + appliedActions: [], + remediation: expect.stringContaining("PI_CODING_AGENT_DIR"), + }); + expect(await readdir(home)).toEqual([]); + + const applied = await run([ + "setup", + "--client", + "codex", + "--yes", + "--json", + ]); + expect(applied.exitCode).toBe(0); + expect(applied.json).toMatchObject({ + status: "ready", + clients: { codex: { status: "configured" } }, + }); + const doctor = await run(["doctor", "--client", "codex", "--json"]); + expect(doctor.exitCode).toBe(0); + expect(doctor.json).toMatchObject({ + healthy: true, + identity: { + registrations: [ + { client: "codex", state: "aligned" }, + { + client: "pi", + state: "invalid", + remediation: expect.stringContaining("PI_CODING_AGENT_DIR"), + }, + ], + }, + }); + const piDoctor = await run(["doctor", "--client", "pi", "--json"]); + expect(piDoctor.exitCode).not.toBe(0); + expect(piDoctor.json).toMatchObject({ healthy: false }); + expect((await readdir(home)).sort()).toEqual([".agents", ".codex"]); + }, +); diff --git a/tests/boundary/filesystem/clientConfigurationDialects.test.ts b/tests/boundary/filesystem/clientConfigurationDialects.test.ts index 71d6512ec..a378cc758 100644 --- a/tests/boundary/filesystem/clientConfigurationDialects.test.ts +++ b/tests/boundary/filesystem/clientConfigurationDialects.test.ts @@ -32,6 +32,7 @@ const getClients = (home: string) => "vscode", "devin", "omp", + "pi", ].includes(name), ); @@ -44,6 +45,7 @@ describe("additional client configuration dialects", () => { "vscode", "devin", "omp", + "pi", ] as const)("registers, reads back, and uninstalls %s", async (name) => { const home = await createTestTempDirectory("rea-client-dialect-"); const client = getClients(home).find( @@ -78,7 +80,7 @@ describe("additional client configuration dialects", () => { command, enabled: true, }); - if (name === "vscode" || name === "omp") + if (name === "vscode" || name === "omp" || name === "pi") expect(registration).toMatchObject({ type: "stdio", command: "npx", diff --git a/tests/boundary/filesystem/clientLifecycle.test.ts b/tests/boundary/filesystem/clientLifecycle.test.ts index 72f1a7a13..62efeddd7 100644 --- a/tests/boundary/filesystem/clientLifecycle.test.ts +++ b/tests/boundary/filesystem/clientLifecycle.test.ts @@ -63,6 +63,7 @@ describe("client configuration filesystem lifecycle", () => { "vscode", "grok_build", "omp", + "pi", "hermes", "grok_bot", ]); diff --git a/tests/boundary/filesystem/piClientConfiguration.test.ts b/tests/boundary/filesystem/piClientConfiguration.test.ts new file mode 100644 index 000000000..bec8a7d08 --- /dev/null +++ b/tests/boundary/filesystem/piClientConfiguration.test.ts @@ -0,0 +1,333 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; +import { parseClientConfiguration } from "../../../src/application/ClientConfigurationDocument.js"; +import { + configureClientConfiguration, + inspectClientConfiguration, +} from "../../../src/application/SetupClientConfiguration.js"; +import { detectClients } from "../../../src/application/SetupHost.js"; +import { supportedClients } from "../../../src/application/SupportedClients.js"; +import { systemUninstallHost } from "../../../src/application/Uninstall.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + clearClientLocationEnvironment, + NPX_REGISTRATION_COMMAND, +} from "../../fixtures/clientEnvironment.js"; + +beforeEach(clearClientLocationEnvironment); +afterEach(() => vi.unstubAllEnvs()); + +const piPath = ( + home: string, + platform: NodeJS.Platform, + env: Parameters[2], +) => supportedClients(home, platform, env).find(({ name }) => name === "pi"); + +// Catch fallback to OMP paths, loss of relative overrides, and normalization +// that differs from Pi's public getAgentDir()/normalizePath boundary. +describe("Pi user configuration paths", () => { + it.each([ + [undefined, "/home/a/.pi/agent"], + ["", "/home/a/.pi/agent"], + ["/custom/agent", "/custom/agent"], + ["~", "/home/a"], + ["~/custom/agent", "/home/a/custom/agent"], + ["agent", "agent"], + ["./agent", "./agent"], + [" agent ", " agent "], + ["~other/agent", "~other/agent"], + ["file:///custom/agent%20dir", "/custom/agent dir"], + ["/mnt/c/agent", "/mnt/c/agent"], + ])( + "uses Pi's agent directory for %s, independently of OMP", + (override, expected) => { + const client = piPath("/home/a", "linux", { + PI_CODING_AGENT_DIR: override, + OMP_PROFILE: "work", + PI_PROFILE: "legacy", + PI_CONFIG_DIR: ".omp-other", + }); + expect(client?.markerPath).toBe(expected); + expect(client?.configPath).toBe(join(expected, "mcp.json")); + }, + ); + + it.each([ + [undefined, "C:\\Users\\a\\.pi\\agent"], + ["", "C:\\Users\\a\\.pi\\agent"], + ["~", "C:\\Users\\a"], + ["~/agent", "C:\\Users\\a\\agent"], + ["~\\agent", "C:\\Users\\a\\agent"], + ["C:\\custom\\agent", "C:\\custom\\agent"], + ["/c/custom/agent", "C:\\custom\\agent"], + ["/mnt/c/custom/agent", "C:\\custom\\agent"], + ["/cygdrive/c/custom/agent", "C:\\custom\\agent"], + ["/c", "C:\\"], + ["//server/share/agent", "//server/share/agent"], + ["\\\\server\\share\\agent", "\\\\server\\share\\agent"], + ["agent", "agent"], + ["file:///C:/custom/agent%20dir", "C:\\custom\\agent dir"], + ["file://server/share/agent", "\\\\server\\share\\agent"], + ])("normalizes Windows Pi override %s", (override, expected) => { + const client = piPath("C:\\Users\\a", "win32", { + PI_CODING_AGENT_DIR: override, + }); + expect(client?.markerPath).toBe(expected); + expect(client?.configPath).toBe( + `${expected.replace(/[\\/]+$/u, "").replaceAll("/", "\\")}\\mcp.json`, + ); + }); + + it("reports malformed file URLs instead of silently choosing the default", async () => { + const home = await createTestTempDirectory("rea-pi-invalid-path-"); + const client = piPath(home, "linux", { + PI_CODING_AGENT_DIR: "file:///agent%2fdir", + }); + expect(client).toMatchObject({ + configPath: "file:///agent%2fdir", + configPathError: expect.stringContaining("PI_CODING_AGENT_DIR"), + }); + if (client === undefined) throw new Error("missing Pi client"); + expect(await configureClientConfiguration(client)).toEqual({ + status: "failed", + reason: "path", + }); + expect(await systemUninstallHost(home).removeClient(client)).toMatchObject({ + status: "failed", + detail: expect.stringContaining("PI_CODING_AGENT_DIR"), + }); + expect( + await detectClients(home, "linux", { + PI_CODING_AGENT_DIR: "file:///agent%2fdir", + }), + ).toEqual([]); + }); + + it("detects the normalized override marker without needing mcp.json", async () => { + const home = await createTestTempDirectory("rea-pi-detection-"); + await mkdir(join(home, "custom-agent")); + const detected = await detectClients(home, process.platform, { + PI_CODING_AGENT_DIR: "~/custom-agent", + }); + expect(detected.find(({ name }) => name === "pi")?.configPath).toBe( + join(home, "custom-agent", "mcp.json"), + ); + }); +}); + +const piClient = async () => { + const home = await createTestTempDirectory("rea-pi-config-"); + const client = piPath(home, process.platform, {}); + if (client?.markerPath === undefined) throw new Error("missing Pi client"); + await mkdir(client.markerPath, { recursive: true }); + return { home, client }; +}; + +describe("Pi registration semantics", () => { + it("preserves unrelated content and OMP-only lists during setup, repeat, and uninstall", async () => { + const { home, client } = await piClient(); + // Pi loads mcp.json with strict JSON, so the retained unrelated settings + // are valid strict JSON rather than the commented JSONC fixture. + const original = `{"autoEnableCodemode": false, + "mcpServers": { "other": { "command": "other-server" } }, + "enabledServers": ["other"], + "disabledServers": ["rea", "other"] +}\n`; + await writeFile(client.configPath, original); + expect( + await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND), + ).toMatchObject({ status: "configured" }); + expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe( + original, + ); + const configured = await readFile(client.configPath, "utf8"); + expect(JSON.parse(configured)).toEqual({ + autoEnableCodemode: false, + mcpServers: { + other: { command: "other-server" }, + rea: { + type: "stdio", + command: "npx", + args: NPX_REGISTRATION_COMMAND.slice(1), + }, + }, + enabledServers: ["other"], + disabledServers: ["rea", "other"], + }); + expect( + await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND), + ).toEqual({ status: "unchanged" }); + expect(await readFile(client.configPath, "utf8")).toBe(configured); + expect( + ( + await readClientRegistrationStatuses(home, undefined, { + environment: {}, + }) + ).find(({ client: name }) => name === "pi"), + ).toMatchObject({ state: "aligned" }); + expect((await systemUninstallHost(home).removeClient(client)).status).toBe( + "removed", + ); + expect(JSON.parse(await readFile(client.configPath, "utf8"))).toEqual( + JSON.parse(original), + ); + expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe( + original, + ); + }); + + it.each([ + [undefined, true, "aligned"], + ["stdio", true, "aligned"], + ["http", true, "invalid"], + ["streamable-http", true, "invalid"], + ["sse", true, "invalid"], + [undefined, false, "stale"], + ["stdio", false, "stale"], + ])( + "doctor handles type %s and enabled %s without OMP allowlist overrides", + async (type, enabled, state) => { + const { home, client } = await piClient(); + await writeFile( + client.configPath, + JSON.stringify({ + mcpServers: { + rea: { + command: "npx", + args: NPX_REGISTRATION_COMMAND.slice(1), + type, + enabled, + }, + }, + enabledServers: ["rea"], + }), + ); + const statuses = await readClientRegistrationStatuses(home, undefined, { + environment: {}, + }); + expect(statuses.find(({ client: name }) => name === "pi")).toMatchObject({ + state, + }); + }, + ); +}); + +describe("Pi strict JSON parsing", () => { + it.each([ + [ + "a comment", + `{ // Pi loads strict JSON only\n"mcpServers": { "other": { "command": "other" } }\n}\n`, + ], + [ + "a trailing comma", + `{"mcpServers": { "other": { "command": "other" }, },}\n`, + ], + [ + "a BOM before valid JSON", + `\uFEFF{"mcpServers": { "other": { "command": "other" } }}\n`, + ], + ["empty text", ""], + ["whitespace only", "\n \t\r\n"], + ["a BOM only", "\uFEFF"], + ])( + "rejects an existing Pi configuration with %s before any mutation", + async (_description, original) => { + const { home, client } = await piClient(); + await writeFile(client.configPath, original); + expect(() => parseClientConfiguration(original, "pi")).toThrow(); + expect( + await inspectClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND), + ).toMatchObject({ status: "invalid" }); + expect( + await configureClientConfiguration( + client, + {}, + NPX_REGISTRATION_COMMAND, + ), + ).toEqual({ status: "failed", reason: "readback" }); + expect(await readFile(client.configPath, "utf8")).toBe(original); + await expect( + readFile(`${client.configPath}.rea.backup`), + ).rejects.toMatchObject({ code: "ENOENT" }); + expect( + ( + await readClientRegistrationStatuses(home, undefined, { + environment: {}, + }) + ).find(({ client: name }) => name === "pi"), + ).toMatchObject({ state: "invalid" }); + expect( + await systemUninstallHost(home).removeClient(client), + ).toMatchObject({ + name: "pi", + status: "failed", + detail: expect.stringContaining("not valid JSON"), + }); + expect(await readFile(client.configPath, "utf8")).toBe(original); + await expect( + readFile(`${client.configPath}.rea.backup`), + ).rejects.toMatchObject({ code: "ENOENT" }); + }, + ); + + it("initializes a missing Pi configuration as valid strict JSON without a backup", async () => { + const { home, client } = await piClient(); + await expect(readFile(client.configPath)).rejects.toMatchObject({ + code: "ENOENT", + }); + expect( + await inspectClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND), + ).toEqual({ status: "create" }); + expect( + await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND), + ).toMatchObject({ status: "configured" }); + const created = await readFile(client.configPath, "utf8"); + expect(() => JSON.parse(created)).not.toThrow(); + expect(JSON.parse(created)).toEqual({ + mcpServers: { + rea: { + type: "stdio", + command: "npx", + args: NPX_REGISTRATION_COMMAND.slice(1), + }, + }, + }); + await expect( + readFile(`${client.configPath}.rea.backup`), + ).rejects.toMatchObject({ code: "ENOENT" }); + expect( + await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND), + ).toEqual({ status: "unchanged" }); + expect(await readFile(client.configPath, "utf8")).toBe(created); + expect( + ( + await readClientRegistrationStatuses(home, undefined, { + environment: {}, + }) + ).find(({ client: name }) => name === "pi"), + ).toMatchObject({ state: "aligned" }); + expect(await systemUninstallHost(home).removeClient(client)).toMatchObject({ + name: "pi", + status: "removed", + }); + expect(JSON.parse(await readFile(client.configPath, "utf8"))).toEqual({ + mcpServers: {}, + }); + }); + + it("keeps JSONC tolerance for other dialects while Pi rejects the same text", () => { + const jsonc = `\uFEFF{\n // A comment Pi rejects but OpenCode keeps.\n "mcp": { "other": { "type": "local" }, },\n}\n`; + expect(parseClientConfiguration(jsonc, "opencode").servers).toEqual({ + other: { type: "local" }, + }); + expect(parseClientConfiguration("", "opencode").document).toEqual({}); + expect(parseClientConfiguration("\uFEFF", "opencode").document).toEqual({}); + expect(() => parseClientConfiguration(jsonc, "pi")).toThrow(); + expect(() => parseClientConfiguration("", "pi")).toThrow(); + expect(() => parseClientConfiguration("\uFEFF", "pi")).toThrow(); + }); +});