From eac42663ba363b7e1cc745165ee8e3e3f58ae064 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Thu, 19 Nov 2026 19:00:35 -0600 Subject: [PATCH] fix(pi): pi-unpin S3 re-check 6: the fit runs get a bus session's environment, built by the launcher's sessionEnv over ENV_ALLOW, the sandbox's sessionSetenv and the runner's adapterEnv with the pi module's harnessEnv (now in session-env.mjs), so no run sets PI_CODING_AGENT_DIR and the agent sources sit at $HOME/.pi/agent; a test fails when the fit env and a bus session's env differ by a name outside one listed exception; the drift test runs the adapter in that env over 98 argv sets, each tool count, -c case, thinking level and provider, and checks every variable the adapter reads; -c over a session dir with nothing for the project is named under Not run, with a gap test (#1873) --- packages/harness/README.md | 28 ++- packages/harness/src/pi-fit.mjs | 118 ++++++++---- packages/harness/tests/pi-fit.test.mjs | 187 +++++++++++++++----- packages/harness/tests/pi-stand-in.mjs | 31 +++- packages/plugins/README.md | 4 +- packages/plugins/harness/pi/index.mjs | 18 +- packages/plugins/harness/pi/session-env.mjs | 26 +++ packages/seat/src/sandbox.mjs | 17 +- 8 files changed, 315 insertions(+), 114 deletions(-) create mode 100644 packages/plugins/harness/pi/session-env.mjs diff --git a/packages/harness/README.md b/packages/harness/README.md index 8c99b75b0..ec5602e0c 100644 --- a/packages/harness/README.md +++ b/packages/harness/README.md @@ -28,8 +28,16 @@ bundle's `manifest.json` names the lines it relies on (`reliesOn`): 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 +found. It runs that binary in a sandbox with the network unshared and +calls no model. Each run gets the variable names a bus session's pi gets, +built by the same code (the launcher's `ENV_ALLOW` and `sessionEnv`, the +sandbox's `sessionSetenv`, the runner's `adapterEnv` and the pi module's +`harnessEnv`), less the provider keys, and starts the binary through +`/bin/sh` as the adapter does. So `HOME` is a scratch home, `TMPDIR` is +`/tmp` bound to scratch, and no run sets `PI_CODING_AGENT_DIR`, which no +session has: pi's agent directory is `$HOME/.pi/agent`, where the user +sources are planted. A test fails when the fit runs' names and a bus +session's differ, apart from the provider variables. It needs `--help` to list, in its option column, every flag the adapter passes (with rpc mode and each thinking level), and a missing `-e` file to stop the start in rpc and in `-p`. The planted ambient sources must stay @@ -66,14 +74,20 @@ session branches (a tool list or `--no-tools`, `-c` over a stored session or none, `--thinking` or none, `--mode json` or none) are spread over the five runs so every pair of them is passed together. A `-c` run gets a stored session and must resume it. Each must load both `-e` -files and show no planted source. A test drives the adapter through all -sixteen branch sets and fails on an argv `sessionShape` doesn't build, -or a pair no run passes. A last sealed `-p` run uses `--no-session`, as +files and show no planted source. A test drives the adapter, in a bus +session's environment, through every branch set with no tools, one or +two, `-c` over a pi-named session file or an unrelated file, each +thinking level and each provider a session can name. It fails on an argv +`sessionShape` doesn't build, a pair no run passes, or a variable the +adapter reads that no session sets. It can't see a branch keyed on a +value it doesn't try (a model, a path, another tool or provider). A last sealed `-p` run uses `--no-session`, as worker runs do. Each run gets a fresh scratch directory, so no run sees what another left. Not run: `--fork`, `--skill` and the interactive TUI (worker containers and `scripts/agent.sh` only), the branches three or -four at a time beyond the five runs, and a session's own values (tool -list, thinking level, provider, model, key, `-e` files, request). The +four at a time beyond the five runs, `-c` over a session directory that +holds nothing for the project (one more run costs about 340 ms cold), +and a session's own values (tools beyond `read` and `bash`, thinking +levels beyond `low`, provider, model, key, `-e` files, request). The runs are offline with no key, so nothing past the start is tried. A pi built to act one way in the fit runs and another way with those is outside what a start-time check can catch. A run killed for taking diff --git a/packages/harness/src/pi-fit.mjs b/packages/harness/src/pi-fit.mjs index 524c1103c..94192be1e 100644 --- a/packages/harness/src/pi-fit.mjs +++ b/packages/harness/src/pi-fit.mjs @@ -1,7 +1,8 @@ // #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 and no provider key is passed. It asks: +// unshared, the found package mounted as a session mounts it, and a bus session's environment +// (fitEnv below), so its agent directory is $HOME/.pi/agent under a scratch HOME, as a session's +// is. No model is called and no provider key is passed. It asks: // // --version a label for the refusal line and the record; not a gate // --help lists, in its option column, every flag Mosaic passes, with rpc mode and each @@ -34,9 +35,10 @@ // session or none, --thinking or none, --mode json or none) are spread over the five // runs so each pair of them is passed together (SESSION_RUNS). A -c run gets a // stored session for the project and must resume it. Each run loads both -e -// extensions, uses the --system-prompt file, and shows no planted source. A test -// drives the adapter through all sixteen branch sets and fails on an argv -// sessionShape doesn't build or a pair no run passes. +// extensions, uses the --system-prompt file, and shows no +// planted source. A test drives the adapter through every branch set, tool list +// length and thinking level, and fails on an argv sessionShape doesn't build or a +// pair no run passes. // sealed -p the seal flags in -p with --no-session, as a worker run passes them. Its -e // extension must reach session_start, and no planted source may show. // missing -e a missing -e file, in rpc and in -p, stops the start: exit non-zero, no answer, @@ -44,7 +46,12 @@ // // Every run gets a fresh scratch directory with the sources planted again, so no run sees what // another one left. Each run passes the same -e and --system-prompt; the other runs differ only by -// their seal flags, their mode, the -p message and the missing -e file. +// their seal flags, their mode, the -p message and the missing -e file. Each run starts the binary +// through /bin/sh, as the adapter does, with fitEnv's variables: the names a bus session's pi gets, +// built by the code that builds those (the launcher's ENV_ALLOW and sessionEnv, the sandbox's +// sessionSetenv, the runner's adapterEnv and the pi module's harnessEnv), less the provider key. +// So no run sets a variable a session lacks, such as PI_CODING_AGENT_DIR, and a test holds the two +// lists together. // // A check that cannot tell refuses: a sandbox that fails, a run that times out or prints more // than 4 MB, an answer that is missing or doesn't parse, a kind of source the control doesn't @@ -59,16 +66,22 @@ // Known limit: pi 0.85.1 appends the agent directory's APPEND_SYSTEM.md whatever the flags. The // check doesn't plant one; a session's agent directory is the run's own. Not run: --fork, // --skill with --no-skills dropped, and the interactive TUI, which only worker containers and -// scripts/agent.sh pass; the session branches three or four at a time beyond the five runs; and -// a session's own values: its tool list, thinking level, provider, model, key, -e files and -// request. The runs are offline with no key, so nothing past the start is tried. A pi built to -// act differently with those is outside what a start-time check can catch. +// scripts/agent.sh pass; the session branches three or four at a time beyond the session-shaped +// runs; -c over a session directory that holds nothing for the project (the adapter passes -c +// whenever the directory isn't empty), since one more run costs about 340 ms cold; and a +// session's own values: its tool names beyond read and bash, thinking levels beyond low, +// provider, model, key, -e files and request. The runs are offline with no key, so nothing +// past the start is tried. A pi built to act differently with those is outside what a start-time +// check can catch. 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"; +import { BWRAP, checkArgv, sandboxProblem, sessionSetenv } from "../../seat/src/sandbox.mjs"; +import { ENV_ALLOW, isProviderVariable, sessionEnv } from "../../seat/src/session.mjs"; +import { adapterEnv } from "./runner.mjs"; +import { harnessEnv } from "../../plugins/harness/pi/session-env.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"]); @@ -142,11 +155,14 @@ function check(found, { levels, bwrap, node, who, digest }) { // whether each -e extension loaded, what the first one saw at session_start (the system prompt, // the command names, the session id), and the planted sources that showed, through the rpc // get_commands answer or through the -e extension's command list (listed: through that alone). - const run = (args, input = "", { timeout = RUN_TIMEOUT } = {}) => { + // shape: a session-shaped run's branches, which set its tools, thinking level and monitor + // variables as a session's would. + const run = (args, input = "", { timeout = RUN_TIMEOUT, noMcp = false, shape = null } = {}) => { const scratch = mkdtempSync(join(tmpdir(), "mosaic-pi-fit-")); try { plant(scratch); - const r = runIn(found, { bwrap, node, scratch, args: typeof args === "function" ? args(scratch) : args, input, timeout }); + const env = fitEnv(scratch, { view: found.view, node, noMcp, shape }); + const r = runIn(found, { bwrap, node, scratch, env, args: typeof args === "function" ? args(scratch) : args, input, timeout }); const answer = answered(r.stdout); const start = started(scratch); const listed = start?.commands ?? []; @@ -175,7 +191,7 @@ function check(found, { levels, bwrap, node, who, digest }) { const seal = [...SEAL, ...(noMcp ? ["--no-mcp"] : [])]; const loaders = [...LOADERS, ...(noMcp ? [["--no-mcp", "MCP server"]] : [])]; const without = (...flags) => seal.filter((f) => !flags.includes(f)); - const rpcRun = (flags) => run((s) => ["--mode", "rpc", ...flags, ...given(s)], ask); + const rpcRun = (flags) => run((s) => ["--mode", "rpc", ...flags, ...given(s)], ask, { noMcp }); // The control keeps the seal flags no planted source tells apart (--offline, --no-themes, // --no-tools, --no-session), so one of those can't stand in for a loader flag either. @@ -224,7 +240,7 @@ function check(found, { levels, bwrap, node, who, digest }) { const r = run((s) => { if (shape.cont) plantSession(s); return sessionShape({ noMcp, extensions: [join(s, "explicit", "fit.ts"), join(s, "explicit", "second.ts")], prompt: join(s, "prompt.md"), sessionDir: join(s, "sessions"), message: "fit check", ...shape }); - }); + }, "", { noMcp, shape }); const name = shapeName(shape); if (r.stopped) return refuse(`can't be checked: the start ${name} ${r.stopped}`); if (r.prompt === null) return refuse(`can't be checked: its -e extension didn't see the system prompt ${name}`); @@ -235,7 +251,7 @@ function check(found, { levels, bwrap, node, who, digest }) { } // -p takes a message; offline with no key, pi stops before any model call. - const p = run((s) => ["-p", ...seal, ...given(s), "fit check"]); + const p = run((s) => ["-p", ...seal, ...given(s), "fit check"], "", { noMcp }); if (p.stopped) return refuse(`can't be checked: a -p start with the seal flags ${p.stopped}`); if (p.prompt === null) return refuse("can't be checked: a -p start with the seal flags didn't run its -e extension"); if (p.seen.length) return refuse(`loaded a planted ${p.seen.map((x) => x.source).join(", ")} with the seal flags on in -p`); @@ -243,29 +259,58 @@ function check(found, { levels, bwrap, node, who, digest }) { // A missing -e file stops the start. pi 0.85.1 loads the -e files in order and still loads the // one after the missing one, then exits 1 before session_start, so only session_start tells. for (const [mode, args, input] of [["rpc", ["--mode", "rpc"], ask], ["-p", ["-p"], ""]]) { - const r = run((s) => [...args, ...seal, "-e", join(s, "missing", "extension.ts"), ...given(s), ...(mode === "-p" ? ["fit check"] : [])], input); + const r = run((s) => [...args, ...seal, "-e", join(s, "missing", "extension.ts"), ...given(s), ...(mode === "-p" ? ["fit check"] : [])], input, { noMcp }); if (r.stopped) return refuse(`can't be checked: a ${mode} start with a missing -e extension ${r.stopped}`); if (r.status === 0 || r.answer.state || r.prompt !== null) return refuse("starts with a missing -e extension"); } 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. +// The binary, inside the sandbox: the system part, the found package where a session sees it, the +// scratch directory read-write, and its tmp/ as /tmp, as a session has it. The environment is +// fitEnv's. The binary starts through /bin/sh, as the adapter starts it, so it also gets the +// variables the shell sets. // stopped: why the run was killed ("timed out", "printed more than 4 MB"), or null. -function runIn(found, { bwrap, node, scratch, args, input, timeout }) { +function runIn(found, { bwrap, node, scratch, env, args, input, timeout }) { const list = [ { kind: "ro", src: found.root, ...(found.dest ? { dest: found.dest } : {}) }, { kind: "rw", src: scratch }, + { kind: "rw", src: join(scratch, "tmp"), dest: "/tmp" }, ]; - 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 argv = checkArgv(list, ["/bin/sh", "-c", 'exec "$0" "$@"', found.view, ...args], { env, chdir: join(scratch, "project"), node, bwrap }); const r = spawnSync(argv[0], argv.slice(1), { input, encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: OUTPUT_MAX, env: {} }); const stopped = r.error?.code === "ENOBUFS" ? `printed more than ${OUTPUT_MAX / 1024 / 1024} MB` : r.error?.code === "ETIMEDOUT" || r.signal === "SIGKILL" ? "timed out" : null; return { status: r.status, stdout: typeof r.stdout === "string" ? r.stdout : "", stopped }; } +// The values a fit run gives the launcher's ENV_ALLOW names. A name not here gets "fit", so a name +// added there reaches the fit runs too. HOME and MOSAIC_PI_BIN are set again below. +const ALLOW_VALUES = { USER: "fit", LOGNAME: "fit", LANG: "C.UTF-8", LC_ALL: "C.UTF-8", TZ: "UTC", TERM: "dumb" }; +// A fit run's environment: a bus session's pi gets these names, built the same way. The launcher +// passes the ENV_ALLOW names through sessionEnv (every one here but the provider variables, since +// no key is passed: no model is called), the sandbox sets sessionSetenv's (HOME is the scratch +// home, so pi's agent directory is $HOME/.pi/agent), the runner adds adapterEnv's with the pi +// module's harnessEnv, and MOSAIC_REQUEST for each turn. shape: a session-shaped run's branches +// (its tool list, thinking level and --mode json, which a proxy session's first turn takes with +// the model event monitor's variables), else none: no tools, no thinking, one -e. noMcp: --help +// lists --no-mcp. pi-fit.test.mjs fails when these names and a bus session's differ. +export function fitEnv(scratch, { view, node = process.execPath, noMcp = false, shape = null }) { + const host = { PATH: `${dirname(node)}:/usr/bin:/bin` }; + for (const name of ENV_ALLOW) if (!isProviderVariable(name)) host[name] = ALLOW_VALUES[name] ?? "fit"; + const runner = { ...sessionEnv(host, "fit"), ...sessionSetenv(scratch, { business: "fit", role: "fit" }) }; + const { tools = "", thinking = "", json = false } = shape ?? {}; + const session = { provider: SESSION_SHAPE.provider, model: SESSION_SHAPE.model, thinking }; + const extensions = [join(scratch, "explicit", "fit.ts"), ...(shape ? [join(scratch, "explicit", "second.ts")] : [])]; + const env = adapterEnv({ + ...session, + bundle: { prompt: join(scratch, "prompt.md"), policy: join(scratch, "policy.json"), tools: join(scratch, "tools.json") }, + workspace: join(scratch, "project"), sessionDir: join(scratch, "sessions"), toolSocket: join(scratch, "tools.sock"), turnMarker: join(scratch, "turn"), + harnessEnv: harnessEnv({ bin: view, noMcp, tools: tools ? tools.split(",") : [], extensions, session }), + runDir: scratch, proxyFirstTurn: json, + }, runner); + return { ...env, MOSAIC_REQUEST: "fit check" }; +} + // The options one help line lists in its option column: a line that starts with "-" (after its // indent), up to the first run of two spaces or a tab, split at commas; the first word of each // part. " --extension, -e Load an extension" lists --extension and -e. A flag named in a @@ -304,21 +349,22 @@ function answered(stdout) { // The planted sources, each with the kind the control must show. Each extension and each MCP // server touches its own marker; each skill and prompt template has a name get_commands lists; // each context and system prompt file holds a word the -e extension's view of the system prompt -// shows. "default agent ..." sits in $HOME/.pi/agent, where pi looks when PI_CODING_AGENT_DIR is -// unset. "settings" sources are listed by a settings.json; "package" sources come from a local -// package a settings.json lists. "parent" is a directory above the project. +// shows. "user" sources sit in the agent directory, $HOME/.pi/agent: no fit run sets +// PI_CODING_AGENT_DIR, as no bus session does. "settings" sources are listed by a settings.json; +// "package" sources come from a local package a settings.json lists. "parent" is a directory above +// the project. const KINDS = ["extension", "MCP server", "skill", "prompt template", "context file", "trusted project file"]; const MARKED = { - "user extension": "extension", "user settings extension": "extension", "user package extension": "extension", "default agent extension": "extension", + "user extension": "extension", "user settings extension": "extension", "user package extension": "extension", "project extension": "extension", "project settings extension": "extension", "project package extension": "extension", - "user mcp.json": "MCP server", "default agent mcp.json": "MCP server", "project mcp.json": "MCP server", "project .mcp.json": "MCP server", + "user mcp.json": "MCP server", "project mcp.json": "MCP server", "project .mcp.json": "MCP server", }; const NAMED = { "fit-user-skill": ["user skill", "skill"], "fit-user-set-skill": ["user settings skill", "skill"], "fit-user-pkg-skill": ["user package skill", "skill"], - "fit-default-skill": ["default agent skill", "skill"], "fit-project-skill": ["project skill", "skill"], "fit-project-set-skill": ["project settings skill", "skill"], + "fit-project-skill": ["project skill", "skill"], "fit-project-set-skill": ["project settings skill", "skill"], "fit-project-pkg-skill": ["project package skill", "skill"], "fit-agents-skill": ["project .agents skill", "skill"], "fit-home-skill": ["home .agents skill", "skill"], "fit-user-prompt": ["user prompt template", "prompt template"], "fit-user-set-prompt": ["user settings prompt template", "prompt template"], - "fit-user-pkg-prompt": ["user package prompt template", "prompt template"], "fit-default-prompt": ["default agent prompt template", "prompt template"], + "fit-user-pkg-prompt": ["user package prompt template", "prompt template"], "fit-project-prompt": ["project prompt template", "prompt template"], "fit-project-set-prompt": ["project settings prompt template", "prompt template"], "fit-project-pkg-prompt": ["project package prompt template", "prompt template"], }; @@ -326,9 +372,8 @@ const NAMED = { // SYSTEM.md or APPEND_SYSTEM.md loads only in a trusted project: the saved trust makes it trusted, // and only --no-approve undoes that with the seal flags on. const TEXTS = [ - ["agent/SYSTEM.md", "FITUSERSYSTEM", "user SYSTEM.md", "context file"], - ["agent/AGENTS.md", "FITUSERAGENTS", "user AGENTS.md", "context file"], - ["home/.pi/agent/AGENTS.md", "FITDEFAULTAGENTS", "default agent AGENTS.md", "context file"], + ["home/.pi/agent/SYSTEM.md", "FITUSERSYSTEM", "user SYSTEM.md", "context file"], + ["home/.pi/agent/AGENTS.md", "FITUSERAGENTS", "user AGENTS.md", "context file"], ["project/.pi/SYSTEM.md", "FITPROJECTSYSTEM", "project SYSTEM.md", "trusted project file"], ["project/.pi/APPEND_SYSTEM.md", "FITPROJECTAPPEND", "project APPEND_SYSTEM.md", "trusted project file"], ["project/AGENTS.md", "FITPROJECTAGENTS", "project AGENTS.md", "context file"], @@ -363,7 +408,7 @@ function plant(scratch) { 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 prompt = "A planted prompt template.\n"; - const agent = join(scratch, "agent"); + const agent = join(scratch, "home", ".pi", "agent"); const project = join(scratch, "project"); mkdirSync(marks, { recursive: true }); mkdirSync(join(scratch, "tmp"), { recursive: true }); @@ -399,11 +444,6 @@ function plant(scratch) { put(join(project, ".agents", "skills", "fit-agents-skill", "SKILL.md"), skill("fit-agents-skill")); put(join(project, ".pi", "prompts", "fit-project-prompt.md"), prompt); 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"), prompt); for (const [file, text] of TEXTS) put(join(scratch, file), `${text}\n`); put(join(scratch, "explicit", "fit.ts"), `import { writeFileSync } from "node:fs";\nexport default function (pi: any): void {\n writeFileSync(${JSON.stringify(join(marks, markerName(EXPLICIT)))}, "");\n pi.on("session_start", (_event: any, ctx: any) => { writeFileSync(${JSON.stringify(join(marks, "start.json"))}, JSON.stringify({ prompt: ctx.getSystemPrompt(), commands: pi.getCommands().map((c: any) => c.name), session: ctx.sessionManager.getSessionId() })); });\n}\n`); put(join(scratch, "explicit", "second.ts"), ext(SECOND)); diff --git a/packages/harness/tests/pi-fit.test.mjs b/packages/harness/tests/pi-fit.test.mjs index 265cb6aeb..80ca7fdd2 100644 --- a/packages/harness/tests/pi-fit.test.mjs +++ b/packages/harness/tests/pi-fit.test.mjs @@ -13,8 +13,8 @@ import * as fitModule 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 { BWRAP, sandboxProblem } from "../../seat/src/sandbox.mjs"; -import { ENV_ALLOW, sessionEnv } from "../../seat/src/session.mjs"; +import { BWRAP, sandboxProblem, sessionSetenv } from "../../seat/src/sandbox.mjs"; +import { ENV_ALLOW, isProviderVariable, sessionEnv } from "../../seat/src/session.mjs"; import { adapterEnv } from "../src/runner.mjs"; const REPO = resolve(fileURLToPath(new URL("../../../", import.meta.url))); @@ -143,7 +143,11 @@ test("pi-unpin S3 re-check 3: every run has its own scratch directory, and the r assert.equal(r.ok, true, r.message); const runs = readFileSync(log, "utf8").split("\n").filter(Boolean).map((l) => l.split("\x1f").slice(0, -1)).filter((a) => a.includes(found.view)).map((a) => { const scratch = a[a.indexOf("--chdir") + 1].replace(/\/project$/, ""); - return { scratch, args: a.slice(a.indexOf(found.view) + 1).map((x) => x.split(scratch).join("")) }; + // Re-check 6: the binary starts through /bin/sh, as the adapter starts it. (Its path is also + // MOSAIC_PI_BIN's value in a --setenv before it.) + const bin = a.indexOf('exec "$0" "$@"') + 1; + assert.deepEqual(a.slice(bin - 3, bin + 1), ["/bin/sh", "-c", 'exec "$0" "$@"', found.view]); + return { scratch, args: a.slice(bin + 1).map((x) => x.split(scratch).join("")) }; }); const seal = [...SEAL, ...extraFlags]; const loaders = [...LOADERS, ...extraFlags]; @@ -246,6 +250,67 @@ test("pi-unpin S3 re-check 5: a -c run must resume the planted session, a sessio assert.equal(fit(standIn(t, { extNoCommands: true }).env).message, "pi 2.0.0 (MOSAIC_PI_BIN) can't be checked: its -e extension didn't list a planted skill, prompt template without the seal flags"); }); +// Re-check 6 P2-1: no bus session has PI_CODING_AGENT_DIR (sessionEnv drops it), so its pi reads +// $HOME/.pi/agent. A pi that leaks only when the variable is unset must be refused. +test("pi-unpin S3 re-check 6: a pi that loads every kind when PI_CODING_AGENT_DIR is unset, as in a bus session, is refused", SKIP, t => { + const r = fit(standIn(t, { leakNoAgentDir: true }).env); + assert.equal(r.ok, false); + assert.match(r.message, /^pi 2\.0\.0 \(MOSAIC_PI_BIN\) loaded a planted /); +}); + +// Re-check 6 P3-2: the adapter passes -c whenever the session directory isn't empty, so -c can +// meet a directory with nothing for this workspace. A run for that costs about 340 ms cold, over +// the bar the Lead set, so pi-fit.mjs names it under "Not run". This test holds the gap open in +// plain sight: when a run for it lands, it goes red and must be turned round. +test("pi-unpin S3 re-check 6: a pi that leaks only under -c over a session directory with nothing for its directory passes: a named gap, not run", SKIP, t => { + assert.equal(fit(standIn(t, { leakNoMatch: true }).env).ok, true); +}); + +// A bus session's environment for pi, built the way the launcher, the sandbox and the runner build +// it: sessionEnv over a host that sets every ENV_ALLOW name and PI_CODING_AGENT_DIR (which it +// drops), the sandbox's sessionSetenv, adapterEnv with pi.env() as harnessEnv, and the runner's +// MOSAIC_REQUEST. A json run is a proxy session's first turn. A non-proxy run's PI_PROVIDER is the +// session's provider; a proxy run's is the transport's. +function busEnv(s, dir, { tools = [], thinking = "", provider = fitModule.SESSION_SHAPE.provider, json = false, prompt = join(dir, "prompt.md") } = {}) { + const host = Object.fromEntries(ENV_ALLOW.map((n) => [n, `host-${n.toLowerCase()}`])); + Object.assign(host, { PATH: `${dirname(process.execPath)}:/usr/bin:/bin`, MOSAIC_PI_BIN: s.env.MOSAIC_PI_BIN, PI_CODING_AGENT_DIR: join(dir, "host-agent") }); + const session = { provider, model: fitModule.SESSION_SHAPE.model, thinking, toolSocket: join(dir, "tools.sock"), proxyTransport: { piProvider: provider } }; + const harnessEnv = pi.env({ policy: { tools }, tools: [], session, proxy: json ? { key: "fixture-key" } : null, env: s.env }); + const runner = { ...sessionEnv(host, "fit1", json ? {} : null), ...sessionSetenv(dir, { business: "b", role: "r" }) }; + const env = adapterEnv({ ...session, bundle: { prompt, policy: join(dir, "policy.json"), tools: join(dir, "tools.json") }, workspace: join(dir, "ws"), sessionDir: join(dir, "session"), turnMarker: join(dir, "turn"), harnessEnv, runDir: dir, proxyFirstTurn: json }, runner); + return { ...env, MOSAIC_REQUEST: "x" }; +} + +// Re-check 6 P2-1, one step on: the fit runs' variables are a bus session's, built by the same +// code, so no run sets a name a session lacks or lacks one a session sets. The one named +// exception, with its reason: +const FIT_ENV_EXCEPT = [ + ["provider variables (isProviderVariable)", isProviderVariable, "the fit check passes no key: it calls no model"], +]; +test("pi-unpin S3 re-check 6: a fit run gets the variable names a bus session's pi gets, apart from a named list, and the runs themselves hold them", SKIP, t => { + const s = standIn(t, {}); + const dir = mkdtempSync(join(s.root, "env-")); + const kept = (names) => names.filter((n) => !FIT_ENV_EXCEPT.some(([, drop]) => drop(n))).sort(); + const names = {}; + for (const json of [false, true]) { + const bus = kept(Object.keys(busEnv(s, dir, { tools: ["read", "bash"], thinking: "low", json }))); + const fitNames = Object.keys(fitModule.fitEnv(dir, { view: "/fit/pi", shape: { tools: "read,bash", thinking: "low", json } })).sort(); + assert.deepEqual(fitNames.filter((n) => !bus.includes(n)), [], `fit names a bus session lacks (json ${json})`); + assert.deepEqual(bus.filter((n) => !fitNames.includes(n)), [], `bus names a fit run lacks (json ${json})`); + names[json ? "json" : "other"] = bus; + } + // A run that isn't session-shaped gets the same names as one without --mode json. + assert.deepEqual(Object.keys(fitModule.fitEnv(dir, { view: "/fit/pi" })).sort(), names.other); + assert.ok(!names.other.includes("PI_CODING_AGENT_DIR")); + // The env each run's process gets, not only fitEnv's object: this pi loads every kind when its + // variables differ from the bus names. It passes; expecting one name more is refused. + assert.equal(fit(standIn(t, { leakEnv: names }).env).ok, true); + for (const extra of [{ json: names.json, other: [...names.other, "PI_CODING_AGENT_DIR"] }, { json: [...names.json, "PI_CODING_AGENT_DIR"], other: names.other }]) { + assert.match(fit(standIn(t, { leakEnv: extra }).env).message ?? "passed", /loaded a planted /); + } + for (const [, drop, reason] of FIT_ENV_EXCEPT) assert.ok(typeof drop === "function" && reason.length > 0); +}); + // Re-check 5 item 2: the --no-mcp run is the only one that shows --no-mcp alone keeps MCP out. // This pi keeps MCP out with --no-mcp or with --no-context-files, so every other run hides that // --no-mcp does nothing on its own. @@ -405,51 +470,89 @@ test("pi-unpin S3: the adapter passes --no-mcp only when the module asks for it" assert.equal(run(standIn(t, {})).includes("--no-mcp"), false); }); -// Re-check 5 item 1: the adapter runs through every branch a bus session can reach, with the -// environment the runner hands it (sessionEnv's allowlist, adapterEnv, and pi.env() as harnessEnv). -// Each argv must be one sessionShape() builds, and each pair of its branches must be passed -// together by one session-shaped fit run. Every variable the adapter reads must come from that -// environment or be one no bus session gets, so a new adapter branch can't go unseen. -test("pi-unpin S3 re-check 5: every argv the adapter builds for a bus session is one sessionShape builds, and each pair of its branches is one a fit run passes", SKIP, t => { +// Re-check 5 item 1, narrowed by re-check 6 P3-1. The adapter runs with the environment a bus +// session's pi gets (busEnv: every ENV_ALLOW name set, sessionSetenv, adapterEnv, pi.env()), so +// HOME, TERM and the rest are set as a session sets them, not by the shell. Each argv must be one +// sessionShape() builds, and each pair of its branches must be passed together by a session-shaped +// fit run. What it tries: with and without --no-mcp; no tools, one, two; -c over an empty session +// directory, one holding a session file named as pi names them, and one holding an unrelated file; +// with and without --mode json; no thinking level and each level; each provider in PROVIDERS. +// Every combination of the first four, with thinking unset or low and the first provider; then +// each other level and each other provider, with and without --mode json. Every $NAME or ${NAME +// the adapter reads must be set in that environment, assigned by the adapter on an earlier line, +// set by the shell (SHELL_SET), or one no bus session gets (NOT_BUS). What it can't see: a branch +// keyed on a value it doesn't try (a model, a path, a request, a tool other than read and bash, a +// provider not listed), or on a pair of values where neither is from the base set. +// The provider names a session's PI_PROVIDER can hold: the providers whose key the pi module +// checks for (index.mjs), then the cliproxy and fixture transports' piProvider values. +const PROVIDERS = ["anthropic", "openai", "openrouter", "zai", "mosaic-proxy-glm", "mosaic-proxy-codex", "mosaic-proxy-other", "mosaic-fixture"]; +// Set by the shell, not the environment: the adapter saves and restores it around its loops. +const SHELL_SET = ["IFS"]; +test("pi-unpin S3 re-check 6: every argv the adapter builds in a bus session's environment is one sessionShape builds, over each tool count, -c case, thinking level and provider, and each pair of its branches is one a fit run passes", SKIP, t => { const adapter = join(REPO, "adapters", "pi", "adapter.sh"); // Set only by worker containers (packages/processing-control) and the TUI (scripts/agent.sh). const NOT_BUS = ["MOSAIC_SKILLS", "MOSAIC_SESSION_FORK", "MOSAIC_INTERACTIVE"]; for (const name of NOT_BUS) assert.ok(!ENV_ALLOW.includes(name), name); - const reads = new Set([...readFileSync(adapter, "utf8").matchAll(/\$\{?((?:MOSAIC|PI)_[A-Z_]+)/g)].map((m) => m[1])); - const set = new Set(["MOSAIC_REQUEST"]); // the runner adds it for each turn + const lines = readFileSync(adapter, "utf8").split("\n"); + const firstSet = new Map(); + lines.forEach((l, i) => { + for (const m of l.matchAll(/(?:^|[\s;])([A-Za-z_][A-Za-z0-9_]*)=|\bfor\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\b/g)) { + const name = m[1] ?? m[2]; + if (!firstSet.has(name)) firstSet.set(name, i); + } + }); + const reads = []; + lines.forEach((l, i) => { for (const m of l.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)/g)) reads.push([m[1], i]); }); + assert.ok(reads.length > 20, "the adapter's variable reads are found"); + const set = new Set(["MOSAIC_REQUEST"]); const branchKeys = ["tools", "cont", "thinking", "json"]; const covered = (b) => fitModule.SESSION_RUNS.some((r) => branchKeys.every((k) => !(k in b) || Boolean(r[k]) === b[k])); - let runs = 0; - for (const extraFlags of [[], ["--no-mcp"]]) { - const s = standIn(t, { extraFlags }); - const prompt = join(s.root, "prompt.md"); + const runs = []; + for (const noMcp of [false, true]) for (const tools of [[], ["read"], ["read", "bash"]]) for (const stored of ["none", "named", "other"]) for (const json of [false, true]) for (const thinking of ["", "low"]) runs.push({ noMcp, tools, stored, json, thinking, provider: PROVIDERS[0] }); + for (const json of [false, true]) { + for (const thinking of LEVELS.filter((l) => l !== "low")) runs.push({ noMcp: false, tools: ["read", "bash"], stored: "named", json, thinking, provider: PROVIDERS[0] }); + for (const provider of PROVIDERS.slice(1)) runs.push({ noMcp: false, tools: ["read", "bash"], stored: "named", json, thinking: "low", provider }); + } + const stands = new Map([false, true].map((noMcp) => [noMcp, standIn(t, { extraFlags: noMcp ? ["--no-mcp"] : [] })])); + const seenLevels = new Set(); + const seenProviders = new Set(); + for (const run of runs) { + const { noMcp, tools, stored, json, thinking, provider } = run; + const s = stands.get(noMcp); + const dir = mkdtempSync(join(s.root, "run-")); + const prompt = join(dir, "prompt.md"); writeFileSync(prompt, "p"); - for (const tools of [[], ["read", "bash"]]) for (const cont of [false, true]) for (const thinking of ["", "low"]) for (const json of [false, true]) { - const dir = mkdtempSync(join(s.root, "run-")); - const sessionDir = join(dir, "session"); - mkdirSync(sessionDir); - if (cont) writeFileSync(join(sessionDir, "earlier.jsonl"), "{}\n"); - const shape = fitModule.SESSION_SHAPE; - const session = { provider: shape.provider, model: shape.model, thinking, toolSocket: join(dir, "tools.sock"), proxyTransport: { piProvider: shape.provider } }; - const harnessEnv = pi.env({ policy: { tools }, tools: [], session, proxy: json ? { key: "fixture-key" } : null, env: s.env }); - const env = adapterEnv({ ...session, bundle: { prompt, policy: join(dir, "policy.json"), tools: join(dir, "tools.json") }, workspace: join(dir, "ws"), sessionDir, turnMarker: join(dir, "turn"), harnessEnv, runDir: dir, proxyFirstTurn: json }, - sessionEnv({ ...s.env, PATH: `${dirname(process.execPath)}:/usr/bin:/bin` }, "fit1", json ? {} : null)); - for (const name of NOT_BUS) assert.equal(env[name], undefined, name); - for (const name of Object.keys(env)) set.add(name); - const out = join(dir, "argv"); - const r = spawnSync("/bin/sh", [adapter], { encoding: "utf8", env: { ...env, ARGV_OUT: out, MOSAIC_REQUEST: "x" } }); - const label = JSON.stringify({ extraFlags, tools, cont, thinking, json }); - // The monitor reads the stand-in's empty output as no answer; the argv is written first. - if (!json) assert.equal(r.status, 0, r.stderr); - const argv = readFileSync(out, "utf8").split("\n").slice(0, -1); - const extensions = env.MOSAIC_EXTENSIONS.split(","); - assert.equal(extensions.length, 2, "the session-shaped fit runs pass two -e, as a session does"); - assert.deepEqual(argv, fitModule.sessionShape({ noMcp: extraFlags.length > 0, extensions, prompt, sessionDir, tools: tools.join(","), cont, thinking, json, message: "x" }), label); - const branch = { tools: tools.length > 0, cont, thinking: thinking !== "", json }; - for (const a of branchKeys) for (const b of branchKeys) if (a < b) assert.ok(covered({ [a]: branch[a], [b]: branch[b] }), `${label}: no fit run passes ${a}=${branch[a]} with ${b}=${branch[b]}`); - runs++; - } + const env = busEnv(s, dir, { tools, thinking, provider, json, prompt }); + const sessionDir = env.MOSAIC_SESSION_DIR; + mkdirSync(sessionDir, { recursive: true }); + if (stored === "named") writeFileSync(join(sessionDir, "2026-11-19T00-00-00-000Z_0b7c4f2e-0000-4000-8000-000000000000.jsonl"), "{}\n"); + if (stored === "other") writeFileSync(join(sessionDir, "notes.txt"), "x\n"); + for (const name of NOT_BUS) assert.equal(env[name], undefined, name); + for (const name of Object.keys(env)) set.add(name); + assert.equal(env.PI_PROVIDER, provider); + const out = join(dir, "argv"); + const r = spawnSync("/bin/sh", [adapter], { encoding: "utf8", env: { ...env, ARGV_OUT: out } }); + const label = JSON.stringify(run); + // The monitor reads the stand-in's empty output as no answer; the argv is written first. + if (!json) assert.equal(r.status, 0, r.stderr); + const argv = readFileSync(out, "utf8").split("\n").slice(0, -1); + const extensions = env.MOSAIC_EXTENSIONS.split(","); + assert.equal(extensions.length, 2, "the session-shaped fit runs pass two -e, as a session does"); + const cont = stored !== "none"; + const want = fitModule.sessionShape({ noMcp, extensions, prompt, sessionDir, tools: tools.join(","), cont, thinking, json, message: "x" }); + // The fit runs pass a fixed provider; the adapter passes the session's. + want[want.indexOf("--provider") + 1] = provider; + assert.deepEqual(argv, want, label); + const branch = { tools: tools.length > 0, cont, thinking: thinking !== "", json }; + for (const a of branchKeys) for (const b of branchKeys) if (a < b) assert.ok(covered({ [a]: branch[a], [b]: branch[b] }), `${label}: no fit run passes ${a}=${branch[a]} with ${b}=${branch[b]}`); + seenLevels.add(thinking); + seenProviders.add(provider); + } + assert.equal(runs.length, 2 * 3 * 3 * 2 * 2 + 2 * (LEVELS.length - 1) + 2 * (PROVIDERS.length - 1)); + assert.deepEqual([...seenLevels].sort(), ["", ...LEVELS].sort()); + assert.deepEqual([...seenProviders].sort(), [...PROVIDERS].sort()); + for (const [name, at] of reads) { + const local = firstSet.has(name) && firstSet.get(name) < at; + assert.ok(set.has(name) || local || SHELL_SET.includes(name) || NOT_BUS.includes(name), `the adapter reads ${name} (line ${at + 1}), which no bus session environment here sets and the adapter doesn't assign first`); } - assert.equal(runs, 32); - for (const name of reads) assert.ok(set.has(name) || NOT_BUS.includes(name), `the adapter reads ${name}, which no bus session environment here sets`); }); diff --git a/packages/harness/tests/pi-stand-in.mjs b/packages/harness/tests/pi-stand-in.mjs index f9d1bfe46..6160b4a37 100644 --- a/packages/harness/tests/pi-stand-in.mjs +++ b/packages/harness/tests/pi-stand-in.mjs @@ -38,7 +38,12 @@ // nothing. `leakWithout`: flags; when any of them is absent, every kind loads. // `leakWith`: flags; when all of them are given, every kind loads (with // `leakWithout` too, both must hold). `mcpAlso`: a flag that keeps MCP servers out -// as well as their own flag does. +// as well as their own flag does. `leakNoAgentDir`: every kind loads when +// PI_CODING_AGENT_DIR is unset, as in a bus session. `leakNoMatch`: with -c, every +// kind loads when no .jsonl in --session-dir names the working directory. +// `leakEnv`: { json, other }, the variable names a run with --mode json and any +// other run should get; every kind loads when the environment holds a name not in +// the list or lacks one, apart from the names /bin/sh sets (PWD, OLDPWD, SHLVL, _). // An -e extension that writes JSON.stringify({...}) at session_start gets the // prompt, the command names, the session id (with -c, the id in the header of a // .jsonl in --session-dir whose cwd is the working directory, else a new one) and @@ -92,6 +97,17 @@ if (rpc || print) { } } const ALL = ["extensions", "mcp", "skills", "prompts", "context", "approve"]; + // The id in the header of the last .jsonl in dir whose cwd is the working directory, or null. + const storedFor = (dir) => { + let id = null; + if (dir) for (const n of (() => { try { return fs.readdirSync(dir); } catch { return []; } })()) { + if (!n.endsWith(".jsonl")) continue; + let h = null; + try { h = JSON.parse(fs.readFileSync(path.join(dir, n), "utf8").split("\n")[0]); } catch { h = null; } + if (h && h.type === "session" && h.cwd === process.cwd()) id = h.id; + } + return id; + }; let ignoreAll = K.ignoreAll; let leak = new Set(K.sealLeak || []); if (K.hideWhen) { @@ -105,6 +121,13 @@ if (rpc || print) { else { fs.writeFileSync(marker, ""); leak = new Set(ALL); } } if ((K.leakWith || K.leakWithout) && (K.leakWith || []).every(has) && (!K.leakWithout || K.leakWithout.some((f) => !has(f)))) leak = new Set(ALL); + if (K.leakNoAgentDir && !process.env.PI_CODING_AGENT_DIR) leak = new Set(ALL); + if (K.leakNoMatch && has("-c") && !storedFor(val("--session-dir"))) leak = new Set(ALL); + if (K.leakEnv) { + const want = new Set(K.leakEnv[val("--mode") === "json" ? "json" : "other"]); + const got = Object.keys(process.env).filter((n) => !["PWD", "OLDPWD", "SHLVL", "_"].includes(n)); + if (got.length !== want.size || got.some((n) => !want.has(n))) leak = new Set(ALL); + } // Whether a seal flag is on: with standIn, its flag reads as the other flag; with needs, only // when that flag is given too. const sealed = (flag) => has(K.standIn && K.standIn[0] === flag ? K.standIn[1] : flag) && (!K.needs || has(K.needs)); @@ -175,11 +198,7 @@ if (rpc || print) { // The session -c resumes: the newest .jsonl in --session-dir whose header names this cwd. let session = "stand-in-" + process.pid; const dir = val("--session-dir"); - if (has("-c") && dir && !K.noResume) for (const f of list(dir, (n) => n.endsWith(".jsonl"))) { - let h = null; - try { h = JSON.parse((read(f) || "").split("\n")[0]); } catch { h = null; } - if (h && h.type === "session" && h.cwd === cwd) session = h.id; - } + if (has("-c") && dir && !K.noResume) session = storedFor(dir) || session; const start = { prompt: parts.join("\n"), commands: K.extNoCommands ? [] : commands.map((c) => c.name), session }; if (!(print && K.printNoStart)) for (const f of starts) fs.writeFileSync(f, JSON.stringify(start)); if (print) { diff --git a/packages/plugins/README.md b/packages/plugins/README.md index c8da9ad44..8000175ac 100644 --- a/packages/plugins/README.md +++ b/packages/plugins/README.md @@ -267,7 +267,9 @@ export returns: adapter passes, starts with a missing `-e` file, loads a planted ambient source or context file 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`. + passes `--no-mcp`; otherwise it sets `MOSAIC_PI_NO_MCP=0`. `env`'s + variables are built in `harness/pi/session-env.mjs`, which the fit + check also uses so its runs get a session's names. - `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/index.mjs b/packages/plugins/harness/pi/index.mjs index 43517da50..647c45410 100644 --- a/packages/plugins/harness/pi/index.mjs +++ b/packages/plugins/harness/pi/index.mjs @@ -9,6 +9,7 @@ import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; import { locate, printedVersion } from "./binary.mjs"; import { piFit } from "../../../harness/src/pi-fit.mjs"; +import { envNames, harnessEnv } from "./session-env.mjs"; export const interfaceVersion = 1; @@ -128,19 +129,7 @@ export function env({ policy, tools, session, proxy = null, env: hostEnv = proce // #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: 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(","), - PI_PROVIDER: proxy ? session.proxyTransport.piProvider : session.provider ?? "", - PI_MODEL: session.model, - MOSAIC_THINKING: session.thinking, - ...(proxy ? { ANTHROPIC_API_KEY: proxy.key } : {}), - }; + return harnessEnv({ bin: at.view, noMcp: fit.noMcp, tools: [...policy.tools, ...tools.map((t) => t.name)], extensions: [EXTENSION, UNSLOP.unslopExtension], session, proxy }); } // #1873 triage-fences: the names env() returns, less the provider key, and the directories its @@ -150,7 +139,8 @@ export function env({ policy, tools, session, proxy = null, env: hostEnv = proce // 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; // 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"]); +// session-env.mjs holds the list beside the builder. +export { envNames }; 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/harness/pi/session-env.mjs b/packages/plugins/harness/pi/session-env.mjs new file mode 100644 index 000000000..c50afc8c9 --- /dev/null +++ b/packages/plugins/harness/pi/session-env.mjs @@ -0,0 +1,26 @@ +// The variables the pi module hands a session (index.mjs env() returns them as harnessEnv). Built +// here, with no fit check, so packages/harness/src/pi-fit.mjs (#1873 S3) gives its runs the same +// names as a session gets without importing index.mjs, which imports it. +// +// bin: the binary's path inside the session. noMcp: the binary's --help lists --no-mcp. tools: the +// tool names. extensions: the -e files. session: { provider, model, thinking, proxyTransport }. +// proxy: { key } when the session runs on the proxy, else null. +export function harnessEnv({ bin, noMcp, tools, extensions, session, proxy = null }) { + return { + MOSAIC_PI_BIN: bin, + // "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: noMcp ? "1" : "0", + PI_OFFLINE: "1", + MOSAIC_TOOLS: tools.join(","), + MOSAIC_EXTENSIONS: extensions.join(","), + PI_PROVIDER: proxy ? session.proxyTransport.piProvider : session.provider ?? "", + PI_MODEL: session.model, + MOSAIC_THINKING: session.thinking, + ...(proxy ? { ANTHROPIC_API_KEY: proxy.key } : {}), + }; +} + +// #1873 triage-fences: the names harnessEnv returns, less the provider key. index.mjs exports +// them; its comment says what a hosted session's host does with them. +export const envNames = Object.freeze(["MOSAIC_PI_BIN", "MOSAIC_PI_NO_MCP", "PI_OFFLINE", "MOSAIC_TOOLS", "MOSAIC_EXTENSIONS", "PI_PROVIDER", "PI_MODEL", "MOSAIC_THINKING"]); diff --git a/packages/seat/src/sandbox.mjs b/packages/seat/src/sandbox.mjs index 00daadffb..c0b564c6d 100644 --- a/packages/seat/src/sandbox.mjs +++ b/packages/seat/src/sandbox.mjs @@ -185,12 +185,19 @@ export function gitIdentity({ business, role }) { return { GIT_AUTHOR_NAME: role, GIT_AUTHOR_EMAIL: email, GIT_COMMITTER_NAME: role, GIT_COMMITTER_EMAIL: email }; } -// The full command line for `command` inside the sandbox. HOME is the run's -// home/, empty at the start; the harness makes what it needs there. The git -// identity is the role's, for the business it runs in. +// The variables the sandbox sets for a session's runner, over the session env +// the launcher hands it. HOME is the run's home/, empty at the start; the +// harness makes what it needs there. TMPDIR is the private /tmp. The git +// identity is the role's, for the business it runs in. #1873 S3: the pi fit +// check gives its runs these too, so they get the names a session gets. +export function sessionSetenv(runDir, { business, role }) { + return { HOME: join(runDir, "home"), TMPDIR: "/tmp", ...gitIdentity({ business, role }) }; +} + +// The full command line for `command` inside the sandbox, with sessionSetenv's variables. export function sandboxArgv(list, runDir, command, { business, role, bwrap = BWRAP }) { - const identity = Object.entries(gitIdentity({ business, role })).flatMap(([k, v]) => ["--setenv", k, v]); - return [bwrap, ...NAMESPACES, ...argsOf(list), "--remount-ro", "/", "--setenv", "HOME", join(runDir, "home"), "--setenv", "TMPDIR", "/tmp", ...identity, "--chdir", runDir, "--", ...KILL_WITH_PARENT, ...command]; + const setenv = Object.entries(sessionSetenv(runDir, { business, role })).flatMap(([k, v]) => ["--setenv", k, v]); + return [bwrap, ...NAMESPACES, ...argsOf(list), "--remount-ro", "/", ...setenv, "--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