@getgavel/cli 0.1.25 → 0.1.27

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.
@@ -6,7 +6,7 @@ import { connect } from "node:net";
6
6
  import { tmpdir } from "node:os";
7
7
  import { basename, dirname, extname, join } from "node:path";
8
8
  import { promisify } from "node:util";
9
- import { bridgePaths } from "./background.js";
9
+ import { bridgePaths, isBridgeStatusLine, ownStatusLineEntry } from "./background.js";
10
10
  import { claudeSessions, claudeWords } from "./claude-code.js";
11
11
  import { claudeSetups } from "./setup.js";
12
12
  // Claude Code live (W-132): what a session tells the bridge through its hooks, and how the bridge
@@ -69,9 +69,14 @@ const DISPLAY_PATH = "/gavel-bridge/";
69
69
  const isBridgeHook = (h) => (Array.isArray(h.args) && h.args.includes("bridge") && h.args.includes("event")) ||
70
70
  (typeof h.url === "string" && h.url.startsWith("http://127.0.0.1:") && h.url.includes(DISPLAY_PATH)) ||
71
71
  (typeof h.command === "string" && /\bbridge wake( |$)/.test(h.command));
72
+ // A command line for the shell, each part quoted.
73
+ const shellLine = (parts) => parts.map((p) => (/^[\w@%+=:,./-]+$/.test(p) ? p : `'${p.replace(/'/g, "'\\''")}'`)).join(" ");
72
74
  // The settings with the bridge's hooks in (its command and the display hook's address) or out
73
- // (null), every other hook and setting kept; null when nothing changes.
74
- export function withBridgeHooks(existing, command, displayUrl) {
75
+ // (null), every other hook and setting kept; null when nothing changes. statusLine: the command for
76
+ // the bridge's status line (W-258), which reads the plan's figures and runs the person's own; a
77
+ // status line the person set in this same file stays theirs, and the bridge's never goes in over it.
78
+ // own: the person's line from their other settings, whose padding and refreshInterval it carries.
79
+ export function withBridgeHooks(existing, command, displayUrl, statusLine = null, own = null) {
75
80
  let settings = {};
76
81
  if (existing?.trim()) {
77
82
  try {
@@ -96,11 +101,16 @@ export function withBridgeHooks(existing, command, displayUrl) {
96
101
  }
97
102
  if (displayUrl)
98
103
  hooks.MessageDisplay = [...(hooks.MessageDisplay ?? []), { hooks: [{ type: "http", url: displayUrl, timeout: 2 }] }];
99
- const { hooks: _old, ...rest } = settings;
100
- const next = Object.keys(hooks).length ? { ...rest, hooks } : rest;
104
+ const { hooks: _old, statusLine: line, ...rest } = settings;
105
+ const ours = isOurStatusLine(line);
106
+ const keptLine = line !== undefined && !ours ? { statusLine: line } : statusLine
107
+ ? { statusLine: { type: "command", command: shellLine([...statusLine, "bridge", "status-line"]), ...(own?.padding !== undefined ? { padding: own.padding } : {}), ...(own?.refreshInterval !== undefined ? { refreshInterval: own.refreshInterval } : {}) } }
108
+ : {};
109
+ const next = { ...rest, ...keptLine, ...(Object.keys(hooks).length ? { hooks } : {}) };
101
110
  const text = `${JSON.stringify(next, null, 2)}\n`;
102
111
  return text === existing ? null : text;
103
112
  }
113
+ const isOurStatusLine = (line) => typeof line?.command === "string" && isBridgeStatusLine(line.command);
104
114
  // The display hook's address for this folder: a port and a secret path kept beside the bridge's
105
115
  // lock (mode 600), the same each time, so the settings name it once.
106
116
  export function displayHook(home, cwd) {
@@ -208,14 +218,19 @@ export async function claudeBridgeHooks(action, opts) {
208
218
  // With Gavel's plugin on, it runs the bridge's hooks: this folder gets only its own address for
209
219
  // the agent's words as they're shown.
210
220
  const plugin = gavelPluginOn(opts.home);
211
- const next = withBridgeHooks(existing, plugin ? null : opts.command, displayHook(opts.home, opts.cwd).url);
221
+ // The status line goes here even with the plugin on, which can't carry one (W-258).
222
+ const next = withBridgeHooks(existing, plugin ? null : opts.command, displayHook(opts.home, opts.cwd).url, opts.command, ownStatusLineEntry(opts.home, opts.cwd, process.env));
212
223
  if (next !== null)
213
224
  writeWhole(file, next);
225
+ const line = JSON.parse(next ?? existing ?? "{}").statusLine;
214
226
  const done = [
215
227
  plugin
216
228
  ? `Gavel's plugin runs the bridge's hooks here; wrote this folder's hook for the words as they're shown into ${name}`
217
229
  : `wrote the bridge's hooks into ${name}: a Claude Code session here starts Gavel's bridge as it starts (and stops it a while after the last one ends), so your person's chat in Gavel reaches it at once, with no terminal open`,
218
230
  ];
231
+ done.push(isOurStatusLine(line)
232
+ ? `wrote the bridge's status line into ${name}: it shows your own status line as before, and sends your Claude plan's use to Gavel for you alone`
233
+ : `kept your own status line in ${name}, so your Claude plan's use isn't read here`);
219
234
  if (gitIn(["rev-parse", "--is-inside-work-tree"], opts.cwd) && !gitIn(["check-ignore", "-q", name], opts.cwd)) {
220
235
  const gitignore = join(opts.cwd, ".gitignore");
221
236
  const text = existsSync(gitignore) ? readFileSync(gitignore, "utf8") : "";
@@ -384,9 +399,13 @@ function agentLine(read, words) {
384
399
  return { found: false, through: start };
385
400
  }
386
401
  const PICTURES_HOURS = 1;
402
+ // How long a session the bridge just started may take to say its first hook, before its wake is
403
+ // taken for lost.
404
+ const STARTING_MS = 30_000;
387
405
  export class ClaudeCodeHarness {
388
406
  ctx;
389
407
  name = "Claude Code";
408
+ takesFresh = true;
390
409
  sessions = new Map();
391
410
  // Each Gavel message the bridge put in, with its prompt's key when a resumed run took it.
392
411
  known = new Map();
@@ -399,6 +418,9 @@ export class ClaudeCodeHarness {
399
418
  lastState = null;
400
419
  // The short ids Claude Code gave the sessions the bridge put in the background.
401
420
  backgrounded = new Set();
421
+ // The fresh sessions the bridge started for a desk's batches or an item (W-240), oldest first, by
422
+ // short id: the newest takes the wakes of its batch, the older ones are stopped once idle.
423
+ batches = [];
402
424
  changedTimer = null;
403
425
  // The person's name, for the words that say who wrote: the core learns it after it builds the
404
426
  // harness, from GET /v1/me.
@@ -578,6 +600,8 @@ export class ClaudeCodeHarness {
578
600
  this.follow(this.current()?.transcript ?? null);
579
601
  this.soon();
580
602
  this.stateNow();
603
+ if (this.batches.length > 1)
604
+ this.reap();
581
605
  }
582
606
  // A turn's end goes once the transcript has its last words in a whole line (Claude Code writes the
583
607
  // file a moment after the Stop hook, and a line sometimes in two writes), so the core's push before
@@ -670,9 +694,19 @@ export class ClaudeCodeHarness {
670
694
  // edits stay in the folder, as their own session's: no worktree of its own (Master Gavel's call).
671
695
  // The words go on stdin, never in its arguments. Delivered once Claude Code says it's backgrounded;
672
696
  // from then the session's own hooks name it, so their next words go through its inbox.
673
- resume(m, text) {
697
+ async resume(m, text) {
674
698
  const newest = claudeSessions(this.ctx.cwd, this.ctx.home, this.ctx.env)[0] ?? null;
675
- const args = [...(newest ? ["--resume", newest.id] : []), "--bg", "--settings", JSON.stringify({ worktree: { bgIsolation: "none" } })];
699
+ const started = await this.background(text, { resume: newest?.id ?? null, model: null });
700
+ if ("reason" in started)
701
+ return { outcome: "failed", reason: started.reason };
702
+ this.remember(m.id, promptKey(text));
703
+ this.backgrounded.add(started.short);
704
+ return { outcome: "delivered" };
705
+ }
706
+ // `claude [--resume <id>] --bg` with the words on stdin: the short id Claude Code names the
707
+ // background session by, or why it didn't start.
708
+ background(text, opts) {
709
+ const args = [...(opts.resume ? ["--resume", opts.resume] : []), ...(opts.model ? ["--model", opts.model] : []), "--bg", "--settings", JSON.stringify({ worktree: { bgIsolation: "none" } })];
676
710
  return new Promise((resolve) => {
677
711
  const child = spawn("claude", args, { cwd: this.ctx.cwd, env: this.ctx.env, stdio: ["pipe", "pipe", "pipe"] });
678
712
  let out = "";
@@ -686,20 +720,16 @@ export class ClaudeCodeHarness {
686
720
  const quit = setTimeout(() => child.kill(), 60_000);
687
721
  child.stdout.on("data", (d) => (out += d));
688
722
  child.stderr.on("data", (d) => (err += d));
689
- child.on("error", (e) => settle({ outcome: "failed", reason: e.code === "ENOENT" ? "Claude Code's claude command isn't on the laptop's PATH where the bridge runs." : `Claude Code didn't start: ${e.message}` }));
723
+ child.on("error", (e) => settle({ reason: e.code === "ENOENT" ? "Claude Code's claude command isn't on the laptop's PATH where the bridge runs." : `Claude Code didn't start: ${e.message}` }));
690
724
  child.on("close", (code) => {
691
725
  clearTimeout(quit);
692
726
  const short = /^backgrounded · ([0-9a-f]{8,36})\b/m.exec(out)?.[1];
693
- if (code === 0 && short) {
694
- this.remember(m.id, promptKey(text));
695
- this.backgrounded.add(short.slice(0, 8));
696
- settle({ outcome: "delivered" });
697
- }
727
+ if (code === 0 && short)
728
+ settle({ short: short.slice(0, 8) });
698
729
  else {
699
730
  const first = (t) => t.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
700
731
  const said = first(err) || first(out);
701
- const reason = (/unknown option.*(--bg|--background)/i.test(err) ? "The laptop's Claude Code is too old for the bridge: run claude update there." : said ? `Claude Code said: ${said}` : `Claude Code stopped without answering (code ${code}).`).slice(0, 300);
702
- settle({ outcome: "failed", reason });
732
+ settle({ reason: (/unknown option.*(--bg|--background)/i.test(err) ? "The laptop's Claude Code is too old for the bridge: run claude update there." : said ? `Claude Code said: ${said}` : `Claude Code stopped without answering (code ${code}).`).slice(0, 300) });
703
733
  }
704
734
  this.listener?.changed();
705
735
  });
@@ -747,10 +777,50 @@ export class ClaudeCodeHarness {
747
777
  return sent ? "stopped" : "over";
748
778
  }
749
779
  // Gavel's one-line wake (D-1103), into an open session: mid-turn or as a turn of its own.
750
- async wake(line) {
780
+ async wake(line, fresh) {
781
+ if (fresh)
782
+ return this.wakeFresh(line, fresh);
751
783
  const open = this.current();
752
784
  return open?.inbox ? inboxSend(open.inbox, line, { priority: "next", bypass: this.bypasses(open) }) : false;
753
785
  }
786
+ sessionOf(short) {
787
+ return [...this.sessions.values()].find((s) => s.id.startsWith(short));
788
+ }
789
+ // A desk's batch or an item's session (W-240, W-254): a wake while its batch's session works or
790
+ // waits goes into it; otherwise a new background session starts with the brief and the wake line
791
+ // (no --resume, so nothing of the last one's conversation), in the folder, under the person's own
792
+ // permissions. A newer batch's start stops the older ones once they're idle.
793
+ async wakeFresh(line, fresh) {
794
+ const last = this.batches.at(-1);
795
+ if (last && (fresh.per === "batch" || last.item === fresh.item)) {
796
+ const there = this.sessionOf(last.short);
797
+ if (there?.open && there.state !== "idle")
798
+ return there.inbox ? inboxSend(there.inbox, line, { priority: "next", bypass: this.bypasses(there) }) : false;
799
+ if (!there && Date.now() - last.at < STARTING_MS)
800
+ return false;
801
+ }
802
+ const started = await this.background(`${fresh.brief}\n\n${line}`, { resume: null, model: fresh.model });
803
+ if ("reason" in started)
804
+ throw new Error(started.reason);
805
+ this.backgrounded.add(started.short);
806
+ this.batches.push({ short: started.short, item: fresh.item, at: Date.now() });
807
+ this.reap();
808
+ return true;
809
+ }
810
+ // The batches before the newest, stopped (`claude stop`) once idle and dropped once closed; one
811
+ // still working or waiting stays for the next look.
812
+ reap() {
813
+ for (const b of this.batches.slice(0, -1)) {
814
+ const s = this.sessionOf(b.short);
815
+ if (s?.open && s.state === "idle")
816
+ void promisify(execFile)("claude", ["stop", b.short], { cwd: this.ctx.cwd, env: this.ctx.env, timeout: 15_000 }).catch(() => undefined);
817
+ else if (s?.open)
818
+ continue;
819
+ this.batches.splice(this.batches.indexOf(b), 1);
820
+ }
821
+ if (this.batches.length > 20)
822
+ this.batches.splice(0, this.batches.length - 20);
823
+ }
754
824
  listen(l) {
755
825
  this.listener = l;
756
826
  this.stateNow();
@@ -0,0 +1,257 @@
1
+ import { createHash } from "node:crypto";
2
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { hostname } from "node:os";
4
+ import { join } from "node:path";
5
+ const WINDOWS = [
6
+ ["five_hour", "five_hour"],
7
+ ["seven_day", "weekly"],
8
+ ];
9
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
10
+ const percent = (v) => {
11
+ const n = num(v);
12
+ return n === null ? null : Math.min(100, Math.max(0, Math.round(n * 10) / 10));
13
+ };
14
+ // Claude Code says a reset in epoch seconds.
15
+ const instant = (v) => {
16
+ const n = num(v);
17
+ return n === null || n <= 0 || n > 4_102_444_800 ? null : new Date(n * 1000).toISOString();
18
+ };
19
+ // The allowlisted numbers from the status line's input (its JSON on stdin), nothing else of it; null
20
+ // when it has none (an API key's session, or before the session's first answer).
21
+ export function statusLineUsage(input) {
22
+ const limits = input?.rate_limits;
23
+ if (!limits || typeof limits !== "object")
24
+ return null;
25
+ const r = limits;
26
+ const windows = [];
27
+ for (const [from, kind] of WINDOWS) {
28
+ const usedPercent = percent(r[from]?.used_percentage);
29
+ const resetsAt = instant(r[from]?.resets_at);
30
+ if (usedPercent !== null && resetsAt)
31
+ windows.push({ kind, usedPercent, resetsAt });
32
+ }
33
+ let spendLimit = null;
34
+ const s = r.spend_limit;
35
+ const spent = percent(s?.used_percentage);
36
+ if (s && spent !== null) {
37
+ spendLimit = { usedPercent: spent, resetsAt: instant(s.resets_at) };
38
+ const used = num(s.used_usd);
39
+ const limit = num(s.limit_usd);
40
+ if (used !== null && used >= 0)
41
+ spendLimit.usedUsd = Math.round(used * 100) / 100;
42
+ if (limit !== null && limit >= 0)
43
+ spendLimit.limitUsd = Math.round(limit * 100) / 100;
44
+ if (typeof s.period === "string" && /^[a-z_]{1,20}$/.test(s.period))
45
+ spendLimit.period = s.period;
46
+ }
47
+ if (!windows.length && !spendLimit)
48
+ return null;
49
+ return { windows, spendLimit, limitReached: windows.some((w) => w.usedPercent >= 100) || (spendLimit?.usedPercent ?? 0) >= 100 };
50
+ }
51
+ // The figures as the bridge takes them from its socket: rebuilt from the known fields alone, so
52
+ // nothing else ever rides along to Gavel; null when they aren't figures.
53
+ export function planUsageOf(given) {
54
+ const g = given;
55
+ if (!g || typeof g !== "object" || !Array.isArray(g.windows))
56
+ return null;
57
+ const windows = [];
58
+ for (const w of g.windows) {
59
+ const usedPercent = percent(w?.usedPercent);
60
+ const at = typeof w?.resetsAt === "string" ? Date.parse(w.resetsAt) : Number.NaN;
61
+ if ((w?.kind === "five_hour" || w?.kind === "weekly") && usedPercent !== null && Number.isFinite(at) && !windows.some((x) => x.kind === w.kind))
62
+ windows.push({ kind: w.kind, usedPercent, resetsAt: new Date(at).toISOString() });
63
+ }
64
+ const s = g.spendLimit;
65
+ let spendLimit = null;
66
+ const spent = percent(s?.usedPercent);
67
+ if (s && spent !== null) {
68
+ const at = typeof s.resetsAt === "string" ? Date.parse(s.resetsAt) : Number.NaN;
69
+ spendLimit = { usedPercent: spent, resetsAt: Number.isFinite(at) ? new Date(at).toISOString() : null };
70
+ const used = num(s.usedUsd);
71
+ const limit = num(s.limitUsd);
72
+ if (used !== null && used >= 0)
73
+ spendLimit.usedUsd = Math.round(used * 100) / 100;
74
+ if (limit !== null && limit >= 0)
75
+ spendLimit.limitUsd = Math.round(limit * 100) / 100;
76
+ if (typeof s.period === "string" && /^[a-z_]{1,20}$/.test(s.period))
77
+ spendLimit.period = s.period;
78
+ }
79
+ if (!windows.length && !spendLimit)
80
+ return null;
81
+ return { windows, spendLimit, limitReached: windows.some((w) => w.usedPercent >= 100) || (spendLimit?.usedPercent ?? 0) >= 100 };
82
+ }
83
+ // The account's hash as the status line handed it over with the figures; null when it isn't one.
84
+ export function accountOf(given) {
85
+ const account = given?.account;
86
+ return typeof account === "string" && /^[0-9a-f]{64}$/.test(account) ? account : null;
87
+ }
88
+ // The Claude account signed in on this laptop, as a hash of its ids (~/.claude.json's oauthAccount):
89
+ // compared here, never sent. Null when none is (an API key's session).
90
+ export function claudeAccount(home, env = process.env) {
91
+ const file = env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, ".claude.json") : join(home, ".claude.json");
92
+ try {
93
+ const account = JSON.parse(readFileSync(file, "utf8")).oauthAccount;
94
+ if (typeof account?.accountUuid !== "string" || !account.accountUuid)
95
+ return null;
96
+ return createHash("sha256").update(`claude\0${account.accountUuid}\0${typeof account.organizationUuid === "string" ? account.organizationUuid : ""}`).digest("hex");
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ }
102
+ // Which account first reported under each plan, kept beside the bridge's locks (mode 600).
103
+ function accountsFile(home) {
104
+ return join(home, ".gavel", "bridge", "plan-accounts.json");
105
+ }
106
+ function readAccounts(home) {
107
+ try {
108
+ const kept = JSON.parse(readFileSync(accountsFile(home), "utf8"));
109
+ return kept && typeof kept === "object" ? kept : {};
110
+ }
111
+ catch {
112
+ return {};
113
+ }
114
+ }
115
+ // Whether the account signed in is the one that first reported under this plan: "unpinned" until the
116
+ // windows' first report keeps it.
117
+ export function accountPin(home, planId, account) {
118
+ const first = readAccounts(home)[planId];
119
+ if (!first)
120
+ return "unpinned";
121
+ return account && first === account ? "match" : "mismatch";
122
+ }
123
+ function keepAccount(home, planId, account) {
124
+ const file = accountsFile(home);
125
+ mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
126
+ const temp = `${file}.${process.pid}.tmp`;
127
+ writeFileSync(temp, `${JSON.stringify({ ...readAccounts(home), [planId]: account }, null, 2)}\n`, { mode: 0o600 });
128
+ chmodSync(temp, 0o600);
129
+ renameSync(temp, file);
130
+ }
131
+ // Whether the next figures say something the last sent didn't: a window's whole percent, a reset, a
132
+ // window come or gone, or the limit reached.
133
+ export function changed(last, next) {
134
+ if (!last)
135
+ return true;
136
+ const key = (u) => JSON.stringify([
137
+ u.windows.map((w) => [w.kind, Math.floor(w.usedPercent), w.resetsAt]),
138
+ u.spendLimit ? [Math.floor(u.spendLimit.usedPercent), u.spendLimit.resetsAt] : null,
139
+ u.limitReached,
140
+ ]);
141
+ return key(last) !== key(next);
142
+ }
143
+ // What Gavel takes (W-247's plans routes, Agent Twelve's): the plan's id, the machine's name for the
144
+ // person's own list of machines (1 to 64 characters, no control characters), and Claude's two windows
145
+ // under one limit, by duration.
146
+ const MINUTES = { five_hour: 300, weekly: 10_080 };
147
+ export function machineNameOf(name) {
148
+ return [...name.replace(/\p{Cc}/gu, "").trim()].slice(0, 64).join("").trim() || "this machine";
149
+ }
150
+ export function usageBody(planId, usage, at, machineName = hostname()) {
151
+ return {
152
+ planId,
153
+ machineName: machineNameOf(machineName),
154
+ observedAt: at.toISOString(),
155
+ windows: usage.windows.map((w) => ({ limitId: "claude", durationMinutes: MINUTES[w.kind], usedPercent: w.usedPercent, resetsAt: w.resetsAt })),
156
+ limitReached: usage.limitReached,
157
+ };
158
+ }
159
+ export const PLAN_EVERY_MS = 60_000;
160
+ const PLAN_LOOK_AGAIN_MS = 5 * 60_000;
161
+ // The bridge's reporter: fed each status line's figures with the account its session is signed in
162
+ // to, it sends them at most once a minute, and only when they changed, onto the plan the agent's
163
+ // link names, while that account is the one that first reported under that plan.
164
+ export function claudePlanReporter(opts) {
165
+ const now = opts.now ?? Date.now;
166
+ const every = opts.everyMs ?? PLAN_EVERY_MS;
167
+ let plan = null;
168
+ let sent = null;
169
+ // When it last tried: a refusal waits for the next figures, a minute on, never a loop.
170
+ let triedAt = -Infinity;
171
+ let latest = null;
172
+ let latestAccount = null;
173
+ let timer = null;
174
+ let sending = false;
175
+ let said = "";
176
+ let closed = false;
177
+ const sayOnce = (line) => {
178
+ if (line !== said)
179
+ opts.say(line);
180
+ said = line;
181
+ };
182
+ const planId = async () => {
183
+ if (plan && now() - plan.at < PLAN_LOOK_AGAIN_MS)
184
+ return plan.id;
185
+ const res = await opts.request("GET", "/v1/agents/me/plan");
186
+ if (res.status === 404) {
187
+ void res.body?.cancel();
188
+ plan = { id: null, at: now() };
189
+ return null;
190
+ }
191
+ if (!res.ok)
192
+ throw new Error(`Gavel answered ${res.status} to which plan this agent is on`);
193
+ const body = (await res.json());
194
+ plan = { id: typeof body?.planId === "string" ? body.planId : null, at: now() };
195
+ return plan.id;
196
+ };
197
+ const send = async () => {
198
+ timer = null;
199
+ if (sending || closed || !latest || !changed(sent, latest))
200
+ return;
201
+ sending = true;
202
+ triedAt = now();
203
+ const usage = latest;
204
+ const account = latestAccount;
205
+ try {
206
+ const id = await planId();
207
+ if (!id)
208
+ return sayOnce("Claude Code's plan use isn't sent: no plan in Gavel names this agent (link it under Settings › You › Plans).");
209
+ if (!account)
210
+ return sayOnce("Claude Code's plan use isn't sent: no Claude account is signed in here.");
211
+ const first = readAccounts(opts.home)[id];
212
+ if (first && first !== account)
213
+ return sayOnce("Claude Code's plan use isn't sent: another Claude account is signed in than the one this plan was first read from. Link that account's plan in Gavel (Settings › You › Plans), or sign back in.");
214
+ const res = await opts.request("POST", "/v1/agents/me/plan/usage", usageBody(id, usage, new Date(now())));
215
+ void res.body?.cancel();
216
+ if (res.status === 403 || res.status === 404 || res.status === 409) {
217
+ plan = null;
218
+ return sayOnce(`Claude Code's plan use isn't sent: Gavel answered ${res.status} for this agent's plan; it looks again in a few minutes.`);
219
+ }
220
+ if (!res.ok)
221
+ return sayOnce(`Claude Code's plan use isn't sent: Gavel answered ${res.status}; it tries again with the next figures.`);
222
+ if (!first)
223
+ keepAccount(opts.home, id, account);
224
+ sent = usage;
225
+ sayOnce("Claude Code's plan use goes to Gavel, for you alone.");
226
+ }
227
+ catch (err) {
228
+ sayOnce(`Claude Code's plan use isn't sent: ${err instanceof Error ? err.message : String(err)}`);
229
+ }
230
+ finally {
231
+ sending = false;
232
+ // Figures that came while it sent go next, a minute after.
233
+ if (sent === usage && latest !== usage)
234
+ schedule();
235
+ }
236
+ };
237
+ const schedule = () => {
238
+ if (closed || timer || sending || !latest || !changed(sent, latest))
239
+ return;
240
+ timer = setTimeout(() => void send(), Math.max(0, triedAt + every - now()));
241
+ timer.unref?.();
242
+ };
243
+ return {
244
+ observe(usage, account) {
245
+ if (closed)
246
+ return;
247
+ latest = usage;
248
+ latestAccount = account;
249
+ schedule();
250
+ },
251
+ close() {
252
+ closed = true;
253
+ if (timer)
254
+ clearTimeout(timer);
255
+ },
256
+ };
257
+ }
@@ -21,7 +21,6 @@ const UNREAD = [
21
21
  "item/mcpToolCall/progress",
22
22
  "turn/diff/updated",
23
23
  "turn/plan/updated",
24
- "thread/tokenUsage/updated",
25
24
  "command/exec/outputDelta",
26
25
  "process/outputDelta",
27
26
  "process/exited",