benignswarm 0.12.75 → 0.12.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/args.js CHANGED
@@ -2,9 +2,9 @@ import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
3
  // These options accept comma-separated collections, so repeating them should
4
4
  // append another collection instead of discarding earlier values.
5
- export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant"];
6
- export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "for", "until", "reason", "at", "priority"];
7
- export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel"];
5
+ export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant", "requires"];
6
+ export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions", "cardinality", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "follow-delay", "env", "scope", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "by", "on", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text"];
7
+ export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel"];
8
8
  export function parse(argv) {
9
9
  const options = {};
10
10
  for (const f of STRING_FLAGS)
@@ -0,0 +1,41 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ /** Run every declaration and preserve failures as results, so dispatch can explain a missing tool. */
6
+ export function probeCapabilities(definitions, projectDir) {
7
+ return definitions.map((definition) => {
8
+ let cwd = homedir();
9
+ let temporary = null;
10
+ try {
11
+ if (definition.scope === "worktree") {
12
+ temporary = mkdtempSync(join(tmpdir(), "bschat-capability-"));
13
+ const path = join(temporary, "worktree");
14
+ const added = spawnSync("git", ["worktree", "add", "--quiet", "--detach", path, "HEAD"], { cwd: projectDir, encoding: "utf8", timeout: 120_000 });
15
+ if (added.status !== 0)
16
+ throw new Error((added.stderr || added.stdout || "git worktree add failed").trim().split(/\r?\n/, 1)[0]);
17
+ const full = spawnSync("git", ["-C", path, "sparse-checkout", "disable"], { encoding: "utf8", timeout: 30_000 });
18
+ if (full.status !== 0)
19
+ throw new Error(full.error?.message ?? (full.stderr || full.stdout || "git sparse-checkout disable failed").trim());
20
+ cwd = path;
21
+ }
22
+ const result = spawnSync("/bin/sh", ["-lc", definition.probe], { cwd, encoding: "utf8", timeout: 60_000, maxBuffer: 64 * 1024 });
23
+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim().split(/\r?\n/, 1)[0] ?? "";
24
+ const ok = result.status === 0 && !result.error;
25
+ return { name: definition.name, ok, version: ok ? (result.stdout.trim().split(/\r?\n/, 1)[0]?.slice(0, 200) || null) : null, error: ok ? null : (result.error?.message ?? (output || `probe exited ${result.status}`)).slice(0, 500) };
26
+ }
27
+ catch (error) {
28
+ return { name: definition.name, ok: false, version: null, error: error.message.split(/\r?\n/, 1)[0] };
29
+ }
30
+ finally {
31
+ if (temporary) {
32
+ try {
33
+ spawnSync("git", ["worktree", "remove", "--force", join(temporary, "worktree")], { cwd: projectDir, encoding: "utf8", timeout: 30_000 });
34
+ }
35
+ finally {
36
+ rmSync(temporary, { recursive: true, force: true });
37
+ }
38
+ }
39
+ }
40
+ });
41
+ }
package/dist/client.js CHANGED
@@ -8,11 +8,13 @@ export class Client {
8
8
  key;
9
9
  auto;
10
10
  agentName;
11
- constructor(url, key, auto, agentName) {
11
+ machineIdentity;
12
+ constructor(url, key, auto, agentName, machineIdentity) {
12
13
  this.url = url;
13
14
  this.key = key;
14
15
  this.auto = auto;
15
16
  this.agentName = agentName;
17
+ this.machineIdentity = machineIdentity;
16
18
  }
17
19
  /**
18
20
  * presence: send the X-Bschat-Auto header, which refreshes the agent's automatic status and
@@ -20,7 +22,8 @@ export class Client {
20
22
  * by the hook or the watcher, which say nothing about whether the agent is alive.
21
23
  */
22
24
  static forAgent(c, model, opts = {}) {
23
- return new Client(c.url, c.key, opts.presence === false ? null : { ...collectAuto({ model, machine: c.machine, effort: resolveEffort(opts.effort, process.env, c.vendor) }) }, c.agent);
25
+ const auto = collectAuto({ model, machine: c.machine, effort: resolveEffort(opts.effort, process.env, c.vendor) });
26
+ return new Client(c.url, c.key, opts.presence === false ? null : { ...auto }, c.agent, opts.machineIdentity ? auto.machine : null);
24
27
  }
25
28
  static forAdmin(c) {
26
29
  return new Client(c.url, c.key, null);
@@ -32,6 +35,8 @@ export class Client {
32
35
  const h = { authorization: `Bearer ${this.key}`, "user-agent": `bschat-cli/${CLI_VERSION}` };
33
36
  if (this.auto)
34
37
  h["x-bschat-auto"] = JSON.stringify(this.auto);
38
+ if (this.machineIdentity)
39
+ h["x-bschat-machine"] = this.machineIdentity;
35
40
  return h;
36
41
  }
37
42
  /**
@@ -213,6 +213,38 @@ export async function send(p, out) {
213
213
  }
214
214
  export async function read(p, out) {
215
215
  const channel = p.positionals[1];
216
+ if (bool(p.flags, "pending")) {
217
+ if (channel)
218
+ throw new CliError("usage", "use either read <channel> or read --pending");
219
+ const { client, creds } = agentClient(p);
220
+ const ref = agentRef(creds);
221
+ const state = readState(ref);
222
+ const pending = state.pending_reads ?? [];
223
+ if (!pending.length) {
224
+ out.print("(no deferred channel reads)", { messages: [], pending: 0 });
225
+ return;
226
+ }
227
+ const channelRead = { ...(state.channel_read ?? {}) };
228
+ const messages = [];
229
+ for (const item of pending) {
230
+ let cursor = item.since;
231
+ let finalCursor = cursor;
232
+ for (;;) {
233
+ const qs = new URLSearchParams({ since: String(cursor), limit: "100" });
234
+ const result = await client.call("GET", `/projects/${item.project}/channels/${item.channel}/messages?${qs}`);
235
+ messages.push(...result.messages);
236
+ finalCursor = result.cursor;
237
+ const last = result.messages.length ? result.messages[result.messages.length - 1].seq : undefined;
238
+ if (last === undefined || last <= cursor || last >= result.cursor)
239
+ break;
240
+ cursor = last;
241
+ }
242
+ channelRead[`${item.project}/${item.channel}`] = finalCursor;
243
+ }
244
+ writeState(ref, { ...state, pending_reads: undefined, channel_read: channelRead });
245
+ out.print(`${messages.length ? messages.map(fmtMessage).join("\n") : "(no messages)"}\nRead ${pending.length} deferred channel${pending.length === 1 ? "" : "s"}.`, { messages, pending: pending.length });
246
+ return;
247
+ }
216
248
  if (!channel)
217
249
  throw new CliError("usage", "read <channel> [--since seq] [--limit n] [--follow]");
218
250
  const { client, creds } = agentClient(p);
@@ -229,7 +261,17 @@ export async function read(p, out) {
229
261
  const r = await client.call("GET", `/projects/${project}/channels/${channel}/messages?${qs}`);
230
262
  const text = r.messages.length ? r.messages.map(fmtMessage).join("\n") : "(no messages)";
231
263
  const st = readState(agentRef(creds));
232
- writeState(agentRef(creds), { ...st, channel_read: { ...(st.channel_read ?? {}), [`${project}/${channel}`]: r.cursor } });
264
+ const pendingReads = (st.pending_reads ?? []).flatMap((item) => {
265
+ if (item.project !== project || item.channel !== channel || since === undefined || Number(since) > item.since)
266
+ return [item];
267
+ const lastShown = r.messages.length ? Number(r.messages[r.messages.length - 1].seq) : undefined;
268
+ if (lastShown === undefined)
269
+ return r.cursor <= item.since ? [] : [item];
270
+ if (lastShown >= r.cursor)
271
+ return [];
272
+ return lastShown > item.since ? [{ ...item, since: lastShown }] : [item];
273
+ });
274
+ writeState(agentRef(creds), { ...st, channel_read: { ...(st.channel_read ?? {}), [`${project}/${channel}`]: r.cursor }, pending_reads: pendingReads.length ? pendingReads : undefined });
233
275
  out.print(`${text}\ncursor: ${r.cursor}`, r);
234
276
  }
235
277
  function follow(client, path, out) {
@@ -21,6 +21,113 @@ function readStdinJson() {
21
21
  }
22
22
  }
23
23
  const THROTTLE_MS = 20_000;
24
+ const utf8Bytes = (text) => new TextEncoder().encode(text).byteLength;
25
+ const DELIVERY_BUDGET_BYTES = 4000;
26
+ /** Preserve operator messages, then shorten lower-priority content to counted pointers until the complete payload fits. */
27
+ export function budgetDelivery(input) {
28
+ const protectedDirect = input.protectedDirect ?? [];
29
+ const budget = input.budget ?? DELIVERY_BUDGET_BYTES;
30
+ let header = input.header;
31
+ let footer = [...input.footer];
32
+ let itemLabel = "Assigned list items (details: bschat item show <id>):";
33
+ const compose = (direct, items, followed, digest, deferredDirect) => [
34
+ ...(input.prefix ?? []), header, ...protectedDirect, ...direct,
35
+ ...(deferredDirect ? [deferredDirect] : []),
36
+ ...(items.length ? [itemLabel, ...items] : []),
37
+ ...(followed ? [followed] : []), ...(digest ? [digest] : []), ...footer, ...(input.suffix ?? []),
38
+ ].filter(Boolean).join("\n");
39
+ let direct = input.direct;
40
+ let items = input.items;
41
+ let followed = input.followed.length ? ["Followed channels:", ...input.followed].join("\n") : "";
42
+ let digest = input.digest.length ? `Unread elsewhere: ${input.digest.join("; ")}` : "";
43
+ let deferredDirect = "";
44
+ let text = compose(direct, items, followed, digest, deferredDirect);
45
+ if (utf8Bytes(text) > budget) {
46
+ followed = input.followed.length ? `${input.followed.length} followed-channel messages deferred; read with ${input.readCommand}.` : "";
47
+ digest = input.digest.length ? `${input.digest.length} unread channel summaries deferred; use bschat inbox --unread, then bschat read <channel> --since <seq>.` : "";
48
+ text = compose(direct, items, followed, digest, deferredDirect);
49
+ }
50
+ let itemBytes = items.join("\n");
51
+ if (utf8Bytes(text) > budget && items.length) {
52
+ itemBytes = `${items.length} assigned list item${items.length === 1 ? "" : "s"} deferred; use ${input.itemPointer ?? "bschat inbox --unread, then bschat item show <id>"}.`;
53
+ items = [itemBytes];
54
+ text = compose(direct, items, followed, digest, deferredDirect);
55
+ }
56
+ if (utf8Bytes(text) > budget && direct.length) {
57
+ deferredDirect = `${direct.length} addressed message${direct.length === 1 ? "" : "s"} deferred; read with ${input.directPointer ?? "bschat inbox --unread"}.`;
58
+ direct = [];
59
+ text = compose(direct, items, followed, digest, deferredDirect);
60
+ }
61
+ // A large rules prefix leaves only a small allowance for the envelope. Apply the remaining
62
+ // bytes to every category: keep the full rules, protected operator content and one valid
63
+ // retrieval pointer per deferred kind, while removing labels and prose that duplicate them.
64
+ if (utf8Bytes(text) > budget) {
65
+ footer = [];
66
+ header = "";
67
+ itemLabel = "";
68
+ if (items.length && input.items.length) {
69
+ itemBytes = `${input.items.length} items; ${input.itemPointer ?? "bschat inbox --unread"}`;
70
+ items = [itemBytes];
71
+ }
72
+ if (followed)
73
+ followed = `${input.followed.length} followed messages; ${input.followedPointer ?? input.readCommand}`;
74
+ if (digest)
75
+ digest = `${input.digest.length} unread channels; ${input.digestPointer ?? "bschat inbox --unread"}`;
76
+ if (deferredDirect)
77
+ deferredDirect = `${input.direct.length} messages; ${input.directPointer ?? "bschat inbox --unread"}`;
78
+ text = compose(direct, items, followed, digest, deferredDirect);
79
+ }
80
+ if (utf8Bytes(text) > budget && followed && digest && input.followedPointer === input.digestPointer) {
81
+ followed = `${input.followed.length} followed`;
82
+ digest = `${input.digest.length} unread; ${input.digestPointer}`;
83
+ text = compose(direct, items, followed, digest, deferredDirect);
84
+ }
85
+ if (utf8Bytes(text) > budget && deferredDirect && items.length && input.directPointer === input.itemPointer) {
86
+ itemBytes = `${input.items.length} items`;
87
+ items = [itemBytes];
88
+ text = compose(direct, items, followed, digest, deferredDirect);
89
+ }
90
+ const by_kind = {
91
+ direct: utf8Bytes([...protectedDirect, ...direct, ...(deferredDirect ? [deferredDirect] : [])].join("\n")),
92
+ items: utf8Bytes(itemBytes),
93
+ followed: utf8Bytes(followed),
94
+ digest: utf8Bytes(digest),
95
+ };
96
+ return { text, bytes: utf8Bytes(text), by_kind };
97
+ }
98
+ /** Re-render an update with its complete wrapper/rules included in the same byte budget. */
99
+ export function formatUpdates(u, prefix = [], suffix = []) {
100
+ const commandLines = suffix.filter((line) => /^\s+bschat read\b.*--since\b/.test(line));
101
+ const compactSuffix = commandLines.length > 8
102
+ ? [...suffix.filter((line) => !/^\s+bschat read\b.*--since\b/.test(line)), ` ${commandLines.length} channel reads deferred; run bschat read --pending`]
103
+ : suffix;
104
+ const result = budgetDelivery({ ...u.parts, prefix, suffix: compactSuffix });
105
+ return { ...u, text: result.text, delivery: { bytes: result.bytes, by_kind: result.by_kind } };
106
+ }
107
+ /** Budget standalone rules too, and defer their acknowledgement until the selected text is emitted. */
108
+ export function formatHookDelivery(u, standing) {
109
+ let text;
110
+ let by_kind;
111
+ const budget = u?.parts.budget ?? DELIVERY_BUDGET_BYTES;
112
+ if (u) {
113
+ let formatted = formatUpdates(u, standing ? [standing.text] : []);
114
+ if (formatted.delivery.bytes > budget && standing && standing.text !== standing.deferredText) {
115
+ formatted = formatUpdates(u, [standing.deferredText]);
116
+ }
117
+ text = formatted.text;
118
+ by_kind = formatted.delivery.by_kind;
119
+ }
120
+ else {
121
+ const render = (ruleText) => budgetDelivery({ header: "", direct: [], items: [], followed: [], digest: [], footer: [], readCommand: "bschat process", prefix: standing ? [ruleText] : [], budget });
122
+ let rendered = render(standing?.text ?? "");
123
+ if (rendered.bytes > budget && standing && standing.text !== standing.deferredText)
124
+ rendered = render(standing.deferredText);
125
+ text = rendered.text;
126
+ by_kind = rendered.by_kind;
127
+ }
128
+ const acknowledge = !!standing?.acknowledge && text.includes(standing.text) && standing.text !== standing.deferredText;
129
+ return { text, by_kind, acknowledge };
130
+ }
24
131
  /**
25
132
  * Collects everything new for an identity and advances its cursors. Returns null when nothing
26
133
  * is new. Shared by the harness hook and `bschat watch`. Never throws for server/network
@@ -60,12 +167,17 @@ export async function gatherUpdates(name, opts) {
60
167
  const channelRead = { ...(state.channel_read ?? {}) };
61
168
  const follows = new Set(state.follows ?? []);
62
169
  const digest = [];
170
+ const digestCommands = [];
171
+ const digestReads = new Map();
63
172
  const followed = [];
64
173
  const readCommands = [];
174
+ const pendingReads = new Map();
65
175
  try {
66
176
  const projects = creds.project ? [creds.project] : ((await client.call("GET", "/me")).projects ?? []).map((x) => x.name);
67
177
  for (const project of projects) {
68
- const { cursors } = await client.call("GET", `/projects/${project}/channels/cursors`);
178
+ const since = Object.fromEntries(Object.entries(channelRead).filter(([k]) => k.startsWith(`${project}/`)).map(([k, v]) => [k.slice(project.length + 1), v]));
179
+ const sinceQuery = Object.keys(since).length ? `?since=${encodeURIComponent(JSON.stringify(since))}` : "";
180
+ const { cursors } = await client.call("GET", `/projects/${project}/channels/cursors${sinceQuery}`);
69
181
  for (const ch of cursors) {
70
182
  const key = `${project}/${ch.name}`;
71
183
  const last = channelRead[key];
@@ -73,7 +185,7 @@ export async function gatherUpdates(name, opts) {
73
185
  channelRead[key] = ch.cursor;
74
186
  continue;
75
187
  }
76
- const unread = ch.cursor - last;
188
+ const unread = ch.unread ?? (ch.cursor - last);
77
189
  if (unread <= 0)
78
190
  continue;
79
191
  // Only followed channels earn a read command in a wake-up. Unfollowed traffic is one digest
@@ -81,6 +193,7 @@ export async function gatherUpdates(name, opts) {
81
193
  // that was never for it.
82
194
  if (follows.has(key)) {
83
195
  readCommands.push(`bschat read ${creds.project ? "" : `--project ${project} `}${ch.name} --since ${last}`);
196
+ pendingReads.set(key, { project, channel: ch.name, since: last });
84
197
  const r = await client.call("GET", `/projects/${project}/channels/${ch.name}/messages?since=${last}&limit=5`);
85
198
  const seen = new Set(messages.map((m) => m.id));
86
199
  const others = r.messages.filter((m) => m.agent_name !== creds.agent && !seen.has(m.id));
@@ -92,7 +205,10 @@ export async function gatherUpdates(name, opts) {
92
205
  channelRead[key] = shown;
93
206
  }
94
207
  else {
95
- digest.push(`#${ch.name}${creds.project ? "" : ` [${project}]`}: ${unread} unread (bschat read ${ch.name} --since ${last})`);
208
+ const readCommand = `bschat read ${creds.project ? "" : `--project ${project} `}${ch.name} --since ${last}`;
209
+ digestCommands.push(readCommand);
210
+ digestReads.set(key, { project, channel: ch.name, since: last });
211
+ digest.push(`#${ch.name}${creds.project ? "" : ` [${project}]`}: ${unread} unread (${readCommand})`);
96
212
  }
97
213
  }
98
214
  }
@@ -101,13 +217,24 @@ export async function gatherUpdates(name, opts) {
101
217
  process.stderr.write(`bschat: channels: ${e.message}\n`);
102
218
  }
103
219
  next.channel_read = channelRead;
220
+ const deferredReads = readCommands.length > 8 ? [...pendingReads.values()].slice(8) : [];
221
+ const pendingBacklog = [...pendingReads.values(), ...digestReads.values()];
222
+ if (pendingBacklog.length) {
223
+ const combined = new Map((state.pending_reads ?? []).map((item) => [`${item.project}/${item.channel}`, item]));
224
+ for (const item of pendingBacklog) {
225
+ const key = `${item.project}/${item.channel}`;
226
+ const previous = combined.get(key);
227
+ combined.set(key, previous ? { ...item, since: Math.min(previous.since, item.since) } : item);
228
+ }
229
+ next.pending_reads = [...combined.values()];
230
+ }
104
231
  if (opts.dryRun) {
105
232
  // Persist only the baselines of channels never seen before; everything else stays unread.
106
233
  const merged = { ...(state.channel_read ?? {}) };
107
234
  for (const [k, v] of Object.entries(channelRead))
108
235
  if (merged[k] === undefined)
109
236
  merged[k] = v;
110
- writeState(name, { ...state, channel_read: merged });
237
+ writeState(name, { ...state, channel_read: merged, ...(next.pending_reads ? { pending_reads: next.pending_reads } : {}) });
111
238
  }
112
239
  else {
113
240
  writeState(name, next);
@@ -115,6 +242,8 @@ export async function gatherUpdates(name, opts) {
115
242
  if (!messages.length && !items.length && !digest.length && !followed.length)
116
243
  return null;
117
244
  const lines = messages.map((m) => `${creds.project ? "" : `[${m.project}] `}${fmtMessage(m)}${m.reply_to_seq ? ` (reply to #${m.reply_to_seq})` : ""}`);
245
+ const protectedDirect = messages.flatMap((m, i) => m.role_name === "human" ? [lines[i]] : []);
246
+ const directLines = messages.flatMap((m, i) => m.role_name === "human" ? [] : [lines[i]]);
118
247
  const itemLines = items.map((i) => ` list "${i.list}"${i.project && !creds.project ? ` [${i.project}]` : ""}: [${i.status}] ${i.title} (item ${i.id}, by ${i.updated_by})`);
119
248
  const head = [
120
249
  messages.length ? `${messages.length} message${messages.length === 1 ? "" : "s"} for you` : null,
@@ -130,21 +259,42 @@ export async function gatherUpdates(name, opts) {
130
259
  footer.push(`Nobody addressed you. Reply in chat only if you have something to contribute: bschat send ${proj}<channel> --reply-to <seq> "...".`);
131
260
  if (messages.length || followed.length)
132
261
  footer.push(`Other agents cannot see what you write in this session; only bschat messages reach them.`);
133
- const text = [
134
- opts.delivery === "watch"
135
- ? `[bschat] Delivered by your BenignSwarm watcher, not typed by the user. ${head} (${name}):`
136
- : `[bschat] ${head} (${name}) on BenignSwarm:`,
137
- ...lines,
138
- ...(items.length ? [`Assigned list items (bschat item show <id>; bschat item set <id> --status ...):`, ...itemLines] : []),
139
- ...(followed.length ? [`Followed channels:`, ...followed] : []),
140
- ...(digest.length ? [`Unread elsewhere: ${digest.join("; ")}`] : []),
141
- ...footer,
142
- ].join("\n");
262
+ const header = opts.delivery === "watch"
263
+ ? `[bschat] Delivered by your BenignSwarm watcher, not typed by the user. ${head} (${name}):`
264
+ : `[bschat] ${head} (${name}) on BenignSwarm:`;
265
+ const budget = opts.delivery === "watch" ? 3500 : opts.continuation ? 3900 : DELIVERY_BUDGET_BYTES;
266
+ // The inbox cursor was advanced when gathering these items. A single explicit time cursor
267
+ // retrieves every deferred addressed message across channels and keeps the pointer within
268
+ // the budget even when the messages span many channels.
269
+ const firstDeferred = messages.filter((m) => m.role_name !== "human").map((m) => m.created_at).sort()[0];
270
+ const firstItemDeferred = items.map((item) => item.updated_at).filter((at) => !!at).sort()[0];
271
+ const firstInboxDeferred = [firstDeferred, firstItemDeferred].filter((at) => !!at).sort()[0];
272
+ const inboxPointer = firstInboxDeferred ? `bschat inbox --after ${new Date(Date.parse(firstInboxDeferred) - 1).toISOString()}` : "bschat inbox --unread";
273
+ const directPointer = firstDeferred ? inboxPointer : "bschat inbox --unread";
274
+ const itemPointer = firstItemDeferred ? inboxPointer : "bschat inbox --unread";
275
+ const followedPointer = pendingReads.size ? "bschat read --pending" : readCommands.join("; ") || "bschat read --pending";
276
+ const parts = { header, protectedDirect, direct: directLines, directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "bschat read --pending" : "bschat inbox --unread", items: itemLines, followed, digest, footer, readCommand: `bschat read <channel> --since <seq>`, budget };
277
+ const delivery = budgetDelivery(parts);
143
278
  const operator = messages.filter((m) => m.role_name === "human").map((m) => m.created_at).sort().pop() ?? null;
144
- const cmds = [...(messages.length || items.length ? ["bschat inbox --unread"] : []), ...readCommands];
279
+ const visibleReadCommands = readCommands.slice(0, 8);
280
+ if (deferredReads.length)
281
+ visibleReadCommands.push("bschat read --pending");
282
+ const cmds = [...(messages.length || items.length ? ["bschat inbox --unread"] : []), ...visibleReadCommands];
145
283
  const direct = items.length > 0 || messages.some((m) => m.role_name === "human" || !!m.reply_to_seq || new RegExp(`(^|[^\\w@])@${name.replace(/[-_]/g, "\\$&")}(?![\\w-])`).test(m.body));
146
284
  const tier = direct ? "direct" : messages.length ? "role" : followed.length ? "followed" : "digest";
147
- return { text, counts: { messages: messages.length, items: items.length, followed: followed.length, digest: digest.length }, latestOperatorAt: operator, readCommands: cmds, tier };
285
+ return { text: delivery.text, counts: { messages: messages.length, items: items.length, followed: followed.length, digest: digest.length }, latestOperatorAt: operator, readCommands: cmds, tier, delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
286
+ }
287
+ export async function reportDelivery(name, text, kinds, source = "hook") {
288
+ try {
289
+ const client = Client.forAgent(loadAgent(name), undefined, { presence: false });
290
+ await client.call("POST", "/agents/me/heartbeat", {
291
+ active_at: new Date().toISOString(), source: `bschat-${source}-delivery`, activity: null,
292
+ delivery: { bytes: utf8Bytes(text), by_kind: { ...kinds, rules: Math.max(0, utf8Bytes(text) - Object.values(kinds).reduce((a, b) => a + b, 0)) } },
293
+ });
294
+ }
295
+ catch (e) {
296
+ process.stderr.write(`bschat: delivery metric failed: ${e.message}\n`);
297
+ }
148
298
  }
149
299
  /**
150
300
  * Harness hook entry point. Prints new items in the format the harness expects for injecting
@@ -199,44 +349,79 @@ export async function hook(p) {
199
349
  }
200
350
  }
201
351
  const u = await gatherUpdates(name, { force: !!p.flags.force, model: str(p.flags, "model") });
202
- const text = [standing, u?.text].filter(Boolean).join("\n\n");
352
+ const formatted = formatHookDelivery(u, standing);
353
+ const text = formatted.text;
203
354
  if (!text)
204
355
  return;
356
+ await reportDelivery(name, text, formatted.by_kind);
205
357
  if (harness === "claude-code") {
206
358
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } }) + "\n");
207
359
  }
208
360
  else {
209
361
  process.stdout.write(text + "\n");
210
362
  }
363
+ await acknowledgeStanding(name, standing, formatted.acknowledge);
211
364
  }
212
365
  /**
213
366
  * The role and process the agent must hold after a new session or a compaction, when it has not
214
367
  * seen this process version (or always after a compaction). Records that it was shown.
215
368
  */
216
369
  async function standingRules(name, compacted) {
217
- let standing = null;
218
370
  try {
219
371
  const creds = loadAgent(name);
220
- const client = Client.forAgent(creds, undefined, { presence: false });
221
- const me = await client.call("GET", "/me");
372
+ const me = await Client.forAgent(creds, undefined, { presence: false }).call("GET", "/me");
222
373
  const proc = me.process;
223
- if (proc && (compacted || proc.seen_version !== proc.version)) {
224
- const lines = [
225
- `[bschat] ${compacted ? "Your context was compacted; here is what must survive it." : "Your standing role and process."}`,
226
- me.role ? `Your role: ${me.role.name}. ${me.role.description}` : `You hold no role in ${me.project?.name ?? "this project"}.`,
227
- `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.`,
228
- proc.agreements ? `Working agreements:\n${proc.agreements}` : null,
229
- proc.charter ? `Charter (how this project weighs its trade-offs):\n${proc.charter}` : null,
230
- ].filter(Boolean);
231
- standing = lines.join("\n");
232
- if (creds.project && proc.version > 0)
233
- await client.call("POST", `/projects/${creds.project}/process/ack`, { version: proc.version });
234
- }
374
+ if (!proc)
375
+ return null;
376
+ const roleIdentity = me.role ? `Your role: ${me.role.name}.` : `You hold no role in ${me.project?.name ?? "this project"}.`;
377
+ const roleLine = me.role ? `${roleIdentity} ${me.role.description}` : roleIdentity;
378
+ const rendered = renderStandingRules(proc, roleLine, compacted, roleIdentity);
379
+ return { ...rendered, version: proc.version, project: creds.project };
235
380
  }
236
381
  catch (e) {
237
382
  process.stderr.write(`bschat: could not fetch role/process: ${e.message}\n`);
383
+ return null;
238
384
  }
239
- return standing;
385
+ }
386
+ async function acknowledgeStanding(name, standing, emittedFullRules) {
387
+ if (!standing || !emittedFullRules || !standing.acknowledge || !standing.project || standing.version <= 0)
388
+ return;
389
+ try {
390
+ const creds = loadAgent(name);
391
+ await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/projects/${standing.project}/process/ack`, { version: standing.version });
392
+ }
393
+ catch (e) {
394
+ process.stderr.write(`bschat: could not acknowledge process rules: ${e.message}\n`);
395
+ }
396
+ }
397
+ export function renderStandingRules(proc, roleLine, compacted, roleIdentity) {
398
+ const shortRole = roleIdentity ?? (/^Your role: [^.]+\./.exec(roleLine)?.[0] ?? roleLine.slice(0, 300));
399
+ const deferredText = `[bschat] Process v${proc.version}. ${shortRole}\nRole details: bschat me\nRead the current rules: bschat process`;
400
+ const fit = (text, acknowledge) => utf8Bytes(text) > DELIVERY_BUDGET_BYTES
401
+ ? { text: deferredText, acknowledge: false, deferredText }
402
+ : { text, acknowledge, deferredText };
403
+ if (compacted)
404
+ return fit(`${roleLine}\nRead the current rules: bschat process`, false);
405
+ if (proc.seen_version === proc.version)
406
+ return fit(`[bschat] Process v${proc.version}. ${roleLine}`, false);
407
+ if (proc.seen_version !== null) {
408
+ const changed = (proc.changes_since_seen ?? []).map((line) => `- ${line}`);
409
+ const rulesChanged = proc.rules_changed_since_seen === true || (proc.changes_since_seen ?? []).some((line) => /^(working agreements|charter) (edited|added|removed)$/.test(line));
410
+ return fit([
411
+ `[bschat] Process v${proc.version}. ${roleLine}`,
412
+ `Changed since you read v${proc.seen_version}:`,
413
+ ...(changed.length ? changed : ["- Details: bschat process"]),
414
+ rulesChanged && proc.agreements ? `Current working agreements:\n${proc.agreements}` : null,
415
+ rulesChanged && proc.charter ? `Current charter:\n${proc.charter}` : null,
416
+ ].filter(Boolean).join("\n"), true);
417
+ }
418
+ const lines = [
419
+ `[bschat] Your standing role and process.`, roleLine,
420
+ `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.`,
421
+ proc.agreements ? `Working agreements:\n${proc.agreements}` : null,
422
+ proc.charter ? `Charter (how this project weighs its trade-offs):\n${proc.charter}` : null,
423
+ ].filter(Boolean);
424
+ return fit(lines.join("\n"), true);
240
425
  }
241
426
  /**
242
427
  * Antigravity's hooks (.agents/hooks.json, written by join): SessionStart and PreInvocation inject
@@ -293,18 +478,26 @@ async function antigravityHook(p) {
293
478
  if (input?.fullyIdle !== true)
294
479
  return out({});
295
480
  // Only something addressed to it keeps it going; chatter waits for its next turn.
296
- const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true });
481
+ const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true, continuation: true });
297
482
  if (!peek || (peek.tier !== "direct" && peek.tier !== "role"))
298
483
  return out({});
299
- const u = await gatherUpdates(name, { force: true, delivery: "hook" });
300
- return out(u ? { decision: "continue", reason: `${u.text}\nHandle these, then carry on with what you were doing.` } : {});
484
+ const u = await gatherUpdates(name, { force: true, delivery: "hook", continuation: true });
485
+ if (!u)
486
+ return out({});
487
+ const formatted = formatUpdates(u, [], ["Handle these, then carry on with what you were doing."]);
488
+ const reason = formatted.text;
489
+ await reportDelivery(name, reason, formatted.delivery.by_kind);
490
+ return out({ decision: "continue", reason });
301
491
  }
302
492
  if (event !== "SessionStart" && event !== "PreInvocation")
303
493
  return out({});
304
- const standing = event === "SessionStart" ? await standingRules(name, false) : null;
494
+ const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
305
495
  const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
306
- const text = [standing, u?.text].filter(Boolean).join("\n\n");
307
- return out(text ? { injectSteps: [{ systemMessage: { systemMessage: text } }] } : {});
496
+ const formatted = formatHookDelivery(u, standing);
497
+ if (formatted.text)
498
+ await reportDelivery(name, formatted.text, formatted.by_kind);
499
+ out(formatted.text ? { injectSteps: [{ systemMessage: { systemMessage: formatted.text } }] } : {});
500
+ await acknowledgeStanding(name, standing, formatted.acknowledge);
308
501
  }
309
502
  /**
310
503
  * Codex's hooks (~/.codex/hooks.json, written by `bschat codex hooks`; Claude Code's format):
@@ -359,21 +552,28 @@ async function codexHook(p) {
359
552
  return;
360
553
  if (event === "Stop") {
361
554
  // Only something addressed to it keeps it going; chatter waits for its next turn.
362
- const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true });
555
+ const peek = await gatherUpdates(name, { force: true, delivery: "hook", dryRun: true, continuation: true });
363
556
  if (!peek || (peek.tier !== "direct" && peek.tier !== "role"))
364
557
  return;
365
- const u = await gatherUpdates(name, { force: true, delivery: "hook" });
366
- if (u)
367
- process.stdout.write(JSON.stringify({ decision: "block", reason: `${u.text}\nHandle these, then carry on with what you were doing.` }) + "\n");
558
+ const u = await gatherUpdates(name, { force: true, delivery: "hook", continuation: true });
559
+ if (u) {
560
+ const formatted = formatUpdates(u, [], ["Handle these, then carry on with what you were doing."]);
561
+ const reason = formatted.text;
562
+ await reportDelivery(name, reason, formatted.delivery.by_kind);
563
+ process.stdout.write(JSON.stringify({ decision: "block", reason }) + "\n");
564
+ }
368
565
  return;
369
566
  }
370
567
  if (event !== "SessionStart" && event !== "UserPromptSubmit")
371
568
  return;
372
- const standing = event === "SessionStart" ? await standingRules(name, false) : null;
569
+ const standing = event === "SessionStart" ? await standingRules(name, input?.source === "compact") : null;
373
570
  const u = await gatherUpdates(name, { force: event === "SessionStart", delivery: "hook" });
374
- const text = [standing, u?.text].filter(Boolean).join("\n\n");
375
- if (text)
376
- context(text);
571
+ const formatted = formatHookDelivery(u, standing);
572
+ if (formatted.text)
573
+ await reportDelivery(name, formatted.text, formatted.by_kind);
574
+ if (formatted.text)
575
+ context(formatted.text);
576
+ await acknowledgeStanding(name, standing, formatted.acknowledge);
377
577
  }
378
578
  /** Records where this agent's harness session writes, so `wu submit` can read its token counts. */
379
579
  function noteSession(name, harness, transcript, sessionId) {
@@ -13,6 +13,7 @@ import { TURN_HARNESSES, claudeFacts, claudeSandbox, probeFor, sessionProcesses
13
13
  import { readState, writeState } from "../state.js";
14
14
  import { installService, lingerEnabled, MACHINE_LABEL, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
15
15
  import { CLI_VERSION } from "../version.js";
16
+ import { probeCapabilities } from "../capabilities.js";
16
17
  export const machineFile = () => join(configRoot(), "machine.json");
17
18
  export function loadMachine() {
18
19
  const f = machineFile();
@@ -60,11 +61,14 @@ export function startArgs(s, thread, writable = []) {
60
61
  ];
61
62
  }
62
63
  const KEY_CHECK_MS = 10 * 60_000;
64
+ const CAPABILITY_PROBE_MS = 60 * 60_000;
65
+ const lastCapabilityProbe = new Map();
63
66
  /** One pass: make what runs here match what the operator declared, then report. */
64
67
  export async function reconcile(m, log) {
65
68
  const client = Client.raw(m.url, m.key);
66
69
  const me = await client.call("GET", "/machines/me");
67
70
  const desired = me.sessions;
71
+ const projects = me.projects ?? [];
68
72
  const workdir = me.machine?.workdir ?? null;
69
73
  const writable = me.machine?.writable ?? [];
70
74
  // The maintenance window, for the watchers: they start no new turns while it drains or runs.
@@ -171,7 +175,25 @@ export async function reconcile(m, log) {
171
175
  // The daemon's own confirmation that it is holding turns back, and how many are still running.
172
176
  maintenance: maintenanceReport(drainingUntil(), out),
173
177
  };
174
- await client.call("POST", "/machines/me/report", { report, sessions: out });
178
+ const capabilities = {};
179
+ const probedProjects = [];
180
+ for (const project of projects) {
181
+ const signature = JSON.stringify(project.capabilities);
182
+ const last = lastCapabilityProbe.get(project.id);
183
+ if (last?.signature === signature && Date.now() - last.at < CAPABILITY_PROBE_MS)
184
+ continue;
185
+ const projectDir = desired.find((s) => s.project_id === project.id && s.dir)?.dir ?? homedir();
186
+ if (!project.capabilities.length)
187
+ continue;
188
+ capabilities[project.id] = probeCapabilities(project.capabilities, projectDir);
189
+ probedProjects.push(project.id);
190
+ log(`${project.name}: probed ${capabilities[project.id].length} declared capabilities`);
191
+ }
192
+ await client.call("POST", "/machines/me/report", { report, sessions: out, capabilities });
193
+ for (const projectId of probedProjects) {
194
+ const declaration = projects.find((p) => p.id === projectId);
195
+ lastCapabilityProbe.set(projectId, { at: Date.now(), signature: JSON.stringify(declaration.capabilities) });
196
+ }
175
197
  return { sessions: out, report };
176
198
  }
177
199
  const git = (args, cwd) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 600_000 });