benignswarm 0.12.57 → 0.12.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/args.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
- export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "ssh", "variant", "count", "needs", "min-ram", "exclude"];
4
- export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate"];
3
+ export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait"];
4
+ export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "print-apparmor"];
5
5
  export function parse(argv) {
6
6
  const options = {};
7
7
  for (const f of STRING_FLAGS)
@@ -7,7 +7,7 @@ import { spawnSync } from "node:child_process";
7
7
  import { CliError } from "../errors.js";
8
8
  import { table } from "../output.js";
9
9
  import { milestoneWith, milestonesWith } from "./wu.js";
10
- import { machineAdmin, poolAdmin, projectCheckoutAdmin, projectRepoAdmin } from "./machine-admin.js";
10
+ import { agentMove, machineAdmin, poolAdmin, projectCheckoutAdmin, projectRepoAdmin } from "./machine-admin.js";
11
11
  import { accountAdmin, answerAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, worktreeAdmin } from "./operator.js";
12
12
  function adminClient(p) {
13
13
  return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
@@ -61,6 +61,8 @@ export async function admin(p, out) {
61
61
  return projectCheckoutAdmin(rest, p, out);
62
62
  return project(action, rest, p, out);
63
63
  case "agent":
64
+ if (action === "move")
65
+ return agentMove(rest, p, out);
64
66
  return agent(action, rest, p, out);
65
67
  case "role":
66
68
  return role(action, rest, p, out);
@@ -77,6 +77,7 @@ export async function codexStart(p, out) {
77
77
  `[bschat] You are ${ref}, a BenignSwarm agent, started headless by \`bschat codex start\`; nobody is typing to you.`,
78
78
  `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
79
79
  `Now: run \`bschat me\`, \`bschat process\` and \`bschat inbox --unread\`, then do what your role and inbox ask.`,
80
+ `If you ran on another machine before, read your latest note first: \`bschat handoffs --agent ${creds.agent}\` (your units, branches and chat are on the server as before).`,
80
81
  ].join("\n");
81
82
  thread = await startThread(codexBin, ["exec", "--json", ...settings, prompt], firstTurnLog, ref);
82
83
  lines.push(`Started Codex thread ${thread}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
@@ -10,7 +10,7 @@ import { CLI_VERSION } from "../version.js";
10
10
  * sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
11
11
  * call here runs in the operator's terminal, and the machine key reaches the machine on ssh's stdin.
12
12
  *
13
- * machine add <name> --ssh <host> [--rotate]
13
+ * machine add <name> --ssh <host> [--rotate] [--codex-userns]
14
14
  * machine list | show <name> | remove <name>
15
15
  * machine session add <machine> <project>/<agent> --dir <path> --sandbox <mode> [--create --role r] [--model m] [--effort e] [--thread id] [--turn-timeout min]
16
16
  * machine session stop|start|remove <machine> <project>/<agent>
@@ -65,7 +65,7 @@ export async function machineAdmin(action, rest, p, out) {
65
65
  const name = rest[0];
66
66
  const host = str(p.flags, "ssh");
67
67
  if (!name || !host)
68
- throw new CliError("usage", "machine add <name> --ssh <host> (the host as your ssh knows it: an alias, user@host)");
68
+ throw new CliError("usage", "machine add <name> --ssh <host> [--rotate] [--codex-userns] (the host as your ssh knows it: an alias, user@host)");
69
69
  const lines = [];
70
70
  const say = (l) => { lines.push(l); if (!out.json)
71
71
  process.stderr.write(`${l}\n`); };
@@ -77,7 +77,7 @@ export async function machineAdmin(action, rest, p, out) {
77
77
  if (boot.status !== 0)
78
78
  throw new CliError("provision_failed", `bootstrapping ${host} failed${steps.length ? `: ${steps[steps.length - 1]}` : `: ${boot.stderr.trim().slice(-300)}`}`);
79
79
  // 2. Linger, Codex, managed hooks: checked and fixed on the machine itself.
80
- const prep = remoteBschat(host, "machine prepare --json");
80
+ const prep = remoteBschat(host, `machine prepare --json${bool(p.flags, "codex-userns") ? " --codex-userns" : ""}`);
81
81
  if (prep.status !== 0)
82
82
  throw new CliError("provision_failed", `bschat machine prepare on ${host} failed: ${prep.stderr.trim().slice(-300)}`);
83
83
  const prepared = JSON.parse(prep.stdout).steps;
@@ -124,7 +124,7 @@ export async function machineAdmin(action, rest, p, out) {
124
124
  const rep = m.report ?? {};
125
125
  const head = [
126
126
  `${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}`,
127
- rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; bschat ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
127
+ rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; bschat ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}, sandbox ${rep.codex.sandbox ? (rep.codex.sandbox.ok ? "ok" : `FAILS (${rep.codex.sandbox.error})`) : "?"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
128
128
  ];
129
129
  const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ bschat watch\[[^\]]+\]: /, "") }));
130
130
  return out.print([...head, rows.length ? table(rows, ["agent", "pool", "desired", "state", "thread", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
@@ -265,3 +265,123 @@ export async function projectRepoAdmin(rest, p, out) {
265
265
  const r = await adminClient(p).call("PUT", `/projects/${project}/repo`, { url: url === "none" ? null : url });
266
266
  out.print(`${project}: repository ${r.repo_url ?? "(none)"}`, r);
267
267
  }
268
+ /**
269
+ * Prints `<yyyy/mm/dd>/<file>` and then the content of a Codex thread's session file, whether it is
270
+ * in ~/.codex/sessions or archived in ~/.codex/archived_sessions (flat); exits 4 when there is none.
271
+ */
272
+ export function threadFileCommand(thread) {
273
+ return `f=$(ls ~/.codex/sessions/*/*/*/rollout-*${thread}.jsonl 2>/dev/null | head -1); [ -n "$f" ] || f=$(ls ~/.codex/archived_sessions/rollout-*${thread}.jsonl 2>/dev/null | head -1); [ -n "$f" ] || exit 4; b=$(basename "$f"); d=$(echo "$b" | sed -E 's#^rollout-([0-9]{4})-([0-9]{2})-([0-9]{2}).*#\\1/\\2/\\3#'); echo "$d/$b"; cat "$f"`;
274
+ }
275
+ /** Runs a shell command on `host` ("local" runs it here). */
276
+ function on(host, command, input) {
277
+ if (host === "local") {
278
+ const r = spawnSync("/bin/sh", ["-c", command], { input, encoding: "utf8", maxBuffer: 256 * 1024 * 1024 });
279
+ return { status: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
280
+ }
281
+ return ssh(host, command, input);
282
+ }
283
+ /**
284
+ * agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir path|auto] [--model m] [--effort e]
285
+ * [--carry note|thread] [--from local|<ssh host>] [--to-ssh <host>] [--thread id] [--wait min] [--force]
286
+ *
287
+ * The agent (name, role, record, units, chat) is on the server and does not move; its harness
288
+ * session does. Its units in progress must be pushed (checked on --from); its context travels as a
289
+ * resume note it writes now (--carry note, the default) or as its Codex thread itself, copied over
290
+ * the operator's ssh (--carry thread; same thread id, full history). The new machine's daemon then
291
+ * runs it, and every key not minted for that machine is revoked, so the old copy stops.
292
+ */
293
+ export async function agentMove(rest, p, out) {
294
+ const ref = rest[0] ?? "";
295
+ const [project, agent] = ref.split("/");
296
+ const to = str(p.flags, "to");
297
+ const sandbox = str(p.flags, "sandbox");
298
+ const carry = str(p.flags, "carry") ?? "note";
299
+ const from = str(p.flags, "from");
300
+ if (!project || !agent || !to || !sandbox)
301
+ throw new CliError("usage", "agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force]");
302
+ if (carry !== "note" && carry !== "thread")
303
+ throw new CliError("usage", "--carry note (a resume note it writes now) or thread (its Codex thread, copied)");
304
+ if (carry === "thread" && !from)
305
+ throw new CliError("usage", "--carry thread needs --from local|<ssh host>: the machine whose ~/.codex holds its thread");
306
+ const c = adminClient(p);
307
+ const say = (l) => { if (!out.json)
308
+ process.stderr.write(`${l}\n`); };
309
+ // 1. Work in progress must be on origin, or it stays behind on the old machine.
310
+ const units = (await c.call("GET", `/projects/${project}/work-units?agent=${encodeURIComponent(agent)}`)).units.filter((u) => ["assigned", "open", "changes_requested", "in_review", "approved"].includes(u.status));
311
+ const problems = [];
312
+ for (const u of units) {
313
+ if (!from || !u.worktree) {
314
+ say(` #${u.number} [${u.status}] ${u.branch ?? ""}${u.worktree ? ` in ${u.worktree}` : ""}: not checked (no --from)`);
315
+ continue;
316
+ }
317
+ const r = on(from, `cd ${JSON.stringify(u.worktree)} 2>/dev/null || exit 3; echo "dirty=$(git status --porcelain | wc -l) unpushed=$(git rev-list --count HEAD --not --remotes)"`);
318
+ if (r.status === 3) {
319
+ say(` #${u.number}: ${u.worktree} is not on ${from}`);
320
+ continue;
321
+ }
322
+ const m = /dirty=\s*(\d+) unpushed=\s*(\d+)/.exec(r.stdout);
323
+ if (!m) {
324
+ problems.push(`#${u.number}: cannot read ${u.worktree} on ${from}: ${r.stderr.trim().slice(0, 200)}`);
325
+ continue;
326
+ }
327
+ if (Number(m[1]) || Number(m[2]))
328
+ problems.push(`#${u.number} (${u.branch}): ${m[2]} unpushed commit(s), ${m[1]} uncommitted file(s) in ${u.worktree}`);
329
+ else
330
+ say(` #${u.number} [${u.status}] ${u.branch}: pushed and clean`);
331
+ }
332
+ if (problems.length && !bool(p.flags, "force"))
333
+ throw new CliError("unpushed_work", `${ref} has work only on ${from}:\n ${problems.join("\n ")}`, "Have the agent push it (or commit and push), then move it; --force moves anyway and leaves that work there");
334
+ // 2. Its context.
335
+ let thread = str(p.flags, "thread") ?? null;
336
+ if (carry === "thread") {
337
+ if (!thread) {
338
+ const map = on(from, "cat ~/.bschat/codex.json 2>/dev/null");
339
+ const ids = Object.entries(JSON.parse(map.stdout || "{}").conversations ?? {}).filter(([, a]) => a === ref).map(([id]) => id);
340
+ if (!ids.length)
341
+ throw new CliError("no_thread", `no Codex thread is bound to ${ref} on ${from} (~/.bschat/codex.json)`, "Pass --thread <id>");
342
+ const newest = on(from, `ls -t ${ids.map((id) => `~/.codex/sessions/*/*/*/rollout-*${id}.jsonl ~/.codex/archived_sessions/rollout-*${id}.jsonl`).join(" ")} 2>/dev/null | head -1`).stdout.trim();
343
+ thread = ids.find((id) => newest.includes(id)) ?? null;
344
+ if (!thread)
345
+ throw new CliError("no_thread", `the threads bound to ${ref} on ${from} have no session file`, "Pass --thread <id>, or use --carry note");
346
+ }
347
+ // The Codex app moves an archived thread's file to ~/.codex/archived_sessions (flat); it is copied
348
+ // into the dated sessions folder on the new machine either way, where codex exec resume finds it.
349
+ const src = on(from, threadFileCommand(thread));
350
+ if (src.status !== 0)
351
+ throw new CliError("no_thread", `${from} has no session file for thread ${thread}`);
352
+ const nl = src.stdout.indexOf("\n");
353
+ const rel = src.stdout.slice(0, nl);
354
+ const toHost = str(p.flags, "to-ssh") ?? to;
355
+ const put = ssh(toHost, `mkdir -p ~/.codex/sessions/${JSON.stringify(rel.slice(0, rel.lastIndexOf("/")))} && cat > ~/.codex/sessions/${JSON.stringify(rel)}`, src.stdout.slice(nl + 1));
356
+ if (put.status !== 0)
357
+ throw new CliError("copy_failed", `copying thread ${thread} to ${toHost}: ${put.stderr.trim()}`);
358
+ say(` thread ${thread} copied to ${toHost} (${Math.round((src.stdout.length - nl) / 1024)} KB); the copy on ${from} is now a dead end: archive it in the Codex app there so nobody types into it`);
359
+ }
360
+ else {
361
+ const wait = Number(str(p.flags, "wait") ?? "10");
362
+ if (wait > 0) {
363
+ const asked = new Date().toISOString();
364
+ await c.call("POST", `/projects/${project}/channels/general/messages`, { body: `@${agent} you are being moved to the machine ${to}. Before anything else, save a resume note: bschat checkpoint "<one line>" --body "<what you are doing, your open units and branches (pushed?), waits and next steps>". Your next session there reads it first. Then end your turn.` });
365
+ say(` asked ${agent} for a resume note; waiting up to ${wait} min`);
366
+ let note = null;
367
+ for (let i = 0; i < wait * 6 && !note; i++) {
368
+ await new Promise((r) => setTimeout(r, 10_000));
369
+ note = (await c.call("GET", `/projects/${project}/handoffs?agent=${encodeURIComponent(agent)}&limit=1`)).handoffs.find((h) => h.created_at > asked) ?? null;
370
+ }
371
+ say(note ? ` resume note saved: ${note.title}` : ` no resume note within ${wait} min; it starts from its units, status and chat`);
372
+ }
373
+ }
374
+ // 3. The new machine runs it; every other key stops working.
375
+ const turnTimeout = str(p.flags, "turn-timeout");
376
+ const r = await c.call("POST", `/machines/${to}/sessions`, {
377
+ project, agent, move: true, harness: str(p.flags, "harness") ?? "codex", dir: str(p.flags, "dir") ?? "auto", sandbox,
378
+ model: str(p.flags, "model"), effort: str(p.flags, "effort"), ...(thread ? { thread } : {}), ...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
379
+ });
380
+ return out.print([
381
+ `${ref} now runs on ${to} (${r.session.sandbox}, ${r.session.dir || "automatic checkout"}${thread ? `, thread ${thread}` : ", a fresh thread"}); its daemon starts it within 30 s.`,
382
+ r.moved_from.length ? `Its session on ${r.moved_from.join(", ")} was removed.` : null,
383
+ `${r.revoked_keys} key(s) elsewhere revoked: a watcher left running there stops and removes itself. Archive its old thread in the Codex app so nobody types into that copy.`,
384
+ problems.length ? `Left behind (--force): ${problems.join("; ")}` : null,
385
+ `Follow it: bschat-admin machine show ${to}`,
386
+ ].filter(Boolean).join("\n"), r);
387
+ }
@@ -6,7 +6,7 @@ import { str } from "../args.js";
6
6
  import { Client } from "../client.js";
7
7
  import { configRoot, loadAgent, saveAgent } from "../config.js";
8
8
  import { CliError } from "../errors.js";
9
- import { CODEX_MANAGED_DIR, CODEX_MANAGED_MARK, codexManagedHooks } from "../harness.js";
9
+ import { CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, CODEX_MANAGED_MARK, codexAppArmorProfile, codexManagedHooks } from "../harness.js";
10
10
  import { applySparse } from "../git.js";
11
11
  import { installService, lingerEnabled, MACHINE_LABEL, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
12
12
  import { CLI_VERSION } from "../version.js";
@@ -241,6 +241,16 @@ function freeBytes(path) {
241
241
  return null;
242
242
  }
243
243
  }
244
+ /** Whether Codex's own sandbox runs here (`codex sandbox -- true`), with its error; checked at most every 10 min. */
245
+ let sandboxCache = null;
246
+ export function codexSandbox(force = false) {
247
+ if (!force && sandboxCache && Date.now() - sandboxCache.at < 10 * 60_000)
248
+ return sandboxCache.result;
249
+ const r = spawnSync("codex", ["sandbox", "--", "true"], { encoding: "utf8", timeout: 60_000 });
250
+ const result = r.status === 0 ? { ok: true, error: null } : { ok: false, error: `${r.stderr ?? ""}${r.stdout ?? ""}`.trim().split("\n")[0].slice(0, 300) || `exit ${r.status}` };
251
+ sandboxCache = { at: Date.now(), result };
252
+ return result;
253
+ }
244
254
  /** What the operator needs to know about this machine, reported with every pass. */
245
255
  export function machineFacts() {
246
256
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8" });
@@ -257,7 +267,7 @@ export function machineFacts() {
257
267
  return {
258
268
  os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
259
269
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
260
- codex: codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200) } : null,
270
+ codex: codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), sandbox: codexSandbox() } : null,
261
271
  managed_hooks: existsSync(req) && readFileSync(req, "utf8").includes(CODEX_MANAGED_MARK),
262
272
  linger: platform() === "linux" ? lingerEnabled() : null,
263
273
  disk_free_bytes: diskFree,
@@ -269,7 +279,7 @@ export function machineFacts() {
269
279
  * Linux, Codex present and logged in, and bschat's hooks in Codex's administrator layer when sudo
270
280
  * works without a password. Each step reports ok, done, skipped or failed; nothing is hidden.
271
281
  */
272
- export function prepare() {
282
+ export function prepare(opts = {}) {
273
283
  const steps = [];
274
284
  const sudo = spawnSync("sudo", ["-n", "true"], { stdio: "ignore" }).status === 0;
275
285
  if (platform() === "linux") {
@@ -290,6 +300,25 @@ export function prepare() {
290
300
  const ok = login.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`);
291
301
  steps.push({ step: "codex", result: ok ? "ok" : "failed", detail: ok ? `${codex.stdout.trim()}, ${`${login.stdout}${login.stderr}`.trim()}` : `${codex.stdout.trim()} is not logged in: run codex login --device-auth on this machine` });
292
302
  }
303
+ if (codex.status === 0) {
304
+ let sb = codexSandbox(true);
305
+ if (sb.ok)
306
+ steps.push({ step: "codex sandbox", result: "ok", detail: "sandboxed (read-only, workspace-write) agents can run here" });
307
+ else if (platform() !== "linux" || !/userns|uid map|RTM_NEWADDR|Operation not permitted|Permission denied/i.test(sb.error ?? ""))
308
+ steps.push({ step: "codex sandbox", result: "failed", detail: `${sb.error}; only danger-full-access agents can run here` });
309
+ else if (!opts.codexUserns)
310
+ steps.push({ step: "codex sandbox", result: "failed", detail: `${sb.error}: this system restricts the user namespaces Codex's sandbox needs. Re-run machine add with --codex-userns to install a Codex-only AppArmor profile (${CODEX_APPARMOR_PATH}), or use danger-full-access pools here` });
311
+ else if (!sudo)
312
+ steps.push({ step: "codex sandbox", result: "failed", detail: `--codex-userns needs passwordless sudo; install ${CODEX_APPARMOR_PATH} by hand (bschat machine prepare --print-apparmor shows it) and run sudo apparmor_parser -r on it` });
313
+ else {
314
+ const t = spawnSync("sudo", ["-n", "tee", CODEX_APPARMOR_PATH], { input: codexAppArmorProfile(), stdio: ["pipe", "ignore", "pipe"], encoding: "utf8" });
315
+ const l = t.status === 0 ? spawnSync("sudo", ["-n", "apparmor_parser", "-r", CODEX_APPARMOR_PATH], { encoding: "utf8" }) : t;
316
+ sb = codexSandbox(true);
317
+ steps.push(l.status === 0 && sb.ok
318
+ ? { step: "codex sandbox", result: "done", detail: `installed ${CODEX_APPARMOR_PATH} (Codex only); the sandbox works` }
319
+ : { step: "codex sandbox", result: "failed", detail: l.status !== 0 ? `installing ${CODEX_APPARMOR_PATH}: ${(l.stderr ?? "").trim()}` : `profile installed but the sandbox still fails: ${sb.error}` });
320
+ }
321
+ }
293
322
  const req = "/etc/codex/requirements.toml";
294
323
  const { requirements, wrapper } = codexManagedHooks(requireInstall().bin);
295
324
  const current = existsSync(req) ? readFileSync(req, "utf8") : null;
@@ -330,7 +359,9 @@ export async function machine(p, out) {
330
359
  if (sub === "prepare") {
331
360
  if (p.flags["print-hooks"])
332
361
  return out.print(codexManagedHooks(requireInstall().bin).requirements, codexManagedHooks(requireInstall().bin));
333
- const steps = prepare();
362
+ if (p.flags["print-apparmor"])
363
+ return out.print(codexAppArmorProfile(), { path: CODEX_APPARMOR_PATH, profile: codexAppArmorProfile() });
364
+ const steps = prepare({ codexUserns: p.flags["codex-userns"] === true });
334
365
  return out.print(steps.map((s) => `${s.result.padEnd(8)} ${s.step}: ${s.detail}`).join("\n"), { steps });
335
366
  }
336
367
  if (sub === "service") {
@@ -78,3 +78,26 @@ export async function handoffs(p, out) {
78
78
  }
79
79
  throw new CliError("usage", "handoffs [list] [--open] [--agent a] | show <id> | pickup <id>");
80
80
  }
81
+ /**
82
+ * A resume note without retiring: what you are doing, open threads, next steps. Your next session
83
+ * reads it first (after a move to another machine, or a fresh thread). Not announced.
84
+ */
85
+ export async function checkpoint(p, out) {
86
+ const { client: c, creds } = client(p);
87
+ const title = str(p.flags, "title") ?? p.positionals.slice(1).join(" ").trim();
88
+ let body = str(p.flags, "body");
89
+ const file = str(p.flags, "body-file");
90
+ if (file) {
91
+ try {
92
+ body = readFileSync(file, "utf8");
93
+ }
94
+ catch (e) {
95
+ throw new CliError("read_failed", `cannot read ${file}: ${e.message}`);
96
+ }
97
+ }
98
+ if (!title || !body || !body.trim())
99
+ throw new CliError("usage", 'checkpoint "<title>" (--body "..." | --body-file notes.md) [--evidence id,id] what you are doing, open threads (units, branches, waits) and next steps');
100
+ const evidence = (str(p.flags, "evidence") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
101
+ const r = await c.call("POST", "/agents/me/checkpoint", { title, body, evidence });
102
+ out.print(`Saved resume note handoff:${r.handoff.id} for ${creds.agent}. Your next session reads it with: bschat handoffs --agent ${creds.agent}`, r);
103
+ }
@@ -2,7 +2,7 @@ import { spawn, spawnSync } from "node:child_process";
2
2
  import { bindSession, codexArchivedRollout, codexRollout, sessionOfExec, threadOfExec } from "../sessions.js";
3
3
  import { readTurnPhase, startTurn, stopTurn, usageLimitUntil } from "../turn.js";
4
4
  import { applyAck } from "./wake.js";
5
- import { lingerEnabled, loadSystemdUnit, reloadLaunchAgent, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX } from "../install.js";
5
+ import { lingerEnabled, loadSystemdUnit, reloadLaunchAgent, removeService, requireInstall, systemdUnit, systemdUserDir, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
6
6
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
7
  import { createHash } from "node:crypto";
8
8
  import { homedir, userInfo } from "node:os";
@@ -137,10 +137,17 @@ export async function watch(p, out) {
137
137
  }
138
138
  }
139
139
  if (!full) {
140
- if (turnMode)
141
- await turnStep(ctl, thread, turnTimeout, log, (sink) => wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, sink), name);
142
- else
143
- await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once);
140
+ try {
141
+ if (turnMode)
142
+ await turnStep(ctl, thread, turnTimeout, log, (sink) => wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, sink), name);
143
+ else
144
+ await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once);
145
+ }
146
+ catch (e) {
147
+ if (e.code === "unauthorized" && !once)
148
+ stopRevokedWatcher(name, log);
149
+ throw e;
150
+ }
144
151
  if (once)
145
152
  return;
146
153
  await new Promise((r) => setTimeout(r, interval * 1000));
@@ -307,6 +314,20 @@ async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq,
307
314
  }
308
315
  return true;
309
316
  }
317
+ /**
318
+ * The agent's key no longer works here: it was moved to another machine (bschat-admin agent move
319
+ * revokes every key not minted for the new one) or retired. Keys are only ever revoked on purpose,
320
+ * so this watcher stops for good and removes its own service; otherwise launchd or systemd would
321
+ * restart it into the same 401 forever. A daemon that still runs the agent here reinstalls it.
322
+ */
323
+ function stopRevokedWatcher(name, log) {
324
+ const label = `${WATCH_LABEL_PREFIX}${name.replace("/", ".")}`;
325
+ log(`this agent's key was revoked (moved to another machine, or retired): stopping and removing ${label}`);
326
+ const svc = watcherServices().find((s) => s.label === label);
327
+ if (svc)
328
+ removeService(svc); // ends this process when it unloads the service
329
+ process.exit(0);
330
+ }
310
331
  const TURN_RETRY_MS = 5 * 60_000;
311
332
  /**
312
333
  * One poll in turn mode. While a turn runs nothing else starts: the turn's own hooks (Stop with new
package/dist/harness.js CHANGED
@@ -301,3 +301,26 @@ export function codexManagedHooks(bin) {
301
301
  ].join("\n");
302
302
  return { requirements, wrapper };
303
303
  }
304
+ export const CODEX_APPARMOR_PATH = "/etc/apparmor.d/bschat-codex";
305
+ /**
306
+ * An AppArmor profile that lets only Codex's own binary create user namespaces, which its Linux
307
+ * sandbox (bubblewrap, built into the binary) needs. Ubuntu 24.04+ restricts unprivileged user
308
+ * namespaces (kernel.apparmor_restrict_unprivileged_userns = 1), so without it every sandboxed
309
+ * command fails with "bwrap: setting up uid map: Permission denied". Unconfined apart from that,
310
+ * as Ubuntu's own profiles for browsers are; installed only when the operator opts in.
311
+ */
312
+ export function codexAppArmorProfile() {
313
+ return [
314
+ `# bschat: let Codex create the user namespaces its Linux sandbox needs (Ubuntu 24.04+ restricts them).`,
315
+ `# Codex only. Written by bschat machine prepare --codex-userns; remove this file and run`,
316
+ `# apparmor_parser -R on it to undo.`,
317
+ `abi <abi/4.0>,`,
318
+ `include <tunables/global>`,
319
+ ``,
320
+ `profile bschat-codex /home/*/.codex/packages/standalone/releases/*/bin/codex flags=(unconfined) {`,
321
+ ` userns,`,
322
+ ` include if exists <local/bschat-codex>`,
323
+ `}`,
324
+ ``,
325
+ ].join("\n");
326
+ }
package/dist/help.js CHANGED
@@ -112,6 +112,8 @@ Agent commands
112
112
  run a Codex agent headless: enroll, start or adopt its thread, turn-mode watcher
113
113
  bschat codex unpause [--as <a>] lift a usage-limit pause now (Codex was switched to an account with quota)
114
114
  bschat machine run | once | status | prepare | service the machine daemon (set up by bschat-admin machine add)
115
+ bschat checkpoint "<title>" --body "..." a resume note without retiring: what you are doing, open threads, next steps;
116
+ your next session (after a move to another machine) reads it first
115
117
  bschat antigravity bind <conversation-id> | sync which Antigravity conversation is you, for its hook (watchers bind theirs)
116
118
  bschat wake ack [<n>] acknowledge your watcher's wake-up #n first thing (no n: the one pending here)
117
119
  Liveness: the watcher reports harness activity (Codex rollout / Antigravity conversation
@@ -198,12 +200,18 @@ bschat-admin login (approve it in your signed-in browser); the session lasts 30
198
200
  bschat-admin worktree forget <project> <id> delete a stale worktree record (never the directory)
199
201
 
200
202
  Machines (provisioned over your own ssh; a daemon on each runs the agent sessions you declare)
201
- bschat-admin machine add <name> --ssh <host> [--rotate] install Node and bschat (no sudo), linger, Codex check,
202
- bschat's Codex hooks in /etc/codex (passwordless sudo only), register, start the daemon
203
+ bschat-admin machine add <name> --ssh <host> [--rotate] [--codex-userns] install Node and bschat (no sudo), linger, Codex check,
204
+ bschat's Codex hooks in /etc/codex (passwordless sudo only), register, start the daemon;
205
+ --codex-userns: where Linux restricts user namespaces (Ubuntu 24.04+), install a
206
+ Codex-only AppArmor profile so sandboxed agents can run
203
207
  bschat-admin machine list | show <name> | remove <name>
204
208
  bschat-admin machine session add <machine> <project>/<agent> --dir <checkout> --sandbox <read-only|workspace-write|danger-full-access>
205
209
  [--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min]
206
210
  bschat-admin machine session stop|start|remove <machine> <project>/<agent>
211
+ bschat-admin agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--carry note|thread]
212
+ [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force]
213
+ run an existing agent on a provisioned machine: refuses unpushed unit work (checked on
214
+ --from), carries its context as a resume note or its Codex thread, revokes other keys
207
215
  bschat-admin machine label <name> <label...> [--remove a,b] what cannot be measured (lab-lan, builds); pools' --needs match it
208
216
  bschat-admin machine slots <name> <n | auto> how many sessions it takes (auto: one per 4 GB of RAM)
209
217
  bschat-admin machine workdir <name> <path | default> where its daemon clones projects for pool sessions (default ~/bschat)
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import * as a from "./commands/agent.js";
4
4
  import { evidence } from "./commands/evidence.js";
5
5
  import { join, setup } from "./commands/join.js";
6
6
  import { hook } from "./commands/hook.js";
7
- import { handoffs, retire } from "./commands/retire.js";
7
+ import { checkpoint, handoffs, retire } from "./commands/retire.js";
8
8
  import { item, list, lists } from "./commands/lists.js";
9
9
  import { watch } from "./commands/watch.js";
10
10
  import { feedback } from "./commands/feedback.js";
@@ -55,6 +55,7 @@ const COMMANDS = {
55
55
  antigravity,
56
56
  codex,
57
57
  machine,
58
+ checkpoint,
58
59
  install,
59
60
  // `update` is the word people reach for: the same as install, latest unless a version is named.
60
61
  update: (p, out) => install(p.positionals[1] ? p : { ...p, flags: { ...p.flags, latest: true } }, out),
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.57";
1
+ export const CLI_VERSION = "0.12.59";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.57",
3
+ "version": "0.12.59",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {