benignswarm 0.12.111 → 0.12.113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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/args.js CHANGED
@@ -23,7 +23,7 @@ export const STRING_FLAGS = [
23
23
  "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
24
24
  "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
25
25
  "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
26
- "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from",
26
+ "plain", "if-yes", "if-no", "ssh", "variant", "count", "min", "max", "needs", "min-ram", "exclude", "carry", "from",
27
27
  "to-ssh", "ssh-from", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires",
28
28
  "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect",
29
29
  "expectations", "reworks", "cause", "lesson", "disputes", "annotation", "send-back-event", "confirm-causes", "floor",
@@ -35,6 +35,7 @@ export const STRING_FLAGS = [
35
35
  "machine-session-id", "pool-sessions", "registry", "detail", "worktree",
36
36
  "purpose", "storage-mode", "hosts", "arn", "version-id",
37
37
  "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
38
+ "expires-at", "conflicts-with", "source-channel-id", "source-message-id",
38
39
  "metadata-file",
39
40
  ];
40
41
  export const BOOL_FLAGS = [
@@ -43,7 +44,9 @@ export const BOOL_FLAGS = [
43
44
  "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
44
45
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
45
46
  "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
46
- "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "in-container", "assessment-only", "retrieve-ec2", "no-wait-verify", "preview", "remove-empty", "dry-run", "stdin", "context-confirmed",
47
+ "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only",
48
+ "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution",
49
+ "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible",
47
50
  ];
48
51
  export function parse(argv) {
49
52
  const options = {};
@@ -53,17 +56,39 @@ export function parse(argv) {
53
56
  options[f] = { type: "boolean" };
54
57
  try {
55
58
  const seen = new Set();
59
+ const negativeBooleans = new Set();
56
60
  for (const arg of argv) {
57
61
  if (!arg.startsWith("--"))
58
62
  continue;
59
- const name = arg.slice(2).split("=", 1)[0].replace(/^no-/, "");
63
+ const rawName = arg.slice(2).split("=", 1)[0];
64
+ // A registered literal option wins over the conventional --no-<boolean>
65
+ // spelling. In particular, --no-source is an existing boolean CLI flag.
66
+ const negated = !(rawName in options) && rawName.startsWith("no-");
67
+ const name = negated ? rawName.slice(3) : rawName;
60
68
  if (!(name in options) || LIST_FLAGS.includes(name))
61
69
  continue;
70
+ if (negated) {
71
+ if (options[name]?.type !== "boolean" || arg.includes("="))
72
+ throw new CliError("usage", `${arg} is only valid for a boolean flag without a value`);
73
+ if (seen.has(name))
74
+ throw new CliError("usage", `--${name} was repeated; it may only be given once`);
75
+ seen.add(name);
76
+ negativeBooleans.add(name);
77
+ continue;
78
+ }
62
79
  if (seen.has(name))
63
80
  throw new CliError("usage", `--${name} was repeated; it may only be given once`);
64
81
  seen.add(name);
65
82
  }
66
- const { values, positionals } = parseArgs({ args: argv, options, allowPositionals: true, strict: true });
83
+ const parseArgv = argv.filter((arg) => {
84
+ if (!arg.startsWith("--"))
85
+ return true;
86
+ const rawName = arg.slice(2).split("=", 1)[0];
87
+ return !(rawName.startsWith("no-") && !(rawName in options) && negativeBooleans.has(rawName.slice(3)));
88
+ });
89
+ const { values, positionals } = parseArgs({ args: parseArgv, options, allowPositionals: true, strict: true });
90
+ for (const name of negativeBooleans)
91
+ values[name] = false;
67
92
  const flags = values;
68
93
  const repeatValues = {};
69
94
  for (const [key, value] of Object.entries(flags))
package/dist/brief.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Client } from "./client.js";
2
2
  import { loadAgent, resolveAgentName } from "./config.js";
3
+ import { formatStandingRuleSet } from "./standing-rules.js";
3
4
  export function formatOutcomeMeasures(measures = [], omitted = 0) {
4
5
  const rows = measures.slice(0, 6).map((m) => {
5
6
  const value = m.value === null || m.value === "unknown" ? "unknown" : `${String(m.value)}${m.unit ? ` ${m.unit}` : ""}`;
@@ -37,7 +38,7 @@ export async function fetchRecoveryBrief(nameOrRef) {
37
38
  throw new Error("GET /agents/me/notices returned no notices array");
38
39
  return { ...response.brief, notices: active.notices };
39
40
  }
40
- export function formatRecoveryBrief(brief) {
41
+ export function formatRecoveryBrief(brief, includeStandingRules = true) {
41
42
  const scope = (base, amendments, omitted = 0) => [
42
43
  ...(base ? [`\n base scope: ${base}`] : []),
43
44
  ...(amendments ?? []).map((amendment) => `\n amendment ${amendment.at} ${amendment.author}: ${amendment.text}`),
@@ -64,6 +65,15 @@ export function formatRecoveryBrief(brief) {
64
65
  lines.push(...(brief.decisions.length ? brief.decisions.map((d) => ` ${d.project} ${d.slice} WU #${d.unit} (${d.source}): ${d.ruling}`) : [" none"]));
65
66
  lines.push("Current notices:");
66
67
  lines.push(...(brief.notices?.length ? brief.notices.map((n) => ` [${n.scope} ${n.scope_name}] ${n.text}`) : [" none"]));
68
+ if (includeStandingRules && brief.standing_rules) {
69
+ lines.push("Standing rules:");
70
+ if (brief.standing_rules.delivery !== "complete")
71
+ lines.push(` delivery pending; retrieve the full rules with ${brief.standing_rules.process_command ?? "b9s process"}`);
72
+ else
73
+ lines.push(...(brief.standing_rules.rulesets.length
74
+ ? brief.standing_rules.rulesets.map((set) => formatStandingRuleSet(set, set.project ?? "account").split("\n").map((line) => ` ${line}`).join("\n"))
75
+ : [" (no rulesets)"]));
76
+ }
67
77
  lines.push(...formatOutcomeMeasures(brief.measures, brief.measures_omitted));
68
78
  return lines.join("\n");
69
79
  }
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";
@@ -35,6 +35,12 @@ function expectedTextReceiptFields(method, path, body, response) {
35
35
  return strings("excerpt");
36
36
  if (verb === "PATCH" && /^\/projects\/[^/]+\/agents\/[^/]+\/moves\/[^/]+$/.test(route))
37
37
  return strings("detail");
38
+ if (verb === "POST" && /^\/projects\/[^/]+\/pools\/[^/]+\/(pause|resume)$/.test(route))
39
+ return strings("reason");
40
+ if ((verb === "PUT" || verb === "DELETE") && /^\/projects\/[^/]+\/pools\/[^/]+\/slots\/[^/]+\/pin$/.test(route))
41
+ return strings("reason");
42
+ if (verb === "POST" && /^\/projects\/[^/]+\/pools\/[^/]+\/slots\/[^/]+\/(suspend|restore)$/.test(route))
43
+ return strings("reason", "note");
38
44
  if (verb === "PUT" && /^\/projects\/[^/]+\/process$/.test(route)) {
39
45
  if (fields.dry_run === true)
40
46
  return [];
@@ -276,7 +282,7 @@ export class Client {
276
282
  * by the hook or the watcher, which say nothing about whether the agent is alive.
277
283
  */
278
284
  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 });
285
+ const auto = collectAuto({ model, machine: machineIdentityForAgent(c.machine), effort: resolveEffort(opts.effort, process.env, c.vendor), provider: process.env.BSCHAT_PROVIDER });
280
286
  return new Client(c.url, c.key, opts.presence === false ? null : { ...auto }, c.agent, opts.machineIdentity ? auto.machine : null);
281
287
  }
282
288
  static forAdmin(c) {
@@ -18,6 +18,7 @@ import { projectImageAdmin } from "./image-admin.js";
18
18
  import { environmentAdmin } from "./environment-admin.js";
19
19
  import { flowAdmin } from "./flow.js";
20
20
  import { projectSecrets } from "./project-secrets.js";
21
+ import { standingRuleAdmin } from "./standing-rules.js";
21
22
  function adminClient(p) {
22
23
  return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
23
24
  }
@@ -97,6 +98,8 @@ export async function admin(p, out) {
97
98
  return keysAdmin(action, rest, p, out);
98
99
  case "process":
99
100
  return processAdmin(action, rest, p, out);
101
+ case "rule":
102
+ return standingRuleAdmin(action, rest, p, out);
100
103
  case "routing":
101
104
  return routingAdmin(action, rest, p, out);
102
105
  case "milestones": {
@@ -8,6 +8,7 @@ import { CliError } from "../errors.js";
8
8
  import { defaultMachine } from "../git.js";
9
9
  import { fmtMessage, fmtStatus, table } from "../output.js";
10
10
  import { readState, writeState } from "../state.js";
11
+ import { formatStandingRuleSummary } from "../standing-rules.js";
11
12
  function agentClient(p) {
12
13
  const name = resolveAgentName(str(p.flags, "as"));
13
14
  const creds = loadAgent(name);
@@ -72,6 +73,7 @@ export async function me(p, out) {
72
73
  r.role?.description ? `\n${r.role.description}\n` : "",
73
74
  `permissions: post=${r.permissions.post_channels.join(",")} broadcast=${r.permissions.broadcast} create_channels=${r.permissions.create_channels} read_account_status=${r.permissions.read_account_status}`,
74
75
  r.scope === "account" ? `tip: project commands take --project <name> (or BSCHAT_PROJECT)` : `channels: ${r.channels.map((c) => `#${c.name}`).join(" ")}`,
76
+ `standing rules:\n${formatStandingRuleSummary(r.standing_rules)}`,
75
77
  ];
76
78
  out.print(lines.join("\n"), r);
77
79
  }
@@ -10,6 +10,7 @@ import { goalFromClaudeTranscript, modelFromClaudeTranscript } from "../model.js
10
10
  import { bindSession, conversationAgent, sessionAgent, sessionsOf, syncFromWatchers } from "../sessions.js";
11
11
  import { fetchRecoveryBrief, formatOutcomeMeasures, formatRecoveryBrief, outcomeMeasureSnapshot, recoveryBriefUnavailableText } from "../brief.js";
12
12
  import { changedNotices, commandNoticeWarning, normalizeShellCommand } from "../notices.js";
13
+ import { formatStandingRuleSet, ruleAcknowledgmentTargets } from "../standing-rules.js";
13
14
  const HEARTBEAT_MS = 60_000;
14
15
  /** Reads the harness's hook payload from stdin without blocking when there is none. */
15
16
  function readStdinJson() {
@@ -136,8 +137,9 @@ export function formatHookDelivery(u, standing) {
136
137
  text = rendered.text;
137
138
  by_kind = rendered.by_kind;
138
139
  }
139
- const acknowledge = !!standing?.acknowledge && text.includes(standing.text) && standing.text !== standing.deferredText;
140
- return { text, by_kind, acknowledge };
140
+ const complete = !!standing && text.includes(standing.text) && standing.text !== standing.deferredText;
141
+ const acknowledge = complete && standing.acknowledge;
142
+ return { text, by_kind, acknowledge, complete };
141
143
  }
142
144
  /**
143
145
  * Collects everything new for an identity and advances its cursors. Returns null when nothing
@@ -420,9 +422,9 @@ export function claudeSessionBound(ref, sid, cwd, allowAutoBind = false) {
420
422
  export async function hook(p, payload) {
421
423
  const harness = p.positionals[1] ?? "plain";
422
424
  if (harness === "antigravity")
423
- return antigravityHook(p);
425
+ return antigravityHook(p, payload);
424
426
  if (harness === "codex")
425
- return codexHook(p);
427
+ return codexHook(p, payload);
426
428
  const event = str(p.flags, "event") ?? (harness === "claude-code" ? "UserPromptSubmit" : "");
427
429
  let name;
428
430
  try {
@@ -481,7 +483,7 @@ export async function hook(p, payload) {
481
483
  // version, and record that it was shown.
482
484
  const compacted = input?.source === "compact";
483
485
  const standing = harness === "claude-code" && event === "SessionStart"
484
- ? compacted ? await recoveryBrief(name) : await standingRules(name, false)
486
+ ? await standingRules(name, compacted)
485
487
  : null;
486
488
  // The hook firing is proof the harness is working; tell the server, at most once a minute.
487
489
  // The session goal (/goal) rides along from the transcript, and a change goes out at once.
@@ -512,12 +514,12 @@ export async function hook(p, payload) {
512
514
  else {
513
515
  process.stdout.write(text + "\n");
514
516
  }
515
- await acknowledgeStanding(name, standing, formatted.acknowledge);
517
+ await acknowledgeStanding(name, standing, formatted.complete);
516
518
  }
517
519
  /** After compaction, restore agent-specific state instead of repeating the standing agreements. */
518
- export async function recoveryBrief(name) {
520
+ export async function recoveryBrief(name, includeStandingRules = true) {
519
521
  try {
520
- const text = formatRecoveryBrief(await fetchRecoveryBrief(name));
522
+ const text = formatRecoveryBrief(await fetchRecoveryBrief(name), includeStandingRules);
521
523
  return { text, deferredText: text, acknowledge: false, version: 0, project: null };
522
524
  }
523
525
  catch (e) {
@@ -529,32 +531,63 @@ export async function recoveryBrief(name) {
529
531
  * The role and process the agent must hold after a new session or a compaction, when it has not
530
532
  * seen this process version (or always after a compaction). Records that it was shown.
531
533
  */
532
- async function standingRules(name, compacted) {
534
+ export async function standingRules(name, compacted) {
533
535
  try {
534
536
  const creds = loadAgent(name);
535
537
  const me = await Client.forAgent(creds, undefined, { presence: false }).call("GET", "/me");
536
538
  const proc = me.process;
539
+ const rules = me.standing_rules;
540
+ const ruleAcks = rules ? ruleAcknowledgmentTargets(rules, creds.project ?? undefined) : [];
541
+ const rulesText = Array.isArray(rules?.rulesets)
542
+ ? rules.rulesets.map((set) => formatStandingRuleSet(set, set.project ?? "account")).join("\n")
543
+ : formatStandingRuleSet(rules, me.project?.name ?? undefined);
544
+ const rulesComplete = rules?.complete === true && (Array.isArray(rules.rulesets)
545
+ ? rules.rulesets.every((set) => set.complete !== false && Array.isArray(set.rules))
546
+ : Array.isArray(rules.rules));
547
+ const ruleText = rulesComplete ? rulesText : "[b9s] Standing rule delivery is incomplete. Run b9s process to retrieve the complete current set; it was not acknowledged.";
537
548
  if (!proc)
538
- return null;
549
+ return { text: ruleText, deferredText: "[b9s] Standing rules could not be fully delivered. Run b9s process.", acknowledge: false, version: 0, project: null, ruleAcks: rulesComplete ? ruleAcks : [] };
539
550
  const roleIdentity = me.role ? `Your role: ${me.role.name}.` : `You hold no role in ${me.project?.name ?? "this project"}.`;
540
551
  const roleLine = me.role ? `${roleIdentity} ${me.role.description}` : roleIdentity;
541
- const rendered = renderStandingRules(proc, roleLine, compacted, roleIdentity);
542
- return { ...rendered, version: proc.version, project: creds.project };
552
+ const rendered = compacted
553
+ ? await recoveryBrief(name, false)
554
+ : { ...renderStandingRules(proc, roleLine, false, roleIdentity), version: proc.version, project: creds.project };
555
+ const text = `${ruleText}\n\n${rendered.text}`;
556
+ const deferredText = `[b9s] Standing rules or process context could not be fully delivered. Run b9s process to retrieve the complete current set; it was not acknowledged.`;
557
+ return { text, deferredText, acknowledge: !compacted && rendered.acknowledge, version: proc.version, project: creds.project, ruleAcks: rulesComplete ? ruleAcks : [] };
543
558
  }
544
559
  catch (e) {
545
560
  process.stderr.write(`b9s: could not fetch role/process: ${e.message}\n`);
546
- return null;
561
+ const deferredText = "[b9s] Standing rules and process could not be fetched. Run b9s process; no ruleset was acknowledged.";
562
+ return { text: deferredText, deferredText, acknowledge: false, version: 0, project: null, ruleAcks: [] };
547
563
  }
548
564
  }
549
- async function acknowledgeStanding(name, standing, emittedFullRules) {
550
- if (!standing || !emittedFullRules || !standing.acknowledge || !standing.project || standing.version <= 0)
565
+ export async function acknowledgeStanding(name, standing, emittedFullRules) {
566
+ if (!standing || !emittedFullRules)
551
567
  return;
568
+ let creds;
552
569
  try {
553
- const creds = loadAgent(name);
554
- await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/projects/${standing.project}/process/ack`, { version: standing.version });
570
+ creds = loadAgent(name);
555
571
  }
556
572
  catch (e) {
557
- process.stderr.write(`b9s: could not acknowledge process rules: ${e.message}\n`);
573
+ process.stderr.write(`b9s: could not load identity for standing-rule acknowledgment: ${e.message}\n`);
574
+ return;
575
+ }
576
+ if (standing.acknowledge && standing.project && standing.version > 0) {
577
+ try {
578
+ await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/projects/${standing.project}/process/ack`, { version: standing.version });
579
+ }
580
+ catch (e) {
581
+ process.stderr.write(`b9s: could not acknowledge process rules: ${e.message}\n`);
582
+ }
583
+ }
584
+ for (const target of standing.ruleAcks ?? []) {
585
+ try {
586
+ await Client.forAgent(creds, undefined, { presence: false }).call("POST", target.path, { fingerprint: target.fingerprint, delivered: true });
587
+ }
588
+ catch (e) {
589
+ process.stderr.write(`b9s: could not acknowledge standing-rule set: ${e.message}\n`);
590
+ }
558
591
  }
559
592
  }
560
593
  export function renderStandingRules(proc, roleLine, compacted, roleIdentity) {
@@ -594,10 +627,10 @@ export function renderStandingRules(proc, roleLine, compacted, roleIdentity) {
594
627
  * The agent is found by the conversation, never the workspace (several Antigravity agents share
595
628
  * one). Always prints valid JSON and exits 0: a hook must never break the session.
596
629
  */
597
- async function antigravityHook(p) {
630
+ async function antigravityHook(p, payload) {
598
631
  const event = str(p.flags, "event") ?? "";
599
632
  const out = (o) => { process.stdout.write(JSON.stringify(o) + "\n"); };
600
- const input = readStdinJson();
633
+ const input = payload === undefined ? readStdinJson() : payload;
601
634
  const conv = typeof input?.conversationId === "string" ? input.conversationId : null;
602
635
  let ref = conv ? conversationAgent(conv) : null;
603
636
  if (conv && !ref) {
@@ -660,7 +693,7 @@ async function antigravityHook(p) {
660
693
  if (formatted.text)
661
694
  await reportDelivery(name, formatted.text, formatted.by_kind);
662
695
  out(formatted.text ? { injectSteps: [{ systemMessage: { systemMessage: formatted.text } }] } : {});
663
- await acknowledgeStanding(name, standing, formatted.acknowledge);
696
+ await acknowledgeStanding(name, standing, formatted.complete);
664
697
  }
665
698
  /**
666
699
  * Codex's hooks (~/.codex/hooks.json, written by `b9s codex hooks`; Claude Code's format):
@@ -671,9 +704,9 @@ async function antigravityHook(p) {
671
704
  * `b9s codex bind`); any other Codex session (the user's own chats) gets nothing.
672
705
  * Always exits 0 with valid output: a hook must never break the session.
673
706
  */
674
- async function codexHook(p) {
707
+ async function codexHook(p, payload) {
675
708
  const event = str(p.flags, "event") ?? "";
676
- const input = readStdinJson();
709
+ const input = payload === undefined ? readStdinJson() : payload;
677
710
  const sid = typeof input?.session_id === "string" ? input.session_id : null;
678
711
  let ref = sid ? sessionAgent("codex", sid) : null;
679
712
  if (sid && !ref) {
@@ -736,7 +769,7 @@ async function codexHook(p) {
736
769
  await reportDelivery(name, formatted.text, formatted.by_kind);
737
770
  if (formatted.text)
738
771
  context(formatted.text);
739
- await acknowledgeStanding(name, standing, formatted.acknowledge);
772
+ await acknowledgeStanding(name, standing, formatted.complete);
740
773
  }
741
774
  /** Records where this agent's harness session writes, so `wu submit` can read its token counts. */
742
775
  function noteSession(name, harness, transcript, sessionId, compacted = false) {
@@ -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
  }