benignswarm 0.12.38 → 0.12.39

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
@@ -1,7 +1,7 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
3
  export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on"];
4
- export const BOOL_FLAGS = ["json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve"];
4
+ export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve"];
5
5
  export function parse(argv) {
6
6
  const options = {};
7
7
  for (const f of STRING_FLAGS)
@@ -0,0 +1,143 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
3
+ import { delimiter, join } from "node:path";
4
+ import { bool } from "../args.js";
5
+ import { CliError } from "../errors.js";
6
+ import { binVersion, ensureInstall, latestPublished, readInstall, restartLaunchAgent, watcherPlists } from "../install.js";
7
+ import { CLI_VERSION } from "../version.js";
8
+ /**
9
+ * bschat install [<version> | --latest] make or upgrade this machine's one bschat install and
10
+ * restart the watchers that run it
11
+ */
12
+ export async function install(p, out) {
13
+ const prev = readInstall();
14
+ const want = p.positionals[1];
15
+ if (want && !/^\d+\.\d+\.\d+$/.test(want))
16
+ throw new CliError("usage", "install [<version> | --latest] e.g. bschat install --latest, bschat install 0.12.38");
17
+ const npm = prev?.npm && existsSync(prev.npm) ? prev.npm : undefined;
18
+ const version = want ?? (bool(p.flags, "latest") ? latestPublished(npm ?? join(process.execPath, "..", "npm")) : CLI_VERSION);
19
+ const rec = ensureInstall(version, (m) => process.stderr.write(`bschat: ${m}\n`), npm);
20
+ const lines = [`bschat ${rec.version} is this machine's install: ${rec.bin}`];
21
+ if (prev && prev.bin !== rec.bin)
22
+ lines.push(`(was ${prev.bin}; run bschat doctor to find hooks and watchers still pointing there)`);
23
+ const restarted = [];
24
+ const elsewhere = [];
25
+ if (!bool(p.flags, "no-restart")) {
26
+ for (const w of watcherPlists()) {
27
+ const program = plistJson(w.path)?.ProgramArguments?.[0];
28
+ if (program !== rec.bin) {
29
+ elsewhere.push(`${w.label} runs ${program ?? "(unreadable plist)"}`);
30
+ continue;
31
+ }
32
+ if (restartLaunchAgent(w.label))
33
+ restarted.push(w.label);
34
+ else
35
+ elsewhere.push(`${w.label} is not loaded (bschat doctor shows how to load it)`);
36
+ }
37
+ }
38
+ if (restarted.length)
39
+ lines.push(`Restarted ${restarted.length} watcher${restarted.length === 1 ? "" : "s"} on it: ${restarted.map((l) => l.replace("org.benignswarm.watch.", "")).join(", ")}`);
40
+ if (elsewhere.length)
41
+ lines.push(`Not restarted:\n ${elsewhere.join("\n ")}`);
42
+ out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere });
43
+ }
44
+ /**
45
+ * bschat doctor every bschat on this machine and who uses which: the recorded install, copies on
46
+ * PATH, npx caches, this repo's hook and instructions, and each watcher (plist versus
47
+ * what launchd is actually running). Read-only; prints the fix for each problem.
48
+ */
49
+ export async function doctor(_p, out) {
50
+ const checks = [];
51
+ const rec = readInstall();
52
+ const recVersion = rec && existsSync(rec.bin) ? binVersion(rec.bin) : null;
53
+ if (!rec)
54
+ checks.push({ ok: false, what: "no recorded install: hooks and watchers have no one bschat to run", fix: "npx -y benignswarm install" });
55
+ else if (!recVersion)
56
+ checks.push({ ok: false, what: `recorded install ${rec.bin} does not run`, fix: "npx -y benignswarm install" });
57
+ else
58
+ checks.push({ ok: true, what: `recorded install: ${rec.bin} (${recVersion})` });
59
+ // Every bschat on PATH, the one the shell finds first marked.
60
+ const seen = new Set();
61
+ const onPath = [];
62
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
63
+ const f = join(dir, "bschat");
64
+ try {
65
+ accessSync(f, constants.X_OK);
66
+ }
67
+ catch {
68
+ continue;
69
+ }
70
+ const real = realpathSync(f);
71
+ if (seen.has(real))
72
+ continue;
73
+ seen.add(real);
74
+ onPath.push({ path: f, real, version: binVersion(f) });
75
+ }
76
+ if (!onPath.length)
77
+ checks.push({ ok: false, what: "no bschat on this shell's PATH", fix: rec ? `add ${join(rec.bin, "..")} to PATH, or call ${rec.bin}` : "npx -y benignswarm install" });
78
+ onPath.forEach((b, i) => {
79
+ const isRec = !!rec && realpathSync(rec.bin) === b.real;
80
+ checks.push({ ok: isRec || i > 0, what: `on PATH${i === 0 ? " (first)" : ""}: ${b.path} (${b.version ?? "does not run"})${isRec ? " = the recorded install" : ""}`, fix: !isRec && i === 0 && rec ? `this shell runs a different bschat than hooks and watchers; put ${join(rec.bin, "..")} first on PATH, or remove this copy` : undefined });
81
+ });
82
+ // npx caches: only used by commands that still say npx.
83
+ const cache = spawnSync(join(process.execPath, "..", "npm"), ["config", "get", "cache"], { encoding: "utf8" }).stdout?.trim();
84
+ const npx = cache && existsSync(join(cache, "_npx")) ? readdirSync(join(cache, "_npx")).map((d) => join(cache, "_npx", d, "node_modules", "benignswarm", "package.json")).filter(existsSync).map((f) => JSON.parse(readFileSync(f, "utf8")).version) : [];
85
+ if (npx.length)
86
+ checks.push({ ok: true, what: `npx caches hold ${npx.length} cop${npx.length === 1 ? "y" : "ies"} (${[...new Set(npx)].sort().join(", ")}); only commands that still say npx use them` });
87
+ // This repo's hook and instructions.
88
+ const root = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8" }).stdout?.trim() || process.cwd();
89
+ const sp = join(root, ".claude", "settings.local.json");
90
+ if (existsSync(sp)) {
91
+ const hooks = JSON.stringify(JSON.parse(readFileSync(sp, "utf8")).hooks ?? {});
92
+ const cmds = [...new Set([...hooks.matchAll(/"command":"([^"]*hook claude-code[^"]*)"/g)].map((m) => m[1].replace(/ --event \w+$/, "")))];
93
+ for (const c of cmds) {
94
+ const good = !!rec && (c === rec.bin || c === `'${rec.bin}'` || c.startsWith(`${rec.bin} `));
95
+ checks.push({ ok: good, what: `Claude Code hook in ${sp}: ${c}`, fix: good ? undefined : "bschat setup --as <your agent> (rewrites the hook to the recorded install)" });
96
+ }
97
+ }
98
+ for (const f of ["AGENTS.md", "GEMINI.md", join(".agents", "rules", "bschat.md")]) {
99
+ const fp = join(root, f);
100
+ if (existsSync(fp) && readFileSync(fp, "utf8").includes("npx -y benignswarm"))
101
+ checks.push({ ok: false, what: `${fp} tells agents to use npx`, fix: "bschat setup --as <the agent of that harness> (rewrites it to the recorded install)" });
102
+ }
103
+ // Watchers: what the plist says versus what launchd is running.
104
+ const uid = process.getuid?.();
105
+ for (const w of watcherPlists()) {
106
+ const pj = plistJson(w.path);
107
+ const args = pj?.ProgramArguments ?? [];
108
+ const short = w.label.replace("org.benignswarm.watch.", "");
109
+ const reload = `launchctl bootout gui/${uid}/${w.label}; launchctl bootstrap gui/${uid} ${w.path}`;
110
+ if (!args.length) {
111
+ checks.push({ ok: false, what: `watcher ${short}: unreadable plist ${w.path}` });
112
+ continue;
113
+ }
114
+ const listed = spawnSync("launchctl", ["list", w.label], { encoding: "utf8" });
115
+ const pid = /"PID" = (\d+);/.exec(listed.stdout ?? "")?.[1];
116
+ const ver = binVersion(args[0]);
117
+ if (rec && args[0] !== rec.bin)
118
+ checks.push({ ok: false, what: `watcher ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its bschat watch ... --launchd (it uses the recorded install and reloads)" });
119
+ if (listed.status !== 0) {
120
+ 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)` });
121
+ continue;
122
+ }
123
+ if (!pid) {
124
+ checks.push({ ok: false, what: `watcher ${short} is loaded but not running; see ~/.bschat/logs/watch.${short}.err.log`, fix: reload });
125
+ continue;
126
+ }
127
+ const running = (spawnSync("ps", ["-o", "command=", "-p", pid], { encoding: "utf8" }).stdout ?? "").trim();
128
+ const tail = args.slice(1).join(" ");
129
+ if (!running.endsWith(tail))
130
+ checks.push({ ok: false, what: `watcher ${short} is running an older definition than its plist (launchd was never reloaded)\n plist: ${tail}\n running: ${running}`, fix: reload });
131
+ else
132
+ checks.push({ ok: true, what: `watcher ${short}: running ${args[0]} (${ver ?? "?"})` });
133
+ }
134
+ const problems = checks.filter((c) => !c.ok);
135
+ const text = checks.map((c) => `${c.ok ? "ok " : "PROBLEM "} ${c.what}${c.fix ? `\n fix: ${c.fix}` : ""}`).join("\n") + `\n${problems.length ? `${problems.length} problem${problems.length === 1 ? "" : "s"}.` : "No problems."}`;
136
+ out.print(text, { install: rec, checks, problems: problems.length });
137
+ if (problems.length)
138
+ process.exitCode = 1;
139
+ }
140
+ function plistJson(path) {
141
+ const r = spawnSync("plutil", ["-convert", "json", "-o", "-", path], { encoding: "utf8" });
142
+ return r.status === 0 ? JSON.parse(r.stdout) : null;
143
+ }
@@ -6,6 +6,7 @@ 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 } from "../install.js";
9
10
  import { HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
10
11
  import { detectVendor } from "../vendor.js";
11
12
  function repoRoot() {
@@ -39,14 +40,15 @@ export async function setup(p, out) {
39
40
  const vendor = normalizeVendor(str(p.flags, "vendor") ?? creds.vendor);
40
41
  const root = str(p.flags, "dir") ?? repoRoot();
41
42
  const model = resolveModel(str(p.flags, "model"), process.env, process.cwd(), ref);
43
+ const inst = machineInstall();
42
44
  const idPath = writeIdentity(root, vendor, creds.agent, model, bool(p.flags, "replace"), creds.project);
43
45
  const files = await fetchSkill(creds.url);
44
46
  const written = [];
45
47
  for (const h of harnessList(p, vendor))
46
- written.push(...installForHarness(root, h, files, ref, creds.url));
48
+ written.push(...installForHarness(root, h, files, ref, creds.url, inst.bin));
47
49
  const uniq = [...new Set(written)];
48
50
  const selfTest = harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
49
- out.print(`Recorded ${vendor} -> ${ref} in ${idPath}\nWrote: ${uniq.join(", ")}${selfTest ? `\n${selfTest}` : ""}`, { identity: idPath, written: uniq, hook_verified: !!selfTest });
51
+ out.print(`bschat ${inst.version} for this machine: ${inst.bin}\nRecorded ${vendor} -> ${ref} in ${idPath}\nWrote: ${uniq.join(", ")}${selfTest ? `\n${selfTest}` : ""}`, { install: inst, identity: idPath, written: uniq, hook_verified: !!selfTest });
50
52
  }
51
53
  export async function join(p, out) {
52
54
  const name = str(p.flags, "as") ?? process.env.BSCHAT_AGENT;
@@ -70,6 +72,8 @@ export async function join(p, out) {
70
72
  const noBind = bool(p.flags, "no-bind");
71
73
  if (!noBind)
72
74
  writeIdentityDryRun(root, vendor, name, bool(p.flags, "replace"));
75
+ // The machine's one bschat install comes first: if it cannot be made, the token is not spent.
76
+ const inst = machineInstall();
73
77
  let res;
74
78
  try {
75
79
  res = await fetch(`${url}/enroll`, { method: "POST", headers: { "content-type": "application/json", "user-agent": `bschat-cli/${CLI_VERSION}` }, body: JSON.stringify({ token, name, vendor, machine }) });
@@ -88,7 +92,7 @@ export async function join(p, out) {
88
92
  if (!bool(p.flags, "no-skill") && !noBind) {
89
93
  const files = await fetchSkill(url);
90
94
  for (const h of harnessList(p, vendor))
91
- written.push(...installForHarness(root, h, files, ref, url));
95
+ written.push(...installForHarness(root, h, files, ref, url, inst.bin));
92
96
  written = [...new Set(written)];
93
97
  }
94
98
  const selfTest = !noBind && !bool(p.flags, "no-skill") && harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
@@ -97,6 +101,7 @@ export async function join(p, out) {
97
101
  ? `Joined project "${json.project.name}" as agent "${name}" (${vendor})${json.agent.role_name ? ` with role ${json.agent.role_name}` : ""}.`
98
102
  : `Joined as account-wide agent "${name}" (${vendor}) with role ${json.agent.role_name}. Project commands take --project <name>; see them with: bschat me`,
99
103
  `Credentials saved to ${path} (private to this machine).`,
104
+ `bschat ${inst.version} is installed for this machine at ${inst.bin}; the hook, the repo instructions and watchers all use it. Upgrade with: bschat install --latest`,
100
105
  noBind
101
106
  ? `This repo's ${vendor} identity was left as is. Address yourself on every call: \`bschat --as ${ref} <command>\` or \`BSCHAT_AGENT=${ref} bschat <command>\`. Never run bare bschat here as ${name}.`
102
107
  : `This repo now maps ${vendor} -> ${ref} in ${idPath}, so bschat commands here know who you are, even after a reboot.`,
@@ -112,7 +117,7 @@ export async function join(p, out) {
112
117
  vendor !== "claude-code" ? `No hook exists for ${vendor}: you will not be told about replies unless you run a watcher. See the skill's "Knowing when someone talks to you" section (bschat watch --launchd).` : null,
113
118
  `Next: bschat me && bschat who && bschat inbox && bschat handoffs --open`,
114
119
  ].filter((l) => l !== null).join("\n");
115
- out.print(human, { agent: json.agent, project: json.project, saved: path, identity: idPath, bound: !noBind, written, revived: !!json.revived, resume: json.resume ?? null, export: { BSCHAT_AGENT: ref } });
120
+ out.print(human, { install: inst, agent: json.agent, project: json.project, saved: path, identity: idPath, bound: !noBind, written, revived: !!json.revived, resume: json.resume ?? null, export: { BSCHAT_AGENT: ref } });
116
121
  }
117
122
  /**
118
123
  * Runs the hook command exactly as Claude Code will, with the settings file's own env, and
@@ -132,6 +137,10 @@ function verifyClaudeHook(root, ref) {
132
137
  }
133
138
  return `Hook verified: ran "${cmd}" successfully as ${ref}.`;
134
139
  }
140
+ /** This machine's one install, at least this CLI's version (installed or upgraded when needed). */
141
+ function machineInstall() {
142
+ return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`bschat: ${m}\n`));
143
+ }
135
144
  function writeIdentityDryRun(root, vendor, name, replace) {
136
145
  const p = findIdentityFile(root);
137
146
  if (!p || !p.startsWith(root))
@@ -1,4 +1,5 @@
1
- import { spawn, spawnSync } from "node:child_process";
1
+ import { spawn } from "node:child_process";
2
+ import { reloadLaunchAgent, requireInstall } from "../install.js";
2
3
  import { mkdirSync, writeFileSync } from "node:fs";
3
4
  import { homedir } from "node:os";
4
5
  import { join } from "node:path";
@@ -304,13 +305,9 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
304
305
  const logDir = join(homedir(), ".bschat", "logs");
305
306
  mkdirSync(dir, { recursive: true });
306
307
  mkdirSync(logDir, { recursive: true });
307
- // Never bake in the path of the copy that is running: it may be an npx cache that is frozen at
308
- // this version. Prefer a global install on PATH; fall back to this copy only if none exists.
309
- const which = spawnSync("sh", ["-c", "command -v bschat"], { encoding: "utf8" });
310
- const globalCli = which.status === 0 ? which.stdout.trim() : "";
311
- const program = globalCli && !globalCli.includes("/_npx/") ? [globalCli] : [process.execPath, process.argv[1]];
312
- if (program.length > 1)
313
- process.stderr.write(`bschat: no global install found; the LaunchAgent will run ${process.argv[1]} and will not pick up upgrades. Install with: npm i -g benignswarm\n`);
308
+ // The machine's one recorded install, never the running copy (an npx cache frozen at this
309
+ // version) or whatever `bschat` a PATH lookup finds: an upgrade must reach every watcher.
310
+ const program = [requireInstall().bin];
314
311
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
315
312
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
316
313
  <plist version="1.0"><dict>
@@ -334,7 +331,10 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
334
331
  `;
335
332
  const path = join(dir, `${label}.plist`);
336
333
  writeFileSync(path, plist);
337
- out.print(`Wrote ${path}${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStart it: launchctl bootstrap gui/$(id -u) ${path}\nStop it: launchctl bootout gui/$(id -u)/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label });
334
+ // Load it from the file now, replacing a running copy: writing a plist changes nothing launchd
335
+ // has loaded, and a watcher re-pointed at a new session kept waking the old one for two days.
336
+ reloadLaunchAgent(label, path);
337
+ out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout gui/$(id -u)/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: bschat doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
338
338
  }
339
339
  function escapeXml(s) {
340
340
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
package/dist/harness.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { shellPath } from "./install.js";
2
3
  import { dirname, join } from "node:path";
3
4
  import { CliError } from "./errors.js";
4
5
  /** Canonical vendor ids and the aliases people type. */
@@ -81,15 +82,17 @@ export function upsertBlock(path, body) {
81
82
  else
82
83
  writeFileSync(path, (cur.endsWith("\n") || cur === "" ? cur : cur + "\n") + "\n" + block);
83
84
  }
84
- function pointer(_name, apiUrl) {
85
+ function pointer(_name, apiUrl, bin) {
85
86
  return [
86
87
  `## bschat: agent chat for this project`,
87
88
  ``,
88
- `This repo's agents coordinate on BenignSwarm. Your identity for this repo is recorded in`,
89
- `\`.bschat/identity.json\` (vendor -> agent name); the CLI reads it, so \`npx -y benignswarm <cmd>\``,
90
- `works without env vars. If you are told you are a different agent, export BSCHAT_AGENT=<project>/<name>.`,
89
+ `This repo's agents coordinate on BenignSwarm with the \`bschat\` command, installed on this`,
90
+ `machine at \`${bin}\` (use that path if \`bschat\` is not on your PATH; do not install another copy,`,
91
+ `and do not use npx). Your identity for this repo is recorded in \`.bschat/identity.json\``,
92
+ `(vendor -> agent name), so it works without env vars. If you are told you are a different agent,`,
93
+ `export BSCHAT_AGENT=<project>/<name>.`,
91
94
  ``,
92
- `Start of session: \`npx -y benignswarm me\`, \`npx -y benignswarm who\`, \`npx -y benignswarm inbox\`.`,
95
+ `Start of session: \`bschat me\`, \`bschat who\`, \`bschat inbox\`.`,
93
96
  `Full instructions: \`.bschat/SKILL.md\` in this repo, or ${apiUrl}/skill.`,
94
97
  ].join("\n");
95
98
  }
@@ -97,7 +100,7 @@ function pointer(_name, apiUrl) {
97
100
  * Writes the files a given harness needs to discover bschat in this repo.
98
101
  * Returns the paths written. Each writer is idempotent.
99
102
  */
100
- export function installForHarness(root, harness, files, agentName, apiUrl) {
103
+ export function installForHarness(root, harness, files, agentName, apiUrl, bin) {
101
104
  const written = [];
102
105
  const neutral = join(root, ".bschat");
103
106
  mkdirSync(join(neutral, "references"), { recursive: true });
@@ -124,7 +127,7 @@ export function installForHarness(root, harness, files, agentName, apiUrl) {
124
127
  }
125
128
  }
126
129
  const env = { ...(settings.env ?? {}), BSCHAT_AGENT: agentName };
127
- const hooks = withBschatHooks(settings.hooks ?? {});
130
+ const hooks = withBschatHooks(settings.hooks ?? {}, bin);
128
131
  writeFileSync(sp, JSON.stringify({ ...settings, env, hooks }, null, 2) + "\n");
129
132
  written.push(sp);
130
133
  break;
@@ -135,20 +138,20 @@ export function installForHarness(root, harness, files, agentName, apiUrl) {
135
138
  case "copilot":
136
139
  case "cursor": {
137
140
  const p = join(root, "AGENTS.md");
138
- upsertBlock(p, pointer(agentName, apiUrl));
141
+ upsertBlock(p, pointer(agentName, apiUrl, bin));
139
142
  written.push(p);
140
143
  break;
141
144
  }
142
145
  case "antigravity": {
143
146
  const p = join(root, ".agents", "rules", "bschat.md");
144
147
  mkdirSync(dirname(p), { recursive: true });
145
- writeFileSync(p, `---\ntrigger: always_on\ndescription: "How to use bschat, the agent chat for this project"\n---\n\n${pointer(agentName, apiUrl)}\n`);
148
+ writeFileSync(p, `---\ntrigger: always_on\ndescription: "How to use bschat, the agent chat for this project"\n---\n\n${pointer(agentName, apiUrl, bin)}\n`);
146
149
  written.push(p);
147
150
  break;
148
151
  }
149
152
  case "gemini-cli": {
150
153
  const p = join(root, "GEMINI.md");
151
- upsertBlock(p, pointer(agentName, apiUrl));
154
+ upsertBlock(p, pointer(agentName, apiUrl, bin));
152
155
  written.push(p);
153
156
  break;
154
157
  }
@@ -158,21 +161,23 @@ export function installForHarness(root, harness, files, agentName, apiUrl) {
158
161
  return written;
159
162
  }
160
163
  const HOOK_MARK = "hook claude-code";
161
- /** `npx -y benignswarm` already runs the package's `bschat` binary; the subcommand follows directly. */
162
- const hookCommand = (event) => `npx -y benignswarm ${HOOK_MARK} --event ${event}`;
163
- /** Versions 0.7.x–0.9.0 wrote `npx -y benignswarm bschat hook ...`, which the CLI rejected as an unknown command. */
164
- const BROKEN_HOOK = /^npx -y benignswarm bschat hook claude-code\b/;
165
- /** Adds the inbox hook to SessionStart, UserPromptSubmit and PostToolUse without duplicating or touching other hooks. */
166
- export function withBschatHooks(hooks) {
164
+ /** The hook runs this machine's recorded install by absolute path: no npx, no PATH lookup. */
165
+ const hookCommand = (bin, event) => `${shellPath(bin)} ${HOOK_MARK} --event ${event}`;
166
+ /**
167
+ * Adds the inbox hook to SessionStart, UserPromptSubmit, PostToolUse and PostModelSwitch without
168
+ * touching other hooks. An existing bschat hook (an npx form, an older install's path, or the
169
+ * 0.7.x–0.9.0 `npx -y benignswarm bschat hook` that never ran) is rewritten to this install.
170
+ */
171
+ export function withBschatHooks(hooks, bin) {
167
172
  const out = { ...hooks };
168
173
  for (const event of ["SessionStart", "UserPromptSubmit", "PostToolUse", "PostModelSwitch"]) {
169
174
  const list = (out[event] ?? []).map((g) => ({
170
175
  ...g,
171
- hooks: (g.hooks ?? []).map((h) => (typeof h.command === "string" && BROKEN_HOOK.test(h.command) ? { ...h, command: hookCommand(event) } : h)),
176
+ hooks: (g.hooks ?? []).map((h) => (typeof h.command === "string" && h.command.includes(HOOK_MARK) ? { ...h, command: hookCommand(bin, event) } : h)),
172
177
  }));
173
178
  const already = list.some((g) => (g.hooks ?? []).some((h) => typeof h.command === "string" && h.command.includes(HOOK_MARK)));
174
179
  if (!already)
175
- list.push({ matcher: "", hooks: [{ type: "command", command: hookCommand(event), timeout: 20 }] });
180
+ list.push({ matcher: "", hooks: [{ type: "command", command: hookCommand(bin, event), timeout: 20 }] });
176
181
  out[event] = list;
177
182
  }
178
183
  return out;
package/dist/help.js CHANGED
@@ -100,6 +100,10 @@ Agent commands
100
100
  --env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
101
101
  ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once / --launchd.
102
102
  Codex: bschat watch --exec "codex queue --thread <id> --message {summary}" --launchd
103
+ bschat install [<version> | --latest] make or upgrade this machine's one bschat (join does it once) and restart
104
+ the watchers on it; hooks, repo instructions and watchers all run its path
105
+ bschat doctor every bschat on this machine and who runs which (PATH, npx caches, this repo's
106
+ hook and instructions, each watcher's plist versus what launchd runs), with fixes
103
107
  bschat wake ack [<n>] acknowledge your watcher's wake-up #n first thing (no n: the one pending here)
104
108
  Liveness: the watcher reports harness activity (Codex rollout / Antigravity conversation
105
109
  found from the session id in --exec, or --activity <file-or-dir>) so you are not shown
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import { watch } from "./commands/watch.js";
10
10
  import { feedback } from "./commands/feedback.js";
11
11
  import { goal } from "./commands/goal.js";
12
12
  import { wake } from "./commands/wake.js";
13
+ import { doctor, install } from "./commands/install.js";
13
14
  import { processCmd, record, wu, milestones, milestone, lock, askOperator } from "./commands/wu.js";
14
15
  import { worktrees } from "./commands/worktrees.js";
15
16
  import { CliError } from "./errors.js";
@@ -47,6 +48,8 @@ const COMMANDS = {
47
48
  feedback,
48
49
  goal,
49
50
  wake,
51
+ install,
52
+ doctor,
50
53
  wu,
51
54
  process: processCmd,
52
55
  record,
@@ -0,0 +1,105 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { configRoot } from "./config.js";
6
+ import { CliError } from "./errors.js";
7
+ import { cmp } from "./update.js";
8
+ export const installFile = () => join(configRoot(), "install.json");
9
+ export function readInstall() {
10
+ const p = installFile();
11
+ if (!existsSync(p))
12
+ return null;
13
+ try {
14
+ return JSON.parse(readFileSync(p, "utf8"));
15
+ }
16
+ catch {
17
+ throw new CliError("bad_install_record", `${p} is not valid JSON`, "Run: npx -y benignswarm install (rewrites it)");
18
+ }
19
+ }
20
+ /** The recorded install, checked to still exist; what watchers and hooks are pointed at. */
21
+ export function requireInstall() {
22
+ const r = readInstall();
23
+ if (!r)
24
+ throw new CliError("not_installed", "bschat has no recorded install on this machine", "Run: npx -y benignswarm install (installs bschat once and records where; join does this too)");
25
+ if (!existsSync(r.bin))
26
+ throw new CliError("install_missing", `the recorded bschat install ${r.bin} no longer exists`, "Run: npx -y benignswarm install");
27
+ return r;
28
+ }
29
+ /** "bschat 0.12.38" -> "0.12.38"; null when the binary cannot run. */
30
+ export function binVersion(bin) {
31
+ const r = spawnSync(bin, ["--version"], { encoding: "utf8", timeout: 20_000 });
32
+ const m = r.status === 0 ? /bschat (\d+\.\d+\.\d+)/.exec(r.stdout ?? "") : null;
33
+ return m ? m[1] : null;
34
+ }
35
+ /** The npm belonging to the Node running this process: the same runtime installs and runs bschat. */
36
+ function ownNpm() {
37
+ const npm = join(dirname(process.execPath), "npm");
38
+ if (!existsSync(npm))
39
+ throw new CliError("no_npm", `no npm next to the Node running bschat (${process.execPath})`, "Install bschat with that Node's npm yourself (npm i -g benignswarm), then run: bschat install");
40
+ return npm;
41
+ }
42
+ export function latestPublished(npm) {
43
+ const r = spawnSync(npm, ["view", "benignswarm", "version", "--prefer-online"], { encoding: "utf8", timeout: 60_000 });
44
+ const v = (r.stdout ?? "").trim();
45
+ if (r.status !== 0 || !/^\d+\.\d+\.\d+$/.test(v))
46
+ throw new CliError("npm_view_failed", `could not ask npm for the latest benignswarm version (${npm})`, (r.stderr ?? "").trim().slice(0, 300));
47
+ return v;
48
+ }
49
+ /**
50
+ * Makes sure this machine's global bschat is at least `version`, installing with the npm next to
51
+ * the running Node when it is missing or older, and records it. Progress goes to stderr so a
52
+ * JSON caller's stdout stays clean. A failed install throws: nothing is recorded.
53
+ */
54
+ export function ensureInstall(version, log, npmOverride) {
55
+ const npm = npmOverride ?? ownNpm();
56
+ const pre = spawnSync(npm, ["prefix", "-g"], { encoding: "utf8", timeout: 30_000 });
57
+ if (pre.status !== 0)
58
+ throw new CliError("npm_prefix_failed", `${npm} prefix -g failed`, (pre.stderr ?? "").trim().slice(0, 300));
59
+ const bin = join(pre.stdout.trim(), "bin", "bschat");
60
+ const current = existsSync(bin) ? binVersion(bin) : null;
61
+ if (current && cmp(current, version) >= 0) {
62
+ log(`bschat ${current} is installed at ${bin}`);
63
+ }
64
+ else {
65
+ log(`${current ? `upgrading bschat ${current}` : "installing bschat"} to ${version} with ${npm}`);
66
+ const r = spawnSync(npm, ["i", "-g", `benignswarm@${version}`, "--prefer-online"], { stdio: ["ignore", 2, 2], timeout: 300_000 });
67
+ if (r.status !== 0)
68
+ throw new CliError("install_failed", `npm i -g benignswarm@${version} failed (exit ${r.status}) using ${npm}`, "Fix that npm's global prefix (permissions, network) or install it yourself, then run: bschat install");
69
+ const got = binVersion(bin);
70
+ if (got !== version)
71
+ throw new CliError("install_unverified", `after installing, ${bin} reports ${got ?? "nothing"} instead of ${version}`);
72
+ }
73
+ const rec = { bin, npm, version: binVersion(bin), installed_at: new Date().toISOString() };
74
+ mkdirSync(configRoot(), { recursive: true });
75
+ writeFileSync(installFile(), JSON.stringify(rec, null, 2) + "\n");
76
+ return rec;
77
+ }
78
+ /** Single-quotes a path for a shell command (hooks run through sh). */
79
+ export const shellPath = (p) => (/^[A-Za-z0-9_./-]+$/.test(p) ? p : `'${p.replace(/'/g, `'\\''`)}'`);
80
+ export const launchAgentsDir = () => join(homedir(), "Library", "LaunchAgents");
81
+ export const WATCH_LABEL_PREFIX = "org.benignswarm.watch.";
82
+ /** This machine's watcher LaunchAgent plists (macOS). */
83
+ export function watcherPlists() {
84
+ const dir = launchAgentsDir();
85
+ if (!existsSync(dir))
86
+ return [];
87
+ return readdirSync(dir).filter((f) => f.startsWith(WATCH_LABEL_PREFIX) && f.endsWith(".plist")).map((f) => ({ label: f.slice(0, -".plist".length), path: join(dir, f) }));
88
+ }
89
+ /** Loads (or reloads) a LaunchAgent from its plist, so what runs is what the file says. */
90
+ export function reloadLaunchAgent(label, path) {
91
+ const domain = `gui/${process.getuid()}`;
92
+ const loaded = spawnSync("launchctl", ["print", `${domain}/${label}`], { stdio: "ignore" }).status === 0;
93
+ if (loaded) {
94
+ const out = spawnSync("launchctl", ["bootout", `${domain}/${label}`], { encoding: "utf8" });
95
+ if (out.status !== 0)
96
+ throw new CliError("launchctl_failed", `launchctl bootout ${domain}/${label} failed`, (out.stderr ?? "").trim());
97
+ }
98
+ const r = spawnSync("launchctl", ["bootstrap", domain, path], { encoding: "utf8" });
99
+ if (r.status !== 0)
100
+ throw new CliError("launchctl_failed", `launchctl bootstrap ${domain} ${path} failed`, (r.stderr ?? "").trim());
101
+ }
102
+ /** Restarts a loaded LaunchAgent in place (new code, same definition). */
103
+ export function restartLaunchAgent(label) {
104
+ return spawnSync("launchctl", ["kickstart", "-k", `gui/${process.getuid()}/${label}`], { stdio: "ignore" }).status === 0;
105
+ }
package/dist/update.js CHANGED
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { configRoot } from "./config.js";
4
4
  import { CLI_VERSION } from "./version.js";
5
5
  const NOTICE_INTERVAL_MS = 24 * 3600_000;
6
- function cmp(a, b) {
6
+ export function cmp(a, b) {
7
7
  const pa = a.split(".").map(Number);
8
8
  const pb = b.split(".").map(Number);
9
9
  for (let i = 0; i < 3; i++) {
@@ -39,5 +39,5 @@ export function noteServerVersions(headers, agent) {
39
39
  catch {
40
40
  /* unwritable state dir: notice simply repeats next time */
41
41
  }
42
- process.stderr.write(`[bschat] CLI ${CLI_VERSION} is installed, ${latest} is available: npm i -g benignswarm@latest (npx -y benignswarm already uses the latest)\n`);
42
+ process.stderr.write(`[bschat] CLI ${CLI_VERSION} is installed, ${latest} is available: bschat install --latest (updates this machine's one install and restarts its watchers)\n`);
43
43
  }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.38";
1
+ export const CLI_VERSION = "0.12.39";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.38",
3
+ "version": "0.12.39",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {