diff --git a/adapters/pi/adapter.sh b/adapters/pi/adapter.sh index be228cf56..fd8876773 100644 --- a/adapters/pi/adapter.sh +++ b/adapters/pi/adapter.sh @@ -134,6 +134,7 @@ set -- \ [ "$INTERACTIVE" = "1" ] || set -- "$@" -p "$MOSAIC_REQUEST" if [ -n "${MOSAIC_MODEL_EVENT_MONITOR:-}" ] && [ "$INTERACTIVE" != "1" ]; then STREAM="$(dirname "$0")/../../packages/plugins/harness/pi/model-stream.mjs" - exec node "$STREAM" pi "$MOSAIC_FIRST_OUTPUT_DIR" pi "$@" --mode json + exec node "$STREAM" pi "$MOSAIC_FIRST_OUTPUT_DIR" "${MOSAIC_PI_BIN:-pi}" "$@" --mode json fi -exec pi "$@" +# #1873 S2: the binary the harness module found (MOSAIC_PI_BIN, its path inside the sandbox). +exec "${MOSAIC_PI_BIN:-pi}" "$@" diff --git a/packages/cli/tests/launcher.test.mjs b/packages/cli/tests/launcher.test.mjs index a5e41bc2c..427898114 100644 --- a/packages/cli/tests/launcher.test.mjs +++ b/packages/cli/tests/launcher.test.mjs @@ -266,6 +266,31 @@ test("bus start --pm: the launcher instance (the chief of staff) runs under its assert.equal(end.exitCode, 0); }); +// #1873 pi-unpin S1/S2: the version label comes from the pi the module finds. A pi whose --version +// fails gives a null label, and the launch still goes ahead. +test("pi-unpin: a pi named by MOSAIC_PI_BIN that exits 1 on --version records a null harnessVersion and still launches", { skip, timeout: 30000 }, async (t) => { + const prepared = prepare(t); + const pkg = join(prepared.root, "pi-prefix", "lib", "node_modules", "@earendil-works", "pi-coding-agent"); + mkdirSync(join(pkg, "dist", "bundle"), { recursive: true }); + writeFileSync(join(pkg, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "3.0.0" })); + writeFileSync(join(pkg, "dist", "bundle", "cli.js"), "#!/bin/sh\n[ \"$1\" = --version ] && exit 1\nexit 0\n", { mode: 0o755 }); + mkdirSync(join(prepared.root, "pi-prefix", "bin")); + const bin = join(prepared.root, "pi-prefix", "bin", "pi"); + symlinkSync("../lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js", bin); + prepared.f.env.MOSAIC_PI_BIN = bin; + // env() reads the bus's own environment, as the launcher's is process.env outside tests. + const before = process.env.MOSAIC_PI_BIN; + process.env.MOSAIC_PI_BIN = bin; + t.after(() => { if (before === undefined) delete process.env.MOSAIC_PI_BIN; else process.env.MOSAIC_PI_BIN = before; }); + const { f, launcher, close } = await setup(t, (doc) => doc, prepared, { harnessVersion: undefined }); + const chief = await launcher.launchPm(); + assert.equal(chief.harness, "pi"); + const [s] = readSessions(f.dataRoot); + const manifest = JSON.parse(readFileSync(join(s.runDir, "bundle", "manifest.json"), "utf8")); + assert.equal(manifest.harnessVersion, null); + assert.equal(await close(), 0); +}); + test("the chief of staff launches a coder through its launch tool; the coder answers; refusals name their code", { skip, timeout: 30000 }, async (t) => { const { f, launcher, client, cto } = await setup(t); const sock = launchSocketPath(f.dataRoot); diff --git a/packages/plugins/README.md b/packages/plugins/README.md index b4e28dd7b..2bcac8dc2 100644 --- a/packages/plugins/README.md +++ b/packages/plugins/README.md @@ -246,10 +246,23 @@ export returns: `minimal`, `low`, `medium`, `high`, `xhigh` and `max` as `--thinking`, Claude Code takes `low`, `medium`, `high`, `xhigh` and `max` as `--effort`. -- `preflight({env})` returns `null` or `{code, message}`: pi checks its - binary in `node_modules` (`harness-binary-missing`), Claude Code its +- `preflight({env})` returns `null` or `{code, message}`: pi checks that + it finds a pi binary (`harness-binary-missing`), Claude Code its session credential (`no-session-credential`) and `MOSAIC_CLAUDE_BIN`. -- `version({env})` is what the manifest records as `harnessVersion`. + Pi (#1873 pi-unpin, `harness/pi/binary.mjs`) takes `MOSAIC_PI_BIN`, + which must be an absolute path to an executable file; else the first + `pi` on PATH, skipping the repository's own `node_modules/.bin`; else + the repository's copy. The binary must belong to the + `@earendil-works/pi-coding-agent` package. With none, the message is + "no pi found: set MOSAIC_PI_BIN, put pi on PATH, or run npm ci". No + version is pinned. Pi's `mounts` and `installRoots` hold the found + package's directory (the repository's whole `node_modules` for the + repository's copy, whose packages are hoisted beside pi), and its `env` + sets `MOSAIC_PI_BIN` to the binary's path inside the session, which the + adapter runs. A refusal names the variable or "the pi on PATH" or "the + repository's pi", never a host path. +- `version({env})` is what the manifest records as `harnessVersion`. Pi's + is the first line its binary prints for `--version`, or null. - `countsAccount()` says whether its launches spend `launch.account` and get the row 126 account checks. The same answer decides whether an account quota covers authority hires (#1873); the bus reads it once at start, so diff --git a/packages/plugins/harness/pi/binary.mjs b/packages/plugins/harness/pi/binary.mjs index 2e69dfe34..e1e34670d 100644 --- a/packages/plugins/harness/pi/binary.mjs +++ b/packages/plugins/harness/pi/binary.mjs @@ -2,7 +2,8 @@ // pinned. The version label is read from the binary (or its package.json), never compared to a // fixed one. The launcher, the bundle and the usage reader call these on the host. import { accessSync, constants, readFileSync, realpathSync, statSync } from "node:fs"; -import { dirname, join } from "node:path"; +import { dirname, isAbsolute, join, relative } from "node:path"; +import { homedir } from "node:os"; import { fileURLToPath } from "node:url"; import { spawnSync } from "node:child_process"; @@ -20,10 +21,51 @@ export const executable = (path) => { } }; -// The binary a session runs, with the name a refusal line uses for it, or why there is none. -export function locate() { - if (executable(REPO_BIN)) return { bin: REPO_BIN, label: "the repository's pi" }; - return { bin: null, problem: "pi isn't installed in the repository's node_modules; run npm ci in the repository" }; +const REPO_NODE_MODULES = join(REPO, "node_modules"); +const realOrNull = (path) => { try { return realpathSync(path); } catch { return null; } }; +const inside = (path, root) => root === "/" || path === root || path.startsWith(root + "/"); + +// #1873 S2: the binary a session runs, with the name a refusal line uses for it (never a path): +// MOSAIC_PI_BIN, which must be an absolute path to an executable file; else the first executable +// pi on PATH, skipping the repository's own node_modules/.bin (a session PATH starts with it, so +// the bus's own PATH and a session's give the same answer); else the repository's copy. The binary +// must belong to the pi package: its package directory (or, for the repository's copy, the +// repository's node_modules) is what the sandbox mounts. The answer: { bin, label, root, view, +// dest } or { bin: null, problem }. root is the real directory mounted, dest where it is mounted +// (null: at root itself), view the binary's path inside the session. +export function locate(env = {}) { + if (env.MOSAIC_PI_BIN !== undefined && env.MOSAIC_PI_BIN !== "") { + const bin = env.MOSAIC_PI_BIN; + if (typeof bin !== "string" || !isAbsolute(bin) || !executable(bin)) return { bin: null, problem: "MOSAIC_PI_BIN isn't an executable file at an absolute path" }; + return placed(bin, "MOSAIC_PI_BIN", env); + } + const repoBin = realOrNull(join(REPO_NODE_MODULES, ".bin")); + for (const dir of String(env.PATH ?? "").split(":")) { + if (!isAbsolute(dir)) continue; + const real = realOrNull(dir); + if (real === null || (repoBin !== null && real === repoBin)) continue; + if (executable(join(dir, "pi"))) return placed(join(dir, "pi"), "the pi on PATH", env); + } + if (executable(REPO_BIN)) return placed(REPO_BIN, "the repository's pi", env); + return { bin: null, problem: "no pi found: set MOSAIC_PI_BIN, put pi on PATH, or run npm ci" }; +} + +function placed(bin, label, env) { + const pkg = packageDir(bin); + const realBin = realOrNull(bin); + if (!pkg || !realBin) return { bin: null, problem: `${label} isn't part of the ${PACKAGE} package` }; + // The repository's copy keeps the mount every session has had: all of node_modules, at its own + // path, since its packages are hoisted beside pi. + const repoReal = realOrNull(REPO_NODE_MODULES); + if (repoReal !== null && inside(pkg, repoReal)) { + return { bin, label, root: repoReal, dest: REPO_NODE_MODULES, view: join(REPO_NODE_MODULES, relative(repoReal, realBin)) }; + } + // Any other copy: its package directory alone, at its real path. npm nests a global install's + // dependencies inside it; a copy that needs packages beside it fails the fit check (S3). + // A package directory that holds the home directory or the repository would mount them. + const held = [homedir(), env.HOME, REPO].filter((p) => typeof p === "string" && isAbsolute(p)).map((p) => realOrNull(p) ?? p); + if (held.some((p) => inside(p, pkg))) return { bin: null, problem: `${label}'s package directory holds the home directory or the repository` }; + return { bin, label, root: pkg, dest: null, view: realBin }; } // The package directory that holds the binary's real file: the nearest directory above it whose @@ -31,7 +73,7 @@ export function locate() { export function packageDir(bin) { let dir; try { dir = dirname(realpathSync(bin)); } catch { return null; } - for (;;) { + for (let depth = 0; depth < 32; depth++) { let pkg = null; try { pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); } catch { pkg = null; } if (pkg && typeof pkg === "object" && pkg.name !== undefined) return pkg.name === PACKAGE ? dir : null; @@ -39,6 +81,7 @@ export function packageDir(bin) { if (up === dir) return null; dir = up; } + return null; } // The found package's own version, a file read with no spawn, or null. diff --git a/packages/plugins/harness/pi/index.mjs b/packages/plugins/harness/pi/index.mjs index 6cbb638fe..07a08e921 100644 --- a/packages/plugins/harness/pi/index.mjs +++ b/packages/plugins/harness/pi/index.mjs @@ -3,7 +3,7 @@ // Pi extension, which stays in packages/harness (a module can't change that boundary). The // launcher, the bundle and the usage reader call these on the host; the runner gets the answers // as data in session.json. packages/plugins/README.md lists the interface. -import { lstatSync, mkdirSync, realpathSync, writeFileSync } from "node:fs"; +import { lstatSync, mkdirSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; @@ -30,7 +30,7 @@ export const adapter = () => join(REPO, "adapters", "pi", "adapter.sh"); export const levels = () => LEVELS; export const outputPolicy = ({ proxy }) => proxy ? "non-newline-stdout" : "stdout"; -// The session runs pi from the repository's node_modules, which the sandbox mounts. +// The session runs the pi binary.mjs finds, from the package directory the sandbox mounts. export function preflight({ env = {}, proxy = null } = {}) { if (!(typeof proxy?.key === "string" && proxy.key) && !["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY", "ZAI_API_KEY"].some(name => Boolean(env[name]))) { @@ -49,11 +49,21 @@ export function version({ env = {} } = {}) { // Pi sessions run on a provider key, never the Claude account limit. export const countsAccount = () => false; -export const mounts = () => [ - { src: join(REPO, "packages/plugins/harness/pi/model-stream.mjs"), why: "the managed model event stream" }, - { src: realpathSync(join(REPO, "node_modules")), dest: join(REPO, "node_modules"), why: "pi and its packages, on the session's PATH" }, - ...Object.values(UNSLOP).map((src) => ({ src, why: "the unslop check the session's second extension runs" })), -]; +// #1873 S2: the found pi's package directory (the repository's copy: all of node_modules, as before). +// One under /usr is already in every sandbox. +const found = (env) => { + const at = locate(env); + if (!at.bin) throw new Error(at.problem); + return at; +}; +export function mounts({ env = {} } = {}) { + const at = found(env); + return [ + { src: join(REPO, "packages/plugins/harness/pi/model-stream.mjs"), why: "the managed model event stream" }, + ...(at.root.startsWith("/usr/") ? [] : [{ src: at.root, ...(at.dest ? { dest: at.dest } : {}), why: `pi and its packages (${at.label})` }]), + ...Object.values(UNSLOP).map((src) => ({ src, why: "the unslop check the session's second extension runs" })), + ]; +} // Pi has no web tool of its own, so a granted role under harness-builtin is refused. export const builtinWeb = () => false; export const builtins = ({ tools }) => [...tools]; @@ -101,9 +111,12 @@ export function bundle({ dir, models, proxy = null, transports = {} } = {}) { return { files: { proxyModels: file }, digests: [["../home/.pi/agent/models.json", createHash("sha256").update(text).digest("hex")]], sources }; } -// The tool limit is the built-ins plus the typed tools, which the extension serves. -export function env({ policy, tools, session, proxy = null }) { +// The tool limit is the built-ins plus the typed tools, which the extension serves. #1873 S2: +// MOSAIC_PI_BIN is the found binary's path inside the session; the bus's own environment names it +// (env defaults to it, since the launcher and the Triage host call env() without one). +export function env({ policy, tools, session, proxy = null, env: hostEnv = process.env }) { return { + MOSAIC_PI_BIN: found(hostEnv).view, PI_OFFLINE: "1", MOSAIC_TOOLS: [...policy.tools, ...tools.map((t) => t.name)].join(","), MOSAIC_EXTENSIONS: [EXTENSION, UNSLOP.unslopExtension].join(","), @@ -118,9 +131,10 @@ export function env({ policy, tools, session, proxy = null }) { // adapter and mounts live in. A hosted session's host (Triage) takes harnessEnv names and mount // sources only from these; launches don't read them. The host refuses every MOSAIC_* name from a // route, so MOSAIC_TOOLS, MOSAIC_EXTENSIONS and MOSAIC_THINKING are listed only to say what env() -// hands a session: a hosted pi needs the host to set them itself (a later slice). -export const envNames = Object.freeze(["PI_OFFLINE", "MOSAIC_TOOLS", "MOSAIC_EXTENSIONS", "PI_PROVIDER", "PI_MODEL", "MOSAIC_THINKING"]); -export const installRoots = () => [join(REPO, "adapters", "pi"), join(REPO, "packages", "plugins", "harness", "pi"), realpathSync(join(REPO, "node_modules")), join(REPO, "tools", "unslop-hook")]; +// hands a session: a hosted pi needs the host to set them itself (a later slice). MOSAIC_PI_BIN +// (#1873 S2) is the binary's path inside the session, which the host keeps from its own env() call. +export const envNames = Object.freeze(["MOSAIC_PI_BIN", "PI_OFFLINE", "MOSAIC_TOOLS", "MOSAIC_EXTENSIONS", "PI_PROVIDER", "PI_MODEL", "MOSAIC_THINKING"]); +export const installRoots = ({ env = {} } = {}) => [join(REPO, "adapters", "pi"), join(REPO, "packages", "plugins", "harness", "pi"), found(env).root, join(REPO, "tools", "unslop-hook")]; // The extension writes the turn marker at agent_end; an exit without it is a failed turn. export const turnEnd = () => "marker"; diff --git a/packages/plugins/tests/harness.test.mjs b/packages/plugins/tests/harness.test.mjs index bb32851e4..0b24f9aa3 100644 --- a/packages/plugins/tests/harness.test.mjs +++ b/packages/plugins/tests/harness.test.mjs @@ -3,7 +3,7 @@ // harness outside the exceptions the brief lists. import test from "node:test"; import assert from "node:assert/strict"; -import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -140,10 +140,15 @@ test("row 65 a route's thinking reaches pi as --thinking and claude as --effort, const pi = await load("pi"), claude = await load("claude-code"); const dir = scratch(t); mkdirSync(join(dir, "bin")); - for (const name of ["pi", "claude"]) { - writeFileSync(join(dir, "bin", name), '#!/bin/sh\nprintf "%s\\n" "$@" > "$ARGV_OUT"\necho \'{"type":"result","subtype":"success","result":"ok"}\'\n'); - chmodSync(join(dir, "bin", name), 0o755); + // #1873 S2: pi's stand-in sits in a pi package, as the module requires, and is found on PATH. + const piPackage = join(dir, "lib", "node_modules", "@earendil-works", "pi-coding-agent"); + mkdirSync(join(piPackage, "dist", "bundle"), { recursive: true }); + writeFileSync(join(piPackage, "package.json"), JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.0.1" })); + for (const file of [join(dir, "bin", "claude"), join(piPackage, "dist", "bundle", "cli.js")]) { + writeFileSync(file, '#!/bin/sh\nprintf "%s\\n" "$@" > "$ARGV_OUT"\necho \'{"type":"result","subtype":"success","result":"ok"}\'\n'); + chmodSync(file, 0o755); } + symlinkSync(join(piPackage, "dist", "bundle", "cli.js"), join(dir, "bin", "pi")); for (const f of ["prompt.md", "settings.json", "mcp.json"]) writeFileSync(join(dir, f), "{}"); const run = (adapter, moduleEnv) => { const out = join(dir, "argv"); @@ -165,7 +170,7 @@ test("row 65 a route's thinking reaches pi as --thinking and claude as --effort, }; for (const thinking of ["xhigh", "low"]) { const session = { provider: "fixture", model: "m", thinking, toolSocket: "/run/tools.sock" }; - assert.equal(flag(run("pi", pi.env({ policy: { tools: ["read"] }, tools: [], session })), "--thinking"), thinking); + assert.equal(flag(run("pi", pi.env({ policy: { tools: ["read"] }, tools: [], session, env: { PATH: `${join(dir, "bin")}:/usr/bin:/bin` } })), "--thinking"), thinking); const files = { settings: join(dir, "settings.json"), mcp: join(dir, "mcp.json") }; assert.equal(flag(run("claude", claude.env({ files, policy: { tools: ["read"], typed: [] }, session })), "--effort"), thinking); } diff --git a/packages/plugins/tests/pi-binary.test.mjs b/packages/plugins/tests/pi-binary.test.mjs index 598787100..4bc464a60 100644 --- a/packages/plugins/tests/pi-binary.test.mjs +++ b/packages/plugins/tests/pi-binary.test.mjs @@ -3,10 +3,12 @@ // compaction count records the found package's own version. import test from "node:test"; import assert from "node:assert/strict"; -import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { spawnSync } from "node:child_process"; +import { sandboxProblem } from "../../seat/src/sandbox.mjs"; const REPO = resolve(fileURLToPath(new URL("../../../", import.meta.url))); const MODULE = join(REPO, "packages", "plugins", "harness", "pi"); @@ -74,3 +76,115 @@ test("pi-unpin S1: the repository's real pi reports its installed package's vers const installed = JSON.parse(readFileSync(join(REPO, "node_modules", NAME, "package.json"), "utf8")).version; assert.equal(pi.version({ env: {} }), installed); }); + +// #1873 pi-unpin (design section 5, S2): the binary comes from MOSAIC_PI_BIN, else the first pi on +// PATH, else the repository's copy. Mounts, install roots and the session's MOSAIC_PI_BIN follow +// the package that binary belongs to. A refusal names the variable, never a path. +const real = await import(pathToFileURL(join(MODULE, "index.mjs")).href); +const CREDENTIAL = { ZAI_API_KEY: "fixture-zai" }; +const ARGV_SCRIPT = '#!/bin/sh\n[ "$1" = --version ] && { echo 7.7.7; exit 0; }\nprintf "%s\\n" "$@" > "$ARGV_OUT"\n'; + +// npm's global layout: prefix/lib/node_modules/, with prefix/bin/pi a link to its bin. +function prefix(t, script = ARGV_SCRIPT, version = "7.7.0") { + const root = join(scratch(t), "prefix"); + const cli = standIn(join(root, "lib", "node_modules"), script, version); + mkdirSync(join(root, "bin"), { recursive: true }); + symlinkSync(`../lib/node_modules/${NAME}/dist/bundle/cli.js`, join(root, "bin", "pi")); + return { root, bin: join(root, "bin", "pi"), cli: realpathSync(cli), pkg: realpathSync(join(root, "lib", "node_modules", NAME)) }; +} +const session = { provider: "fixture", model: "m", thinking: "low", toolSocket: "/run/tools.sock" }; +const piEnv = (env) => real.env({ policy: { tools: ["read"] }, tools: [], session, env }); +const noPath = (problem, ...paths) => { for (const p of paths) assert.ok(!problem.message.includes(p), problem.message); }; + +test("pi-unpin S2: a stand-in pi in an npm prefix, named by MOSAIC_PI_BIN, is found, mounted alone and run from the mount", async t => { + const p = prefix(t); + const env = { ...CREDENTIAL, MOSAIC_PI_BIN: p.bin, PATH: "/usr/bin:/bin" }; + assert.equal(real.preflight({ env }), null); + assert.equal(real.version({ env }), "7.7.7"); + const mounts = real.mounts({ env }); + assert.deepEqual(mounts.filter(m => (m.dest ?? m.src) === p.pkg || m.src === p.pkg).map(m => m.src), [p.pkg]); + assert.ok(!mounts.some(m => (m.dest ?? m.src) === join(REPO, "node_modules")), "the repository's node_modules is not mounted"); + const roots = real.installRoots({ env }); + assert.ok(roots.includes(p.pkg)); + assert.ok(!roots.includes(realpathSync(join(REPO, "node_modules")))); + const given = piEnv(env); + assert.equal(given.MOSAIC_PI_BIN, p.cli, "the session runs the real file inside the mounted package"); + assert.ok(real.envNames.includes("MOSAIC_PI_BIN")); + + // Run the real adapter in a sandbox that holds the system, the adapter and the module's mounts, + // and not the repository's node_modules: the stand-in records the argv it was given. + if (sandboxProblem()) return t.skip("no usable bwrap"); + const out = join(scratch(t), "out"); + mkdirSync(out); + writeFileSync(join(out, "prompt.md"), "p"); + const argv = ["/usr/bin/bwrap", "--unshare-user", "--unshare-pid", "--unshare-net", "--die-with-parent", "--clearenv", "--ro-bind", "/usr", "/usr"]; + for (const link of ["/bin", "/sbin", "/lib", "/lib64"]) { + if (!existsSync(link)) continue; + if (lstatSync(link).isSymbolicLink()) argv.push("--symlink", readlinkSync(link), link); + else argv.push("--ro-bind", link, link); + } + argv.push("--proc", "/proc", "--dev", "/dev", "--ro-bind", join(REPO, "adapters", "pi"), join(REPO, "adapters", "pi")); + for (const m of mounts) argv.push("--ro-bind", m.src, m.dest ?? m.src); + // The extensions the adapter checks for, which a launch's bundle binds. + for (const e of given.MOSAIC_EXTENSIONS.split(",")) argv.push("--ro-bind", e, e); + argv.push("--bind", out, out); + for (const [k, v] of Object.entries({ ...given, PATH: "/usr/bin:/bin", ARGV_OUT: join(out, "argv"), MOSAIC_SYSTEM_PROMPT_FILE: join(out, "prompt.md"), + MOSAIC_REQUEST: "x", MOSAIC_WORKSPACE: join(out, "ws"), MOSAIC_SESSION_DIR: join(out, "session"), MOSAIC_MODEL: "m" })) argv.push("--setenv", k, v); + argv.push("/bin/sh", join(REPO, "adapters", "pi", "adapter.sh")); + const r = spawnSync(argv[0], argv.slice(1), { encoding: "utf8", timeout: 20000 }); + assert.equal(r.status, 0, r.stderr); + const ran = readFileSync(join(out, "argv"), "utf8").split("\n"); + assert.ok(ran.includes("--no-context-files") && ran.includes("--thinking"), ran.join(" ")); +}); + +test("pi-unpin S2: a relative or non-executable MOSAIC_PI_BIN is refused with harness-binary-missing, naming the variable only", async t => { + const p = prefix(t); + const plain = join(scratch(t), "pi"); + writeFileSync(plain, "#!/bin/sh\n", { mode: 0o644 }); + for (const bin of ["bin/pi", "pi", plain, join(p.root, "missing")]) { + const problem = real.preflight({ env: { ...CREDENTIAL, MOSAIC_PI_BIN: bin, PATH: `${join(p.root, "bin")}:/usr/bin:/bin` } }); + assert.deepEqual([problem?.code, problem?.message], ["harness-binary-missing", "MOSAIC_PI_BIN isn't an executable file at an absolute path"], bin); + noPath(problem, plain, p.root); + assert.equal(real.version({ env: { MOSAIC_PI_BIN: bin } }), null, "no fallback to another pi"); + } +}); + +test("pi-unpin S2: with MOSAIC_PI_BIN unset the first pi on PATH is used, and the repository's own .bin on PATH does not count", async t => { + const p = prefix(t); + const env = { ...CREDENTIAL, PATH: `${join(REPO, "node_modules", ".bin")}:/nonexistent:relative:${join(p.root, "bin")}:/usr/bin:/bin` }; + assert.equal(real.preflight({ env }), null); + assert.equal(real.version({ env }), "7.7.7"); + assert.equal(piEnv(env).MOSAIC_PI_BIN, p.cli); + assert.ok(real.mounts({ env }).some(m => m.src === p.pkg)); +}); + +test("pi-unpin S2: with neither, the repository's copy is used and mounted as before", async () => { + for (const PATH of ["/usr/bin:/bin", `${join(REPO, "node_modules", ".bin")}:/usr/bin:/bin`]) { + const env = { ...CREDENTIAL, PATH }; + assert.equal(real.preflight({ env }), null, PATH); + const nm = realpathSync(join(REPO, "node_modules")); + assert.deepEqual(real.mounts({ env }).filter(m => m.dest === join(REPO, "node_modules")).map(m => m.src), [nm]); + assert.ok(real.installRoots({ env }).includes(nm)); + const bin = piEnv(env).MOSAIC_PI_BIN; + assert.ok(bin.startsWith(join(REPO, "node_modules") + "/"), bin); + assert.equal(realpathSync(bin), realpathSync(join(REPO, "node_modules", ".bin", "pi"))); + } +}); + +test("pi-unpin S2: a pi that is not in a pi package is refused, and so is a pi that cannot be found at all", async t => { + const dir = join(scratch(t), "bin"); + mkdirSync(dir); + writeFileSync(join(dir, "pi"), "#!/bin/sh\necho 1.0.0\n"); + chmodSync(join(dir, "pi"), 0o755); + let problem = real.preflight({ env: { ...CREDENTIAL, PATH: `${dir}:/usr/bin:/bin` } }); + assert.deepEqual([problem?.code, problem?.message], ["harness-binary-missing", `the pi on PATH isn't part of the ${NAME} package`]); + problem = real.preflight({ env: { ...CREDENTIAL, MOSAIC_PI_BIN: join(dir, "pi") } }); + assert.deepEqual([problem?.code, problem?.message], ["harness-binary-missing", `MOSAIC_PI_BIN isn't part of the ${NAME} package`]); + noPath(problem, dir); + // The scratch copy has no node_modules of its own: no pi anywhere. + const { root, pi } = await copyRepo(t, "#!/bin/sh\n", "1.0.0"); + rmSync(join(root, "node_modules"), { recursive: true }); + problem = pi.preflight({ env: { ...CREDENTIAL, PATH: "/usr/bin:/bin" } }); + assert.deepEqual([problem?.code, problem?.message], ["harness-binary-missing", "no pi found: set MOSAIC_PI_BIN, put pi on PATH, or run npm ci"]); + assert.throws(() => pi.env({ policy: { tools: [] }, tools: [], session, env: { PATH: "/usr/bin:/bin" } }), /no pi found/); +}); diff --git a/packages/seat/src/session.mjs b/packages/seat/src/session.mjs index 60964627f..a3932cb6d 100644 --- a/packages/seat/src/session.mjs +++ b/packages/seat/src/session.mjs @@ -254,7 +254,7 @@ export const ENV_ALLOW = Object.freeze([ "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TZ", "TERM", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "OPENROUTER_API_KEY", "ZAI_API_KEY", - "MOSAIC_CLAUDE_BIN", + "MOSAIC_CLAUDE_BIN", "MOSAIC_PI_BIN", ]); // The ways a Claude Code session can log in, each a set of variables that diff --git a/packages/seat/tests/session.test.mjs b/packages/seat/tests/session.test.mjs index 08b3d051c..807c68558 100644 --- a/packages/seat/tests/session.test.mjs +++ b/packages/seat/tests/session.test.mjs @@ -58,6 +58,15 @@ test("sessionEnv passes only the allowlist, the repo's bin on PATH, and the run assert.equal(sessionEnv({ MOSAIC_CLAUDE_BIN: "/opt/claude" }, "r0123456789ab").MOSAIC_CLAUDE_BIN, "/opt/claude"); }); +// #1873 pi-unpin S2: the host's MOSAIC_PI_BIN reaches the session, as MOSAIC_CLAUDE_BIN does, and +// it is the only name the slice adds: every other MOSAIC_* and PI_* name from the host stays out. +test("pi-unpin S2: sessionEnv passes MOSAIC_PI_BIN and nothing else new", () => { + const env = sessionEnv({ MOSAIC_PI_BIN: "/opt/pi/bin/pi", PI_CODING_AGENT_DIR: "/h/.pi", PI_OFFLINE: "0", MOSAIC_PI_ROOT: "/x", PATH: "/usr/bin" }, "r0123456789ab"); + assert.deepEqual(Object.keys(env).sort(), ["MOSAIC_PI_BIN", "MOSAIC_RUN_ID", "PATH"]); + assert.equal(env.MOSAIC_PI_BIN, "/opt/pi/bin/pi"); + assert.deepEqual(ENV_ALLOW.filter((k) => k.startsWith("MOSAIC_")), ["MOSAIC_CLAUDE_BIN", "MOSAIC_PI_BIN"]); +}); + test("ZAI_API_KEY passes the session allowlist, and ZAI_TOKEN does not", () => { assert.ok(ENV_ALLOW.includes("ZAI_API_KEY")); const env = sessionEnv({ ZAI_API_KEY: "fixture-zai", ZAI_TOKEN: "t" }, "r0123456789ab"); diff --git a/packages/webui/src/triage-host.mjs b/packages/webui/src/triage-host.mjs index 71f1b5052..8fe9c0c4c 100644 --- a/packages/webui/src/triage-host.mjs +++ b/packages/webui/src/triage-host.mjs @@ -127,8 +127,8 @@ const CAP = /^[0-9a-f]{64}$/; // The spawn's environment: these names from the Console's own environment, PATH fixed, and the // route's proxy variables. bwrap sets HOME and TMPDIR inside. export const SPAWN_ENV_ALLOW = Object.freeze(["PATH", "LANG", "LC_ALL", "TZ", "TERM"]); -// Passed only as an absolute path: the pinned harness binary (packages/seat/src/session.mjs ENV_ALLOW). -export const SPAWN_PATH_ALLOW = Object.freeze(["MOSAIC_CLAUDE_BIN"]); +// Passed only as an absolute path: a harness binary the Console names (packages/seat/src/session.mjs ENV_ALLOW). +export const SPAWN_PATH_ALLOW = Object.freeze(["MOSAIC_CLAUDE_BIN", "MOSAIC_PI_BIN"]); // The names the runner sets for every harness (runner.mjs adapterEnv); the host's own names never replace them. const RUNNER_NAMES = new Set(["MOSAIC_SYSTEM_PROMPT_FILE", "MOSAIC_WORKSPACE", "MOSAIC_SESSION_DIR", "MOSAIC_POLICY_FILE", "MOSAIC_TOOLS_FILE", "MOSAIC_TOOL_SOCKET", "MOSAIC_TURN_MARKER", "MOSAIC_PROVIDER", "MOSAIC_MODEL", "MOSAIC_MODEL_ACTIVITY_DIR", "MOSAIC_UNSLOP_LOG", diff --git a/packages/webui/tests/triage-host.test.mjs b/packages/webui/tests/triage-host.test.mjs index e7c13c9a2..6db74e48f 100644 --- a/packages/webui/tests/triage-host.test.mjs +++ b/packages/webui/tests/triage-host.test.mjs @@ -58,9 +58,13 @@ test("triageEnv keeps the fixed names and the route's proxy variables, and nothi assert.equal(triageEnv(CONSOLE_ENV, { ANTHROPIC_API_KEY: "from-the-route" }).ANTHROPIC_API_KEY, "from-the-route", "the route's key under the name its harness takes"); assert.equal(triageEnv(CONSOLE_ENV).ANTHROPIC_API_KEY, undefined, "a key in the Console's environment is not the route's"); // #1873 triage-wiring: the pinned harness binary passes as an absolute path, as a bus session's does. - assert.deepEqual(SPAWN_PATH_ALLOW, ["MOSAIC_CLAUDE_BIN"]); + // #1873 pi-unpin S2: and so does the pi binary the Console names, under the same checks. + assert.deepEqual(SPAWN_PATH_ALLOW, ["MOSAIC_CLAUDE_BIN", "MOSAIC_PI_BIN"]); assert.equal(triageEnv({ ...CONSOLE_ENV, MOSAIC_CLAUDE_BIN: "/opt/claude/bin/claude" }).MOSAIC_CLAUDE_BIN, "/opt/claude/bin/claude"); - for (const bad of ["claude", "bin/claude", "/opt/a\nb", "/" + "x".repeat(300)]) assert.equal(triageEnv({ ...CONSOLE_ENV, MOSAIC_CLAUDE_BIN: bad }).MOSAIC_CLAUDE_BIN, undefined, bad); + assert.equal(triageEnv({ ...CONSOLE_ENV, MOSAIC_PI_BIN: "/opt/pi/bin/pi" }).MOSAIC_PI_BIN, "/opt/pi/bin/pi"); + for (const name of SPAWN_PATH_ALLOW) { + for (const bad of ["claude", "bin/claude", "/opt/a\nb", "/" + "x".repeat(300)]) assert.equal(triageEnv({ ...CONSOLE_ENV, [name]: bad })[name], undefined, `${name} ${bad}`); + } }); test("the relay refuses every verb but a message to the person, and any call without the capability", async (t) => { @@ -438,7 +442,9 @@ test("a host whose HOME holds the repository starts the shipped pi harness's own // triage-wiring); the module's PI_PROVIDER is not the host's to set. const own = Object.fromEntries(Object.entries(s.harnessEnv).filter(([k]) => !k.startsWith("MOSAIC_"))); assert.deepEqual(own, { PI_MODEL: "m", PI_OFFLINE: "1" }); - assert.deepEqual(Object.keys(s.harnessEnv).filter((k) => k.startsWith("MOSAIC_")).sort(), ["MOSAIC_EXTENSIONS", "MOSAIC_THINKING", "MOSAIC_TOOLS"]); + assert.deepEqual(Object.keys(s.harnessEnv).filter((k) => k.startsWith("MOSAIC_")).sort(), ["MOSAIC_EXTENSIONS", "MOSAIC_PI_BIN", "MOSAIC_THINKING", "MOSAIC_TOOLS"]); + // #1873 pi-unpin S2: the session runs the pi the module found, here the repository's copy. + assert.ok(s.harnessEnv.MOSAIC_PI_BIN.startsWith(join(REPO, "node_modules") + "/"), s.harnessEnv.MOSAIC_PI_BIN); // The same host and module, with HOME's own directory (which holds the repository) as an extra // install root and mount: it is under HOME and not in the code, so it is refused. const wide = { ...pi, installRoots: (o) => [...pi.installRoots(o), home] };