benignswarm 0.12.82 → 0.12.84

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.
@@ -5,21 +5,25 @@ import { bool } from "../args.js";
5
5
  import { CliError } from "../errors.js";
6
6
  import { binVersion, ensureInstall, latestPublished, lingerEnabled, readInstall, restartWatcher, watcherServices } from "../install.js";
7
7
  import { CLI_VERSION } from "../version.js";
8
+ import { refreshInstalledHooks } from "../harness.js";
8
9
  /**
9
- * bschat install [<version> | --latest] make or upgrade this machine's one bschat install and
10
+ * b9s install [<version> | --latest] make or upgrade this machine's one b9s install and
10
11
  * restart the watchers that run it
11
12
  */
12
13
  export async function install(p, out) {
13
14
  const prev = readInstall();
14
15
  const want = p.positionals[1];
15
16
  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
+ throw new CliError("usage", "install [<version> | --latest] e.g. b9s install --latest, b9s install 0.12.38");
17
18
  const npm = prev?.npm && existsSync(prev.npm) ? prev.npm : undefined;
18
19
  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}`];
20
+ const rec = ensureInstall(version, (m) => process.stderr.write(`b9s: ${m}\n`), npm);
21
+ const lines = [`b9s ${rec.version} is this machine's install: ${rec.bin}`];
22
+ const refreshedHooks = bool(p.flags, "latest") ? refreshInstalledHooks(process.cwd(), rec.bin) : [];
23
+ if (refreshedHooks.length)
24
+ lines.push(`Updated harness hooks: ${refreshedHooks.join(", ")}`);
21
25
  if (prev && prev.bin !== rec.bin)
22
- lines.push(`(was ${prev.bin}; run bschat doctor to find hooks and watchers still pointing there)`);
26
+ lines.push(`(was ${prev.bin}; run b9s doctor to find hooks and watchers still pointing there)`);
23
27
  const restarted = [];
24
28
  const elsewhere = [];
25
29
  if (!bool(p.flags, "no-restart")) {
@@ -32,7 +36,7 @@ export async function install(p, out) {
32
36
  if (restartWatcher(w))
33
37
  restarted.push(w.label);
34
38
  else
35
- elsewhere.push(`${w.label} is not loaded (bschat doctor shows how to load it)`);
39
+ elsewhere.push(`${w.label} is not loaded (b9s doctor shows how to load it)`);
36
40
  }
37
41
  }
38
42
  if (restarted.length)
@@ -42,7 +46,7 @@ export async function install(p, out) {
42
46
  out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere });
43
47
  }
44
48
  /**
45
- * bschat doctor every bschat on this machine and who uses which: the recorded install, copies on
49
+ * b9s doctor every b9s on this machine and who uses which: the recorded install, copies on
46
50
  * PATH, npx caches, this repo's hook and instructions, and each watcher (plist versus
47
51
  * what launchd is actually running). Read-only; prints the fix for each problem.
48
52
  */
@@ -51,33 +55,35 @@ export async function doctor(_p, out) {
51
55
  const rec = readInstall();
52
56
  const recVersion = rec && existsSync(rec.bin) ? binVersion(rec.bin) : null;
53
57
  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" });
58
+ checks.push({ ok: false, what: "no recorded install: hooks and watchers have no one b9s to run", fix: "npx -y benignswarm install" });
55
59
  else if (!recVersion)
56
60
  checks.push({ ok: false, what: `recorded install ${rec.bin} does not run`, fix: "npx -y benignswarm install" });
57
61
  else
58
62
  checks.push({ ok: true, what: `recorded install: ${rec.bin} (${recVersion})` });
59
- // Every bschat on PATH, the one the shell finds first marked.
63
+ // Every b9s on PATH, the one the shell finds first marked.
60
64
  const seen = new Set();
61
65
  const onPath = [];
62
66
  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;
67
+ for (const name of ["b9s", "bschat"]) {
68
+ const f = join(dir, name);
69
+ try {
70
+ accessSync(f, constants.X_OK);
71
+ }
72
+ catch {
73
+ continue;
74
+ }
75
+ const real = realpathSync(f);
76
+ if (seen.has(real))
77
+ continue;
78
+ seen.add(real);
79
+ onPath.push({ path: f, real, version: binVersion(f) });
69
80
  }
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
81
  }
76
82
  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" });
83
+ checks.push({ ok: false, what: "no b9s on this shell's PATH", fix: rec ? `add ${join(rec.bin, "..")} to PATH, or call ${rec.bin}` : "npx -y benignswarm install" });
78
84
  onPath.forEach((b, i) => {
79
85
  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 });
