diff --git a/adapters/pi/adapter.sh b/adapters/pi/adapter.sh index fd8876773..4ea49eaf7 100644 --- a/adapters/pi/adapter.sh +++ b/adapters/pi/adapter.sh @@ -92,6 +92,11 @@ fi THINKING_FLAG="" [ -n "${MOSAIC_THINKING:-}" ] && THINKING_FLAG="--thinking $MOSAIC_THINKING" +# MCP (#1873 S3): the harness module sets MOSAIC_PI_NO_MCP=1 when the binary's --help lists +# --no-mcp, so MCP stays off by its own flag and not only as a side effect of --no-extensions. +NO_MCP_FLAG="" +[ "${MOSAIC_PI_NO_MCP:-}" = "1" ] && NO_MCP_FLAG="--no-mcp" + # Mode (M13): interactive TUI or one-shot print. PRINT_MODE="-p" REQUEST_ARG="" @@ -107,6 +112,7 @@ fi # --system-prompt replace the default prompt with the generated one, given # as the file's absolute path (checked above), never its text # --no-* no ambient context/skills/extensions/templates/themes +# NO_MCP_FLAG --no-mcp when the binary lists it, else nothing # EXT_FLAGS the explicitly provided extensions only (-e) # SESSION_FLAGS ephemeral | persistent | forked (per env) # TOOLS_FLAG per capabilities @@ -118,6 +124,7 @@ set -- \ --offline \ --no-approve \ --no-extensions \ + $NO_MCP_FLAG \ $EXT_FLAGS \ $SKILLS_FLAG \ --no-prompt-templates \ diff --git a/packages/cli/tests/launcher.test.mjs b/packages/cli/tests/launcher.test.mjs index 427898114..d89490f37 100644 --- a/packages/cli/tests/launcher.test.mjs +++ b/packages/cli/tests/launcher.test.mjs @@ -24,6 +24,7 @@ import { bootConfig, loadSystem } from "../src/config.mjs"; import { cmdlineOf, startHost, startTimeOf } from "../src/host.mjs"; import { createLauncher } from "../src/launcher.mjs"; import { mockAnthropic, REPO } from "../../harness/tests/helpers.mjs"; +import { piStandIn } from "../../harness/tests/pi-stand-in.mjs"; import { fakeHarnesses, fixture, HOST_CREDENTIALS, tmp, withoutHostCredentials } from "./helpers.mjs"; const FAKE = fileURLToPath(new URL("../../harness/tests/fixtures/fake-adapter.mjs", import.meta.url)); @@ -273,7 +274,8 @@ test("pi-unpin: a pi named by MOSAIC_PI_BIN that exits 1 on --version records a 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 }); + // #1873 S3: the stand-in passes the fit check; only its --version fails. + writeFileSync(join(pkg, "dist", "bundle", "cli.js"), piStandIn({ versionExit: 1 }), { 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); diff --git a/packages/harness/README.md b/packages/harness/README.md index 5dc337f35..ac9d590f5 100644 --- a/packages/harness/README.md +++ b/packages/harness/README.md @@ -18,13 +18,30 @@ Every harness layer below is a row S0 line (`docs/plans/2026-10-04_slice-1.md`, "What S6 can rely on"), and each bundle's `manifest.json` names the lines it relies on (`reliesOn`): -| | Pi | Claude Code | -|---|---|---| -| 1. block a tool | `tool_call` handler returns a block | PreToolUse command hook exits 2; `--bare` is never passed | -| 2. gate crash | a throw in the handler blocks | the hook runs as ` \|\| exit 2` | -| 3. gate missing | a missing `-e` file refuses to start | the wrapper blocks | -| 4. gate hang | the runner's wall clock plus the `agent_end` marker | `timeout -k 2 10 \|\| exit 2`, hook timeout 20 | -| 5. bash | limited only by the tool limit | limited only by the tool limit | +| | Pi | Claude Code | How pi's line is checked | +|---|---|---|---| +| 1. block a tool | `tool_call` handler returns a block | PreToolUse command hook exits 2; `--bare` is never passed | suites, on the repository's pi (`pi-session.test.mjs`) | +| 2. gate crash | a throw in the handler blocks | the hook runs as ` \|\| exit 2` | suites, on the repository's pi | +| 3. gate missing | a missing `-e` file refuses to start | the wrapper blocks | at every start, by the fit check, on the pi that runs; and suites | +| 4. gate hang | the runner's wall clock plus the `agent_end` marker | `timeout -k 2 10 \|\| exit 2`, hook timeout 20 | suites, on the repository's pi | +| 5. bash | limited only by the tool limit | limited only by the tool limit | suites, on the repository's pi | + +Pi is not pinned (#1873 pi-unpin). Before a session starts, `preflight` +and `env` run the fit check in `src/pi-fit.mjs` on the binary the module +found. It runs that binary in a sandbox with the network unshared, an +empty environment and a scratch home, and calls no model. It needs +`--help` to list every flag the adapter passes (with rpc mode and each +thinking level), a missing `-e` file to stop the start, and the planted +ambient sources (extensions, settings lists, `mcp.json` files, skills, +prompt templates, context files) to stay unloaded with the seal flags on. +A control run without the seal flags must load at least one of them, or +the check can't tell and refuses. Any failure refuses the launch with +`harness-feature-missing` and one line that names the binary by its label, +for example `pi 2.0.0 (MOSAIC_PI_BIN) lacks --no-context-files`. When +`--help` lists `--no-mcp`, the adapter passes it too. A pass is cached in +memory by a digest of the package's files. Lines 1, 2, 4 and 5 are not +checked at start; a pi other than the repository's copy relies on them +unproved until a scripted-model fit run exists (design section 5, S6). Claude Code also runs with `--restricted`: no user, project or local settings, file tools confined to the working directory, and no `CLAUDE.md` diff --git a/packages/harness/src/pi-fit.mjs b/packages/harness/src/pi-fit.mjs new file mode 100644 index 000000000..7022048ff --- /dev/null +++ b/packages/harness/src/pi-fit.mjs @@ -0,0 +1,233 @@ +// #1873 pi-unpin S3: the start-time fit check for a pi binary the harness module found. Nothing +// here compares a version. The check runs the binary only inside a sandbox with the network +// unshared, an empty environment, a scratch HOME and agent directory, and the found package +// mounted as a session mounts it. No model is called. It asks: +// +// --version a label for the refusal line and the record; not a gate +// --help lists every flag Mosaic passes, with rpc mode and each thinking level +// -e /missing a missing extension stops the start (exit non-zero) before any answer +// control with planted ambient sources and no seal flags, the binary answers get_state and +// loads at least one planted source, so the sealed run can tell +// sealed with the adapter's seal flags (and --no-mcp when --help lists it) and one -e +// extension, the binary answers get_state, loads that extension (a session's gate +// comes in that way) and loads none of the planted sources +// +// A check that cannot tell refuses: a sandbox that fails, a run that times out, an answer that +// doesn't parse. A pass is cached in memory by a digest of the files that run (the package's +// package.json, every file under dist/bundle/, and every file in the directory tree that holds +// the binary's real file) and the mount layout. +// A refusal line names the found binary by its label (MOSAIC_PI_BIN, the pi on PATH, the +// repository's pi), never a host path. +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, relative } from "node:path"; +import { BWRAP, checkArgv, sandboxProblem } from "../../seat/src/sandbox.mjs"; + +// The flags adapters/pi/adapter.sh and the conversation engine pass. +export const FIT_FLAGS = Object.freeze(["--mode", "--session", "--no-session", "--session-dir", "--fork", "-c", "--no-extensions", "-e", "--no-skills", "--skill", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-approve", "--offline", "--tools", "--no-tools", "--provider", "--model", "--thinking", "--system-prompt", "-p"]); +// The adapter's seal flags, as it passes them in an ephemeral session with no tools. +const SEAL = ["--offline", "--no-approve", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-tools", "--no-session"]; +const RUN_TIMEOUT = 20000; +const OUTPUT_MAX = 4 * 1024 * 1024; +const DIGEST_FILES_MAX = 20000; + +const passed = new Map(); + +// found: binary.mjs's answer ({ bin, label, root, dest, view, pkg }). levels: the thinking levels +// the module applies. Returns { ok: true, version, noMcp, digest } or { ok: false, message }. +export function piFit(found, { levels = [], bwrap = BWRAP, node = process.execPath } = {}) { + const who = (version) => `pi${version ? ` ${version}` : ""} (${found.label})`; + let digest; + try { + digest = filesDigest(found); + } catch { + return { ok: false, message: `${who(null)} can't be checked: its files can't be read` }; + } + const key = JSON.stringify([digest, found.root, found.dest ?? null, found.view, bwrap, node, levels]); + if (passed.has(key)) return passed.get(key); + // The sandbox's own error text can name a host path, so the line keeps only what failed. + const problem = sandboxProblem({ bwrap }); + if (problem) return { ok: false, message: `${who(null)} can't be checked: ${problem.startsWith("the sandbox (bwrap) is missing") ? "the sandbox (bwrap) is missing" : "the sandbox (bwrap) failed"}` }; + const scratch = mkdtempSync(join(tmpdir(), "mosaic-pi-fit-")); + try { + const result = check(found, { levels, bwrap, node, scratch, who, digest }); + if (result.ok) passed.set(key, result); + return result; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +} + +function check(found, { levels, bwrap, node, scratch, who, digest }) { + const run = (args, input = "") => runIn(found, { bwrap, node, scratch, args, input }); + plant(scratch); + const v = run(["--version"]); + const version = v.status === 0 ? versionLabel(v.stdout) : null; + const help = run(["--help"]); + if (help.status !== 0) return { ok: false, message: `${who(version)} can't be checked: --help failed` }; + const lines = help.stdout.split("\n"); + const has = (flag) => lines.some((l) => flagIn(l, flag)); + const line = (flag) => lines.find((l) => flagIn(l, flag)) ?? ""; + const missing = FIT_FLAGS.filter((f) => !has(f)); + if (has("--mode") && !word(line("--mode"), "rpc")) missing.push("--mode rpc"); + if (has("--thinking")) for (const l of levels) if (!word(line("--thinking"), l)) missing.push(`--thinking ${l}`); + if (missing.length) return { ok: false, message: `${who(version)} lacks ${missing.join(", ")}` }; + const noMcp = has("--no-mcp"); + const approve = has("--approve"); + + const ask = '{"id":"fit-state","type":"get_state"}\n{"id":"fit-commands","type":"get_commands"}\n'; + plant(scratch); + const missingExt = run(["-e", join(scratch, "missing", "extension.ts"), "--mode", "rpc", ...SEAL], ask); + if (missingExt.timedOut) return { ok: false, message: `${who(version)} can't be checked: a start with a missing -e extension timed out` }; + if (missingExt.status === 0 || answered(missingExt.stdout).state) return { ok: false, message: `${who(version)} starts with a missing -e extension` }; + + plant(scratch); + const control = run(["--mode", "rpc", "--no-session", "--offline", ...(approve ? ["--approve"] : [])], ask); + const controlAnswer = answered(control.stdout); + if (!controlAnswer.state) return { ok: false, message: `${who(version)} can't be checked: it didn't answer get_state` }; + if (seen(scratch, controlAnswer).length === 0) return { ok: false, message: `${who(version)} can't be checked: it loaded none of the planted sources without the seal flags` }; + + plant(scratch); + const sealed = run(["--mode", "rpc", ...SEAL, ...(noMcp ? ["--no-mcp"] : []), "-e", join(scratch, "explicit", "fit.ts"), "--system-prompt", join(scratch, "prompt.md")], ask); + const sealedAnswer = answered(sealed.stdout); + if (!sealedAnswer.state) return { ok: false, message: `${who(version)} can't be checked: it didn't answer get_state with the seal flags on` }; + if (!marked(scratch, EXPLICIT)) return { ok: false, message: `${who(version)} didn't load an -e extension with the seal flags on` }; + const leaked = seen(scratch, sealedAnswer); + if (leaked.length) return { ok: false, message: `${who(version)} loaded a planted ${leaked.join(", ")} with the seal flags on` }; + return { ok: true, version, noMcp, digest }; +} + +// The binary, inside the sandbox: the system part, the found package where a session sees it, and +// the scratch directory read-write. The environment holds HOME, the agent directory, TMPDIR, a +// PATH that finds node, and PI_OFFLINE. +function runIn(found, { bwrap, node, scratch, args, input }) { + const list = [ + { kind: "ro", src: found.root, ...(found.dest ? { dest: found.dest } : {}) }, + { kind: "rw", src: scratch }, + ]; + const env = { HOME: join(scratch, "home"), PI_CODING_AGENT_DIR: join(scratch, "agent"), TMPDIR: join(scratch, "tmp"), PATH: `${dirname(node)}:/usr/bin:/bin`, PI_OFFLINE: "1" }; + const argv = checkArgv(list, [found.view, ...args], { env, chdir: join(scratch, "project"), node, bwrap }); + const r = spawnSync(argv[0], argv.slice(1), { input, encoding: "utf8", timeout: RUN_TIMEOUT, killSignal: "SIGKILL", maxBuffer: OUTPUT_MAX, env: {} }); + return { status: r.status, stdout: typeof r.stdout === "string" ? r.stdout : "", timedOut: r.error?.code === "ETIMEDOUT" || r.signal === "SIGKILL" }; +} + +// One flag in one help line: the flag as its own token, at the line's start or after a space or +// a comma, and followed by the end, a space, a comma, "=" or "<". +function flagIn(line, flag) { + const at = (i) => i === 0 || line[i - 1] === " " || line[i - 1] === "," || line[i - 1] === "\t"; + const after = (i) => i === line.length || " ,=<\t".includes(line[i]); + for (let i = line.indexOf(flag); i !== -1; i = line.indexOf(flag, i + 1)) if (at(i) && after(i + flag.length)) return true; + return false; +} +const word = (line, w) => line.split(/[^A-Za-z0-9-]+/).includes(w); + +// The version a refusal line may carry: a version-shaped first line, else none. Anything else the +// binary prints stays out of the line. +function versionLabel(stdout) { + const first = String(stdout).split("\n")[0].trim(); + return /^v?[0-9]+(\.[0-9]+){0,3}([-+][0-9A-Za-z.-]{1,32})?$/.test(first) ? first : null; +} + +// The rpc answers in the output: whether get_state succeeded, and the command names get_commands +// listed (an empty list when it failed). +function answered(stdout) { + let state = false; + const commands = []; + for (const l of String(stdout).split("\n")) { + let m; + try { m = JSON.parse(l); } catch { continue; } + if (!m || m.type !== "response" || m.success !== true) continue; + if (m.id === "fit-state" && m.command === "get_state" && m.data && typeof m.data === "object") state = true; + if (m.id === "fit-commands" && m.command === "get_commands" && Array.isArray(m.data?.commands)) { + for (const c of m.data.commands) if (typeof c?.name === "string") commands.push(c.name); + } + } + return { state, commands }; +} + +// The planted sources. Each extension and each MCP server touches its own marker; each skill and +// prompt template has a name get_commands would list. Context and system prompt files are planted +// too, so nothing ambient that a session could meet is missing from the tree. +// "default agent ..." sits in $HOME/.pi/agent, where pi looks when PI_CODING_AGENT_DIR is unset. +const MARKED = ["user extension", "user settings extension", "default agent extension", "project extension", "project settings extension", "user mcp.json", "default agent mcp.json", "project mcp.json", "project .mcp.json"]; +const NAMED = { "fit-user-skill": "user skill", "fit-default-skill": "default agent skill", "fit-project-skill": "project skill", "fit-agents-skill": "project .agents skill", "fit-home-skill": "home .agents skill", "fit-user-prompt": "user prompt template", "fit-default-prompt": "default agent prompt template", "fit-project-prompt": "project prompt template" }; +// The -e extension the sealed run passes, which must load. +const EXPLICIT = "explicit extension"; +const markerName = (source) => source.replace(/[^a-z]/g, "-"); +const marked = (scratch, source) => { try { return readdirSync(join(scratch, "marks")).includes(markerName(source)); } catch { return false; } }; + +function plant(scratch) { + for (const d of ["home", "agent", "project", "marks", "tmp", "missing", "explicit"]) rmSync(join(scratch, d), { recursive: true, force: true }); + const marks = join(scratch, "marks"); + const put = (path, text) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); }; + const ext = (source) => `import { writeFileSync } from "node:fs";\nexport default function (): void { writeFileSync(${JSON.stringify(join(marks, markerName(source)))}, ""); }\n`; + const mcp = (source) => JSON.stringify({ mcpServers: { fit: { command: "/bin/sh", args: ["-c", `: > ${join(marks, markerName(source))}`] } } }); + const skill = (name) => `---\nname: ${name}\ndescription: a planted skill\n---\nA planted skill.\n`; + const agent = join(scratch, "agent"); + const project = join(scratch, "project"); + mkdirSync(marks, { recursive: true }); + mkdirSync(join(scratch, "tmp"), { recursive: true }); + put(join(agent, "extensions", "fit.ts"), ext("user extension")); + put(join(agent, "listed", "fit.ts"), ext("user settings extension")); + put(join(agent, "settings.json"), JSON.stringify({ extensions: [join(agent, "listed", "fit.ts")] })); + put(join(agent, "mcp.json"), mcp("user mcp.json")); + put(join(agent, "skills", "fit-user-skill", "SKILL.md"), skill("fit-user-skill")); + put(join(agent, "prompts", "fit-user-prompt.md"), "A planted prompt template.\n"); + for (const f of ["SYSTEM.md", "APPEND_SYSTEM.md", "AGENTS.md"]) put(join(agent, f), "A planted file.\n"); + put(join(project, ".pi", "extensions", "fit.ts"), ext("project extension")); + put(join(project, ".pi", "listed", "fit.ts"), ext("project settings extension")); + put(join(project, ".pi", "settings.json"), JSON.stringify({ extensions: [join(project, ".pi", "listed", "fit.ts")] })); + put(join(project, ".pi", "mcp.json"), mcp("project mcp.json")); + put(join(project, ".mcp.json"), mcp("project .mcp.json")); + put(join(project, ".pi", "skills", "fit-project-skill", "SKILL.md"), skill("fit-project-skill")); + put(join(project, ".agents", "skills", "fit-agents-skill", "SKILL.md"), skill("fit-agents-skill")); + put(join(project, ".pi", "prompts", "fit-project-prompt.md"), "A planted prompt template.\n"); + for (const f of [".pi/SYSTEM.md", ".pi/APPEND_SYSTEM.md", "AGENTS.md", "CLAUDE.md"]) put(join(project, f), "A planted file.\n"); + put(join(scratch, "home", ".agents", "skills", "fit-home-skill", "SKILL.md"), skill("fit-home-skill")); + const fallback = join(scratch, "home", ".pi", "agent"); + put(join(fallback, "extensions", "fit.ts"), ext("default agent extension")); + put(join(fallback, "mcp.json"), mcp("default agent mcp.json")); + put(join(fallback, "skills", "fit-default-skill", "SKILL.md"), skill("fit-default-skill")); + put(join(fallback, "prompts", "fit-default-prompt.md"), "A planted prompt template.\n"); + put(join(scratch, "explicit", "fit.ts"), ext(EXPLICIT)); + put(join(scratch, "prompt.md"), "A fit check.\n"); +} + +// The planted sources a run loaded: markers present, and planted names get_commands listed. +function seen(scratch, answer) { + let marks = []; + try { marks = readdirSync(join(scratch, "marks")); } catch { marks = []; } + const out = MARKED.filter((s) => marks.includes(markerName(s))); + for (const [name, source] of Object.entries(NAMED)) if (answer.commands.some((c) => c === name || c.endsWith(`:${name}`))) out.push(source); + return out; +} + +// sha256 over the sorted (path, sha256) list of the package's package.json, every regular file +// under dist/bundle/ (design section 4), and every regular file in the directory tree that holds +// the binary's real file, so a bin outside dist/bundle/ can't import a file the digest skips. A +// symlink there is read through. +function filesDigest(found) { + const pkg = found.pkg; + const bin = realpathSync(found.bin); + const files = new Set([join(pkg, "package.json"), bin]); + const walk = (dir) => { + let entries; + try { entries = readdirSync(dir, { withFileTypes: true }); } catch (e) { if (e.code === "ENOENT") return; throw e; } + for (const e of entries) { + const p = join(dir, e.name); + if (e.isDirectory()) walk(p); + else if (e.isFile() || (e.isSymbolicLink() && lstatSync(realpathSync(p)).isFile())) files.add(p); + if (files.size > DIGEST_FILES_MAX) throw new Error("too many files"); + } + }; + walk(join(pkg, "dist", "bundle")); + const binDir = dirname(bin); + if (binDir !== pkg && binDir.startsWith(`${pkg}/`)) walk(binDir); + const h = createHash("sha256"); + for (const f of [...files].sort()) { + h.update(relative(pkg, f)).update("\0").update(createHash("sha256").update(readFileSync(f)).digest("hex")).update("\n"); + } + return h.digest("hex"); +} diff --git a/packages/harness/tests/pi-fit.test.mjs b/packages/harness/tests/pi-fit.test.mjs new file mode 100644 index 000000000..b6ec8321e --- /dev/null +++ b/packages/harness/tests/pi-fit.test.mjs @@ -0,0 +1,192 @@ +// #1873 pi-unpin (design section 5, S3): before a session starts, a fit check proves the found pi +// takes every flag Mosaic passes and keeps the planted ambient sources off with the seal flags. +// Nothing compares a version. A check that cannot tell refuses. A refusal line names the found +// binary by its label, never a host path. +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { piFit } from "../src/pi-fit.mjs"; +import { piStandIn } from "./pi-stand-in.mjs"; +import { locate } from "../../plugins/harness/pi/binary.mjs"; +import * as pi from "../../plugins/harness/pi/index.mjs"; +import { sandboxProblem } from "../../seat/src/sandbox.mjs"; + +const REPO = resolve(fileURLToPath(new URL("../../../", import.meta.url))); +const NAME = "@earendil-works/pi-coding-agent"; +// The module's thinking levels (packages/plugins/harness/pi/index.mjs LEVELS). +const LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; +const CREDENTIAL = { ZAI_API_KEY: "fixture-zai" }; +const SKIP = sandboxProblem() ? { skip: "no working bwrap here" } : {}; + +// A stand-in pi in an npm prefix (prefix/lib/node_modules/, prefix/bin/pi a link to its +// bin), named by MOSAIC_PI_BIN. Returns the env that names it and the paths a refusal must not +// carry. +function standIn(t, knobs, version = "2.0.0") { + const root = mkdtempSync(join(tmpdir(), "mosaic-pi-fit-t-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const pkg = join(root, "prefix", "lib", "node_modules", NAME); + mkdirSync(join(pkg, "dist", "bundle"), { recursive: true }); + writeFileSync(join(pkg, "package.json"), JSON.stringify({ name: NAME, version, bin: { pi: "dist/bundle/cli.js" } })); + writeFileSync(join(pkg, "dist", "bundle", "cli.js"), piStandIn({ version, ...knobs }), { mode: 0o755 }); + mkdirSync(join(root, "prefix", "bin")); + symlinkSync(`../lib/node_modules/${NAME}/dist/bundle/cli.js`, join(root, "prefix", "bin", "pi")); + const env = { MOSAIC_PI_BIN: join(root, "prefix", "bin", "pi"), PATH: "/usr/bin:/bin" }; + return { env, root, cli: join(pkg, "dist", "bundle", "cli.js"), paths: [root, realpathSync(root), tmpdir(), REPO] }; +} + +const fit = (env) => piFit(locate(env), { levels: LEVELS }); +// A refusal names no host path: none of the stand-in's, the scratch's or the repository's, and no +// "/" at all, since every expected line is plain words and flag names. +const noPath = (message, paths) => { + for (const p of paths) assert.ok(!message.includes(p), message); + assert.ok(!message.includes("/"), message); +}; + +test("pi-unpin S3: a stand-in pi reporting another version that implements every check is accepted, and its version is recorded", SKIP, t => { + const s = standIn(t, { version: "2.0.0" }); + const r = fit(s.env); + assert.equal(r.ok, true, r.message); + assert.equal(r.version, "2.0.0"); + assert.equal(r.noMcp, false); + assert.match(r.digest, /^[0-9a-f]{64}$/); + assert.equal(pi.preflight({ env: { ...CREDENTIAL, ...s.env } }), null); + assert.equal(pi.version({ env: s.env }), "2.0.0", "the launcher records what the binary prints"); +}); + +test("pi-unpin S3: a stand-in missing --no-context-files from --help is refused with that line", SKIP, t => { + const s = standIn(t, { dropFlags: ["--no-context-files"] }); + const problem = pi.preflight({ env: { ...CREDENTIAL, ...s.env } }); + assert.deepEqual(problem, { code: "harness-feature-missing", message: "pi 2.0.0 (MOSAIC_PI_BIN) lacks --no-context-files" }); + noPath(problem.message, s.paths); + // rpc mode and each thinking level the module applies are part of the check too. + assert.equal(fit(standIn(t, { modes: ["text", "json"] }).env).message, "pi 2.0.0 (MOSAIC_PI_BIN) lacks --mode rpc"); + assert.equal(fit(standIn(t, { levels: ["off", "low"] }).env).message, "pi 2.0.0 (MOSAIC_PI_BIN) lacks --thinking minimal, --thinking medium, --thinking high, --thinking xhigh, --thinking max"); + assert.equal(fit(standIn(t, { dropFlags: ["--offline", "-e"] }).env).message, "pi 2.0.0 (MOSAIC_PI_BIN) lacks -e, --offline"); +}); + +test("pi-unpin S3: a stand-in that exits 0 on a missing -e is refused", SKIP, t => { + const s = standIn(t, { missingExtOk: true }); + const problem = pi.preflight({ env: { ...CREDENTIAL, ...s.env } }); + assert.deepEqual(problem, { code: "harness-feature-missing", message: "pi 2.0.0 (MOSAIC_PI_BIN) starts with a missing -e extension" }); + noPath(problem.message, s.paths); +}); + +test("pi-unpin S3: a stand-in that touches the planted MCP marker under the seal flags is refused", SKIP, t => { + const s = standIn(t, { sealLeak: ["mcp"] }); + const problem = pi.preflight({ env: { ...CREDENTIAL, ...s.env } }); + assert.deepEqual(problem, { code: "harness-feature-missing", message: "pi 2.0.0 (MOSAIC_PI_BIN) loaded a planted user mcp.json, project mcp.json, project .mcp.json with the seal flags on" }); + noPath(problem.message, s.paths); + // Each other kind of planted source is caught the same way. + const lines = { + extensions: "loaded a planted user extension, user settings extension, project extension, project settings extension with the seal flags on", + skills: "loaded a planted user skill, project skill, project .agents skill, home .agents skill with the seal flags on", + prompts: "loaded a planted user prompt template, project prompt template with the seal flags on", + }; + for (const [kind, line] of Object.entries(lines)) assert.equal(fit(standIn(t, { sealLeak: [kind] }).env).message, `pi 2.0.0 (MOSAIC_PI_BIN) ${line}`, kind); +}); + +test("pi-unpin S3: a stand-in that ignores the planted sources even without the seal flags fails the positive control and is refused as can't tell", SKIP, t => { + const s = standIn(t, { ignoreAll: true }); + const problem = pi.preflight({ env: { ...CREDENTIAL, ...s.env } }); + assert.deepEqual(problem, { code: "harness-feature-missing", message: "pi 2.0.0 (MOSAIC_PI_BIN) can't be checked: it loaded none of the planted sources without the seal flags" }); + noPath(problem.message, s.paths); +}); + +test("pi-unpin S3: a stand-in that ignores an -e extension with the seal flags on is refused, since a session's gate comes in that way", SKIP, t => { + const s = standIn(t, { dropExplicit: true }); + const problem = pi.preflight({ env: { ...CREDENTIAL, ...s.env } }); + assert.deepEqual(problem, { code: "harness-feature-missing", message: "pi 2.0.0 (MOSAIC_PI_BIN) didn't load an -e extension with the seal flags on" }); + noPath(problem.message, s.paths); +}); + +test("pi-unpin S3: a binary-printed version that is not version-shaped stays out of the line, and a --version failure is no refusal", SKIP, t => { + const s = standIn(t, { version: "/home/someone/secret 1.0", dropFlags: ["--no-skills"] }); + assert.equal(fit(s.env).message, "pi (MOSAIC_PI_BIN) lacks --no-skills"); + const quiet = standIn(t, { versionExit: 1 }); + const r = fit(quiet.env); + assert.equal(r.ok, true, r.message); + assert.equal(r.version, null); +}); + +test("pi-unpin S3: a pass is cached by the files that run; a changed file is checked again, and a refusal is not cached", SKIP, t => { + const s = standIn(t, {}); + const first = fit(s.env); + assert.equal(first.ok, true, first.message); + assert.equal(fit(s.env), first, "the second call reuses the pass"); + writeFileSync(s.cli, piStandIn({ version: "2.0.0", dropFlags: ["--no-themes"] }), { mode: 0o755 }); + assert.equal(fit(s.env).message, "pi 2.0.0 (MOSAIC_PI_BIN) lacks --no-themes"); + writeFileSync(s.cli, piStandIn({ version: "2.0.0" }), { mode: 0o755 }); + assert.equal(fit(s.env).ok, true, "the refusal was not kept"); +}); + +test("pi-unpin S3: when --help lists --no-mcp the session env asks the adapter to pass it", SKIP, t => { + const s = standIn(t, { extraFlags: ["--no-mcp"] }); + assert.equal(fit(s.env).noMcp, true); + const env = pi.env({ policy: { tools: ["read"] }, tools: [], session: { provider: "fixture", model: "m", thinking: "low", toolSocket: "/run/tools.sock" }, env: s.env }); + assert.equal(env.MOSAIC_PI_NO_MCP, "1"); + assert.ok(pi.envNames.includes("MOSAIC_PI_NO_MCP")); + const plain = pi.env({ policy: { tools: ["read"] }, tools: [], session: { provider: "fixture", model: "m", thinking: "low", toolSocket: "/run/tools.sock" }, env: standIn(t, {}).env }); + assert.equal(plain.MOSAIC_PI_NO_MCP, "0"); +}); + +test("pi-unpin S3: env() refuses a binary that fails the fit check, naming it by its label", SKIP, t => { + const s = standIn(t, { dropFlags: ["--no-approve"] }); + assert.throws(() => pi.env({ policy: { tools: ["read"] }, tools: [], session: { provider: "fixture", model: "m", thinking: "low", toolSocket: "/run/tools.sock" }, env: s.env }), { message: "pi 2.0.0 (MOSAIC_PI_BIN) lacks --no-approve" }); +}); + +test("pi-unpin S3: a check that cannot run refuses", SKIP, t => { + const s = standIn(t, {}); + const r = piFit(locate(s.env), { levels: LEVELS, bwrap: join(s.root, "no-bwrap") }); + assert.deepEqual(r, { ok: false, message: "pi (MOSAIC_PI_BIN) can't be checked: the sandbox (bwrap) is missing" }); + // A sandbox that fails says so without its own error text, which can name a host path. + const broken = join(s.root, "broken-bwrap"); + writeFileSync(broken, `#!/bin/sh\necho "bwrap: Can't find source path ${s.root}/x" >&2\nexit 1\n`, { mode: 0o755 }); + assert.deepEqual(piFit(locate(s.env), { levels: LEVELS, bwrap: broken }), { ok: false, message: "pi (MOSAIC_PI_BIN) can't be checked: the sandbox (bwrap) failed" }); + // An unreadable package is refused before anything runs. + const found = locate(s.env); + rmSync(join(s.root, "prefix", "lib", "node_modules", NAME, "package.json")); + assert.equal(piFit(found, { levels: LEVELS }).message, "pi (MOSAIC_PI_BIN) can't be checked: its files can't be read"); +}); + +test("pi-unpin S3: the fit check leaves no scratch behind", SKIP, t => { + const before = readdirSync(tmpdir()).filter((n) => n.startsWith("mosaic-pi-fit-") && !n.startsWith("mosaic-pi-fit-t-")); + fit(standIn(t, { ignoreAll: true }).env); + const after = readdirSync(tmpdir()).filter((n) => n.startsWith("mosaic-pi-fit-") && !n.startsWith("mosaic-pi-fit-t-")); + assert.deepEqual(after, before); +}); + +test("pi-unpin S3: real pi 0.85.1 from node_modules is accepted", SKIP, t => { + const found = locate({ PATH: "/usr/bin:/bin" }); + assert.equal(found.label, "the repository's pi"); + let at = process.hrtime.bigint(); + const r = piFit(found, { levels: LEVELS }); + const cold = Number(process.hrtime.bigint() - at) / 1e6; + assert.equal(r.ok, true, r.message); + assert.equal(r.version, "0.85.1"); + assert.equal(r.noMcp, false, "0.85.1 has no MCP and no --no-mcp"); + at = process.hrtime.bigint(); + assert.equal(piFit(found, { levels: LEVELS }), r); + const cached = Number(process.hrtime.bigint() - at) / 1e6; + t.diagnostic(`real pi 0.85.1 fit check: cold ${cold.toFixed(0)} ms, cached ${cached.toFixed(1)} ms`); +}); + +test("pi-unpin S3: the adapter passes --no-mcp only when the module asks for it", SKIP, t => { + const session = { provider: "fixture", model: "m", thinking: "low", toolSocket: "/run/tools.sock" }; + const run = (s) => { + const out = join(s.root, "argv"); + writeFileSync(join(s.root, "prompt.md"), "p"); + const given = pi.env({ policy: { tools: ["read"] }, tools: [], session, env: s.env }); + const r = spawnSync("/bin/sh", [join(REPO, "adapters", "pi", "adapter.sh")], { + encoding: "utf8", + env: { ...given, PATH: "/usr/bin:/bin", ARGV_OUT: out, MOSAIC_SYSTEM_PROMPT_FILE: join(s.root, "prompt.md"), MOSAIC_REQUEST: "x", MOSAIC_WORKSPACE: join(s.root, "ws"), MOSAIC_SESSION_DIR: join(s.root, "session"), MOSAIC_MODEL: "m" }, + }); + assert.equal(r.status, 0, r.stderr); + return readFileSync(out, "utf8").split("\n"); + }; + assert.equal(run(standIn(t, { extraFlags: ["--no-mcp"] })).filter((a) => a === "--no-mcp").length, 1); + assert.equal(run(standIn(t, {})).includes("--no-mcp"), false); +}); diff --git a/packages/harness/tests/pi-stand-in.mjs b/packages/harness/tests/pi-stand-in.mjs new file mode 100644 index 000000000..50d928038 --- /dev/null +++ b/packages/harness/tests/pi-stand-in.mjs @@ -0,0 +1,110 @@ +// #1873 pi-unpin S3: a stand-in pi that the fit check (src/pi-fit.mjs) can run. It is one sh +// script with its knobs written into it, because the fit check runs it with an empty +// environment. Put it at dist/bundle/cli.js in a package named @earendil-works/pi-coding-agent. +// +// What it does, in order: +// --version prints `version` (default 9.9.9), or exits `versionExit` when that is set +// $ARGV_OUT set: a session. Writes its argv there, prints `sessionOut`, exits 0. This part is +// sh, so it runs in a sandbox that holds no node. +// otherwise runs node (the absolute path, since the fit check gives it no PATH) on the rest: +// --help lists every flag the fit check wants, less `dropFlags`, plus `extraFlags` +// -e a file that doesn't exist stops it with exit 1, unless `missingExtOk`; one that +// exists is loaded even with --no-extensions, unless `dropExplicit` +// --mode rpc loads the planted sources the way pi finds them, honouring the seal flags, +// then answers get_state and get_commands. `ignoreAll` loads nothing. +// `sealLeak` lists kinds (extensions, mcp, skills, prompts) loaded even when +// their seal flag is on. +// otherwise a session with no $ARGV_OUT: prints `sessionOut` and exits 0. +import { FIT_FLAGS } from "../src/pi-fit.mjs"; + +const BODY = String.raw` +const fs = require("node:fs"); +const path = require("node:path"); +const cp = require("node:child_process"); +const argv = process.argv.slice(1); +const has = (f) => argv.includes(f); +const val = (f) => { const i = argv.indexOf(f); return i === -1 ? undefined : argv[i + 1]; }; +if (argv[0] === "--help") { + const drop = new Set(K.dropFlags || []); + const lines = ["Usage: pi [options] [messages...]", "", "Options:"]; + for (const f of FLAGS) { + if (drop.has(f)) continue; + if (f === "--mode") lines.push(" --mode Output mode: " + (K.modes || ["text", "json", "rpc"]).join(", ")); + else if (f === "--thinking") lines.push(" --thinking Thinking level: " + (K.levels || ["off", "minimal", "low", "medium", "high", "xhigh", "max"]).join(", ")); + else lines.push(" " + f); + } + for (const f of K.extraFlags || []) lines.push(" " + f); + process.stdout.write(lines.join("\n") + "\n"); + process.exit(0); +} +for (let i = 0; i < argv.length; i++) { + if (argv[i] === "-e" && !fs.existsSync(argv[i + 1]) && !K.missingExtOk) { + process.stderr.write("Failed to load extension: it does not exist\n"); + process.exit(1); + } +} +if (val("--mode") === "rpc") { + const leak = new Set(K.sealLeak || []); + const on = (kind, flag) => !K.ignoreAll && (!has(flag) || leak.has(kind)); + const agent = process.env.PI_CODING_AGENT_DIR || path.join(process.env.HOME || "/", ".pi", "agent"); + const cwd = process.cwd(); + const list = (dir, test) => { try { return fs.readdirSync(dir).filter(test).map((n) => path.join(dir, n)); } catch { return []; } }; + const json = (file) => { try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; } }; + const commands = []; + // Each planted extension writes one marker; do what it would do on load. + const load = (f) => { + let text = ""; + try { text = fs.readFileSync(f, "utf8"); } catch { return; } + const m = text.match(/writeFileSync\(("(?:[^"\\]|\\.)*")/); + if (m) fs.writeFileSync(JSON.parse(m[1]), ""); + }; + if (!K.dropExplicit) for (let i = 0; i < argv.length; i++) if (argv[i] === "-e") load(argv[i + 1]); + if (on("extensions", "--no-extensions")) { + const files = [...list(path.join(agent, "extensions"), (n) => n.endsWith(".ts")), ...list(path.join(cwd, ".pi", "extensions"), (n) => n.endsWith(".ts"))]; + for (const s of [path.join(agent, "settings.json"), path.join(cwd, ".pi", "settings.json")]) files.push(...(json(s)?.extensions || [])); + for (const f of files) load(f); + } + if (on("mcp", "--no-extensions") && (!has("--no-mcp") || leak.has("mcp"))) { + for (const f of [path.join(agent, "mcp.json"), path.join(cwd, ".pi", "mcp.json"), path.join(cwd, ".mcp.json")]) { + for (const s of Object.values(json(f)?.mcpServers || {})) cp.spawnSync(s.command, s.args || [], { stdio: "ignore" }); + } + } + if (on("skills", "--no-skills")) { + const home = process.env.HOME || "/"; + for (const d of [path.join(agent, "skills"), path.join(cwd, ".pi", "skills"), path.join(cwd, ".agents", "skills"), path.join(home, ".agents", "skills")]) { + for (const p of list(d, () => true)) commands.push({ name: "skill:" + path.basename(p), source: "skill" }); + } + } + if (on("prompts", "--no-prompt-templates")) { + for (const d of [path.join(agent, "prompts"), path.join(cwd, ".pi", "prompts")]) { + for (const p of list(d, (n) => n.endsWith(".md"))) commands.push({ name: path.basename(p, ".md"), source: "prompt" }); + } + } + let input = ""; + try { input = fs.readFileSync(0, "utf8"); } catch { input = ""; } + for (const line of input.split("\n")) { + let m; + try { m = JSON.parse(line); } catch { continue; } + if (m.type === "get_state") process.stdout.write(JSON.stringify({ id: m.id, type: "response", command: "get_state", success: true, data: { isStreaming: false } }) + "\n"); + if (m.type === "get_commands") process.stdout.write(JSON.stringify({ id: m.id, type: "response", command: "get_commands", success: true, data: { commands } }) + "\n"); + } + process.exit(0); +} +if (K.sessionOut) process.stdout.write(K.sessionOut); +process.exit(0); +`; + +const quote = (text) => `'${String(text).replace(/'/g, "'\\''")}'`; + +// The script text. node: the interpreter the fit part runs on (absolute, so it runs with no PATH). +export function piStandIn(knobs = {}, { node = process.execPath } = {}) { + const version = knobs.versionExit != null ? `exit ${Number(knobs.versionExit)}` : `printf '%s\\n' ${quote(knobs.version ?? "9.9.9")}; exit 0`; + const program = `"use strict";\nconst K = ${JSON.stringify(knobs)};\nconst FLAGS = ${JSON.stringify(FIT_FLAGS)};\n${BODY}`; + return [ + "#!/bin/sh", + `[ "$1" = --version ] && { ${version}; }`, + `if [ -n "\${ARGV_OUT:-}" ]; then printf '%s\\n' "$@" > "$ARGV_OUT"; printf '%s' ${quote(knobs.sessionOut ?? "")}; exit 0; fi`, + `exec ${quote(node)} -e ${quote(program)} -- "$@"`, + "", + ].join("\n"); +} diff --git a/packages/plugins/README.md b/packages/plugins/README.md index 2bcac8dc2..a2d1358e8 100644 --- a/packages/plugins/README.md +++ b/packages/plugins/README.md @@ -260,7 +260,13 @@ export returns: 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. + repository's pi", never a host path. Pi's `preflight` and `env` then run + the fit check (#1873 S3, `packages/harness/src/pi-fit.mjs`), which + refuses `harness-feature-missing` when the binary lacks a flag the + adapter passes, starts with a missing `-e` file, loads a planted ambient + source with the seal flags on, or can't be checked. When its `--help` + lists `--no-mcp`, `env` sets `MOSAIC_PI_NO_MCP=1` and the adapter + passes `--no-mcp`; otherwise it sets `MOSAIC_PI_NO_MCP=0`. - `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 diff --git a/packages/plugins/harness/pi/binary.mjs b/packages/plugins/harness/pi/binary.mjs index e1e34670d..d4bc0562c 100644 --- a/packages/plugins/harness/pi/binary.mjs +++ b/packages/plugins/harness/pi/binary.mjs @@ -31,8 +31,9 @@ const inside = (path, root) => root === "/" || path === root || path.startsWith( // 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. +// dest, pkg } 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, pkg the package's +// real directory. export function locate(env = {}) { if (env.MOSAIC_PI_BIN !== undefined && env.MOSAIC_PI_BIN !== "") { const bin = env.MOSAIC_PI_BIN; @@ -58,14 +59,14 @@ function placed(bin, label, env) { // 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)) }; + return { bin, label, root: repoReal, dest: REPO_NODE_MODULES, view: join(REPO_NODE_MODULES, relative(repoReal, realBin)), pkg }; } // 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 }; + return { bin, label, root: pkg, dest: null, view: realBin, pkg }; } // The package directory that holds the binary's real file: the nearest directory above it whose diff --git a/packages/plugins/harness/pi/index.mjs b/packages/plugins/harness/pi/index.mjs index 07a08e921..f18642607 100644 --- a/packages/plugins/harness/pi/index.mjs +++ b/packages/plugins/harness/pi/index.mjs @@ -8,6 +8,7 @@ import { dirname, join } from "node:path"; import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; import { locate, printedVersion } from "./binary.mjs"; +import { piFit } from "../../../harness/src/pi-fit.mjs"; export const interfaceVersion = 1; @@ -38,6 +39,10 @@ export function preflight({ env = {}, proxy = null } = {}) { } const found = locate(env); if (!found.bin) return { code: "harness-binary-missing", message: found.problem }; + // #1873 S3: the found binary takes every flag the adapter passes and keeps the known ambient + // sources off with them, or the launch is refused. A check that cannot tell refuses too. + const fit = piFit(found, { levels: LEVELS }); + if (!fit.ok) return { code: "harness-feature-missing", message: fit.message }; return null; } @@ -115,8 +120,15 @@ export function bundle({ dir, models, proxy = null, transports = {} } = {}) { // 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 }) { + const at = found(hostEnv); + // #1873 S3: a session runs only a binary that passed the fit check (cached from preflight). + const fit = piFit(at, { levels: LEVELS }); + if (!fit.ok) throw new Error(fit.message); return { - MOSAIC_PI_BIN: found(hostEnv).view, + MOSAIC_PI_BIN: at.view, + // "1" when --help lists --no-mcp: the adapter then passes it, so MCP stays off by its own + // flag. "0" otherwise, so every name in envNames is always set. + MOSAIC_PI_NO_MCP: fit.noMcp ? "1" : "0", PI_OFFLINE: "1", MOSAIC_TOOLS: [...policy.tools, ...tools.map((t) => t.name)].join(","), MOSAIC_EXTENSIONS: [EXTENSION, UNSLOP.unslopExtension].join(","), @@ -132,8 +144,9 @@ export function env({ policy, tools, session, proxy = null, env: hostEnv = proce // 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). 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"]); +// (#1873 S2) is the binary's path inside the session, which the host keeps from its own env() call; +// MOSAIC_PI_NO_MCP (#1873 S3) is "1" when the binary's --help lists --no-mcp, else "0". +export const envNames = Object.freeze(["MOSAIC_PI_BIN", "MOSAIC_PI_NO_MCP", "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. diff --git a/packages/plugins/tests/harness.test.mjs b/packages/plugins/tests/harness.test.mjs index 0b24f9aa3..6a78a76d9 100644 --- a/packages/plugins/tests/harness.test.mjs +++ b/packages/plugins/tests/harness.test.mjs @@ -10,6 +10,7 @@ import { fileURLToPath } from "node:url"; import { spawnSync } from "node:child_process"; import { createLoader } from "../src/loader.mjs"; import { KINDS } from "../src/kinds.mjs"; +import { piStandIn } from "../../harness/tests/pi-stand-in.mjs"; const REPO = resolve(fileURLToPath(new URL("../../../", import.meta.url))); @@ -144,10 +145,11 @@ test("row 65 a route's thinking reaches pi as --thinking and claude as --effort, 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); - } + const result = '{"type":"result","subtype":"success","result":"ok"}\n'; + writeFileSync(join(dir, "bin", "claude"), `#!/bin/sh\nprintf "%s\\n" "$@" > "$ARGV_OUT"\necho '${result.trim()}'\n`); + // #1873 S3: pi's stand-in also passes the fit check that env() runs. + writeFileSync(join(piPackage, "dist", "bundle", "cli.js"), piStandIn({ sessionOut: result })); + for (const file of [join(dir, "bin", "claude"), join(piPackage, "dist", "bundle", "cli.js")]) 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) => { diff --git a/packages/plugins/tests/pi-binary.test.mjs b/packages/plugins/tests/pi-binary.test.mjs index 4bc464a60..a64d9974f 100644 --- a/packages/plugins/tests/pi-binary.test.mjs +++ b/packages/plugins/tests/pi-binary.test.mjs @@ -9,6 +9,7 @@ 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"; +import { piStandIn } from "../../harness/tests/pi-stand-in.mjs"; const REPO = resolve(fileURLToPath(new URL("../../../", import.meta.url))); const MODULE = join(REPO, "packages", "plugins", "harness", "pi"); @@ -82,7 +83,9 @@ test("pi-unpin S1: the repository's real pi reports its installed package's vers // 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'; +// #1873 S3: the stand-in passes the fit check, prints 7.7.7 for --version, and as a session +// records its argv in $ARGV_OUT. +const ARGV_SCRIPT = piStandIn({ version: "7.7.7" }); // 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") { diff --git a/packages/seat/src/sandbox.mjs b/packages/seat/src/sandbox.mjs index b98c047b4..00daadffb 100644 --- a/packages/seat/src/sandbox.mjs +++ b/packages/seat/src/sandbox.mjs @@ -6,7 +6,7 @@ // // read-only /usr, /etc and the host's /bin, /lib, /lib64, /sbin links; // the repository files the runner loads; the adapter; for pi -// the repository's node_modules, for Claude Code its pinned +// the found package's directory (#1873), for Claude Code its // binary; node when it lives outside /usr; the broker socket, // the launch socket for the role that may launch, and the // host's git socket for a role holding git.push.working or @@ -193,6 +193,14 @@ export function sandboxArgv(list, runDir, command, { business, role, bwrap = BWR return [bwrap, ...NAMESPACES, ...argsOf(list), "--remount-ro", "/", "--setenv", "HOME", join(runDir, "home"), "--setenv", "TMPDIR", "/tmp", ...identity, "--chdir", runDir, "--", ...KILL_WITH_PARENT, ...command]; } +// #1873 pi-unpin S3: the command line for a start-time check of a harness binary. It has the +// system part every session gets, then `list`, with the network unshared, an empty environment +// but `env`, and `chdir` as the working directory. +export function checkArgv(list, command, { env = {}, chdir, node = process.execPath, bwrap = BWRAP }) { + const setenv = Object.entries(env).flatMap(([k, v]) => ["--setenv", k, v]); + return [bwrap, ...NAMESPACES, "--unshare-net", ...argsOf([...systemBinds(node), ...list]), "--remount-ro", "/", "--clearenv", ...setenv, "--chdir", chdir, "--", ...KILL_WITH_PARENT, ...command]; +} + // #1873 triage-fences: what a model route may hand a hosted session, checked before the host // writes anything and again in hostedBinds. The adapter and each mount's source must be a clean // absolute path whose real path lies under one of the harness module's install roots, named under diff --git a/packages/webui/tests/triage-host.test.mjs b/packages/webui/tests/triage-host.test.mjs index 6db74e48f..2dc844efb 100644 --- a/packages/webui/tests/triage-host.test.mjs +++ b/packages/webui/tests/triage-host.test.mjs @@ -442,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_PI_BIN", "MOSAIC_THINKING", "MOSAIC_TOOLS"]); + assert.deepEqual(Object.keys(s.harnessEnv).filter((k) => k.startsWith("MOSAIC_")).sort(), ["MOSAIC_EXTENSIONS", "MOSAIC_PI_BIN", "MOSAIC_PI_NO_MCP", "MOSAIC_THINKING", "MOSAIC_TOOLS"]); + // #1873 pi-unpin S3: the repository's pi has no --no-mcp, so the module sets it to "0". + assert.equal(s.harnessEnv.MOSAIC_PI_NO_MCP, "0"); // #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