benignswarm 0.12.93 → 0.12.95

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.
@@ -140,14 +140,43 @@ export async function machineAdmin(action, rest, p, out) {
140
140
  const m = r.machine;
141
141
  const rep = m.report ?? {};
142
142
  const head = [
143
- `${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; writable ${(m.writable ?? []).join(", ") || "-"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}`,
143
+ `${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; writable ${(m.writable ?? []).join(", ") || "-"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}; cache budget ${m.cache_budget_gb ?? 40} GB (floor ${m.cache_floor_pct ?? 15}%)`,
144
144
  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?)",
145
+ 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,
145
146
  ];
147
+ const cacheLines = [];
148
+ const declaredCaches = (m.build_caches ?? []);
149
+ if (declaredCaches.length)
150
+ cacheLines.push(` declared build caches: ${declaredCaches.map((c) => c.path).join(", ")}`);
151
+ const cacheReport = rep.build_caches;
152
+ if (cacheReport) {
153
+ for (const v of cacheReport.volumes ?? []) {
154
+ const freed = v.freed_bytes > 0 ? `, freed ${Math.round(v.freed_bytes / 1e6)} MB` : "";
155
+ cacheLines.push(` volume ${v.mount}: ${v.free_pct.toFixed(1)}% free${v.under_floor ? " (UNDER FLOOR)" : ""}${freed}`);
156
+ }
157
+ for (const cItem of cacheReport.caches ?? []) {
158
+ const mb = Math.round(cItem.size_bytes / 1e6);
159
+ const protectedNote = cItem.skipped_protected?.length ? `; retained protected: ${cItem.skipped_protected.join(", ")}` : "";
160
+ const note = cItem.status === "skipped_in_use"
161
+ ? ` (${cItem.probe_incomplete ? "inspection incomplete: " : "in use by "}${(cItem.active_processes ?? []).join(", ")}${protectedNote})`
162
+ : cItem.status === "skipped_protected"
163
+ ? ` (protected subtrees retained: ${(cItem.skipped_protected ?? []).join(", ")})`
164
+ : cItem.status === "cleaned"
165
+ ? ` (cleaned ${Math.round(cItem.removed_bytes / 1e6)} MB${protectedNote})`
166
+ : protectedNote ? ` (${protectedNote.slice(2)})` : "";
167
+ cacheLines.push(` cache ${cItem.path} [${cItem.volume}]: ${mb} MB [${cItem.status}]${note}`);
168
+ }
169
+ for (const f of cacheReport.faults ?? []) {
170
+ cacheLines.push(f.kind === "inspection_incomplete"
171
+ ? ` FAULT ${f.volume}: ${f.reason ?? "build process inspection incomplete"} (${(f.caches ?? []).join(", ")}; uninspected: ${(f.processes ?? []).join(", ") || "unknown"})`
172
+ : ` FAULT ${f.volume}: ${f.free_pct.toFixed(1)}% < ${f.floor_pct}% floor while ${(f.processes ?? []).join(", ") || "build"} uses ${(f.caches ?? []).join(", ")}`);
173
+ }
174
+ }
146
175
  const capabilityLines = machineCapabilityLines(m.capabilities ?? []);
147
176
  const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", harness: s.harness, provider: s.provider ?? "anthropic", 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+ b9s watch\[[^\]]+\]: /, "") }));
148
177
  const providers = rep.claude_code?.providers ?? {};
149
178
  const providerLines = Object.entries(providers).map(([provider, check]) => ` Claude Code ${provider}: ${check.logged_in ? "verified" : `NOT verified (${check.reason ?? "unknown reason"})`}`);
150
- return out.print([...head, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "thread", "harness", "provider", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
179
+ return out.print([...head, ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "thread", "harness", "provider", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].filter((line) => line !== null).join("\n"), r);
151
180
  }
152
181
  if (action === "maintenance") {
153
182
  // A window on the machine: no new turns from 15 min before, its agents away until it ends.
@@ -179,6 +208,49 @@ export async function machineAdmin(action, rest, p, out) {
179
208
  const r = await c.call("PATCH", `/machines/${name}`, { workdir: path === "default" ? null : path });
180
209
  return out.print(`${name}: pool checkouts go to ${r.machine.workdir ?? "~/bschat"} from its next pass (existing checkouts stay where they are).`, r);
181
210
  }
211
+ if (action === "cache-budget") {
212
+ const name = rest[0];
213
+ const budgetArg = rest[1];
214
+ const floorArg = str(p.flags, "floor");
215
+ const usage = "machine cache-budget <name> [<GB> | default] [--floor <pct | default>] (per declared cache directory; default 40 GB budget, 15% free volume floor)";
216
+ if (!name || (!budgetArg && !floorArg))
217
+ throw new CliError("usage", usage);
218
+ const body = {};
219
+ if (budgetArg !== undefined) {
220
+ if (budgetArg === "default")
221
+ body.cache_budget_gb = null;
222
+ else {
223
+ const gb = Number(budgetArg);
224
+ if (!Number.isInteger(gb) || gb < 1 || gb > 100_000)
225
+ throw new CliError("usage", "cache-budget <GB> must be a whole number 1..100000, or 'default'");
226
+ body.cache_budget_gb = gb;
227
+ }
228
+ }
229
+ if (floorArg !== undefined) {
230
+ if (floorArg === "default")
231
+ body.cache_floor_pct = null;
232
+ else {
233
+ const pct = Number(floorArg);
234
+ if (!Number.isInteger(pct) || pct < 1 || pct > 90)
235
+ throw new CliError("usage", "--floor <pct> must be a whole percentage 1..90, or 'default'");
236
+ body.cache_floor_pct = pct;
237
+ }
238
+ }
239
+ const r = await c.call("PATCH", `/machines/${name}`, body);
240
+ const gb = r.machine.cache_budget_gb ?? 40;
241
+ const fl = r.machine.cache_floor_pct ?? 15;
242
+ return out.print(`${name}: build cache budget ${gb} GB${r.machine.cache_budget_gb == null ? " (default)" : ""}, volume free-space floor ${fl}%${r.machine.cache_floor_pct == null ? " (default)" : ""}.`, r);
243
+ }
244
+ if (action === "caches") {
245
+ const name = rest[0];
246
+ if (!name || rest.length < 2)
247
+ throw new CliError("usage", "machine caches <name> <path...> | none [--tool auto|cargo|generic] [--processes cmd,...] (declared build cache paths managed by the daemon)");
248
+ const tool = str(p.flags, "tool");
249
+ const processes = (str(p.flags, "processes") ?? "").split(",").map((s) => s.trim()).filter(Boolean);
250
+ const build_caches = rest[1] === "none" ? [] : rest.slice(1).map((path) => ({ path, ...(tool ? { tool } : {}), ...(processes.length ? { processes } : {}) }));
251
+ const r = await c.call("PATCH", `/machines/${name}`, { build_caches });
252
+ return out.print(`${name}: declared build caches ${r.machine.build_caches.map((x) => x.path).join(", ") || "(none; only project-declared caches apply)"}.`, r);
253
+ }
182
254
  if (action === "label" || action === "slots") {
183
255
  const name = rest[0];
184
256
  if (!name)
@@ -211,13 +283,17 @@ export async function machineAdmin(action, rest, p, out) {
211
283
  if (sub === "add") {
212
284
  const turnTimeout = str(p.flags, "turn-timeout");
213
285
  const turnsPerHour = str(p.flags, "turns-per-hour");
214
- if (turnsPerHour !== undefined && (!/^\d+$/.test(turnsPerHour) || Number(turnsPerHour) < 1 || Number(turnsPerHour) > 20))
215
- throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 20");
286
+ const unproductivePerHour = str(p.flags, "unproductive-per-hour");
287
+ if (turnsPerHour !== undefined && (!/^\d+$/.test(turnsPerHour) || Number(turnsPerHour) < 1 || Number(turnsPerHour) > 60))
288
+ throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
289
+ if (unproductivePerHour !== undefined && (!/^\d+$/.test(unproductivePerHour) || Number(unproductivePerHour) < 1 || Number(unproductivePerHour) > 60))
290
+ throw new CliError("usage", "--unproductive-per-hour must be a whole number from 1 to 60");
216
291
  const body = {
217
292
  project, agent, harness: str(p.flags, "harness") ?? "codex", provider: str(p.flags, "provider") ?? "anthropic", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
218
293
  model: str(p.flags, "model"), effort: str(p.flags, "effort"), thread: str(p.flags, "thread"),
219
294
  ...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
220
295
  ...(turnsPerHour ? { turns_per_hour: Number(turnsPerHour) } : {}),
296
+ ...(unproductivePerHour ? { unproductive_per_hour: Number(unproductivePerHour) } : {}),
221
297
  create: bool(p.flags, "create"), role: str(p.flags, "role"),
222
298
  };
223
299
  const r = await c.call("POST", `/machines/${machineName}/sessions`, body);
@@ -240,10 +316,15 @@ export async function machineAdmin(action, rest, p, out) {
240
316
  }
241
317
  if (sub === "limit") {
242
318
  const value = str(p.flags, "turns-per-hour");
243
- if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 20)
244
- throw new CliError("usage", "machine session limit <machine> <project>/<agent> --turns-per-hour <1..20>");
245
- const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { turns_per_hour: Number(value) });
246
- return out.print(`${ref} on ${machineName}: turn limit set to ${value} per hour; the daemon applies it within 30 s.`, r);
319
+ const unproductive = str(p.flags, "unproductive-per-hour");
320
+ if (!value && !unproductive)
321
+ throw new CliError("usage", "machine session limit <machine> <project>/<agent> [--turns-per-hour <1..60>] [--unproductive-per-hour <1..60>]");
322
+ if (value && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 60))
323
+ throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
324
+ if (unproductive && (!/^\d+$/.test(unproductive) || Number(unproductive) < 1 || Number(unproductive) > 60))
325
+ throw new CliError("usage", "--unproductive-per-hour must be a whole number from 1 to 60");
326
+ const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { ...(value ? { turns_per_hour: Number(value) } : {}), ...(unproductive ? { unproductive_per_hour: Number(unproductive) } : {}) });
327
+ return out.print(`${ref} on ${machineName}: ${value ? `busy cap ${value}/hour` : "busy cap unchanged"}; ${unproductive ? `${unproductive} unproductive turns/hour` : "unproductive fault threshold unchanged"}; the daemon applies changes within 30 s.`, r);
247
328
  }
248
329
  if (sub === "remove") {
249
330
  await c.call("DELETE", `/machines/${machineName}/sessions/${project}/${agent}`);
@@ -273,13 +354,13 @@ export function repeated(argv, flag) {
273
354
  return out;
274
355
  }
275
356
  /**
276
- * 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..20]
357
+ * 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]
277
358
  * pool list [project] | show <project>/<name> | remove <project>/<name>
278
359
  */
279
360
  export async function poolAdmin(action, rest, p, out, argv) {
280
361
  const c = adminClient(p);
281
362
  const statusLines = (pool) => [
282
- `${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; max ${pool.turns_per_hour ?? 20} turns/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` : ""}`,
363
+ `${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` : ""}`,
283
364
  ...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
284
365
  ...(pool.status?.unplaced ?? []).map((x) => ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
285
366
  ];
@@ -288,13 +369,16 @@ export async function poolAdmin(action, rest, p, out, argv) {
288
369
  const variants = repeated(argv, "variant").map(parseVariant);
289
370
  const count = Number(str(p.flags, "count"));
290
371
  if (!project || !name || !variants.length || !Number.isInteger(count))
291
- 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..20]");
372
+ 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]");
292
373
  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")) } : {}) };
293
374
  const tt = str(p.flags, "turn-timeout");
294
375
  const tph = str(p.flags, "turns-per-hour");
295
- if (tph !== undefined && (!/^\d+$/.test(tph) || Number(tph) < 1 || Number(tph) > 20))
296
- throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 20");
297
- 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) } : {}) });
376
+ const uph = str(p.flags, "unproductive-per-hour");
377
+ if (tph !== undefined && (!/^\d+$/.test(tph) || Number(tph) < 1 || Number(tph) > 60))
378
+ throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
379
+ if (uph !== undefined && (!/^\d+$/.test(uph) || Number(uph) < 1 || Number(uph) > 60))
380
+ throw new CliError("usage", "--unproductive-per-hour must be a whole number from 1 to 60");
381
+ 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) } : {}) });
298
382
  return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
299
383
  }
300
384
  if (action === "list" || action === undefined) {
@@ -1,7 +1,7 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, statSync, statfsSync, writeFileSync } from "node:fs";
4
- import { arch, cpus, freemem, homedir, hostname, loadavg, platform, totalmem, uptime, userInfo } from "node:os";
3
+ import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, statSync, statfsSync, writeFileSync } from "node:fs";
4
+ import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { str } from "../args.js";
7
7
  import { Client } from "../client.js";
@@ -17,8 +17,11 @@ import { CLI_VERSION } from "../version.js";
17
17
  import { probeCapabilities } from "../capabilities.js";
18
18
  import { diskSpaceNotice } from "../notices.js";
19
19
  import { verifyClaudeProvider } from "../providers.js";
20
- import { resumeTurnGuard } from "../turn-guard.js";
20
+ import { busyTurnPause, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, resumeTurnGuard } from "../turn-guard.js";
21
21
  import { defaultWorkspaceWritableRoots } from "../start-options.js";
22
+ import { antigravityTurnArgs, parseAntigravityJson } from "../antigravity.js";
23
+ import { bootTimeMs } from "../boot-time.js";
24
+ import { manageBuildCaches } from "../build-caches.js";
22
25
  export const machineFile = () => join(configRoot(), "machine.json");
23
26
  export function loadMachine() {
24
27
  const f = machineFile();
@@ -38,8 +41,8 @@ function writeMachineState(s) {
38
41
  * again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
39
42
  * 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
40
43
  */
41
- const START_REV = 5;
42
- export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? 20, s.thread, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
44
+ const START_REV = 6;
45
+ export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.thread, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
43
46
  /** A clear is distinct from a thread that the server has not received from the machine yet. */
44
47
  export function reconcileThread(s, local) {
45
48
  const clearing = s.thread === null && !!s.thread_override_at && s.thread_override_at !== local?.thread_override_at;
@@ -63,7 +66,7 @@ export function maintenanceReport(drain, sessions) {
63
66
  /** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
64
67
  export function startArgs(s, thread, writable = []) {
65
68
  return [
66
- "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? 20), "--json",
69
+ "start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--json",
67
70
  ...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
68
71
  ...(s.model ? ["--model", s.model] : []),
69
72
  ...(s.effort ? ["--effort", s.effort] : []),
@@ -78,7 +81,7 @@ export function turnFaultSessionFields(fault) {
78
81
  return { turn_fault_at: new Date(fault.at).toISOString() };
79
82
  }
80
83
  /** One pass: make what runs here match what the operator declared, then report. */
81
- export async function reconcile(m, log) {
84
+ export async function reconcile(m, log, reportIntervalSeconds = 30) {
82
85
  const client = Client.raw(m.url, m.key);
83
86
  const me = await client.call("GET", "/machines/me");
84
87
  const desired = me.sessions;
@@ -151,7 +154,7 @@ export async function reconcile(m, log) {
151
154
  const fault = agentState.turn_guard.fault;
152
155
  const detail = fault.reason === "unproductive"
153
156
  ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call; likely cause: ${fault.likely_cause}`
154
- : `the ${fault.turns_last_hour}-turn hourly ceiling was reached; likely cause: ${fault.likely_cause}`;
157
+ : `${fault.unproductive_last_hour} unproductive turns in the rolling hour; likely cause: ${fault.likely_cause}`;
155
158
  const error = `turn mode stopped after ${detail}; estimated tokens spent: ${fault.estimated_tokens}; last turn output: ${fault.output_tail || "(empty)"}`.slice(0, 1000);
156
159
  const w = svc();
157
160
  if (w) {
@@ -222,7 +225,7 @@ export async function reconcile(m, log) {
222
225
  state.sessions[s.id].unpause_applied = s.unpause_at;
223
226
  log(`${s.agent}: usage-limit pause lifted by the operator`);
224
227
  }
225
- out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, s.harness, th) });
228
+ out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR) });
226
229
  }
227
230
  catch (e) {
228
231
  const error = e.message.slice(0, 1000);
@@ -242,9 +245,38 @@ export async function reconcile(m, log) {
242
245
  delete state.sessions[id];
243
246
  }
244
247
  writeMachineState(state);
248
+ const protectedWorktrees = [...new Set(desired.map((s) => s.dir).filter((d) => Boolean(d)))];
249
+ const buildCaches = manageBuildCaches({
250
+ budgetGb: me.machine?.cache_budget_gb ?? null,
251
+ floorPct: me.machine?.cache_floor_pct ?? null,
252
+ machineCaches: me.machine?.build_caches ?? [],
253
+ projects,
254
+ workdir,
255
+ protectedWorktrees,
256
+ });
257
+ for (const cache of buildCaches.caches) {
258
+ const protectedNote = cache.skipped_protected?.length ? `; retained protected: ${cache.skipped_protected.join(", ")}` : "";
259
+ if (cache.status === "cleaned")
260
+ log(`build cache cleaned ${cache.path} (${cache.volume}): removed ${(cache.removed_bytes / 1e6).toFixed(1)} MB${protectedNote}`);
261
+ else if (cache.status === "skipped_in_use")
262
+ log(`build cache skipped ${cache.path} (in use by ${cache.active_processes.join(", ")})${protectedNote}`);
263
+ else if (cache.status === "skipped_protected")
264
+ log(`build cache skipped ${cache.path} (protected subtrees retained: ${(cache.skipped_protected ?? []).join(", ")})`);
265
+ else if (cache.status === "error")
266
+ log(`build cache error ${cache.path}: ${cache.error}`);
267
+ }
268
+ for (const fault of buildCaches.faults) {
269
+ if (fault.kind === "inspection_incomplete")
270
+ log(`build cache fault on ${fault.volume}: ${fault.reason} (${fault.caches.join(", ")}; uninspected: ${fault.processes.join(", ")})`);
271
+ else
272
+ log(`build cache fault on ${fault.volume} (${fault.free_pct}% < ${fault.floor_pct}% floor): ${fault.caches.join(", ")} in use by ${fault.processes.join(", ")}`);
273
+ }
245
274
  const clones = refreshClones(workdir, [...new Set(desired.filter((s) => !s.dir && s.project && s.desired === "running").map((s) => s.project))], log);
275
+ const actualWorkdir = workdir ?? join(homedir(), "bschat");
276
+ const workSpace = volumeSpace(actualWorkdir, "workdir");
246
277
  const report = {
247
- ...machineFacts([...providerChecks]), workdir: workdir ?? join(homedir(), "bschat"), workdir_free_bytes: freeBytes(workdir ?? homedir()), clones,
278
+ ...machineFacts([...providerChecks]), workdir: actualWorkdir, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null, clones,
279
+ build_caches: buildCaches,
248
280
  // The daemon's own confirmation that it is holding turns back, and how many are still running.
249
281
  maintenance: maintenanceReport(drainingUntil(), out),
250
282
  };
@@ -262,7 +294,7 @@ export async function reconcile(m, log) {
262
294
  probedProjects.push(project.id);
263
295
  log(`${project.name}: probed ${capabilities[project.id].length} declared capabilities`);
264
296
  }
265
- await client.call("POST", "/machines/me/report", { report, sessions: out, capabilities });
297
+ await client.call("POST", "/machines/me/report", { report, report_interval_seconds: reportIntervalSeconds, sessions: out, capabilities });
266
298
  for (const projectId of probedProjects) {
267
299
  const declaration = projects.find((p) => p.id === projectId);
268
300
  lastCapabilityProbe.set(projectId, { at: Date.now(), signature: JSON.stringify(declaration.capabilities) });
@@ -425,14 +457,14 @@ export function errorText(s) {
425
457
  }
426
458
  }
427
459
  /** Whether the session has a turn running, its process, and a usage-limit pause still in force. */
428
- function turnFacts(agent, harness, thread) {
460
+ function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
429
461
  const ph = thread ? probeFor(harness, thread, agent).phase() : null;
430
462
  if (!thread || !ph || "missing" in ph)
431
- return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null };
463
+ return { turn: { running: false, since: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null };
432
464
  const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
433
465
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
434
466
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
435
- return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused, pause_started_at: paused ? ph.lastErrorAt : null };
467
+ return { turn: { running: ph.running, since: ph.running ? ph.startedAt : ph.lastEventAt }, process: ph.running ? turnProcess(thread, harness, undefined, agent) : null, paused_until: paused, pause_started_at: paused ? ph.lastErrorAt : null, turn_guard: busyTurnPause(readState(agent).turn_guard, turnCap, Date.now()) };
436
468
  }
437
469
  /** The harness process running a turn of this session (`codex exec resume <thread>`, `claude ... --resume <id>`), from ps. */
438
470
  export function turnProcess(thread, harness = "codex", psOutput, agent) {
@@ -545,10 +577,19 @@ function lastTurnLine(ref) {
545
577
  const lines = readFileSync(f, "utf8").split("\n").filter((l) => /b9s watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l));
546
578
  return lines.length ? lines[lines.length - 1].slice(0, 300) : null;
547
579
  }
548
- function freeBytes(path) {
580
+ /** Linux pressure stall information is optional; unsupported hosts report it as unknown. */
581
+ function ioPressure() {
582
+ if (platform() !== "linux")
583
+ return null;
549
584
  try {
550
- const st = statfsSync(existsSync(path) ? path : dirname(path));
551
- return st.bavail * st.bsize;
585
+ const content = readFileSync("/proc/pressure/io", "utf8");
586
+ const avg10 = (kind) => {
587
+ const line = content.split("\n").find((entry) => entry.startsWith(`${kind} `));
588
+ const match = line && /(?:^|\s)avg10=([0-9]+(?:\.[0-9]+)?)(?:\s|$)/.exec(line);
589
+ return match ? Number(match[1]) : null;
590
+ };
591
+ const some = avg10("some"), full = avg10("full");
592
+ return some === null && full === null ? null : { some_avg10: some, full_avg10: full };
552
593
  }
553
594
  catch {
554
595
  return null;
@@ -573,6 +614,61 @@ export function codexSandbox(force = false, path = process.env.PATH ?? "") {
573
614
  sandboxCache = { at: Date.now(), result, path };
574
615
  return result;
575
616
  }
617
+ const AGY_SANDBOX_PROBE_MS = 10 * 60_000;
618
+ const AGY_SANDBOX_PROBE_MODEL = "gemini-4-hydrogen-low";
619
+ const AGY_SANDBOX_PROBE_RESPONSE = "B9S_SANDBOX_OK";
620
+ let agySandboxCache = null;
621
+ /** Runs one cached no-op turn through Antigravity's real workspace-write terminal sandbox. */
622
+ export function antigravitySandbox(force = false, path = process.env.PATH ?? "") {
623
+ if (!force && agySandboxCache && agySandboxCache.path === path && Date.now() - agySandboxCache.at < AGY_SANDBOX_PROBE_MS)
624
+ return agySandboxCache.result;
625
+ const work = mkdtempSync(join(tmpdir(), "b9s-agy-sandbox-probe-"));
626
+ let result;
627
+ try {
628
+ const marker = join(work, ".b9s-sandbox-probe");
629
+ const quotedMarker = `'${marker.replace(/'/g, `'\\''`)}'`;
630
+ const prompt = `Use your terminal tool once to run exactly: printf '${AGY_SANDBOX_PROBE_RESPONSE}' > ${quotedMarker}. Then reply with exactly ${AGY_SANDBOX_PROBE_RESPONSE}. Do not call any other tool.`;
631
+ const settings = ["--sandbox", "--settings", JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: [] } })];
632
+ const r = spawnSync("agy", antigravityTurnArgs(prompt, AGY_SANDBOX_PROBE_MODEL, undefined, 45, settings), {
633
+ encoding: "utf8", timeout: 60_000, maxBuffer: 1024 * 1024, cwd: work, env: { ...process.env, PATH: path },
634
+ });
635
+ const parsed = parseAntigravityJson(r.stdout ?? "");
636
+ let wroteMarker = false;
637
+ try {
638
+ wroteMarker = readFileSync(marker, "utf8") === AGY_SANDBOX_PROBE_RESPONSE;
639
+ }
640
+ catch { /* a missing marker means the sandbox command did not run */ }
641
+ result = r.status === 0 && parsed?.status === "SUCCESS" && parsed.response?.trim() === AGY_SANDBOX_PROBE_RESPONSE && wroteMarker
642
+ ? { ok: true, error: null }
643
+ : { ok: false, error: r.status !== 0 ? `agy sandbox no-op failed (exit ${r.status ?? "unknown"})` : "agy sandbox no-op did not return the required successful result" };
644
+ }
645
+ finally {
646
+ rmSync(work, { recursive: true, force: true });
647
+ }
648
+ agySandboxCache = { at: Date.now(), result, path };
649
+ return result;
650
+ }
651
+ function antigravityLoginFacts(path) {
652
+ const env = { ...process.env, PATH: path };
653
+ const version = spawnSync("agy", ["--version"], { encoding: "utf8", timeout: 15_000, env });
654
+ if (version.status !== 0)
655
+ return { available: false, version: null, logged_in: false, error: "agy is not installed or --version failed" };
656
+ const models = spawnSync("agy", ["models"], { encoding: "utf8", timeout: 20_000, env, maxBuffer: 1024 * 1024 });
657
+ return {
658
+ available: true,
659
+ version: version.stdout.trim().slice(0, 100) || null,
660
+ logged_in: models.status === 0,
661
+ error: models.status === 0 ? null : "agy models did not succeed; log in interactively with agy on this machine",
662
+ };
663
+ }
664
+ /** Machine facts used by placement; the daemon probes login cheaply and caches the sandbox turn. */
665
+ export function antigravityFacts(path = process.env.PATH ?? "") {
666
+ const facts = antigravityLoginFacts(path);
667
+ return {
668
+ ...facts,
669
+ sandbox: facts.logged_in ? antigravitySandbox(false, path) : null,
670
+ };
671
+ }
576
672
  /** Memory a new process could use: Linux's MemAvailable (free alone undercounts the page cache), else free. */
577
673
  function memAvailable() {
578
674
  if (platform() === "linux") {
@@ -606,30 +702,28 @@ export function machineFacts(providersInUse = ["anthropic"]) {
606
702
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env });
607
703
  const login = codex.status === 0 ? spawnSync("codex", ["login", "status"], { encoding: "utf8", env }) : null;
608
704
  const dsh = dshFacts(platform(), path);
609
- let diskFree = null;
610
- try {
611
- const st = statfsSync(homedir());
612
- diskFree = st.bavail * st.bsize;
613
- }
614
- catch {
615
- diskFree = null;
616
- }
705
+ const antigravity = antigravityFacts(path);
706
+ const homeSpace = volumeSpace(homedir(), "home");
617
707
  const req = "/etc/codex/requirements.toml";
618
708
  const claude = claudeReport(path, providersInUse);
709
+ const bootedAt = bootTimeMs();
619
710
  return {
620
711
  os: platform(), arch: arch(), hostname: hostname(), user: userInfo().username, cpus: cpus().length, mem_total_bytes: totalmem(),
621
712
  load: loadavg().map((x) => Math.round(x * 100) / 100), mem_available_bytes: memAvailable(),
622
713
  // When this machine last booted: the server ends a maintenance window once the machine is back.
623
- booted_at: new Date(Math.floor((Date.now() - uptime() * 1000) / 60_000) * 60_000).toISOString(),
714
+ booted_at: bootedAt === null ? null : new Date(Math.floor(bootedAt / 60_000) * 60_000).toISOString(),
624
715
  daemon_path: path,
625
716
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
626
717
  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), account_fingerprint: codexAccountFingerprint(), sandbox: codexSandbox(false, path) } : null,
627
718
  "claude-code": claude,
628
719
  claude_code: claude,
629
720
  dsh,
721
+ antigravity,
630
722
  managed_hooks: existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8")),
631
723
  linger: platform() === "linux" ? lingerEnabled() : null,
632
- disk_free_bytes: diskFree,
724
+ disk_free_bytes: homeSpace?.freeBytes ?? null,
725
+ disk_total_bytes: homeSpace?.totalBytes ?? null,
726
+ io_pressure: ioPressure(),
633
727
  at: new Date().toISOString(),
634
728
  };
635
729
  }
@@ -669,6 +763,12 @@ export function prepare(opts = {}) {
669
763
  steps.push(dsh.available
670
764
  ? { step: "dsh", result: "ok", detail: `${dsh.version}, ${dsh.path}` }
671
765
  : { step: "dsh", result: platform() === "linux" ? "skipped" : "failed", detail: dsh.error ?? "DeepSeek Harness dsh CLI is unavailable" });
766
+ const agy = antigravityLoginFacts(daemonPath);
767
+ steps.push(!agy.available
768
+ ? { step: "antigravity login", result: "skipped", detail: "agy is not available on the daemon PATH; install Antigravity and log in interactively before using Antigravity pools" }
769
+ : agy.logged_in
770
+ ? { step: "antigravity login", result: "ok", detail: `${agy.version ?? "agy"}; agy models succeeded` }
771
+ : { step: "antigravity login", result: "failed", detail: `${agy.version ?? "agy"}; agy models did not succeed; log in interactively with agy on this machine` });
672
772
  const codex = spawnSync("codex", ["--version"], { encoding: "utf8", env: daemonEnv });
673
773
  if (codex.status !== 0)
674
774
  steps.push({ step: "codex", result: "failed", detail: "codex is not on PATH; install the Codex CLI (npm i -g @openai/codex) and log in (codex login --device-auth)" });
@@ -794,10 +894,12 @@ export async function machine(p, out) {
794
894
  }
795
895
  if (sub === "run") {
796
896
  const interval = Number(str(p.flags, "interval") ?? "30");
897
+ if (!Number.isFinite(interval) || interval < 1 || interval > 3600)
898
+ throw new CliError("usage", "--interval must be from 1 to 3600 seconds");
797
899
  log(`running every ${interval}s against ${m.url}`);
798
900
  for (;;) {
799
901
  try {
800
- await reconcile(m, log);
902
+ await reconcile(m, log, interval);
801
903
  }
802
904
  catch (e) {
803
905
  log(`pass failed: ${e.message}`);