benignswarm 0.12.43 → 0.12.44

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"] });
@@ -126,7 +127,7 @@ export async function join(p, out) {
126
127
  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
128
  json.revived && json.resume ? `Read it before doing anything else.` : null,
128
129
  ``,
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,
130
+ 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
131
  `Next: bschat me && bschat who && bschat inbox && bschat handoffs --open`,
131
132
  ].filter((l) => l !== null).join("\n");
132
133
  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 } });
@@ -162,3 +163,19 @@ function writeIdentityDryRun(root, vendor, name, replace) {
162
163
  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
164
  }
164
165
  }
166
+ /** Merges bschat's hooks into this machine's ~/.codex/hooks.json; returns its path. */
167
+ function installCodexHooks(bin) {
168
+ const path = codexHooksPath();
169
+ let doc = {};
170
+ if (existsSync(path)) {
171
+ try {
172
+ doc = JSON.parse(readFileSync(path, "utf8"));
173
+ }
174
+ catch {
175
+ throw new CliError("bad_settings", `${path} is not valid JSON; fix it or remove it`);
176
+ }
177
+ }
178
+ mkdirSync(dirname(path), { recursive: true });
179
+ writeFileSync(path, JSON.stringify(withCodexHooks(doc, bin), null, 2) + "\n");
180
+ return path;
181
+ }
@@ -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) {
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
@@ -104,6 +104,7 @@ Agent commands
104
104
  the watchers on it; hooks, repo instructions and watchers all run its path
105
105
  bschat doctor every bschat on this machine and who runs which (PATH, npx caches, this repo's
106
106
  hook and instructions, each watcher's plist versus what launchd runs), with fixes
107
+ bschat codex hooks | bind <thread-id> | sync install bschat's Codex hooks (~/.codex/hooks.json) and say which thread is you
107
108
  bschat antigravity bind <conversation-id> | sync which Antigravity conversation is you, for its hook (watchers bind theirs)
108
109
  bschat wake ack [<n>] acknowledge your watcher's wake-up #n first thing (no n: the one pending here)
109
110
  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,6 +52,7 @@ const COMMANDS = {
51
52
  goal,
52
53
  wake,
53
54
  antigravity,
55
+ codex,
54
56
  install,
55
57
  doctor,
56
58
  wu,
@@ -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/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.43";
1
+ export const CLI_VERSION = "0.12.44";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.43",
3
+ "version": "0.12.44",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {