@getgavel/cli 0.1.24 → 0.1.26

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gavel",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
4
4
  "displayName": "Gavel",
5
5
  "description": "Gavel in Claude Code: your person's chat in Gavel reaches your sessions at once (Gavel's bridge, started with each session), the end-of-turn reminder of what's waiting for you, and how to work with Gavel.",
6
6
  "author": { "name": "Gavel", "url": "https://getgavel.ai" },
@@ -2,7 +2,9 @@ import { execFileSync, spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import { chmodSync, closeSync, copyFileSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { connect, createServer } from "node:net";
5
+ import { tmpdir } from "node:os";
5
6
  import { dirname, join } from "node:path";
7
+ import { statusLineUsage } from "./claude-plan.js";
6
8
  import { claudeSetups, codexSetups } from "./setup.js";
7
9
  // How long a bridge a hook started stays after its folder's last session ends: long enough for a
8
10
  // /clear, a restart or a resume, never all night.
@@ -19,15 +21,29 @@ const realpath = (path) => {
19
21
  }
20
22
  };
21
23
  export const bridgeDir = (home) => join(home, ".gavel", "bridge");
22
- // One key per folder and harness: a short hash, so the socket's path stays under the ~104 bytes a
23
- // Unix socket's address allows.
24
+ // One key per folder and harness: a short hash, so the socket's path stays under the bytes a Unix
25
+ // socket's address allows.
24
26
  export function bridgeKey(cwd, harness) {
25
27
  return createHash("sha256").update(`${realpath(cwd)}\0${harness}`).digest("hex").slice(0, 16);
26
28
  }
29
+ // The longest path a Unix socket can listen on: macOS's address holds 104 bytes with its closing
30
+ // zero (Linux's 108), and past it listen fails (W-244).
31
+ export const MAX_SOCKET_PATH = 103;
32
+ // The hook socket beside the lock, unless a long home folder pushes it past the limit: then in a
33
+ // private folder of the user's own under the system's temporary folder, which the lock names.
34
+ function socketPath(dir, key) {
35
+ const beside = join(dir, `${key}.sock`);
36
+ if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH)
37
+ return beside;
38
+ return join(tmpdir(), `gavel-bridge-${process.getuid?.() ?? "user"}`, `${key}.sock`);
39
+ }
27
40
  export function bridgePaths(home, cwd, harness) {
28
41
  const dir = bridgeDir(home);
29
42
  const key = bridgeKey(cwd, harness);
30
- return { dir, key, lock: join(dir, `${key}.json`), log: join(dir, `${key}.log`), socket: join(dir, `${key}.sock`) };
43
+ return { dir, key, lock: join(dir, `${key}.json`), log: join(dir, `${key}.log`), socket: socketPath(dir, key) };
44
+ }
45
+ // Says why the hook socket can't be made, in words a person can act on.
46
+ export class BridgeSocketError extends Error {
31
47
  }
32
48
  function privateDir(dir) {
33
49
  mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -84,6 +100,11 @@ export function onHookEvent(fn) {
84
100
  export function holdBridge(opts) {
85
101
  const paths = bridgePaths(opts.home, opts.cwd, opts.harness);
86
102
  privateDir(paths.dir);
103
+ if (Buffer.byteLength(paths.socket) > MAX_SOCKET_PATH) {
104
+ throw new BridgeSocketError(`the bridge's socket path (${paths.socket}) is longer than the ${MAX_SOCKET_PATH} bytes a Unix socket allows: set TMPDIR to a shorter folder, such as /tmp`);
105
+ }
106
+ if (dirname(paths.socket) !== paths.dir)
107
+ privateDir(dirname(paths.socket));
87
108
  const open = new Set();
88
109
  let lastClosed = null;
89
110
  const lock = {
@@ -173,6 +194,12 @@ export function holdBridge(opts) {
173
194
  });
174
195
  conn.on("error", () => undefined);
175
196
  });
197
+ // A socket that can't listen is said, never a silent exit (W-244).
198
+ server.on("error", (err) => {
199
+ console.error(`gavel bridge: can't listen for hooks at ${paths.socket} (${err.code ?? err.message}).`);
200
+ release();
201
+ process.exit(1);
202
+ });
176
203
  server.listen(paths.socket, () => chmodSync(paths.socket, 0o600));
177
204
  server.unref();
178
205
  let released = false;
@@ -395,3 +422,82 @@ export async function hookEvent(opts) {
395
422
  }
396
423
  return 0;
397
424
  }
425
+ // The bridge's event for a status line's figures (W-258): never a hook's own name.
426
+ export const STATUS_LINE_EVENT = "StatusLine";
427
+ const OWN_LINE_MS = 10_000;
428
+ const OWN_LINE_BYTES = 64 * 1024;
429
+ // The status line the person had before the bridge's took this folder's place: the project's
430
+ // settings, then their own; never the bridge's own.
431
+ export function ownStatusLine(home, project, env) {
432
+ const config = env.CLAUDE_CONFIG_DIR || join(home, ".claude");
433
+ for (const file of [join(project, ".claude", "settings.json"), join(config, "settings.json")]) {
434
+ try {
435
+ const line = JSON.parse(readFileSync(file, "utf8")).statusLine;
436
+ if (line?.type === "command" && typeof line.command === "string" && line.command.trim() && !isBridgeStatusLine(line.command))
437
+ return line.command;
438
+ }
439
+ catch {
440
+ // none there
441
+ }
442
+ }
443
+ return null;
444
+ }
445
+ export const isBridgeStatusLine = (command) => /\bbridge status-line\b/.test(command);
446
+ function runOwn(command, input, cwd, env) {
447
+ return new Promise((resolve) => {
448
+ const child = spawn("/bin/sh", ["-c", command], { cwd, env, stdio: ["pipe", "pipe", "ignore"] });
449
+ let out = "";
450
+ const done = () => resolve(out);
451
+ const timer = setTimeout(() => child.kill("SIGKILL"), OWN_LINE_MS);
452
+ child.stdout.setEncoding("utf8");
453
+ child.stdout.on("data", (chunk) => {
454
+ if (out.length < OWN_LINE_BYTES)
455
+ out += chunk.slice(0, OWN_LINE_BYTES - out.length);
456
+ });
457
+ child.on("error", () => {
458
+ clearTimeout(timer);
459
+ done();
460
+ });
461
+ child.on("close", () => {
462
+ clearTimeout(timer);
463
+ done();
464
+ });
465
+ child.stdin.on("error", () => undefined);
466
+ child.stdin.end(input);
467
+ });
468
+ }
469
+ // `gavel bridge status-line`, Claude Code's status line in a folder whose bridge's hooks are on: the
470
+ // plan's figures alone (statusLineUsage) to the folder's running bridge, never starting one; then the
471
+ // person's own status line, with the same input, and only what it prints.
472
+ export async function bridgeStatusLine(opts) {
473
+ const text = await stdinText();
474
+ let input = {};
475
+ try {
476
+ const parsed = JSON.parse(text);
477
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
478
+ input = parsed;
479
+ }
480
+ catch {
481
+ // no input: the person's own line still runs
482
+ }
483
+ const dir = (v) => (typeof v === "string" && existsSync(v) ? v : null);
484
+ const cwd = dir(input.workspace?.current_dir) ?? dir(input.cwd) ?? opts.cwd;
485
+ const project = dir(input.workspace?.project_dir) ?? cwd;
486
+ const usage = statusLineUsage(input);
487
+ const handed = (async () => {
488
+ try {
489
+ const live = usage ? runningBridge(opts.home, project, "claude-code") : null;
490
+ if (live)
491
+ await send(live.socket, `${JSON.stringify({ event: STATUS_LINE_EVENT, input: usage, inbox: null, at: Date.now() })}\n`);
492
+ }
493
+ catch {
494
+ // never the status line's failure
495
+ }
496
+ })();
497
+ const own = ownStatusLine(opts.home, project, opts.env);
498
+ const shown = own ? await runOwn(own, text, cwd, opts.env) : "";
499
+ await handed;
500
+ // Written whole before the process exits: a pipe on a Mac takes it asynchronously.
501
+ await new Promise((resolve) => process.stdout.write(shown, () => resolve()));
502
+ return 0;
503
+ }
@@ -3,7 +3,8 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { basename, join } from "node:path";
5
5
  import { jsonText } from "../output.js";
6
- import { markChatOff, onHookEvent } from "./background.js";
6
+ import { markChatOff, onHookEvent, STATUS_LINE_EVENT } from "./background.js";
7
+ import { claudePlanReporter, planUsageOf } from "./claude-plan.js";
7
8
  import { claudeSessions } from "./claude-code.js";
8
9
  import { ClaudeCodeHarness } from "./claude-live.js";
9
10
  import { codexHarness, codexSessions } from "./codex.js";
@@ -96,7 +97,29 @@ async function show(run, ctx) {
96
97
  async function bridge(run, ctx) {
97
98
  const harness = harnessHere(run.harness, ctx);
98
99
  const setup = setupHere(harness, run.server, ctx);
99
- return harnessBridge(harnessOf(harness, ctx), harness, setup, ctx);
100
+ const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
101
+ let linked = null;
102
+ const report = async (method, path, input) => {
103
+ const res = await call(api, method, path, input);
104
+ if (res.status === 404)
105
+ linked = null;
106
+ if (!res.ok)
107
+ throw new Error("Gavel refused the plan usage report");
108
+ };
109
+ const planReporter = {
110
+ async linked() {
111
+ if (linked && Date.now() < linked.until)
112
+ return linked.id;
113
+ const res = await call(api, "GET", "/v1/agents/me/plan");
114
+ const body = res.ok ? await res.json() : null;
115
+ const id = typeof body?.planId === "string" ? body.planId : null;
116
+ linked = { id, until: Date.now() + 120_000 };
117
+ return id;
118
+ },
119
+ day: (input) => report("PUT", "/v1/agents/me/plan/days", input),
120
+ record: (input) => report("POST", "/v1/agents/me/plan/usage", input),
121
+ };
122
+ return harnessBridge(harnessOf(harness, { ...ctx, planReporter }), harness, setup, ctx);
100
123
  }
101
124
  const PICTURE_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp" };
102
125
  const PICTURE_MAX = 15 * 1024 * 1024;
@@ -440,8 +463,16 @@ async function harnessBridge(h, harness, setup, ctx) {
440
463
  }
441
464
  };
442
465
  const wakeTimer = setInterval(() => void tryWake(), WAKE_AGAIN_MS);
443
- // The harness's own hooks, through `gavel bridge event` (background.ts).
444
- const offHooks = onHookEvent((event) => h.hook?.(event.event, event));
466
+ // Claude Code's plan use, from its status line (W-258): to the plan the agent's link names.
467
+ const plan = harness === "claude-code" ? claudePlanReporter({ home: ctx.home, env: ctx.env, request: (method, path, body) => call(api, method, path, body), say }) : null;
468
+ // The harness's own hooks, through `gavel bridge event` (background.ts), and the status line's.
469
+ const offHooks = onHookEvent((event) => {
470
+ if (event.event !== STATUS_LINE_EVENT)
471
+ return h.hook?.(event.event, event);
472
+ const usage = planUsageOf(event.input);
473
+ if (plan && usage)
474
+ plan.observe(usage);
475
+ });
445
476
  h.listen({
446
477
  live: (event) => {
447
478
  if (!on || !liveRoute)
@@ -470,6 +501,7 @@ async function harnessBridge(h, harness, setup, ctx) {
470
501
  if (soon)
471
502
  clearTimeout(soon);
472
503
  offHooks();
504
+ plan?.close();
473
505
  };
474
506
  const stop = (said = "Stopped.") => {
475
507
  if (stopping)
@@ -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 } 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
@@ -24,11 +24,22 @@ import { claudeSetups } from "./setup.js";
24
24
  // PostToolUse, Stop, StopFailure and SessionEnd.
25
25
  export const BRIDGE_MIN_VERSION = [2, 1, 224];
26
26
  // One message into a session's inbox; true once Claude Code took the line.
27
+ const ENVELOPE = "cross-session-message";
28
+ // Claude Code (2.1.332) holds another session's message for approval in a session that bypasses
29
+ // permission prompts, unless the sender says it bypasses them too, in the message's own envelope
30
+ // (`from-mode`); the bridge says so for a session it knows bypasses them (W-256), carrying its
31
+ // person's own words and Gavel's wakes. Only that: said to a session that prompts, `bypass` is held
32
+ // as a mismatch, and saying nothing it takes. Words holding the envelope's closing tag go as they are.
33
+ export function attested(text, bypass) {
34
+ if (!bypass || new RegExp(`</${ENVELOPE}`, "i").test(text))
35
+ return text;
36
+ return `<${ENVELOPE} from-name="Gavel" from-mode="bypass">\n${text}\n</${ENVELOPE}>`;
37
+ }
27
38
  export function inboxSend(inbox, text, opts) {
28
39
  return new Promise((resolve) => {
29
40
  const lines = [
30
41
  ...(inbox.token ? [JSON.stringify({ type: "auth", token: inbox.token })] : []),
31
- JSON.stringify({ type: "user", message: { role: "user", content: text }, priority: opts.priority, ...(opts.msgId ? { msg_id: opts.msgId } : {}) }),
42
+ JSON.stringify({ type: "user", message: { role: "user", content: attested(text, opts.bypass === true) }, priority: opts.priority, ...(opts.msgId ? { msg_id: opts.msgId } : {}) }),
32
43
  ];
33
44
  const conn = connect(inbox.socket, () => conn.end(`${lines.join("\n")}\n`));
34
45
  conn.setTimeout(5_000, () => conn.destroy(new Error("timeout")));
@@ -58,9 +69,13 @@ const DISPLAY_PATH = "/gavel-bridge/";
58
69
  const isBridgeHook = (h) => (Array.isArray(h.args) && h.args.includes("bridge") && h.args.includes("event")) ||
59
70
  (typeof h.url === "string" && h.url.startsWith("http://127.0.0.1:") && h.url.includes(DISPLAY_PATH)) ||
60
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(" ");
61
74
  // The settings with the bridge's hooks in (its command and the display hook's address) or out
62
- // (null), every other hook and setting kept; null when nothing changes.
63
- 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
+ export function withBridgeHooks(existing, command, displayUrl, statusLine = null) {
64
79
  let settings = {};
65
80
  if (existing?.trim()) {
66
81
  try {
@@ -85,11 +100,14 @@ export function withBridgeHooks(existing, command, displayUrl) {
85
100
  }
86
101
  if (displayUrl)
87
102
  hooks.MessageDisplay = [...(hooks.MessageDisplay ?? []), { hooks: [{ type: "http", url: displayUrl, timeout: 2 }] }];
88
- const { hooks: _old, ...rest } = settings;
89
- const next = Object.keys(hooks).length ? { ...rest, hooks } : rest;
103
+ const { hooks: _old, statusLine: line, ...rest } = settings;
104
+ const ours = isOurStatusLine(line);
105
+ const keptLine = line !== undefined && !ours ? { statusLine: line } : statusLine ? { statusLine: { type: "command", command: shellLine([...statusLine, "bridge", "status-line"]) } } : {};
106
+ const next = { ...rest, ...keptLine, ...(Object.keys(hooks).length ? { hooks } : {}) };
90
107
  const text = `${JSON.stringify(next, null, 2)}\n`;
91
108
  return text === existing ? null : text;
92
109
  }
110
+ const isOurStatusLine = (line) => typeof line?.command === "string" && isBridgeStatusLine(line.command);
93
111
  // The display hook's address for this folder: a port and a secret path kept beside the bridge's
94
112
  // lock (mode 600), the same each time, so the settings name it once.
95
113
  export function displayHook(home, cwd) {
@@ -197,14 +215,19 @@ export async function claudeBridgeHooks(action, opts) {
197
215
  // With Gavel's plugin on, it runs the bridge's hooks: this folder gets only its own address for
198
216
  // the agent's words as they're shown.
199
217
  const plugin = gavelPluginOn(opts.home);
200
- const next = withBridgeHooks(existing, plugin ? null : opts.command, displayHook(opts.home, opts.cwd).url);
218
+ // 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);
201
220
  if (next !== null)
202
221
  writeWhole(file, next);
222
+ const line = JSON.parse(next ?? existing ?? "{}").statusLine;
203
223
  const done = [
204
224
  plugin
205
225
  ? `Gavel's plugin runs the bridge's hooks here; wrote this folder's hook for the words as they're shown into ${name}`
206
226
  : `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`,
207
227
  ];
228
+ done.push(isOurStatusLine(line)
229
+ ? `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`
230
+ : `kept your own status line in ${name}, so your Claude plan's use isn't read here`);
208
231
  if (gitIn(["rev-parse", "--is-inside-work-tree"], opts.cwd) && !gitIn(["check-ignore", "-q", name], opts.cwd)) {
209
232
  const gitignore = join(opts.cwd, ".gitignore");
210
233
  const text = existsSync(gitignore) ? readFileSync(gitignore, "utf8") : "";
@@ -252,8 +275,9 @@ export function sessionWords(jsonl, fromGavel, prompts = new Map()) {
252
275
  const id = line.origin?.msg_id;
253
276
  if (line.type !== "user" || line.origin?.kind !== "peer" || typeof id !== "string" || !fromGavel.has(id) || !line.uuid || !line.timestamp)
254
277
  continue;
278
+ // An attested message's words are its envelope's body, which Claude Code keeps beside it.
255
279
  const content = typeof line.message?.content === "string" ? line.message.content : "";
256
- const body = content.replace(PEER_HEADER, "");
280
+ const body = typeof line.origin.body === "string" ? line.origin.body : content.replace(PEER_HEADER, "");
257
281
  const end = body.indexOf(PEER_FOOTER);
258
282
  const text = theirWords(end >= 0 ? body.slice(0, end) : body);
259
283
  words.push({ id: line.uuid, side: "person", text: text || "(message)", at: line.timestamp, gavelId: id });
@@ -288,6 +312,54 @@ function readFrom(file, offset, max = READ_MAX) {
288
312
  return null;
289
313
  }
290
314
  }
315
+ // A session's permission mode as its transcript last noted it (Claude Code writes it as the file
316
+ // starts and with each prompt), from the file's last 256 KB; null when it says none.
317
+ export function lastMode(file) {
318
+ const read = readFrom(file, Math.max(0, sizeOf(file) - 262_144), 262_144);
319
+ const all = read ? [...read.toString("utf8").matchAll(/"permissionMode":"([A-Za-z]+)"/g)] : [];
320
+ return all.at(-1)?.[1] ?? null;
321
+ }
322
+ // What Claude Code held of the messages other sessions sent this one, as its transcript notes each
323
+ // ("Held peer message", a notice for the person); how many, and when the last was.
324
+ export function heldNotices(file) {
325
+ let held = 0;
326
+ let lastAt = null;
327
+ let text = "";
328
+ try {
329
+ text = readFileSync(file, "utf8");
330
+ }
331
+ catch {
332
+ return { held, lastAt };
333
+ }
334
+ for (const raw of text.split("\n")) {
335
+ if (!raw.includes("Held peer message"))
336
+ continue;
337
+ try {
338
+ const line = JSON.parse(raw);
339
+ if (line.type !== "system" || typeof line.content !== "string" || !line.content.startsWith("Held peer message"))
340
+ continue;
341
+ held++;
342
+ if (typeof line.timestamp === "string")
343
+ lastAt = line.timestamp;
344
+ }
345
+ catch {
346
+ // a line read as it was written
347
+ }
348
+ }
349
+ return { held, lastAt };
350
+ }
351
+ // For `gavel bridge status`: what Claude Code held in the folder's newest session of the messages
352
+ // other sessions sent it (the bridge's before it said who it is, W-256), and how they go through.
353
+ export function claudeHeld(cwd, home, env) {
354
+ const newest = claudeSessions(cwd, home, env)[0];
355
+ const notes = newest ? heldNotices(newest.file) : null;
356
+ if (!notes?.held)
357
+ return null;
358
+ return {
359
+ ...notes,
360
+ release: "Claude Code holds messages from other sessions while this session bypasses permission prompts. Let them through in the session's dialog (Deliver), or in /config, Messages from your other sessions. The bridge from 0.1.25 says who it is, so its messages aren't held.",
361
+ };
362
+ }
291
363
  // The first and the last of an answer's words as its transcript line has them (JSON), each within
292
364
  // one line of it: Claude Code joins a message's parts with a newline for the Stop hook, so neither
293
365
  // spans two parts.
@@ -372,6 +444,11 @@ export class ClaudeCodeHarness {
372
444
  renameSync(temp, this.idsFile);
373
445
  }
374
446
  // The session Gavel shows and writes to: the newest one open, else the folder's newest.
447
+ // Whether a session bypasses permission prompts, as its hooks or else its transcript last said.
448
+ bypasses(s) {
449
+ const file = s.transcript ?? claudeSessions(this.ctx.cwd, this.ctx.home, this.ctx.env).find((c) => c.id === s.id)?.file ?? null;
450
+ return (s.mode ?? (file ? lastMode(file) : null)) === "bypassPermissions";
451
+ }
375
452
  current() {
376
453
  const open = [...this.sessions.values()].filter((s) => s.open).sort((a, b) => Number(b.begun) - Number(a.begun) || b.seen - a.seen);
377
454
  return open[0] ?? null;
@@ -430,7 +507,7 @@ export class ClaudeCodeHarness {
430
507
  session(id) {
431
508
  let s = this.sessions.get(id);
432
509
  if (!s) {
433
- s = { id, inbox: null, transcript: null, open: true, hooked: false, background: false, begun: false, state: "idle", seen: Date.now(), run: null, spoken: new Map() };
510
+ s = { id, inbox: null, transcript: null, open: true, hooked: false, background: false, begun: false, mode: null, state: "idle", seen: Date.now(), run: null, spoken: new Map() };
434
511
  this.sessions.set(id, s);
435
512
  }
436
513
  return s;
@@ -454,6 +531,8 @@ export class ClaudeCodeHarness {
454
531
  s.inbox = e.inbox;
455
532
  if (typeof input.transcript_path === "string")
456
533
  s.transcript = input.transcript_path;
534
+ if (typeof input.permission_mode === "string")
535
+ s.mode = input.permission_mode;
457
536
  const runId = typeof input.prompt_id === "string" ? input.prompt_id : s.run;
458
537
  switch (event) {
459
538
  case "SessionStart":
@@ -587,7 +666,7 @@ export class ClaudeCodeHarness {
587
666
  open = (await this.liveSession()) ?? this.current();
588
667
  if (open?.inbox) {
589
668
  this.remember(m.id);
590
- if (await inboxSend(open.inbox, text, { priority: "next", msgId: m.id }))
669
+ if (await inboxSend(open.inbox, text, { priority: "next", msgId: m.id, bypass: this.bypasses(open) }))
591
670
  return { outcome: "delivered" };
592
671
  open.open = false;
593
672
  open.inbox = null;
@@ -676,13 +755,13 @@ export class ClaudeCodeHarness {
676
755
  const open = this.current();
677
756
  if (!open?.inbox || (open.state !== "working" && open.state !== "waiting"))
678
757
  return "over";
679
- const sent = await inboxSend(open.inbox, `${this.ctx.person} pressed Stop in Gavel: stop what you're doing, say in a line where you stopped, and wait for them.`, { priority: "now" });
758
+ const sent = await inboxSend(open.inbox, `${this.ctx.person} pressed Stop in Gavel: stop what you're doing, say in a line where you stopped, and wait for them.`, { priority: "now", bypass: this.bypasses(open) });
680
759
  return sent ? "stopped" : "over";
681
760
  }
682
761
  // Gavel's one-line wake (D-1103), into an open session: mid-turn or as a turn of its own.
683
762
  async wake(line) {
684
763
  const open = this.current();
685
- return open?.inbox ? inboxSend(open.inbox, line, { priority: "next" }) : false;
764
+ return open?.inbox ? inboxSend(open.inbox, line, { priority: "next", bypass: this.bypasses(open) }) : false;
686
765
  }
687
766
  listen(l) {
688
767
  this.listener = l;
@@ -0,0 +1,238 @@
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 Claude account signed in on this laptop, as a hash of its ids (~/.claude.json's oauthAccount):
84
+ // compared here, never sent. Null when none is (an API key's session).
85
+ export function claudeAccount(home, env = process.env) {
86
+ const file = env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, ".claude.json") : join(home, ".claude.json");
87
+ try {
88
+ const account = JSON.parse(readFileSync(file, "utf8")).oauthAccount;
89
+ if (typeof account?.accountUuid !== "string" || !account.accountUuid)
90
+ return null;
91
+ return createHash("sha256").update(`claude\0${account.accountUuid}\0${typeof account.organizationUuid === "string" ? account.organizationUuid : ""}`).digest("hex");
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ }
97
+ // Which account first reported under each plan, kept beside the bridge's locks (mode 600).
98
+ function accountsFile(home) {
99
+ return join(home, ".gavel", "bridge", "plan-accounts.json");
100
+ }
101
+ function readAccounts(home) {
102
+ try {
103
+ const kept = JSON.parse(readFileSync(accountsFile(home), "utf8"));
104
+ return kept && typeof kept === "object" ? kept : {};
105
+ }
106
+ catch {
107
+ return {};
108
+ }
109
+ }
110
+ function keepAccount(home, planId, account) {
111
+ const file = accountsFile(home);
112
+ mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
113
+ const temp = `${file}.${process.pid}.tmp`;
114
+ writeFileSync(temp, `${JSON.stringify({ ...readAccounts(home), [planId]: account }, null, 2)}\n`, { mode: 0o600 });
115
+ chmodSync(temp, 0o600);
116
+ renameSync(temp, file);
117
+ }
118
+ // Whether the next figures say something the last sent didn't: a window's whole percent, a reset, a
119
+ // window come or gone, or the limit reached.
120
+ export function changed(last, next) {
121
+ if (!last)
122
+ return true;
123
+ const key = (u) => JSON.stringify([
124
+ u.windows.map((w) => [w.kind, Math.floor(w.usedPercent), w.resetsAt]),
125
+ u.spendLimit ? [Math.floor(u.spendLimit.usedPercent), u.spendLimit.resetsAt] : null,
126
+ u.limitReached,
127
+ ]);
128
+ return key(last) !== key(next);
129
+ }
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.
132
+ const MINUTES = { five_hour: 300, weekly: 10_080 };
133
+ export function usageBody(planId, usage, at, machineName = hostname()) {
134
+ return {
135
+ planId,
136
+ machineName: machineName.slice(0, 200),
137
+ observedAt: at.toISOString(),
138
+ windows: usage.windows.map((w) => ({ limitId: "claude", durationMinutes: MINUTES[w.kind], usedPercent: w.usedPercent, resetsAt: w.resetsAt })),
139
+ limitReached: usage.limitReached,
140
+ };
141
+ }
142
+ export const PLAN_EVERY_MS = 60_000;
143
+ 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.
147
+ export function claudePlanReporter(opts) {
148
+ const now = opts.now ?? Date.now;
149
+ const every = opts.everyMs ?? PLAN_EVERY_MS;
150
+ let plan = null;
151
+ let sent = null;
152
+ // When it last tried: a refusal waits for the next figures, a minute on, never a loop.
153
+ let triedAt = -Infinity;
154
+ let latest = null;
155
+ let timer = null;
156
+ let sending = false;
157
+ let said = "";
158
+ let closed = false;
159
+ const sayOnce = (line) => {
160
+ if (line !== said)
161
+ opts.say(line);
162
+ said = line;
163
+ };
164
+ const planId = async () => {
165
+ if (plan && now() - plan.at < PLAN_LOOK_AGAIN_MS)
166
+ return plan.id;
167
+ const res = await opts.request("GET", "/v1/agents/me/plan");
168
+ if (res.status === 404) {
169
+ void res.body?.cancel();
170
+ plan = { id: null, at: now() };
171
+ return null;
172
+ }
173
+ if (!res.ok)
174
+ throw new Error(`Gavel answered ${res.status} to which plan this agent is on`);
175
+ const body = (await res.json());
176
+ plan = { id: typeof body?.planId === "string" ? body.planId : null, at: now() };
177
+ return plan.id;
178
+ };
179
+ const send = async () => {
180
+ timer = null;
181
+ if (sending || closed || !latest || !changed(sent, latest))
182
+ return;
183
+ sending = true;
184
+ triedAt = now();
185
+ const usage = latest;
186
+ try {
187
+ const id = await planId();
188
+ if (!id)
189
+ 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
+ if (!account)
192
+ return sayOnce("Claude Code's plan use isn't sent: no Claude account is signed in here.");
193
+ const first = readAccounts(opts.home)[id];
194
+ if (first && first !== account)
195
+ 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.");
196
+ const res = await opts.request("POST", "/v1/agents/me/plan/usage", usageBody(id, usage, new Date(now())));
197
+ void res.body?.cancel();
198
+ if (res.status === 403 || res.status === 404 || res.status === 409) {
199
+ plan = null;
200
+ 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.`);
201
+ }
202
+ if (!res.ok)
203
+ return sayOnce(`Claude Code's plan use isn't sent: Gavel answered ${res.status}; it tries again with the next figures.`);
204
+ if (!first)
205
+ keepAccount(opts.home, id, account);
206
+ sent = usage;
207
+ sayOnce("Claude Code's plan use goes to Gavel, for you alone.");
208
+ }
209
+ catch (err) {
210
+ sayOnce(`Claude Code's plan use isn't sent: ${err instanceof Error ? err.message : String(err)}`);
211
+ }
212
+ finally {
213
+ sending = false;
214
+ // Figures that came while it sent go next, a minute after.
215
+ if (sent === usage && latest !== usage)
216
+ schedule();
217
+ }
218
+ };
219
+ const schedule = () => {
220
+ if (closed || timer || sending || !latest || !changed(sent, latest))
221
+ return;
222
+ timer = setTimeout(() => void send(), Math.max(0, triedAt + every - now()));
223
+ timer.unref?.();
224
+ };
225
+ return {
226
+ observe(usage) {
227
+ if (closed)
228
+ return;
229
+ latest = usage;
230
+ schedule();
231
+ },
232
+ close() {
233
+ closed = true;
234
+ if (timer)
235
+ clearTimeout(timer);
236
+ },
237
+ };
238
+ }
@@ -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",
@@ -0,0 +1,261 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { hostname } from "node:os";
4
+ import { join } from "node:path";
5
+ const countKeys = ["inputTokens", "cacheWriteTokens", "cacheReadTokens", "outputTokens"];
6
+ const zero = () => ({ inputTokens: 0, cacheWriteTokens: 0, cacheReadTokens: 0, outputTokens: 0 });
7
+ export function codexCounts(value) {
8
+ if (!value || typeof value !== "object")
9
+ return null;
10
+ const { inputTokens, cachedInputTokens, outputTokens } = value;
11
+ if (typeof inputTokens !== "number" || typeof cachedInputTokens !== "number" || typeof outputTokens !== "number")
12
+ return null;
13
+ if (![inputTokens, cachedInputTokens, outputTokens].every((count) => Number.isSafeInteger(count) && count >= 0))
14
+ return null;
15
+ return { inputTokens: Math.max(0, inputTokens - cachedInputTokens), cacheReadTokens: cachedInputTokens, outputTokens, cacheWriteTokens: 0 };
16
+ }
17
+ export function codexWindows(snapshot) {
18
+ const buckets = Object.entries(snapshot.rateLimitsByLimitId ?? {});
19
+ if (!buckets.length && snapshot.rateLimits)
20
+ buckets.push(["codex", snapshot.rateLimits]);
21
+ const windows = new Map();
22
+ for (const [key, bucket] of buckets) {
23
+ if (!bucket || typeof bucket !== "object")
24
+ continue;
25
+ const limitId = typeof bucket.limitId === "string" ? bucket.limitId : key;
26
+ if (!/^[a-z0-9_-]{1,64}$/i.test(limitId))
27
+ continue;
28
+ for (const value of [bucket.primary, bucket.secondary]) {
29
+ if (!value || typeof value !== "object")
30
+ continue;
31
+ const { windowDurationMins, usedPercent, resetsAt } = value;
32
+ if (typeof windowDurationMins !== "number" || !Number.isInteger(windowDurationMins) || windowDurationMins < 1 || windowDurationMins > 100_800)
33
+ continue;
34
+ if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent) || usedPercent < 0 || usedPercent > 10_000)
35
+ continue;
36
+ if (typeof resetsAt !== "number" || !Number.isFinite(resetsAt) || resetsAt <= 0 || resetsAt > 253402300799)
37
+ continue;
38
+ windows.set(`${limitId}:${windowDurationMins}`, {
39
+ limitId, durationMinutes: windowDurationMins, usedPercent, resetsAt: new Date(resetsAt * 1000).toISOString(),
40
+ });
41
+ }
42
+ }
43
+ return [...windows.values()].slice(0, 32);
44
+ }
45
+ async function accountOf(app) {
46
+ const { account } = await app.request("account/read", { refreshToken: false });
47
+ return account?.type === "chatgpt" && typeof account.email === "string" ? account.email.trim().toLowerCase() : null;
48
+ }
49
+ function boundAccount(home, planId, account) {
50
+ if (!/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(planId))
51
+ return false;
52
+ const dir = join(home, ".gavel", "plan-accounts");
53
+ const file = join(dir, `codex-${planId}`);
54
+ const fingerprint = createHash("sha256").update(planId).update("\0").update(account).digest("hex");
55
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
56
+ try {
57
+ writeFileSync(file, fingerprint, { mode: 0o600, flag: "wx" });
58
+ }
59
+ catch (err) {
60
+ if (err.code !== "EEXIST")
61
+ throw err;
62
+ }
63
+ return readFileSync(file, "utf8") === fingerprint;
64
+ }
65
+ const MINUTE = 60_000;
66
+ const localDate = (date) => [date.getFullYear(), String(date.getMonth() + 1).padStart(2, "0"), String(date.getDate()).padStart(2, "0")].join("-");
67
+ export class CodexPlanUsage {
68
+ home;
69
+ cwd;
70
+ reporter;
71
+ checking = false;
72
+ accountRevision = 0;
73
+ confirmedPlan = null;
74
+ pendingApp = null;
75
+ quotaTimer = null;
76
+ dayTimer = null;
77
+ nextQuota = 0;
78
+ nextDay = 0;
79
+ lastWindows = "";
80
+ warned = new Set();
81
+ totals = new Map();
82
+ pendingDays = new Map();
83
+ sendingDays = false;
84
+ constructor(home, cwd, reporter) {
85
+ this.home = home;
86
+ this.cwd = cwd;
87
+ this.reporter = reporter;
88
+ }
89
+ once(key, line) {
90
+ if (this.warned.has(key))
91
+ return;
92
+ this.warned.add(key);
93
+ console.error(line);
94
+ }
95
+ source() {
96
+ const folder = createHash("sha256").update(this.cwd).digest("hex").slice(0, 16);
97
+ const path = join(this.home, ".gavel", "plan-accounts", `source-${folder}`);
98
+ try {
99
+ writeFileSync(path, randomUUID(), { mode: 0o600, flag: "wx" });
100
+ }
101
+ catch (err) {
102
+ if (err.code !== "EEXIST")
103
+ throw err;
104
+ }
105
+ return { folder, sourceId: readFileSync(path, "utf8") };
106
+ }
107
+ observe(thread, usage, count) {
108
+ if (!usage || typeof usage !== "object")
109
+ return;
110
+ const raw = usage;
111
+ const total = codexCounts(raw.total);
112
+ if (!total)
113
+ return;
114
+ const before = this.totals.get(thread);
115
+ this.totals.set(thread, total);
116
+ const planId = this.confirmedPlan;
117
+ if (!count || !planId)
118
+ return;
119
+ const delta = before ? zero() : codexCounts(raw.last);
120
+ if (!delta)
121
+ return;
122
+ if (before)
123
+ for (const key of countKeys)
124
+ delta[key] = Math.max(0, total[key] - before[key]);
125
+ if (countKeys.every((key) => delta[key] === 0))
126
+ return;
127
+ try {
128
+ const date = localDate(new Date());
129
+ const { folder, sourceId } = this.source();
130
+ const file = join(this.home, ".gavel", "plan-accounts", `codex-${planId}-${folder}-${date}.json`);
131
+ let sum = zero();
132
+ try {
133
+ sum = JSON.parse(readFileSync(file, "utf8"));
134
+ }
135
+ catch (err) {
136
+ if (err.code !== "ENOENT")
137
+ throw err;
138
+ }
139
+ for (const key of countKeys)
140
+ sum[key] += delta[key];
141
+ const temp = `${file}.${process.pid}.tmp`;
142
+ writeFileSync(temp, JSON.stringify(sum), { mode: 0o600 });
143
+ renameSync(temp, file);
144
+ this.pendingDays.set(`${planId}:${date}`, { planId, date, sourceId, ...sum });
145
+ this.scheduleDay();
146
+ }
147
+ catch {
148
+ this.once("day-storage", "Gavel could not store local Codex usage counts.");
149
+ }
150
+ }
151
+ scheduleDay() {
152
+ if (this.dayTimer || this.sendingDays || !this.pendingDays.size)
153
+ return;
154
+ this.dayTimer = setTimeout(() => {
155
+ this.dayTimer = null;
156
+ void this.flushDay();
157
+ }, Math.max(0, this.nextDay - Date.now()));
158
+ this.dayTimer.unref();
159
+ }
160
+ async flushDay() {
161
+ if (this.sendingDays || !this.pendingDays.size)
162
+ return;
163
+ if (this.dayTimer)
164
+ clearTimeout(this.dayTimer);
165
+ this.dayTimer = null;
166
+ this.sendingDays = true;
167
+ this.nextDay = Date.now() + MINUTE;
168
+ try {
169
+ for (const [key, day] of this.pendingDays) {
170
+ if (day.planId !== await this.reporter.linked()) {
171
+ this.pendingDays.delete(key);
172
+ continue;
173
+ }
174
+ await this.reporter.day(day);
175
+ if (this.pendingDays.get(key) === day)
176
+ this.pendingDays.delete(key);
177
+ }
178
+ }
179
+ catch {
180
+ this.once("day-refused", "Gavel could not record Codex's daily usage. The bridge will retry.");
181
+ }
182
+ finally {
183
+ this.sendingDays = false;
184
+ this.scheduleDay();
185
+ }
186
+ }
187
+ refresh(app, accountChanged = false) {
188
+ if (accountChanged) {
189
+ this.accountRevision++;
190
+ this.confirmedPlan = null;
191
+ this.totals.clear();
192
+ }
193
+ this.pendingApp = app;
194
+ this.scheduleQuota();
195
+ }
196
+ scheduleQuota() {
197
+ if (this.quotaTimer || this.checking || !this.pendingApp)
198
+ return;
199
+ this.quotaTimer = setTimeout(() => {
200
+ this.quotaTimer = null;
201
+ void this.readQuota();
202
+ }, Math.max(0, this.nextQuota - Date.now()));
203
+ this.quotaTimer.unref();
204
+ }
205
+ async readQuota() {
206
+ const app = this.pendingApp;
207
+ if (!app)
208
+ return;
209
+ this.pendingApp = null;
210
+ this.checking = true;
211
+ const revision = this.accountRevision;
212
+ this.nextQuota = Date.now() + MINUTE;
213
+ try {
214
+ const planId = await this.reporter.linked();
215
+ if (!planId) {
216
+ this.confirmedPlan = null;
217
+ return;
218
+ }
219
+ const account = await accountOf(app);
220
+ if (!account || !boundAccount(this.home, planId, account)) {
221
+ this.confirmedPlan = null;
222
+ if (account)
223
+ this.once(planId, "Gavel plan usage paused: Codex switched accounts. Link the active plan in Settings.");
224
+ return;
225
+ }
226
+ const snapshot = await app.request("account/rateLimits/read");
227
+ if (await accountOf(app) !== account || revision !== this.accountRevision)
228
+ return;
229
+ this.confirmedPlan = planId;
230
+ const windows = codexWindows(snapshot);
231
+ if (!windows.length)
232
+ return;
233
+ const buckets = Object.values(snapshot.rateLimitsByLimitId ?? {});
234
+ const limitReached = [...buckets, snapshot.rateLimits].some((bucket) => typeof bucket?.rateLimitReachedType === "string");
235
+ const signature = JSON.stringify([planId, windows.map((w) => ({ ...w, usedPercent: Math.floor(w.usedPercent) })), limitReached]);
236
+ if (signature === this.lastWindows)
237
+ return;
238
+ const machineName = hostname().replace(/\p{Cc}/gu, "").slice(0, 64) || "Codex";
239
+ await this.reporter.record({ planId, windows, observedAt: new Date().toISOString(), machineName, ...(limitReached ? { limitReached: true } : {}) });
240
+ this.lastWindows = signature;
241
+ }
242
+ catch {
243
+ this.once("quota-refused", "Gavel could not read or record Codex plan usage. The bridge will retry.");
244
+ if (revision === this.accountRevision)
245
+ this.pendingApp ??= app;
246
+ }
247
+ finally {
248
+ this.checking = false;
249
+ this.scheduleQuota();
250
+ }
251
+ }
252
+ disconnect() {
253
+ this.accountRevision++;
254
+ this.confirmedPlan = null;
255
+ this.pendingApp = null;
256
+ this.totals.clear();
257
+ if (this.quotaTimer)
258
+ clearTimeout(this.quotaTimer);
259
+ this.quotaTimer = null;
260
+ }
261
+ }
@@ -5,6 +5,7 @@ import { basename, join } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { cliVersion, withCodexHooks, writeWhole } from "../hook.js";
7
7
  import { connectCodex, controlSocket, startCodexServer } from "./codex-app.js";
8
+ import { CodexPlanUsage } from "./codex-plan.js";
8
9
  import { codexSetups } from "./setup.js";
9
10
  import { WebSocketError } from "./websocket.js";
10
11
  import { cut } from "./words.js";
@@ -180,8 +181,11 @@ class CodexHarness {
180
181
  state = null;
181
182
  stoppedAt = 0;
182
183
  started = null;
184
+ planTurns = new Set();
185
+ planUsage;
183
186
  constructor(ctx) {
184
187
  this.ctx = ctx;
188
+ this.planUsage = ctx.planReporter ? new CodexPlanUsage(ctx.home, ctx.cwd, ctx.planReporter) : null;
185
189
  }
186
190
  here(cwd) {
187
191
  return cwd === this.ctx.cwd || realpath(cwd) === realpath(this.ctx.cwd);
@@ -227,10 +231,12 @@ class CodexHarness {
227
231
  app = await connectCodex(socket, handlers, cliVersion());
228
232
  }
229
233
  this.app = app;
234
+ this.planUsage?.refresh(app, true);
230
235
  void app.closed.then(() => {
231
236
  if (this.app !== app)
232
237
  return;
233
238
  this.app = null;
239
+ this.planUsage?.disconnect();
234
240
  if (this.current)
235
241
  this.current.subscribed = false;
236
242
  this.turnId = null;
@@ -303,6 +309,10 @@ class CodexHarness {
303
309
  return { thread: `codex:${current.id}`, label: this.label(), session: current.id, messages: [...this.words.values()].sort((a, b) => a.at.localeCompare(b.at)) };
304
310
  }
305
311
  notified(method, params) {
312
+ if (this.app && (method === "account/rateLimits/updated" || method === "account/updated")) {
313
+ this.planUsage?.refresh(this.app, method === "account/updated");
314
+ return;
315
+ }
306
316
  const threadId = typeof params.threadId === "string" ? params.threadId : null;
307
317
  if (method === "thread/started") {
308
318
  const thread = params.thread;
@@ -314,6 +324,10 @@ class CodexHarness {
314
324
  if (!current || threadId !== current.id)
315
325
  return;
316
326
  switch (method) {
327
+ case "thread/tokenUsage/updated":
328
+ if (this.app)
329
+ this.planUsage?.observe(current.id, params.tokenUsage, typeof params.turnId === "string" && this.planTurns.has(params.turnId));
330
+ return;
317
331
  case "thread/status/changed":
318
332
  current.status = params.status;
319
333
  this.setState(stateOf(current.status));
@@ -334,6 +348,8 @@ class CodexHarness {
334
348
  const item = params.item;
335
349
  if (item.type === "agentMessage")
336
350
  this.offsets.set(item.id, 0);
351
+ if (item.type === "userMessage" && item.clientId?.startsWith("gavel") && typeof params.turnId === "string")
352
+ this.planTurns.add(params.turnId);
337
353
  // Someone typed at the laptop: the session has its person there now.
338
354
  if (item.type === "userMessage" && !item.clientId?.startsWith("gavel"))
339
355
  this.ownLoaded.delete(current.id);
@@ -370,6 +386,8 @@ class CodexHarness {
370
386
  if (turn.status === "failed" && this.unattended.has(turn.id))
371
387
  this.listener?.note(`Codex couldn't finish: ${turn.error?.message ?? "the turn failed"}`.slice(0, 300));
372
388
  this.unattended.delete(turn.id);
389
+ if (this.planTurns.delete(turn.id))
390
+ void this.planUsage?.flushDay();
373
391
  this.listener?.changed();
374
392
  if (this.announced.delete(turn.id))
375
393
  this.listener?.live({ event: "end", runId: turn.id });
@@ -402,6 +420,8 @@ class CodexHarness {
402
420
  if (wake && (this.turnId || current.status.type === "active" || Date.now() - this.stoppedAt < QUIET_AFTER_STOP_MS))
403
421
  return "busy";
404
422
  const { turn } = await app.request("turn/start", { threadId: current.id, input, clientUserMessageId });
423
+ if (turn.status === "inProgress")
424
+ this.planTurns.add(turn.id);
405
425
  if (this.ownLoaded.has(current.id))
406
426
  this.unattended.add(turn.id);
407
427
  return "in";
@@ -467,6 +487,7 @@ class CodexHarness {
467
487
  // Codex's session is heard through its server, whatever the chat: nothing to put in or take out.
468
488
  }
469
489
  async close() {
490
+ this.planUsage?.disconnect();
470
491
  this.app?.close();
471
492
  this.app = null;
472
493
  }
package/dist/gavel.js CHANGED
@@ -9,8 +9,8 @@ import { createHash, randomUUID } from "node:crypto";
9
9
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
10
10
  import { homedir, hostname } from "node:os";
11
11
  import { basename, dirname, extname, join } from "node:path";
12
- import { bridgeStatus, harnessFor, holdBridge, hookEvent, lastingCommand, startBridge, stopBridge } from "./bridge/background.js";
13
- import { claudeBridgeHooks, gavelPluginOn } from "./bridge/claude-live.js";
12
+ import { bridgeStatus, bridgeStatusLine, harnessFor, holdBridge, hookEvent, lastingCommand, startBridge, stopBridge } from "./bridge/background.js";
13
+ import { claudeBridgeHooks, claudeHeld, gavelPluginOn } from "./bridge/claude-live.js";
14
14
  import { codexBridgeHooks } from "./bridge/codex.js";
15
15
  import { claudeSetups } from "./bridge/setup.js";
16
16
  import { BRIDGE_HARNESSES, runBridge } from "./bridge/bridge.js";
@@ -47,6 +47,9 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
47
47
  gavel bridge event <name> [--harness claude-code|codex] [--server <name>]
48
48
  a hook's event for this folder's bridge, its input on stdin
49
49
  (run by the hook, not by hand); prints nothing, exits 0
50
+ gavel bridge status-line Claude Code's status line in a folder with the bridge's
51
+ hooks (run by Claude Code, not by hand): your plan's use to
52
+ the bridge, then your own status line, as it prints it
50
53
  gavel bridge service install|remove|status [--harness claude-code|codex] [--server <name>]
51
54
  the bridge for this folder kept running by the system (a
52
55
  LaunchAgent on a Mac, systemd on Linux), so a closed
@@ -1081,6 +1084,10 @@ export function toRequest(argv) {
1081
1084
  throw new UsageError(`"${name}" isn't a hook's event`);
1082
1085
  return { bridgeBackground: { action, harness, server: f.server, name } };
1083
1086
  }
1087
+ if (action === "status-line") {
1088
+ upTo(1);
1089
+ return { bridgeBackground: { action, harness: "claude-code", server: f.server } };
1090
+ }
1084
1091
  if (action === "service" || action === "hooks") {
1085
1092
  upTo(2);
1086
1093
  const what = need(p[1], "install, remove or status");
@@ -1706,6 +1713,8 @@ async function background(run) {
1706
1713
  const cwd = process.cwd();
1707
1714
  const env = process.env;
1708
1715
  const print = (answer) => console.log(JSON.stringify(answer, null, 2));
1716
+ if (run.action === "status-line")
1717
+ return bridgeStatusLine({ home, cwd, env });
1709
1718
  if (run.action === "hooks") {
1710
1719
  // A folder whose harness can't be told is Claude Code's to answer, refusal and all.
1711
1720
  let which = run.harness ?? "claude-code";
@@ -1736,17 +1745,26 @@ async function background(run) {
1736
1745
  return hookEvent({ home, cwd, harness, server: run.server, name: run.name, env });
1737
1746
  case "start": {
1738
1747
  const started = await startBridge({ home, cwd, harness, server: run.server, untilClosed: false, env });
1739
- print(started.bridge === "failed" ? { ...started, reason: lastLine(started.log) } : started);
1740
- return started.bridge === "failed" ? 1 : 0;
1748
+ if (started.bridge !== "failed") {
1749
+ print(started);
1750
+ return 0;
1751
+ }
1752
+ const reason = lastLine(started.log);
1753
+ print({ ...started, reason });
1754
+ // On stderr too, so a failed start always says why (W-244).
1755
+ console.error(`gavel bridge: it didn't start${reason ? `: ${reason}` : ""} (its log: ${started.log}).`);
1756
+ return 1;
1741
1757
  }
1742
1758
  case "stop": {
1743
1759
  const stopped = await stopBridge({ home, cwd, harness });
1744
1760
  print(stopped);
1745
1761
  return stopped.bridge === "still running" ? 1 : 0;
1746
1762
  }
1747
- case "status":
1748
- print(bridgeStatus({ home, cwd, harness }));
1763
+ case "status": {
1764
+ const held = harness === "claude-code" ? claudeHeld(cwd, home, env) : null;
1765
+ print({ ...bridgeStatus({ home, cwd, harness }), ...(held ? { held } : {}) });
1749
1766
  return 0;
1767
+ }
1750
1768
  case "service": {
1751
1769
  const answer = bridgeService(run.service, { home, cwd, harness, server: run.server, env });
1752
1770
  print(answer);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.24",
3
+ "version": "0.1.26",
4
4
  "description": "The gavel command: an agent's Gavel from a shell (pair, ask, wait, watch and the rest)",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://getgavel.ai/agents",