@getgavel/cli 0.1.25 → 0.1.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/dist/bridge/background.js +106 -4
- package/dist/bridge/bridge.js +74 -11
- package/dist/bridge/claude-code.js +5 -5
- package/dist/bridge/claude-days.js +236 -0
- package/dist/bridge/claude-live.js +87 -17
- package/dist/bridge/claude-plan.js +257 -0
- package/dist/bridge/codex-app.js +0 -1
- package/dist/bridge/codex-plan.js +261 -0
- package/dist/bridge/codex.js +21 -0
- package/dist/gavel.js +27 -10
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gavel",
|
|
3
|
-
"version": "0.1.
|
|
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,9 +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 { claudeAccount, statusLineUsage } from "./claude-plan.js";
|
|
7
8
|
import { claudeSetups, codexSetups } from "./setup.js";
|
|
8
9
|
// How long a bridge a hook started stays after its folder's last session ends: long enough for a
|
|
9
10
|
// /clear, a restart or a resume, never all night.
|
|
@@ -29,12 +30,14 @@ export function bridgeKey(cwd, harness) {
|
|
|
29
30
|
// zero (Linux's 108), and past it listen fails (W-244).
|
|
30
31
|
export const MAX_SOCKET_PATH = 103;
|
|
31
32
|
// The hook socket beside the lock, unless a long home folder pushes it past the limit: then in a
|
|
32
|
-
// private folder of the user's own under
|
|
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.
|
|
33
35
|
function socketPath(dir, key) {
|
|
34
36
|
const beside = join(dir, `${key}.sock`);
|
|
35
37
|
if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH)
|
|
36
38
|
return beside;
|
|
37
|
-
|
|
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`);
|
|
38
41
|
}
|
|
39
42
|
export function bridgePaths(home, cwd, harness) {
|
|
40
43
|
const dir = bridgeDir(home);
|
|
@@ -48,6 +51,17 @@ function privateDir(dir) {
|
|
|
48
51
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
49
52
|
chmodSync(dir, 0o700);
|
|
50
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
|
+
}
|
|
51
65
|
// A process is the bridge its lock names only while it's alive and still a gavel bridge: a pid the
|
|
52
66
|
// system gave to something else since doesn't count.
|
|
53
67
|
function isBridge(pid) {
|
|
@@ -103,7 +117,7 @@ export function holdBridge(opts) {
|
|
|
103
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`);
|
|
104
118
|
}
|
|
105
119
|
if (dirname(paths.socket) !== paths.dir)
|
|
106
|
-
|
|
120
|
+
ownSocketDir(dirname(paths.socket));
|
|
107
121
|
const open = new Set();
|
|
108
122
|
let lastClosed = null;
|
|
109
123
|
const lock = {
|
|
@@ -281,6 +295,8 @@ export async function startBridge(opts) {
|
|
|
281
295
|
return { bridge: "running", pid: live.pid, log: live.log };
|
|
282
296
|
privateDir(paths.dir);
|
|
283
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);
|
|
284
300
|
const [command, ...args] = [process.execPath, ...process.execArgv, process.argv[1]];
|
|
285
301
|
const env = { ...opts.env, GAVEL_BRIDGE_UNTIL_CLOSED: opts.untilClosed ? "1" : "" };
|
|
286
302
|
// A session's own inbox stays with the session's hooks, never in a bridge that outlives it.
|
|
@@ -421,3 +437,89 @@ export async function hookEvent(opts) {
|
|
|
421
437
|
}
|
|
422
438
|
return 0;
|
|
423
439
|
}
|
|
440
|
+
// The bridge's event for a status line's figures (W-258): never a hook's own name.
|
|
441
|
+
export const STATUS_LINE_EVENT = "StatusLine";
|
|
442
|
+
const OWN_LINE_MS = 10_000;
|
|
443
|
+
const OWN_LINE_BYTES = 64 * 1024;
|
|
444
|
+
export function ownStatusLineEntry(home, project, env) {
|
|
445
|
+
const config = env.CLAUDE_CONFIG_DIR || join(home, ".claude");
|
|
446
|
+
for (const file of [join(project, ".claude", "settings.json"), join(config, "settings.json")]) {
|
|
447
|
+
try {
|
|
448
|
+
const line = JSON.parse(readFileSync(file, "utf8")).statusLine;
|
|
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
|
+
}
|
|
457
|
+
}
|
|
458
|
+
catch {
|
|
459
|
+
// none there
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
return null;
|
|
463
|
+
}
|
|
464
|
+
export const ownStatusLine = (home, project, env) => ownStatusLineEntry(home, project, env)?.command ?? null;
|
|
465
|
+
export const isBridgeStatusLine = (command) => /\bbridge status-line\b/.test(command);
|
|
466
|
+
function runOwn(command, input, cwd, env) {
|
|
467
|
+
return new Promise((resolve) => {
|
|
468
|
+
const child = spawn("/bin/sh", ["-c", command], { cwd, env, stdio: ["pipe", "pipe", "ignore"] });
|
|
469
|
+
let out = "";
|
|
470
|
+
const done = () => resolve(out);
|
|
471
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), OWN_LINE_MS);
|
|
472
|
+
child.stdout.setEncoding("utf8");
|
|
473
|
+
child.stdout.on("data", (chunk) => {
|
|
474
|
+
if (out.length < OWN_LINE_BYTES)
|
|
475
|
+
out += chunk.slice(0, OWN_LINE_BYTES - out.length);
|
|
476
|
+
});
|
|
477
|
+
child.on("error", () => {
|
|
478
|
+
clearTimeout(timer);
|
|
479
|
+
done();
|
|
480
|
+
});
|
|
481
|
+
child.on("close", () => {
|
|
482
|
+
clearTimeout(timer);
|
|
483
|
+
done();
|
|
484
|
+
});
|
|
485
|
+
child.stdin.on("error", () => undefined);
|
|
486
|
+
child.stdin.end(input);
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
// `gavel bridge status-line`, Claude Code's status line in a folder whose bridge's hooks are on: the
|
|
490
|
+
// plan's figures alone (statusLineUsage) to the folder's running bridge, never starting one; then the
|
|
491
|
+
// person's own status line, with the same input, and only what it prints.
|
|
492
|
+
export async function bridgeStatusLine(opts) {
|
|
493
|
+
const text = await stdinText();
|
|
494
|
+
let input = {};
|
|
495
|
+
try {
|
|
496
|
+
const parsed = JSON.parse(text);
|
|
497
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
498
|
+
input = parsed;
|
|
499
|
+
}
|
|
500
|
+
catch {
|
|
501
|
+
// no input: the person's own line still runs
|
|
502
|
+
}
|
|
503
|
+
const dir = (v) => (typeof v === "string" && existsSync(v) ? v : null);
|
|
504
|
+
const cwd = dir(input.workspace?.current_dir) ?? dir(input.cwd) ?? opts.cwd;
|
|
505
|
+
const project = dir(input.workspace?.project_dir) ?? cwd;
|
|
506
|
+
const usage = statusLineUsage(input);
|
|
507
|
+
const handed = (async () => {
|
|
508
|
+
try {
|
|
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.
|
|
512
|
+
if (live)
|
|
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`);
|
|
514
|
+
}
|
|
515
|
+
catch {
|
|
516
|
+
// never the status line's failure
|
|
517
|
+
}
|
|
518
|
+
})();
|
|
519
|
+
const own = ownStatusLine(opts.home, project, opts.env);
|
|
520
|
+
const shown = own ? await runOwn(own, text, cwd, opts.env) : "";
|
|
521
|
+
await handed;
|
|
522
|
+
// Written whole before the process exits: a pipe on a Mac takes it asynchronously.
|
|
523
|
+
await new Promise((resolve) => process.stdout.write(shown, () => resolve()));
|
|
524
|
+
return 0;
|
|
525
|
+
}
|
package/dist/bridge/bridge.js
CHANGED
|
@@ -3,7 +3,9 @@ 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 { claudeDayReporter, DAYS_EVERY_MS } from "./claude-days.js";
|
|
8
|
+
import { accountOf, claudePlanReporter, planUsageOf } from "./claude-plan.js";
|
|
7
9
|
import { claudeSessions } from "./claude-code.js";
|
|
8
10
|
import { ClaudeCodeHarness } from "./claude-live.js";
|
|
9
11
|
import { codexHarness, codexSessions } from "./codex.js";
|
|
@@ -70,6 +72,14 @@ async function whoAmI(api, setup) {
|
|
|
70
72
|
throw new BridgeError(`Gavel answered ${res.status} to who this agent is: try again in a moment.`);
|
|
71
73
|
return (await res.json());
|
|
72
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
|
+
}
|
|
73
83
|
const clock = () => new Date().toTimeString().slice(0, 5);
|
|
74
84
|
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
75
85
|
const backoff = (failures) => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
|
|
@@ -96,7 +106,29 @@ async function show(run, ctx) {
|
|
|
96
106
|
async function bridge(run, ctx) {
|
|
97
107
|
const harness = harnessHere(run.harness, ctx);
|
|
98
108
|
const setup = setupHere(harness, run.server, ctx);
|
|
99
|
-
|
|
109
|
+
const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
|
|
110
|
+
let linked = null;
|
|
111
|
+
const report = async (method, path, input) => {
|
|
112
|
+
const res = await call(api, method, path, input);
|
|
113
|
+
if (res.status === 404)
|
|
114
|
+
linked = null;
|
|
115
|
+
if (!res.ok)
|
|
116
|
+
throw new Error("Gavel refused the plan usage report");
|
|
117
|
+
};
|
|
118
|
+
const planReporter = {
|
|
119
|
+
async linked() {
|
|
120
|
+
if (linked && Date.now() < linked.until)
|
|
121
|
+
return linked.id;
|
|
122
|
+
const res = await call(api, "GET", "/v1/agents/me/plan");
|
|
123
|
+
const body = res.ok ? await res.json() : null;
|
|
124
|
+
const id = typeof body?.planId === "string" ? body.planId : null;
|
|
125
|
+
linked = { id, until: Date.now() + 120_000 };
|
|
126
|
+
return id;
|
|
127
|
+
},
|
|
128
|
+
day: (input) => report("PUT", "/v1/agents/me/plan/days", input),
|
|
129
|
+
record: (input) => report("POST", "/v1/agents/me/plan/usage", input),
|
|
130
|
+
};
|
|
131
|
+
return harnessBridge(harnessOf(harness, { ...ctx, planReporter }), harness, setup, ctx);
|
|
100
132
|
}
|
|
101
133
|
const PICTURE_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp" };
|
|
102
134
|
const PICTURE_MAX = 15 * 1024 * 1024;
|
|
@@ -367,17 +399,28 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
367
399
|
// Wakes: what waits for the agent in Gavel (an answer to what it waits on, a message, a request),
|
|
368
400
|
// as Gavel's one line into the session once it's idle. The person's own messages it puts in itself.
|
|
369
401
|
const watchId = randomUUID();
|
|
402
|
+
const planProvider = harness === "codex" ? "openai" : "anthropic";
|
|
370
403
|
let watching = true;
|
|
371
404
|
let pending = [];
|
|
372
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.
|
|
373
408
|
const stillWaiting = async () => {
|
|
374
409
|
try {
|
|
375
|
-
const res = await call(api, "GET", "/v1/me", undefined, { "x-gavel-waiting": "1" });
|
|
376
|
-
|
|
377
|
-
|
|
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)) };
|
|
378
421
|
}
|
|
379
422
|
catch {
|
|
380
|
-
return true;
|
|
423
|
+
return { waiting: true, fresh: null };
|
|
381
424
|
}
|
|
382
425
|
};
|
|
383
426
|
const tryWake = async () => {
|
|
@@ -385,12 +428,13 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
385
428
|
return;
|
|
386
429
|
waking = true;
|
|
387
430
|
try {
|
|
388
|
-
|
|
431
|
+
const still = await stillWaiting();
|
|
432
|
+
if (!still.waiting) {
|
|
389
433
|
pending = [];
|
|
390
434
|
return;
|
|
391
435
|
}
|
|
392
436
|
const line = wakeLineOf(pending);
|
|
393
|
-
if (await h.wake(line)) {
|
|
437
|
+
if (await h.wake(line, still.fresh)) {
|
|
394
438
|
say(`Woke ${h.name} for what waits in Gavel: ${line}`);
|
|
395
439
|
pending = [];
|
|
396
440
|
}
|
|
@@ -408,7 +452,7 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
408
452
|
while (watching && !stopping) {
|
|
409
453
|
let res;
|
|
410
454
|
try {
|
|
411
|
-
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" : ""}`);
|
|
412
456
|
}
|
|
413
457
|
catch {
|
|
414
458
|
failures++;
|
|
@@ -440,10 +484,25 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
440
484
|
}
|
|
441
485
|
};
|
|
442
486
|
const wakeTimer = setInterval(() => void tryWake(), WAKE_AGAIN_MS);
|
|
443
|
-
//
|
|
444
|
-
const
|
|
487
|
+
// Claude Code's plan use, from its status line (W-258): to the plan the agent's link names.
|
|
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();
|
|
493
|
+
// The harness's own hooks, through `gavel bridge event` (background.ts), and the status line's.
|
|
494
|
+
const offHooks = onHookEvent((event) => {
|
|
495
|
+
if (event.event !== STATUS_LINE_EVENT)
|
|
496
|
+
return h.hook?.(event.event, event);
|
|
497
|
+
const usage = planUsageOf(event.input);
|
|
498
|
+
if (plan && usage)
|
|
499
|
+
plan.observe(usage, accountOf(event.input));
|
|
500
|
+
days?.poke();
|
|
501
|
+
});
|
|
445
502
|
h.listen({
|
|
446
503
|
live: (event) => {
|
|
504
|
+
if (event.event === "end")
|
|
505
|
+
days?.poke();
|
|
447
506
|
if (!on || !liveRoute)
|
|
448
507
|
return;
|
|
449
508
|
outgoing.push(event);
|
|
@@ -470,6 +529,10 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
470
529
|
if (soon)
|
|
471
530
|
clearTimeout(soon);
|
|
472
531
|
offHooks();
|
|
532
|
+
plan?.close();
|
|
533
|
+
days?.close();
|
|
534
|
+
if (daysTimer)
|
|
535
|
+
clearInterval(daysTimer);
|
|
473
536
|
};
|
|
474
537
|
const stop = (said = "Stopped.") => {
|
|
475
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
|
|
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
|
|
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
|
+
}
|