import { spawn } from "node:child_process"; import { mkdir, readFile, realpath } from "node:fs/promises"; import { dirname, isAbsolute, join } from "node:path"; import { fileURLToPath } from "node:url"; import { readStoredCredential } from "@earendil-works/pi-coding-agent"; import { REPOSITORY, rootPath, within } from "./harness.ts"; /** Read-only host; only the approved root is writable. Hide HOME, other temp trees and host processes. */ export async function sandboxCommand(root: string): Promise { root = rootPath(root); await within(root, root); const repository = await realpath(REPOSITORY); const node = await realpath(process.execPath); const nodeRoot = dirname(dirname(node)); return [ "--die-with-parent", "--new-session", "--unshare-pid", "--unshare-ipc", "--unshare-user", "--disable-userns", "--ro-bind", "/", "/", "--tmpfs", "/home", "--tmpfs", "/root", "--tmpfs", "/tmp", "--tmpfs", "/run/user", "--ro-bind", repository, repository, "--ro-bind", nodeRoot, nodeRoot, "--bind", root, root, "--proc", "/proc", "--dev", "/dev", "--chdir", root, "--clearenv", "--setenv", "ULTRA_EVAL_CONFINED", "1", "--setenv", "PATH", `${join(nodeRoot, "bin")}:${join(repository, "node_modules/.bin")}:/usr/bin:/bin`, "--setenv", "HOME", join(root, "home"), "--setenv", "PI_CODING_AGENT_DIR", join(root, "agent"), "--setenv", "TMPDIR", join(root, "tmp"), "--setenv", "PI_CONTEXT_DOCS", join(repository, "node_modules/@earendil-works/pi-coding-agent/docs"), "--setenv", "PI_CONTEXT_EXAMPLES", join(repository, "node_modules/@earendil-works/pi-coding-agent/examples"), ]; } /** Credential travels once through an anonymous pipe, never argv, env, file or stdout. */ export async function isolatedCanary( root: string, trial: string, authPath: string, ): Promise { if (!isAbsolute(authPath)) throw new Error("Explicit absolute credential path required"); const command = await sandboxCommand(root); trial = await within(root, trial); for (const directory of ["home", "agent", "tmp"]) await mkdir(join(root, directory), { recursive: true }); const manifest = JSON.parse( await readFile(join(root, "manifest.json"), "utf8"), ); const provider = String(manifest.model).split("/")[0]; if (!provider) throw new Error("Manifest provider missing"); const credential = readStoredCredential(provider, authPath); if (!credential) throw new Error("Provider credential missing"); const child = spawn( "bwrap", [ ...command, process.execPath, fileURLToPath(new URL("cli.ts", import.meta.url)), "canary-child", root, trial, provider, ], { stdio: ["pipe", "inherit", "ignore"], }, ); child.stdin.on("error", () => {}); child.stdin.end(JSON.stringify(credential)); await new Promise((resolve, reject) => { child.once("error", () => reject(new Error("Native sandbox could not start")), ); child.once("close", (code) => code === 0 ? resolve() : reject(new Error("Native sandbox failed; no unconfined fallback")), ); }); }