@getgavel/cli 0.1.26 → 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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gavel",
3
- "version": "0.1.26",
3
+ "version": "0.1.27",
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" },
@@ -1,10 +1,10 @@
1
1
  import { execFileSync, spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
- import { chmodSync, closeSync, copyFileSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { chmodSync, closeSync, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { connect, createServer } from "node:net";
5
5
  import { tmpdir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
- import { statusLineUsage } from "./claude-plan.js";
7
+ import { claudeAccount, statusLineUsage } from "./claude-plan.js";
8
8
  import { claudeSetups, codexSetups } from "./setup.js";
9
9
  // How long a bridge a hook started stays after its folder's last session ends: long enough for a
10
10
  // /clear, a restart or a resume, never all night.
@@ -30,12 +30,14 @@ export function bridgeKey(cwd, harness) {
30
30
  // zero (Linux's 108), and past it listen fails (W-244).
31
31
  export const MAX_SOCKET_PATH = 103;
32
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.
33
+ // private folder of the user's own under their runtime folder (Linux's XDG_RUNTIME_DIR, theirs alone)
34
+ // or the system's temporary folder, which the lock names.
34
35
  function socketPath(dir, key) {
35
36
  const beside = join(dir, `${key}.sock`);
36
37
  if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH)
37
38
  return beside;
38
- return join(tmpdir(), `gavel-bridge-${process.getuid?.() ?? "user"}`, `${key}.sock`);
39
+ const runtime = process.env.XDG_RUNTIME_DIR?.startsWith("/") ? process.env.XDG_RUNTIME_DIR : tmpdir();
40
+ return join(runtime, `gavel-bridge-${process.getuid?.() ?? "user"}`, `${key}.sock`);
39
41
  }
40
42
  export function bridgePaths(home, cwd, harness) {
41
43
  const dir = bridgeDir(home);
@@ -49,6 +51,17 @@ function privateDir(dir) {
49
51
  mkdirSync(dir, { recursive: true, mode: 0o700 });
50
52
  chmodSync(dir, 0o700);
51
53
  }
54
+ // The socket's folder outside ~/.gavel: the socket carries each session's messaging token, and a
55
+ // shared temporary folder lets anyone make that name first. So it must be a real folder (never a
56
+ // link), the user's own, with nothing for group or others; otherwise the bridge refuses.
57
+ function ownSocketDir(dir) {
58
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
59
+ const st = lstatSync(dir);
60
+ const uid = process.getuid?.();
61
+ if (st.isSymbolicLink() || !st.isDirectory() || (uid !== undefined && st.uid !== uid) || (st.mode & 0o077) !== 0) {
62
+ throw new BridgeSocketError(`the bridge's socket folder (${dir}) isn't yours alone: remove it, or set TMPDIR to a folder of your own`);
63
+ }
64
+ }
52
65
  // A process is the bridge its lock names only while it's alive and still a gavel bridge: a pid the
53
66
  // system gave to something else since doesn't count.
54
67
  function isBridge(pid) {
@@ -104,7 +117,7 @@ export function holdBridge(opts) {
104
117
  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
118
  }
106
119
  if (dirname(paths.socket) !== paths.dir)
107
- privateDir(dirname(paths.socket));
120
+ ownSocketDir(dirname(paths.socket));
108
121
  const open = new Set();
109
122
  let lastClosed = null;
110
123
  const lock = {
@@ -282,6 +295,8 @@ export async function startBridge(opts) {
282
295
  return { bridge: "running", pid: live.pid, log: live.log };
283
296
  privateDir(paths.dir);
284
297
  const log = openSync(paths.log, "a", 0o600);
298
+ // The mode applies only to a new file: a log an older bridge made stays as it was.
299
+ chmodSync(paths.log, 0o600);
285
300
  const [command, ...args] = [process.execPath, ...process.execArgv, process.argv[1]];
286
301
  const env = { ...opts.env, GAVEL_BRIDGE_UNTIL_CLOSED: opts.untilClosed ? "1" : "" };
287
302
  // A session's own inbox stays with the session's hooks, never in a bridge that outlives it.
@@ -426,15 +441,19 @@ export async function hookEvent(opts) {
426
441
  export const STATUS_LINE_EVENT = "StatusLine";
427
442
  const OWN_LINE_MS = 10_000;
428
443
  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) {
444
+ export function ownStatusLineEntry(home, project, env) {
432
445
  const config = env.CLAUDE_CONFIG_DIR || join(home, ".claude");
433
446
  for (const file of [join(project, ".claude", "settings.json"), join(config, "settings.json")]) {
434
447
  try {
435
448
  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;
449
+ if (line?.type === "command" && typeof line.command === "string" && line.command.trim() && !isBridgeStatusLine(line.command)) {
450
+ const own = { command: line.command };
451
+ if (typeof line.padding === "number" && Number.isFinite(line.padding))
452
+ own.padding = line.padding;
453
+ if (typeof line.refreshInterval === "number" && Number.isFinite(line.refreshInterval))
454
+ own.refreshInterval = line.refreshInterval;
455
+ return own;
456
+ }
438
457
  }
439
458
  catch {
440
459
  // none there
@@ -442,6 +461,7 @@ export function ownStatusLine(home, project, env) {
442
461
  }
443
462
  return null;
444
463
  }
464
+ export const ownStatusLine = (home, project, env) => ownStatusLineEntry(home, project, env)?.command ?? null;
445
465
  export const isBridgeStatusLine = (command) => /\bbridge status-line\b/.test(command);
446
466
  function runOwn(command, input, cwd, env) {
447
467
  return new Promise((resolve) => {
@@ -487,8 +507,10 @@ export async function bridgeStatusLine(opts) {
487
507
  const handed = (async () => {
488
508
  try {
489
509
  const live = usage ? runningBridge(opts.home, project, "claude-code") : null;
510
+ // The account is read here, with the session's own environment (its CLAUDE_CONFIG_DIR), not
511
+ // the bridge's: handed over as its hash alone, beside the figures.
490
512
  if (live)
491
- await send(live.socket, `${JSON.stringify({ event: STATUS_LINE_EVENT, input: usage, inbox: null, at: Date.now() })}\n`);
513
+ await send(live.socket, `${JSON.stringify({ event: STATUS_LINE_EVENT, input: { ...usage, account: claudeAccount(opts.home, opts.env) }, inbox: null, at: Date.now() })}\n`);
492
514
  }
493
515
  catch {
494
516
  // never the status line's failure
@@ -4,7 +4,8 @@ import { tmpdir } from "node:os";
4
4
  import { basename, join } from "node:path";
5
5
  import { jsonText } from "../output.js";
6
6
  import { markChatOff, onHookEvent, STATUS_LINE_EVENT } from "./background.js";
7
- import { claudePlanReporter, planUsageOf } from "./claude-plan.js";
7
+ import { claudeDayReporter, DAYS_EVERY_MS } from "./claude-days.js";
8
+ import { accountOf, claudePlanReporter, planUsageOf } from "./claude-plan.js";
8
9
  import { claudeSessions } from "./claude-code.js";
9
10
  import { ClaudeCodeHarness } from "./claude-live.js";
10
11
  import { codexHarness, codexSessions } from "./codex.js";
@@ -71,6 +72,14 @@ async function whoAmI(api, setup) {
71
72
  throw new BridgeError(`Gavel answered ${res.status} to who this agent is: try again in a moment.`);
72
73
  return (await res.json());
73
74
  }
75
+ // The `agent.fresh` of /v1/me?fresh=true, rebuilt from its known fields; null while one session goes on.
76
+ function freshOf(body) {
77
+ const f = body?.agent?.fresh;
78
+ if (!f || (f.per !== "batch" && f.per !== "item") || typeof f.brief !== "string" || !f.brief.trim())
79
+ return null;
80
+ const model = typeof f.model === "string" && /^[A-Za-z0-9][\w.:[\]-]{0,79}$/.test(f.model) ? f.model : null;
81
+ return { per: f.per, brief: f.brief, model, item: typeof f.item === "string" && /^[A-Z]{1,6}-\d{1,9}$/.test(f.item) ? f.item : null };
82
+ }
74
83
  const clock = () => new Date().toTimeString().slice(0, 5);
75
84
  const pause = (ms) => new Promise((r) => setTimeout(r, ms));
76
85
  const backoff = (failures) => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
@@ -390,17 +399,28 @@ async function harnessBridge(h, harness, setup, ctx) {
390
399
  // Wakes: what waits for the agent in Gavel (an answer to what it waits on, a message, a request),
391
400
  // as Gavel's one line into the session once it's idle. The person's own messages it puts in itself.
392
401
  const watchId = randomUUID();
402
+ const planProvider = harness === "codex" ? "openai" : "anthropic";
393
403
  let watching = true;
394
404
  let pending = [];
395
405
  let waking = false;
406
+ // Whether something still waits, as /v1/me's header says, and (for a harness that starts fresh
407
+ // sessions) how this agent's start, from the same read.
396
408
  const stillWaiting = async () => {
397
409
  try {
398
- const res = await call(api, "GET", "/v1/me", undefined, { "x-gavel-waiting": "1" });
399
- void res.body?.cancel();
400
- return !res.ok || res.headers.get("x-gavel-waiting") !== null;
410
+ const res = await call(api, "GET", h.takesFresh ? "/v1/me?fresh=true" : "/v1/me", undefined, { "x-gavel-waiting": "1" });
411
+ if (!res.ok) {
412
+ void res.body?.cancel();
413
+ return { waiting: true, fresh: null };
414
+ }
415
+ const waiting = res.headers.get("x-gavel-waiting") !== null;
416
+ if (!h.takesFresh || !waiting) {
417
+ void res.body?.cancel();
418
+ return { waiting, fresh: null };
419
+ }
420
+ return { waiting, fresh: freshOf(await res.json().catch(() => null)) };
401
421
  }
402
422
  catch {
403
- return true;
423
+ return { waiting: true, fresh: null };
404
424
  }
405
425
  };
406
426
  const tryWake = async () => {
@@ -408,12 +428,13 @@ async function harnessBridge(h, harness, setup, ctx) {
408
428
  return;
409
429
  waking = true;
410
430
  try {
411
- if (!(await stillWaiting())) {
431
+ const still = await stillWaiting();
432
+ if (!still.waiting) {
412
433
  pending = [];
413
434
  return;
414
435
  }
415
436
  const line = wakeLineOf(pending);
416
- if (await h.wake(line)) {
437
+ if (await h.wake(line, still.fresh)) {
417
438
  say(`Woke ${h.name} for what waits in Gavel: ${line}`);
418
439
  pending = [];
419
440
  }
@@ -431,7 +452,7 @@ async function harnessBridge(h, harness, setup, ctx) {
431
452
  while (watching && !stopping) {
432
453
  let res;
433
454
  try {
434
- res = await call(api, "GET", `/v1/inbox/watch?watch=${watchId}&timeout=50&kinds=health,claim,work,drift${start ? "&start=true" : ""}`);
455
+ res = await call(api, "GET", `/v1/inbox/watch?watch=${watchId}&timeout=50&kinds=health,claim,work,drift&planProvider=${planProvider}${start ? "&start=true" : ""}`);
435
456
  }
436
457
  catch {
437
458
  failures++;
@@ -464,17 +485,24 @@ async function harnessBridge(h, harness, setup, ctx) {
464
485
  };
465
486
  const wakeTimer = setInterval(() => void tryWake(), WAKE_AGAIN_MS);
466
487
  // 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;
488
+ const plan = harness === "claude-code" ? claudePlanReporter({ home: ctx.home, request: (method, path, body) => call(api, method, path, body), say }) : null;
489
+ // Its tokens for each day, summed from the agent's transcripts here (W-247, for the plan's share).
490
+ const days = harness === "claude-code" && ctx.planReporter ? claudeDayReporter({ home: ctx.home, cwd: ctx.cwd, env: ctx.env, reporter: ctx.planReporter, say }) : null;
491
+ const daysTimer = days ? setInterval(() => days.poke(), DAYS_EVERY_MS) : null;
492
+ days?.poke();
468
493
  // The harness's own hooks, through `gavel bridge event` (background.ts), and the status line's.
469
494
  const offHooks = onHookEvent((event) => {
470
495
  if (event.event !== STATUS_LINE_EVENT)
471
496
  return h.hook?.(event.event, event);
472
497
  const usage = planUsageOf(event.input);
473
498
  if (plan && usage)
474
- plan.observe(usage);
499
+ plan.observe(usage, accountOf(event.input));
500
+ days?.poke();
475
501
  });
476
502
  h.listen({
477
503
  live: (event) => {
504
+ if (event.event === "end")
505
+ days?.poke();
478
506
  if (!on || !liveRoute)
479
507
  return;
480
508
  outgoing.push(event);
@@ -502,6 +530,9 @@ async function harnessBridge(h, harness, setup, ctx) {
502
530
  clearTimeout(soon);
503
531
  offHooks();
504
532
  plan?.close();
533
+ days?.close();
534
+ if (daysTimer)
535
+ clearInterval(daysTimer);
505
536
  };
506
537
  const stop = (said = "Stopped.") => {
507
538
  if (stopping)
@@ -3,7 +3,7 @@ import { join } from "node:path";
3
3
  import { cut } from "./words.js";
4
4
  // Claude Code keeps each session as <its folder>/projects/<project>/<session id>.jsonl, the project
5
5
  // its working folder's path with every character but a letter or a digit as a dash.
6
- export function claudeSessions(cwd, home, env) {
6
+ export function claudeProjectDirs(cwd, home, env) {
7
7
  const projects = join(env.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "projects");
8
8
  const real = (path) => {
9
9
  try {
@@ -16,11 +16,11 @@ export function claudeSessions(cwd, home, env) {
16
16
  const paths = new Set([cwd, real(cwd)]);
17
17
  if (env.PWD && real(env.PWD) === real(cwd))
18
18
  paths.add(env.PWD);
19
+ return [...new Set([...paths].map((path) => join(projects, path.replace(/[^A-Za-z0-9]/g, "-"))))].filter((dir) => existsSync(dir));
20
+ }
21
+ export function claudeSessions(cwd, home, env) {
19
22
  const sessions = new Map();
20
- for (const path of paths) {
21
- const dir = join(projects, path.replace(/[^A-Za-z0-9]/g, "-"));
22
- if (!existsSync(dir))
23
- continue;
23
+ for (const dir of claudeProjectDirs(cwd, home, env)) {
24
24
  for (const name of readdirSync(dir)) {
25
25
  const id = /^([0-9a-f-]{36})\.jsonl$/i.exec(name)?.[1];
26
26
  if (!id)
@@ -0,0 +1,236 @@
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
+ // Claude Code's tokens for each day (W-247, for the plan's share in W-248): the four counts the
7
+ // agent's own sessions in this folder used, summed here from their transcripts, once for each
8
+ // answer (a message id: an answer written in several parts repeats its usage) and by the laptop's
9
+ // own date. Only the sums, each with its date, go to Gavel (D-894); never a line, an id or a path.
10
+ const KEYS = ["inputTokens", "cacheWriteTokens", "cacheReadTokens", "outputTokens"];
11
+ const USAGE = { inputTokens: "input_tokens", cacheWriteTokens: "cache_creation_input_tokens", cacheReadTokens: "cache_read_input_tokens", outputTokens: "output_tokens" };
12
+ const DAY_MS = 86_400_000;
13
+ const CHUNK = 8 * 1024 * 1024;
14
+ export const DAYS_EVERY_MS = 60_000;
15
+ const pad = (n) => String(n).padStart(2, "0");
16
+ export const localDate = (ms) => {
17
+ const d = new Date(ms);
18
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
19
+ };
20
+ const startOfDay = (ms) => {
21
+ const d = new Date(ms);
22
+ return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
23
+ };
24
+ const whole = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : 0);
25
+ // The transcripts that can hold the last two days' answers: each session's file and its sub-agents'.
26
+ function transcripts(dirs, since) {
27
+ const files = [];
28
+ const add = (file) => {
29
+ try {
30
+ if (statSync(file).mtimeMs >= since)
31
+ files.push(file);
32
+ }
33
+ catch {
34
+ // gone
35
+ }
36
+ };
37
+ for (const dir of dirs) {
38
+ for (const name of readdirSync(dir)) {
39
+ if (name.endsWith(".jsonl"))
40
+ add(join(dir, name));
41
+ else {
42
+ const sub = join(dir, name, "subagents");
43
+ if (existsSync(sub))
44
+ for (const s of readdirSync(sub))
45
+ if (s.endsWith(".jsonl"))
46
+ add(join(sub, s));
47
+ }
48
+ }
49
+ }
50
+ return files;
51
+ }
52
+ // The sums by date, read on from where each file was last read, whole lines only.
53
+ export class DaySums {
54
+ dirs;
55
+ now;
56
+ offsets = new Map();
57
+ answers = new Map();
58
+ changed = new Set();
59
+ constructor(dirs, now = Date.now) {
60
+ this.dirs = dirs;
61
+ this.now = now;
62
+ }
63
+ scan() {
64
+ const today = startOfDay(this.now());
65
+ for (const file of transcripts(this.dirs(), today - DAY_MS))
66
+ this.read(file, today - DAY_MS);
67
+ }
68
+ read(file, from) {
69
+ let fd = null;
70
+ try {
71
+ fd = openSync(file, "r");
72
+ for (;;) {
73
+ const at = this.offsets.get(file) ?? 0;
74
+ const buffer = Buffer.alloc(CHUNK);
75
+ const n = readSync(fd, buffer, 0, CHUNK, at);
76
+ if (!n)
77
+ return;
78
+ const end = buffer.subarray(0, n).lastIndexOf(10);
79
+ if (end < 0) {
80
+ if (n < CHUNK)
81
+ return;
82
+ this.offsets.set(file, at + n);
83
+ continue;
84
+ }
85
+ for (const line of buffer.subarray(0, end).toString("utf8").split("\n"))
86
+ this.take(line, from);
87
+ this.offsets.set(file, at + end + 1);
88
+ }
89
+ }
90
+ catch {
91
+ // read again at the next scan
92
+ }
93
+ finally {
94
+ if (fd !== null)
95
+ closeSync(fd);
96
+ }
97
+ }
98
+ take(line, from) {
99
+ if (!line.includes('"usage"'))
100
+ return;
101
+ try {
102
+ const l = JSON.parse(line);
103
+ const id = l.message?.id;
104
+ const usage = l.message?.usage;
105
+ const at = typeof l.timestamp === "string" ? Date.parse(l.timestamp) : Number.NaN;
106
+ if (l.type !== "assistant" || typeof id !== "string" || !usage || !Number.isFinite(at) || at < from)
107
+ return;
108
+ const date = localDate(at);
109
+ let day = this.answers.get(date);
110
+ if (!day)
111
+ this.answers.set(date, (day = new Map()));
112
+ const before = day.get(id);
113
+ const next = { ...(before ?? { inputTokens: 0, cacheWriteTokens: 0, cacheReadTokens: 0, outputTokens: 0 }) };
114
+ // A later part of one answer says at least what an earlier part did.
115
+ for (const key of KEYS)
116
+ next[key] = Math.max(next[key], whole(usage[USAGE[key]]));
117
+ if (before && KEYS.every((key) => before[key] === next[key]))
118
+ return;
119
+ day.set(id, next);
120
+ this.changed.add(date);
121
+ }
122
+ catch {
123
+ // not a line of answers
124
+ }
125
+ }
126
+ // The dates whose sums moved since they were last taken, each with its sums.
127
+ moved() {
128
+ const out = [];
129
+ for (const date of [...this.changed].sort()) {
130
+ const sum = { inputTokens: 0, cacheWriteTokens: 0, cacheReadTokens: 0, outputTokens: 0 };
131
+ for (const a of this.answers.get(date)?.values() ?? [])
132
+ for (const key of KEYS)
133
+ sum[key] += a[key];
134
+ out.push([date, sum]);
135
+ }
136
+ this.changed.clear();
137
+ return out;
138
+ }
139
+ // What was taken and wasn't sent goes round again.
140
+ again(dates) {
141
+ for (const d of dates)
142
+ this.changed.add(d);
143
+ }
144
+ forget() {
145
+ const keep = localDate(startOfDay(this.now()) - DAY_MS);
146
+ for (const date of [...this.answers.keys()])
147
+ if (date < keep)
148
+ this.answers.delete(date);
149
+ }
150
+ }
151
+ // This folder's own id for its sums, kept (mode 600) so the same one goes each time and a second
152
+ // folder's or machine's sums for the same day add up beside it, never over it.
153
+ function sourceId(home, cwd) {
154
+ const dir = join(home, ".gavel", "plan-accounts");
155
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
156
+ const path = join(dir, `source-claude-${createHash("sha256").update(cwd).digest("hex").slice(0, 16)}`);
157
+ try {
158
+ writeFileSync(path, randomUUID(), { mode: 0o600, flag: "wx" });
159
+ }
160
+ catch (err) {
161
+ if (err.code !== "EEXIST")
162
+ throw err;
163
+ }
164
+ return readFileSync(path, "utf8").trim();
165
+ }
166
+ // The bridge's reporter of the days' sums: each poke reads what the transcripts gained, and the
167
+ // sums that moved go to the plan the agent's link names, a minute apart at most, only while the
168
+ // Claude account that first reported the plan's windows is the one signed in.
169
+ export function claudeDayReporter(opts) {
170
+ const now = opts.now ?? Date.now;
171
+ const every = opts.everyMs ?? DAYS_EVERY_MS;
172
+ const sums = new DaySums(() => claudeProjectDirs(opts.cwd, opts.home, opts.env), now);
173
+ let timer = null;
174
+ let sentAt = -Infinity;
175
+ let sending = false;
176
+ let closed = false;
177
+ let said = "";
178
+ const sayOnce = (line) => {
179
+ if (line !== said)
180
+ opts.say(line);
181
+ said = line;
182
+ };
183
+ const send = async () => {
184
+ timer = null;
185
+ if (sending || closed)
186
+ return;
187
+ sending = true;
188
+ sentAt = now();
189
+ let pending = [];
190
+ try {
191
+ sums.scan();
192
+ pending = sums.moved();
193
+ sums.forget();
194
+ if (!pending.length)
195
+ return;
196
+ const planId = await opts.reporter.linked();
197
+ if (!planId)
198
+ return void sums.again(pending.map(([d]) => d));
199
+ const pin = accountPin(opts.home, planId, claudeAccount(opts.home, opts.env));
200
+ if (pin !== "match") {
201
+ sums.again(pending.map(([d]) => d));
202
+ return sayOnce(pin === "unpinned"
203
+ ? "Claude Code's daily tokens wait for its plan's first report from the status line."
204
+ : "Claude Code's daily tokens aren't sent: another Claude account is signed in than the one this plan was first read from.");
205
+ }
206
+ const source = sourceId(opts.home, opts.cwd);
207
+ while (pending.length) {
208
+ const [date, counts] = pending[0];
209
+ await opts.reporter.day({ planId, date, sourceId: source, ...counts });
210
+ pending.shift();
211
+ }
212
+ sayOnce("Claude Code's daily tokens go to Gavel, for you alone.");
213
+ }
214
+ catch (err) {
215
+ sums.again(pending.map(([d]) => d));
216
+ sayOnce(`Claude Code's daily tokens aren't sent: ${err instanceof Error ? err.message : String(err)}; it tries again.`);
217
+ }
218
+ finally {
219
+ sending = false;
220
+ }
221
+ };
222
+ return {
223
+ // Something may have been written: look, within a minute of the last send.
224
+ poke() {
225
+ if (closed || timer || sending)
226
+ return;
227
+ timer = setTimeout(() => void send(), Math.max(0, sentAt + every - now()));
228
+ timer.unref?.();
229
+ },
230
+ close() {
231
+ closed = true;
232
+ if (timer)
233
+ clearTimeout(timer);
234
+ },
235
+ };
236
+ }
@@ -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
@@ -682,9 +694,19 @@ 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) {
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: 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" } })];
688
710
  return new Promise((resolve) => {
689
711
  const child = spawn("claude", args, { cwd: this.ctx.cwd, env: this.ctx.env, stdio: ["pipe", "pipe", "pipe"] });
690
712
  let out = "";
@@ -698,20 +720,16 @@ export class ClaudeCodeHarness {
698
720
  const quit = setTimeout(() => child.kill(), 60_000);
699
721
  child.stdout.on("data", (d) => (out += d));
700
722
  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}` }));
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}` }));
702
724
  child.on("close", (code) => {
703
725
  clearTimeout(quit);
704
726
  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
- }
727
+ if (code === 0 && short)
728
+ settle({ short: short.slice(0, 8) });
710
729
  else {
711
730
  const first = (t) => t.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
712
731
  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 });
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) });
715
733
  }
716
734
  this.listener?.changed();
717
735
  });
@@ -759,10 +777,50 @@ export class ClaudeCodeHarness {
759
777
  return sent ? "stopped" : "over";
760
778
  }
761
779
  // Gavel's one-line wake (D-1103), into an open session: mid-turn or as a turn of its own.
762
- async wake(line) {
780
+ async wake(line, fresh) {
781
+ if (fresh)
782
+ return this.wakeFresh(line, fresh);
763
783
  const open = this.current();
764
784
  return open?.inbox ? inboxSend(open.inbox, line, { priority: "next", bypass: this.bypasses(open) }) : false;
765
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
+ }
766
824
  listen(l) {
767
825
  this.listener = l;
768
826
  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() {
package/dist/gavel.js CHANGED
@@ -86,7 +86,10 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
86
86
  answer an Ask someone
87
87
  gavel act <D-12> (<note> | --note <words>)
88
88
  what you did with the answer
89
- gavel inbox what's waiting on you
89
+ gavel inbox [<section>] [--offset <n>] [--limit <n>]
90
+ what's waiting on you, each list's first 10 (counts has
91
+ every total); with a section (requests, decisions, …),
92
+ that list's next page
90
93
  gavel status (<title> | --text <words>) [--description <words>] [--folders <a,b>]
91
94
  [--state working|blocked|idle] [--issue <MA-482>] [--waiting-on <email or agent>] [--item <W-12>]
92
95
  what you're doing now: a title of two to four words in
@@ -219,7 +222,8 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
219
222
  [--snooze-until <time>|none]
220
223
  gavel set-my-reports [--weekly-report true|false] [--slack-messages true|false]
221
224
  gavel set-agent-runtime <agent id> [--model <id>|cursor-default|none] [--effort low|medium|high|xhigh|max|none]
222
- [--context 300k|1m|none] a Cursor agent's model, effort and context (none: the router's)
225
+ [--context 300k|1m|none] [--sessions item|batch|continuous|none]
226
+ a Cursor agent's model, effort, context and sessions (none: the router's)
223
227
  gavel set-area-runtime <area id> [--model <id>|cursor-default|none] [--effort <effort>|none] [--context 300k|1m|none]
224
228
  gavel set-job-runtime work|wake|chat|night [--model <id>|cursor-default|none] [--effort <effort>|none] [--context 300k|1m|none]
225
229
  gavel my-notifications [--limit <n>] what went out to them, and how many are unread
@@ -321,7 +325,7 @@ const FLAGS = {
321
325
  upload: ["type"],
322
326
  answer: ["response"],
323
327
  act: ["note"],
324
- inbox: [],
328
+ inbox: ["offset", "limit"],
325
329
  status: ["text", "description", "folders", "state", "issue", "waiting-on", "item"],
326
330
  "claim-folders": ["mode", "item"],
327
331
  work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "open", "waits-on", "program", "area", "why", "key"],
@@ -363,7 +367,7 @@ const FLAGS = {
363
367
  "set-my-day": ["timezone", "day-start", "day-end", "morning", "later-every"],
364
368
  "set-my-alerts": ["on-call", "sounds", "sound", "later-like-now", "muted", "workspace-sound", "snooze-until"],
365
369
  "set-my-reports": ["weekly-report", "slack-messages"],
366
- "set-agent-runtime": ["model", "effort", "context"],
370
+ "set-agent-runtime": ["model", "effort", "context", "sessions"],
367
371
  "set-area-runtime": ["model", "effort", "context"],
368
372
  "set-job-runtime": ["model", "effort", "context"],
369
373
  "my-notifications": ["limit"],
@@ -729,9 +733,9 @@ function personRequest(command, p, f, options) {
729
733
  case "set-area-runtime":
730
734
  case "set-job-runtime": {
731
735
  upTo(1);
732
- const body = compact({ model: orNone("model"), effort: orNone("effort"), context: orNone("context") });
736
+ const body = compact({ model: orNone("model"), effort: orNone("effort"), context: orNone("context"), ...(command === "set-agent-runtime" ? { sessions: orNone("sessions") } : {}) });
733
737
  if (!Object.keys(body).length)
734
- throw new UsageError("give --model, --effort or --context: none sets one back to the router's pick");
738
+ throw new UsageError(`give --model, --effort${command === "set-agent-runtime" ? ", --context or --sessions" : " or --context"}: none sets one back to the router's pick`);
735
739
  if (command === "set-agent-runtime")
736
740
  return asThem("PUT", `/v1/agents/${encodeURIComponent(need(p[0], "the agent's id"))}/runtime`, body);
737
741
  if (command === "set-area-runtime")
@@ -1166,9 +1170,13 @@ export function toRequest(argv) {
1166
1170
  return { method: "POST", path: `/v1/requests/${encodeURIComponent(need(p[0], "the request id"))}/answer`, body: { response: readText(words("response", p.slice(1), "the response")) } };
1167
1171
  case "act":
1168
1172
  return { method: "POST", path: `/v1/decisions/${ref(p[0])}/act`, body: { note: readText(words("note", p.slice(1), "the note")) } };
1169
- case "inbox":
1170
- upTo(0);
1171
- return { method: "GET", path: "/v1/inbox" };
1173
+ case "inbox": {
1174
+ upTo(1);
1175
+ if (!p[0] && (f.offset !== undefined || f.limit !== undefined))
1176
+ throw new UsageError("--offset and --limit go with a section: gavel inbox requests --offset 10");
1177
+ const query = new URLSearchParams(compact({ section: p[0], offset: f.offset, limit: f.limit }));
1178
+ return { method: "GET", path: `/v1/inbox${query.size ? `?${query}` : ""}` };
1179
+ }
1172
1180
  case "chat": {
1173
1181
  if (f.text !== undefined && p.length)
1174
1182
  throw new UsageError("give your answer once: as words or as --text");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.26",
3
+ "version": "0.1.27",
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",