diff --git a/packages/seat/src/sandbox.mjs b/packages/seat/src/sandbox.mjs index d463d8741..435f86960 100644 --- a/packages/seat/src/sandbox.mjs +++ b/packages/seat/src/sandbox.mjs @@ -193,6 +193,48 @@ 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 triage-host: the binds for a session the Console hosts in no organization (Triage). It +// gets the system part, the runner's files, the adapter and the harness module's mounts like any +// session, and from the data root exactly two directories: its own `runDir` read-write, and +// `healthDir` read-only over runDir/work/health, inside the workspace the read tools' gate allows. The run's bundle/, session.json and the relay socket the runner +// calls through stay read-only inside it, and its tmp/ is /tmp. There is no workspace, broker, +// launch or git socket, thread store or org root. Each source inside runDir must be what the host +// just made there, never a link the session left: bwrap resolves a bind's source on the host. +export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], relaySocket, node = process.execPath, readOnly = [] }) { + if (relaySocket !== join(runDir, "relay.sock")) throw new Error("hosted binds: the relay socket must be the run directory's relay.sock"); + const healthDest = join(runDir, "work", "health"); + for (const p of [runDir, healthDir, join(runDir, "bundle"), join(runDir, "tmp"), join(runDir, "work"), healthDest]) { + let st; + try { st = lstatSync(p); } catch { throw new Error(`hosted binds: ${p === healthDir ? "the health directory" : relative(runDir, p) || "the run directory"} is missing`); } + if (st.isSymbolicLink() || !st.isDirectory()) throw new Error(`hosted binds: ${p === healthDir ? "the health directory" : relative(runDir, p) || "the run directory"} is not a directory`); + } + for (const [p, ok] of [[join(runDir, "session.json"), (st) => st.isFile()], [relaySocket, (st) => st.isSocket()]]) { + let st; + try { st = lstatSync(p); } catch { throw new Error(`hosted binds: ${relative(runDir, p)} is missing`); } + if (!ok(st)) throw new Error(`hosted binds: ${relative(runDir, p)} is not what the host made`); + } + const out = systemBinds(node); + for (const f of RUNNER_FILES) out.push({ kind: "ro", src: f, why: "a repository file the runner loads" }); + out.push({ kind: "ro", src: adapter, why: "the harness adapter the runner starts each turn" }); + for (const m of harnessMounts) out.push({ kind: "ro", src: m.src, ...(m.dest ? { dest: m.dest } : {}), why: m.why }); + for (const f of readOnly) out.push({ kind: "ro", src: f, why: "a test fixture" }); + out.push( + { kind: "rw", src: runDir, why: "the session's own state: turns/, session/, work/, tools.sock, turn.done, home/, tmp/" }, + { kind: "ro", src: healthDir, dest: healthDest, why: "the health snapshots the Console writes, read-only, inside the workspace the read tools reach" }, + { kind: "ro", src: join(runDir, "bundle"), why: "the run's bundle stays as the host wrote it" }, + { kind: "ro", src: join(runDir, "session.json"), why: "the session file stays as the host wrote it" }, + { kind: "ro", src: relaySocket, why: "the host's relay, the only broker the runner reaches" }, + { kind: "rw", src: join(runDir, "tmp"), dest: "/tmp", why: "a private /tmp, on disk in the run directory" }, + ); + return out; +} + +// The command line for a hosted session: as sandboxArgv, with no git identity, since a hosted +// session belongs to no organization and holds no git verb. +export function hostedArgv(list, runDir, command, { bwrap = BWRAP } = {}) { + return [bwrap, ...NAMESPACES, ...argsOf(list), "--remount-ro", "/", "--setenv", "HOME", join(runDir, "home"), "--setenv", "TMPDIR", "/tmp", "--chdir", runDir, "--", ...KILL_WITH_PARENT, ...command]; +} + // Whether bwrap runs here at all: the namespaces and the system binds, then // setpriv and `true`. Returns null, or why not. export function sandboxProblem({ bwrap = BWRAP } = {}) { diff --git a/packages/seat/tests/hosted-binds.test.mjs b/packages/seat/tests/hosted-binds.test.mjs new file mode 100644 index 000000000..bfd64db77 --- /dev/null +++ b/packages/seat/tests/hosted-binds.test.mjs @@ -0,0 +1,83 @@ +// #1873 triage-host: the binds of a session the Console hosts in no organization. From the data root +// it gets its own run directory and the health directory, read-only, and nothing else; every source +// inside the run directory must be what the host made, never a link. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:net"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { RUNNER_FILES, hostedArgv, hostedBinds } from "../src/sandbox.mjs"; + +function layout(t) { + const root = mkdtempSync(join(process.env.TMPDIR, "hb-")); + const dataRoot = join(root, "data"); + const runDir = join(dataRoot, "triage", "agent"); + const healthDir = join(dataRoot, "triage", "health"); + for (const d of [join(dataRoot, "orgs"), join(dataRoot, "triage", "host"), healthDir, join(runDir, "bundle"), join(runDir, "tmp"), join(runDir, "work", "health")]) mkdirSync(d, { recursive: true }); + writeFileSync(join(runDir, "session.json"), "{}"); + const adapter = join(root, "adapter.sh"); + writeFileSync(adapter, "exit 0\n"); + return new Promise((resolve) => { + const server = createServer().listen(join(runDir, "relay.sock"), () => { + t.after(() => server.close()); + resolve({ root, dataRoot, runDir, healthDir, adapter, relaySocket: join(runDir, "relay.sock") }); + }); + }); +} + +test("hosted binds hold the run directory and the health directory of the data root, and nothing else of it", async (t) => { + const p = await layout(t); + const list = hostedBinds({ runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket }); + const fromData = list.filter((b) => typeof b.src === "string" && b.src.startsWith(p.dataRoot + "/")); + assert.deepEqual(fromData.map((b) => [b.kind, b.src, b.dest ?? null]), [ + ["rw", p.runDir, null], + ["ro", p.healthDir, join(p.runDir, "work", "health")], + ["ro", join(p.runDir, "bundle"), null], + ["ro", join(p.runDir, "session.json"), null], + ["ro", p.relaySocket, null], + ["rw", join(p.runDir, "tmp"), "/tmp"], + ]); + for (const f of RUNNER_FILES) assert.ok(list.some((b) => b.kind === "ro" && b.src === f), f); + assert.ok(list.some((b) => b.kind === "ro" && b.src === p.adapter)); + assert.ok(!list.some((b) => b.src === p.root || b.src === p.dataRoot || (typeof b.src === "string" && b.src.startsWith(join(p.dataRoot, "orgs"))))); + assert.ok(!list.some((b) => b.src === process.env.HOME || b.dest === process.env.HOME)); + assert.ok(list.every((b) => typeof b.why === "string" && b.why.length > 0)); +}); + +test("hosted binds refuse a relay socket elsewhere, and any source in the run directory that the host did not make", async (t) => { + const p = await layout(t); + const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket }; + assert.throws(() => hostedBinds({ ...base, relaySocket: join(p.root, "bus.sock") }), /relay socket must be the run directory's relay\.sock/); + // A link in place of each directory the binds read: bwrap would follow it on the host. + for (const d of ["bundle", "tmp", "work"]) { + rmSync(join(p.runDir, d), { recursive: true }); + symlinkSync(join(p.dataRoot, "orgs"), join(p.runDir, d)); + assert.throws(() => hostedBinds(base), /is not a directory/, d); + rmSync(join(p.runDir, d)); + mkdirSync(join(p.runDir, d === "work" ? join("work", "health") : d), { recursive: true }); + } + rmSync(join(p.runDir, "work", "health"), { recursive: true }); + symlinkSync(join(p.dataRoot, "triage", "host"), join(p.runDir, "work", "health")); + assert.throws(() => hostedBinds(base), /is not a directory/); + rmSync(join(p.runDir, "work", "health")); + mkdirSync(join(p.runDir, "work", "health")); + rmSync(join(p.runDir, "session.json")); + symlinkSync(join(p.dataRoot, "orgs"), join(p.runDir, "session.json")); + assert.throws(() => hostedBinds(base), /session\.json is not what the host made/); + rmSync(join(p.runDir, "session.json")); + writeFileSync(join(p.runDir, "session.json"), "{}"); + assert.throws(() => hostedBinds({ ...base, healthDir: join(p.root, "absent") }), /the health directory is missing/); + hostedBinds(base); +}); + +test("the hosted command line sets no git identity and runs the command under the namespaces", async (t) => { + const p = await layout(t); + const argv = hostedArgv(hostedBinds({ runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket }), p.runDir, ["node", "runner.mjs", p.runDir], { bwrap: "/b/bwrap" }); + assert.equal(argv[0], "/b/bwrap"); + assert.deepEqual(argv.slice(1, 5), ["--unshare-user", "--unshare-pid", "--unshare-ipc", "--as-pid-1"]); + assert.deepEqual(argv.slice(-3), ["node", "runner.mjs", p.runDir]); + assert.ok(!argv.some((a) => a.startsWith("GIT_"))); + const home = argv.indexOf("HOME"); + assert.equal(argv[home + 1], join(p.runDir, "home")); + assert.ok(argv.includes("--remount-ro")); +}); diff --git a/packages/webui/src/triage-host.mjs b/packages/webui/src/triage-host.mjs new file mode 100644 index 000000000..d3bf00d5b --- /dev/null +++ b/packages/webui/src/triage-host.mjs @@ -0,0 +1,376 @@ +// #1873 triage-host: the Triage session's host, held by the Console (design sections 1 and 4). +// +// Directories, under /triage/ (0700, real directories owned by this user): +// health/ the snapshot the Console writes (triage-snapshot.mjs); mounted read-only +// agent/ the session's own run directory; mounted read-write, with bundle/, session.json and +// relay.sock read-only inside it +// host/ the transcript (transcript.jsonl, 0600) and the runner's log; never mounted +// Nothing else of the data root, no org root, bus socket, config directory or secrets directory is +// in the sandbox (packages/seat/src/sandbox.mjs, hostedBinds). +// +// The session starts on the owner's first message, never when the Console starts. Its spawn +// environment is SPAWN_ENV_ALLOW and the route's ROUTE_ENV_ALLOW names; bwrap adds HOME and TMPDIR. +// No MOSAIC_CONFIG, no MOSAIC_BUS_* and no Console variable reaches it. +// +// The relay is the only broker the runner reaches. It answers the runner's own lifecycle verbs with +// fixed answers that change nothing, hands over the owner's queued messages, and keeps a +// message.send only when it is addressed to "human": that text goes into the transcript and its +// cards are checked (triage-cards.mjs). Every other verb, decision.raise and event.emit included, +// a send to anyone else and a call with the wrong capability are refused with RELAY_REFUSED. +// +// A model route comes from an injected `route` ({ admit() }). Without one nothing launches and the +// state says so. The route's answer names the harness: adapter, its mounts, harnessEnv, turnEnd, +// model and provider, and the proxy variables for the spawn. Over the cap the route refuses until +// the next day, and the message is refused with its code. + +import { spawn } from "node:child_process"; +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { appendFileSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, chmodSync, writeFileSync } from "node:fs"; +import { createServer } from "node:net"; +import { dirname, join } from "node:path"; +import { BWRAP, REPO, RUNNER_FILES, hostedArgv, hostedBinds } from "../../seat/src/sandbox.mjs"; +import { typedTools } from "../../harness/src/tools.mjs"; +import { builtinTools } from "../../harness/src/bundle.mjs"; +import { FOUNDER_ENV } from "../../harness/src/runner.mjs"; +import { extractCards, plainText } from "./triage-cards.mjs"; +import { SNAPSHOT_FILE, writeSnapshot } from "./triage-snapshot.mjs"; + +export const RUNNER = RUNNER_FILES[0]; +export const RELAY_REFUSED = "triage-refused"; +export const MESSAGE_MAX = 4000; +export const TRANSCRIPT_KEEP = 200; +export const QUEUE_MAX = 20; +const LINE_MAX = 64 * 1024; +const CAP = /^[0-9a-f]{64}$/; + +// The spawn's environment: these names from the Console's own environment, PATH fixed, and the +// route's proxy variables. bwrap sets HOME and TMPDIR inside. +export const SPAWN_ENV_ALLOW = Object.freeze(["PATH", "LANG", "LC_ALL", "TZ", "TERM"]); +export const ROUTE_ENV_ALLOW = Object.freeze(["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"]); +const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/; +const deniedHarnessName = (k) => !ENV_NAME.test(k) || k === "MOSAIC_CONFIG" || k.startsWith("MOSAIC_BUS_") || FOUNDER_ENV.includes(k) || k === "SSH_AUTH_SOCK"; + +export function triageEnv(source, routeEnv = {}, { node = process.execPath } = {}) { + const env = { PATH: `${dirname(node)}:/usr/bin:/bin` }; + for (const k of SPAWN_ENV_ALLOW) if (k !== "PATH" && typeof source?.[k] === "string" && source[k].length <= 256) env[k] = source[k]; + for (const k of ROUTE_ENV_ALLOW) if (typeof routeEnv?.[k] === "string" && routeEnv[k].length <= 4096) env[k] = routeEnv[k]; + return env; +} + +// The relay's fixed answers. None of them reaches a bus or changes anything. +const LIFECYCLE = Object.freeze({ + "role.claim": () => ({ library: false }), + state: () => ({ launch: { state: "on", at: null, event: null }, tasks: { open: [], total: 0, cap: 0 } }), + "processing.status": () => ({ halted: false, invalid: false }), + "usage.begin": () => ({}), + "usage.end": () => ({}), + "role.release": () => ({}), +}); + +export class TriageError extends Error { + constructor(code, message) { + super(message); + this.code = code; + } +} + +function realDir(path, { create = true } = {}) { + let st; + try { + st = lstatSync(path); + } catch (e) { + if (e.code !== "ENOENT" || !create) throw new TriageError("triage-dir-unsafe", "a Triage directory is missing"); + mkdirSync(path, { mode: 0o700 }); + st = lstatSync(path); + } + if (st.isSymbolicLink() || !st.isDirectory()) throw new TriageError("triage-dir-unsafe", "a Triage directory is not a real directory"); + if (typeof process.getuid === "function" && st.uid !== process.getuid()) throw new TriageError("triage-dir-unsafe", "a Triage directory is not owned by the Console's user"); + chmodSync(path, 0o700); +} + +// A directory inside agent/, which the session can write: removed whole (rm never follows a link) +// and made again, so a link the session left there can't steer a bind or a host write. +function freshDir(path) { + rmSync(path, { recursive: true, force: true }); + mkdirSync(path, { mode: 0o700 }); +} + +export function triagePaths(dataRoot) { + const root = join(dataRoot, "triage"); + return { root, health: join(root, "health"), agent: join(root, "agent"), host: join(root, "host"), transcript: join(root, "host", "transcript.jsonl"), log: join(root, "host", "runner.log") }; +} + +// The prompt is the role's contract and the host's own lines: where the snapshot is and how a +// card is written. It names the snapshot inside the session, never a host path of the data root. +export function hostPrompt(contract, { snapshotPath, steps }) { + return [ + contract.trimEnd(), + "", + "## This host", + "", + `- The health snapshot is the JSON file ${snapshotPath}. Read it at the start of each turn; it is the only health you can see. A field that says "not read" was not read; say so, never guess it.`, + "- Each message arrives as one turn and your final answer goes back to the person. send_message reaches only \"human\"; this host refuses every other call.", + "- Propose each fix as a card in one fenced block marked cards, holding a JSON array of objects with exactly two keys, step and org, for example:", + "```cards", + '[{"step": "bus-start", "org": "alpha"}]', + "```", + `- step is one of: ${steps.join(", ")}. org is an organization id from the snapshot. The Console writes the command for each card; never write a command yourself. A card with anything else is dropped.`, + "", + ].join("\n"); +} + +function sameCap(a, b) { + if (typeof a !== "string" || !CAP.test(a)) return false; + return timingSafeEqual(Buffer.from(a), Buffer.from(b)); +} + +// The relay server. `onSend(body)` keeps a human-bound send; `take()` returns the queued owner +// messages; `read(id)` drops one that was answered. +export function createRelay({ socket, cap, take, read, onSend, log = () => {} }) { + const answer = (conn, value) => { try { conn.end(JSON.stringify(value) + "\n"); } catch {} }; + const refuse = (conn) => answer(conn, { ok: false, error: RELAY_REFUSED, reason: "the Triage host answers only a message to the person" }); + const server = createServer((conn) => { + let buf = ""; + let done = false; + conn.setTimeout(30_000, () => conn.destroy()); + conn.on("error", () => {}); + conn.on("data", (chunk) => { + if (done) return; + buf += chunk.toString("utf8"); + if (buf.length > LINE_MAX) { done = true; return refuse(conn); } + const nl = buf.indexOf("\n"); + if (nl < 0) return; + done = true; + let req; + try { req = JSON.parse(buf.slice(0, nl)); } catch { return refuse(conn); } + if (!req || typeof req !== "object" || !sameCap(req.cap, cap) || typeof req.verb !== "string") return refuse(conn); + const args = req.args && typeof req.args === "object" && !Array.isArray(req.args) ? req.args : {}; + const verb = req.verb; + try { + if (Object.hasOwn(LIFECYCLE, verb)) return answer(conn, { ok: true, result: LIFECYCLE[verb]() }); + if (verb === "message.receive") return answer(conn, { ok: true, result: take() }); + if (verb === "message.read") { read(args.id); return answer(conn, { ok: true, result: {} }); } + if (verb === "message.send" && args.to === "human" && typeof args.body === "string" && args.body.length <= 32768) { + onSend({ body: args.body, in_reply_to: typeof args.in_reply_to === "string" ? args.in_reply_to : null }); + return answer(conn, { ok: true, result: { id: `triage-${randomBytes(6).toString("hex")}` } }); + } + } catch (e) { + log(`triage relay: ${verb} failed: ${e.code ?? "error"}`); + } + log(`triage relay: refused ${/^[a-z][a-z0-9._-]{0,63}$/.test(verb) ? verb : "a verb"}`); + return refuse(conn); + }); + }); + return new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socket, () => { + server.off("error", reject); + chmodSync(socket, 0o600); + resolve(server); + }); + }); +} + +// createTriageHost({ dataRoot, route, readSnapshot, env, node, bwrap, now, log }) +// route { admit() -> { ok: true, adapter, harness, harnessEnv, harnessMounts, turnEnd, model, +// provider, env } | { ok: false, code, until? } } or null for no route +// readSnapshot async () -> the snapshot (triage-snapshot.mjs composeSnapshot), written to health/ +// pollInterval the runner's receive interval in ms, for tests; the runner's default otherwise +export function createTriageHost({ dataRoot, route = null, readSnapshot = async () => null, env = process.env, node = process.execPath, bwrap = BWRAP, now = () => new Date(), log = () => {}, roleDir = join(REPO, "roles"), readOnly = [], pollInterval = null }) { + if (typeof dataRoot !== "string" || !dataRoot.startsWith("/")) throw new TriageError("triage-no-data-root", "no data root"); + const paths = triagePaths(dataRoot); + const role = JSON.parse(readFileSync(join(roleDir, "triage.json"), "utf8")); + const contract = readFileSync(join(roleDir, role.contract), "utf8"); + let last = null; // the last snapshot written + let child = null; + let relay = null; + let starting = null; + let lastExit = null; + let cap = null; + const queue = []; + + const ensureDirs = () => { + mkdirSync(dataRoot, { recursive: true, mode: 0o700 }); + for (const d of [paths.root, paths.health, paths.agent, paths.host]) realDir(d); + }; + + const append = (entry) => { + ensureDirs(); + const fd = openSync(paths.transcript, "a", 0o600); + try { appendFileSync(fd, JSON.stringify(entry) + "\n"); } finally { closeSync(fd); } + chmodSync(paths.transcript, 0o600); + }; + + const transcript = () => { + let text = ""; + try { + const st = lstatSync(paths.transcript); + if (!st.isFile()) return []; + text = readFileSync(paths.transcript, "utf8"); + } catch { return []; } + const out = []; + for (const line of text.split("\n")) { + if (!line) continue; + try { out.push(JSON.parse(line)); } catch {} + } + return out.slice(-TRANSCRIPT_KEEP); + }; + + const orgIds = () => new Set(Array.isArray(last?.organizations?.list) ? last.organizations.list.map((o) => o.id) : []); + + const refresh = async () => { + ensureDirs(); + let snap = null; + try { snap = await readSnapshot(); } catch { snap = null; } + if (snap && typeof snap === "object") { + writeSnapshot(paths.health, snap); + last = snap; + } + return last; + }; + + const writeBundle = (admitted) => { + const a = paths.agent; + for (const d of ["bundle", "tmp", "work", "home"]) freshDir(join(a, d)); + mkdirSync(join(a, "work", "health"), { mode: 0o700 }); + for (const f of ["session.json", "relay.sock", "tools.sock", "turn.done"]) rmSync(join(a, f), { recursive: true, force: true }); + // The session's history stays across starts, unless the session put something other than a + // real directory there. + try { realDir(join(a, "session")); } catch { freshDir(join(a, "session")); } + const resolved = { limits: { authority: role.authority, tools: role.tools }, definition: "triage", pluginTools: [] }; + const tools = typedTools({ resolved }).filter((t) => t.name === "send_message"); + const workspace = join(a, "work"); + const policy = { harness: admitted.harness, workspace, tools: builtinTools(role.tools), typed: tools.map((t) => t.name), network: role.network, needs: [], credentials: [] }; + const bundle = { prompt: join(a, "bundle", "prompt.md"), policy: join(a, "bundle", "policy.json"), tools: join(a, "bundle", "tools.json") }; + const steps = ["bus-start", "bus-restart", "bus-recover", "bus-stop", "org-config-validate"]; + writeFileSync(bundle.prompt, hostPrompt(contract, { snapshotPath: join(workspace, "health", SNAPSHOT_FILE), steps }), { mode: 0o600, flag: "wx" }); + writeFileSync(bundle.policy, JSON.stringify(policy, null, 2) + "\n", { mode: 0o600, flag: "wx" }); + writeFileSync(bundle.tools, JSON.stringify(tools, null, 2) + "\n", { mode: 0o600, flag: "wx" }); + const session = { + bundle, adapter: admitted.adapter, harness: admitted.harness, harnessEnv: admitted.harnessEnv, turnEnd: admitted.turnEnd, + workspace, sessionDir: join(a, "session"), toolSocket: join(a, "tools.sock"), turnMarker: join(a, "turn.done"), + brokerSocket: join(a, "relay.sock"), business: "system", instance: "triage", run: `triage-${now().toISOString().replace(/[^0-9]/g, "").slice(0, 14)}`, + model: admitted.model, provider: admitted.provider ?? "", + ...(Number.isInteger(pollInterval) && pollInterval >= 100 ? { pollInterval } : {}), + }; + writeFileSync(join(a, "session.json"), JSON.stringify(session, null, 2) + "\n", { mode: 0o600, flag: "wx" }); + }; + + const checkAdmitted = (a) => { + if (!a || typeof a !== "object" || typeof a.adapter !== "string" || !a.adapter.startsWith("/") + || !["marker", "exit"].includes(a.turnEnd) || typeof a.model !== "string" || !a.model + || typeof a.harness !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(a.harness) + || !a.harnessEnv || typeof a.harnessEnv !== "object" || Array.isArray(a.harnessEnv) + || Object.entries(a.harnessEnv).some(([k, v]) => typeof v !== "string" || deniedHarnessName(k)) + || !Array.isArray(a.harnessMounts ?? [])) throw new TriageError("triage-route-invalid", "the model route's answer is not usable"); + }; + + const start = async (admitted) => { + checkAdmitted(admitted); + ensureDirs(); + writeBundle(admitted); + cap = randomBytes(32).toString("hex"); + relay = await createRelay({ + socket: join(paths.agent, "relay.sock"), cap, + take: () => { + const out = queue.filter((m) => !m.delivered); + for (const m of out) m.delivered = true; + return out.map(({ id, body, at }) => ({ id, from_role: "human", class: "REQUEST", body, at })); + }, + read: (id) => { + const i = queue.findIndex((m) => m.id === id); + if (i >= 0) queue.splice(i, 1); + }, + onSend: ({ body, in_reply_to }) => { + const { text, cards, dropped } = extractCards(body, orgIds()); + append({ at: now().toISOString(), from: "triage", text, cards, dropped, ...(in_reply_to ? { in_reply_to } : {}) }); + }, + log, + }); + const list = hostedBinds({ runDir: paths.agent, healthDir: paths.health, adapter: admitted.adapter, harnessMounts: admitted.harnessMounts ?? [], relaySocket: join(paths.agent, "relay.sock"), node, readOnly }); + const argv = hostedArgv(list, paths.agent, [node, RUNNER, paths.agent], { bwrap }); + const out = openSync(paths.log, "a", 0o600); + try { + child = spawn(argv[0], argv.slice(1), { env: triageEnv(env, admitted.env, { node }), detached: true, stdio: ["pipe", out, out] }); + } finally { + closeSync(out); + } + const mine = child; + mine.on("error", () => {}); + mine.stdin.on("error", () => {}); + mine.stdin.end(JSON.stringify({ cap }) + "\n"); + mine.on("exit", (code, signal) => { + if (child !== mine) return; + lastExit = { code: Number.isInteger(code) ? code : null, signal: signal ?? null, at: now().toISOString() }; + child = null; + relay?.close(); + relay = null; + rmSync(join(paths.agent, "relay.sock"), { force: true }); + }); + }; + + const admit = async () => { + if (!route || typeof route.admit !== "function") return { ok: false, code: "triage-no-route" }; + let a; + try { a = await route.admit(); } catch { return { ok: false, code: "triage-route-unreadable" }; } + if (a?.ok === true) return a; + const code = ["triage-no-route", "triage-over-cap"].includes(a?.code) ? a.code : "triage-route-refused"; + return { ok: false, code, ...(typeof a?.until === "string" ? { until: a.until } : {}) }; + }; + + return { + paths, + get running() { return child !== null; }, + get pid() { return child?.pid ?? null; }, + routeSet: () => Boolean(route && typeof route.admit === "function"), + async state() { + return { + route: this.routeSet() ? "set" : "not set", + running: child !== null, + lastExit, + snapshot: last, + transcript: transcript(), + }; + }, + refresh, + // The owner's message: checked, admitted by the route, written to the transcript, queued, and + // the session started when it isn't running. + async message(raw) { + const text = plainText(typeof raw === "string" ? raw : "", MESSAGE_MAX + 1).trim(); + if (!text) throw new TriageError("triage-message-empty", "the message is empty"); + if (text.length > MESSAGE_MAX) throw new TriageError("triage-message-too-long", `a message holds at most ${MESSAGE_MAX} characters`); + if (queue.length >= QUEUE_MAX) throw new TriageError("triage-busy", "Triage has too many messages waiting"); + const admitted = await admit(); + if (!admitted.ok) throw Object.assign(new TriageError(admitted.code, admitted.code === "triage-over-cap" ? "Triage is over its daily cap" : admitted.code === "triage-no-route" ? "no model route is set for Triage" : "the model route refused"), admitted.until ? { until: admitted.until } : {}); + await refresh(); + const at = now().toISOString(); + const id = `owner-${randomBytes(6).toString("hex")}`; + append({ at, from: "owner", id, text }); + queue.push({ id, body: text, at, delivered: false }); + if (!child) { + starting ??= start(admitted).finally(() => { starting = null; }); + try { await starting; } + catch (e) { + queue.splice(queue.findIndex((m) => m.id === id), 1); + relay?.close(); + relay = null; + log(`triage host: start failed: ${e.code ?? "error"}`); + throw e instanceof TriageError ? e : new TriageError("triage-start-failed", "the Triage session did not start"); + } + } + return { id, at }; + }, + async stop() { + const c = child; + if (c) { + try { process.kill(-c.pid, "SIGTERM"); } catch {} + await new Promise((resolve) => { + const t = setTimeout(() => { try { process.kill(-c.pid, "SIGKILL"); } catch {} resolve(); }, 5000); + c.once("exit", () => { clearTimeout(t); resolve(); }); + }); + } + relay?.close(); + relay = null; + }, + }; +} diff --git a/packages/webui/tests/fixtures/triage-adapter.mjs b/packages/webui/tests/fixtures/triage-adapter.mjs new file mode 100644 index 000000000..30a2c0650 --- /dev/null +++ b/packages/webui/tests/fixtures/triage-adapter.mjs @@ -0,0 +1,61 @@ +// A stand-in harness turn for the Triage host tests (#1873). It imports nothing from the repository, +// so it runs with only the binds the host gives it. The message body picks the behaviour: +// PROBE answer JSON: the environment's variable names (never values), which of the paths in +// $TRIAGE_PROBE (a JSON array) are visible, the snapshot's version, and whether the +// health directory and the bundle refuse a write +// CARDS answer a reply with a cards fence: one valid card, one unknown step +// TOOL call send_message to through the tool socket and answer the raw reply +// SLEEP hang until killed +// anything else answer "echo: " +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { connect } from "node:net"; +import { join } from "node:path"; + +const request = process.env.MOSAIC_REQUEST ?? ""; +const body = request.match(/^Message [^\n]*:\n\n([\s\S]*)$/m)?.[1] ?? ""; +const workspace = process.env.MOSAIC_WORKSPACE; + +const tryWrite = (path) => { + try { + writeFileSync(path, "x"); + return "written"; + } catch (e) { + return e.code ?? "refused"; + } +}; + +function toolCall(tool, args) { + return new Promise((resolve) => { + const socket = connect(process.env.MOSAIC_TOOL_SOCKET); + let input = ""; + socket.on("connect", () => socket.write(JSON.stringify({ tool, args }) + "\n")); + socket.on("data", (b) => { + input += b; + if (input.includes("\n")) { socket.destroy(); resolve(input.trim()); } + }); + socket.on("error", (e) => resolve(`socket ${e.code}`)); + }); +} + +if (body === "PROBE") { + let paths = []; + try { paths = JSON.parse(process.env.TRIAGE_PROBE ?? "[]"); } catch {} + let snapshot = null; + try { snapshot = JSON.parse(readFileSync(join(workspace, "health", "snapshot.json"), "utf8")).snapshotVersion; } catch {} + process.stdout.write(JSON.stringify({ + env: Object.keys(process.env).sort(), + seen: Object.fromEntries(paths.map((p) => [p, existsSync(p)])), + snapshot, + writeHealth: tryWrite(join(workspace, "health", "planted.json")), + writeBundle: tryWrite(join(process.env.MOSAIC_POLICY_FILE, "..", "planted.json")), + writeWork: tryWrite(join(workspace, "note.txt")), + })); +} else if (body === "CARDS") { + process.stdout.write('The alpha bus is stopped.\n```cards\n[{"step": "bus-start", "org": "alpha"}, {"step": "bus-wipe", "org": "alpha"}]\n```\n'); +} else if (body.startsWith("TOOL ")) { + process.stdout.write(await toolCall("send_message", { to: body.slice(5), body: "from the tool", class: "INFO" })); +} else if (body === "SLEEP") { + setInterval(() => {}, 1000); +} else { + process.stdout.write(`echo: ${body}`); +} diff --git a/packages/webui/tests/triage-host.test.mjs b/packages/webui/tests/triage-host.test.mjs new file mode 100644 index 000000000..6b61207b3 --- /dev/null +++ b/packages/webui/tests/triage-host.test.mjs @@ -0,0 +1,232 @@ +// #1873 triage-host: the Triage session's host and its relay. The relay answers only a message to +// the person; the session sees its own run directory and the health snapshots and nothing else of +// the data root; its environment is a fixed list; nothing launches without a model route or over +// the cap. The session runs the stub adapter (tests/fixtures/triage-adapter.mjs); no model is called. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { connect } from "node:net"; +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { Client } from "../../bus/src/client.mjs"; +import { sandboxProblem } from "../../seat/src/sandbox.mjs"; +import { + RELAY_REFUSED, ROUTE_ENV_ALLOW, SPAWN_ENV_ALLOW, createRelay, createTriageHost, hostPrompt, triageEnv, +} from "../src/triage-host.mjs"; + +const FIXTURE = new URL("./fixtures/triage-adapter.mjs", import.meta.url).pathname; +const skip = sandboxProblem() ?? false; +const scratch = () => mkdtempSync(join(process.env.TMPDIR, "th-")); +const CAP = "a".repeat(64); +const SNAPSHOT = { + snapshotVersion: 1, at: "2026-11-16T12:00:00.000Z", console: { state: "answering", at: "2026-11-16T12:00:00.000Z" }, + proxy: "not read", systemConfig: { valid: true, exit: 0, code: null }, + organizations: { count: 1, list: [{ id: "alpha", bus: { state: "stopped", lastStart: null }, processing: "not read", config: { valid: true, exit: 0, code: null } }] }, +}; +// What the Console's own environment might hold: none of it but the allowed names may reach the session. +const CONSOLE_ENV = { + PATH: "/should/not/pass", LANG: "C.UTF-8", TZ: "UTC", HOME: "/home/someone", MOSAIC_CONFIG: "/x/config.json", + MOSAIC_BUS_CONSOLE_SOCKET: "/x/bus.sock", MOSAIC_GITEA_CREDENTIAL_FILE: "/x/cred", GITEA_TOKEN: "t", SSH_AUTH_SOCK: "/x/agent", + ANTHROPIC_API_KEY: "from-the-console", XDG_CONFIG_HOME: "/x", MOSAIC_DATA_ROOT: "/x", +}; + +const raw = (socket, line) => new Promise((resolve, reject) => { + const c = connect(socket); + let input = ""; + c.on("connect", () => c.write(line + "\n")); + c.on("data", (b) => { input += b; }); + c.on("end", () => resolve(JSON.parse(input))); + c.on("error", reject); +}); + +test("triageEnv keeps the fixed names and the route's proxy variables, and nothing else", () => { + const env = triageEnv(CONSOLE_ENV, { ANTHROPIC_BASE_URL: "http://127.0.0.1:1", ANTHROPIC_AUTH_TOKEN: "k", MOSAIC_CONFIG: "/y", OTHER: "z" }, { node: "/opt/node/bin/node" }); + assert.deepEqual(Object.keys(env).sort(), ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "LANG", "PATH", "TZ"]); + assert.equal(env.PATH, "/opt/node/bin:/usr/bin:/bin"); + assert.deepEqual(SPAWN_ENV_ALLOW, ["PATH", "LANG", "LC_ALL", "TZ", "TERM"]); + assert.deepEqual(ROUTE_ENV_ALLOW, ["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"]); + assert.equal(triageEnv(CONSOLE_ENV).ANTHROPIC_API_KEY, undefined, "a key in the Console's environment is not the route's"); +}); + +test("the relay refuses every verb but a message to the person, and any call without the capability", async (t) => { + const dir = scratch(); + const socket = join(dir, "relay.sock"); + const sent = []; + const queue = [{ id: "owner-1", from_role: "human", class: "REQUEST", body: "hello", at: "2026-11-16T12:00:00.000Z" }]; + const read = []; + const server = await createRelay({ socket, cap: CAP, take: () => queue.splice(0), read: (id) => read.push(id), onSend: (m) => sent.push(m) }); + t.after(() => server.close()); + const client = new Client({ path: socket, cap: CAP }); + assert.deepEqual(await client.call("role.claim"), { library: false }); + assert.deepEqual(await client.call("processing.status"), { halted: false, invalid: false }); + assert.deepEqual((await client.call("state")).tasks, { open: [], total: 0, cap: 0 }); + assert.deepEqual(await client.call("message.receive"), [{ id: "owner-1", from_role: "human", class: "REQUEST", body: "hello", at: "2026-11-16T12:00:00.000Z" }]); + assert.match((await client.call("message.send", { to: "human", body: "answer", class: "RESULT", in_reply_to: "owner-1" })).id, /^triage-/); + await client.call("message.read", { id: "owner-1" }); + assert.deepEqual(sent, [{ body: "answer", in_reply_to: "owner-1" }]); + assert.deepEqual(read, ["owner-1"]); + const refused = [ + ["decision.raise", { kind: "hire", body: "x" }], ["event.emit", { kind: "action.allowed", body: {} }], + ["message.send", { to: "chief", body: "x", class: "INFO" }], ["message.send", { to: "pm", body: "x" }], + ["message.send", { to: "human" }], ["task.create", { title: "x" }], ["launch", { instance: "chief" }], + ["plugin.tool", {}], ["toString", {}], ["__proto__", {}], ["constructor", {}], + ]; + for (const [verb, args] of refused) { + await assert.rejects(client.call(verb, args), (e) => e.code === RELAY_REFUSED, verb); + } + await assert.rejects(new Client({ path: socket, cap: "b".repeat(64) }).call("message.send", { to: "human", body: "x" }), (e) => e.code === RELAY_REFUSED); + await assert.rejects(new Client({ path: socket, human: "jason" }).call("message.receive"), (e) => e.code === RELAY_REFUSED); + assert.deepEqual(await raw(socket, "not json"), { ok: false, error: RELAY_REFUSED, reason: "the Triage host answers only a message to the person" }); + assert.equal((await raw(socket, JSON.stringify({ cap: CAP.toUpperCase(), verb: "role.claim" }))).error, RELAY_REFUSED); + assert.equal(sent.length, 1, "no refused call reached the transcript"); + assert.equal(lstatSync(socket).mode & 0o777, 0o600); +}); + +test("the prompt names the snapshot inside the session and the card form, after the role's contract", () => { + const text = hostPrompt("# Triage\n\nContract.\n", { snapshotPath: "/r/work/health/snapshot.json", steps: ["bus-start"] }); + assert.match(text, /^# Triage\n\nContract\.\n\n## This host/); + assert.match(text, /\/r\/work\/health\/snapshot\.json/); + assert.match(text, /```cards\n\[\{"step": "bus-start", "org": "alpha"\}\]\n```/); +}); + +function host(t, root, opts = {}) { + const dataRoot = join(root, "data"); + const h = createTriageHost({ dataRoot, readSnapshot: async () => SNAPSHOT, env: CONSOLE_ENV, readOnly: [FIXTURE], pollInterval: 100, ...opts }); + t.after(() => h.stop()); + return { h, dataRoot }; +} + +test("no model route: nothing launches, the message is refused, and the state says the route is not set", async (t) => { + const { h, dataRoot } = host(t, scratch()); + assert.equal((await h.state()).route, "not set"); + await assert.rejects(h.message("hello"), (e) => e.code === "triage-no-route" && /no model route is set/.test(e.message)); + assert.equal(h.running, false); + assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false); + assert.deepEqual((await h.state()).transcript, []); +}); + +test("over the cap: the message is refused until the next day and nothing launches", async (t) => { + const route = { admit: async () => ({ ok: false, code: "triage-over-cap", until: "2026-11-17T00:00:00.000Z" }) }; + const { h, dataRoot } = host(t, scratch(), { route }); + assert.equal((await h.state()).route, "set"); + await assert.rejects(h.message("hello"), (e) => e.code === "triage-over-cap" && e.until === "2026-11-17T00:00:00.000Z"); + assert.equal(h.running, false); + assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false); + const odd = { admit: async () => ({ ok: false, code: "rm -rf", until: 5 }) }; + const other = host(t, scratch(), { route: odd }).h; + await assert.rejects(other.message("hello"), (e) => e.code === "triage-route-refused" && e.until === undefined); +}); + +test("a route whose answer carries a config, bus or founder variable is refused before anything starts", async (t) => { + for (const name of ["MOSAIC_CONFIG", "MOSAIC_BUS_CONSOLE_SOCKET", "GITEA_TOKEN", "SSH_AUTH_SOCK", "lower"]) { + const root = scratch(); + const adapter = join(root, "adapter.sh"); + writeFileSync(adapter, "exit 0\n"); + const route = { admit: async () => ({ ok: true, adapter, harness: "fake", harnessEnv: { [name]: "x" }, harnessMounts: [], turnEnd: "exit", model: "m", provider: "p", env: {} }) }; + const { h, dataRoot } = host(t, root, { route }); + await assert.rejects(h.message("hello"), (e) => e.code === "triage-route-invalid", name); + assert.equal(h.running, false); + assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false); + } +}); + +test("a Triage directory that is a link is refused", async (t) => { + const root = scratch(); + const dataRoot = join(root, "data"); + mkdirSync(join(root, "elsewhere"), { recursive: true }); + mkdirSync(dataRoot); + symlinkSync(join(root, "elsewhere"), join(dataRoot, "triage")); + const route = { admit: async () => ({ ok: true }) }; + const { h } = host(t, root, { route }); + await assert.rejects(h.message("hello"), (e) => e.code === "triage-dir-unsafe"); + assert.deepEqual(readdirSync(join(root, "elsewhere")), []); +}); + +async function waitFor(fn, ms = 30000) { + const end = Date.now() + ms; + while (Date.now() < end) { + const v = await fn(); + if (v) return v; + await new Promise((r) => setTimeout(r, 50)); + } + throw new Error("timed out"); +} + +test("end to end under the sandbox: the first message starts the session, which sees only its two directories and answers into the transcript", { skip, timeout: 120000 }, async (t) => { + const root = scratch(); + const dataRoot = join(root, "data"); + // What the session must not see: an org root, a config, a secrets file, the host's transcript. + mkdirSync(join(dataRoot, "orgs", "alpha"), { recursive: true }); + writeFileSync(join(dataRoot, "orgs", "alpha", "org.json"), "{}"); + mkdirSync(join(root, "config")); + writeFileSync(join(root, "config", "config.json"), "{}"); + mkdirSync(join(root, "secrets")); + writeFileSync(join(root, "secrets", "token"), "secret"); + // A link left where the host makes its work directory must not steer the bind. + mkdirSync(join(dataRoot, "triage", "agent"), { recursive: true, mode: 0o700 }); + symlinkSync(join(dataRoot, "orgs"), join(dataRoot, "triage", "agent", "work")); + const adapter = join(root, "adapter.sh"); + writeFileSync(adapter, `exec '${process.execPath}' '${FIXTURE}'\n`, { mode: 0o644 }); + const probe = [ + join(dataRoot, "orgs", "alpha", "org.json"), join(root, "config", "config.json"), join(root, "secrets", "token"), + join(dataRoot, "triage", "host", "transcript.jsonl"), join(dataRoot, "triage", "host"), + join(dataRoot, "triage", "health", "snapshot.json"), join(dataRoot, "triage", "agent", "work", "health", "snapshot.json"), + ]; + let admits = 0; + const route = { admit: async () => { admits += 1; return { ok: true, adapter, harness: "fake", harnessEnv: { TRIAGE_PROBE: JSON.stringify(probe) }, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", OTHER: "x" } }; } }; + const { h } = host(t, root, { route }); + assert.equal(h.running, false, "nothing starts before the owner's first message"); + assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false); + + const replies = async (n) => waitFor(async () => { + const list = (await h.state()).transcript.filter((e) => e.from === "triage"); + return list.length >= n ? list : null; + }); + + await h.message("PROBE"); + assert.equal(h.running, true); + const probed = JSON.parse((await replies(1))[0].text.replace(/\n\n.*$/s, "")); + const allowed = new Set([ + "PATH", "LANG", "TZ", "HOME", "TMPDIR", "ANTHROPIC_BASE_URL", "TRIAGE_PROBE", "PWD", "SHLVL", "_", "OLDPWD", + "MOSAIC_REQUEST", "MOSAIC_SYSTEM_PROMPT_FILE", "MOSAIC_WORKSPACE", "MOSAIC_SESSION_DIR", "MOSAIC_POLICY_FILE", "MOSAIC_TOOLS_FILE", + "MOSAIC_TOOL_SOCKET", "MOSAIC_TURN_MARKER", "MOSAIC_PROVIDER", "MOSAIC_MODEL", "MOSAIC_MODEL_ACTIVITY_DIR", "MOSAIC_UNSLOP_LOG", + ]); + for (const name of probed.env) assert.ok(allowed.has(name), `the session's environment holds ${name}`); + for (const name of ["MOSAIC_CONFIG", "MOSAIC_BUS_CONSOLE_SOCKET", "GITEA_TOKEN", "SSH_AUTH_SOCK", "ANTHROPIC_API_KEY", "OTHER", "MOSAIC_DATA_ROOT"]) assert.ok(!probed.env.includes(name), name); + assert.deepEqual(probed.seen, Object.fromEntries(probe.map((p) => [p, p.endsWith(join("work", "health", "snapshot.json"))]))); + assert.equal(probed.snapshot, 1); + assert.equal(probed.writeHealth, "EROFS"); + assert.equal(probed.writeBundle, "EROFS"); + assert.equal(probed.writeWork, "written"); + assert.deepEqual(readdirSync(join(dataRoot, "orgs")), ["alpha"], "the planted link's target is untouched"); + assert.equal(lstatSync(join(dataRoot, "triage", "agent", "work")).isDirectory(), true); + assert.deepEqual(readdirSync(join(dataRoot, "triage", "health")), ["snapshot.json"]); + + await h.message("CARDS"); + const cards = (await replies(2))[1]; + assert.deepEqual(cards.cards, [{ step: "bus-start", org: "alpha", command: "mosaic bus start alpha --detach" }]); + assert.equal(cards.dropped, 1); + assert.match(cards.text, /^The alpha bus is stopped\./); + + await h.message("TOOL chief"); + assert.match((await replies(3))[2].text, new RegExp(RELAY_REFUSED)); + await h.message("TOOL human"); + const last = await replies(5); + const texts = last.slice(3).map((e) => e.text); + assert.ok(texts.includes("from the tool"), "the session's own send to the person reaches the transcript"); + assert.ok(texts.some((x) => /"ok":true/.test(x)), "and the tool call was answered"); + assert.equal(admits, 4, "each message is admitted by the route"); + + const tr = join(dataRoot, "triage", "host", "transcript.jsonl"); + assert.equal(lstatSync(tr).mode & 0o777, 0o600); + for (const d of ["", "health", "agent", "host"]) assert.equal(lstatSync(join(dataRoot, "triage", d)).mode & 0o777, 0o700, d); + const owner = readFileSync(tr, "utf8").trim().split("\n").map((l) => JSON.parse(l)).filter((e) => e.from === "owner").map((e) => e.text); + assert.deepEqual(owner, ["PROBE", "CARDS", "TOOL chief", "TOOL human"]); + const tools = JSON.parse(readFileSync(join(dataRoot, "triage", "agent", "bundle", "tools.json"), "utf8")); + assert.deepEqual(tools.map((x) => x.name), ["send_message"]); + const policy = JSON.parse(readFileSync(join(dataRoot, "triage", "agent", "bundle", "policy.json"), "utf8")); + assert.deepEqual([policy.tools, policy.typed, policy.network, policy.needs, policy.credentials], [["read", "grep", "find", "ls"], ["send_message"], "none", [], []]); + + await h.stop(); + assert.equal(h.running, false); + assert.equal(existsSync(join(dataRoot, "triage", "agent", "relay.sock")), false); +});