86
+ 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 b9s than hooks and watchers; put ${join(rec.bin, "..")} first on PATH, or remove this copy` : undefined });
81
87
  });
82
88
  // npx caches: only used by commands that still say npx.
83
89
  const cache = spawnSync(join(process.execPath, "..", "npm"), ["config", "get", "cache"], { encoding: "utf8" }).stdout?.trim();
@@ -92,13 +98,13 @@ export async function doctor(_p, out) {
92
98
  const cmds = [...new Set([...hooks.matchAll(/"command":"([^"]*hook claude-code[^"]*)"/g)].map((m) => m[1].replace(/ --event \w+$/, "")))];
93
99
  for (const c of cmds) {
94
100
  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)" });
101
+ 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)" });
96
102
  }
97
103
  }
98
104
  for (const f of ["AGENTS.md", "GEMINI.md", join(".agents", "rules", "bschat.md")]) {
99
105
  const fp = join(root, f);
100
106
  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)" });
107
+ 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)" });
102
108
  }
103
109
  // Watchers: what the definition says versus what is running.
104
110
  const uid = process.getuid?.();
@@ -115,9 +121,9 @@ export async function doctor(_p, out) {
115
121
  }
116
122
  const ver = binVersion(args[0]);
117
123
  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 ... --service (it uses the recorded install and reloads)" });
124
+ checks.push({ ok: false, what: `watcher ${short} runs ${args[0]} (${ver ?? "does not run"}), not the recorded install`, fix: "re-run its b9s watch ... --service (it uses the recorded install and reloads)" });
119
125
  const active = (spawnSync("systemctl", ["--user", "is-active", `${w.label}.service`], { encoding: "utf8" }).stdout ?? "").trim();
120
- checks.push(active === "active" ? { ok: true, what: `watcher ${short}: running ${args[0]} (${ver ?? "?"})` } : { ok: false, what: `watcher ${short} is ${active || "unknown"}; see ~/.bschat/logs/watch.${short}.err.log`, fix: `systemctl --user daemon-reload && systemctl --user restart ${w.label}.service` });
126
+ checks.push(active === "active" ? { ok: true, what: `watcher ${short}: running ${args[0]} (${ver ?? "?"})` } : { ok: false, what: `watcher ${short} is ${active || "unknown"}; see ~/.b9s/logs/watch.${short}.err.log`, fix: `systemctl --user daemon-reload && systemctl --user restart ${w.label}.service` });
121
127
  continue;
122
128
  }
123
129
  const short = w.label.replace("org.benignswarm.watch.", "");
@@ -130,13 +136,13 @@ export async function doctor(_p, out) {
130
136
  const pid = /"PID" = (\d+);/.exec(listed.stdout ?? "")?.[1];
131
137
  const ver = binVersion(args[0]);
132
138
  if (rec && args[0] !== rec.bin)
133
- 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)" });
139
+ 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)" });
134
140
  if (listed.status !== 0) {
135
141
  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)` });
136
142
  continue;
137
143
  }
138
144
  if (!pid) {
139
- checks.push({ ok: false, what: `watcher ${short} is loaded but not running; see ~/.bschat/logs/watch.${short}.err.log`, fix: reload });
145
+ checks.push({ ok: false, what: `watcher ${short} is loaded but not running; see ~/.b9s/logs/watch.${short}.err.log`, fix: reload });
140
146
  continue;
141
147
  }
142
148
  const running = (spawnSync("ps", ["-o", "command=", "-p", pid], { encoding: "utf8" }).stdout ?? "").trim();
@@ -1,4 +1,4 @@
1
- import { CLI_VERSION } from "../version.js";
1
+ 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";
@@ -10,6 +10,7 @@ import { ensureInstall, readInstall } from "../install.js";
10
10
  import { codexHooksPath } from "./codex.js";
11
11
  import { claudeCheckoutOwner, claudeCheckoutTaken, withCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
12
12
  import { detectVendor } from "../vendor.js";
13
+ import { CLI_VERSION } from "../version.js";
13
14
  function repoRoot() {
14
15
  const r = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
15
16
  return r.status === 0 ? r.stdout.trim() : process.cwd();
@@ -61,7 +62,7 @@ export async function setup(p, out) {
61
62
  written.push(...installForHarness(root, h, files, ref, creds.url, inst.bin));
62
63
  const uniq = [...new Set(written)];
63
64
  const selfTest = harnessList(p, vendor).includes("claude-code") ? verifyClaudeHook(root, ref) : null;
64
- 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 });
65
+ out.print(`b9s ${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 });
65
66
  }
66
67
  export async function join(p, out) {
67
68
  const name = str(p.flags, "as") ?? process.env.BSCHAT_AGENT;
@@ -93,11 +94,11 @@ export async function join(p, out) {
93
94
  }
94
95
  if (!noBind)
95
96
  writeIdentityDryRun(root, vendor, name, bool(p.flags, "replace"));
96
- // The machine's one bschat install comes first: if it cannot be made, the token is not spent.
97
+ // The machine's one b9s install comes first: if it cannot be made, the token is not spent.
97
98
  const inst = machineInstall();
98
99
  let res;
99
100
  try {
100
- 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 }) });
101
+ res = await fetch(`${url}/enroll`, { method: "POST", headers: { "content-type": "application/json", "user-agent": cliUserAgent() }, body: JSON.stringify({ token, name, vendor, machine }) });
101
102
  }
102
103
  catch (e) {
103
104
  throw new CliError("network", `could not reach ${url}: ${e.message}`);
@@ -120,12 +121,12 @@ export async function join(p, out) {
120
121
  const human = [
121
122
  json.project
122
123
  ? `Joined project "${json.project.name}" as agent "${name}" (${vendor})${json.agent.role_name ? ` with role ${json.agent.role_name}` : ""}.`
123
- : `Joined as account-wide agent "${name}" (${vendor}) with role ${json.agent.role_name}. Project commands take --project <name>; see them with: bschat me`,
124
+ : `Joined as account-wide agent "${name}" (${vendor}) with role ${json.agent.role_name}. Project commands take --project <name>; see them with: b9s me`,
124
125
  `Credentials saved to ${path} (private to this machine).`,
125
- `bschat ${inst.version} is installed for this machine at ${inst.bin}; the hook, the repo instructions and watchers all use it. Upgrade with: bschat update`,
126
+ `b9s ${inst.version} is installed for this machine at ${inst.bin}; the hook, the repo instructions and watchers all use it. Upgrade with: b9s update`,
126
127
  noBind
127
- ? `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}.`
128
- : `This repo now maps ${vendor} -> ${ref} in ${idPath}, so bschat commands here know who you are, even after a reboot.`,
128
+ ? `This repo's ${vendor} identity was left as is. Address yourself on every call: \`b9s --as ${ref} <command>\` or \`BSCHAT_AGENT=${ref} b9s <command>\`. Never run bare b9s here as ${name}.`
129
+ : `This repo now maps ${vendor} -> ${ref} in ${idPath}, so b9s commands here know who you are, even after a reboot.`,
129
130
  written.length ? `Harness files written: ${written.join(", ")}` : null,
130
131
  selfTest,
131
132
  ``,
@@ -135,8 +136,8 @@ export async function join(p, out) {
135
136
  json.revived && json.resume ? `--- ${json.resume.title} ---\n${json.resume.body}\n---${json.resume.evidence.length ? `\nevidence: ${json.resume.evidence.map((e) => `evidence:${e}`).join(" ")}` : ""}` : null,
136
137
  json.revived && json.resume ? `Read it before doing anything else.` : null,
137
138
  ``,
138
- vendor === "codex" ? `Codex: bschat's hooks are in ${installCodexHooks(inst.bin)} (approve them when Codex asks); they deliver your mentions and assignments inside your thread once bschat knows which thread is you: bschat codex bind <thread-id>, or a watcher (bschat watch --launchd), which is still what wakes you when you are idle.` : vendor === "antigravity" ? `Antigravity: .agents/hooks.json now delivers your mentions and assignments inside your conversation, once bschat knows which conversation is you: bschat antigravity bind <conversation-id> (the folder name under ~/.gemini/antigravity/brain/ holding your artifacts). A watcher (bschat watch --launchd) also binds it, and is still what wakes you when you are idle.` : 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,
139
- `Next: bschat me && bschat who && bschat inbox && bschat handoffs --open`,
139
+ vendor === "codex" ? `Codex: b9s's hooks are in ${installCodexHooks(inst.bin)} (approve them when Codex asks); they deliver your mentions and assignments inside your thread once b9s knows which thread is you: b9s codex bind <thread-id>, or a watcher (b9s watch --launchd), which is still what wakes you when you are idle.` : vendor === "antigravity" ? `Antigravity: .agents/hooks.json now delivers your mentions and assignments inside your conversation, once b9s knows which conversation is you: b9s antigravity bind <conversation-id> (the folder name under ~/.gemini/antigravity/brain/ holding your artifacts). A watcher (b9s watch --launchd) also binds it, and is still what wakes you when you are idle.` : 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 (b9s watch --launchd).` : null,
140
+ `Next: b9s me && b9s who && b9s inbox && b9s handoffs --open`,
140
141
  ].filter((l) => l !== null).join("\n");
141
142
  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 } });
142
143
  }
@@ -150,7 +151,7 @@ function verifyClaudeHook(root, ref) {
150
151
  const settings = JSON.parse(readFileSync(sp, "utf8"));
151
152
  const cmd = settings.hooks?.SessionStart?.flatMap((g) => g.hooks ?? []).map((h) => h.command).find((c) => typeof c === "string" && c.includes("hook claude-code"));
152
153
  if (!cmd)
153
- throw new CliError("hook_missing", `${sp} has no bschat SessionStart hook after install`);
154
+ throw new CliError("hook_missing", `${sp} has no b9s SessionStart hook after install`);
154
155
  const r = spawnSync("sh", ["-c", cmd], { cwd: root, input: "{}", encoding: "utf8", env: { ...process.env, BSCHAT_AGENT: ref }, timeout: 60_000 });
155
156
  const err = (r.stderr ?? "") + (r.status !== 0 ? (r.stdout ?? "") : "");
156
157
  if (r.status !== 0 || /"error"\s*:/.test(r.stdout ?? "")) {
@@ -182,7 +183,7 @@ export function assertVendorMatchesRepo(root, name, vendor, replace) {
182
183
  function machineInstall() {
183
184
  const prev = readInstall();
184
185
  const npm = prev?.npm && existsSync(prev.npm) ? prev.npm : undefined;
185
- return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`bschat: ${m}\n`), npm);
186
+ return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`b9s: ${m}\n`), npm);
186
187
  }
187
188
  function writeIdentityDryRun(root, vendor, name, replace) {
188
189
  const p = findIdentityFile(root);
@@ -190,10 +191,10 @@ function writeIdentityDryRun(root, vendor, name, replace) {
190
191
  return;
191
192
  const existing = readIdentityFile(p).agents[vendor];
192
193
  if (existing && existing.name !== name && !replace) {
193
- throw new CliError("identity_exists", `${p} already maps ${vendor} to agent "${existing.name}"`, `Two ${vendor} agents share this checkout. Join with --no-bind and address yourself per call (bschat --as ${name} ...), or --replace to make "${name}" this checkout's default instead of "${existing.name}".`);
194
+ throw new CliError("identity_exists", `${p} already maps ${vendor} to agent "${existing.name}"`, `Two ${vendor} agents share this checkout. Join with --no-bind and address yourself per call (b9s --as ${name} ...), or --replace to make "${name}" this checkout's default instead of "${existing.name}".`);
194
195
  }
195
196
  }
196
- /** Merges bschat's hooks into this machine's ~/.codex/hooks.json; returns its path. */
197
+ /** Merges b9s's hooks into this machine's ~/.codex/hooks.json; returns its path. */
197
198
  function installCodexHooks(bin) {
198
199
  const path = codexHooksPath();
199
200
  let doc = {};
@@ -38,7 +38,7 @@ export async function lists(p, out) {
38
38
  const { client: c, creds } = client(p);
39
39
  const r = await c.call("GET", `${scope(p, creds)}/lists`);
40
40
  const rows = r.lists.map((l) => ({ name: l.name, items: `${l.open_count} open / ${l.item_count}`, unread: l.unread_items, children: l.child_count, seen: l.my_viewed_at ? "yes" : "no", description: l.description.split("\n")[0].slice(0, 50), id: l.id }));
41
- out.print(rows.length ? table(rows, ["name", "items", "unread", "children", "seen", "description", "id"]) : "(no lists here; create one with: bschat list create <name>)", r);
41
+ out.print(rows.length ? table(rows, ["name", "items", "unread", "children", "seen", "description", "id"]) : "(no lists here; create one with: b9s list create <name>)", r);
42
42
  }
43
43
  export async function list(p, out) {
44
44
  const sub = p.positionals[1];
@@ -155,7 +155,7 @@ export async function item(p, out) {
155
155
  throw new CliError("usage", "item show|set|done|view|rm <id>");
156
156
  const full = /^[0-9a-f-]{36}$/.test(id) ? id : null;
157
157
  if (!full)
158
- throw new CliError("usage", "item commands take the full item id (bschat list show prints the first 8 chars; use --json for full ids)");
158
+ throw new CliError("usage", "item commands take the full item id (b9s list show prints the first 8 chars; use --json for full ids)");
159
159
  if (sub === "show") {
160
160
  const r = await c.call("GET", `/items/${id}`);
161
161
  const i = r.item;
@@ -6,7 +6,7 @@ import { CliError } from "../errors.js";
6
6
  import { table } from "../output.js";
7
7
  import { CLI_VERSION } from "../version.js";
8
8
  /**
9
- * bschat-admin machine: provision machines over the operator's own ssh and declare the agent
9
+ * b9s-admin machine: provision machines over the operator's own ssh and declare the agent
10
10
  * sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
11
11
  * call here runs in the operator's terminal, and the machine key reaches the machine on ssh's stdin.
12
12
  *
@@ -17,8 +17,8 @@ import { CLI_VERSION } from "../version.js";
17
17
  */
18
18
  const adminClient = (p) => Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
19
19
  /**
20
- * Brings Node 22+ and bschat to the machine without sudo: Node's official tarball under
21
- * ~/.local/node (checked against nodejs.org's SHASUMS256), bschat installed with that npm and
20
+ * Brings Node 22+ and b9s to the machine without sudo: Node's official tarball under
21
+ * ~/.local/node (checked against nodejs.org's SHASUMS256), b9s installed with that npm and
22
22
  * recorded as the machine's install, both linked into ~/.local/bin. Prints one BSCHAT-STEP line per
23
23
  * step; any failure stops it with a FAILED line.
24
24
  */
@@ -27,7 +27,7 @@ export function bootstrapScript(version) {
27
27
  step() { echo "BSCHAT-STEP $1 $2 \${3:-}"; }
28
28
  fail() { step "$1" failed "$2"; exit 1; }
29
29
  mkdir -p "$HOME/.local/bin"
30
- case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) export PATH="$HOME/.local/bin:$PATH"; printf '\\nexport PATH="$HOME/.local/bin:$PATH" # bschat\\n' >> "$HOME/.profile"; step path done "added ~/.local/bin to ~/.profile" ;; esac
30
+ case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) export PATH="$HOME/.local/bin:$PATH"; printf '\\nexport PATH="$HOME/.local/bin:$PATH" # b9s\\n' >> "$HOME/.profile"; step path done "added ~/.local/bin to ~/.profile" ;; esac
31
31
  major=0
32
32
  if command -v node >/dev/null 2>&1; then major=$(node -p 'process.versions.node.split(".")[0]'); fi
33
33
  if [ "$major" -ge 22 ]; then step node ok "$(node --version) $(command -v node)"
@@ -44,11 +44,11 @@ else
44
44
  hash -r; step node done "$(node --version) in ~/.local/node"
45
45
  fi
46
46
  # --prefer-online: a cached package listing from before the publish says the version does not exist.
47
- npx -y --prefer-online -p benignswarm@${version} bschat install ${version} >/tmp/bschat-install.$$ 2>&1 || fail bschat "$(grep -v 'complete log' /tmp/bschat-install.$$ | grep -m1 -iE 'error|failed' || tail -1 /tmp/bschat-install.$$)"
47
+ npx -y --prefer-online -p benignswarm@${version} b9s install ${version} >/tmp/bschat-install.$$ 2>&1 || fail b9s "$(grep -v 'complete log' /tmp/bschat-install.$$ | grep -m1 -iE 'error|failed' || tail -1 /tmp/bschat-install.$$)"
48
48
  rm -f /tmp/bschat-install.$$
49
- bin=$(node -p 'require(require("os").homedir()+"/.bschat/install.json").bin')
50
- for b in bschat bschat-admin; do [ -e "$HOME/.local/bin/$b" ] || ln -sf "$(dirname "$bin")/$b" "$HOME/.local/bin/$b"; done
51
- step bschat ok "$("$bin" --version) $bin"
49
+ bin=$(node -p 'require(require("os").homedir()+"/.b9s/install.json").bin')
50
+ for b in b9s b9s-admin bschat bschat-admin; do [ -e "$HOME/.local/bin/$b" ] || ln -sf "$(dirname "$bin")/$b" "$HOME/.local/bin/$b"; done
51
+ step b9s ok "$("$bin" --version) $bin"
52
52
  `;
53
53
  }
54
54
  /**
@@ -62,8 +62,8 @@ function ssh(host, command, input) {
62
62
  throw new CliError("ssh_failed", `ssh ${host}: ${r.error.message}`);
63
63
  return { status: r.status ?? 255, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
64
64
  }
65
- /** Runs a bschat command on the machine in a login shell (so ~/.local/bin and the harness CLIs are on PATH). */
66
- const remoteBschat = (host, args, input) => ssh(host, `bash -lc ${JSON.stringify(`bschat ${args}`)}`, input);
65
+ /** Runs a b9s command on the machine in a login shell (so ~/.local/bin and the harness CLIs are on PATH). */
66
+ const remoteBschat = (host, args, input) => ssh(host, `bash -lc ${JSON.stringify(`b9s ${args}`)}`, input);
67
67
  export async function machineAdmin(action, rest, p, out) {
68
68
  const c = adminClient(p);
69
69
  if (action === "add") {
@@ -74,7 +74,7 @@ export async function machineAdmin(action, rest, p, out) {
74
74
  const lines = [];
75
75
  const say = (l) => { lines.push(l); if (!out.json)
76
76
  process.stderr.write(`${l}\n`); };
77
- // 1. Node and bschat, over the operator's ssh.
77
+ // 1. Node and b9s, over the operator's ssh.
78
78
  const boot = ssh(host, "bash -l -s", bootstrapScript(CLI_VERSION));
79
79
  const steps = boot.stdout.split("\n").filter((l) => l.startsWith("BSCHAT-STEP ")).map((l) => l.slice(12));
80
80
  for (const s of steps)
@@ -84,7 +84,7 @@ export async function machineAdmin(action, rest, p, out) {
84
84
  // 2. Linger, Codex, managed hooks: checked and fixed on the machine itself.
85
85
  const prep = remoteBschat(host, `machine prepare --json${bool(p.flags, "codex-userns") ? " --codex-userns" : ""}${bool(p.flags, "bwrap-userns") ? " --bwrap-userns" : ""}`);
86
86
  if (prep.status !== 0)
87
- throw new CliError("provision_failed", `bschat machine prepare on ${host} failed: ${prep.stderr.trim().slice(-300)}`);
87
+ throw new CliError("provision_failed", `b9s machine prepare on ${host} failed: ${prep.stderr.trim().slice(-300)}`);
88
88
  const prepared = JSON.parse(prep.stdout).steps;
89
89
  for (const s of prepared)
90
90
  say(` ${s.step} ${s.result} ${s.detail}`);
@@ -100,9 +100,9 @@ export async function machineAdmin(action, rest, p, out) {
100
100
  say(` registration: ${name} existed; its key was rotated`);
101
101
  }
102
102
  const admin = loadAdmin(resolveAdminName(str(p.flags, "admin")));
103
- const wrote = ssh(host, `umask 077 && mkdir -p ~/.bschat && cat > ~/.bschat/machine.json`, JSON.stringify({ url: admin.url, key: reg.key, name }, null, 2) + "\n");
103
+ const wrote = ssh(host, `umask 077 && mkdir -p ~/.b9s && cat > ~/.b9s/machine.json`, JSON.stringify({ url: admin.url, key: reg.key, name }, null, 2) + "\n");
104
104
  if (wrote.status !== 0)
105
- throw new CliError("provision_failed", `writing ~/.bschat/machine.json on ${host} failed: ${wrote.stderr.trim()}`);
105
+ throw new CliError("provision_failed", `writing ~/.b9s/machine.json on ${host} failed: ${wrote.stderr.trim()}`);
106
106
  // 4. The daemon.
107
107
  const svc = remoteBschat(host, "machine service");
108
108
  if (svc.status !== 0)
@@ -113,13 +113,13 @@ export async function machineAdmin(action, rest, p, out) {
113
113
  `Machine ${name} (${host}) is provisioned and its daemon is running.`,
114
114
  ...lines,
115
115
  failed.length ? `Still to do on the machine: ${failed.map((s) => `${s.step} (${s.detail})`).join("; ")}` : null,
116
- `Declare what it runs: bschat-admin machine session add ${name} <project>/<agent> --dir <checkout on ${host}> --sandbox <mode> [--create --role <role>]`,
116
+ `Declare what it runs: b9s-admin machine session add ${name} <project>/<agent> --dir <checkout on ${host}> --sandbox <mode> [--create --role <role>]`,
117
117
  ].filter(Boolean).join("\n"), { machine: name, host, bootstrap: steps, prepare: prepared });
118
118
  }
119
119
  if (action === "list" || action === undefined) {
120
120
  const r = await c.call("GET", "/machines");
121
- const rows = r.machines.map((m) => ({ name: m.name, os: m.report?.os ?? "-", bschat: m.report?.bschat?.version ?? "-", codex: m.report?.codex ? (m.report.codex.logged_in ? "logged in" : "NOT logged in") : "-", sessions: m.sessions.length, last_report: m.last_report_at ?? "never" }));
122
- return out.print(rows.length ? table(rows, ["name", "os", "bschat", "codex", "sessions", "last_report"]) : "No machines. Add one: bschat-admin machine add <name> --ssh <host>", r);
121
+ const rows = r.machines.map((m) => ({ name: m.name, os: m.report?.os ?? "-", b9s: m.report?.bschat?.version ?? "-", codex: m.report?.codex ? (m.report.codex.logged_in ? "logged in" : "NOT logged in") : "-", sessions: m.sessions.length, last_report: m.last_report_at ?? "never" }));
122
+ return out.print(rows.length ? table(rows, ["name", "os", "b9s", "codex", "sessions", "last_report"]) : "No machines. Add one: b9s-admin machine add <name> --ssh <host>", r);
123
123
  }
124
124
  if (action === "show") {
125
125
  if (!rest[0])
@@ -129,9 +129,9 @@ export async function machineAdmin(action, rest, p, out) {
129
129
  const rep = m.report ?? {};
130
130
  const head = [
131
131
  `${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; writable ${(m.writable ?? []).join(", ") || "-"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}`,
132
- 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"}; bschat ${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?)",
132
+ 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?)",
133
133
  ];
134
- const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ bschat watch\[[^\]]+\]: /, "") }));
134
+ const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", thread: s.thread ?? "-", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ b9s watch\[[^\]]+\]: /, "") }));
135
135
  return out.print([...head, rows.length ? table(rows, ["agent", "pool", "desired", "state", "thread", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].join("\n"), r);
136
136
  }
137
137
  if (action === "maintenance") {
@@ -180,7 +180,7 @@ export async function machineAdmin(action, rest, p, out) {
180
180
  body = { slots: rest[1] === "auto" ? null : Number(rest[1]) };
181
181
  }
182
182
  const r = await c.call("PATCH", `/machines/${name}`, body);
183
- return out.print(`${name}: labels ${r.machine.labels.join(", ") || "(none)"}; slots ${r.machine.slots ?? "auto"}. Pools were re-placed: bschat-admin pool list`, r);
183
+ return out.print(`${name}: labels ${r.machine.labels.join(", ") || "(none)"}; slots ${r.machine.slots ?? "auto"}. Pools were re-placed: b9s-admin pool list`, r);
184
184
  }
185
185
  if (action === "remove") {
186
186
  if (!rest[0])
@@ -202,7 +202,7 @@ export async function machineAdmin(action, rest, p, out) {
202
202
  create: bool(p.flags, "create"), role: str(p.flags, "role"),
203
203
  };
204
204
  const r = await c.call("POST", `/machines/${machineName}/sessions`, body);
205
- return out.print(`Declared ${r.session.agent} on ${machineName} (${r.session.harness}, ${r.session.sandbox}, ${r.session.dir}). Its daemon starts it within 30 s: bschat-admin machine show ${machineName}`, r);
205
+ return out.print(`Declared ${r.session.agent} on ${machineName} (${r.session.harness}, ${r.session.sandbox}, ${r.session.dir}). Its daemon starts it within 30 s: b9s-admin machine show ${machineName}`, r);
206
206
  }
207
207
  if (sub === "stop" || sub === "start") {
208
208
  const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { desired: sub === "stop" ? "stopped" : "running" });
@@ -253,11 +253,11 @@ export async function poolAdmin(action, rest, p, out, argv) {
253
253
  const needs = { ...(str(p.flags, "needs") ? { labels: str(p.flags, "needs").split(",").map((x) => x.trim()).filter(Boolean) } : {}), ...(str(p.flags, "min-ram") ? { min_ram_gb: Number(str(p.flags, "min-ram")) } : {}) };
254
254
  const tt = str(p.flags, "turn-timeout");
255
255
  const r = await c.call("PUT", `/projects/${project}/pools/${name}`, { role: str(p.flags, "role") ?? null, variants, count, sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}) });
256
- return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: bschat-admin machine show <machine>"].join("\n"), r);
256
+ return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
257
257
  }
258
258
  if (action === "list" || action === undefined) {
259
259
  const r = await c.call("GET", rest[0] ? `/projects/${rest[0]}/pools` : "/pools");
260
- return out.print(r.pools.flatMap(statusLines).join("\n") || "No pools. Make one: bschat-admin pool set <project>/<name> --role ... --variant ... --count n --sandbox ...", r);
260
+ return out.print(r.pools.flatMap(statusLines).join("\n") || "No pools. Make one: b9s-admin pool set <project>/<name> --role ... --variant ... --count n --sandbox ...", r);
261
261
  }
262
262
  if (action === "show") {
263
263
  const [project, name] = (rest[0] ?? "").split("/");
@@ -317,6 +317,19 @@ export function lastTurnSettings(rollout) {
317
317
  return { model: null, effort: null };
318
318
  }
319
319
  export const shellSingle = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
320
+ /** Reads a remote Codex map without changing the source machine's installed layout. */
321
+ export function remoteCodexMapCommand() {
322
+ return [
323
+ `new="$HOME/.b9s"; old="$HOME/.bschat";`,
324
+ `if [ -d "$new" ] && [ -d "$old" ] && [ ! -L "$old" ]; then printf '%s\\n' "both $new and $old are real directories; refusing to choose a Codex map" >&2; exit 1; fi;`,
325
+ `if [ -L "$new" ]; then printf '%s\\n' "$new is a symlink; refusing to choose between $new and $old" >&2; exit 1; fi;`,
326
+ `if [ -e "$new" ] && [ ! -d "$new" ]; then printf '%s\\n' "$new exists but is not a directory; refusing to choose between $new and $old" >&2; exit 1; fi;`,
327
+ `if [ -e "$old" ] && [ ! -d "$old" ] && [ ! -L "$old" ]; then printf '%s\\n' "$old exists but is not a directory" >&2; exit 1; fi;`,
328
+ `if [ -L "$old" ]; then if [ ! -d "$new" ]; then printf '%s\\n' "$old is a symlink but $new is not a directory" >&2; exit 1; fi; old_real=$(cd "$old" 2>/dev/null && pwd -P) || { printf '%s\\n' "$old cannot be resolved as a directory" >&2; exit 1; }; new_real=$(cd "$new" 2>/dev/null && pwd -P) || { printf '%s\\n' "$new cannot be resolved as a directory" >&2; exit 1; }; if [ "$old_real" != "$new_real" ]; then printf '%s\\n' "$old is not a symlink to $new" >&2; exit 1; fi; fi;`,
329
+ `if [ -d "$new" ]; then root="$new"; elif [ -d "$old" ]; then root="$old"; else printf '{}'; exit 0; fi;`,
330
+ `if [ -f "$root/codex.json" ]; then cat "$root/codex.json"; elif [ -e "$root/codex.json" ]; then printf '%s\\n' "$root/codex.json exists but is not a file" >&2; exit 1; else printf '{}'; fi;`,
331
+ ].join(" ");
332
+ }
320
333
  /** Runs a shell command on `host` ("local" runs it here). */
321
334
  function on(host, command, input) {
322
335
  if (host === "local") {
@@ -385,10 +398,25 @@ export async function agentMove(rest, p, out) {
385
398
  let effort = str(p.flags, "effort");
386
399
  if (carry === "thread") {
387
400
  if (!thread) {
388
- const map = on(from, "cat ~/.bschat/codex.json 2>/dev/null");
389
- const ids = Object.entries(JSON.parse(map.stdout || "{}").conversations ?? {}).filter(([, a]) => a === ref).map(([id]) => id);
401
+ const map = on(from, remoteCodexMapCommand());
402
+ if (map.status !== 0)
403
+ throw new CliError("codex_map_unavailable", `could not read the Codex thread map on ${from}: ${map.stderr.trim()}`);
404
+ let conversationMap;
405
+ try {
406
+ const parsed = JSON.parse(map.stdout);
407
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
408
+ throw new Error("map must be an object");
409
+ const conversations = parsed.conversations ?? {};
410
+ if (!conversations || typeof conversations !== "object" || Array.isArray(conversations))
411
+ throw new Error("conversations must be an object");
412
+ conversationMap = conversations;
413
+ }
414
+ catch (error) {
415
+ throw new CliError("bad_codex_map", `the Codex thread map on ${from} is not valid JSON: ${error.message}`);
416
+ }
417
+ const ids = Object.entries(conversationMap).filter(([, a]) => a === ref).map(([id]) => id);
390
418
  if (!ids.length)
391
- throw new CliError("no_thread", `no Codex thread is bound to ${ref} on ${from} (~/.bschat/codex.json)`, "Pass --thread <id>");
419
+ throw new CliError("no_thread", `no Codex thread is bound to ${ref} on ${from} (~/.b9s/codex.json or ~/.bschat/codex.json)`, "Pass --thread <id>");
392
420
  const newest = on(from, `ls -t ${ids.map((id) => `~/.codex/sessions/*/*/*/rollout-*${id}.jsonl ~/.codex/archived_sessions/rollout-*${id}.jsonl`).join(" ")} 2>/dev/null | head -1`).stdout.trim();
393
421
  thread = ids.find((id) => newest.includes(id)) ?? null;
394
422
  if (!thread)
@@ -414,7 +442,7 @@ export async function agentMove(rest, p, out) {
414
442
  const wait = Number(str(p.flags, "wait") ?? "10");
415
443
  if (wait > 0) {
416
444
  const asked = new Date().toISOString();
417
- await c.call("POST", `/projects/${project}/channels/general/messages`, { body: `@${agent} you are being moved to the machine ${to}. Before anything else, save a resume note: bschat checkpoint "<one line>" --body "<what you are doing, your open units and branches (pushed?), waits and next steps>". Your next session there reads it first. Then end your turn.` });
445
+ await c.call("POST", `/projects/${project}/channels/general/messages`, { body: `@${agent} you are being moved to the machine ${to}. Before anything else, save a resume note: b9s checkpoint "<one line>" --body "<what you are doing, your open units and branches (pushed?), waits and next steps>". Your next session there reads it first. Then end your turn.` });
418
446
  say(` asked ${agent} for a resume note; waiting up to ${wait} min`);
419
447
  let note = null;
420
448
  for (let i = 0; i < wait * 6 && !note; i++) {
@@ -444,7 +472,7 @@ export async function agentMove(rest, p, out) {
444
472
  r.moved_from.length ? `Its session on ${r.moved_from.join(", ")} was removed.` : null,
445
473
  `${r.revoked_keys} key(s) elsewhere revoked: a watcher left running there stops and removes itself. Archive its old thread in the Codex app so nobody types into that copy.`,
446
474
  problems.length ? `Left behind (--force): ${problems.join("; ")}` : null,
447
- `Follow it: bschat-admin machine show ${to}`,
475
+ `Follow it: b9s-admin machine show ${to}`,
448
476
  ].filter(Boolean).join("\n"), r);
449
477
  }
450
478
  /** --at: an ISO timestamp, or HH:MM in this machine's local time (today, or tomorrow when past). */