benignswarm 0.12.44 → 0.12.46

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
+ }
@@ -41,6 +41,7 @@ export async function setup(p, out) {
41
41
  const vendor = normalizeVendor(str(p.flags, "vendor") ?? creds.vendor);
42
42
  const root = str(p.flags, "dir") ?? repoRoot();
43
43
  const model = resolveModel(str(p.flags, "model"), process.env, process.cwd(), ref);
44
+ assertVendorMatchesRepo(root, creds.agent, vendor, bool(p.flags, "replace"));
44
45
  if (harnessList(p, vendor).includes("claude-code") && !bool(p.flags, "replace")) {
45
46
  const owner = claudeCheckoutOwner(root);
46
47
  if (owner && owner !== ref && owner !== creds.agent)
@@ -76,6 +77,7 @@ export async function join(p, out) {
76
77
  // A second agent of the same vendor in one worktree must not steal the repo mapping. With
77
78
  // --no-bind the credentials are saved and the agent is addressed per call instead.
78
79
  const noBind = bool(p.flags, "no-bind");
80
+ assertVendorMatchesRepo(root, name, vendor, bool(p.flags, "replace"));
79
81
  // --no-bind keeps the repo's mapping, but for Claude Code the hook still runs as the bound agent
80
82
  // in every session here: a second Claude Code agent needs its own worktree, not --no-bind.
81
83
  if (vendor === "claude-code" && !bool(p.flags, "replace")) {
@@ -114,7 +116,7 @@ export async function join(p, out) {
114
116
  ? `Joined project "${json.project.name}" as agent "${name}" (${vendor})${json.agent.role_name ? ` with role ${json.agent.role_name}` : ""}.`
115
117
  : `Joined as account-wide agent "${name}" (${vendor}) with role ${json.agent.role_name}. Project commands take --project <name>; see them with: bschat me`,
116
118
  `Credentials saved to ${path} (private to this machine).`,
117
- `bschat ${inst.version} is installed for this machine at ${inst.bin}; the hook, the repo instructions and watchers all use it. Upgrade with: bschat install --latest`,
119
+ `bschat ${inst.version} is installed for this machine at ${inst.bin}; the hook, the repo instructions and watchers all use it. Upgrade with: bschat update`,
118
120
  noBind
119
121
  ? `This repo's ${vendor} identity was left as is. Address yourself on every call: \`bschat --as ${ref} <command>\` or \`BSCHAT_AGENT=${ref} bschat <command>\`. Never run bare bschat here as ${name}.`
120
122
  : `This repo now maps ${vendor} -> ${ref} in ${idPath}, so bschat commands here know who you are, even after a reboot.`,
@@ -150,6 +152,20 @@ function verifyClaudeHook(root, ref) {
150
152
  }
151
153
  return `Hook verified: ran "${cmd}" successfully as ${ref}.`;
152
154
  }
155
+ /**
156
+ * Refuses when this repo's identity file already says the agent runs in another harness than the
157
+ * one detected (or passed). Learned from fabricbios: sol-reviewer, mapped as the Codex agent in the
158
+ * repo, was saved as Claude Code by a join run where Claude Code's environment was set, so it got
159
+ * no watcher and no thread binding and stalled with three reviews waiting.
160
+ */
161
+ export function assertVendorMatchesRepo(root, name, vendor, replace) {
162
+ const p = findIdentityFile(root);
163
+ if (!p || !p.startsWith(root) || replace)
164
+ return;
165
+ const mapped = Object.entries(readIdentityFile(p).agents).filter(([v, a]) => a.name === name && v !== vendor).map(([v]) => v);
166
+ if (mapped.length)
167
+ throw new CliError("vendor_mismatch", `${p} says ${name} runs in ${mapped.join(" and ")} here, but this command detected ${vendor}`, `If ${name} runs in ${mapped[0]}, run this from that harness or pass --vendor ${mapped[0]}. If the file is wrong, pass --replace.`);
168
+ }
153
169
  /** This machine's one install, at least this CLI's version (installed or upgraded when needed). */
154
170
  function machineInstall() {
155
171
  return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`bschat: ${m}\n`));
@@ -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, readFileSync, 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 { 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 recent = repoScannedRecently(SCAN_EVERY_MS);
94
+ if (recent)
95
+ log(`worktree scan: skipped, ${recent}`);
96
+ else {
97
+ const r = await scanProject(scanCreds, scanCreds.project);
98
+ markRepoScanned(scanCreds.agent);
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,33 @@ 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
+ /** "by <agent> 12 min ago" when another watcher scanned this repository within `ms`, else null. */
367
+ function repoScannedRecently(ms) {
368
+ const f = scanMarker();
369
+ if (!f || !existsSync(f))
370
+ return null;
371
+ try {
372
+ const m = JSON.parse(readFileSync(f, "utf8"));
373
+ const age = Date.now() - m.at;
374
+ return age < ms ? `scanned by ${m.by} ${Math.round(age / 60_000)} min ago` : null;
375
+ }
376
+ catch {
377
+ return null;
378
+ }
379
+ }
380
+ function markRepoScanned(by) {
381
+ const f = scanMarker();
382
+ if (!f)
383
+ return;
384
+ mkdirSync(dirname(f), { recursive: true });
385
+ writeFileSync(f, JSON.stringify({ at: Date.now(), by }));
386
+ }
@@ -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";
@@ -151,10 +154,15 @@ export async function wu(p, out) {
151
154
  pushed = remote === null ? (fetchRef(where.branch) ? false : null) : remote === local;
152
155
  if (pushed === false && def.merge.require_pushed)
153
156
  throw new CliError("not_pushed", `${where.branch} is not pushed at ${local?.slice(0, 9)} (origin has ${remote ? remote.slice(0, 9) : "no such branch"})`, `git push -u origin ${where.branch}, then submit again`);
157
+ // Not required here, but a reviewer working from origin (bschat wu review, another machine)
158
+ // cannot fetch it, unless the commit is already on the target (then the branch adds nothing).
159
+ if (pushed === false && !def.merge.require_pushed && isAncestor("HEAD", fetchRef(unitTarget) ? "FETCH_HEAD" : `origin/${unitTarget}`) !== true)
160
+ process.stderr.write(`bschat: ${where.branch} is not on origin at ${local?.slice(0, 9)}: bschat wu review and reviewers on other machines cannot fetch it. git push -u origin ${where.branch}\n`);
154
161
  }
155
162
  }
156
163
  const pr = str(p.flags, "pr") ?? null;
157
- 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 });
158
166
  const u = r.unit;
159
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);
160
168
  return;
@@ -304,17 +312,33 @@ export async function wu(p, out) {
304
312
  const parent = repoParent();
305
313
  if (!name || !parent)
306
314
  throw new CliError("not_a_repo", "run wu review from a checkout of the project's repository");
307
- if (!fetchRef(unit.branch))
308
- throw new CliError("fetch_failed", `cannot fetch ${unit.branch} from origin`, `Is it pushed? Ask ${unit.owner_name}: git push -u origin ${unit.branch}`);
309
- const remote = fullSha("FETCH_HEAD");
310
- if (!remote)
311
- throw new CliError("fetch_failed", `fetched ${unit.branch} but found no commit`);
312
- if (!remote.startsWith(unit.head))
313
- throw new CliError("head_mismatch", `origin/${unit.branch} is at ${remote.slice(0, 9)} but WU #${n} was submitted at ${unit.head}`, `Either the owner pushed more since submitting (ask for a resubmit) or has not pushed the submitted commit.`);
315
+ // A unit that added no commits (an audit or a diagnosis whose output is evidence) was
316
+ // submitted at a commit already on origin's target: review that commit, no branch needed.
317
+ // Learned from fabricbios: three audits sat behind "cannot fetch the branch" though their
318
+ // head was already on origin/main.
319
+ const target = unit.target ?? (await processDef()).merge.target_branch;
320
+ let remote = null;
321
+ let onTarget = false;
322
+ if (fetchRef(target)) {
323
+ const head = fullSha(unit.head);
324
+ if (head && isAncestor(head, "FETCH_HEAD")) {
325
+ remote = head;
326
+ onTarget = true;
327
+ }
328
+ }
329
+ if (!remote) {
330
+ if (!fetchRef(unit.branch))
331
+ throw new CliError("fetch_failed", `cannot fetch ${unit.branch} from origin`, `Is it pushed? Ask ${unit.owner_name}: git push -u origin ${unit.branch}`);
332
+ remote = fullSha("FETCH_HEAD");
333
+ if (!remote)
334
+ throw new CliError("fetch_failed", `fetched ${unit.branch} but found no commit`);
335
+ if (!remote.startsWith(unit.head))
336
+ throw new CliError("head_mismatch", `origin/${unit.branch} is at ${remote.slice(0, 9)} but WU #${n} was submitted at ${unit.head}`, `Either the owner pushed more since submitting (ask for a resubmit) or has not pushed the submitted commit.`);
337
+ }
314
338
  const path = resolve(parent, `${name}-review-wu${n}`);
315
339
  const made = ensureReviewWorktree(path, remote);
316
340
  const ev = unit.evidence.map((e) => `evidence:${e}`).join(" ") || "(none)";
317
- out.print(`${fmt(unit)}\nReview checkout: ${path} (detached at ${remote.slice(0, 9)}${made.created ? "" : ", already there"})\n cd ${path}\nEvidence: ${ev} (bschat evidence get <id>)\nVerdict: bschat wu approve ${n} --note "..." | bschat wu changes ${n} --note "..."\nWhen finished: git worktree remove ${path}`, { unit, worktree: path, head: remote });
341
+ out.print(`${fmt(unit)}\nReview checkout: ${path} (detached at ${remote.slice(0, 9)}${made.created ? "" : ", already there"})${onTarget ? `\nThe submitted commit is already on origin/${target}: the unit added no commits, so its evidence is the work.` : ""}\n cd ${path}\nEvidence: ${ev} (bschat evidence get <id>)\nVerdict: bschat wu approve ${n} --note "..." | bschat wu changes ${n} --note "..."\nWhen finished: git worktree remove ${path}`, { unit, worktree: path, head: remote });
318
342
  return;
319
343
  }
320
344
  case "show": {
@@ -634,3 +658,34 @@ export async function askOperator(p, out) {
634
658
  const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, blocks: str(p.flags, "blocks") ?? "", proposal });
635
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);
636
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/help.js CHANGED
@@ -100,6 +100,7 @@ Agent commands
100
100
  --env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
101
101
  ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once / --launchd.
102
102
  Codex: bschat watch --exec "codex queue --thread <id> --message {summary}" --launchd
103
+ bschat update the same as install --latest: upgrade this machine's bschat and restart its watchers
103
104
  bschat install [<version> | --latest] make or upgrade this machine's one bschat (join does it once) and restart
104
105
  the watchers on it; hooks, repo instructions and watchers all run its path
105
106
  bschat doctor every bschat on this machine and who runs which (PATH, npx caches, this repo's
package/dist/index.js CHANGED
@@ -54,6 +54,8 @@ const COMMANDS = {
54
54
  antigravity,
55
55
  codex,
56
56
  install,
57
+ // `update` is the word people reach for: the same as install, latest unless a version is named.
58
+ update: (p, out) => install(p.positionals[1] ? p : { ...p, flags: { ...p.flags, latest: true } }, out),
57
59
  doctor,
58
60
  wu,
59
61
  process: processCmd,
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/update.js CHANGED
@@ -39,5 +39,5 @@ export function noteServerVersions(headers, agent) {
39
39
  catch {
40
40
  /* unwritable state dir: notice simply repeats next time */
41
41
  }
42
- process.stderr.write(`[bschat] CLI ${CLI_VERSION} is installed, ${latest} is available: bschat install --latest (updates this machine's one install and restarts its watchers)\n`);
42
+ process.stderr.write(`[bschat] CLI ${CLI_VERSION} is installed, ${latest} is available: bschat update (upgrades this machine's one install and restarts its watchers)\n`);
43
43
  }
package/dist/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.44";
1
+ export const CLI_VERSION = "0.12.46";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.44",
3
+ "version": "0.12.46",
4
4
  "description": "bschat: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {