benignswarm 0.12.43 → 0.12.45

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.
@@ -1,6 +1,6 @@
1
1
  import { str } from "../args.js";
2
2
  import { agentRef, loadAgent, resolveAgentName } from "../config.js";
3
- import { bindConversation, syncFromWatchers } from "../antigravity.js";
3
+ import { bindConversation, syncFromWatchers } from "../sessions.js";
4
4
  import { CliError } from "../errors.js";
5
5
  /**
6
6
  * bschat antigravity bind <conversation-id> [--as <agent>] this Antigravity conversation is you: its hook delivers to you
@@ -0,0 +1,50 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { str } from "../args.js";
5
+ import { agentRef, loadAgent, resolveAgentName } from "../config.js";
6
+ import { CliError } from "../errors.js";
7
+ import { withCodexHooks } from "../harness.js";
8
+ import { requireInstall } from "../install.js";
9
+ import { bindSession, syncFromWatchers } from "../sessions.js";
10
+ /**
11
+ * bschat codex hooks install bschat's hooks in ~/.codex/hooks.json (this machine's Codex)
12
+ * bschat codex bind <thread-id> [--as a] this Codex thread is you: its hooks deliver to you
13
+ * bschat codex sync bind every thread an installed watcher wakes
14
+ */
15
+ export async function codex(p, out) {
16
+ const sub = p.positionals[1];
17
+ if (sub === "hooks") {
18
+ const path = codexHooksPath();
19
+ let doc = {};
20
+ if (existsSync(path)) {
21
+ try {
22
+ doc = JSON.parse(readFileSync(path, "utf8"));
23
+ }
24
+ catch {
25
+ throw new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
26
+ }
27
+ }
28
+ mkdirSync(dirname(path), { recursive: true });
29
+ writeFileSync(path, JSON.stringify(withCodexHooks(doc, requireInstall().bin), null, 2) + "\n");
30
+ const bound = syncFromWatchers().filter((b) => b.kind === "codex");
31
+ out.print(`Wrote bschat's hooks to ${path} (SessionStart, UserPromptSubmit, PostToolUse, Stop).\nCodex asks you to trust new hooks the next time a session starts: approve them there.\nThreads bound from watchers: ${bound.length ? bound.map((b) => `${b.conversation} -> ${b.agent}`).join(", ") : "none"}. Any other Codex session gets nothing from them.`, { path, bound });
32
+ return;
33
+ }
34
+ if (sub === "bind") {
35
+ const thread = p.positionals[2];
36
+ if (!thread)
37
+ throw new CliError("usage", "codex bind <thread-id> [--as <agent>] (the thread id is in the Codex session's rollout file name, ~/.codex/sessions/.../rollout-*-<id>.jsonl)");
38
+ const ref = agentRef(loadAgent(resolveAgentName(str(p.flags, "as"))));
39
+ bindSession("codex", thread, ref);
40
+ out.print(`Codex thread ${thread} is ${ref}: its hooks now deliver your mentions and assignments there.`, { thread, agent: ref });
41
+ return;
42
+ }
43
+ if (sub === "sync") {
44
+ const bound = syncFromWatchers().filter((b) => b.kind === "codex");
45
+ out.print(bound.length ? `Bound ${bound.length} thread(s) from watchers:\n${bound.map((b) => ` ${b.conversation} -> ${b.agent}`).join("\n")}` : "No Codex watcher found on this machine.", { bound });
46
+ return;
47
+ }
48
+ throw new CliError("usage", "codex hooks | codex bind <thread-id> [--as <agent>] | codex sync");
49
+ }
50
+ export const codexHooksPath = () => join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "hooks.json");
@@ -6,7 +6,7 @@ import { heartbeatNow } from "../heartbeat.js";
6
6
  import { fmtMessage } from "../output.js";
7
7
  import { readState, writeState } from "../state.js";
8
8
  import { goalFromClaudeTranscript, modelFromClaudeTranscript } from "../model.js";
9
- import { conversationAgent, syncFromWatchers } from "../antigravity.js";
9
+ import { conversationAgent, sessionAgent, syncFromWatchers } from "../sessions.js";
10
10
  const HEARTBEAT_MS = 60_000;
11
11
  /** Reads the harness's hook payload from stdin without blocking when there is none. */
12
12
  function readStdinJson() {
@@ -155,6 +155,8 @@ export async function hook(p) {
155
155
  const harness = p.positionals[1] ?? "plain";
156
156
  if (harness === "antigravity")
157
157
  return antigravityHook(p);
158
+ if (harness === "codex")
159
+ return codexHook(p);
158
160
  const event = str(p.flags, "event") ?? (harness === "claude-code" ? "UserPromptSubmit" : "");
159
161
  let name;
160
162
  try {
@@ -300,3 +302,70 @@ async function antigravityHook(p) {
300
302
  const text = [standing, u?.text].filter(Boolean).join("\n\n");
301
303
  return out(text ? { injectSteps: [{ systemMessage: { systemMessage: text } }] } : {});
302
304
  }
305
+ /**
306
+ * Codex's hooks (~/.codex/hooks.json, written by `bschat codex hooks`; Claude Code's format):
307
+ * SessionStart injects the standing rules and anything unread, UserPromptSubmit new items,
308
+ * PostToolUse is a liveness heartbeat, and Stop with something addressed to the agent returns
309
+ * "block" with it, which Codex takes as the next input instead of stopping. The hooks file is the
310
+ * machine's, so the agent is found by the session id (the Codex thread a watcher wakes, or
311
+ * `bschat codex bind`); any other Codex session (the user's own chats) gets nothing.
312
+ * Always exits 0 with valid output: a hook must never break the session.
313
+ */
314
+ async function codexHook(p) {
315
+ const event = str(p.flags, "event") ?? "";
316
+ const input = readStdinJson();
317
+ const sid = typeof input?.session_id === "string" ? input.session_id : null;
318
+ let ref = sid ? sessionAgent("codex", sid) : null;
319
+ if (sid && !ref) {
320
+ try {
321
+ syncFromWatchers();
322
+ }
323
+ catch (e) {
324
+ process.stderr.write(`bschat: could not read watchers: ${e.message}\n`);
325
+ }
326
+ ref = sessionAgent("codex", sid);
327
+ }
328
+ if (!ref)
329
+ return; // not an agent's thread: nothing
330
+ let name;
331
+ try {
332
+ name = resolveAgentName(ref);
333
+ }
334
+ catch {
335
+ return;
336
+ }
337
+ if (typeof input?.model === "string" && input.model) {
338
+ const st = readState(name);
339
+ if (st.model !== input.model)
340
+ writeState(name, { ...st, model: input.model, model_observed_at: Date.now() });
341
+ }
342
+ if (Date.now() - (readState(name).heartbeat_at ?? 0) > HEARTBEAT_MS) {
343
+ try {
344
+ await heartbeatNow(Client.forAgent(loadAgent(name), undefined, { presence: false }), "codex-hook");
345
+ writeState(name, { ...readState(name), heartbeat_at: Date.now() });
346
+ }
347
+ catch (e) {
348
+ process.stderr.write(`bschat: heartbeat failed: ${e.message}\n`);
349
+ }
350
+ }
351
+ const context = (text) => process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } }) + "\n");
352
+ if (event === "PostToolUse")
353
+ return;
354
+ if (event === "Stop") {
355
+ // Only something addressed to it keeps it going; chatter waits for its next turn.
356
+ const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true });
357
+ if (!peek || (peek.tier !== "direct" && peek.tier !== "role"))
358
+ return;
359
+ const u = await gatherUpdates(name, { force: true, delivery: "hook" });
360
+ if (u)
361
+ process.stdout.write(JSON.stringify({ decision: "block", reason: `${u.text}\nHandle these, then carry on with what you were doing.` }) + "\n");
362
+ return;
363
+ }
364
+ if (event !== "SessionStart" && event !== "UserPromptSubmit")
365
+ return;
366
+ const standing = event === "SessionStart" ? await standingRules(name, false) : null;
367
+ const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
368
+ const text = [standing, u?.text].filter(Boolean).join("\n\n");
369
+ if (text)
370
+ context(text);
371
+ }
@@ -2,12 +2,13 @@ import { CLI_VERSION } from "../version.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 { readFileSync } from "node:fs";
6
- import { join as pathJoin } from "node:path";
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { dirname, join as pathJoin } from "node:path";
7
7
  import { CliError } from "../errors.js";
8
8
  import { defaultMachine } from "../git.js";
9
9
  import { ensureInstall } from "../install.js";
10
- import { claudeCheckoutOwner, claudeCheckoutTaken, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
10
+ import { codexHooksPath } from "./codex.js";
11
+ import { claudeCheckoutOwner, claudeCheckoutTaken, withCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
11
12
  import { detectVendor } from "../vendor.js";
12
13
  function repoRoot() {
13
14
  const r = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
@@ -40,6 +41,7 @@ export async function setup(p, out) {
40
41
  const vendor = normalizeVendor(str(p.flags, "vendor") ?? creds.vendor);
41
42
  const root = str(p.flags, "dir") ?? repoRoot();
42
43
  const model = resolveModel(str(p.flags, "model"), process.env, process.cwd(), ref);
44
+ assertVendorMatchesRepo(root, creds.agent, vendor, bool(p.flags, "replace"));
43
45
  if (harnessList(p, vendor).includes("claude-code") && !bool(p.flags, "replace")) {
44
46
  const owner = claudeCheckoutOwner(root);
45
47
  if (owner && owner !== ref && owner !== creds.agent)
@@ -75,6 +77,7 @@ export async function join(p, out) {
75
77
  // A second agent of the same vendor in one worktree must not steal the repo mapping. With
76
78
  // --no-bind the credentials are saved and the agent is addressed per call instead.
77
79
  const noBind = bool(p.flags, "no-bind");
80
+ assertVendorMatchesRepo(root, name, vendor, bool(p.flags, "replace"));
78
81
  // --no-bind keeps the repo's mapping, but for Claude Code the hook still runs as the bound agent
79
82
  // in every session here: a second Claude Code agent needs its own worktree, not --no-bind.
80
83
  if (vendor === "claude-code" && !bool(p.flags, "replace")) {
@@ -113,7 +116,7 @@ export async function join(p, out) {
113
116
  ? `Joined project "${json.project.name}" as agent "${name}" (${vendor})${json.agent.role_name ? ` with role ${json.agent.role_name}` : ""}.`
114
117
  : `Joined as account-wide agent "${name}" (${vendor}) with role ${json.agent.role_name}. Project commands take --project <name>; see them with: bschat me`,
115
118
  `Credentials saved to ${path} (private to this machine).`,
116
- `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`,
119
+ `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`,
117
120
  noBind
118
121
  ? `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}.`
119
122
  : `This repo now maps ${vendor} -> ${ref} in ${idPath}, so bschat commands here know who you are, even after a reboot.`,
@@ -126,7 +129,7 @@ export async function join(p, out) {
126
129
  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,
127
130
  json.revived && json.resume ? `Read it before doing anything else.` : null,
128
131
  ``,
129
- 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,
132
+ 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,
130
133
  `Next: bschat me && bschat who && bschat inbox && bschat handoffs --open`,
131
134
  ].filter((l) => l !== null).join("\n");
132
135
  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 } });
@@ -149,6 +152,20 @@ function verifyClaudeHook(root, ref) {
149
152
  }
150
153
  return `Hook verified: ran "${cmd}" successfully as ${ref}.`;
151
154
  }
155
+ /**
156
+ * Refuses when this repo's identity file already says the agent runs in another harness than the
157
+ * one detected (or passed). Learned from fabricbios: sol-reviewer, mapped as the Codex agent in the
158
+ * repo, was saved as Claude Code by a join run where Claude Code's environment was set, so it got
159
+ * no watcher and no thread binding and stalled with three reviews waiting.
160
+ */
161
+ export function assertVendorMatchesRepo(root, name, vendor, replace) {
162
+ const p = findIdentityFile(root);
163
+ if (!p || !p.startsWith(root) || replace)
164
+ return;
165
+ const mapped = Object.entries(readIdentityFile(p).agents).filter(([v, a]) => a.name === name && v !== vendor).map(([v]) => v);
166
+ if (mapped.length)
167
+ throw new CliError("vendor_mismatch", `${p} says ${name} runs in ${mapped.join(" and ")} here, but this command detected ${vendor}`, `If ${name} runs in ${mapped[0]}, run this from that harness or pass --vendor ${mapped[0]}. If the file is wrong, pass --replace.`);
168
+ }
152
169
  /** This machine's one install, at least this CLI's version (installed or upgraded when needed). */
153
170
  function machineInstall() {
154
171
  return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`bschat: ${m}\n`));
@@ -162,3 +179,19 @@ function writeIdentityDryRun(root, vendor, name, replace) {
162
179
  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}".`);
163
180
  }
164
181
  }
182
+ /** Merges bschat's hooks into this machine's ~/.codex/hooks.json; returns its path. */
183
+ function installCodexHooks(bin) {
184
+ const path = codexHooksPath();
185
+ let doc = {};
186
+ if (existsSync(path)) {
187
+ try {
188
+ doc = JSON.parse(readFileSync(path, "utf8"));
189
+ }
190
+ catch {
191
+ throw new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
192
+ }
193
+ }
194
+ mkdirSync(dirname(path), { recursive: true });
195
+ writeFileSync(path, JSON.stringify(withCodexHooks(doc, bin), null, 2) + "\n");
196
+ return path;
197
+ }
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { bindConversation, conversationOfExec } from "../antigravity.js";
2
+ import { bindSession, sessionOfExec } from "../sessions.js";
3
3
  import { reloadLaunchAgent, requireInstall } from "../install.js";
4
4
  import { mkdirSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
@@ -335,10 +335,10 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
335
335
  // Load it from the file now, replacing a running copy: writing a plist changes nothing launchd
336
336
  // has loaded, and a watcher re-pointed at a new session kept waking the old one for two days.
337
337
  reloadLaunchAgent(label, path);
338
- // An Antigravity watcher names its conversation: bind it, so that conversation's hook knows who it is.
339
- const conv = conversationOfExec(exec);
340
- if (conv)
341
- bindConversation(conv, name);
338
+ // A watcher names its session (Antigravity conversation, Codex thread): bind it, so that session's hook knows who it is.
339
+ const sess = sessionOfExec(exec);
340
+ if (sess)
341
+ bindSession(sess.kind, sess.id, name);
342
342
  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] });
343
343
  }
344
344
  function escapeXml(s) {
@@ -151,6 +151,10 @@ export async function wu(p, out) {
151
151
  pushed = remote === null ? (fetchRef(where.branch) ? false : null) : remote === local;
152
152
  if (pushed === false && def.merge.require_pushed)
153
153
  throw new CliError("not_pushed", `${where.branch} is not pushed at ${local?.slice(0, 9)} (origin has ${remote ? remote.slice(0, 9) : "no such branch"})`, `git push -u origin ${where.branch}, then submit again`);
154
+ // Not required here, but a reviewer working from origin (bschat wu review, another machine)
155
+ // cannot fetch it, unless the commit is already on the target (then the branch adds nothing).
156
+ if (pushed === false && !def.merge.require_pushed && isAncestor("HEAD", fetchRef(unitTarget) ? "FETCH_HEAD" : `origin/${unitTarget}`) !== true)
157
+ process.stderr.write(`bschat: ${where.branch} is not on origin at ${local?.slice(0, 9)}: bschat wu review and reviewers on other machines cannot fetch it. git push -u origin ${where.branch}\n`);
154
158
  }
155
159
  }
156
160
  const pr = str(p.flags, "pr") ?? null;
@@ -304,17 +308,33 @@ export async function wu(p, out) {
304
308
  const parent = repoParent();
305
309
  if (!name || !parent)
306
310
  throw new CliError("not_a_repo", "run wu review from a checkout of the project's repository");
307
- if (!fetchRef(unit.branch))
308
- throw new CliError("fetch_failed", `cannot fetch ${unit.branch} from origin`, `Is it pushed? Ask ${unit.owner_name}: git push -u origin ${unit.branch}`);
309
- const remote = fullSha("FETCH_HEAD");
310
- if (!remote)
311
- throw new CliError("fetch_failed", `fetched ${unit.branch} but found no commit`);
312
- if (!remote.startsWith(unit.head))
313
- throw new CliError("head_mismatch", `origin/${unit.branch} is at ${remote.slice(0, 9)} but WU #${n} was submitted at ${unit.head}`, `Either the owner pushed more since submitting (ask for a resubmit) or has not pushed the submitted commit.`);
311
+ // A unit that added no commits (an audit or a diagnosis whose output is evidence) was
312
+ // submitted at a commit already on origin's target: review that commit, no branch needed.
313
+ // Learned from fabricbios: three audits sat behind "cannot fetch the branch" though their
314
+ // head was already on origin/main.
315
+ const target = unit.target ?? (await processDef()).merge.target_branch;
316
+ let remote = null;
317
+ let onTarget = false;
318
+ if (fetchRef(target)) {
319
+ const head = fullSha(unit.head);
320
+ if (head && isAncestor(head, "FETCH_HEAD")) {
321
+ remote = head;
322
+ onTarget = true;
323
+ }
324
+ }
325
+ if (!remote) {
326
+ if (!fetchRef(unit.branch))
327
+ throw new CliError("fetch_failed", `cannot fetch ${unit.branch} from origin`, `Is it pushed? Ask ${unit.owner_name}: git push -u origin ${unit.branch}`);
328
+ remote = fullSha("FETCH_HEAD");
329
+ if (!remote)
330
+ throw new CliError("fetch_failed", `fetched ${unit.branch} but found no commit`);
331
+ if (!remote.startsWith(unit.head))
332
+ throw new CliError("head_mismatch", `origin/${unit.branch} is at ${remote.slice(0, 9)} but WU #${n} was submitted at ${unit.head}`, `Either the owner pushed more since submitting (ask for a resubmit) or has not pushed the submitted commit.`);
333
+ }
314
334
  const path = resolve(parent, `${name}-review-wu${n}`);
315
335
  const made = ensureReviewWorktree(path, remote);
316
336
  const ev = unit.evidence.map((e) => `evidence:${e}`).join(" ") || "(none)";
317
- out.print(`${fmt(unit)}\nReview checkout: ${path} (detached at ${remote.slice(0, 9)}${made.created ? "" : ", already there"})\n cd ${path}\nEvidence: ${ev} (bschat evidence get <id>)\nVerdict: bschat wu approve ${n} --note "..." | bschat wu changes ${n} --note "..."\nWhen finished: git worktree remove ${path}`, { unit, worktree: path, head: remote });
337
+ out.print(`${fmt(unit)}\nReview checkout: ${path} (detached at ${remote.slice(0, 9)}${made.created ? "" : ", already there"})${onTarget ? `\nThe submitted commit is already on origin/${target}: the unit added no commits, so its evidence is the work.` : ""}\n cd ${path}\nEvidence: ${ev} (bschat evidence get <id>)\nVerdict: bschat wu approve ${n} --note "..." | bschat wu changes ${n} --note "..."\nWhen finished: git worktree remove ${path}`, { unit, worktree: path, head: remote });
318
338
  return;
319
339
  }
320
340
  case "show": {
package/dist/harness.js CHANGED
@@ -240,3 +240,23 @@ export function antigravityHooks(bin) {
240
240
  Stop: [cmd("Stop")],
241
241
  };
242
242
  }
243
+ const CODEX_HOOK_MARK = "hook codex";
244
+ /**
245
+ * Merges bschat's hooks into a Codex hooks.json document ({"hooks": {Event: [groups]}}): any
246
+ * earlier bschat group is replaced, every other hook is kept. Commands carry no identity.
247
+ */
248
+ export function withCodexHooks(doc, bin) {
249
+ const hooks = { ...(doc.hooks ?? {}) };
250
+ const cmd = (event) => ({ type: "command", command: `${shellPath(bin)} ${CODEX_HOOK_MARK} --event ${event}`, timeout: 20 });
251
+ const ours = {
252
+ SessionStart: { matcher: "startup|resume|clear|compact", hooks: [cmd("SessionStart")] },
253
+ UserPromptSubmit: { hooks: [cmd("UserPromptSubmit")] },
254
+ PostToolUse: { matcher: "*", hooks: [cmd("PostToolUse")] },
255
+ Stop: { hooks: [cmd("Stop")] },
256
+ };
257
+ for (const [event, group] of Object.entries(ours)) {
258
+ const kept = (hooks[event] ?? []).filter((g) => !(g.hooks ?? []).some((h) => typeof h.command === "string" && h.command.includes(CODEX_HOOK_MARK)));
259
+ hooks[event] = [...kept, group];
260
+ }
261
+ return { ...doc, hooks };
262
+ }
package/dist/help.js CHANGED
@@ -100,10 +100,12 @@ 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 update the same as install --latest: upgrade this machine's bschat and restart its watchers
103
104
  bschat install [<version> | --latest] make or upgrade this machine's one bschat (join does it once) and restart
104
105
  the watchers on it; hooks, repo instructions and watchers all run its path
105
106
  bschat doctor every bschat on this machine and who runs which (PATH, npx caches, this repo's
106
107
  hook and instructions, each watcher's plist versus what launchd runs), with fixes
108
+ bschat codex hooks | bind <thread-id> | sync install bschat's Codex hooks (~/.codex/hooks.json) and say which thread is you
107
109
  bschat antigravity bind <conversation-id> | sync which Antigravity conversation is you, for its hook (watchers bind theirs)
108
110
  bschat wake ack [<n>] acknowledge your watcher's wake-up #n first thing (no n: the one pending here)
109
111
  Liveness: the watcher reports harness activity (Codex rollout / Antigravity conversation
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { feedback } from "./commands/feedback.js";
11
11
  import { goal } from "./commands/goal.js";
12
12
  import { wake } from "./commands/wake.js";
13
13
  import { antigravity } from "./commands/antigravity.js";
14
+ import { codex } from "./commands/codex.js";
14
15
  import { doctor, install } from "./commands/install.js";
15
16
  import { warnIfForeignCopy } from "./install.js";
16
17
  import { processCmd, record, wu, milestones, milestone, lock, askOperator } from "./commands/wu.js";
@@ -51,7 +52,10 @@ const COMMANDS = {
51
52
  goal,
52
53
  wake,
53
54
  antigravity,
55
+ codex,
54
56
  install,
57
+ // `update` is the word people reach for: the same as install, latest unless a version is named.
58
+ update: (p, out) => install(p.positionals[1] ? p : { ...p, flags: { ...p.flags, latest: true } }, out),
55
59
  doctor,
56
60
  wu,
57
61
  process: processCmd,
@@ -0,0 +1,65 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { configRoot } from "./config.js";
5
+ import { CliError } from "./errors.js";
6
+ import { watcherPlists } from "./install.js";
7
+ const file = (kind) => join(configRoot(), `${kind}.json`);
8
+ const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
9
+ function read(kind) {
10
+ if (!existsSync(file(kind)))
11
+ return { conversations: {} };
12
+ try {
13
+ return JSON.parse(readFileSync(file(kind), "utf8"));
14
+ }
15
+ catch {
16
+ throw new CliError("bad_session_map", `${file(kind)} is not valid JSON`, `Remove it and run: bschat ${kind} sync`);
17
+ }
18
+ }
19
+ export function bindSession(kind, id, ref) {
20
+ if (!UUID.test(id))
21
+ throw new CliError("usage", `"${id}" is not ${kind === "codex" ? "a Codex thread" : "an Antigravity conversation"} id (a UUID)`);
22
+ const m = read(kind);
23
+ m.conversations[id.toLowerCase()] = ref;
24
+ mkdirSync(dirname(file(kind)), { recursive: true });
25
+ writeFileSync(file(kind), JSON.stringify(m, null, 2) + "\n");
26
+ }
27
+ export function sessionAgent(kind, id) {
28
+ return read(kind).conversations[id.toLowerCase()] ?? null;
29
+ }
30
+ export const bindConversation = (id, ref) => bindSession("antigravity", id, ref);
31
+ export const conversationAgent = (id) => sessionAgent("antigravity", id);
32
+ /** The Codex thread a wake command addresses (`codex queue --thread <id>`), if any. */
33
+ export function threadOfExec(exec) {
34
+ return /\bcodex\b/.test(exec) && /--thread\b/.test(exec) ? UUID.exec(exec.slice(exec.indexOf("--thread")))?.[0]?.toLowerCase() ?? null : null;
35
+ }
36
+ /** The harness session a wake command addresses, if it names one. */
37
+ export function sessionOfExec(exec) {
38
+ const a = conversationOfExec(exec);
39
+ if (a)
40
+ return { kind: "antigravity", id: a };
41
+ const c = threadOfExec(exec);
42
+ return c ? { kind: "codex", id: c } : null;
43
+ }
44
+ /** The conversation an Antigravity wake command addresses (`agentapi send-message ... <id>`), if any. */
45
+ export function conversationOfExec(exec) {
46
+ return /agentapi\b/.test(exec) ? UUID.exec(exec)?.[0]?.toLowerCase() ?? null : null;
47
+ }
48
+ /** Binds every session an installed watcher wakes (Antigravity conversation, Codex thread) to the agent it runs as. */
49
+ export function syncFromWatchers() {
50
+ const out = [];
51
+ for (const w of watcherPlists()) {
52
+ const r = spawnSync("plutil", ["-convert", "json", "-o", "-", w.path], { encoding: "utf8" });
53
+ if (r.status !== 0)
54
+ continue;
55
+ const args = JSON.parse(r.stdout).ProgramArguments ?? [];
56
+ const exec = args[args.indexOf("--exec") + 1] ?? "";
57
+ const as = args[args.indexOf("--as") + 1];
58
+ const sess = sessionOfExec(exec);
59
+ if (sess && as && args.includes("--as")) {
60
+ bindSession(sess.kind, sess.id, as);
61
+ out.push({ kind: sess.kind, conversation: sess.id, agent: as });
62
+ }
63
+ }
64
+ return out;
65
+ }
package/dist/update.js CHANGED
@@ -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: bschat install --latest (updates this machine's one install and restarts its watchers)\n`);
42
+ process.stderr.write(`[bschat] CLI ${CLI_VERSION} is installed, ${latest} is available: bschat update (upgrades 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.43";
1
+ export const CLI_VERSION = "0.12.45";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.43",
3
+ "version": "0.12.45",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {