benignswarm 0.12.42 → 0.12.43

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.
@@ -0,0 +1,57 @@
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
+ /**
8
+ * Which agent each Antigravity conversation belongs to, on this machine. Antigravity's hooks are
9
+ * configured per workspace, and one workspace often hosts several Antigravity agents (ester has
10
+ * four), so the hook cannot take its identity from the workspace: it looks up the conversationId
11
+ * every event carries. A conversation nobody bound gets nothing, never another agent's messages.
12
+ */
13
+ const file = () => join(configRoot(), "antigravity.json");
14
+ const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
15
+ function read() {
16
+ if (!existsSync(file()))
17
+ return { conversations: {} };
18
+ try {
19
+ return JSON.parse(readFileSync(file(), "utf8"));
20
+ }
21
+ catch {
22
+ throw new CliError("bad_antigravity_map", `${file()} is not valid JSON`, "Remove it and run: bschat antigravity sync");
23
+ }
24
+ }
25
+ export function bindConversation(conversationId, ref) {
26
+ if (!UUID.test(conversationId))
27
+ throw new CliError("usage", `"${conversationId}" is not an Antigravity conversation id (a UUID)`);
28
+ const m = read();
29
+ m.conversations[conversationId.toLowerCase()] = ref;
30
+ mkdirSync(dirname(file()), { recursive: true });
31
+ writeFileSync(file(), JSON.stringify(m, null, 2) + "\n");
32
+ }
33
+ export function conversationAgent(conversationId) {
34
+ return read().conversations[conversationId.toLowerCase()] ?? null;
35
+ }
36
+ /** The conversation an Antigravity wake command addresses (`agentapi send-message ... <id>`), if any. */
37
+ export function conversationOfExec(exec) {
38
+ return /agentapi\b/.test(exec) ? UUID.exec(exec)?.[0]?.toLowerCase() ?? null : null;
39
+ }
40
+ /** Binds every conversation an installed Antigravity watcher wakes to the agent it runs as. */
41
+ export function syncFromWatchers() {
42
+ const out = [];
43
+ for (const w of watcherPlists()) {
44
+ const r = spawnSync("plutil", ["-convert", "json", "-o", "-", w.path], { encoding: "utf8" });
45
+ if (r.status !== 0)
46
+ continue;
47
+ const args = JSON.parse(r.stdout).ProgramArguments ?? [];
48
+ const exec = args[args.indexOf("--exec") + 1] ?? "";
49
+ const as = args[args.indexOf("--as") + 1];
50
+ const conv = conversationOfExec(exec);
51
+ if (conv && as && args.includes("--as")) {
52
+ bindConversation(conv, as);
53
+ out.push({ conversation: conv, agent: as });
54
+ }
55
+ }
56
+ return out;
57
+ }
@@ -0,0 +1,26 @@
1
+ import { str } from "../args.js";
2
+ import { agentRef, loadAgent, resolveAgentName } from "../config.js";
3
+ import { bindConversation, syncFromWatchers } from "../antigravity.js";
4
+ import { CliError } from "../errors.js";
5
+ /**
6
+ * bschat antigravity bind <conversation-id> [--as <agent>] this Antigravity conversation is you: its hook delivers to you
7
+ * bschat antigravity sync bind every conversation an installed watcher wakes
8
+ */
9
+ export async function antigravity(p, out) {
10
+ const sub = p.positionals[1];
11
+ if (sub === "bind") {
12
+ const conv = p.positionals[2];
13
+ if (!conv)
14
+ throw new CliError("usage", "antigravity bind <conversation-id> [--as <agent>] (the id is the folder name under ~/.gemini/antigravity/brain/ that holds your artifacts)");
15
+ const ref = agentRef(loadAgent(resolveAgentName(str(p.flags, "as"))));
16
+ bindConversation(conv, ref);
17
+ out.print(`Antigravity conversation ${conv} is ${ref}: its hook now delivers your mentions and assignments there.`, { conversation: conv, agent: ref });
18
+ return;
19
+ }
20
+ if (sub === "sync") {
21
+ const bound = syncFromWatchers();
22
+ out.print(bound.length ? `Bound ${bound.length} conversation(s) from watchers:\n${bound.map((b) => ` ${b.conversation} -> ${b.agent}`).join("\n")}` : "No Antigravity watcher found on this machine.", { bound });
23
+ return;
24
+ }
25
+ throw new CliError("usage", "antigravity bind <conversation-id> [--as <agent>] | antigravity sync");
26
+ }
@@ -6,6 +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
10
  const HEARTBEAT_MS = 60_000;
10
11
  /** Reads the harness's hook payload from stdin without blocking when there is none. */
11
12
  function readStdinJson() {
@@ -152,6 +153,8 @@ export async function gatherUpdates(name, opts) {
152
153
  */
153
154
  export async function hook(p) {
154
155
  const harness = p.positionals[1] ?? "plain";
156
+ if (harness === "antigravity")
157
+ return antigravityHook(p);
155
158
  const event = str(p.flags, "event") ?? (harness === "claude-code" ? "UserPromptSubmit" : "");
156
159
  let name;
157
160
  try {
@@ -173,31 +176,7 @@ export async function hook(p) {
173
176
  // Standing rules die with the context. On SessionStart (startup, resume, and after a compaction)
174
177
  // re-deliver the role description and the project's process when the agent has not seen this
175
178
  // version, and record that it was shown.
176
- let standing = null;
177
- if (harness === "claude-code" && event === "SessionStart") {
178
- try {
179
- const creds = loadAgent(name);
180
- const client = Client.forAgent(creds, undefined, { presence: false });
181
- const me = await client.call("GET", "/me");
182
- const proc = me.process;
183
- const compacted = input?.source === "compact";
184
- if (proc && (compacted || proc.seen_version !== proc.version)) {
185
- const lines = [
186
- `[bschat] ${compacted ? "Your context was compacted; here is what must survive it." : "Your standing role and process."}`,
187
- me.role ? `Your role: ${me.role.name}. ${me.role.description}` : `You hold no role in ${me.project?.name ?? "this project"}.`,
188
- `Process v${proc.version}: work goes through bschat wu open --tags <from the vocabulary> / submit; reviewers are whoever is qualified for the tags; evidence ${proc.definition.require_evidence_to_submit ? "required" : "optional"} before review; max ${proc.definition.max_open_per_agent} open units; nothing is done until every tag is approved. Details: bschat process.`,
189
- proc.agreements ? `Working agreements:\n${proc.agreements}` : null,
190
- proc.charter ? `Charter (how this project weighs its trade-offs):\n${proc.charter}` : null,
191
- ].filter(Boolean);
192
- standing = lines.join("\n");
193
- if (creds.project && proc.version > 0)
194
- await client.call("POST", `/projects/${creds.project}/process/ack`, { version: proc.version });
195
- }
196
- }
197
- catch (e) {
198
- process.stderr.write(`bschat: could not fetch role/process: ${e.message}\n`);
199
- }
200
- }
179
+ const standing = harness === "claude-code" && event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
201
180
  // The hook firing is proof the harness is working; tell the server, at most once a minute.
202
181
  // The session goal (/goal) rides along from the transcript, and a change goes out at once.
203
182
  if (harness === "claude-code") {
@@ -226,3 +205,98 @@ export async function hook(p) {
226
205
  process.stdout.write(text + "\n");
227
206
  }
228
207
  }
208
+ /**
209
+ * The role and process the agent must hold after a new session or a compaction, when it has not
210
+ * seen this process version (or always after a compaction). Records that it was shown.
211
+ */
212
+ async function standingRules(name, compacted) {
213
+ let standing = null;
214
+ try {
215
+ const creds = loadAgent(name);
216
+ const client = Client.forAgent(creds, undefined, { presence: false });
217
+ const me = await client.call("GET", "/me");
218
+ const proc = me.process;
219
+ if (proc && (compacted || proc.seen_version !== proc.version)) {
220
+ const lines = [
221
+ `[bschat] ${compacted ? "Your context was compacted; here is what must survive it." : "Your standing role and process."}`,
222
+ me.role ? `Your role: ${me.role.name}. ${me.role.description}` : `You hold no role in ${me.project?.name ?? "this project"}.`,
223
+ `Process v${proc.version}: work goes through bschat wu open --tags <from the vocabulary> / submit; reviewers are whoever is qualified for the tags; evidence ${proc.definition.require_evidence_to_submit ? "required" : "optional"} before review; max ${proc.definition.max_open_per_agent} open units; nothing is done until every tag is approved. Details: bschat process.`,
224
+ proc.agreements ? `Working agreements:\n${proc.agreements}` : null,
225
+ proc.charter ? `Charter (how this project weighs its trade-offs):\n${proc.charter}` : null,
226
+ ].filter(Boolean);
227
+ standing = lines.join("\n");
228
+ if (creds.project && proc.version > 0)
229
+ await client.call("POST", `/projects/${creds.project}/process/ack`, { version: proc.version });
230
+ }
231
+ }
232
+ catch (e) {
233
+ process.stderr.write(`bschat: could not fetch role/process: ${e.message}\n`);
234
+ }
235
+ return standing;
236
+ }
237
+ /**
238
+ * Antigravity's hooks (.agents/hooks.json, written by join): SessionStart and PreInvocation inject
239
+ * new mentions and assignments (and the standing rules) as a system message; PostToolUse is a
240
+ * liveness heartbeat; Stop, when the agent is about to go fully idle with something addressed to
241
+ * it, returns "continue" with the new items so it carries on instead of waiting for a wake-up.
242
+ * The agent is found by the conversation, never the workspace (several Antigravity agents share
243
+ * one). Always prints valid JSON and exits 0: a hook must never break the session.
244
+ */
245
+ async function antigravityHook(p) {
246
+ const event = str(p.flags, "event") ?? "";
247
+ const out = (o) => { process.stdout.write(JSON.stringify(o) + "\n"); };
248
+ const input = readStdinJson();
249
+ const conv = typeof input?.conversationId === "string" ? input.conversationId : null;
250
+ let ref = conv ? conversationAgent(conv) : null;
251
+ if (conv && !ref) {
252
+ try {
253
+ syncFromWatchers();
254
+ }
255
+ catch (e) {
256
+ process.stderr.write(`bschat: could not read watchers: ${e.message}\n`);
257
+ }
258
+ ref = conversationAgent(conv);
259
+ }
260
+ if (!ref)
261
+ return out({}); // a conversation nobody bound: nothing, never another agent's messages
262
+ let name;
263
+ try {
264
+ name = resolveAgentName(ref);
265
+ }
266
+ catch {
267
+ return out({});
268
+ }
269
+ if (typeof input?.modelName === "string" && input.modelName) {
270
+ const st = readState(name);
271
+ if (st.model !== input.modelName)
272
+ writeState(name, { ...st, model: input.modelName, model_observed_at: Date.now() });
273
+ }
274
+ const st = readState(name);
275
+ if (Date.now() - (st.heartbeat_at ?? 0) > HEARTBEAT_MS) {
276
+ try {
277
+ await heartbeatNow(Client.forAgent(loadAgent(name), undefined, { presence: false }), "antigravity-hook");
278
+ writeState(name, { ...readState(name), heartbeat_at: Date.now() });
279
+ }
280
+ catch (e) {
281
+ process.stderr.write(`bschat: heartbeat failed: ${e.message}\n`);
282
+ }
283
+ }
284
+ if (event === "PostToolUse")
285
+ return out({});
286
+ if (event === "Stop") {
287
+ if (input?.fullyIdle !== true)
288
+ return out({});
289
+ // Only something addressed to it keeps it going; chatter waits for its next turn.
290
+ const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true });
291
+ if (!peek || (peek.tier !== "direct" && peek.tier !== "role"))
292
+ return out({});
293
+ const u = await gatherUpdates(name, { force: true, delivery: "hook" });
294
+ return out(u ? { decision: "continue", reason: `${u.text}\nHandle these, then carry on with what you were doing.` } : {});
295
+ }
296
+ if (event !== "SessionStart" && event !== "PreInvocation")
297
+ return out({});
298
+ const standing = event === "SessionStart" ? await standingRules(name, false) : null;
299
+ const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
300
+ const text = [standing, u?.text].filter(Boolean).join("\n\n");
301
+ return out(text ? { injectSteps: [{ systemMessage: { systemMessage: text } }] } : {});
302
+ }
@@ -126,7 +126,7 @@ export async function join(p, out) {
126
126
  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
127
  json.revived && json.resume ? `Read it before doing anything else.` : null,
128
128
  ``,
129
- 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,
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
130
  `Next: bschat me && bschat who && bschat inbox && bschat handoffs --open`,
131
131
  ].filter((l) => l !== null).join("\n");
132
132
  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 } });
