@getgavel/cli 0.1.26 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gavel",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
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.
@@ -403,13 +418,15 @@ export async function hookEvent(opts) {
403
418
  input,
404
419
  inbox: socket ? { socket, token: opts.env.CLAUDE_CODE_MESSAGING_TOKEN || null } : null,
405
420
  at: Date.now(),
421
+ ...(opts.env.GAVEL_PLAN_PROFILE ? { planId: opts.env.GAVEL_PLAN_PROFILE } : {}),
406
422
  };
407
- let live = runningBridge(opts.home, cwd, opts.harness);
423
+ const ownerHarness = opts.env.GAVEL_BRIDGE_OWNER_HARNESS === "codex" ? "codex" : opts.harness;
424
+ let live = runningBridge(opts.home, cwd, ownerHarness);
408
425
  // Hooks a plugin or the user's settings give every folder start a bridge only where this
409
426
  // harness has a Gavel agent set up.
410
427
  const setUp = (opts.harness === "codex" ? codexSetups(cwd, opts.home, opts.env) : claudeSetups(cwd, opts.home)).some((s) => s.where.endsWith("this folder"));
411
428
  const looksAgain = opts.name === "SessionStart" || !offRecently(opts.home, cwd, opts.harness);
412
- if (!live && setUp && STARTS.has(opts.name) && looksAgain) {
429
+ if (!live && !opts.env.GAVEL_PLAN_PROFILE && setUp && STARTS.has(opts.name) && looksAgain) {
413
430
  const started = await startBridge({ home: opts.home, cwd, harness: opts.harness, server: opts.server, untilClosed: true, env: opts.env });
414
431
  if (started.bridge !== "failed")
415
432
  live = runningBridge(opts.home, cwd, opts.harness);
@@ -426,15 +443,19 @@ export async function hookEvent(opts) {
426
443
  export const STATUS_LINE_EVENT = "StatusLine";
427
444
  const OWN_LINE_MS = 10_000;
428
445
  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) {
446
+ export function ownStatusLineEntry(home, project, env) {
432
447
  const config = env.CLAUDE_CONFIG_DIR || join(home, ".claude");
433
448
  for (const file of [join(project, ".claude", "settings.json"), join(config, "settings.json")]) {
434
449
  try {
435
450
  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;
451
+ if (line?.type === "command" && typeof line.command === "string" && line.command.trim() && !isBridgeStatusLine(line.command)) {
452
+ const own = { command: line.command };
453
+ if (typeof line.padding === "number" && Number.isFinite(line.padding))
454
+ own.padding = line.padding;
455
+ if (typeof line.refreshInterval === "number" && Number.isFinite(line.refreshInterval))
456
+ own.refreshInterval = line.refreshInterval;
457
+ return own;
458
+ }
438
459
  }
439
460
  catch {
440
461
  // none there
@@ -442,6 +463,7 @@ export function ownStatusLine(home, project, env) {
442
463
  }
443
464
  return null;
444
465
  }
466
+ export const ownStatusLine = (home, project, env) => ownStatusLineEntry(home, project, env)?.command ?? null;
445
467
  export const isBridgeStatusLine = (command) => /\bbridge status-line\b/.test(command);
446
468
  function runOwn(command, input, cwd, env) {
447
469
  return new Promise((resolve) => {
@@ -486,9 +508,11 @@ export async function bridgeStatusLine(opts) {
486
508
  const usage = statusLineUsage(input);
487
509
  const handed = (async () => {
488
510
  try {
489
- const live = usage ? runningBridge(opts.home, project, "claude-code") : null;
511
+ const live = usage ? runningBridge(opts.home, project, opts.env.GAVEL_BRIDGE_OWNER_HARNESS === "codex" ? "codex" : "claude-code") : null;
512
+ // The account is read here, with the session's own environment (its CLAUDE_CONFIG_DIR), not
513
+ // the bridge's: handed over as its hash alone, beside the figures.
490
514
  if (live)
491
- await send(live.socket, `${JSON.stringify({ event: STATUS_LINE_EVENT, input: usage, inbox: null, at: Date.now() })}\n`);
515
+ await send(live.socket, `${JSON.stringify({ event: STATUS_LINE_EVENT, input: { ...usage, ...(opts.env.GAVEL_PLAN_PROFILE ? { planId: opts.env.GAVEL_PLAN_PROFILE } : { account: claudeAccount(opts.home, opts.env) }) }, inbox: null, at: Date.now() })}\n`);
492
516
  }
493
517
  catch {
494
518
  // never the status line's failure
@@ -4,10 +4,12 @@ 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, usageBody } 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";
12
+ import { planEnvironment, planIdPattern, planMachine, rememberPlanSession } from "./plan-profiles.js";
11
13
  import { apiFor, claudeSetups, codexSetups } from "./setup.js";
12
14
  // `gavel bridge` (D-905): run by a person on their laptop, in the folder where their agent works
13
15
  // (Claude Code or Codex), beside it. It shows the newest session's words in the person's Gavel chat
@@ -71,6 +73,14 @@ async function whoAmI(api, setup) {
71
73
  throw new BridgeError(`Gavel answered ${res.status} to who this agent is: try again in a moment.`);
72
74
  return (await res.json());
73
75
  }
76
+ // The `agent.fresh` of /v1/me?fresh=true, rebuilt from its known fields; null while one session goes on.
77
+ function freshOf(body) {
78
+ const f = body?.agent?.fresh;
79
+ if (!f || (f.per !== "batch" && f.per !== "item") || typeof f.brief !== "string" || !f.brief.trim())
80
+ return null;
81
+ const model = typeof f.model === "string" && /^[A-Za-z0-9][\w.:[\]-]{0,79}$/.test(f.model) ? f.model : null;
82
+ 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 };
83
+ }
74
84
  const clock = () => new Date().toTimeString().slice(0, 5);
75
85
  const pause = (ms) => new Promise((r) => setTimeout(r, ms));
76
86
  const backoff = (failures) => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
@@ -119,7 +129,9 @@ async function bridge(run, ctx) {
119
129
  day: (input) => report("PUT", "/v1/agents/me/plan/days", input),
120
130
  record: (input) => report("POST", "/v1/agents/me/plan/usage", input),
121
131
  };
122
- return harnessBridge(harnessOf(harness, { ...ctx, planReporter }), harness, setup, ctx);
132
+ const managed = !!planMachine(ctx.home);
133
+ const bridgeContext = { ...ctx, planReporter: managed ? undefined : planReporter };
134
+ return harnessBridge(harnessOf(harness, bridgeContext), harness, setup, bridgeContext);
123
135
  }
124
136
  const PICTURE_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp" };
125
137
  const PICTURE_MAX = 15 * 1024 * 1024;
@@ -169,8 +181,16 @@ async function answer(res) {
169
181
  // The Gavel side for a harness: the one peek (presence, the person's messages, Stop), their messages
170
182
  // put in beside it with their pictures, the session's words kept (the transcript) and shown as written
171
183
  // (live), its state, and wakes for what waits in Gavel.
172
- async function harnessBridge(h, harness, setup, ctx) {
184
+ async function harnessBridge(initial, harness, setup, ctx) {
173
185
  const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
186
+ let h = initial;
187
+ const machineId = planMachine(ctx.home);
188
+ let activeHarness = harness;
189
+ let activePlan = null;
190
+ let activeEnv = ctx.env;
191
+ let retryPlanAt = 0;
192
+ let lastManagedUsage = 0;
193
+ let lastManagedWindows = "";
174
194
  const me = await whoAmI(api, setup);
175
195
  if (h instanceof ClaudeCodeHarness)
176
196
  h.setPerson(me.person.name);
@@ -346,11 +366,22 @@ async function harnessBridge(h, harness, setup, ctx) {
346
366
  }
347
367
  return { paths, missed };
348
368
  };
369
+ let launchQueue = Promise.resolve();
370
+ const launch = (run) => {
371
+ const chosen = launchQueue.then(run);
372
+ launchQueue = chosen.then(() => undefined, () => undefined);
373
+ return chosen;
374
+ };
349
375
  const deliver = async (m) => {
350
376
  try {
351
377
  const { paths, missed } = await fetchPictures(m.images ?? []);
352
378
  urgentUntil = Date.now() + PUSH_URGENT_MS;
353
- const result = await h.deliver({ id: m.id, text: m.text, decision: m.decision, pictures: paths });
379
+ const result = await launch(async () => {
380
+ const route = await pick(null, "chat");
381
+ return route.allowed ? h.deliver({ id: m.id, text: m.text, decision: m.decision, pictures: paths }, route.fresh) : null;
382
+ });
383
+ if (!result)
384
+ return;
354
385
  if (result.outcome === "left") {
355
386
  if (!left.has(m.id))
356
387
  say(result.say);
@@ -390,30 +421,122 @@ async function harnessBridge(h, harness, setup, ctx) {
390
421
  // Wakes: what waits for the agent in Gavel (an answer to what it waits on, a message, a request),
391
422
  // as Gavel's one line into the session once it's idle. The person's own messages it puts in itself.
392
423
  const watchId = randomUUID();
424
+ const planProvider = harness === "codex" ? "openai" : "anthropic";
393
425
  let watching = true;
394
426
  let pending = [];
395
427
  let waking = false;
428
+ // Whether something still waits, as /v1/me's header says, and (for a harness that starts fresh
429
+ // sessions) how this agent's start, from the same read.
396
430
  const stillWaiting = async () => {
397
431
  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;
432
+ const res = await call(api, "GET", h.takesFresh ? "/v1/me?fresh=true" : "/v1/me", undefined, { "x-gavel-waiting": "1" });
433
+ if (!res.ok) {
434
+ void res.body?.cancel();
435
+ return { waiting: true, fresh: null };
436
+ }
437
+ const waiting = res.headers.get("x-gavel-waiting") !== null;
438
+ if (!h.takesFresh || !waiting) {
439
+ void res.body?.cancel();
440
+ return { waiting, fresh: null };
441
+ }
442
+ return { waiting, fresh: freshOf(await res.json().catch(() => null)) };
401
443
  }
402
444
  catch {
403
- return true;
445
+ return { waiting: true, fresh: null };
446
+ }
447
+ };
448
+ const busy = () => state === "working" || state === "waiting";
449
+ const pick = async (fresh, job = "wake") => {
450
+ if (!machineId || busy() || (!fresh && thread && state === "idle"))
451
+ return { allowed: true, fresh };
452
+ if (state === null)
453
+ await h.newest().catch(() => null);
454
+ if (busy())
455
+ return { allowed: true, fresh };
456
+ if (Date.now() < retryPlanAt)
457
+ return { allowed: false, fresh };
458
+ const res = await call(api, "POST", "/v1/agents/me/plan/pick", { machineId, harness: activeHarness, job });
459
+ if (res.status === 404)
460
+ return { allowed: true, fresh };
461
+ const route = res.ok ? await answer(res) : null;
462
+ if (route?.why === "unmanaged")
463
+ return { allowed: true, fresh };
464
+ if (route?.why === "wait") {
465
+ const reset = route.resetsAt ? Date.parse(route.resetsAt) : Number.NaN;
466
+ retryPlanAt = Number.isFinite(reset) ? Math.min(reset, Date.now() + 60_000) : Date.now() + 60_000;
467
+ const at = Number.isFinite(reset) ? new Date(reset).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : null;
468
+ const words = `Waiting for your ${activeHarness === "codex" ? "ChatGPT" : "Claude"} plans${at ? `, back at ${at}.` : ". Reset time unavailable."}`;
469
+ if (words !== trouble)
470
+ void note(words);
471
+ complain(words);
472
+ return { allowed: false, fresh };
473
+ }
474
+ const selected = route?.planId;
475
+ const nextHarness = route?.harness;
476
+ if (!selected || !planIdPattern.test(selected) || (nextHarness !== "codex" && nextHarness !== "claude-code")) {
477
+ retryPlanAt = Date.now() + 30_000;
478
+ complain("No signed-in plan is available for a fresh session on this machine.");
479
+ return { allowed: false, fresh };
480
+ }
481
+ const env = planEnvironment(ctx, selected, nextHarness);
482
+ if (!env) {
483
+ retryPlanAt = Date.now() + 30_000;
484
+ complain("Gavel selected a plan whose local profile is missing. Run gavel plans sign-in for that plan.");
485
+ return { allowed: false, fresh };
486
+ }
487
+ if (activePlan !== selected || activeHarness !== nextHarness) {
488
+ const previous = h;
489
+ env.GAVEL_BRIDGE_OWNER_HARNESS = harness;
490
+ activeHarness = nextHarness;
491
+ activePlan = selected;
492
+ activeEnv = env;
493
+ lastManagedUsage = 0;
494
+ lastManagedWindows = "";
495
+ const reporter = {
496
+ linked: async () => selected,
497
+ async hit(resetsAt) {
498
+ await call(api, "POST", "/v1/agents/me/plan/limit", { planId: selected, machineId, resetsAt });
499
+ },
500
+ async record(input) {
501
+ const result = await call(api, "POST", "/v1/agents/me/plan/usage", { ...input, machineId });
502
+ if (!result.ok)
503
+ throw new Error("Gavel refused the managed plan usage report");
504
+ },
505
+ async day(input) {
506
+ const result = await call(api, "PUT", "/v1/agents/me/plan/days", { ...input, machineId });
507
+ if (!result.ok)
508
+ throw new Error("Gavel refused the managed plan usage day");
509
+ },
510
+ };
511
+ h = harnessOf(nextHarness, { ...ctx, env, planReporter: reporter });
512
+ if (h instanceof ClaudeCodeHarness)
513
+ h.setPerson(me.person.name);
514
+ previous.listen({ live() { }, state() { }, changed() { }, note() { } });
515
+ await previous.close();
516
+ h.listen(listener);
517
+ h.setChat(!!on);
518
+ resetReporters(reporter);
404
519
  }
520
+ const model = typeof route?.model === "string" && /^[A-Za-z0-9][\w.:[\]-]{0,79}$/.test(route.model) ? route.model : null;
521
+ const effort = typeof route?.effort === "string" ? route.effort : null;
522
+ const context = typeof route?.context === "string" ? route.context : null;
523
+ return { allowed: true, fresh: { per: fresh?.per ?? "batch", item: fresh?.item ?? null, brief: fresh?.brief ?? "", model: model ?? fresh?.model ?? null, effort, context } };
405
524
  };
406
525
  const tryWake = async () => {
407
526
  if (waking || stopping || !pending.length)
408
527
  return;
409
528
  waking = true;
410
529
  try {
411
- if (!(await stillWaiting())) {
530
+ const still = await stillWaiting();
531
+ if (!still.waiting) {
412
532
  pending = [];
413
533
  return;
414
534
  }
415
535
  const line = wakeLineOf(pending);
416
- if (await h.wake(line)) {
536
+ if (await launch(async () => {
537
+ const chosen = await pick(still.fresh);
538
+ return chosen.allowed && await h.wake(line, chosen.fresh);
539
+ })) {
417
540
  say(`Woke ${h.name} for what waits in Gavel: ${line}`);
418
541
  pending = [];
419
542
  }
@@ -431,7 +554,7 @@ async function harnessBridge(h, harness, setup, ctx) {
431
554
  while (watching && !stopping) {
432
555
  let res;
433
556
  try {
434
- res = await call(api, "GET", `/v1/inbox/watch?watch=${watchId}&timeout=50&kinds=health,claim,work,drift${start ? "&start=true" : ""}`);
557
+ res = await call(api, "GET", `/v1/inbox/watch?watch=${watchId}&timeout=50&kinds=health,claim,work,drift${machineId ? "" : `&planProvider=${planProvider}`}${start ? "&start=true" : ""}`);
435
558
  }
436
559
  catch {
437
560
  failures++;
@@ -464,17 +587,61 @@ async function harnessBridge(h, harness, setup, ctx) {
464
587
  };
465
588
  const wakeTimer = setInterval(() => void tryWake(), WAKE_AGAIN_MS);
466
589
  // 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;
590
+ let plan = !machineId && harness === "claude-code" ? claudePlanReporter({ home: ctx.home, request: (method, path, body) => call(api, method, path, body), say }) : null;
591
+ // Its tokens for each day, summed from the agent's transcripts here (W-247, for the plan's share).
592
+ let days = harness === "claude-code" && ctx.planReporter ? claudeDayReporter({ home: ctx.home, cwd: ctx.cwd, env: ctx.env, reporter: ctx.planReporter, say }) : null;
593
+ const daysTimer = days || machineId ? setInterval(() => days?.poke(), DAYS_EVERY_MS) : null;
594
+ const resetReporters = (reporter) => {
595
+ plan?.close();
596
+ days?.close();
597
+ plan = null;
598
+ days = activeHarness === "claude-code" ? claudeDayReporter({ home: ctx.home, cwd: ctx.cwd, env: activeEnv, reporter, say }) : null;
599
+ };
600
+ days?.poke();
468
601
  // The harness's own hooks, through `gavel bridge event` (background.ts), and the status line's.
469
602
  const offHooks = onHookEvent((event) => {
470
- if (event.event !== STATUS_LINE_EVENT)
603
+ if (event.event !== STATUS_LINE_EVENT) {
604
+ if (activePlan && activeHarness === "claude-code" && event.planId === activePlan && event.event === "SessionStart" && typeof event.input.session_id === "string") {
605
+ try {
606
+ rememberPlanSession(ctx.home, activePlan, event.input.session_id);
607
+ }
608
+ catch {
609
+ say("Gavel could not record this Claude session for daily plan usage.");
610
+ }
611
+ }
612
+ if (machineId && activePlan && event.planId === activePlan && event.event === "StopFailure" && event.input.error === "rate_limit") {
613
+ const text = event.input.last_assistant_message;
614
+ if (typeof text === "string" && /(?:usage limit|hit your limit|session limit|weekly limit)/i.test(text)) {
615
+ const details = event.input.error_details;
616
+ const detailsText = typeof details === "string" ? details : "";
617
+ const stamp = detailsText.match(/reset(?:s|_at)?(?: at)?[: ]+([0-9]{4}-[0-9]{2}-[0-9]{2}T[^\s,;]+)/i)?.[1];
618
+ const reset = stamp ? Date.parse(stamp) : Number.NaN;
619
+ void call(api, "POST", "/v1/agents/me/plan/limit", { planId: activePlan, machineId, resetsAt: reset > Date.now() ? new Date(reset).toISOString() : null }).catch(() => undefined);
620
+ }
621
+ }
471
622
  return h.hook?.(event.event, event);
623
+ }
472
624
  const usage = planUsageOf(event.input);
473
- if (plan && usage)
474
- plan.observe(usage);
625
+ if (plan && usage && !activePlan)
626
+ plan.observe(usage, accountOf(event.input));
627
+ if (usage && machineId && activePlan && activeHarness === "claude-code" && event.input.planId === activePlan) {
628
+ const now = Date.now();
629
+ const windows = JSON.stringify(usage.windows.map((window) => [window.kind, Math.floor(window.usedPercent), window.resetsAt]));
630
+ if (usage.windows.length && windows !== lastManagedWindows && now - lastManagedUsage >= 60_000) {
631
+ lastManagedUsage = now;
632
+ const planId = activePlan;
633
+ void call(api, "POST", "/v1/agents/me/plan/usage", { ...usageBody(planId, usage, new Date(now)), machineId }).then((result) => {
634
+ if (result.ok && activePlan === planId)
635
+ lastManagedWindows = windows;
636
+ }).catch(() => undefined);
637
+ }
638
+ }
639
+ days?.poke();
475
640
  });
476
- h.listen({
641
+ const listener = {
477
642
  live: (event) => {
643
+ if (event.event === "end")
644
+ days?.poke();
478
645
  if (!on || !liveRoute)
479
646
  return;
480
647
  outgoing.push(event);
@@ -492,7 +659,8 @@ async function harnessBridge(h, harness, setup, ctx) {
492
659
  },
493
660
  changed: pushSoon,
494
661
  note: (text) => void note(text),
495
- });
662
+ };
663
+ h.listen(listener);
496
664
  const timers = () => {
497
665
  if (liveTimer)
498
666
  clearTimeout(liveTimer);
@@ -502,6 +670,9 @@ async function harnessBridge(h, harness, setup, ctx) {
502
670
  clearTimeout(soon);
503
671
  offHooks();
504
672
  plan?.close();
673
+ days?.close();
674
+ if (daysTimer)
675
+ clearInterval(daysTimer);
505
676
  };
506
677
  const stop = (said = "Stopped.") => {
507
678
  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)