benignswarm 0.12.45 → 0.12.47

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.
@@ -173,6 +173,8 @@ export async function hook(p) {
173
173
  if (observed && observed !== state.model)
174
174
  writeState(name, { ...state, model: observed, model_observed_at: Date.now() });
175
175
  }
176
+ if (harness === "claude-code" && typeof input?.transcript_path === "string")
177
+ noteSession(name, "claude-code", input.transcript_path, typeof input.session_id === "string" ? input.session_id : null);
176
178
  if (event === "PostModelSwitch")
177
179
  return;
178
180
  // Standing rules die with the context. On SessionStart (startup, resume, and after a compaction)
@@ -268,6 +270,8 @@ async function antigravityHook(p) {
268
270
  catch {
269
271
  return out({});
270
272
  }
273
+ if (typeof input?.transcriptPath === "string" && input.transcriptPath)
274
+ noteSession(name, "antigravity", input.transcriptPath, conv);
271
275
  if (typeof input?.modelName === "string" && input.modelName) {
272
276
  const st = readState(name);
273
277
  if (st.model !== input.modelName)
@@ -334,6 +338,8 @@ async function codexHook(p) {
334
338
  catch {
335
339
  return;
336
340
  }
341
+ if (typeof input?.transcript_path === "string" && input.transcript_path)
342
+ noteSession(name, "codex", input.transcript_path, sid);
337
343
  if (typeof input?.model === "string" && input.model) {
338
344
  const st = readState(name);
339
345
  if (st.model !== input.model)
@@ -369,3 +375,11 @@ async function codexHook(p) {
369
375
  if (text)
370
376
  context(text);
371
377
  }
378
+ /** Records where this agent's harness session writes, so `wu submit` can read its token counts. */
379
+ function noteSession(name, harness, transcript, sessionId) {
380
+ const st = readState(name);
381
+ const cur = st.harness_session;
382
+ if (cur && cur.transcript === transcript && cur.harness === harness)
383
+ return;
384
+ writeState(name, { ...st, harness_session: { harness, transcript, session_id: sessionId, at: Date.now() } });
385
+ }
@@ -1,11 +1,12 @@
1
- import { spawn } from "node:child_process";
1
+ import { spawn, spawnSync } from "node:child_process";
2
2
  import { bindSession, sessionOfExec } from "../sessions.js";
3
3
  import { reloadLaunchAgent, requireInstall } from "../install.js";
4
- import { mkdirSync, writeFileSync } from "node:fs";
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { createHash } from "node:crypto";
5
6
  import { homedir } from "node:os";
6
- import { join } from "node:path";
7
+ import { basename, dirname, join } from "node:path";
7
8
  import { bool, str } from "../args.js";
8
- import { loadAgent, resolveAgentName } from "../config.js";
9
+ import { configRoot, loadAgent, resolveAgentName } from "../config.js";
9
10
  import { Client } from "../client.js";
10
11
  import { heartbeatIfActive, resolveActivitySource } from "../heartbeat.js";
11
12
  import { scanProject, unitWorktrees } from "./worktrees.js";
@@ -86,8 +87,17 @@ export async function watch(p, out) {
86
87
  if (scanCreds.project && Date.now() - lastScan > 3_600_000) {
87
88
  lastScan = Date.now();
88
89
  try {
89
- const r = await scanProject(scanCreds, scanCreds.project);
90
- log(`worktree scan: ${r.recorded} in ${r.repo}${r.missing ? `, ${r.missing} gone` : ""}`);
90
+ // One scan per repository per machine per hour, whichever watcher gets there first: five
91
+ // fabricbios watchers rescanning the same 136 worktrees cost ~1,400 database queries an hour,
92
+ // and D1 runs one query at a time for every tenant.
93
+ const marker = scanMarker();
94
+ const taken = marker ? claimRepoScan(marker, scanCreds.agent, SCAN_EVERY_MS) : null;
95
+ if (taken)
96
+ log(`worktree scan: skipped, ${taken}`);
97
+ else {
98
+ const r = await scanProject(scanCreds, scanCreds.project);
99
+ log(`worktree scan: ${r.recorded} in ${r.repo}${r.missing ? `, ${r.missing} gone` : ""}`);
100
+ }
91
101
  if (bool(p.flags, "prune")) {
92
102
  // Space back on a schedule: only clean worktrees whose work has landed or whose unit is
93
103
  // closed; never one a unit is still being worked in (it may have no commits yet).
@@ -344,3 +354,51 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
344
354
  function escapeXml(s) {
345
355
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
346
356
  }
357
+ const SCAN_EVERY_MS = 50 * 60_000;
358
+ /** The state file shared by every watcher on this machine for the repository at cwd. */
359
+ function scanMarker() {
360
+ const r = spawnSync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf8" });
361
+ if (r.status !== 0)
362
+ return null;
363
+ const key = createHash("sha256").update(r.stdout.trim()).digest("hex").slice(0, 16);
364
+ return join(configRoot(), "state", `scan-${key}.json`);
365
+ }
366
+ /**
367
+ * Claim this repository's scan for `by`, or say why another watcher has it. Watchers launched
368
+ * together reach this in the same second, so reading the marker and writing it after the scan let
369
+ * all of them scan (seven StickJoy watchers at once). The claim is an exclusive create of a file
370
+ * named after the marker version read, so exactly one watcher moves the marker on; it writes the
371
+ * marker before scanning, and older claim files are removed then.
372
+ */
373
+ export function claimRepoScan(f, by, everyMs, nowMs = Date.now()) {
374
+ let prev = { at: 0, by: "" };
375
+ if (existsSync(f)) {
376
+ const raw = readFileSync(f, "utf8");
377
+ try {
378
+ prev = JSON.parse(raw);
379
+ }
380
+ catch {
381
+ throw new Error(`scan marker ${f} is not JSON (${raw.slice(0, 40)}); remove it to let scans resume`);
382
+ }
383
+ }
384
+ const age = nowMs - prev.at;
385
+ if (prev.by && age < everyMs)
386
+ return `scanned by ${prev.by} ${Math.round(age / 60_000)} min ago`;
387
+ const claim = `${f}.${prev.at}.claim`;
388
+ mkdirSync(dirname(f), { recursive: true });
389
+ try {
390
+ writeFileSync(claim, by, { flag: "wx" });
391
+ }
392
+ catch (e) {
393
+ if (e.code === "EEXIST")
394
+ return `another watcher (${readFileSync(claim, "utf8")}) claimed this scan`;
395
+ throw e;
396
+ }
397
+ writeFileSync(f, JSON.stringify({ at: nowMs, by }));
398
+ const base = basename(f);
399
+ for (const old of readdirSync(dirname(f))) {
400
+ if (old.startsWith(`${base}.`) && old.endsWith(".claim") && old !== basename(claim))
401
+ rmSync(join(dirname(f), old), { force: true });
402
+ }
403
+ return null;
404
+ }
@@ -2,7 +2,10 @@ import { spawnSync } from "node:child_process";
2
2
  import { readFileSync, writeFileSync } from "node:fs";
3
3
  import { bool, str } from "../args.js";
4
4
  import { Client } from "../client.js";
5
- import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
5
+ import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
6
+ import { readState } from "../state.js";
7
+ import { codexRollout, sessionsOf } from "../sessions.js";
8
+ import { sessionUsage } from "../usage.js";
6
9
  import { CliError } from "../errors.js";
7
10
  import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, fullSha, isAncestor, remoteHead, removeWorktreeIfClean, repoName, repoParent, worktreeForBranch } from "../git.js";
8
11
  import { resolve } from "node:path";
@@ -158,7 +161,8 @@ export async function wu(p, out) {
158
161
  }
159
162
  }
160
163
  const pr = str(p.flags, "pr") ?? null;
161
- const r = await client.call("POST", `${base}/${num()}/submit`, { evidence: evidenceIds, ...where, pr_url: pr, rebased, pushed });
164
+ const usage = await roundUsage(client, base, num(), name);
165
+ const r = await client.call("POST", `${base}/${num()}/submit`, { evidence: evidenceIds, ...where, pr_url: pr, rebased, pushed, usage });
162
166
  const u = r.unit;
163
167
  out.print(`${fmt(u)}\n${u.status === "classifying" ? `Waiting for ${u.reviewers[0]?.name} to classify it.` : `Routed to ${u.reviewers.map((x) => `@${x.name}`).join(", ")}; you will be told in chat when it is reviewed.`}`, r);
164
168
  return;
@@ -654,3 +658,34 @@ export async function askOperator(p, out) {
654
658
  const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, blocks: str(p.flags, "blocks") ?? "", proposal });
655
659
  out.print(`Asked the operator${proposal ? " with your proposal (they can approve it as written)" : ""}; it is on their console banner and reported to them. You will be @mentioned with the decision. Carry on with what does not depend on it.`, r);
656
660
  }
661
+ /**
662
+ * Tokens the agent's harness session used since the unit started or was last submitted, for the
663
+ * model comparison (docs/MODEL-COMPARISON.md). Never fails a submission: an unreadable session is
664
+ * recorded as unavailable with the reason.
665
+ */
666
+ async function roundUsage(client, base, n, name) {
667
+ const until = new Date().toISOString();
668
+ let since = until;
669
+ try {
670
+ const events = (await client.call("GET", `${base}/${n}`)).events;
671
+ const marks = events.filter((e) => ["started", "submitted", "resubmitted", "refreshed"].includes(e.type)).map((e) => e.at);
672
+ since = marks.length ? marks[marks.length - 1] : (events[0]?.at ?? until);
673
+ }
674
+ catch (e) {
675
+ return { harness: "unknown", source: "none", scope: "session", since, until, tokens: null, reason: `could not read the unit's timeline: ${e.message}` };
676
+ }
677
+ let session = readState(name).harness_session;
678
+ if (!session) {
679
+ // A Codex agent woken only by its watcher: its thread is bound, and the rollout names it.
680
+ const ref = agentRef(loadAgent(name));
681
+ const rollout = sessionsOf("codex", ref).map(codexRollout).find((f) => !!f);
682
+ if (rollout)
683
+ session = { harness: "codex", transcript: rollout, session_id: null, at: Date.now() };
684
+ }
685
+ try {
686
+ return sessionUsage(session, since, until);
687
+ }
688
+ catch (e) {
689
+ return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since, until, tokens: null, reason: `could not read the session: ${e.message}` };
690
+ }
691
+ }
package/dist/sessions.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
3
4
  import { dirname, join } from "node:path";
4
5
  import { configRoot } from "./config.js";
5
6
  import { CliError } from "./errors.js";
@@ -63,3 +64,27 @@ export function syncFromWatchers() {
63
64
  }
64
65
  return out;
65
66
  }
67
+ /** The session ids bound to an agent for one harness. */
68
+ export function sessionsOf(kind, ref) {
69
+ return Object.entries(read(kind).conversations).filter(([, r]) => r === ref).map(([id]) => id);
70
+ }
71
+ /** A Codex thread's rollout file (~/.codex/sessions/YYYY/MM/DD/rollout-*-<thread>.jsonl), newest first, or null. */
72
+ export function codexRollout(thread) {
73
+ const root = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "sessions");
74
+ if (!existsSync(root))
75
+ return null;
76
+ const walk = (dir, depth) => {
77
+ for (const e of readdirSync(dir, { withFileTypes: true }).sort((a, b) => b.name.localeCompare(a.name))) {
78
+ const p = join(dir, e.name);
79
+ if (e.isDirectory() && depth < 3) {
80
+ const f = walk(p, depth + 1);
81
+ if (f)
82
+ return f;
83
+ }
84
+ else if (e.isFile() && e.name.includes(thread) && e.name.endsWith(".jsonl"))
85
+ return p;
86
+ }
87
+ return null;
88
+ };
89
+ return walk(root, 0);
90
+ }
package/dist/usage.js ADDED
@@ -0,0 +1,81 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ const zero = () => ({ input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 });
3
+ function lines(path) {
4
+ return readFileSync(path, "utf8").split("\n").filter(Boolean).flatMap((l) => {
5
+ try {
6
+ return [JSON.parse(l)];
7
+ }
8
+ catch {
9
+ return [];
10
+ }
11
+ });
12
+ }
13
+ /**
14
+ * Codex rollout: `event_msg` `token_count` events carry running totals, so the window's use is the
15
+ * last total at or before `until` minus the last total before `since` (zero when the session began
16
+ * inside the window).
17
+ */
18
+ export function codexUsage(path, since, until) {
19
+ let before = null, end = null;
20
+ let plan = null;
21
+ for (const j of lines(path)) {
22
+ const p = j.payload;
23
+ const at = typeof j.timestamp === "string" ? j.timestamp : null;
24
+ if (j.type !== "event_msg" || p?.type !== "token_count" || !at)
25
+ continue;
26
+ const total = p.info?.total_token_usage;
27
+ if (total && at < since)
28
+ before = total;
29
+ if (total && at <= until)
30
+ end = total;
31
+ if (at <= until && p.rate_limits?.primary && typeof p.rate_limits.primary.used_percent === "number")
32
+ plan = { used_percent: p.rate_limits.primary.used_percent, window_minutes: p.rate_limits.primary.window_minutes ?? null };
33
+ }
34
+ const base = { harness: "codex", source: "codex-rollout", scope: "session", since, until, tokens: null, plan };
35
+ if (!end)
36
+ return { ...base, reason: "no token counts in the session up to now" };
37
+ const d = (k) => (end[k] ?? 0) - (before?.[k] ?? 0);
38
+ const t = { input: d("input_tokens"), cached_input: d("cached_input_tokens"), output: d("output_tokens"), reasoning: d("reasoning_output_tokens"), total: 0 };
39
+ t.total = t.input + t.output;
40
+ return { ...base, tokens: t };
41
+ }
42
+ /**
43
+ * Claude Code transcript: assistant entries carry `message.usage`. One message is written once per
44
+ * content block with the same id, so each message id counts once (its last entry).
45
+ */
46
+ export function claudeUsage(path, since, until) {
47
+ const byMessage = new Map();
48
+ for (const j of lines(path)) {
49
+ const m = j.message;
50
+ const at = typeof j.timestamp === "string" ? j.timestamp : null;
51
+ if (j.type !== "assistant" || !m?.usage || !at || at < since || at > until)
52
+ continue;
53
+ byMessage.set(m.id ?? `${at}`, m.usage);
54
+ }
55
+ const base = { harness: "claude-code", source: "claude-transcript", scope: "session", since, until, tokens: null };
56
+ if (!byMessage.size)
57
+ return { ...base, reason: "no assistant messages in the window" };
58
+ const t = zero();
59
+ for (const u of byMessage.values()) {
60
+ const cached = u.cache_read_input_tokens ?? 0;
61
+ t.input += (u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) + cached;
62
+ t.cached_input += cached;
63
+ t.output += u.output_tokens ?? 0;
64
+ t.reasoning += u.output_tokens_details?.thinking_tokens ?? 0;
65
+ }
66
+ t.total = t.input + t.output;
67
+ return { ...base, tokens: t };
68
+ }
69
+ /** The usage for a harness session the hook recorded, or an honest "unavailable" record. */
70
+ export function sessionUsage(session, since, until) {
71
+ const none = (harness, reason) => ({ harness, source: "none", scope: "session", since, until, tokens: null, reason });
72
+ if (!session)
73
+ return none("unknown", "no hook has reported this agent's session on this machine");
74
+ if (!existsSync(session.transcript))
75
+ return none(session.harness, `the session file ${session.transcript} is gone`);
76
+ if (session.harness === "codex")
77
+ return codexUsage(session.transcript, since, until);
78
+ if (session.harness === "claude-code")
79
+ return claudeUsage(session.transcript, since, until);
80
+ return none(session.harness, `${session.harness} keeps no readable token counts locally`);
81
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.45";
1
+ export const CLI_VERSION = "0.12.47";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.45",
3
+ "version": "0.12.47",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {