diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 10e272406..d01717f4a 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -18,11 +18,10 @@ "skills": "./skills", "mcpServers": { "rea": { - "command": "npx", + "command": "node", "args": [ - "-y", - "rea-agents@6.4.0", - "mcp" + "${CLAUDE_PLUGIN_ROOT}/scripts/plugin-mcp-launcher.mjs", + "rea-agents@6.4.0" ] } } diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index ff458145a..1e90d221e 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -18,13 +18,13 @@ "skills": "./skills", "mcpServers": { "rea": { - "command": "npx", + "command": "node", "args": [ - "-y", - "rea-agents@6.4.0", - "mcp" + "./scripts/plugin-mcp-launcher.mjs", + "rea-agents@6.4.0" ], - "startup_timeout_sec": 30 + "startup_timeout_sec": 30, + "cwd": "." } }, "interface": { diff --git a/docs/installation.md b/docs/installation.md index 76c912b49..6befc8d4d 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -785,8 +785,14 @@ Ghidra/JDK installation; neither is inferred from startup alone. REA's npm package is the shared Claude Code and Codex plugin artifact. It contains `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json`, and the -canonical generated `skills/` tree. Both manifests select `./skills` and pin -the stdio MCP server to that exact package version. The existing release skill +canonical generated `skills/` tree. Both manifests select `./skills` and run a plain Node bootstrap pinned to +that exact package version. The client must have a supported standalone `node` +on its PATH. Claude expands its documented `CLAUDE_PLUGIN_ROOT` in the script +argument; Codex resolves `cwd: "."` from the installed plugin root before +launching the relative script. The shared bootstrap preserves the pinned +package-runner arguments and stdio, handles Windows npm shims, and uses an owned +empty working directory so an unbuilt local checkout cannot shadow the exact +registry release. The existing release skill generator also pins CLI recovery commands to the same version. The repository's single-plugin marketplaces are declared in diff --git a/package.json b/package.json index a7611f58d..b38f5c149 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,8 @@ "bridge/android/ReaJadxBridge.java", "bridge/mitmproxy/capture.py", "scripts/rea.mjs", + "scripts/plugin-mcp-launcher.mjs", + "src/process/packageRunnerCommand.mjs", "scripts/electron-active-hook.cjs", "scripts/electron-active-hook-boundaries.cjs", "scripts/hopper-demo-x11.py", diff --git a/scripts/plugin-mcp-launcher.mjs b/scripts/plugin-mcp-launcher.mjs new file mode 100644 index 000000000..87772d7dc --- /dev/null +++ b/scripts/plugin-mcp-launcher.mjs @@ -0,0 +1,95 @@ +#!/usr/bin/env node + +import { spawn } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { constants, tmpdir } from "node:os"; +import { join } from "node:path"; + +import { packageRunnerCommand } from "../src/process/packageRunnerCommand.mjs"; + +// The manifest owns this exact package pin; args[1] remains release-managed. +// No build, dependency installation or ambient latest-version lookup is needed +// to run this bootstrap from a Git-installed plugin. +const [packageSpecifier, ...extra] = process.argv.slice(2); +if ( + extra.length !== 0 || + !/^rea-agents@\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/u.test( + packageSpecifier ?? "", + ) +) { + process.stderr.write( + "REA plugin requires one exact rea-agents@VERSION pin.\n", + ); + process.exitCode = 1; +} else { + await launch(packageSpecifier); +} + +async function launch(packageSpecifier) { + const [command, ...args] = packageRunnerCommand( + "npx", + packageSpecifier, + process.platform, + ); + // npm can satisfy the exact pin from a same-version local checkout. An + // empty owned cwd prevents a Git-installed plugin or caller project from + // shadowing the registry package with unbuilt/different local files. + let workingDirectory; + try { + workingDirectory = await mkdtemp(join(tmpdir(), "rea-plugin-launcher-")); + } catch (cause) { + process.stderr.write( + `REA plugin could not create its working directory: ${cause.message}\n`, + ); + process.exitCode = 1; + return; + } + const child = spawn(command, args, { + cwd: workingDirectory, + stdio: "inherit", + shell: false, + }); + let spawnFailed = false; + const signals = new Map(); + for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) { + const forward = () => { + if (child.exitCode === null && child.signalCode === null) + child.kill(signal); + }; + signals.set(signal, forward); + process.on(signal, forward); + } + const stopForwarding = () => { + for (const [signal, listener] of signals) process.off(signal, listener); + }; + child.once("error", (cause) => { + spawnFailed = true; + stopForwarding(); + process.stderr.write( + `REA plugin could not start ${command}: ${cause.message}\n`, + ); + process.exitCode = 1; + }); + child.once("close", async (code, signal) => { + stopForwarding(); + let cleanupFailed = false; + try { + await rm(workingDirectory, { recursive: true }); + } catch (cause) { + cleanupFailed = true; + process.stderr.write( + `REA plugin retained its working directory at ${workingDirectory}: ${cause.message}\n`, + ); + } + if (spawnFailed) return; + if (signal !== null && process.platform !== "win32") { + // Preserve signal termination after the owned child has closed its streams. + process.kill(process.pid, signal); + } else { + process.exitCode = + code === 0 && cleanupFailed + ? 1 + : (code ?? 128 + (constants.signals[signal] ?? 1)); + } + }); +} diff --git a/scripts/verify-package-pack.mjs b/scripts/verify-package-pack.mjs index f38d99909..a8c88a7eb 100644 --- a/scripts/verify-package-pack.mjs +++ b/scripts/verify-package-pack.mjs @@ -70,17 +70,26 @@ export async function verifyPackagePack({ root, workspace }) { if ( manifest.version !== packedManifest.version || manifest.skills !== "./skills" || + manifest.mcpServers?.rea?.command !== "node" || + (path.startsWith(".codex") && manifest.mcpServers?.rea?.cwd !== ".") || JSON.stringify(manifest.mcpServers?.rea?.args) !== JSON.stringify([ - "-y", + `${path.startsWith(".claude") ? "${CLAUDE_PLUGIN_ROOT}/" : "./"}scripts/plugin-mcp-launcher.mjs`, `${packedManifest.name}@${packedManifest.version}`, - "mcp", ]) ) throw new Error( `Packaged plugin ${path} does not match the exact runtime and canonical skill release`, ); } + for (const path of [ + "scripts/plugin-mcp-launcher.mjs", + "src/process/packageRunnerCommand.mjs", + ]) + if (!packedFiles.includes(`package/${path}`)) + throw new Error( + `Packaged plugin launcher dependency is missing: ${path}`, + ); if ( skill.includes(`${packedManifest.name}@latest`) || !skill.includes(`${packedManifest.name}@${packedManifest.version}`) diff --git a/src/application/ClientRegistrationIdentity.ts b/src/application/ClientRegistrationIdentity.ts index 6e7744698..53cf4ca4f 100644 --- a/src/application/ClientRegistrationIdentity.ts +++ b/src/application/ClientRegistrationIdentity.ts @@ -2,6 +2,7 @@ import { basename, isAbsolute, resolve } from "node:path"; import { valid } from "semver"; import { PRODUCT_IDENTITY } from "../identity.js"; +import { packageRunnerCommand } from "../process/packageRunnerCommand.mjs"; /** Package runners whose pinned launcher setup can register. */ export type PackageRunner = "npx" | "bunx"; @@ -53,14 +54,12 @@ export const withoutPackageRunnerIdentity = ( export const packageRunnerRegistrationCommand = ( runner: PackageRunner, platform: NodeJS.Platform = process.platform, -): readonly string[] => { - const command = - runner === "npx" - ? ["npx", "-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"] - : ["bunx", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"]; - // Both runners may be .cmd shims on Windows, which clients cannot spawn directly. - return platform === "win32" ? ["cmd.exe", "/d", "/c", ...command] : command; -}; +): readonly string[] => + packageRunnerCommand( + runner, + PRODUCT_IDENTITY.registrationPackageSpecifier, + platform, + ); /** Resolve a pinned npx launcher that stdio clients can spawn on the host. */ export const npxRegistrationCommand = ( diff --git a/src/process/packageRunnerCommand.d.mts b/src/process/packageRunnerCommand.d.mts new file mode 100644 index 000000000..c1fb477cc --- /dev/null +++ b/src/process/packageRunnerCommand.d.mts @@ -0,0 +1,6 @@ +/** Exact host argv for a pinned registry package's MCP entry point. */ +export function packageRunnerCommand( + runner: "npx" | "bunx", + packageSpecifier: string, + platform: NodeJS.Platform, +): readonly string[]; diff --git a/src/process/packageRunnerCommand.mjs b/src/process/packageRunnerCommand.mjs new file mode 100644 index 000000000..82cec0cd5 --- /dev/null +++ b/src/process/packageRunnerCommand.mjs @@ -0,0 +1,16 @@ +/** Host argv shared by setup registrations and the source-only plugin launcher. */ +export const packageRunnerCommand = (runner, packageSpecifier, platform) => { + if (runner !== "npx" && runner !== "bunx") + throw new Error("Unsupported package runner"); + // Windows cmd.exe consumes these tokens itself. Package registrations use + // exact registry references, never shell expressions or arbitrary operands. + if (!/^[@A-Za-z0-9_./+-]+$/u.test(packageSpecifier)) + throw new Error("Package runner requires a shell-safe registry reference"); + const command = + runner === "npx" + ? ["npx", "-y", packageSpecifier, "mcp"] + : ["bunx", packageSpecifier, "mcp"]; + // npm's .cmd shim is not a native executable. Disable cmd AutoRun, matching + // the setup registration policy, and keep all dynamic values out of syntax. + return platform === "win32" ? ["cmd.exe", "/d", "/c", ...command] : command; +}; diff --git a/tests/boundary/process/pluginMcpLauncher.test.ts b/tests/boundary/process/pluginMcpLauncher.test.ts new file mode 100644 index 000000000..9f47a1a7a --- /dev/null +++ b/tests/boundary/process/pluginMcpLauncher.test.ts @@ -0,0 +1,122 @@ +import { spawn } from "node:child_process"; +import { lstat, mkdir, writeFile } from "node:fs/promises"; +import { delimiter, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { expect, it, onTestFinished } from "vitest"; + +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +const launcher = fileURLToPath( + new URL("../../../scripts/plugin-mcp-launcher.mjs", import.meta.url), +); + +const start = (path: string, packageSpecifier = "rea-agents@6.4.0") => { + const child = spawn(process.execPath, [launcher, packageSpecifier], { + env: { + ...process.env, + PATH: `${path}${delimiter}${process.env.PATH ?? ""}`, + }, + stdio: "pipe", + }); + let stdout = ""; + let stderr = ""; + child.stdout.on( + "data", + (bytes: Buffer) => (stdout += bytes.toString("utf8")), + ); + child.stderr.on( + "data", + (bytes: Buffer) => (stderr += bytes.toString("utf8")), + ); + const closed = new Promise<{ + code: number | null; + signal: NodeJS.Signals | null; + stdout: string; + stderr: string; + }>((resolve, reject) => { + child.once("error", reject); + child.once("close", (code, signal) => + resolve({ code, signal, stdout, stderr }), + ); + }); + onTestFinished(async () => { + if (child.exitCode === null && child.signalCode === null) + child.kill("SIGKILL"); + await closed; + }); + return { child, closed }; +}; + +const fakeRunner = async (body: string) => { + const root = await createTestTempDirectory("rea-plugin-launcher-"); + const bin = join(root, "plugin with spaces", "bin"); + await mkdir(bin, { recursive: true }); + await writeFile(join(bin, "npx"), `#!${process.execPath}\n${body}\n`, { + mode: 0o755, + }); + return bin; +}; + +it.skipIf(process.platform === "win32")( + "passes the exact pin and protocol streams through the source-only plugin launcher", + async () => { + const bin = await fakeRunner(` + process.stderr.write(JSON.stringify(process.argv.slice(2))); + process.stdin.pipe(process.stdout); + process.stdin.on("end", () => { process.exitCode = 7; }); + `); + const { child, closed } = start(bin, "rea-agents@6.4.0-rc.1"); + child.stdin.end('{"jsonrpc":"2.0","id":1}\n'); + expect(await closed).toEqual({ + code: 7, + signal: null, + stdout: '{"jsonrpc":"2.0","id":1}\n', + stderr: '["-y","rea-agents@6.4.0-rc.1","mcp"]', + }); + }, +); + +it.skipIf(process.platform === "win32")( + "forwards termination to the live package-runner child before exiting", + async () => { + const bin = await fakeRunner(` + process.on("SIGTERM", () => { process.stderr.write("stopped"); process.exit(0); }); + process.stdout.write("ready"); + process.stdin.resume(); + `); + const { child, closed } = start(bin); + await new Promise((resolve, reject) => { + child.stdout.once("data", () => resolve()); + child.once("error", reject); + }); + child.kill("SIGTERM"); + expect(await closed).toMatchObject({ code: 0, stderr: "stopped" }); + }, +); + +it.skipIf(process.platform === "win32")( + "isolates local package resolution and removes the owned runner directory", + async () => { + const bin = await fakeRunner("process.stdout.write(process.cwd());"); + const { child, closed } = start(bin); + child.stdin.end(); + const result = await closed; + expect(result.code).toBe(0); + expect(result.stdout).toContain("rea-plugin-launcher-"); + expect(result.stdout).not.toBe(process.cwd()); + await expect(lstat(result.stdout)).rejects.toMatchObject({ + code: "ENOENT", + }); + }, +); + +it("rejects a shell expression instead of treating it as the pinned package", async () => { + const root = await createTestTempDirectory("rea-plugin-invalid-pin-"); + const { child, closed } = start(root, "rea-agents@6.4.0&echo wrong"); + child.stdin.end(); + expect(await closed).toMatchObject({ + code: 1, + stdout: "", + stderr: "REA plugin requires one exact rea-agents@VERSION pin.\n", + }); +}); diff --git a/tests/conformance/releaseConfiguration.test.ts b/tests/conformance/releaseConfiguration.test.ts index 7c9718765..65f785929 100644 --- a/tests/conformance/releaseConfiguration.test.ts +++ b/tests/conformance/releaseConfiguration.test.ts @@ -197,8 +197,12 @@ describe("plugin manifests", () => { version: packageJson.version, mcpServers: { rea: { - command: "npx", - args: ["-y", `${packageJson.name}@${packageJson.version}`, "mcp"], + command: "node", + args: [ + `${path.startsWith(".claude") ? "${CLAUDE_PLUGIN_ROOT}/" : "./"}scripts/plugin-mcp-launcher.mjs`, + `${packageJson.name}@${packageJson.version}`, + ], + ...(path.startsWith(".codex") ? { cwd: "." } : {}), }, }, }); diff --git a/tsconfig.build.json b/tsconfig.build.json index 1601f3a0a..e9675b4bc 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -2,9 +2,10 @@ "extends": "./tsconfig.json", "compilerOptions": { "rootDir": "src", - "types": ["node"] + "types": ["node"], + "allowJs": true }, - "include": ["src/**/*.ts"], + "include": ["src/**/*.ts", "src/process/packageRunnerCommand.mjs"], "exclude": [ "src/**/*.fixture.ts", "src/**/*.test.ts",