@@ -1,4 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { bindConversation, conversationOfExec } from "../antigravity.js";
2
3
  import { reloadLaunchAgent, requireInstall } from "../install.js";
3
4
  import { mkdirSync, writeFileSync } from "node:fs";
4
5
  import { homedir } from "node:os";
@@ -334,6 +335,10 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
334
335
  // Load it from the file now, replacing a running copy: writing a plist changes nothing launchd
335
336
  // has loaded, and a watcher re-pointed at a new session kept waking the old one for two days.
336
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);
337
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] });
338
343
  }
339
344
  function escapeXml(s) {
package/dist/harness.js CHANGED
@@ -149,6 +149,18 @@ export function installForHarness(root, harness, files, agentName, apiUrl, bin)
149
149
  mkdirSync(dirname(p), { recursive: true });
150
150
  writeFileSync(p, `---\ntrigger: always_on\ndescription: "How to use bschat, the agent chat for this project"\n---\n\n${pointer(agentName, apiUrl, bin)}\n`);
151
151
  written.push(p);
152
+ const hp = join(root, ".agents", "hooks.json");
153
+ let hooks = {};
154
+ if (existsSync(hp)) {
155
+ try {
156
+ hooks = JSON.parse(readFileSync(hp, "utf8"));
157
+ }
158
+ catch {
159
+ throw new CliError("bad_settings", `${hp} is not valid JSON; fix it or remove it`);
160
+ }
161
+ }
162
+ writeFileSync(hp, JSON.stringify({ ...hooks, bschat: antigravityHooks(bin) }, null, 2) + "\n");
163
+ written.push(hp);
152
164
  break;
153
165
  }
154
166
  case "gemini-cli": {
@@ -214,3 +226,17 @@ export function claudeCheckoutTaken(root, owner, name) {
214
226
  const sibling = join(dirname(root), `${basename(root)}-${name}`);
215
227
  return new CliError("checkout_taken", `this checkout's Claude Code hook runs as ${owner} for every Claude Code session opened here, so ${name} would be handed ${owner}'s messages (and they would count as delivered)`, `Give ${name} its own worktree: git -C ${root} worktree add ${sibling} then start Claude Code in ${sibling} and run this command there. (--replace makes ${name} this checkout's Claude Code agent instead of ${owner}.)`);
216
228
  }
229
+ /**
230
+ * The `bschat` entry of an Antigravity workspace's .agents/hooks.json. The command carries no
231
+ * identity: several Antigravity agents share a workspace, so the hook finds its agent by the
232
+ * conversation (`bschat antigravity bind`, or a watcher installed for that conversation).
233
+ */
234
+ export function antigravityHooks(bin) {
235
+ const cmd = (event) => ({ type: "command", command: `${shellPath(bin)} hook antigravity --event ${event}`, timeout: 20 });
236
+ return {
237
+ SessionStart: [cmd("SessionStart")],
238
+ PreInvocation: [cmd("PreInvocation")],
239
+ PostToolUse: [{ matcher: "*", hooks: [cmd("PostToolUse")] }],
240
+ Stop: [cmd("Stop")],
241
+ };
242
+ }
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 antigravity bind <conversation-id> | sync which Antigravity conversation is you, for its hook (watchers bind theirs)
107
108
  bschat wake ack [<n>] acknowledge your watcher's wake-up #n first thing (no n: the one pending here)
108
109
  Liveness: the watcher reports harness activity (Codex rollout / Antigravity conversation
109
110
  found from the session id in --exec, or --activity <file-or-dir>) so you are not shown
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import { watch } from "./commands/watch.js";
10
10
  import { feedback } from "./commands/feedback.js";
11
11
  import { goal } from "./commands/goal.js";
12
12
  import { wake } from "./commands/wake.js";
13
+ import { antigravity } from "./commands/antigravity.js";
13
14
  import { doctor, install } from "./commands/install.js";
14
15
  import { warnIfForeignCopy } from "./install.js";
15
16
  import { processCmd, record, wu, milestones, milestone, lock, askOperator } from "./commands/wu.js";
@@ -49,6 +50,7 @@ const COMMANDS = {
49
50
  feedback,
50
51
  goal,
51
52
  wake,
53
+ antigravity,
52
54
  install,
53
55
  doctor,
54
56
  wu,
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.42";
1
+ export const CLI_VERSION = "0.12.43";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.42",
3
+ "version": "0.12.43",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {