benignswarm 0.12.117 → 0.12.119

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/args.js CHANGED
@@ -11,7 +11,7 @@ export const STRING_FLAGS = [
11
11
  "as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task",
12
12
  "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions",
13
13
  "cardinality", "assign-outside-qualifications", "judges", "machine", "idempotency-key", "dir", "confirm", "impact-revision", "type",
14
- "name", "out", "token", "token-file", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
14
+ "name", "out", "token", "token-file", "job", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
15
15
  "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent",
16
16
  "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval",
17
17
  "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "startup-jitter-seconds", "env", "scope",
@@ -91,6 +91,9 @@ export async function who(p, out) {
91
91
  }
92
92
  export async function status(p, out) {
93
93
  const sub = p.positionals[1];
94
+ // Bare `b9s status` is about the machine, not an agent: it needs no agent identity.
95
+ if (sub === undefined)
96
+ return (await import("./machine-status.js")).machineStatus(out);
94
97
  const { client, creds } = agentClient(p);
95
98
  if (sub === "set") {
96
99
  const body = {};
@@ -55,7 +55,7 @@ function formatSettings(s) {
55
55
  ];
56
56
  return lines.join("\n");
57
57
  }
58
- const USAGE = "b9s-admin environment settings show | settings set [--stage disabled|report_only|staged|enabled] [--projects a,b] [--machines m1,m2] [--resolved-retention-days n] [--wont-fix-retention-days n] [--alerts on|off] [--alert-cooldown-minutes n] | retention run [--dry-run] | alerts [list|evaluate]";
58
+ const USAGE = "b9s-admin environment settings show | settings set [--stage disabled|report_only|staged|enabled] [--projects a,b] [--machines m1,m2] [--resolved-retention-days n] [--wont-fix-retention-days n] [--alerts on|off] [--alert-cooldown-minutes n] | retention run --dry-run | alerts [list|evaluate]";
59
59
  export async function environmentAdmin(c, action, rest, p, out) {
60
60
  if (action === "settings") {
61
61
  const sub = rest[0] ?? "show";
@@ -97,9 +97,11 @@ export async function environmentAdmin(c, action, rest, p, out) {
97
97
  }
98
98
  if (action === "retention" && rest[0] === "run" && rest.length === 1) {
99
99
  const dryRun = bool(p.flags, "dry-run");
100
- const r = await c.call("POST", "/account/environment/retention/run", { dry_run: dryRun });
100
+ if (!dryRun)
101
+ throw new CliError("review_required", "Manual retention deletion requires the reviewed batch in Account → Environment. Use retention run --dry-run to inspect candidates.");
102
+ const r = await c.call("POST", "/account/environment/retention/run", { dry_run: true });
101
103
  const res = r.result;
102
- out.print(`${res.dry_run ? "Retention dry run" : "Retention prune"} (${res.ran_at}): ${res.candidates_resolved} resolved + ${res.candidates_wont_fix} wont_fix candidate(s); deleted ${res.deleted_issues}.`, r);
104
+ out.print(`Retention candidate preview (${res.ran_at}): ${res.candidates_resolved} resolved + ${res.candidates_wont_fix} wont_fix candidate(s); deleted ${res.deleted_issues}. Confirm a reviewed batch in Account → Environment.`, r);
103
105
  return;
104
106
  }
105
107
  if (action === "alerts") {
@@ -0,0 +1,133 @@
1
+ import { existsSync, statSync } from "node:fs";
2
+ import { hostname } from "node:os";
3
+ import { join } from "node:path";
4
+ import { Client } from "../client.js";
5
+ import { DEFAULT_URL } from "../config.js";
6
+ import { configDirectory } from "../directories.js";
7
+ import { MACHINE_LABEL, readInstall, serviceActive, watcherServices } from "../install.js";
8
+ import { checkReachable, interfaceFacts, requiredHosts } from "../network.js";
9
+ import { CLI_VERSION } from "../version.js";
10
+ const firstLine = (text) => text.split("\n")[0].slice(0, 220);
11
+ /** How old the service's latest report may be before the machine counts as not heard from. */
12
+ export const staleAfterSeconds = (interval) => Math.max(90, 3 * (interval ?? 30));
13
+ /** Fixed rules, no guessing: every line of the verdict names the fact it comes from. */
14
+ export function statusVerdict(input) {
15
+ const problems = [];
16
+ const limits = [];
17
+ if (!input.interfaces.length)
18
+ problems.push("no network interface has an address");
19
+ for (const r of input.reach)
20
+ if (!r.ok)
21
+ problems.push(`cannot reach ${r.host} (${r.purpose}): ${r.error}`);
22
+ if (input.install.recorded && input.install.recorded.version !== input.install.running) {
23
+ limits.push(`this command is b9s ${input.install.running} but the machine's recorded install is ${input.install.recorded.version} at ${input.install.recorded.bin}`);
24
+ }
25
+ const m = input.machine;
26
+ if (!m)
27
+ return { state: "NOT A PROVISIONED MACHINE", problems, limits };
28
+ if (m.daemon !== "running")
29
+ problems.push(`the machine daemon is ${m.daemon}: b9s machine service`);
30
+ if (m.cloudError)
31
+ problems.push(`the service did not answer for this machine: ${m.cloudError}`);
32
+ const cloud = m.cloud;
33
+ if (cloud) {
34
+ if (cloud.machine.quarantined_at)
35
+ problems.push(`the service has quarantined this machine since ${cloud.machine.quarantined_at}`);
36
+ if (!cloud.received)
37
+ problems.push("the service has never received a report from this machine");
38
+ else if (cloud.received.age_seconds > staleAfterSeconds(cloud.received.report_interval_seconds)) {
39
+ problems.push(`the service last heard from this machine ${cloud.received.age_seconds} s ago (reports are due every ${cloud.received.report_interval_seconds ?? 30} s)`);
40
+ }
41
+ const reported = cloud.report?.install?.version;
42
+ if (reported && reported !== input.install.running)
43
+ limits.push(`the daemon last reported b9s ${reported}; this command is ${input.install.running} (the daemon reports the new version after its restart)`);
44
+ if (cloud.report?.git_identity && cloud.report.git_identity.ok === false)
45
+ limits.push("git has no user name and email here; agents cannot commit");
46
+ for (const name of ["codex", "claude-code", "antigravity"]) {
47
+ const h = cloud.report?.[name];
48
+ if (!h || h.available === false)
49
+ continue;
50
+ if (h.logged_in === false)
51
+ limits.push(`${name}: not logged in`);
52
+ else if (h.sandbox && h.sandbox.ok === false)
53
+ limits.push(`${name}: sandbox check failed: ${firstLine(h.sandbox.error ?? "no reason reported")}`);
54
+ }
55
+ for (const s of cloud.sessions)
56
+ if (s.state === "error")
57
+ problems.push(`session ${s.id ?? "?"} is in error: ${firstLine(s.error ?? "no reason reported")}`);
58
+ }
59
+ return { state: problems.length ? "NOT READY" : limits.length ? "READY WITH LIMITS" : "READY", problems, limits };
60
+ }
61
+ function harnessLine(name, h) {
62
+ if (!h || h.available === false)
63
+ return null;
64
+ if (h.logged_in === false)
65
+ return `${name}: not logged in`;
66
+ return `${name}: logged in, sandbox ${h.sandbox ? (h.sandbox.ok ? "ok" : "FAILED") : "not checked"}`;
67
+ }
68
+ export function renderStatus(input, verdict) {
69
+ const m = input.machine;
70
+ const cloud = m?.cloud ?? null;
71
+ const heard = cloud?.received ? ` · the service heard from it ${cloud.received.age_seconds} s ago` : "";
72
+ const lines = [`${m?.name ?? input.host}: ${verdict.state}${verdict.state.startsWith("READY") ? heard : ""}`];
73
+ const row = (label, value) => lines.push(`${label.padEnd(12)} ${value}`);
74
+ row("install", `b9s ${input.install.running}${input.install.recorded ? ` (recorded install ${input.install.recorded.version} at ${input.install.recorded.bin})` : " (no recorded install on this machine)"}`);
75
+ row("network", input.interfaces.length ? input.interfaces.map((i) => `${i.name} ${i.addresses.join(", ")}`).join(" · ") : "no interface has an address");
76
+ row("internet", input.reach.map((r) => `${r.host} ${r.ok ? `ok ${r.ms} ms` : `FAILED (${r.error})`}`).join(" · "));
77
+ if (!m) {
78
+ row("machine", "not provisioned: no machine registration here, so no daemon and no report to the service");
79
+ }
80
+ else {
81
+ row("daemon", m.daemon);
82
+ row("service", cloud ? (cloud.received ? `last report received ${cloud.received.at} (${cloud.received.age_seconds} s ago)` : "no report received yet") : `no answer: ${m.cloudError}`);
83
+ if (cloud) {
84
+ const harnesses = [harnessLine("codex", cloud.report?.codex), harnessLine("claude-code", cloud.report?.["claude-code"]), harnessLine("antigravity", cloud.report?.antigravity)].filter((x) => x !== null);
85
+ row("harnesses", harnesses.length ? harnesses.join(" · ") : "none reported");
86
+ const errors = cloud.sessions.filter((s) => s.state === "error").length;
87
+ row("sessions", `${cloud.sessions.length} reported, ${errors} in error`);
88
+ row("labels", cloud.machine.labels.length ? cloud.machine.labels.join(", ") : "none");
89
+ }
90
+ }
91
+ if (verdict.problems.length) {
92
+ lines.push("problems");
93
+ for (const p of verdict.problems)
94
+ lines.push(` - ${p}`);
95
+ }
96
+ if (verdict.limits.length) {
97
+ lines.push("limits");
98
+ for (const l of verdict.limits)
99
+ lines.push(` - ${l}`);
100
+ }
101
+ if (!verdict.problems.length && !verdict.limits.length)
102
+ lines.push("problems none");
103
+ return lines.join("\n");
104
+ }
105
+ /** `b9s status`: this machine's own checks next to what the service holds about it. */
106
+ export async function machineStatus(out) {
107
+ const file = join(configDirectory(), "machine.json");
108
+ const creds = existsSync(file) && statSync(file).isFile()
109
+ ? (await import("./machine.js")).loadMachine()
110
+ : null;
111
+ const url = creds?.url ?? process.env.BSCHAT_URL ?? process.env.B9S_URL ?? DEFAULT_URL;
112
+ const recorded = readInstall();
113
+ const reach = await checkReachable(requiredHosts(url));
114
+ let machine = null;
115
+ if (creds) {
116
+ const service = watcherServices().find((s) => s.label === MACHINE_LABEL);
117
+ const daemon = service ? (serviceActive(service) ? "running" : "stopped") : "not installed";
118
+ let cloud = null;
119
+ let cloudError = null;
120
+ try {
121
+ cloud = await Client.raw(creds.url, creds.key).call("GET", "/machines/me/status");
122
+ }
123
+ catch (error) {
124
+ cloudError = firstLine(error.message);
125
+ }
126
+ machine = { name: creds.name, url: creds.url, daemon, cloud, cloudError };
127
+ }
128
+ const input = { host: hostname(), install: { running: CLI_VERSION, recorded: recorded ? { version: recorded.version, bin: recorded.bin } : null }, interfaces: interfaceFacts(), reach, machine };
129
+ const verdict = statusVerdict(input);
130
+ out.print(renderStatus(input, verdict), { ...input, machine: machine ? { ...machine } : null, verdict });
131
+ if (verdict.state === "NOT READY")
132
+ process.exitCode = 1;
133
+ }
@@ -6,6 +6,7 @@ import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtemp
6
6
  import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
7
7
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
8
8
  import { str } from "../args.js";
9
+ import { interfaceFacts } from "../network.js";
9
10
  import { Client } from "../client.js";
10
11
  import { agentRef, configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
11
12
  import { CliError } from "../errors.js";
@@ -2527,7 +2528,8 @@ export function antigravityAccountFingerprintForModelCheck(credentialsFile = joi
2527
2528
  const credentials = jsonRecord(credentialsFile);
2528
2529
  return accountIdentityFingerprint("antigravity", [
2529
2530
  jwtAccountSubject(credentials?.id_token),
2530
- stableIdAt(credentials, ["account_id", "accountId", "user_id"]),
2531
+ // The agy command's own token file names the signed-in account as `id_token_email`.
2532
+ stableIdAt(credentials, ["account_id", "accountId", "user_id", "id_token_email"]),
2531
2533
  ]);
2532
2534
  }
2533
2535
  function accountFingerprintForModelCheck(harness, provider) {
@@ -2552,7 +2554,9 @@ function accountFingerprintForModelCheck(harness, provider) {
2552
2554
  return null;
2553
2555
  }
2554
2556
  if (harness === "antigravity") {
2555
- for (const credentialsFile of [join(homedir(), ".gemini", "oauth_creds.json"), join(homedir(), ".gemini", "antigravity", "oauth_creds.json")]) {
2557
+ // agy keeps its login in ~/.gemini/antigravity-cli/antigravity-oauth-token (the only file on a
2558
+ // Linux host that never ran another client); without it every Antigravity model read "not verified".
2559
+ for (const credentialsFile of [join(homedir(), ".gemini", "antigravity-cli", "antigravity-oauth-token"), join(homedir(), ".gemini", "oauth_creds.json"), join(homedir(), ".gemini", "antigravity", "oauth_creds.json")]) {
2556
2560
  const fingerprint = antigravityAccountFingerprintForModelCheck(credentialsFile);
2557
2561
  if (fingerprint)
2558
2562
  return fingerprint;
@@ -2659,6 +2663,8 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
2659
2663
  // macOS: which launchd domain the services use, so a headless Mac is visible, never silent (WU #478).
2660
2664
  ...(platform() === "darwin" ? { launchd: (probes?.launchd ?? launchdFacts)() } : {}),
2661
2665
  bschat: { version: CLI_VERSION, bin: requireInstall().bin },
2666
+ // IPv4 only: temporary IPv6 addresses rotate, and this report is compared for change.
2667
+ network: { interfaces: interfaceFacts(true) },
2662
2668
  git_identity: gitIdentity,
2663
2669
  on_ec2: onEc2,
2664
2670
  imds_blocked: imds.ok,
@@ -1,3 +1,4 @@
1
+ import { forgetLockJob, lockJobKey, lockJobsFile, rememberLockJob, savedLockJobs, tokenForRelease } from "../lock-jobs.js";
1
2
  import { spawnSync } from "node:child_process";
2
3
  import { createHash, randomBytes, randomUUID } from "node:crypto";
3
4
  import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
@@ -1606,7 +1607,13 @@ export async function lock(p, out) {
1606
1607
  throw new CliError("usage", "--remove-empty is only valid with b9s unlock <name>");
1607
1608
  if (cmd === "unlock") {
1608
1609
  const removeEmpty = bool(p.flags, "remove-empty");
1609
- const r = await client.call("POST", `/projects/${project}/locks/${lockName}/release`, { shared: bool(p.flags, "shared"), machine: str(p.flags, "machine"), ...(removeEmpty ? { remove_empty: true } : { job_token: str(p.flags, "token") }) });
1610
+ // The job's token is kept on this machine at acquisition; typing it is only needed elsewhere.
1611
+ const jobsFile = lockJobsFile(creds.project ? `${creds.project}.${creds.agent}` : `account.${creds.agent}`);
1612
+ const jobsKey = lockJobKey(project, lockName, bool(p.flags, "shared") ? null : str(p.flags, "machine") ?? defaultMachine());
1613
+ const releaseToken = removeEmpty ? undefined : str(p.flags, "token") ?? tokenForRelease(savedLockJobs(jobsFile, jobsKey), str(p.flags, "job"), lockName);
1614
+ const r = await client.call("POST", `/projects/${project}/locks/${lockName}/release`, { shared: bool(p.flags, "shared"), machine: str(p.flags, "machine"), ...(removeEmpty ? { remove_empty: true } : { job_token: releaseToken }) });
1615
+ if (releaseToken !== undefined)
1616
+ forgetLockJob(jobsFile, jobsKey, releaseToken);
1610
1617
  if (removeEmpty) {
1611
1618
  out.print(`${lockName} removed as an empty lock.`, r);
1612
1619
  return;
@@ -1622,7 +1629,7 @@ export async function lock(p, out) {
1622
1629
  const token = str(p.flags, "token") ?? `b9sjob_${randomBytes(24).toString("hex")}`;
1623
1630
  const jobId = createHash("sha256").update(token).digest("hex").slice(0, 12);
1624
1631
  const machine = defaultMachine();
1625
- const unlockCommand = `b9s unlock ${lockName}${bool(p.flags, "shared") ? " --shared" : ""} --token ${token}`;
1632
+ const unlockCommand = `b9s unlock ${lockName}${bool(p.flags, "shared") ? " --shared" : ""} (from this machine; elsewhere add --token ${token})`;
1626
1633
  let r;
1627
1634
  try {
1628
1635
  r = await client.call("POST", `/projects/${project}/locks/${lockName}/acquire`, { unit: unit ? Number(unit) : null, ...(str(p.flags, "note") !== undefined ? { note: str(p.flags, "note") } : {}), shared: bool(p.flags, "shared"), machine, job_token: token });
@@ -1640,6 +1647,7 @@ export async function lock(p, out) {
1640
1647
  }
1641
1648
  if (r.job_token !== token)
1642
1649
  throw new CliError("lock_protocol_mismatch", `The server did not confirm job ownership; do not start work. Inspect the lock state. Job token: ${token}`);
1650
+ rememberLockJob(lockJobsFile(creds.project ? `${creds.project}.${creds.agent}` : `account.${creds.agent}`), lockJobKey(project, lockName, bool(p.flags, "shared") ? null : machine), { job: jobId, token, at: new Date().toISOString() });
1643
1651
  out.print(r.maintenance
1644
1652
  ? `${lockName} is not handed out now: ${r.maintenance}. Job ${jobId} is #${r.position} in line. Job token: ${token}. Leave the queue: ${unlockCommand}`
1645
1653
  : r.acquired
package/dist/help.js CHANGED
@@ -35,7 +35,7 @@ Work-unit open, start, submit and close endpoints accept context fill and compac
35
35
  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.
36
36
  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.
37
37
  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.
38
- 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.
38
+ 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. Agent listings/status and work-unit/vocabulary JSON omit retired tier fields; submission history retains its stamped tier as historical evidence. 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.
39
39
  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.
40
40
 
41
41
  Agent commands
@@ -48,6 +48,7 @@ Agent commands
48
48
  b9s notice add --project <p> "<text>" [--until <time>] [--command-pattern <regex>]
49
49
  assigner only: add a project notice; matching commands warn but continue
50
50
  b9s who [--account] agent status (--account: all projects); shows pressure for active machine sessions
51
+ b9s status is this machine ready: install, network interfaces, internet reach, daemon, and what the service last heard from it
51
52
  b9s status set [--state s] [--goal g] [--task t] [--blocked-on b] [--tags a,b] [--custom '{json}']
52
53
  [--checks-every <min>|none] not always on but checking on a schedule: say how often
53
54
  b9s status history <agent> [--limit n]
@@ -125,7 +126,7 @@ Agent commands
125
126
  acquisition queues through a machine maintenance drain/window and resumes after it
126
127
  machine identity is this host's hostname plus its registered label, shared by all agents here
127
128
  save the returned job token; reuse --token to check/retry the same job
128
- b9s unlock <name> --token <job-token> [--machine <label>|--shared] | b9s locks
129
+ b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks on the machine that took it the job's token is kept for you
129
130
  b9s unlock <name> --remove-empty [--machine <label>|--shared]
130
131
  new agent jobs release by token; legacy jobs retain identity release; assigners/operators may release without a token
131
132
  closing a unit does not release a new job's lock
@@ -323,8 +324,8 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
323
324
  setup queues one reviewed work unit; set records its merged declaration; catalog versions are x.y.z
324
325
  b9s-admin environment settings show | settings set [--stage disabled|report_only|staged|enabled] [--projects a,b] [--machines m1,m2] [--resolved-retention-days n] [--wont-fix-retention-days n] [--alerts on|off] [--alert-cooldown-minutes n]
325
326
  staged rollout, closed-issue retention, and operator alert settings (also in Account -> Environment)
326
- b9s-admin environment retention run [--dry-run] | alerts [list|evaluate]
327
- preview or prune closed issues past retention; inspect or evaluate cooled-down alerts
327
+ b9s-admin environment retention run --dry-run | alerts [list|evaluate]
328
+ inspect closed-issue candidates; deletion requires a reviewed batch in Account -> Environment
328
329
  b9s-admin agent create <project> <name> --vendor <v> [--role r] [--machine m]
329
330
  b9s-admin agent --account create <name> --vendor <v> --role <r> account-wide agent (role's --projects decides access)
330
331
  b9s-admin agent --account list|role|rotate-key|bench|unbench|delete ...
@@ -385,6 +386,7 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
385
386
  --assign-outside-qualifications yes|no allow assigners in this role to make reasoned ownership exceptions; dispatch stays qualified
386
387
  --judges yes|no the turn-judge capability: this role may be chosen as the independent judge (docs/TURN-JUDGE.md)
387
388
  b9s-admin needs decisions waiting on you (asks, unit questions, broken wake paths, alert failures)
389
+ Browser conditional actions and retry receipts: docs/NEEDS-BROWSER-ACTIONS.md; console work #555/#556
388
390
  b9s-admin answer <key> "decision" answer one; the asker is @mentioned
389
391
  b9s-admin answer <key> --approve [--assign <agent>] [--note ".."] accept an ask proposal and name its action owner
390
392
  b9s-admin answer <key> --approve [--note ".."] accept a unit-question proposal as written
package/dist/index.js CHANGED
@@ -144,7 +144,9 @@ async function main(argv) {
144
144
  const codexSubcommand = cmd === "codex" ? p.positionals[1] : undefined;
145
145
  const antigravitySubcommand = cmd === "antigravity" ? p.positionals[1] : undefined;
146
146
  // These sync/setup subcommands only inspect or configure local harness session state.
147
- const localHarnessDispatch = (cmd === "codex" && ["hooks", "sync", "start"].includes(codexSubcommand ?? "")) || (cmd === "antigravity" && antigravitySubcommand === "sync") || (cmd === "claude" && p.positionals[1] === "sessions");
147
+ const localHarnessDispatch = (cmd === "codex" && ["hooks", "sync", "start"].includes(codexSubcommand ?? "")) || (cmd === "antigravity" && antigravitySubcommand === "sync") || (cmd === "claude" && p.positionals[1] === "sessions")
148
+ // Bare `status` is the machine's readiness report: it needs no agent identity.
149
+ || (cmd === "status" && p.positionals[1] === undefined);
148
150
  const noticePreflightExempt = NOTICE_PREFLIGHT_EXEMPT_COMMANDS.has(cmd) || localHarnessDispatch;
149
151
  if (!noticePreflightExempt) {
150
152
  const agentName = resolveAgentName(str(p.flags, "as"));
@@ -0,0 +1,68 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { configDirectory } from "./directories.js";
4
+ import { CliError } from "./errors.js";
5
+ const KEEP_MS = 7 * 24 * 60 * 60 * 1000;
6
+ export function lockJobsFile(agentRef, root = configDirectory()) {
7
+ return join(root, "state", `lock-jobs.${agentRef.replace(/[^A-Za-z0-9._-]/g, ".")}.json`);
8
+ }
9
+ export const lockJobKey = (project, lock, machine) => JSON.stringify([project, lock, machine ?? ""]);
10
+ function read(file) {
11
+ if (!existsSync(file))
12
+ return {};
13
+ let parsed;
14
+ try {
15
+ parsed = JSON.parse(readFileSync(file, "utf8"));
16
+ }
17
+ catch {
18
+ throw new CliError("corrupt_state", `${file} is not valid JSON; move it aside, then release held locks with their tokens or ask an assigner`);
19
+ }
20
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
21
+ throw new CliError("corrupt_state", `${file} does not hold lock jobs; move it aside`);
22
+ return parsed;
23
+ }
24
+ function write(file, store) {
25
+ mkdirSync(join(file, ".."), { recursive: true });
26
+ const temporary = `${file}.${process.pid}.tmp`;
27
+ writeFileSync(temporary, JSON.stringify(store), { mode: 0o600 });
28
+ chmodSync(temporary, 0o600);
29
+ renameSync(temporary, file);
30
+ }
31
+ export function savedLockJobs(file, key) {
32
+ return read(file)[key] ?? [];
33
+ }
34
+ export function rememberLockJob(file, key, entry, nowMs = Date.now()) {
35
+ const store = read(file);
36
+ for (const k of Object.keys(store)) {
37
+ store[k] = store[k].filter((e) => nowMs - Date.parse(e.at) < KEEP_MS);
38
+ if (!store[k].length)
39
+ delete store[k];
40
+ }
41
+ store[key] = [...(store[key] ?? []).filter((e) => e.job !== entry.job), entry];
42
+ write(file, store);
43
+ }
44
+ export function forgetLockJob(file, key, token) {
45
+ const store = read(file);
46
+ if (!store[key])
47
+ return;
48
+ store[key] = store[key].filter((e) => e.token !== token);
49
+ if (!store[key].length)
50
+ delete store[key];
51
+ write(file, store);
52
+ }
53
+ /**
54
+ * The token to release with when none was typed: the one saved job, or the one named by --job.
55
+ * Several saved jobs without --job is refused by name; nothing is guessed. No saved job returns
56
+ * undefined, which leaves the release to the server's own rules (an assigner, a legacy holder).
57
+ */
58
+ export function tokenForRelease(saved, job, lock) {
59
+ if (job !== undefined) {
60
+ const match = saved.find((e) => e.job === job);
61
+ if (!match)
62
+ throw new CliError("unknown_lock_job", `no saved job ${job} for ${lock} on this machine${saved.length ? `; saved: ${saved.map((e) => e.job).join(", ")}` : ""}`, "Pass --token <job-token>, or ask an assigner to release it");
63
+ return match.token;
64
+ }
65
+ if (saved.length > 1)
66
+ throw new CliError("ambiguous_lock_job", `this agent has ${saved.length} saved jobs for ${lock} on this machine: ${saved.map((e) => `${e.job} (${e.at})`).join(", ")}`, `Name one: b9s unlock ${lock} --job <id>`);
67
+ return saved[0]?.token;
68
+ }
@@ -0,0 +1,45 @@
1
+ import { networkInterfaces } from "node:os";
2
+ /**
3
+ * The machine's network interfaces that carry an address other hosts could use. Loopback and
4
+ * link-local addresses are left out; so are IPv6 addresses when `ipv4Only` is set, because
5
+ * temporary IPv6 addresses rotate and the daemon's report is compared for change.
6
+ */
7
+ export function interfaceFacts(ipv4Only = false, source = networkInterfaces()) {
8
+ const rows = [];
9
+ for (const [name, entries] of Object.entries(source)) {
10
+ const addresses = (entries ?? [])
11
+ .filter((entry) => !entry.internal && !(entry.family === "IPv6" && (ipv4Only || entry.address.toLowerCase().startsWith("fe80"))) && !(entry.family === "IPv4" && entry.address.startsWith("169.254.")))
12
+ .map((entry) => entry.address);
13
+ if (addresses.length)
14
+ rows.push({ name, addresses: [...new Set(addresses)].sort() });
15
+ }
16
+ return rows.sort((a, b) => a.name.localeCompare(b.name));
17
+ }
18
+ /** The hosts a machine must reach to do its work, and why. */
19
+ export function requiredHosts(apiUrl) {
20
+ const api = new URL(apiUrl);
21
+ return [
22
+ { url: `${api.origin}/health`, host: api.host, purpose: "the service" },
23
+ { url: "https://registry.npmjs.org/-/ping", host: "registry.npmjs.org", purpose: "upgrades" },
24
+ { url: "https://github.com/", host: "github.com", purpose: "repositories" },
25
+ ];
26
+ }
27
+ /**
28
+ * One real HTTPS request per host. Any HTTP answer proves name resolution, routing and TLS; only a
29
+ * failure to get an answer counts as unreachable, and its cause is reported as the system gave it.
30
+ */
31
+ export async function checkReachable(targets, timeoutMs = 8000, fetcher = fetch) {
32
+ return Promise.all(targets.map(async (target) => {
33
+ const started = Date.now();
34
+ try {
35
+ const response = await fetcher(target.url, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
36
+ await response.body?.cancel();
37
+ return { host: target.host, purpose: target.purpose, ok: true, ms: Date.now() - started, status: response.status, error: null };
38
+ }
39
+ catch (error) {
40
+ const cause = error.cause;
41
+ const text = error.name === "TimeoutError" ? `no answer within ${Math.round(timeoutMs / 1000)} s` : (cause?.code ?? cause?.message ?? error.message);
42
+ return { host: target.host, purpose: target.purpose, ok: false, ms: Date.now() - started, status: null, error: text };
43
+ }
44
+ }));
45
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.117";
1
+ export const CLI_VERSION = "0.12.119";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.117",
3
+ "version": "0.12.119",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {