@getgavel/cli 0.1.26 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,242 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { claudeProjectDirs } from "./claude-code.js";
5
+ import { accountPin, claudeAccount } from "./claude-plan.js";
6
+ import { isPlanSession } from "./plan-profiles.js";
7
+ // Claude Code's tokens for each day (W-247, for the plan's share in W-248): the four counts the
8
+ // agent's own sessions in this folder used, summed here from their transcripts, once for each
9
+ // answer (a message id: an answer written in several parts repeats its usage) and by the laptop's
10
+ // own date. Only the sums, each with its date, go to Gavel (D-894); never a line, an id or a path.
11
+ const KEYS = ["inputTokens", "cacheWriteTokens", "cacheReadTokens", "outputTokens"];
12
+ const USAGE = { inputTokens: "input_tokens", cacheWriteTokens: "cache_creation_input_tokens", cacheReadTokens: "cache_read_input_tokens", outputTokens: "output_tokens" };
13
+ const DAY_MS = 86_400_000;
14
+ const CHUNK = 8 * 1024 * 1024;
15
+ export const DAYS_EVERY_MS = 60_000;
16
+ const pad = (n) => String(n).padStart(2, "0");
17
+ export const localDate = (ms) => {
18
+ const d = new Date(ms);
19
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
20
+ };
21
+ const startOfDay = (ms) => {
22
+ const d = new Date(ms);
23
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
24
+ };
25
+ const whole = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : 0);
26
+ // The transcripts that can hold the last two days' answers: each session's file and its sub-agents'.
27
+ function transcripts(dirs, since, include) {
28
+ const files = [];
29
+ const add = (file) => {
30
+ try {
31
+ if (statSync(file).mtimeMs >= since)
32
+ files.push(file);
33
+ }
34
+ catch {
35
+ // gone
36
+ }
37
+ };
38
+ for (const dir of dirs) {
39
+ for (const name of readdirSync(dir)) {
40
+ if (!include(name.replace(/\.jsonl$/, "")))
41
+ continue;
42
+ if (name.endsWith(".jsonl"))
43
+ add(join(dir, name));
44
+ else {
45
+ const sub = join(dir, name, "subagents");
46
+ if (existsSync(sub))
47
+ for (const s of readdirSync(sub))
48
+ if (s.endsWith(".jsonl"))
49
+ add(join(sub, s));
50
+ }
51
+ }
52
+ }
53
+ return files;
54
+ }
55
+ // The sums by date, read on from where each file was last read, whole lines only.
56
+ export class DaySums {
57
+ dirs;
58
+ now;
59
+ include;
60
+ offsets = new Map();
61
+ answers = new Map();
62
+ changed = new Set();
63
+ constructor(dirs, now = Date.now, include = () => true) {
64
+ this.dirs = dirs;
65
+ this.now = now;
66
+ this.include = include;
67
+ }
68
+ scan() {
69
+ const today = startOfDay(this.now());
70
+ for (const file of transcripts(this.dirs(), today - DAY_MS, this.include))
71
+ this.read(file, today - DAY_MS);
72
+ }
73
+ read(file, from) {
74
+ let fd = null;
75
+ try {
76
+ fd = openSync(file, "r");
77
+ for (;;) {
78
+ const at = this.offsets.get(file) ?? 0;
79
+ const buffer = Buffer.alloc(CHUNK);
80
+ const n = readSync(fd, buffer, 0, CHUNK, at);
81
+ if (!n)
82
+ return;
83
+ const end = buffer.subarray(0, n).lastIndexOf(10);
84
+ if (end < 0) {
85
+ if (n < CHUNK)
86
+ return;
87
+ this.offsets.set(file, at + n);
88
+ continue;
89
+ }
90
+ for (const line of buffer.subarray(0, end).toString("utf8").split("\n"))
91
+ this.take(line, from);
92
+ this.offsets.set(file, at + end + 1);
93
+ }
94
+ }
95
+ catch {
96
+ // read again at the next scan
97
+ }
98
+ finally {
99
+ if (fd !== null)
100
+ closeSync(fd);
101
+ }
102
+ }
103
+ take(line, from) {
104
+ if (!line.includes('"usage"'))
105
+ return;
106
+ try {
107
+ const l = JSON.parse(line);
108
+ const id = l.message?.id;
109
+ const usage = l.message?.usage;
110
+ const at = typeof l.timestamp === "string" ? Date.parse(l.timestamp) : Number.NaN;
111
+ if (l.type !== "assistant" || typeof id !== "string" || !usage || !Number.isFinite(at) || at < from)
112
+ return;
113
+ const date = localDate(at);
114
+ let day = this.answers.get(date);
115
+ if (!day)
116
+ this.answers.set(date, (day = new Map()));
117
+ const before = day.get(id);
118
+ const next = { ...(before ?? { inputTokens: 0, cacheWriteTokens: 0, cacheReadTokens: 0, outputTokens: 0 }) };
119
+ // A later part of one answer says at least what an earlier part did.
120
+ for (const key of KEYS)
121
+ next[key] = Math.max(next[key], whole(usage[USAGE[key]]));
122
+ if (before && KEYS.every((key) => before[key] === next[key]))
123
+ return;
124
+ day.set(id, next);
125
+ this.changed.add(date);
126
+ }
127
+ catch {
128
+ // not a line of answers
129
+ }
130
+ }
131
+ // The dates whose sums moved since they were last taken, each with its sums.
132
+ moved() {
133
+ const out = [];
134
+ for (const date of [...this.changed].sort()) {
135
+ const sum = { inputTokens: 0, cacheWriteTokens: 0, cacheReadTokens: 0, outputTokens: 0 };
136
+ for (const a of this.answers.get(date)?.values() ?? [])
137
+ for (const key of KEYS)
138
+ sum[key] += a[key];
139
+ out.push([date, sum]);
140
+ }
141
+ this.changed.clear();
142
+ return out;
143
+ }
144
+ // What was taken and wasn't sent goes round again.
145
+ again(dates) {
146
+ for (const d of dates)
147
+ this.changed.add(d);
148
+ }
149
+ forget() {
150
+ const keep = localDate(startOfDay(this.now()) - DAY_MS);
151
+ for (const date of [...this.answers.keys()])
152
+ if (date < keep)
153
+ this.answers.delete(date);
154
+ }
155
+ }
156
+ // This folder's own id for its sums, kept (mode 600) so the same one goes each time and a second
157
+ // folder's or machine's sums for the same day add up beside it, never over it.
158
+ function sourceId(home, cwd) {
159
+ const dir = join(home, ".gavel", "plan-accounts");
160
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
161
+ const path = join(dir, `source-claude-${createHash("sha256").update(cwd).digest("hex").slice(0, 16)}`);
162
+ try {
163
+ writeFileSync(path, randomUUID(), { mode: 0o600, flag: "wx" });
164
+ }
165
+ catch (err) {
166
+ if (err.code !== "EEXIST")
167
+ throw err;
168
+ }
169
+ return readFileSync(path, "utf8").trim();
170
+ }
171
+ // The bridge's reporter of the days' sums: each poke reads what the transcripts gained, and the
172
+ // sums that moved go to the plan the agent's link names, a minute apart at most, only while the
173
+ // Claude account that first reported the plan's windows is the one signed in.
174
+ export function claudeDayReporter(opts) {
175
+ const now = opts.now ?? Date.now;
176
+ const every = opts.everyMs ?? DAYS_EVERY_MS;
177
+ const profile = opts.env.GAVEL_PLAN_PROFILE;
178
+ const sums = new DaySums(() => claudeProjectDirs(opts.cwd, opts.home, opts.env), now, profile ? (id) => isPlanSession(opts.home, profile, id) : undefined);
179
+ let timer = null;
180
+ let sentAt = -Infinity;
181
+ let sending = false;
182
+ let closed = false;
183
+ let said = "";
184
+ const sayOnce = (line) => {
185
+ if (line !== said)
186
+ opts.say(line);
187
+ said = line;
188
+ };
189
+ const send = async () => {
190
+ timer = null;
191
+ if (sending || closed)
192
+ return;
193
+ sending = true;
194
+ sentAt = now();
195
+ let pending = [];
196
+ try {
197
+ sums.scan();
198
+ pending = sums.moved();
199
+ sums.forget();
200
+ if (!pending.length)
201
+ return;
202
+ const planId = await opts.reporter.linked();
203
+ if (!planId)
204
+ return void sums.again(pending.map(([d]) => d));
205
+ const pin = profile ? (profile === planId ? "match" : "other") : accountPin(opts.home, planId, claudeAccount(opts.home, opts.env));
206
+ if (pin !== "match") {
207
+ sums.again(pending.map(([d]) => d));
208
+ return sayOnce(pin === "unpinned"
209
+ ? "Claude Code's daily tokens wait for its plan's first report from the status line."
210
+ : "Claude Code's daily tokens aren't sent: another Claude account is signed in than the one this plan was first read from.");
211
+ }
212
+ const source = sourceId(opts.home, opts.cwd);
213
+ while (pending.length) {
214
+ const [date, counts] = pending[0];
215
+ await opts.reporter.day({ planId, date, sourceId: source, ...counts });
216
+ pending.shift();
217
+ }
218
+ sayOnce("Claude Code's daily tokens go to Gavel, for you alone.");
219
+ }
220
+ catch (err) {
221
+ sums.again(pending.map(([d]) => d));
222
+ sayOnce(`Claude Code's daily tokens aren't sent: ${err instanceof Error ? err.message : String(err)}; it tries again.`);
223
+ }
224
+ finally {
225
+ sending = false;
226
+ }
227
+ };
228
+ return {
229
+ // Something may have been written: look, within a minute of the last send.
230
+ poke() {
231
+ if (closed || timer || sending)
232
+ return;
233
+ timer = setTimeout(() => void send(), Math.max(0, sentAt + every - now()));
234
+ timer.unref?.();
235
+ },
236
+ close() {
237
+ closed = true;
238
+ if (timer)
239
+ clearTimeout(timer);
240
+ },
241
+ };
242
+ }
@@ -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, isBridgeStatusLine } 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
@@ -75,7 +75,8 @@ const shellLine = (parts) => parts.map((p) => (/^[\w@%+=:,./-]+$/.test(p) ? p :
75
75
  // (null), every other hook and setting kept; null when nothing changes. statusLine: the command for
76
76
  // the bridge's status line (W-258), which reads the plan's figures and runs the person's own; a
77
77
  // status line the person set in this same file stays theirs, and the bridge's never goes in over it.
78
- export function withBridgeHooks(existing, command, displayUrl, statusLine = null) {
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) {
79
80
  let settings = {};
80
81
  if (existing?.trim()) {
81
82
  try {
@@ -102,7 +103,9 @@ export function withBridgeHooks(existing, command, displayUrl, statusLine = null
102
103
  hooks.MessageDisplay = [...(hooks.MessageDisplay ?? []), { hooks: [{ type: "http", url: displayUrl, timeout: 2 }] }];
103
104
  const { hooks: _old, statusLine: line, ...rest } = settings;
104
105
  const ours = isOurStatusLine(line);
105
- const keptLine = line !== undefined && !ours ? { statusLine: line } : statusLine ? { statusLine: { type: "command", command: shellLine([...statusLine, "bridge", "status-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
+ : {};
106
109
  const next = { ...rest, ...keptLine, ...(Object.keys(hooks).length ? { hooks } : {}) };
107
110
  const text = `${JSON.stringify(next, null, 2)}\n`;
108
111
  return text === existing ? null : text;
@@ -216,7 +219,7 @@ export async function claudeBridgeHooks(action, opts) {
216
219
  // the agent's words as they're shown.
217
220
  const plugin = gavelPluginOn(opts.home);
218
221
  // The status line goes here even with the plugin on, which can't carry one (W-258).
219
- const next = withBridgeHooks(existing, plugin ? null : opts.command, displayHook(opts.home, opts.cwd).url, opts.command);
222
+ const next = withBridgeHooks(existing, plugin ? null : opts.command, displayHook(opts.home, opts.cwd).url, opts.command, ownStatusLineEntry(opts.home, opts.cwd, process.env));
220
223
  if (next !== null)
221
224
  writeWhole(file, next);
222
225
  const line = JSON.parse(next ?? existing ?? "{}").statusLine;
@@ -396,9 +399,13 @@ function agentLine(read, words) {
396
399
  return { found: false, through: start };
397
400
  }
398
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;
399
405
  export class ClaudeCodeHarness {
400
406
  ctx;
401
407
  name = "Claude Code";
408
+ takesFresh = true;
402
409
  sessions = new Map();
403
410
  // Each Gavel message the bridge put in, with its prompt's key when a resumed run took it.
404
411
  known = new Map();
@@ -411,6 +418,9 @@ export class ClaudeCodeHarness {
411
418
  lastState = null;
412
419
  // The short ids Claude Code gave the sessions the bridge put in the background.
413
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 = [];
414
424
  changedTimer = null;
415
425
  // The person's name, for the words that say who wrote: the core learns it after it builds the
416
426
  // harness, from GET /v1/me.
@@ -590,6 +600,8 @@ export class ClaudeCodeHarness {
590
600
  this.follow(this.current()?.transcript ?? null);
591
601
  this.soon();
592
602
  this.stateNow();
603
+ if (this.batches.length > 1)
604
+ this.reap();
593
605
  }
594
606
  // A turn's end goes once the transcript has its last words in a whole line (Claude Code writes the
595
607
  // file a moment after the Stop hook, and a line sometimes in two writes), so the core's push before
@@ -658,7 +670,7 @@ export class ClaudeCodeHarness {
658
670
  return to;
659
671
  });
660
672
  }
661
- async deliver(m) {
673
+ async deliver(m, fresh) {
662
674
  const pictures = this.keepPictures(m);
663
675
  const text = this.prompt(m, pictures);
664
676
  let open = this.current();
@@ -674,7 +686,7 @@ export class ClaudeCodeHarness {
674
686
  }
675
687
  if (open)
676
688
  return { outcome: "left", say: `${this.ctx.person} wrote in Gavel; your Claude Code session here is open and the bridge can't reach it yet, so it goes in at the session's next step, or once it closes.` };
677
- return this.resume(m, text);
689
+ return this.resume(m, text, fresh);
678
690
  }
679
691
  // A closed session, resumed with the person's words as a turn of its own in the background
680
692
  // (D-1174, changing D-905's "nothing that would prompt runs"): it runs under their own permission
@@ -682,9 +694,23 @@ export class ClaudeCodeHarness {
682
694
  // edits stay in the folder, as their own session's: no worktree of its own (Master Gavel's call).
683
695
  // The words go on stdin, never in its arguments. Delivered once Claude Code says it's backgrounded;
684
696
  // from then the session's own hooks name it, so their next words go through its inbox.
685
- resume(m, text) {
697
+ async resume(m, text, fresh) {
686
698
  const newest = claudeSessions(this.ctx.cwd, this.ctx.home, this.ctx.env)[0] ?? null;
687
- const args = [...(newest ? ["--resume", newest.id] : []), "--bg", "--settings", JSON.stringify({ worktree: { bgIsolation: "none" } })];
699
+ const started = await this.background(text, { resume: fresh ? null : newest?.id ?? null, model: fresh?.model ?? null, effort: fresh?.effort });
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 settings = JSON.stringify({ worktree: { bgIsolation: "none" } });
710
+ const command = process.argv[1] ? [process.execPath, process.argv[1]] : null;
711
+ const managed = this.ctx.env.GAVEL_PLAN_PROFILE && (this.ctx.env.CLAUDE_CONFIG_DIR || this.ctx.env.GAVEL_BRIDGE_OWNER_HARNESS === "codex");
712
+ const launchSettings = managed && command ? withBridgeHooks(settings, command, null, command) ?? settings : settings;
713
+ const args = [...(opts.resume ? ["--resume", opts.resume] : []), ...(opts.model ? ["--model", opts.model] : []), ...(opts.effort ? ["--effort", opts.effort] : []), "--bg", "--settings", launchSettings];
688
714
  return new Promise((resolve) => {
689
715
  const child = spawn("claude", args, { cwd: this.ctx.cwd, env: this.ctx.env, stdio: ["pipe", "pipe", "pipe"] });
690
716
  let out = "";
@@ -698,20 +724,16 @@ export class ClaudeCodeHarness {
698
724
  const quit = setTimeout(() => child.kill(), 60_000);
699
725
  child.stdout.on("data", (d) => (out += d));
700
726
  child.stderr.on("data", (d) => (err += d));
701
- 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}` }));
727
+ 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}` }));
702
728
  child.on("close", (code) => {
703
729
  clearTimeout(quit);
704
730
  const short = /^backgrounded · ([0-9a-f]{8,36})\b/m.exec(out)?.[1];
705
- if (code === 0 && short) {
706
- this.remember(m.id, promptKey(text));
707
- this.backgrounded.add(short.slice(0, 8));
708
- settle({ outcome: "delivered" });
709
- }
731
+ if (code === 0 && short)
732
+ settle({ short: short.slice(0, 8) });
710
733
  else {
711
734
  const first = (t) => t.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
712
735
  const said = first(err) || first(out);
713
- 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);
714
- settle({ outcome: "failed", reason });
736
+ 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) });
715
737
  }
716
738
  this.listener?.changed();
717
739
  });
@@ -759,10 +781,50 @@ export class ClaudeCodeHarness {
759
781
  return sent ? "stopped" : "over";
760
782
  }
761
783
  // Gavel's one-line wake (D-1103), into an open session: mid-turn or as a turn of its own.
762
- async wake(line) {
784
+ async wake(line, fresh) {
785
+ if (fresh)
786
+ return this.wakeFresh(line, fresh);
763
787
  const open = this.current();
764
788
  return open?.inbox ? inboxSend(open.inbox, line, { priority: "next", bypass: this.bypasses(open) }) : false;
765
789
  }
790
+ sessionOf(short) {
791
+ return [...this.sessions.values()].find((s) => s.id.startsWith(short));
792
+ }
793
+ // A desk's batch or an item's session (W-240, W-254): a wake while its batch's session works or
794
+ // waits goes into it; otherwise a new background session starts with the brief and the wake line
795
+ // (no --resume, so nothing of the last one's conversation), in the folder, under the person's own
796
+ // permissions. A newer batch's start stops the older ones once they're idle.
797
+ async wakeFresh(line, fresh) {
798
+ const last = this.batches.at(-1);
799
+ if (last && (fresh.per === "batch" || last.item === fresh.item)) {
800
+ const there = this.sessionOf(last.short);
801
+ if (there?.open && there.state !== "idle")
802
+ return there.inbox ? inboxSend(there.inbox, line, { priority: "next", bypass: this.bypasses(there) }) : false;
803
+ if (!there && Date.now() - last.at < STARTING_MS)
804
+ return false;
805
+ }
806
+ const started = await this.background(`${fresh.brief}\n\n${line}`, { resume: null, model: fresh.model, effort: fresh.effort });
807
+ if ("reason" in started)
808
+ throw new Error(started.reason);
809
+ this.backgrounded.add(started.short);
810
+ this.batches.push({ short: started.short, item: fresh.item, at: Date.now() });
811
+ this.reap();
812
+ return true;
813
+ }
814
+ // The batches before the newest, stopped (`claude stop`) once idle and dropped once closed; one
815
+ // still working or waiting stays for the next look.
816
+ reap() {
817
+ for (const b of this.batches.slice(0, -1)) {
818
+ const s = this.sessionOf(b.short);
819
+ if (s?.open && s.state === "idle")
820
+ void promisify(execFile)("claude", ["stop", b.short], { cwd: this.ctx.cwd, env: this.ctx.env, timeout: 15_000 }).catch(() => undefined);
821
+ else if (s?.open)
822
+ continue;
823
+ this.batches.splice(this.batches.indexOf(b), 1);
824
+ }
825
+ if (this.batches.length > 20)
826
+ this.batches.splice(0, this.batches.length - 20);
827
+ }
766
828
  listen(l) {
767
829
  this.listener = l;
768
830
  this.stateNow();
@@ -80,6 +80,11 @@ export function planUsageOf(given) {
80
80
  return null;
81
81
  return { windows, spendLimit, limitReached: windows.some((w) => w.usedPercent >= 100) || (spendLimit?.usedPercent ?? 0) >= 100 };
82
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
+ }
83
88
  // The Claude account signed in on this laptop, as a hash of its ids (~/.claude.json's oauthAccount):
84
89
  // compared here, never sent. Null when none is (an API key's session).
85
90
  export function claudeAccount(home, env = process.env) {
@@ -107,6 +112,14 @@ function readAccounts(home) {
107
112
  return {};
108
113
  }
109
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
+ }
110
123
  function keepAccount(home, planId, account) {
111
124
  const file = accountsFile(home);
112
125
  mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
@@ -127,13 +140,17 @@ export function changed(last, next) {
127
140
  ]);
128
141
  return key(last) !== key(next);
129
142
  }
130
- // What Gavel takes (W-247's contract with Agent Twelve, W-258): the plan's id, the machine's name
131
- // for the person's own list of machines, and Claude's two windows under one limit, by duration.
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.
132
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
+ }
133
150
  export function usageBody(planId, usage, at, machineName = hostname()) {
134
151
  return {
135
152
  planId,
136
- machineName: machineName.slice(0, 200),
153
+ machineName: machineNameOf(machineName),
137
154
  observedAt: at.toISOString(),
138
155
  windows: usage.windows.map((w) => ({ limitId: "claude", durationMinutes: MINUTES[w.kind], usedPercent: w.usedPercent, resetsAt: w.resetsAt })),
139
156
  limitReached: usage.limitReached,
@@ -141,9 +158,9 @@ export function usageBody(planId, usage, at, machineName = hostname()) {
141
158
  }
142
159
  export const PLAN_EVERY_MS = 60_000;
143
160
  const PLAN_LOOK_AGAIN_MS = 5 * 60_000;
144
- // The bridge's reporter: fed each status line's figures, it sends them at most once a minute, and
145
- // only when they changed, onto the plan the agent's link names, while the account that first
146
- // reported under that plan is still the one signed in.
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.
147
164
  export function claudePlanReporter(opts) {
148
165
  const now = opts.now ?? Date.now;
149
166
  const every = opts.everyMs ?? PLAN_EVERY_MS;
@@ -152,6 +169,7 @@ export function claudePlanReporter(opts) {
152
169
  // When it last tried: a refusal waits for the next figures, a minute on, never a loop.
153
170
  let triedAt = -Infinity;
154
171
  let latest = null;
172
+ let latestAccount = null;
155
173
  let timer = null;
156
174
  let sending = false;
157
175
  let said = "";
@@ -183,11 +201,11 @@ export function claudePlanReporter(opts) {
183
201
  sending = true;
184
202
  triedAt = now();
185
203
  const usage = latest;
204
+ const account = latestAccount;
186
205
  try {
187
206
  const id = await planId();
188
207
  if (!id)
189
208
  return sayOnce("Claude Code's plan use isn't sent: no plan in Gavel names this agent (link it under Settings › You › Plans).");
190
- const account = claudeAccount(opts.home, opts.env);
191
209
  if (!account)
192
210
  return sayOnce("Claude Code's plan use isn't sent: no Claude account is signed in here.");
193
211
  const first = readAccounts(opts.home)[id];
@@ -223,10 +241,11 @@ export function claudePlanReporter(opts) {
223
241
  timer.unref?.();
224
242
  };
225
243
  return {
226
- observe(usage) {
244
+ observe(usage, account) {
227
245
  if (closed)
228
246
  return;
229
247
  latest = usage;
248
+ latestAccount = account;
230
249
  schedule();
231
250
  },
232
251
  close() {
@@ -68,6 +68,7 @@ export class CodexPlanUsage {
68
68
  home;
69
69
  cwd;
70
70
  reporter;
71
+ nativeProfile;
71
72
  checking = false;
72
73
  accountRevision = 0;
73
74
  confirmedPlan = null;
@@ -81,10 +82,11 @@ export class CodexPlanUsage {
81
82
  totals = new Map();
82
83
  pendingDays = new Map();
83
84
  sendingDays = false;
84
- constructor(home, cwd, reporter) {
85
+ constructor(home, cwd, reporter, nativeProfile) {
85
86
  this.home = home;
86
87
  this.cwd = cwd;
87
88
  this.reporter = reporter;
89
+ this.nativeProfile = nativeProfile;
88
90
  }
89
91
  once(key, line) {
90
92
  if (this.warned.has(key))
@@ -94,7 +96,9 @@ export class CodexPlanUsage {
94
96
  }
95
97
  source() {
96
98
  const folder = createHash("sha256").update(this.cwd).digest("hex").slice(0, 16);
97
- const path = join(this.home, ".gavel", "plan-accounts", `source-${folder}`);
99
+ const dir = join(this.home, ".gavel", "plan-accounts");
100
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
101
+ const path = join(dir, `source-${folder}`);
98
102
  try {
99
103
  writeFileSync(path, randomUUID(), { mode: 0o600, flag: "wx" });
100
104
  }
@@ -216,15 +220,16 @@ export class CodexPlanUsage {
216
220
  this.confirmedPlan = null;
217
221
  return;
218
222
  }
219
- const account = await accountOf(app);
220
- if (!account || !boundAccount(this.home, planId, account)) {
223
+ const managed = this.nativeProfile === planId;
224
+ const account = managed ? null : await accountOf(app);
225
+ if (!managed && (!account || !boundAccount(this.home, planId, account))) {
221
226
  this.confirmedPlan = null;
222
227
  if (account)
223
228
  this.once(planId, "Gavel plan usage paused: Codex switched accounts. Link the active plan in Settings.");
224
229
  return;
225
230
  }
226
231
  const snapshot = await app.request("account/rateLimits/read");
227
- if (await accountOf(app) !== account || revision !== this.accountRevision)
232
+ if ((!managed && await accountOf(app) !== account) || revision !== this.accountRevision)
228
233
  return;
229
234
  this.confirmedPlan = planId;
230
235
  const windows = codexWindows(snapshot);
@@ -249,6 +254,20 @@ export class CodexPlanUsage {
249
254
  this.scheduleQuota();
250
255
  }
251
256
  }
257
+ async hit(app) {
258
+ if (!this.reporter.hit)
259
+ return;
260
+ let reset = null;
261
+ try {
262
+ const snapshot = await app.request("account/rateLimits/read");
263
+ reset = codexWindows(snapshot).filter((window) => window.usedPercent >= 90 && Date.parse(window.resetsAt) > Date.now())
264
+ .map((window) => window.resetsAt).sort().at(-1) ?? null;
265
+ }
266
+ catch {
267
+ // The provider can report the hit without a reset time.
268
+ }
269
+ await this.reporter.hit(reset);
270
+ }
252
271
  disconnect() {
253
272
  this.accountRevision++;
254
273
  this.confirmedPlan = null;