benignswarm 0.12.110 → 0.12.112

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.
@@ -110,7 +110,9 @@ export function antigravityTurnEnv(sandbox, b9sBin) {
110
110
  if (sandbox !== "workspace-write")
111
111
  return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox };
112
112
  const path = b9sBin ? antigravityPath(b9sBin) : [...new Set([dirname(process.execPath), ...(process.env.PATH ?? "").split(delimiter).filter(Boolean)])].join(delimiter);
113
- return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, PATH: path };
113
+ // Antigravity supplies its restricted outbound proxy to sandboxed commands. Node's fetch
114
+ // ignores the proxy environment unless opted in; b9s uses fetch for authenticated API calls.
115
+ return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, NODE_USE_ENV_PROXY: "1", PATH: path };
114
116
  }
115
117
  export function runAntigravityTurn(bin, args, logPath, cwd, agent, expectedConversation, run = spawnSync, envOverride = {}) {
116
118
  const started = new Date().toISOString();
package/dist/client.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { CliError, WrittenReceiptMismatchError } from "./errors.js";
3
- import { collectAuto } from "./git.js";
3
+ import { collectAuto, machineIdentityForAgent } from "./git.js";
4
4
  import { resolveEffort } from "./model.js";
5
5
  import { cliUserAgent } from "./legacy-alias.js";
6
6
  import { noteServerVersions } from "./update.js";
@@ -276,7 +276,7 @@ export class Client {
276
276
  * by the hook or the watcher, which say nothing about whether the agent is alive.
277
277
  */
278
278
  static forAgent(c, model, opts = {}) {
279
- const auto = collectAuto({ model, machine: c.machine, effort: resolveEffort(opts.effort, process.env, c.vendor), provider: process.env.BSCHAT_PROVIDER });
279
+ const auto = collectAuto({ model, machine: machineIdentityForAgent(c.machine), effort: resolveEffort(opts.effort, process.env, c.vendor), provider: process.env.BSCHAT_PROVIDER });
280
280
  return new Client(c.url, c.key, opts.presence === false ? null : { ...auto }, c.agent, opts.machineIdentity ? auto.machine : null);
281
281
  }
282
282
  static forAdmin(c) {
@@ -5,7 +5,7 @@ import { basename, delimiter, join } from "node:path";
5
5
  import { homedir, platform } from "node:os";
6
6
  import { bool } from "../args.js";
7
7
  import { CliError } from "../errors.js";
8
- import { binVersion, ensureCommandLinks, ensureInstall, latestPublished, lingerEnabled, readInstall, restartInstallServices, watcherServices } from "../install.js";
8
+ import { binVersion, ensureCommandLinks, ensureInstall, latestPublished, launchdLoadedIn, launchdPid, launchdSessionNow, lingerEnabled, ownNpm, plistLaunchdDomain, readInstall, restartInstallServices, watcherServices } from "../install.js";
9
9
  import { CLI_VERSION } from "../version.js";
10
10
  import { CODEX_REQUIREMENTS_PATH, codexHooksDuplicateWithManagedPolicy, reconcileCodexHooks, refreshInstalledHooks } from "../harness.js";
11
11
  import { configRoot } from "../config.js";
@@ -20,8 +20,9 @@ export async function install(p, out) {
20
20
  const want = p.positionals[1];
21
21
  if (want && !/^\d+\.\d+\.\d+$/.test(want))
22
22
  throw new CliError("usage", "install [<version> | --latest] e.g. b9s install --latest, b9s install 0.12.38");
23
- const npm = prev?.npm && existsSync(prev.npm) ? prev.npm : undefined;
24
- const version = want ?? (bool(p.flags, "latest") ? latestPublished(npm ?? join(process.execPath, "..", "npm")) : CLI_VERSION);
23
+ // Explicit install is the only command that may move the machine record to this Node's npm.
24
+ const npm = ownNpm();
25
+ const version = want ?? (bool(p.flags, "latest") ? latestPublished(npm) : CLI_VERSION);
25
26
  const rec = ensureInstall(version, (m) => process.stderr.write(`b9s: ${m}\n`), npm);
26
27
  const lines = [`b9s ${rec.version} is this machine's install: ${rec.bin}`];
27
28
  const aliases = ensureCommandLinks(rec.bin);
@@ -32,7 +33,7 @@ export async function install(p, out) {
32
33
  const managedCodex = reconcileCodexHooks(rec.bin, false);
33
34
  if (managedCodex.managed && managedCodex.changed && managedCodex.path)
34
35
  lines.push(`Removed duplicate Codex hook registration from ${managedCodex.path}; ${CODEX_REQUIREMENTS_PATH} already registers it.`);
35
- const refreshedHooks = bool(p.flags, "latest") ? refreshInstalledHooks(process.cwd(), rec.bin) : [];
36
+ const refreshedHooks = refreshInstalledHooks(process.cwd(), rec.bin);
36
37
  if (refreshedHooks.length)
37
38
  lines.push(`Updated harness hooks: ${refreshedHooks.join(", ")}`);
38
39
  if (prev && prev.bin !== rec.bin)
@@ -50,6 +51,28 @@ export async function install(p, out) {
50
51
  lines.push(`Not restarted:\n ${elsewhere.join("\n ")}`);
51
52
  out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere });
52
53
  }
54
+ export function embeddedHookCommands(value, marker) {
55
+ const found = [];
56
+ const visit = (item) => {
57
+ if (!item || typeof item !== "object")
58
+ return;
59
+ if (Array.isArray(item)) {
60
+ item.forEach(visit);
61
+ return;
62
+ }
63
+ for (const [key, child] of Object.entries(item)) {
64
+ if (key === "command" && typeof child === "string" && child.includes(marker))
65
+ found.push(child.replace(/ --event \w+$/, ""));
66
+ else
67
+ visit(child);
68
+ }
69
+ };
70
+ visit(value);
71
+ return [...new Set(found)];
72
+ }
73
+ export function hookUsesRecordedInstall(command, bin) {
74
+ return command === bin || command === `'${bin}'` || command.startsWith(`${bin} `) || command.startsWith(`'${bin}' `);
75
+ }
53
76
  function diagnosticSpace(path) {
54
77
  try {
55
78
  const stat = statfsSync(path);
@@ -193,21 +216,59 @@ export async function doctor(_p, out) {
193
216
  }
194
217
  const sp = join(root, ".claude", "settings.local.json");
195
218
  if (existsSync(sp)) {
196
- const hooks = JSON.stringify(JSON.parse(readFileSync(sp, "utf8")).hooks ?? {});
197
- const cmds = [...new Set([...hooks.matchAll(/"command":"([^"]*hook claude-code[^"]*)"/g)].map((m) => m[1].replace(/ --event \w+$/, "")))];
219
+ const hooks = JSON.parse(readFileSync(sp, "utf8")).hooks ?? {};
220
+ const cmds = embeddedHookCommands(hooks, "hook claude-code");
198
221
  for (const c of cmds) {
199
- const good = !!rec && (c === rec.bin || c === `'${rec.bin}'` || c.startsWith(`${rec.bin} `));
222
+ const good = !!rec && hookUsesRecordedInstall(c, rec.bin);
200
223
  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)" });
201
224
  }
202
225
  }
203
226
  checks.push(...claudeSessionChecks());
227
+ const codexHooks = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
228
+ const antigravityHooks = join(root, ".agents", "hooks.json");
229
+ for (const [path, marker, label, fix] of [
230
+ [codexHooks, "hook codex", "Codex", "b9s codex hooks (rewrites the hook to the recorded install)"],
231
+ [antigravityHooks, "hook antigravity", "Antigravity", "b9s setup --as <your agent> --vendor antigravity (rewrites the hook to the recorded install)"],
232
+ ])
233
+ if (existsSync(path)) {
234
+ let hooks;
235
+ try {
236
+ hooks = JSON.parse(readFileSync(path, "utf8"));
237
+ }
238
+ catch {
239
+ throw new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
240
+ }
241
+ for (const command of embeddedHookCommands(hooks, marker)) {
242
+ const good = !!rec && hookUsesRecordedInstall(command, rec.bin);
243
+ checks.push({ ok: good, what: `${label} hook in ${path}: ${command}`, fix: good ? undefined : fix });
244
+ }
245
+ }
246
+ if (existsSync(CODEX_REQUIREMENTS_PATH)) {
247
+ const policy = readFileSync(CODEX_REQUIREMENTS_PATH, "utf8");
248
+ const commands = [...new Set([...policy.matchAll(/command\s*=\s*"([^"]*hook codex[^"]*)"/g)].map((match) => match[1].replace(/ --event \w+$/, "")))];
249
+ for (const command of commands) {
250
+ const good = !!rec && hookUsesRecordedInstall(command, rec.bin);
251
+ checks.push({ ok: good, what: `managed Codex hook in ${CODEX_REQUIREMENTS_PATH}: ${command}`, fix: good ? undefined : `update the managed Codex hook to ${rec?.bin ?? "the recorded install"}` });
252
+ }
253
+ }
204
254
  for (const f of ["AGENTS.md", "GEMINI.md", join(".agents", "rules", "bschat.md")]) {
205
255
  const fp = join(root, f);
206
- if (existsSync(fp) && readFileSync(fp, "utf8").includes("npx -y benignswarm"))
207
- checks.push({ ok: false, what: `${fp} tells agents to use npx`, fix: "b9s setup --as <the agent of that harness> (rewrites it to the recorded install)" });
256
+ if (existsSync(fp)) {
257
+ const text = readFileSync(fp, "utf8");
258
+ if (text.includes("npx -y benignswarm"))
259
+ checks.push({ ok: false, what: `${fp} tells agents to use npx`, fix: "b9s setup --as <the agent of that harness> (rewrites it to the recorded install)" });
260
+ const pointer = /recorded install at `([^`]+)`/.exec(text)?.[1];
261
+ if (pointer && rec && pointer !== rec.bin)
262
+ checks.push({ ok: false, what: `${fp} points at ${pointer}, not the recorded install ${rec.bin}`, fix: "b9s setup --as <the agent of that harness> (rewrites the pointer to the recorded install)" });
263
+ }
208
264
  }
209
265
  // Watchers: what the definition says versus what is running.
210
266
  const uid = process.getuid?.();
267
+ if (process.platform === "darwin") {
268
+ checks.push(launchdSessionNow() === "gui"
269
+ ? { ok: true, what: "launchd: desktop session (services in the gui domain)" }
270
+ : { ok: true, what: "launchd: headless Mac (no desktop session): services run as Background agents in the user domain; after a reboot an SSH login (FileVault unlock) is needed before they start" });
271
+ }
211
272
  const services = watcherServices();
212
273
  if (services.some((s) => s.kind === "systemd") && lingerEnabled() === false)
213
274
  checks.push({ ok: false, what: "linger is off: systemd stops the watchers when your last login session on this machine ends", fix: "loginctl enable-linger $USER" });
@@ -227,18 +288,21 @@ export async function doctor(_p, out) {
227
288
  continue;
228
289
  }
229
290
  const short = w.label.replace("org.benignswarm.watch.", "");
230
- const reload = `launchctl bootout gui/${uid}/${w.label}; launchctl bootstrap gui/${uid} ${w.path}`;
291
+ const domain = plistLaunchdDomain(w.path);
292
+ const reload = `launchctl bootout ${domain}/${w.label}; launchctl bootstrap ${domain} ${w.path}`;
231
293
  if (!args.length) {
232
294
  checks.push({ ok: false, what: `watcher ${short}: unreadable plist ${w.path}` });
233
295
  continue;
234
296
  }
235
- const listed = spawnSync("launchctl", ["list", w.label], { encoding: "utf8" });
236
- const pid = /"PID" = (\d+);/.exec(listed.stdout ?? "")?.[1];
297
+ const loadedIn = launchdLoadedIn(w.label);
298
+ const listed = { status: loadedIn.length ? 0 : 1 };
299
+ const pidNum = launchdPid(w.label);
300
+ const pid = pidNum === null ? undefined : String(pidNum);
237
301
  const ver = binVersion(args[0]);
238
302
  if (rec && args[0] !== rec.bin)
239
303
  checks.push({ ok: false, what: `watcher ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its b9s watch ... --launchd (it uses the recorded install and reloads)" });
240
304
  if (listed.status !== 0) {
241
- checks.push({ ok: false, what: `watcher ${short} is not loaded (a login or reboot loads it)`, fix: `launchctl bootstrap gui/${uid} ${w.path} (or delete the plist if the agent is gone)` });
305
+ checks.push({ ok: false, what: `watcher ${short} is not loaded (a login or reboot loads it)`, fix: `launchctl bootstrap ${domain} ${w.path} (or delete the plist if the agent is gone)` });
242
306
  continue;
243
307
  }
244
308
  if (!pid) {
@@ -2,11 +2,11 @@ import { cliUserAgent } from "../legacy-alias.js";
2
2
  import { need, str, bool } from "../args.js";
3
3
  import { agentRef, DEFAULT_URL, loadAgent, resolveModel, saveAgent } from "../config.js";
4
4
  import { spawnSync } from "node:child_process";
5
- import { existsSync, readFileSync } from "node:fs";
5
+ import { readFileSync } from "node:fs";
6
6
  import { join as pathJoin } from "node:path";
7
7
  import { CliError } from "../errors.js";
8
8
  import { defaultMachine } from "../git.js";
9
- import { ensureInstall, readInstall } from "../install.js";
9
+ import { ensureMachineInstall } from "../install.js";
10
10
  import { claudeCheckoutOwner, claudeCheckoutTaken, reconcileCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
11
11
  import { detectVendor } from "../vendor.js";
12
12
  import { CLI_VERSION } from "../version.js";
@@ -196,9 +196,7 @@ export function assertVendorMatchesRepo(root, name, vendor, replace) {
196
196
  * the npm next to the running Node.
197
197
  */
198
198
  function machineInstall() {
199
- const prev = readInstall();
200
- const npm = prev?.npm && existsSync(prev.npm) ? prev.npm : undefined;
201
- return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`b9s: ${m}\n`), npm);
199
+ return ensureMachineInstall(CLI_VERSION, (m) => process.stderr.write(`b9s: ${m}\n`));
202
200
  }
203
201
  function writeIdentityDryRun(root, vendor, name, replace) {
204
202
  const p = findIdentityFile(root);
@@ -1,11 +1,11 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { hostname } from "node:os";
3
2
  import { spawnSync } from "node:child_process";
4
3
  import { bool, str } from "../args.js";
5
4
  import { Client } from "../client.js";
6
5
  import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
7
6
  import { CliError } from "../errors.js";
8
7
  import { table } from "../output.js";
8
+ import { defaultMachine } from "../git.js";
9
9
  import { projectOf } from "./agent.js";
10
10
  function client(p) {
11
11
  const name = resolveAgentName(str(p.flags, "as"));
@@ -71,7 +71,7 @@ export async function list(p, out) {
71
71
  assoc.branch = branch;
72
72
  if (wt)
73
73
  assoc.worktree = wt;
74
- assoc.machine = hostname();
74
+ assoc.machine = defaultMachine();
75
75
  if (!assoc.agent)
76
76
  assoc.agent = creds.agent;
77
77
  }
@@ -176,6 +176,8 @@ export async function machineAdmin(action, rest, p, out) {
176
176
  throw new CliError("provision_failed", `installing the machine daemon on ${host} failed: ${svc.stderr.trim().slice(-300)}`);
177
177
  const daemon = JSON.parse(svc.stdout);
178
178
  say(` daemon: ${daemon.path} with PATH ${daemon.daemon_path}`);
179
+ if (daemon.launchd)
180
+ say(` ${daemon.launchd.guidance}`);
179
181
  const failed = prepared.filter((s) => s.result === "failed");
180
182
  return out.print([
181
183
  `Machine ${name} (${host}) is provisioned and its daemon is running.`,
@@ -210,6 +212,7 @@ export async function machineAdmin(action, rest, p, out) {
210
212
  rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; b9s ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}, sandbox ${rep.codex.sandbox ? (rep.codex.sandbox.ok ? "ok" : `FAILS (${rep.codex.sandbox.error})`) : "?"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
211
213
  rep.os ? ` Antigravity: ${rep.antigravity ? `${rep.antigravity.version ?? "agy"}, ${rep.antigravity.available ? "available" : "unavailable"}, ${rep.antigravity.logged_in ? "logged in" : "not logged in"}, sandbox ${rep.antigravity.sandbox ? (rep.antigravity.sandbox.ok ? "ok" : `FAILS (${rep.antigravity.sandbox.error})`) : "not checked"}` : "not installed"}` : null,
212
214
  rep.container_runtime ? ` Container runtime: ${rep.container_runtime.runtime ?? "none"} (${rep.container_runtime.rootless ? "rootless" : "daemon"}, ${rep.container_runtime.usable_without_root === false ? "NO non-root access" : "non-root ok"}, arch ${(rep.container_runtime.architectures ?? []).join(",") || rep.arch || "?"}${rep.on_ec2 ? `, EC2 container IMDS ${rep.container_imds_blocked ? "blocked" : "NOT blocked"}` : ""})` : null,
215
+ rep.launchd ? ` launchd: ${rep.launchd.session === "headless" ? "headless Mac (no desktop session)" : "desktop session"}; daemon ${rep.launchd.daemon_domain ?? "not installed"}; watchers ${Object.entries(rep.launchd.watchers ?? {}).map(([d, n]) => `${n} in ${d}`).join(", ") || "none"}` : null,
213
216
  m.quarantined ? ` QUARANTINED: ${m.quarantine?.reason ?? "operator containment"}${m.quarantine?.at ? ` (${m.quarantine.at})` : ""}` : null,
214
217
  ];
215
218
  const cacheLines = [];
@@ -415,7 +418,7 @@ export async function machineAdmin(action, rest, p, out) {
415
418
  throw new CliError("confirmation_required", `non-interactive removal requires a reviewed revision: run machine remove ${name} --preview, then pass --confirm ${name} --impact-revision <revision>`);
416
419
  await confirmMachineName(name, p);
417
420
  await c.call("DELETE", `/machines/${name}`, { source_revision: impact.source_revision, confirmation: name });
418
- return out.print(`Removed machine ${name}; its machine key and machine-scoped agent keys are revoked. Agent identities remain. Stop its daemon on the machine with: systemctl --user disable --now org.benignswarm.machine (Linux) or launchctl bootout gui/$(id -u)/org.benignswarm.machine (macOS)`, { removed: name, impact });
421
+ return out.print(`Removed machine ${name}; its machine key and machine-scoped agent keys are revoked. Agent identities remain. Stop its daemon on the machine with: systemctl --user disable --now org.benignswarm.machine (Linux) or launchctl bootout gui/$(id -u)/org.benignswarm.machine (macOS with a desktop session; user/$(id -u)/org.benignswarm.machine on a headless Mac)`, { removed: name, impact });
419
422
  }
420
423
  if (action === "session") {
421
424
  const [sub, machineName, ref] = rest;
@@ -592,7 +595,7 @@ async function runMachineCompanion(code, p, out) {
592
595
  if (svc.status !== 0)
593
596
  throw new CliError("provision_failed", `installing the machine daemon on ${operation.ssh_host} failed: ${svc.stderr.trim().slice(-300)}`);
594
597
  const daemon = JSON.parse(svc.stdout);
595
- await report("daemon", "completed", `Daemon installed at ${daemon.path}`);
598
+ await report("daemon", "completed", `Daemon installed at ${daemon.path}${daemon.launchd ? `; ${daemon.launchd.guidance}` : ""}`);
596
599
  const outcome = operation.kind === "provision" ? "is provisioned" : "has its machine key rotated";
597
600
  const completed = await companion.call("POST", `/machine-operations/${operation.id}/finish`, { status: "succeeded", result: `Machine ${operation.machine} ${outcome} and its daemon is running` });
598
601
  const result = { operation: completed.operation, machine: operation.machine, ssh_host: operation.ssh_host, daemon_path: daemon.daemon_path, prepare: prepared };