benignswarm 0.12.111 → 0.12.113

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.
@@ -176,6 +176,8 @@ export async function machineAdmin(action, rest, p, out) {
176
176
  throw new CliError("provision_failed", `installing the machine daemon on ${host} failed: ${svc.stderr.trim().slice(-300)}`);
177
177
  const daemon = JSON.parse(svc.stdout);
178
178
  say(` daemon: ${daemon.path} with PATH ${daemon.daemon_path}`);
179
+ if (daemon.launchd)
180
+ say(` ${daemon.launchd.guidance}`);
179
181
  const failed = prepared.filter((s) => s.result === "failed");
180
182
  return out.print([
181
183
  `Machine ${name} (${host}) is provisioned and its daemon is running.`,
@@ -189,6 +191,36 @@ export async function machineAdmin(action, rest, p, out) {
189
191
  const rows = r.machines.map((m) => ({ name: m.name, os: m.report?.os ?? "-", b9s: m.report?.bschat?.version ?? "-", codex: m.report?.codex ? (m.report.codex.logged_in ? "logged in" : "NOT logged in") : "-", sessions: m.sessions.length, last_report: m.last_report_at ?? "never" }));
190
192
  return out.print(rows.length ? table(rows, ["name", "os", "b9s", "codex", "sessions", "last_report"]) : "No machines. Add one: b9s-admin machine add <name> --ssh <host>", r);
191
193
  }
194
+ if (action === "headroom") {
195
+ const requested = rest[0];
196
+ const r = await c.call("GET", "/machines/headroom");
197
+ const machines = r.machines.filter((machine) => requested === undefined || machine.name === requested);
198
+ if (requested && !machines.length)
199
+ throw new CliError("not_found", `machine ${requested} not found`);
200
+ const metric = (value, unit) => {
201
+ if (!value || value.status !== "available")
202
+ return value?.status ?? "unknown";
203
+ if (unit === "ratio")
204
+ return `${Math.round(value.headroom * 100)}% headroom`;
205
+ return value.free_bytes == null ? "unknown" : `${Math.round(value.free_bytes / 1e9)} GB free`;
206
+ };
207
+ const lines = machines.flatMap((machine) => {
208
+ const h = machine.headroom, resources = h.resources ?? {};
209
+ const memory = resources.memory?.status === "available"
210
+ ? `${Math.round(resources.memory.available_bytes / 1e9)}/${Math.round(resources.memory.total_bytes / 1e9)} GB available (${metric(resources.memory, "ratio")})`
211
+ : resources.memory?.status ?? "unknown";
212
+ const storage = (value) => value?.status === "available"
213
+ ? `${Math.round(value.free_bytes / 1e9)} GB free of ${Math.round(value.total_bytes / 1e9)} GB`
214
+ : value?.status ?? "unknown";
215
+ const pools = machine.reservations.pools.map((pool) => `${pool.project}/${pool.pool}: ${pool.sessions}`).join(", ") || "none";
216
+ return [
217
+ `${machine.name}: resource headroom ${h.status}; latest sample ${machine.latest_sample_at ?? "never"}; limiting signal ${machine.limiting_signal ?? "unknown"}`,
218
+ ` CPU ${metric(resources.cpu, "ratio")}; RAM ${memory}; home storage ${storage(resources.home_storage)}; work storage ${storage(resources.work_storage)}; I/O pressure ${h.io_pressure?.status ?? "unknown"}`,
219
+ ` sessions ${machine.capacity.sessions_in_use}/${machine.capacity.effective_slots} (configured ${machine.capacity.configured_slots ?? "auto"}); ${machine.capacity.available_session_slots} available; manual ${machine.reservations.manual_sessions}, pool ${machine.reservations.pool_sessions} [${pools}]`,
220
+ ];
221
+ });
222
+ return out.print(lines.join("\n") || "No machines.", { machines });
223
+ }
192
224
  if (action === "show") {
193
225
  if (!rest[0])
194
226
  throw new CliError("usage", "machine show <name>");
@@ -210,6 +242,7 @@ export async function machineAdmin(action, rest, p, out) {
210
242
  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"}; b9s ${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?)",
211
243
  rep.os ? ` Antigravity: ${rep.antigravity ? `${rep.antigravity.version ?? "agy"}, ${rep.antigravity.available ? "available" : "unavailable"}, ${rep.antigravity.logged_in ? "logged in" : "not logged in"}, sandbox ${rep.antigravity.sandbox ? (rep.antigravity.sandbox.ok ? "ok" : `FAILS (${rep.antigravity.sandbox.error})`) : "not checked"}` : "not installed"}` : null,
212
244
  rep.container_runtime ? ` Container runtime: ${rep.container_runtime.runtime ?? "none"} (${rep.container_runtime.rootless ? "rootless" : "daemon"}, ${rep.container_runtime.usable_without_root === false ? "NO non-root access" : "non-root ok"}, arch ${(rep.container_runtime.architectures ?? []).join(",") || rep.arch || "?"}${rep.on_ec2 ? `, EC2 container IMDS ${rep.container_imds_blocked ? "blocked" : "NOT blocked"}` : ""})` : null,
245
+ rep.launchd ? ` launchd: ${rep.launchd.session === "headless" ? "headless Mac (no desktop session)" : "desktop session"}; daemon ${rep.launchd.daemon_domain ?? "not installed"}; watchers ${Object.entries(rep.launchd.watchers ?? {}).map(([d, n]) => `${n} in ${d}`).join(", ") || "none"}` : null,
213
246
  m.quarantined ? ` QUARANTINED: ${m.quarantine?.reason ?? "operator containment"}${m.quarantine?.at ? ` (${m.quarantine.at})` : ""}` : null,
214
247
  ];
215
248
  const cacheLines = [];
@@ -415,7 +448,7 @@ export async function machineAdmin(action, rest, p, out) {
415
448
  throw new CliError("confirmation_required", `non-interactive removal requires a reviewed revision: run machine remove ${name} --preview, then pass --confirm ${name} --impact-revision <revision>`);
416
449
  await confirmMachineName(name, p);
417
450
  await c.call("DELETE", `/machines/${name}`, { source_revision: impact.source_revision, confirmation: name });
418
- return out.print(`Removed machine ${name}; its machine key and machine-scoped agent keys are revoked. Agent identities remain. Stop its daemon on the machine with: systemctl --user disable --now org.benignswarm.machine (Linux) or launchctl bootout gui/$(id -u)/org.benignswarm.machine (macOS)`, { removed: name, impact });
451
+ return out.print(`Removed machine ${name}; its machine key and machine-scoped agent keys are revoked. Agent identities remain. Stop its daemon on the machine with: systemctl --user disable --now org.benignswarm.machine (Linux) or launchctl bootout gui/$(id -u)/org.benignswarm.machine (macOS with a desktop session; user/$(id -u)/org.benignswarm.machine on a headless Mac)`, { removed: name, impact });
419
452
  }
420
453
  if (action === "session") {
421
454
  const [sub, machineName, ref] = rest;
@@ -592,7 +625,7 @@ async function runMachineCompanion(code, p, out) {
592
625
  if (svc.status !== 0)
593
626
  throw new CliError("provision_failed", `installing the machine daemon on ${operation.ssh_host} failed: ${svc.stderr.trim().slice(-300)}`);
594
627
  const daemon = JSON.parse(svc.stdout);
595
- await report("daemon", "completed", `Daemon installed at ${daemon.path}`);
628
+ await report("daemon", "completed", `Daemon installed at ${daemon.path}${daemon.launchd ? `; ${daemon.launchd.guidance}` : ""}`);
596
629
  const outcome = operation.kind === "provision" ? "is provisioned" : "has its machine key rotated";
597
630
  const completed = await companion.call("POST", `/machine-operations/${operation.id}/finish`, { status: "succeeded", result: `Machine ${operation.machine} ${outcome} and its daemon is running` });
598
631
  const result = { operation: completed.operation, machine: operation.machine, ssh_host: operation.ssh_host, daemon_path: daemon.daemon_path, prepare: prepared };
@@ -637,8 +670,10 @@ export function repeated(argv, flag) {
637
670
  return out;
638
671
  }
639
672
  /**
640
- * pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60]
641
- * pool list [project] | show <project>/<name> | remove <project>/<name>
673
+ * pool set <project>/<name> --role r --variant spec [--variant ...] (--count n | --min n --max n) --sandbox mode [...]
674
+ * pool list [project] | show <project>/<name> | events <project>/<name> | pause|resume <project>/<name>
675
+ * pool pin <project>/<name> <slot> --machine <name> | unpin|suspend|restore <project>/<name> <slot>
676
+ * pool remove <project>/<name>
642
677
  */
643
678
  export async function poolAdmin(action, rest, p, out, argv) {
644
679
  if (action === "suggestions" || action === "suggestion") {
@@ -648,6 +683,30 @@ export async function poolAdmin(action, rest, p, out, argv) {
648
683
  throw new CliError("usage", "--turn-coalesce-seconds is only supported for individual machine sessions; pool settings do not support turn coalescing");
649
684
  }
650
685
  const c = adminClient(p);
686
+ const path = (project, name) => `/projects/${project}/pools/${name}`;
687
+ const previewOrConfirm = async (project, name, operation, payload, commit) => {
688
+ const base = path(project, name);
689
+ const suppliedRevision = str(p.flags, "impact-revision");
690
+ if (bool(p.flags, "preview") && suppliedRevision !== undefined)
691
+ throw new CliError("usage", "use either --preview or --impact-revision, not both");
692
+ const response = await c.call("POST", `${base}/preview`, { action: operation, ...payload });
693
+ const preview = response.preview;
694
+ const revision = preview?.revision ?? preview?.impact_revision;
695
+ if (!preview || typeof revision !== "string" || !revision)
696
+ throw new CliError("invalid_response", "pool preview did not include an impact revision");
697
+ const previewText = [
698
+ `${project}/${name}: ${operation} preview (${revision})`,
699
+ ` slots added: ${(preview.slots_added ?? []).length}; removed: ${(preview.slots_removed ?? []).length}; revived: ${(preview.revived ?? []).length}; retired: ${(preview.retired ?? []).length}`,
700
+ ` moves: ${(preview.moves ?? []).length}; unplaced: ${(preview.unplaced ?? []).length}; affected work/session: ${(preview.affected_work ?? []).length}/${(preview.affected_sessions ?? []).length}`,
701
+ ...((preview.refusals ?? []).length ? [` safety refusals: ${preview.refusals.map((item) => item.reason).join("; ")}`] : []),
702
+ `Review this impact, then repeat the command with --impact-revision ${revision}.`,
703
+ ].join("\n");
704
+ if (bool(p.flags, "preview") || suppliedRevision === undefined)
705
+ return out.print(previewText, { preview });
706
+ if (suppliedRevision !== revision)
707
+ throw new CliError("stale_preview", `pool impact changed since revision ${suppliedRevision}; the current preview is ${revision}. Nothing was changed; review it with --preview and confirm the new revision.`);
708
+ return commit(revision);
709
+ };
651
710
  if (action === "move") {
652
711
  const [project, name] = (rest[0] ?? "").split("/");
653
712
  const from = str(p.flags, "from");
@@ -694,8 +753,11 @@ export async function poolAdmin(action, rest, p, out, argv) {
694
753
  }
695
754
  const KEPT_IN_PLACE = KEPT_IN_PLACE_RE;
696
755
  const statusLines = (pool) => [
697
- `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; busy cap ${pool.turns_per_hour ?? 60}/hour, unproductive fault ${pool.unproductive_per_hour ?? 6}/hour; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
698
- ...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
756
+ `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; busy cap ${pool.turns_per_hour ?? 60}/hour, unproductive fault ${pool.unproductive_per_hour ?? 6}/hour${pool.quota_substitution ? "; quota substitution enabled" : ""}; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
757
+ ...(pool.adaptive ? [` adaptive target ${pool.adaptive.target} (min ${pool.adaptive.min}, max ${pool.adaptive.max}); ${pool.adaptive.snapshot?.decision?.kind ?? "state unknown"}: ${pool.adaptive.snapshot?.decision?.reason ?? "no snapshot"}; queued ${pool.adaptive.snapshot?.queuedWork ?? "unknown"}, idle ${pool.adaptive.snapshot?.usableIdleSlots ?? "unknown"}, oldest ${pool.adaptive.snapshot?.oldestQueuedAgeSeconds == null ? "unknown" : `${Math.floor(pool.adaptive.snapshot.oldestQueuedAgeSeconds / 60)}m`}`] : []),
758
+ ...(pool.adaptive?.paused ? [" scaling paused by operator"] : []),
759
+ ...(pool.slots ?? []).map((slot) => ` ${slot.slot}: ${slot.suspended ? `SUSPENDED${slot.bench_note ? ` (${slot.bench_note})` : ""}` : slot.drain?.state && slot.drain.state !== "none" ? `DRAIN ${slot.drain.state}${slot.drain.reason ? ` (${slot.drain.reason})` : ""}` : slot.desired ?? "unplaced"}; ${slot.machine ? `on ${slot.machine}` : "NOT PLACED"}${slot.reported_state ? `; reported ${slot.reported_state}` : ""}${slot.stale_machine ? "; machine stale" : ""}${slot.pin ? `; pinned ${slot.pin.machine}${slot.pin.conflict ? ` (conflict: ${slot.pin.conflict})` : ""}` : ""}${slot.quota_pause ? `; quota paused: ${slot.quota_pause}` : ""}${slot.current_work ? `; work ${slot.current_work}` : ""}`),
760
+ ...(pool.slots ? [] : (pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`)),
699
761
  ...(pool.status?.unplaced ?? []).map((x) => KEPT_IN_PLACE.test(x.reason)
700
762
  ? ` ${x.agent.padEnd(32)} KEPT IN PLACE (cannot move): ${x.reason}`
701
763
  : ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
@@ -708,9 +770,12 @@ export async function poolAdmin(action, rest, p, out, argv) {
708
770
  if (action === "set") {
709
771
  const [project, name] = (rest[0] ?? "").split("/");
710
772
  const variants = repeated(argv, "variant").map(parseVariant);
711
- const count = Number(str(p.flags, "count"));
712
- if (!project || !name || !variants.length || !Number.isInteger(count))
713
- throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60]");
773
+ const countRaw = str(p.flags, "count"), minRaw = str(p.flags, "min"), maxRaw = str(p.flags, "max");
774
+ const count = countRaw === undefined ? undefined : Number(countRaw);
775
+ const min = minRaw === undefined ? undefined : Number(minRaw), max = maxRaw === undefined ? undefined : Number(maxRaw);
776
+ const adaptive = minRaw !== undefined || maxRaw !== undefined;
777
+ if (!project || !name || !variants.length || (adaptive ? min === undefined || max === undefined || !Number.isInteger(min) || !Number.isInteger(max) || min < 0 || max > 50 || min > max || (count !== undefined && (!Number.isInteger(count) || count < min || count > max)) : count === undefined || !Number.isInteger(count) || count < 0 || count > 50))
778
+ throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] (--count <n> | --min <n> --max <n> [--count <target>]) --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60]");
714
779
  const needs = { ...(str(p.flags, "needs") ? { labels: str(p.flags, "needs").split(",").map((x) => x.trim()).filter(Boolean) } : {}), ...(str(p.flags, "min-ram") ? { min_ram_gb: Number(str(p.flags, "min-ram")) } : {}) };
715
780
  const tt = str(p.flags, "turn-timeout");
716
781
  const tph = str(p.flags, "turns-per-hour");
@@ -719,8 +784,11 @@ export async function poolAdmin(action, rest, p, out, argv) {
719
784
  throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
720
785
  if (uph !== undefined && (!/^\d+$/.test(uph) || Number(uph) < 1 || Number(uph) > 60))
721
786
  throw new CliError("usage", "--unproductive-per-hour must be a whole number from 1 to 60");
722
- const r = await c.call("PUT", `/projects/${project}/pools/${name}`, { role: str(p.flags, "role") ?? null, variants, count, sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}), ...(tph ? { turns_per_hour: Number(tph) } : {}), ...(uph ? { unproductive_per_hour: Number(uph) } : {}) });
723
- return out.print([...statusLines(r.pool), ...keptWarning(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
787
+ const body = { role: str(p.flags, "role") ?? null, variants, ...(count !== undefined ? { count } : {}), ...(adaptive ? { min, max } : {}), ...(p.flags["quota-substitution"] !== undefined ? { quota_substitution: bool(p.flags, "quota-substitution") } : {}), sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}), ...(tph ? { turns_per_hour: Number(tph) } : {}), ...(uph ? { unproductive_per_hour: Number(uph) } : {}) };
788
+ return previewOrConfirm(project, name, "configure", body, async (revision) => {
789
+ const r = await c.call("PUT", path(project, name), { ...body, impact_revision: revision });
790
+ return out.print([...statusLines(r.pool), ...keptWarning(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
791
+ });
724
792
  }
725
793
  if (action === "list" || action === undefined) {
726
794
  const r = await c.call("GET", rest[0] ? `/projects/${rest[0]}/pools` : "/pools");
@@ -728,20 +796,59 @@ export async function poolAdmin(action, rest, p, out, argv) {
728
796
  }
729
797
  if (action === "show") {
730
798
  const [project, name] = (rest[0] ?? "").split("/");
731
- const r = await c.call("GET", `/projects/${project}/pools`);
732
- const pool = r.pools.find((x) => x.name === name);
733
- if (!pool)
734
- throw new CliError("not_found", `no pool ${rest[0]}`);
799
+ if (!project || !name)
800
+ throw new CliError("usage", "pool show <project>/<name>");
801
+ const r = await c.call("GET", path(project, name));
802
+ const pool = r.pool;
735
803
  return out.print(statusLines(pool).join("\n"), { pool });
736
804
  }
805
+ if (action === "events" || action === "decisions") {
806
+ const [project, name] = (rest[0] ?? "").split("/");
807
+ if (!project || !name)
808
+ throw new CliError("usage", "pool events <project>/<name> [--limit 1..100]");
809
+ const limit = str(p.flags, "limit");
810
+ if (limit !== undefined && (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > 100))
811
+ throw new CliError("usage", "--limit must be a whole number from 1 to 100");
812
+ const r = await c.call("GET", `${path(project, name)}/decisions${limit ? `?limit=${limit}` : ""}`);
813
+ const lines = (r.events ?? []).map((event) => `${event.at} ${event.kind} by ${event.actor}: ${event.reason}${event.after ? `; ${JSON.stringify(event.after)}` : ""}`);
814
+ return out.print(lines.join("\n") || "No pool decisions recorded.", r);
815
+ }
816
+ if (action === "pause" || action === "resume") {
817
+ const [project, name] = (rest[0] ?? "").split("/");
818
+ if (!project || !name)
819
+ throw new CliError("usage", `pool ${action} <project>/<name> [--reason <text>]`);
820
+ const reason = str(p.flags, "reason");
821
+ const body = reason === undefined ? {} : { reason };
822
+ return previewOrConfirm(project, name, action, body, async (revision) => {
823
+ const r = await c.call("POST", `${path(project, name)}/${action}`, { ...body, impact_revision: revision });
824
+ return out.print(`${project}/${name}: scaling ${action === "pause" ? "paused" : "resumed"}.${reason ? ` ${reason}` : ""}`, r);
825
+ });
826
+ }
827
+ if (["pin", "unpin", "suspend", "restore"].includes(action ?? "")) {
828
+ const [project, name] = (rest[0] ?? "").split("/");
829
+ const slot = rest[1];
830
+ if (!project || !name || !slot)
831
+ throw new CliError("usage", `pool ${action} <project>/<name> <slot> ${action === "pin" ? "--machine <name> " : ""}[--reason <text>] [--note <text>]`);
832
+ const reason = str(p.flags, "reason"), note = str(p.flags, "note"), machine = str(p.flags, "machine"), until = str(p.flags, "until");
833
+ if (action === "pin" && !machine)
834
+ throw new CliError("usage", "pool pin requires --machine <name>");
835
+ const body = { ...(machine ? { machine } : {}), ...(until !== undefined ? { expires_at: until } : {}), ...(reason !== undefined ? { reason } : {}), ...(note !== undefined ? { note } : {}) };
836
+ const endpoint = `${path(project, name)}/slots/${encodeURIComponent(slot)}/${action === "pin" || action === "unpin" ? "pin" : action === "suspend" ? "suspend" : "restore"}`;
837
+ return previewOrConfirm(project, name, action, { ...body, slot }, async (revision) => {
838
+ const r = await c.call(action === "pin" ? "PUT" : action === "unpin" ? "DELETE" : "POST", endpoint, { ...body, impact_revision: revision });
839
+ return out.print(`${project}/${name}/${slot}: ${action === "unpin" ? "pin cleared" : action === "restore" ? "slot restored" : action === "suspend" ? "slot suspended" : `pinned to ${machine}${until ? ` until ${until}` : ""}`}.`, r);
840
+ });
841
+ }
737
842
  if (action === "remove") {
738
843
  const [project, name] = (rest[0] ?? "").split("/");
739
844
  if (!project || !name)
740
845
  throw new CliError("usage", "pool remove <project>/<name> (retires its agents; their units go back to the queue)");
741
- await c.call("DELETE", `/projects/${project}/pools/${name}`);
742
- return out.print(`Removed pool ${rest[0]}: its agents are retired and their sessions removed.`, { removed: rest[0] });
846
+ return previewOrConfirm(project, name, "remove", {}, async (revision) => {
847
+ const r = await c.call("DELETE", `/projects/${project}/pools/${name}`, { impact_revision: revision });
848
+ return out.print(`Removed pool ${rest[0]}: its agents are retired and their sessions removed.`, { removed: rest[0], ...r });
849
+ });
743
850
  }
744
- throw new CliError("usage", "pool set <project>/<name> ... | list [project] | show <project>/<name> | remove <project>/<name>");
851
+ throw new CliError("usage", "pool set <project>/<name> ... | list [project] | show <project>/<name> | events <project>/<name> | pause|resume <project>/<name> | pin|unpin|suspend|restore <project>/<name> <slot> | remove <project>/<name>");
745
852
  }
746
853
  /** project checkout <project> --exclude logs/,docs/big | none: paths new worktrees leave out. */
747
854
  export async function projectCheckoutAdmin(rest, p, out) {
@@ -1,25 +1,27 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
+ import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "../tail-lines.js";
3
+ import { rotateLogs } from "../log-rotation.js";
2
4
  import { createHash, createHmac } from "node:crypto";
3
5
  import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
4
6
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
5
7
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
6
8
  import { str } from "../args.js";
7
9
  import { Client } from "../client.js";
8
- import { configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
10
+ import { agentRef, configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
9
11
  import { CliError } from "../errors.js";
10
12
  import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
11
13
  import { applySparse, sessionCheckoutFacts } from "../git.js";
12
14
  import { drainingUntil, writeMaintenance } from "../maintenance.js";
13
- import { TURN_HARNESSES, claudeFacts, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
15
+ import { TURN_HARNESSES, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
14
16
  import { readState, writeState } from "../state.js";
15
- import { installService, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
17
+ import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
16
18
  import { CLI_VERSION } from "../version.js";
17
19
  import { probeCapabilities } from "../capabilities.js";
18
20
  import { diskSpaceNotice } from "../notices.js";
19
21
  import { verifyClaudeProvider } from "../providers.js";
20
22
  import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard, verificationUnavailable } from "../turn-guard.js";
21
23
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
22
- import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
24
+ import { antigravityPath, antigravitySandboxPermissions, antigravityTurnArgs, antigravityTurnEnv, parseAntigravityJson } from "../antigravity.js";
23
25
  import { bootTimeMs } from "../boot-time.js";
24
26
  import { DEFAULT_CACHE_FLOOR_PCT, manageBuildCaches } from "../build-caches.js";
25
27
  import { agentContainerName, agentContainerRunArgs, detectEc2Host, ensurePinnedImagePulled, isolatedBuildCommand, isolatedDevcontainerBuildCommand, isolatedImagePullCommands, isolatedSubprocessEnv, probeContainerImdsIsolation, networklessRuntimeWrapper, parseContainerRuntimeVersion, probeImdsIsolation, probeNestedSandbox, readGitIdentity, resolveSessionSecretDelivery, resolveWritableMounts, validateDevcontainerSpec, BUILD_SECRET_KEY_NAME_RE, BUILD_SECRET_CONTENT_RE, containsBuildSecretMaterial, sanitizeBuildDiagnosticText, } from "../container.js";
@@ -852,6 +854,9 @@ export async function launchDesiredSession(opts) {
852
854
  return { status: 1, stdout: "", stderr: `timed out waiting for in-container b9s start (${containerName})` };
853
855
  }
854
856
  /** One pass: make what runs here match what the operator declared, then report. */
857
+ /** Service logs are rotated by the daemon (WU #481), checked at most this often. */
858
+ const LOG_ROTATION_EVERY_MS = 10 * 60_000;
859
+ let lastLogRotationAt = 0;
855
860
  export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
856
861
  const client = Client.raw(m.url, m.key, {
857
862
  requestTimeoutMs: MACHINE_REQUEST_TIMEOUT_MS,
@@ -860,6 +865,11 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
860
865
  ? `request start ${event.method} ${event.path}`
861
866
  : `request end ${event.method} ${event.path} in ${event.durationMs}ms${event.error ? ` (${event.error})` : ""}`),
862
867
  });
868
+ if (Date.now() - lastLogRotationAt >= LOG_ROTATION_EVERY_MS) {
869
+ lastLogRotationAt = Date.now();
870
+ for (const r of rotateLogs(join(configRoot(), "logs")))
871
+ log(`rotated ${r.file}: ${Math.round(r.bytes_before / 1048576)} MB, kept the newest ${Math.round(r.kept_bytes / 1048576)} MB as ${r.file}.1`);
872
+ }
863
873
  const me = await client.call("GET", "/machines/me");
864
874
  const desired = me.sessions;
865
875
  const processScanner = deps?.worktreeProcessScanner ?? scanWorktreeProcesses;
@@ -1182,7 +1192,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1182
1192
  dir: s.dir,
1183
1193
  thread: th,
1184
1194
  watcher: watcherState,
1185
- last_turn: lastTurnLine(s.agent),
1195
+ ...((t) => ({ last_turn: t.line, ...(t.unknown_reason ? { last_turn_unknown: t.unknown_reason } : {}) }))(lastTurn(s.agent)),
1186
1196
  turn_judgment: s.turn_judgment ?? null,
1187
1197
  ...(s.pool_move_pending ? { checkout: sessionCheckoutFacts(s.dir) } : {}),
1188
1198
  ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR),
@@ -1661,16 +1671,37 @@ export function turnProcess(thread, harness = "codex", psOutput, agent) {
1661
1671
  */
1662
1672
  const CRASH_STARTS = 5;
1663
1673
  const CRASH_WINDOW_MS = 5 * 60_000;
1664
- function watcherLogText(ref) {
1674
+ /**
1675
+ * The last 64 KiB of a watcher's error log. Log rotation (WU #481) can empty the live file; then the
1676
+ * rotated <name>.1 supplies the rest of the window, from a line start, so a fault the guards look for
1677
+ * (a directory_conflict marker, a crash loop) is still seen on the pass right after a rotation.
1678
+ */
1679
+ export function watcherLogText(ref) {
1665
1680
  const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
1666
1681
  if (!existsSync(f))
1667
1682
  return null;
1668
- const size = statSync(f).size;
1669
- const fd = openSync(f, "r");
1670
- const buf = Buffer.alloc(Math.min(size, 65_536));
1671
- readSync(fd, buf, 0, buf.length, size - buf.length);
1672
- closeSync(fd);
1673
- return buf.toString("utf8");
1683
+ const WINDOW = 65_536;
1684
+ const tail = (path, max) => {
1685
+ const size = statSync(path).size;
1686
+ const fd = openSync(path, "r");
1687
+ try {
1688
+ const buf = Buffer.alloc(Math.min(size, max));
1689
+ readSync(fd, buf, 0, buf.length, size - buf.length);
1690
+ return buf;
1691
+ }
1692
+ finally {
1693
+ closeSync(fd);
1694
+ }
1695
+ };
1696
+ const live = tail(f, WINDOW);
1697
+ const rotated = `${f}.1`;
1698
+ if (live.length >= WINDOW || !existsSync(rotated))
1699
+ return live.toString("utf8");
1700
+ let earlier = tail(rotated, WINDOW - live.length);
1701
+ const nl = earlier.indexOf(0x0a);
1702
+ if (statSync(rotated).size > earlier.length && nl >= 0)
1703
+ earlier = earlier.subarray(nl + 1); // start at a whole line
1704
+ return Buffer.concat([earlier, live]).toString("utf8");
1674
1705
  }
1675
1706
  /** A marked startup failure is unambiguous even when it prevents the first watching banner. */
1676
1707
  export function watcherDirectoryConflict(ref, logText) {
@@ -1736,12 +1767,44 @@ export function watcherFault(ref, logText, nowMs = Date.now()) {
1736
1767
  }
1737
1768
  }
1738
1769
  /** The watcher's latest turn line (started, finished, FAILED, STOPPED, paused), for the report. */
1739
- function lastTurnLine(ref) {
1770
+ const TURN_LINE = (l) => /b9s watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l);
1771
+ const lastTurnCache = new FileFactsCache();
1772
+ /**
1773
+ * The latest turn line of a watcher log, read from the end (WU #481: the whole-file read ran per session
1774
+ * per pass over logs up to 190 MB). Within the cap it equals the whole-file answer; past it, line is null
1775
+ * and unknown_reason says why, so no diagnostic text is ever reported as a turn line.
1776
+ */
1777
+ export function lastTurnFromFile(f, chunkBytes = TAIL_CHUNK_BYTES, maxBytes = TAIL_MAX_BYTES) {
1778
+ let found = null;
1779
+ const visit = (l) => { if (TURN_LINE(l)) {
1780
+ found = l.slice(0, 300);
1781
+ return true;
1782
+ } return false; };
1783
+ const scan = scanLinesBackward(f, visit, chunkBytes, maxBytes);
1784
+ let read = scan.bytesRead;
1785
+ let capped = scan.capped;
1786
+ // A rotation (WU #481) may have moved the latest turn line into <name>.1 and left the live log short:
1787
+ // continue there with what is left of the same cap, so rotation never hides the latest turn.
1788
+ const rotated = `${f}.1`;
1789
+ if (found === null && !capped && existsSync(rotated) && statSync(rotated).size > 0) {
1790
+ if (read < maxBytes) {
1791
+ const more = scanLinesBackward(rotated, visit, chunkBytes, maxBytes - read);
1792
+ read += more.bytesRead;
1793
+ capped = more.capped;
1794
+ }
1795
+ else {
1796
+ capped = true; // the budget ended exactly at the live log's start; the rotated bytes went unread
1797
+ }
1798
+ }
1799
+ if (found !== null)
1800
+ return { line: found };
1801
+ return capped ? { line: null, unknown_reason: `no turn line in the last ${Math.round(maxBytes / 1048576)} MB of the watcher log` } : { line: null };
1802
+ }
1803
+ export function lastTurn(ref) {
1740
1804
  const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
1741
1805
  if (!existsSync(f))
1742
- return null;
1743
- const lines = readFileSync(f, "utf8").split("\n").filter((l) => /b9s watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l));
1744
- return lines.length ? lines[lines.length - 1].slice(0, 300) : null;
1806
+ return { line: null };
1807
+ return lastTurnCache.get(f, (path) => lastTurnFromFile(path));
1745
1808
  }
1746
1809
  function volumeSpace(path, label) {
1747
1810
  try {
@@ -1809,6 +1872,16 @@ function antigravityUsernsDenied(parsed, output) {
1809
1872
  const denied = value?.denied_actions ?? error?.denied_actions;
1810
1873
  return /Terminal sandbox unavailable/i.test(output) || (Array.isArray(denied) && denied.some((entry) => entry && typeof entry === "object" && entry.action === "command"));
1811
1874
  }
1875
+ /** Resolve an authenticated identity before the probe moves into its fresh temporary cwd. */
1876
+ function antigravityProbeAgent(sessions = [], cwd = process.cwd()) {
1877
+ const session = sessions.find((item) => item.harness === "antigravity") ?? sessions[0];
1878
+ try {
1879
+ return resolveAgentName(session?.agent ?? process.env.BSCHAT_AGENT?.trim(), process.env, cwd);
1880
+ }
1881
+ catch {
1882
+ return null;
1883
+ }
1884
+ }
1812
1885
  /** Install only an absent or byte-identical b9s profile; leave every other owner untouched. */
1813
1886
  export function installAgyAppArmorProfile(binary, profilePath = AGY_APPARMOR_PATH, run = (args, input) => spawnSync("sudo", args, { input, encoding: "utf8", stdio: input === undefined ? "pipe" : ["pipe", "ignore", "pipe"] })) {
1814
1887
  const profile = agyAppArmorProfile(binary);
@@ -1838,13 +1911,38 @@ function resolvedAgyBinary(path) {
1838
1911
  const binary = result.status === 0 ? (result.stdout ?? "").trim() : "";
1839
1912
  return isAbsolute(binary) ? binary : null;
1840
1913
  }
1841
- /** Runs one cached no-op turn through Antigravity's real workspace-write terminal sandbox. */
1842
- export function antigravitySandbox(force = false, path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
1843
- if (!force && agySandboxCache && agySandboxCache.path === path && agySandboxCache.b9sBin === b9sBin && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
1914
+ /** Runs one cached authenticated API check through Antigravity's real workspace-write terminal sandbox. */
1915
+ export function antigravitySandbox(force = false, path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null, agent = antigravityProbeAgent()) {
1916
+ if (agent) {
1917
+ try {
1918
+ agent = resolveAgentName(agent, process.env, process.cwd());
1919
+ }
1920
+ catch {
1921
+ agent = null;
1922
+ }
1923
+ }
1924
+ if (!agent) {
1925
+ const result = { ok: false, error: "authenticated sandbox probe has no project-agent identity; set BSCHAT_AGENT or run from a checkout with a b9s identity" };
1926
+ agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint: null };
1927
+ return result;
1928
+ }
1929
+ let credentialFingerprint;
1930
+ try {
1931
+ const credentials = loadAgent(agent);
1932
+ if (agentRef(credentials) !== agent)
1933
+ throw new Error("saved identity does not match the selected agent");
1934
+ credentialFingerprint = createHash("sha256").update(credentials.key).digest("hex");
1935
+ }
1936
+ catch {
1937
+ const result = { ok: false, error: `authenticated sandbox probe cannot resolve saved credentials for ${agent} from the machine's b9s home` };
1938
+ agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint: null };
1939
+ return result;
1940
+ }
1941
+ if (!force && agySandboxCache && agySandboxCache.path === path && agySandboxCache.b9sBin === b9sBin && agySandboxCache.agent === agent && agySandboxCache.credentialFingerprint === credentialFingerprint && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
1844
1942
  return agySandboxCache.result;
1845
1943
  if (!b9sBin) {
1846
1944
  const result = { ok: false, error: `recorded b9s install is unavailable; expected ${join(configRoot(), "install.json")}` };
1847
- agySandboxCache = { at: Date.now(), result, path, b9sBin };
1945
+ agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint };
1848
1946
  return result;
1849
1947
  }
1850
1948
  let result;
@@ -1852,11 +1950,19 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
1852
1950
  try {
1853
1951
  work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
1854
1952
  const marker = join(work, ".b9s-sandbox-probe");
1953
+ const meOutputPath = join(work, ".b9s-sandbox-probe-me");
1954
+ const meErrorPath = join(work, ".b9s-sandbox-probe-me-error");
1955
+ const meStatusPath = join(work, ".b9s-sandbox-probe-status");
1855
1956
  const quotedMarker = `'${marker.replace(/'/g, `'\\''`)}'`;
1856
- const prompt = `Use your terminal tool once to run exactly: b9s --version && printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
1957
+ const quotedMeOutput = `'${meOutputPath.replace(/'/g, `'\\''`)}'`;
1958
+ const quotedMeError = `'${meErrorPath.replace(/'/g, `'\\''`)}'`;
1959
+ const quotedMeStatus = `'${meStatusPath.replace(/'/g, `'\\''`)}'`;
1960
+ const command = `b9s me > ${quotedMeOutput} 2> ${quotedMeError}; me_status=$?; printf '%s' "$me_status" > ${quotedMeStatus}; if [ "$me_status" -eq 0 ]; then printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}; fi`;
1961
+ const prompt = `Use your terminal tool once to run this exact command and do not replace or simulate its output: ${command}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
1857
1962
  const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: antigravitySandboxPermissions("api.benignswarm.org", configRoot(), b9sBin) } })];
1858
1963
  const r = spawnSync("agy", antigravityTurnArgs(prompt, AGY_SANDBOX_PROBE_MODEL, undefined, 45, settings), {
1859
- encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work, env: { ...process.env, PATH: antigravityPath(b9sBin, path) },
1964
+ encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work,
1965
+ env: { ...process.env, ...antigravityTurnEnv("workspace-write", b9sBin), BSCHAT_AGENT: agent, PATH: antigravityPath(b9sBin, path) },
1860
1966
  });
1861
1967
  const parsed = parseAntigravityJson(r.stdout ?? "");
1862
1968
  let wroteMarker = false;
@@ -1864,22 +1970,39 @@ export function antigravitySandbox(force = false, path = process.env.PATH ?? "",
1864
1970
  wroteMarker = readFileSync(marker, "utf8") === AGY_SANDBOX_PROBE_RESPONSE;
1865
1971
  }
1866
1972
  catch { /* a missing marker means the sandbox command did not run */ }
1973
+ let meOutput = "";
1974
+ let meError = "";
1975
+ let meStatus = "";
1976
+ try {
1977
+ meOutput = readFileSync(meOutputPath, "utf8");
1978
+ }
1979
+ catch { /* missing output means b9s me did not run */ }
1980
+ try {
1981
+ meError = readFileSync(meErrorPath, "utf8");
1982
+ }
1983
+ catch { /* missing stderr means b9s me did not run */ }
1984
+ try {
1985
+ meStatus = readFileSync(meStatusPath, "utf8");
1986
+ }
1987
+ catch { /* missing status means b9s me did not run */ }
1988
+ const authenticatedMe = meStatus === "0" && /^agent:\s+\S+/m.test(meOutput);
1989
+ const meDiagnostic = meError.trim().replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/(https?:\/\/)[^/\s@]+@/gi, "$1[redacted]@").slice(0, 300);
1867
1990
  const output = `${r.stdout ?? ""}\n${r.stderr ?? ""}`;
1868
- result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker
1991
+ result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker && authenticatedMe
1869
1992
  ? { ok: true, error: null }
1870
1993
  : { ok: false, error: antigravityUsernsDenied(parsed, output)
1871
1994
  ? AGY_USERNS_FIX
1872
- : `sandbox could not run b9s --version and its no-op check (agy exit ${r.status ?? "unknown"}); verify recorded install ${b9sBin} and Node runtime ${process.execPath} are readable and executable inside the sandbox` };
1995
+ : `sandbox authenticated API check failed (b9s me exit ${meStatus || "unknown"}; agy exit ${r.status ?? "unknown"})${meDiagnostic ? `: ${meDiagnostic}` : meOutput && !authenticatedMe ? `: ${meOutput.trim().slice(0, 300)}` : ""}; verify the API host is allowed and the recorded b9s install ${b9sBin} and Node runtime ${process.execPath} are usable inside the sandbox` };
1873
1996
  }
1874
1997
  catch (error) {
1875
1998
  const detail = error instanceof Error ? error.message : String(error);
1876
- result = { ok: false, error: `sandbox could not prepare b9s --version probe for recorded install ${b9sBin} with Node runtime ${process.execPath}: ${detail}` };
1999
+ result = { ok: false, error: `sandbox could not prepare authenticated b9s me probe for recorded install ${b9sBin} with Node runtime ${process.execPath}: ${detail}` };
1877
2000
  }
1878
2001
  finally {
1879
2002
  if (work)
1880
2003
  rmSync(work, { recursive: true, force: true });
1881
2004
  }
1882
- agySandboxCache = { at: Date.now(), result, path, b9sBin };
2005
+ agySandboxCache = { at: Date.now(), result, path, b9sBin, agent, credentialFingerprint };
1883
2006
  return result;
1884
2007
  }
1885
2008
  function antigravityLoginFacts(path) {
@@ -1896,11 +2019,11 @@ function antigravityLoginFacts(path) {
1896
2019
  };
1897
2020
  }
1898
2021
  /** Machine facts used by placement; the daemon probes login cheaply and caches the sandbox turn. */
1899
- export function antigravityFacts(path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null) {
2022
+ export function antigravityFacts(path = process.env.PATH ?? "", b9sBin = readInstall()?.bin ?? null, agent = antigravityProbeAgent()) {
1900
2023
  const facts = antigravityLoginFacts(path);
1901
2024
  return {
1902
2025
  ...facts,
1903
- sandbox: facts.logged_in ? antigravitySandbox(false, path, b9sBin) : null,
2026
+ sandbox: facts.logged_in ? antigravitySandbox(false, path, b9sBin, agent) : null,
1904
2027
  };
1905
2028
  }
1906
2029
  /** Linux's MemAvailable; Darwin is supplied by vm_stat, never approximated by free pages. */
@@ -1913,12 +2036,24 @@ function memAvailable() {
1913
2036
  }
1914
2037
  return platform() === "darwin" ? null : freemem();
1915
2038
  }
2039
+ /**
2040
+ * On a headless Mac, a Claude Code sign-in kept in the login keychain can't be read, and 'claude auth status'
2041
+ * then reports no stored login, which looks the same as never having signed in. The observed status is kept;
2042
+ * when it is "not logged in" there, with no file credential, the report adds the keychain as a possible cause
2043
+ * and its fix as a readiness gap (WU #478). A rejected stored login or any other failure is left as observed.
2044
+ */
2045
+ export function claudeKeychainGap(f, headlessMac, fileCredentials) {
2046
+ if (!headlessMac || fileCredentials || f.logged_in || f.login !== "not logged in")
2047
+ return f;
2048
+ return { ...f, readiness_gap: "possible cause: this Mac has no desktop session, and a Claude Code sign-in kept in the login keychain can't be read without one. If Claude Code is signed in at the desktop, sign in there (or enable automatic sign-in), or store a file credential with 'claude setup-token'" };
2049
+ }
1916
2050
  /** Claude Code's version, login and sandbox; the sandbox check runs at most every 10 min. */
1917
2051
  let claudeSandboxCache = null;
1918
2052
  function claudeReport(path = process.env.PATH ?? "", providersInUse = ["anthropic"]) {
1919
- const f = claudeFacts(undefined, path);
1920
- if (!f)
2053
+ const found = claudeFacts(undefined, path);
2054
+ if (!found)
1921
2055
  return null;
2056
+ const f = claudeKeychainGap(found, process.platform === "darwin" && launchdSessionNow() === "headless", existsSync(join(claudeHome(), ".credentials.json")));
1922
2057
  if (!claudeSandboxCache || claudeSandboxCache.path !== path || Date.now() - claudeSandboxCache.at > 10 * 60_000)
1923
2058
  claudeSandboxCache = { at: Date.now(), result: claudeSandbox(path), path };
1924
2059
  const providers = {};
@@ -1945,7 +2080,8 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1945
2080
  return 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), account_fingerprint: codexAccountFingerprint(), sandbox: codexSandbox(false, path) } : null;
1946
2081
  })();
1947
2082
  const dsh = (probes?.dsh ?? (() => dshFacts(platform(), path)))();
1948
- const antigravity = (probes?.antigravity ?? (() => antigravityFacts(path)))();
2083
+ const probeAgent = antigravityProbeAgent(sessions);
2084
+ const antigravity = probes?.antigravity ? probes.antigravity(probeAgent) : antigravityFacts(path, readInstall()?.bin ?? null, probeAgent);
1949
2085
  const homeSpace = volumeSpace(homedir(), "home");
1950
2086
  const readTelemetryFile = (path) => { try {
1951
2087
  return readFileSync(path, "utf8");
@@ -1987,6 +2123,8 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1987
2123
  booted_at: bootedAt === null ? null : new Date(Math.floor(bootedAt / 60_000) * 60_000).toISOString(),
1988
2124
  booted_at_exact: bootedAt === null ? null : new Date(bootedAt).toISOString(),
1989
2125
  daemon_path: path,
2126
+ // macOS: which launchd domain the services use, so a headless Mac is visible, never silent (WU #478).
2127
+ ...(platform() === "darwin" ? { launchd: (probes?.launchd ?? launchdFacts)() } : {}),
1990
2128
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
1991
2129
  git_identity: gitIdentity,
1992
2130
  on_ec2: onEc2,
@@ -2122,6 +2260,8 @@ export function prepare(opts = {}) {
2122
2260
  const daemonPath = machineDaemonPath();
2123
2261
  const daemonEnv = { ...process.env, PATH: daemonPath };
2124
2262
  steps.push({ step: "daemon PATH", result: "ok", detail: daemonPath });
2263
+ if (platform() === "darwin")
2264
+ steps.push({ step: "launchd", result: "ok", detail: launchdGuidance() });
2125
2265
  if (platform() === "darwin")
2126
2266
  steps.push(...macReadinessSteps(macReadiness({ path: daemonPath })).map((step) => ({ ...step, result: step.result })));
2127
2267
  const sudo = spawnSync("sudo", ["-n", "true"], { stdio: "ignore" }).status === 0;
@@ -2611,7 +2751,8 @@ export async function machine(p, out) {
2611
2751
  const bin = requireInstall().bin;
2612
2752
  const daemonPath = machineDaemonPath();
2613
2753
  const path = installService(MACHINE_LABEL, [bin, "machine", "run"], homedir(), { PATH: daemonPath, HOME: homedir() }, "machine");
2614
- return out.print(`Wrote ${path} and (re)started it: the machine daemon runs ${bin} machine run with PATH ${daemonPath}. Logs: ~/.b9s/logs/machine.*.log`, { path, label: MACHINE_LABEL, daemon_path: daemonPath });
2754
+ const launchd = process.platform === "darwin" ? { ...launchdFacts(), guidance: launchdGuidance() } : null;
2755
+ return out.print([`Wrote ${path} and (re)started it: the machine daemon runs ${bin} machine run with PATH ${daemonPath}. Logs: ~/.b9s/logs/machine.*.log`, ...(launchd ? [launchd.guidance] : [])].join("\n"), { path, label: MACHINE_LABEL, daemon_path: daemonPath, ...(launchd ? { launchd } : {}) });
2615
2756
  }
2616
2757
  const m = loadMachine();
2617
2758
  const log = (s) => process.stderr.write(`${new Date().toISOString()} b9s machine[${m.name}]: ${s}\n`);
@@ -2623,7 +2764,8 @@ export async function machine(p, out) {
2623
2764
  const judgment = s.turn_judgment ? ` judgment ${s.turn_judgment.state}: ${s.turn_judgment.trigger_reasons.join(", ")}` : "";
2624
2765
  return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} ${s.harness}/${s.provider ?? "anthropic"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"}${judgment} ${s.dir}`;
2625
2766
  });
2626
- return out.print([`machine ${m.name} (${m.url})`, ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state });
2767
+ const launchd = process.platform === "darwin" ? launchdFacts() : null;
2768
+ return out.print([`machine ${m.name} (${m.url})`, ...(launchd ? [launchdFactsLine(launchd)] : []), ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state, ...(launchd ? { launchd } : {}) });
2627
2769
  }
2628
2770
  if (sub === "once") {
2629
2771
  const r = await reconcile(m, log);