benignswarm 0.12.106 → 0.12.108

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.
@@ -0,0 +1,26 @@
1
+ import { str } from "../args.js";
2
+ import { agentRef, loadAgent, resolveAgentName } from "../config.js";
3
+ import { CliError } from "../errors.js";
4
+ import { boundSessions, bindSession } from "../sessions.js";
5
+ /**
6
+ * b9s claude bind <session-id> [--as <agent>] this Claude Code session is you: its hook delivers to you (replaces your earlier session)
7
+ * b9s claude sessions the Claude Code sessions bound on this machine
8
+ */
9
+ export async function claude(p, out) {
10
+ const sub = p.positionals[1];
11
+ if (sub === "bind") {
12
+ const id = p.positionals[2];
13
+ if (!id)
14
+ throw new CliError("usage", "claude bind <session-id> [--as <agent>] (the session id is in the SessionStart notice a session that is not bound prints, and in the hook payload's session_id)");
15
+ const ref = agentRef(loadAgent(resolveAgentName(str(p.flags, "as"))));
16
+ bindSession("claude-code", id, ref);
17
+ out.print(`Claude Code session ${id} is ${ref}: its hook now delivers your mentions and assignments there, and no other session of yours gets them.`, { session: id, agent: ref });
18
+ return;
19
+ }
20
+ if (sub === "sessions") {
21
+ const bound = boundSessions("claude-code");
22
+ out.print(bound.length ? bound.map((b) => `${b.id} -> ${b.agent}${b.auto ? " (bound automatically)" : ""}`).join("\n") : "No Claude Code session is bound on this machine.", { sessions: bound });
23
+ return;
24
+ }
25
+ throw new CliError("usage", "claude bind <session-id> [--as <agent>] | claude sessions");
26
+ }
@@ -285,12 +285,14 @@ export async function harnessStart(p, out, harness) {
285
285
  }
286
286
  if (!session)
287
287
  throw new CliError("harness_failed", "the harness did not provide a session id");
288
- // 3. Bind it, so the hooks in that session deliver to this agent and nobody else. Claude Code's
289
- // hook knows the agent from BSCHAT_AGENT (the watcher sets it for every turn), so it needs no map.
288
+ // 3. Bind it, so the hooks in that session deliver to this agent and nobody else. The Claude Code hook
289
+ // takes the agent from BSCHAT_AGENT (the watcher sets it for every turn) and the session id from the map.
290
290
  if (harness === "codex")
291
291
  bindSession("codex", session, ref);
292
292
  if (harness === "antigravity")
293
293
  bindSession("antigravity", session, ref);
294
+ if (harness === "claude-code")
295
+ bindSession("claude-code", session, ref);
294
296
  const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "antigravity" ? antigravityLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
295
297
  writeState(ref, { ...readState(ref), harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(model ? { model } : {}), ...(harness === "claude-code" ? { provider } : {}), ...(initialPid ? { initial_pid: initialPid } : {}) } });
296
298
  // A session adopted here may end in a usage-limit error from the machine it came from, written in
@@ -1,12 +1,13 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { str } from "../args.js";
3
3
  import { Client } from "../client.js";
4
- import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
4
+ import { ACCOUNT_SCOPE, loadAgent, resolveAgentName, resolveModel } from "../config.js";
5
+ import { findIdentityFile, readIdentityFile } from "../harness.js";
5
6
  import { heartbeatNow } from "../heartbeat.js";
6
7
  import { fmtMessage } from "../output.js";
7
8
  import { readState, writeState } from "../state.js";
8
9
  import { goalFromClaudeTranscript, modelFromClaudeTranscript } from "../model.js";
9
- import { conversationAgent, sessionAgent, syncFromWatchers } from "../sessions.js";
10
+ import { bindSession, conversationAgent, sessionAgent, sessionsOf, syncFromWatchers } from "../sessions.js";
10
11
  import { fetchRecoveryBrief, formatOutcomeMeasures, formatRecoveryBrief, outcomeMeasureSnapshot, recoveryBriefUnavailableText } from "../brief.js";
11
12
  import { changedNotices, commandNoticeWarning, normalizeShellCommand } from "../notices.js";
12
13
  const HEARTBEAT_MS = 60_000;
@@ -387,7 +388,36 @@ export async function reportDelivery(name, text, kinds, source = "hook") {
387
388
  * context, and nothing when there is nothing new. Always exits 0: a hook that fails must never
388
389
  * break the agent's session. Problems go to stderr.
389
390
  */
390
- export async function hook(p) {
391
+ /**
392
+ * Whether this Claude Code session is the agent's own. The hook's identity comes from
393
+ * BSCHAT_AGENT or the repo's identity file, which every session in the checkout shares, so the
394
+ * session id decides: only the session bound to the agent (b9s claude bind, b9s start) gets its
395
+ * messages and moves its cursors. The first SessionStart while the identity file names this agent
396
+ * and no session is bound is bound automatically, so a single-session setup needs no step.
397
+ */
398
+ export function claudeSessionBound(ref, sid, cwd, allowAutoBind = false) {
399
+ if (!sid)
400
+ return false;
401
+ const owner = sessionAgent("claude-code", sid);
402
+ if (owner === ref)
403
+ return true;
404
+ // Never let an identity-file auto-bind overwrite another agent's explicit/session binding.
405
+ if (owner !== null)
406
+ return false;
407
+ if (!allowAutoBind)
408
+ return false;
409
+ if (sessionsOf("claude-code", ref).length > 0)
410
+ return false;
411
+ const file = findIdentityFile(cwd);
412
+ if (!file)
413
+ return false;
414
+ const entry = readIdentityFile(file).agents["claude-code"];
415
+ if (!entry || `${entry.project ?? ACCOUNT_SCOPE}/${entry.name}` !== ref)
416
+ return false;
417
+ bindSession("claude-code", sid, ref, { auto: true });
418
+ return true;
419
+ }
420
+ export async function hook(p, payload) {
391
421
  const harness = p.positionals[1] ?? "plain";
392
422
  if (harness === "antigravity")
393
423
  return antigravityHook(p);
@@ -401,8 +431,26 @@ export async function hook(p) {
401
431
  catch {
402
432
  return; // not configured here, or ambiguous: silent by design; the agent's own commands will say so
403
433
  }
434
+ const input = payload === undefined ? readStdinJson() : payload;
435
+ if (harness === "claude-code") {
436
+ const sid = typeof input?.session_id === "string" ? input.session_id : null;
437
+ let bound = false;
438
+ try {
439
+ bound = claudeSessionBound(name, sid, typeof input?.cwd === "string" ? input.cwd : process.cwd(), event === "SessionStart");
440
+ }
441
+ catch (e) {
442
+ process.stderr.write(`b9s: could not check this session's binding: ${e.message}\n`);
443
+ }
444
+ if (!bound) {
445
+ // Nothing of the agent's goes to a session that is not its own, and no cursor or delivery state moves.
446
+ if (event === "SessionStart") {
447
+ const how = sid ? `b9s claude bind ${sid} --as ${name}` : "b9s claude bind <session id> --as " + name;
448
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: `[b9s] This Claude Code session is not bound to ${name}, so none of that agent's messages are delivered here. Only if this session is ${name}, bind it: ${how}` } }) + "\n");
449
+ }
450
+ return;
451
+ }
452
+ }
404
453
  // Model observation: hook input (SessionStart `model`, PostModelSwitch `to_model`) or the transcript tail.
405
- const input = readStdinJson();
406
454
  if (input) {
407
455
  const state = readState(name);
408
456
  const observed = (typeof input.to_model === "string" && input.to_model) || (typeof input.model === "string" && input.model) || (typeof input.transcript_path === "string" ? modelFromClaudeTranscript(input.transcript_path) : null);
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import { boundSessions } from "../sessions.js";
2
3
  import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statfsSync } from "node:fs";
3
4
  import { basename, delimiter, join } from "node:path";
4
5
  import { homedir, platform } from "node:os";
@@ -127,6 +128,13 @@ function doctorEnvironmentChecks(pathValue, writableRoots) {
127
128
  * PATH, npx caches, this repo's hook and instructions, and each watcher (plist versus
128
129
  * what launchd is actually running). Read-only; prints the fix for each problem.
129
130
  */
131
+ /** Doctor lines for the Claude Code sessions the hook delivers to; any other session in a checkout gets nothing. */
132
+ export function claudeSessionChecks() {
133
+ const bound = boundSessions("claude-code");
134
+ if (!bound.length)
135
+ return [{ ok: true, what: "no Claude Code session is bound: the first session of a checkout whose identity file names its agent binds itself" }];
136
+ return bound.map((b) => ({ ok: true, what: `Claude Code session ${b.id} is bound to ${b.agent}${b.auto ? " (bound automatically)" : ""}` }));
137
+ }
130
138
  export async function doctor(_p, out) {
131
139
  const checks = [];
132
140
  const rec = readInstall();
@@ -192,6 +200,7 @@ export async function doctor(_p, out) {
192
200
  checks.push({ ok: good, what: `Claude Code hook in ${sp}: ${c}`, fix: good ? undefined : "b9s setup --as <your agent> (rewrites the hook to the recorded install)" });
193
201
  }
194
202
  }
203
+ checks.push(...claudeSessionChecks());
195
204
  for (const f of ["AGENTS.md", "GEMINI.md", join(".agents", "rules", "bschat.md")]) {
196
205
  const fp = join(root, f);
197
206
  if (existsSync(fp) && readFileSync(fp, "utf8").includes("npx -y benignswarm"))
@@ -1823,14 +1823,15 @@ export function antigravityFacts(path = process.env.PATH ?? "", b9sBin = readIns
1823
1823
  sandbox: facts.logged_in ? antigravitySandbox(false, path, b9sBin) : null,
1824
1824
  };
1825
1825
  }
1826
- /** Memory a new process could use: Linux's MemAvailable (free alone undercounts the page cache), else free. */
1826
+ /** Linux's MemAvailable; Darwin is supplied by vm_stat, never approximated by free pages. */
1827
1827
  function memAvailable() {
1828
1828
  if (platform() === "linux") {
1829
1829
  const m = /^MemAvailable:\s+(\d+) kB/m.exec(readFileSync("/proc/meminfo", "utf8"));
1830
1830
  if (m)
1831
1831
  return Number(m[1]) * 1024;
1832
+ return freemem();
1832
1833
  }
1833
- return freemem();
1834
+ return platform() === "darwin" ? null : freemem();
1834
1835
  }
1835
1836
  /** Claude Code's version, login and sandbox; the sandbox check runs at most every 10 min. */
1836
1837
  let claudeSandboxCache = null;
@@ -1872,9 +1873,17 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
1872
1873
  catch {
1873
1874
  return null;
1874
1875
  } };
1875
- const pageSize = platform() === "linux" ? parsePageSize(spawnSync("getconf", ["PAGESIZE"], { encoding: "utf8", timeout: 2_000 }).stdout ?? "") : null;
1876
- const macSwap = platform() === "darwin" ? spawnSync("sysctl", ["-n", "vm.swapusage"], { encoding: "utf8", timeout: 2_000 }).stdout ?? null : null;
1877
- const telemetry = machineResourceTelemetry(platform(), readTelemetryFile, pageSize, macSwap);
1876
+ const hostPlatform = platform();
1877
+ const isDarwin = hostPlatform === "darwin";
1878
+ const pageSizeResult = hostPlatform === "linux"
1879
+ ? spawnSync("getconf", ["PAGESIZE"], { encoding: "utf8", timeout: 2_000 })
1880
+ : isDarwin ? spawnSync("sysctl", ["-n", "hw.pagesize"], { encoding: "utf8", timeout: 2_000 }) : null;
1881
+ const pageSize = pageSizeResult?.status === 0 ? parsePageSize(pageSizeResult.stdout ?? "") : null;
1882
+ const macSwapResult = isDarwin ? spawnSync("sysctl", ["-n", "vm.swapusage"], { encoding: "utf8", timeout: 2_000 }) : null;
1883
+ const macVmStatResult = isDarwin ? spawnSync("vm_stat", [], { encoding: "utf8", timeout: 2_000 }) : null;
1884
+ const macSwap = macSwapResult?.status === 0 ? macSwapResult.stdout ?? null : null;
1885
+ const macVmStat = macVmStatResult?.status === 0 ? macVmStatResult.stdout ?? null : null;
1886
+ const telemetry = machineResourceTelemetry(hostPlatform, readTelemetryFile, pageSize, macSwap, macVmStat);
1878
1887
  const telemetryAvailability = telemetry.metric_availability;
1879
1888
  const volumeFloorPct = diskFloorPct;
1880
1889
  const req = "/etc/codex/requirements.toml";
package/dist/help.js CHANGED
@@ -31,6 +31,7 @@ Environment problems: agents report bounded, redacted observations with b9s envi
31
31
 
32
32
  Work-unit open, start, submit and close endpoints accept context fill and compaction metadata on lifecycle events. Report explicit unknown reasons when unavailable; never send prompt or response text as context. Context aggregation is grouped by the event owner and its stamped model/effort. Context policies (keep | compact | clear | agent-decides) resolve unit > role > project > system default keep, freeze on assignment/open, audit settings and action-metadata decisions via GET/PUT /projects/:p/context-policy, POST /projects/:p/work-units/:n/context-policy, and POST /projects/:p/work-units/:n/context-policy/decision, and fail closed until an assigner or operator updates a blocked unit. See packages/skill/references/api.md for field validation and response shapes.
33
33
  GET /projects/:p/context-policy/comparison reports descriptive project-scoped policy aggregates by build/review mode, tag, and exact event-stamped class. Reviewer event counts are separate from replay-cluster uncertainty; turn token usage stays unknown. Clear-cohort units need their own server-verified clear event and a later start by the same actor. Results are not causal or paired; the console view is WU #299.
34
+ Test results expose GET /projects/:p/test-flaky-signals?target_key=<encoded> and GET /projects/:p/frontier-progress?target_key=<encoded>&period_days=30. These are descriptive, target-specific views; mixed outcomes never waive failures or change expectations. See packages/skill/references/api.md.
34
35
  GET /projects/:p/work-units/:n/cost reports recorded worker, review and rework session tokens across superseded units; GET /projects/:p/stats includes finished-unit model costs. Incomplete or overlapping windows remain explicit, and token-weight prices are estimates. GET /projects/:p/agents/me/usage-cursor gives the caller's session boundary. See packages/skill/references/api.md.
35
36
  Build dispatch checks role qualifications, capabilities, holds, reservations and operator-only required_class first, then ranks eligible workers by routing_policy weights, build quality guardrail, weakest-tag tie-break and build exploration budget, falling back when the preferred class is busy and recording route_decision / dispatch_reasons on units and events. Operators set/clear hard required_class with an audited reason via POST /projects/:p/work-units/:n/required-class (or tag definitions) and inspect cleared legacy min_tier rows via GET /projects/:p/routing/tier-migration (never guessing class mappings). Console routing controls are WU #244; CLI routing view/controls are WU #242.
36
37
  Review routing ranks only independent qualified reviewers (excluding owner, prior builders, same-worktree occupants, and forbidden_dependent_roles), preserves trial/expert/mandatory_reviewer blockers, supports paired comparisons and head-to-head verdicts (POST /projects/:p/work-units/:n/compare, closing non-selected units as compared), and exposes GET /projects/:p/review-routing. Console routing controls are WU #244; CLI routing view/controls are WU #242. See packages/skill/references/api.md for field validation and response shapes.
@@ -239,6 +240,8 @@ Machine placement shares capacity across the account's projects: session seats a
239
240
  b9s checkpoint "<title>" --body "..." a resume note without retiring: what you are doing, open threads, next steps;
240
241
  your next session (after a move to another machine) reads it first
241
242
  b9s antigravity bind <conversation-id> | sync which Antigravity conversation is you, for its hook (watchers bind theirs)
243
+ b9s claude bind <session-id> | sessions which Claude Code session is you, for its hook (b9s start binds its own; the first session of a
244
+ single-session checkout binds itself; any other session gets nothing until you bind it)
242
245
  b9s wake ack [<n>] acknowledge your watcher's wake-up #n first thing (no n: the one pending here)
243
246
  Liveness: the watcher reports harness activity (Codex rollout / Antigravity conversation
244
247
  found from the session id in --exec, or --activity <file-or-dir>) so you are not shown
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ import { goal } from "./commands/goal.js";
12
12
  import { wake } from "./commands/wake.js";
13
13
  import { turn } from "./commands/turn.js";
14
14
  import { antigravity } from "./commands/antigravity.js";
15
+ import { claude } from "./commands/claude.js";
15
16
  import { codex, unpause } from "./commands/codex.js";
16
17
  import { harnessStart } from "./commands/codex-start.js";
17
18
  import { turnHarness } from "./harnesses.js";
@@ -76,6 +77,7 @@ const COMMANDS = {
76
77
  wake,
77
78
  turn,
78
79
  antigravity,
80
+ claude,
79
81
  codex,
80
82
  start: async (p, out) => {
81
83
  const h = str(p.flags, "harness");
@@ -138,7 +140,7 @@ async function main(argv) {
138
140
  const codexSubcommand = cmd === "codex" ? p.positionals[1] : undefined;
139
141
  const antigravitySubcommand = cmd === "antigravity" ? p.positionals[1] : undefined;
140
142
  // These sync/setup subcommands only inspect or configure local harness session state.
141
- const localHarnessDispatch = (cmd === "codex" && ["hooks", "sync", "start"].includes(codexSubcommand ?? "")) || (cmd === "antigravity" && antigravitySubcommand === "sync");
143
+ const localHarnessDispatch = (cmd === "codex" && ["hooks", "sync", "start"].includes(codexSubcommand ?? "")) || (cmd === "antigravity" && antigravitySubcommand === "sync") || (cmd === "claude" && p.positionals[1] === "sessions");
142
144
  const noticePreflightExempt = NOTICE_PREFLIGHT_EXEMPT_COMMANDS.has(cmd) || localHarnessDispatch;
143
145
  if (!noticePreflightExempt) {
144
146
  const agentName = resolveAgentName(str(p.flags, "as"));
@@ -1,4 +1,4 @@
1
- import { readdirSync, readlinkSync, realpathSync, readFileSync } from "node:fs";
1
+ import { readdirSync, readlinkSync, realpathSync, readFileSync, statSync } from "node:fs";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { isAbsolute, relative, sep } from "node:path";
4
4
  const run = (command, args) => {
@@ -269,6 +269,57 @@ function linuxListenersForPid(pid) {
269
269
  }
270
270
  return [...new Set(out)];
271
271
  }
272
+ function readLinuxProcessOrigin(pid, ppid) {
273
+ let parentUid = null;
274
+ let cgroup = null;
275
+ try {
276
+ parentUid = statSync(`/proc/${ppid}`).uid;
277
+ }
278
+ catch { /* unknown stays unknown */ }
279
+ try {
280
+ cgroup = readFileSync(`/proc/${pid}/cgroup`, "utf8").trim();
281
+ }
282
+ catch { /* unknown stays unknown */ }
283
+ return { parentPid: ppid, parentUid, cgroup };
284
+ }
285
+ /** True when the process no longer runs: /proc/<pid> is gone, or its state is Z (zombie) or X (dead). */
286
+ function linuxProcessEnded(pid) {
287
+ let stat;
288
+ try {
289
+ stat = readFileSync(`/proc/${pid}/stat`, "utf8");
290
+ }
291
+ catch (error) {
292
+ return isDisappearedProcess(error);
293
+ }
294
+ const state = stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3);
295
+ return state === "Z" || state === "X";
296
+ }
297
+ /** User services a host runs for its user that are allowed to stay uninspected. Named, never by pattern. */
298
+ const UNINSPECTABLE_USER_SERVICES = new Set(["gpg-agent.service", "ssh-agent.service"]);
299
+ /**
300
+ * Why an uninspectable same-user process may be left out of a worktree scan, or null when it must fail
301
+ * the scan. The operator's rule (WU #472, 2026-11-17) allows exactly three exclusions:
302
+ * - a child of a root-owned process other than PID 1: login and session leaders (sshd-session).
303
+ * - a member of the user manager's init.scope: systemd --user and sd-pam.
304
+ * - a member of a named user service in UNINSPECTABLE_USER_SERVICES.
305
+ * Linux cannot prove where a non-dumpable process works, so these are a policy, not a proof. Accepted
306
+ * residual risk: a root-owned supervisor or subreaper that adopts or launches same-user work inside a
307
+ * checkout would pass the first rule; BenignSwarm hosts run no such supervisor for agent work.
308
+ * Unknown facts, PID 1 parents, transient run-* units and org.benignswarm.* units all return null.
309
+ */
310
+ export function uninspectableExclusion(o) {
311
+ if (o.parentUid === 0 && o.parentPid > 1)
312
+ return "child of a root-owned daemon (login session leader)";
313
+ const unified = o.cgroup?.split("\n").find((l) => l.startsWith("0::"))?.slice(3) ?? null;
314
+ if (!unified)
315
+ return null;
316
+ if (/\/user@\d+\.service\/init\.scope$/.test(unified))
317
+ return "the user's systemd manager";
318
+ const unit = /\/user@\d+\.service\/app\.slice\/([^/]+\.service)$/.exec(unified)?.[1];
319
+ if (unit && UNINSPECTABLE_USER_SERVICES.has(unit))
320
+ return `user service ${unit}`;
321
+ return null;
322
+ }
272
323
  function readLinuxProcessPaths(rows, worktree) {
273
324
  const cwd = new Map();
274
325
  const listeners = new Map();
@@ -278,8 +329,21 @@ function readLinuxProcessPaths(rows, worktree) {
278
329
  cwd.set(row.pid, readlinkSync(`/proc/${row.pid}/cwd`));
279
330
  }
280
331
  catch (error) {
281
- if (!isDisappearedProcess(error))
282
- throw new Error(`cannot inspect working directory for process ${row.pid}: ${error.message}`);
332
+ if (isDisappearedProcess(error))
333
+ continue;
334
+ // The rows are this user's own processes (ps -u). The kernel denies /proc/<pid>/cwd (EACCES) for a
335
+ // non-dumpable process even to its own user. Non-dumpable is a setting any process may take, so it
336
+ // proves nothing about where the process works. Only the exclusions in uninspectableExclusion (the
337
+ // operator's rule) are left out; any other uninspectable process fails the scan (WU #472).
338
+ if (error.code === "EACCES") {
339
+ const excluded = uninspectableExclusion(readLinuxProcessOrigin(row.pid, row.parent_pid));
340
+ if (excluded)
341
+ continue;
342
+ // A process that exited while being scanned (gone, or a zombie awaiting its parent) is not working anywhere.
343
+ if (linuxProcessEnded(row.pid))
344
+ continue;
345
+ }
346
+ throw new Error(`cannot inspect working directory for process ${row.pid}: ${error.message}`);
283
347
  }
284
348
  }
285
349
  for (const row of rows) {
@@ -298,7 +362,13 @@ export function scanWorktreeProcesses(worktree, scope, runner = run, sampledAt =
298
362
  const uid = process.getuid?.();
299
363
  if (uid === undefined)
300
364
  throw new Error(`host process inspection is unsupported on ${process.platform}`);
301
- const ps = runner("ps", ["-U", String(uid), "-ww", "-axo", "pid=,ppid=,lstart=,command="]);
365
+ // Only this user's processes. On Linux (procps) "-U uid -ax" is a union that lists every process on the
366
+ // host, and reading another user's /proc/<pid>/cwd fails with EACCES, which made every scan throw and
367
+ // every stopped session's turn "unknown" (WU #472); "-u uid" alone selects by effective user there.
368
+ // BSD ps on macOS needs -ax for processes without a terminal, and -U already restricts it to the user.
369
+ const ps = runner("ps", process.platform === "linux"
370
+ ? ["-u", String(uid), "-ww", "-o", "pid=,ppid=,lstart=,command="]
371
+ : ["-U", String(uid), "-ww", "-axo", "pid=,ppid=,lstart=,command="]);
302
372
  if (ps.status !== 0)
303
373
  throw new Error(`could not inspect the host process table: ${ps.stderr.trim() || `ps exited ${ps.status}`}`);
304
374
  const rows = parsePsProcessRows(ps.stdout);
@@ -65,6 +65,31 @@ export function parseMacSwapUsage(content) {
65
65
  const totalBytes = field("total"), usedBytes = field("used");
66
66
  return totalBytes !== null && usedBytes !== null && usedBytes <= totalBytes ? { total_bytes: totalBytes, used_bytes: usedBytes } : null;
67
67
  }
68
+ /** Parse macOS `vm_stat` page counts and cumulative swap counters. */
69
+ export function parseMacVmStat(content, pageSizeBytes) {
70
+ const pages = (label) => {
71
+ const match = new RegExp(`^${label}:\\s+(\\d+)\\.?\\s*$`, "m").exec(content);
72
+ if (!match)
73
+ return null;
74
+ const count = Number(match[1]);
75
+ return Number.isSafeInteger(count) ? count : null;
76
+ };
77
+ const toBytes = (count) => {
78
+ if (count === null || pageSizeBytes === null || !Number.isSafeInteger(pageSizeBytes) || pageSizeBytes < 1)
79
+ return null;
80
+ const bytes = count * pageSizeBytes;
81
+ return Number.isSafeInteger(bytes) ? bytes : null;
82
+ };
83
+ const reclaimable = ["Pages free", "Pages inactive", "Pages speculative", "Pages purgeable"].map(pages);
84
+ const availablePages = reclaimable.every((count) => count !== null)
85
+ ? reclaimable.reduce((sum, count) => sum + count, 0)
86
+ : null;
87
+ return {
88
+ available_bytes: toBytes(availablePages),
89
+ swap_in_bytes_total: toBytes(pages("Swapins")),
90
+ swap_out_bytes_total: toBytes(pages("Swapouts")),
91
+ };
92
+ }
68
93
  function flattenPressure(report) {
69
94
  return {
70
95
  some_avg10: report?.some?.avg10 ?? null,
@@ -78,12 +103,13 @@ function flattenPressure(report) {
78
103
  };
79
104
  }
80
105
  /** Normalize supported host readings into the daemon report contract. */
81
- export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes, macSwapUsage = null) {
106
+ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes, macSwapUsage = null, macVmStat = null) {
82
107
  const linux = hostPlatform === "linux";
83
108
  const darwin = hostPlatform === "darwin";
84
109
  const memoryText = linux ? readText("/proc/meminfo") : null;
85
110
  const linuxMemory = memoryText ? parseLinuxMemory(memoryText) : null;
86
111
  const macSwap = darwin && macSwapUsage !== null ? parseMacSwapUsage(macSwapUsage) : null;
112
+ const macMemory = darwin && macVmStat !== null ? parseMacVmStat(macVmStat, pageSizeBytes) : null;
87
113
  const vmstat = linux ? parseLinuxSwapCounters(readText("/proc/vmstat") ?? "", pageSizeBytes) : { in_bytes_total: null, out_bytes_total: null };
88
114
  const pressure = (kind) => linux ? parsePressureStall(readText(`/proc/pressure/${kind}`) ?? "") : null;
89
115
  const memoryPressure = pressure("memory");
@@ -93,12 +119,17 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
93
119
  const swapUsed = linuxMemory?.swap_used_bytes ?? macSwap?.used_bytes ?? null;
94
120
  const swapAvailable = swapTotal !== null && swapUsed !== null;
95
121
  const swapIoAvailable = linux && vmstat.in_bytes_total !== null && vmstat.out_bytes_total !== null;
122
+ const macSwapIoAvailable = darwin && macMemory?.swap_in_bytes_total !== null && macMemory?.swap_in_bytes_total !== undefined && macMemory?.swap_out_bytes_total !== null && macMemory?.swap_out_bytes_total !== undefined;
96
123
  return {
97
124
  ...(linux ? {
98
125
  mem_total_bytes: linuxMemory?.total_bytes ?? null,
99
126
  mem_available_bytes: linuxMemory?.available_bytes ?? null,
100
127
  swap_in_bytes_total: vmstat.in_bytes_total,
101
128
  swap_out_bytes_total: vmstat.out_bytes_total,
129
+ } : darwin ? {
130
+ mem_available_bytes: macMemory?.available_bytes ?? null,
131
+ swap_in_bytes_total: macMemory?.swap_in_bytes_total ?? null,
132
+ swap_out_bytes_total: macMemory?.swap_out_bytes_total ?? null,
102
133
  } : {
103
134
  swap_in_bytes_total: null,
104
135
  swap_out_bytes_total: null,
@@ -109,10 +140,12 @@ export function machineResourceTelemetry(hostPlatform, readText, pageSizeBytes,
109
140
  cpu_pressure: flattenPressure(cpuPressure),
110
141
  io_pressure: flattenPressure(ioPressure),
111
142
  metric_availability: {
112
- memory: linux ? (typeof linuxMemory?.total_bytes === "number" && typeof linuxMemory?.available_bytes === "number" ? "available" : "unavailable") : "available",
143
+ memory: linux ? (typeof linuxMemory?.total_bytes === "number" && typeof linuxMemory?.available_bytes === "number" ? "available" : "unavailable") : darwin ? (typeof macMemory?.available_bytes === "number" ? "available" : "unavailable") : "unsupported",
144
+ ...(darwin ? { memory_source: "vm_stat_reclaimable_pages" } : {}),
113
145
  load: linux || darwin ? "available" : "unsupported",
114
146
  swap: swapAvailable ? "available" : "unavailable",
115
- swap_io: swapIoAvailable ? "available" : linux ? "unavailable" : "unsupported",
147
+ ...(darwin ? { swap_io_source: "vm_stat_cumulative_counters" } : {}),
148
+ swap_io: swapIoAvailable || macSwapIoAvailable ? "available" : linux || darwin ? "unavailable" : "unsupported",
116
149
  memory_pressure: memoryPressure ? "available" : linux ? "unsupported" : "unsupported",
117
150
  cpu_pressure: cpuPressure ? "available" : linux ? "unsupported" : "unsupported",
118
151
  io_pressure: ioPressure ? "available" : linux ? "unsupported" : "unsupported",
package/dist/sessions.js CHANGED
@@ -16,11 +16,30 @@ function read(kind) {
16
16
  throw new CliError("bad_session_map", `${file(kind)} is not valid JSON`, `Remove it and run: b9s ${kind} sync`);
17
17
  }
18
18
  }
19
- export function bindSession(kind, id, ref) {
19
+ const KIND_NOUN = { codex: "a Codex thread", antigravity: "an Antigravity conversation", "claude-code": "a Claude Code session" };
20
+ /**
21
+ * Binds a session to an agent. A Claude Code agent has one session at a time (its hook hands the
22
+ * agent's messages to the session and counts them delivered), so binding one there replaces the
23
+ * agent's earlier sessions; Codex and Antigravity keep every session a watcher has woken.
24
+ */
25
+ export function bindSession(kind, id, ref, opts = {}) {
20
26
  if (!UUID.test(id))
21
- throw new CliError("usage", `"${id}" is not ${kind === "codex" ? "a Codex thread" : "an Antigravity conversation"} id (a UUID)`);
27
+ throw new CliError("usage", `"${id}" is not ${KIND_NOUN[kind]} id (a UUID)`);
22
28
  const m = read(kind);
23
- m.conversations[id.toLowerCase()] = ref;
29
+ const key = id.toLowerCase();
30
+ if (kind === "claude-code") {
31
+ for (const [other, owner] of Object.entries(m.conversations))
32
+ if (owner === ref && other !== key) {
33
+ delete m.conversations[other];
34
+ if (m.auto)
35
+ delete m.auto[other];
36
+ }
37
+ }
38
+ m.conversations[key] = ref;
39
+ if (opts.auto)
40
+ m.auto = { ...(m.auto ?? {}), [key]: true };
41
+ else if (m.auto)
42
+ delete m.auto[key];
24
43
  mkdirSync(dirname(file(kind)), { recursive: true });
25
44
  writeFileSync(file(kind), JSON.stringify(m, null, 2) + "\n");
26
45
  }
@@ -65,6 +84,11 @@ export function syncFromWatchers() {
65
84
  }
66
85
  return out;
67
86
  }
87
+ /** Every bound session of one harness: id, agent, and whether the hook bound it by itself. */
88
+ export function boundSessions(kind) {
89
+ const m = read(kind);
90
+ return Object.entries(m.conversations).map(([id, agent]) => ({ id, agent, auto: !!m.auto?.[id] }));
91
+ }
68
92
  /** The session ids bound to an agent for one harness. */
69
93
  export function sessionsOf(kind, ref) {
70
94
  return Object.entries(read(kind).conversations).filter(([, r]) => r === ref).map(([id]) => id);
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.106";
1
+ export const CLI_VERSION = "0.12.108";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.106",
3
+ "version": "0.12.108",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {