@getgavel/cli 0.1.25 → 0.1.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/dist/bridge/background.js +80 -0
- package/dist/bridge/bridge.js +36 -4
- package/dist/bridge/claude-live.js +18 -6
- package/dist/bridge/claude-plan.js +238 -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 +10 -1
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gavel",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.26",
|
|
4
4
|
"displayName": "Gavel",
|
|
5
5
|
"description": "Gavel in Claude Code: your person's chat in Gavel reaches your sessions at once (Gavel's bridge, started with each session), the end-of-turn reminder of what's waiting for you, and how to work with Gavel.",
|
|
6
6
|
"author": { "name": "Gavel", "url": "https://getgavel.ai" },
|
|
@@ -4,6 +4,7 @@ import { chmodSync, closeSync, copyFileSync, existsSync, linkSync, mkdirSync, op
|
|
|
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
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.
|
|
@@ -421,3 +422,82 @@ export async function hookEvent(opts) {
|
|
|
421
422
|
}
|
|
422
423
|
return 0;
|
|
423
424
|
}
|
|
425
|
+
// The bridge's event for a status line's figures (W-258): never a hook's own name.
|
|
426
|
+
export const STATUS_LINE_EVENT = "StatusLine";
|
|
427
|
+
const OWN_LINE_MS = 10_000;
|
|
428
|
+
const OWN_LINE_BYTES = 64 * 1024;
|
|
429
|
+
// The status line the person had before the bridge's took this folder's place: the project's
|
|
430
|
+
// settings, then their own; never the bridge's own.
|
|
431
|
+
export function ownStatusLine(home, project, env) {
|
|
432
|
+
const config = env.CLAUDE_CONFIG_DIR || join(home, ".claude");
|
|
433
|
+
for (const file of [join(project, ".claude", "settings.json"), join(config, "settings.json")]) {
|
|
434
|
+
try {
|
|
435
|
+
const line = JSON.parse(readFileSync(file, "utf8")).statusLine;
|
|
436
|
+
if (line?.type === "command" && typeof line.command === "string" && line.command.trim() && !isBridgeStatusLine(line.command))
|
|
437
|
+
return line.command;
|
|
438
|
+
}
|
|
439
|
+
catch {
|
|
440
|
+
// none there
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
export const isBridgeStatusLine = (command) => /\bbridge status-line\b/.test(command);
|
|
446
|
+
function runOwn(command, input, cwd, env) {
|
|
447
|
+
return new Promise((resolve) => {
|
|
448
|
+
const child = spawn("/bin/sh", ["-c", command], { cwd, env, stdio: ["pipe", "pipe", "ignore"] });
|
|
449
|
+
let out = "";
|
|
450
|
+
const done = () => resolve(out);
|
|
451
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), OWN_LINE_MS);
|
|
452
|
+
child.stdout.setEncoding("utf8");
|
|
453
|
+
child.stdout.on("data", (chunk) => {
|
|
454
|
+
if (out.length < OWN_LINE_BYTES)
|
|
455
|
+
out += chunk.slice(0, OWN_LINE_BYTES - out.length);
|
|
456
|
+
});
|
|
457
|
+
child.on("error", () => {
|
|
458
|
+
clearTimeout(timer);
|
|
459
|
+
done();
|
|
460
|
+
});
|
|
461
|
+
child.on("close", () => {
|
|
462
|
+
clearTimeout(timer);
|
|
463
|
+
done();
|
|
464
|
+
});
|
|
465
|
+
child.stdin.on("error", () => undefined);
|
|
466
|
+
child.stdin.end(input);
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
// `gavel bridge status-line`, Claude Code's status line in a folder whose bridge's hooks are on: the
|
|
470
|
+
// plan's figures alone (statusLineUsage) to the folder's running bridge, never starting one; then the
|
|
471
|
+
// person's own status line, with the same input, and only what it prints.
|
|
472
|
+
export async function bridgeStatusLine(opts) {
|
|
473
|
+
const text = await stdinText();
|
|
474
|
+
let input = {};
|
|
475
|
+
try {
|
|
476
|
+
const parsed = JSON.parse(text);
|
|
477
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
478
|
+
input = parsed;
|
|
479
|
+
}
|
|
480
|
+
catch {
|
|
481
|
+
// no input: the person's own line still runs
|
|
482
|
+
}
|
|
483
|
+
const dir = (v) => (typeof v === "string" && existsSync(v) ? v : null);
|
|
484
|
+
const cwd = dir(input.workspace?.current_dir) ?? dir(input.cwd) ?? opts.cwd;
|
|
485
|
+
const project = dir(input.workspace?.project_dir) ?? cwd;
|
|
486
|
+
const usage = statusLineUsage(input);
|
|
487
|
+
const handed = (async () => {
|
|
488
|
+
try {
|
|
489
|
+
const live = usage ? runningBridge(opts.home, project, "claude-code") : null;
|
|
490
|
+
if (live)
|
|
491
|
+
await send(live.socket, `${JSON.stringify({ event: STATUS_LINE_EVENT, input: usage, inbox: null, at: Date.now() })}\n`);
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
// never the status line's failure
|
|
495
|
+
}
|
|
496
|
+
})();
|
|
497
|
+
const own = ownStatusLine(opts.home, project, opts.env);
|
|
498
|
+
const shown = own ? await runOwn(own, text, cwd, opts.env) : "";
|
|
499
|
+
await handed;
|
|
500
|
+
// Written whole before the process exits: a pipe on a Mac takes it asynchronously.
|
|
501
|
+
await new Promise((resolve) => process.stdout.write(shown, () => resolve()));
|
|
502
|
+
return 0;
|
|
503
|
+
}
|
package/dist/bridge/bridge.js
CHANGED
|
@@ -3,7 +3,8 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { basename, join } from "node:path";
|
|
5
5
|
import { jsonText } from "../output.js";
|
|
6
|
-
import { markChatOff, onHookEvent } from "./background.js";
|
|
6
|
+
import { markChatOff, onHookEvent, STATUS_LINE_EVENT } from "./background.js";
|
|
7
|
+
import { claudePlanReporter, planUsageOf } from "./claude-plan.js";
|
|
7
8
|
import { claudeSessions } from "./claude-code.js";
|
|
8
9
|
import { ClaudeCodeHarness } from "./claude-live.js";
|
|
9
10
|
import { codexHarness, codexSessions } from "./codex.js";
|
|
@@ -96,7 +97,29 @@ async function show(run, ctx) {
|
|
|
96
97
|
async function bridge(run, ctx) {
|
|
97
98
|
const harness = harnessHere(run.harness, ctx);
|
|
98
99
|
const setup = setupHere(harness, run.server, ctx);
|
|
99
|
-
|
|
100
|
+
const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
|
|
101
|
+
let linked = null;
|
|
102
|
+
const report = async (method, path, input) => {
|
|
103
|
+
const res = await call(api, method, path, input);
|
|
104
|
+
if (res.status === 404)
|
|
105
|
+
linked = null;
|
|
106
|
+
if (!res.ok)
|
|
107
|
+
throw new Error("Gavel refused the plan usage report");
|
|
108
|
+
};
|
|
109
|
+
const planReporter = {
|
|
110
|
+
async linked() {
|
|
111
|
+
if (linked && Date.now() < linked.until)
|
|
112
|
+
return linked.id;
|
|
113
|
+
const res = await call(api, "GET", "/v1/agents/me/plan");
|
|
114
|
+
const body = res.ok ? await res.json() : null;
|
|
115
|
+
const id = typeof body?.planId === "string" ? body.planId : null;
|
|
116
|
+
linked = { id, until: Date.now() + 120_000 };
|
|
117
|
+
return id;
|
|
118
|
+
},
|
|
119
|
+
day: (input) => report("PUT", "/v1/agents/me/plan/days", input),
|
|
120
|
+
record: (input) => report("POST", "/v1/agents/me/plan/usage", input),
|
|
121
|
+
};
|
|
122
|
+
return harnessBridge(harnessOf(harness, { ...ctx, planReporter }), harness, setup, ctx);
|
|
100
123
|
}
|
|
101
124
|
const PICTURE_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp" };
|
|
102
125
|
const PICTURE_MAX = 15 * 1024 * 1024;
|
|
@@ -440,8 +463,16 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
440
463
|
}
|
|
441
464
|
};
|
|
442
465
|
const wakeTimer = setInterval(() => void tryWake(), WAKE_AGAIN_MS);
|
|
443
|
-
//
|
|
444
|
-
const
|
|
466
|
+
// Claude Code's plan use, from its status line (W-258): to the plan the agent's link names.
|
|
467
|
+
const plan = harness === "claude-code" ? claudePlanReporter({ home: ctx.home, env: ctx.env, request: (method, path, body) => call(api, method, path, body), say }) : null;
|
|
468
|
+
// The harness's own hooks, through `gavel bridge event` (background.ts), and the status line's.
|
|
469
|
+
const offHooks = onHookEvent((event) => {
|
|
470
|
+
if (event.event !== STATUS_LINE_EVENT)
|
|
471
|
+
return h.hook?.(event.event, event);
|
|
472
|
+
const usage = planUsageOf(event.input);
|
|
473
|
+
if (plan && usage)
|
|
474
|
+
plan.observe(usage);
|
|
475
|
+
});
|
|
445
476
|
h.listen({
|
|
446
477
|
live: (event) => {
|
|
447
478
|
if (!on || !liveRoute)
|
|
@@ -470,6 +501,7 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
470
501
|
if (soon)
|
|
471
502
|
clearTimeout(soon);
|
|
472
503
|
offHooks();
|
|
504
|
+
plan?.close();
|
|
473
505
|
};
|
|
474
506
|
const stop = (said = "Stopped.") => {
|
|
475
507
|
if (stopping)
|
|
@@ -6,7 +6,7 @@ import { connect } from "node:net";
|
|
|
6
6
|
import { tmpdir } from "node:os";
|
|
7
7
|
import { basename, dirname, extname, join } from "node:path";
|
|
8
8
|
import { promisify } from "node:util";
|
|
9
|
-
import { bridgePaths } from "./background.js";
|
|
9
|
+
import { bridgePaths, isBridgeStatusLine } from "./background.js";
|
|
10
10
|
import { claudeSessions, claudeWords } from "./claude-code.js";
|
|
11
11
|
import { claudeSetups } from "./setup.js";
|
|
12
12
|
// Claude Code live (W-132): what a session tells the bridge through its hooks, and how the bridge
|
|
@@ -69,9 +69,13 @@ const DISPLAY_PATH = "/gavel-bridge/";
|
|
|
69
69
|
const isBridgeHook = (h) => (Array.isArray(h.args) && h.args.includes("bridge") && h.args.includes("event")) ||
|
|
70
70
|
(typeof h.url === "string" && h.url.startsWith("http://127.0.0.1:") && h.url.includes(DISPLAY_PATH)) ||
|
|
71
71
|
(typeof h.command === "string" && /\bbridge wake( |$)/.test(h.command));
|
|
72
|
+
// A command line for the shell, each part quoted.
|
|
73
|
+
const shellLine = (parts) => parts.map((p) => (/^[\w@%+=:,./-]+$/.test(p) ? p : `'${p.replace(/'/g, "'\\''")}'`)).join(" ");
|
|
72
74
|
// The settings with the bridge's hooks in (its command and the display hook's address) or out
|
|
73
|
-
// (null), every other hook and setting kept; null when nothing changes.
|
|
74
|
-
|
|
75
|
+
// (null), every other hook and setting kept; null when nothing changes. statusLine: the command for
|
|
76
|
+
// the bridge's status line (W-258), which reads the plan's figures and runs the person's own; a
|
|
77
|
+
// status line the person set in this same file stays theirs, and the bridge's never goes in over it.
|
|
78
|
+
export function withBridgeHooks(existing, command, displayUrl, statusLine = null) {
|
|
75
79
|
let settings = {};
|
|
76
80
|
if (existing?.trim()) {
|
|
77
81
|
try {
|
|
@@ -96,11 +100,14 @@ export function withBridgeHooks(existing, command, displayUrl) {
|
|
|
96
100
|
}
|
|
97
101
|
if (displayUrl)
|
|
98
102
|
hooks.MessageDisplay = [...(hooks.MessageDisplay ?? []), { hooks: [{ type: "http", url: displayUrl, timeout: 2 }] }];
|
|
99
|
-
const { hooks: _old, ...rest } = settings;
|
|
100
|
-
const
|
|
103
|
+
const { hooks: _old, statusLine: line, ...rest } = settings;
|
|
104
|
+
const ours = isOurStatusLine(line);
|
|
105
|
+
const keptLine = line !== undefined && !ours ? { statusLine: line } : statusLine ? { statusLine: { type: "command", command: shellLine([...statusLine, "bridge", "status-line"]) } } : {};
|
|
106
|
+
const next = { ...rest, ...keptLine, ...(Object.keys(hooks).length ? { hooks } : {}) };
|
|
101
107
|
const text = `${JSON.stringify(next, null, 2)}\n`;
|
|
102
108
|
return text === existing ? null : text;
|
|
103
109
|
}
|
|
110
|
+
const isOurStatusLine = (line) => typeof line?.command === "string" && isBridgeStatusLine(line.command);
|
|
104
111
|
// The display hook's address for this folder: a port and a secret path kept beside the bridge's
|
|
105
112
|
// lock (mode 600), the same each time, so the settings name it once.
|
|
106
113
|
export function displayHook(home, cwd) {
|
|
@@ -208,14 +215,19 @@ export async function claudeBridgeHooks(action, opts) {
|
|
|
208
215
|
// With Gavel's plugin on, it runs the bridge's hooks: this folder gets only its own address for
|
|
209
216
|
// the agent's words as they're shown.
|
|
210
217
|
const plugin = gavelPluginOn(opts.home);
|
|
211
|
-
|
|
218
|
+
// The status line goes here even with the plugin on, which can't carry one (W-258).
|
|
219
|
+
const next = withBridgeHooks(existing, plugin ? null : opts.command, displayHook(opts.home, opts.cwd).url, opts.command);
|
|
212
220
|
if (next !== null)
|
|
213
221
|
writeWhole(file, next);
|
|
222
|
+
const line = JSON.parse(next ?? existing ?? "{}").statusLine;
|
|
214
223
|
const done = [
|
|
215
224
|
plugin
|
|
216
225
|
? `Gavel's plugin runs the bridge's hooks here; wrote this folder's hook for the words as they're shown into ${name}`
|
|
217
226
|
: `wrote the bridge's hooks into ${name}: a Claude Code session here starts Gavel's bridge as it starts (and stops it a while after the last one ends), so your person's chat in Gavel reaches it at once, with no terminal open`,
|
|
218
227
|
];
|
|
228
|
+
done.push(isOurStatusLine(line)
|
|
229
|
+
? `wrote the bridge's status line into ${name}: it shows your own status line as before, and sends your Claude plan's use to Gavel for you alone`
|
|
230
|
+
: `kept your own status line in ${name}, so your Claude plan's use isn't read here`);
|
|
219
231
|
if (gitIn(["rev-parse", "--is-inside-work-tree"], opts.cwd) && !gitIn(["check-ignore", "-q", name], opts.cwd)) {
|
|
220
232
|
const gitignore = join(opts.cwd, ".gitignore");
|
|
221
233
|
const text = existsSync(gitignore) ? readFileSync(gitignore, "utf8") : "";
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { hostname } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
const WINDOWS = [
|
|
6
|
+
["five_hour", "five_hour"],
|
|
7
|
+
["seven_day", "weekly"],
|
|
8
|
+
];
|
|
9
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
|
10
|
+
const percent = (v) => {
|
|
11
|
+
const n = num(v);
|
|
12
|
+
return n === null ? null : Math.min(100, Math.max(0, Math.round(n * 10) / 10));
|
|
13
|
+
};
|
|
14
|
+
// Claude Code says a reset in epoch seconds.
|
|
15
|
+
const instant = (v) => {
|
|
16
|
+
const n = num(v);
|
|
17
|
+
return n === null || n <= 0 || n > 4_102_444_800 ? null : new Date(n * 1000).toISOString();
|
|
18
|
+
};
|
|
19
|
+
// The allowlisted numbers from the status line's input (its JSON on stdin), nothing else of it; null
|
|
20
|
+
// when it has none (an API key's session, or before the session's first answer).
|
|
21
|
+
export function statusLineUsage(input) {
|
|
22
|
+
const limits = input?.rate_limits;
|
|
23
|
+
if (!limits || typeof limits !== "object")
|
|
24
|
+
return null;
|
|
25
|
+
const r = limits;
|
|
26
|
+
const windows = [];
|
|
27
|
+
for (const [from, kind] of WINDOWS) {
|
|
28
|
+
const usedPercent = percent(r[from]?.used_percentage);
|
|
29
|
+
const resetsAt = instant(r[from]?.resets_at);
|
|
30
|
+
if (usedPercent !== null && resetsAt)
|
|
31
|
+
windows.push({ kind, usedPercent, resetsAt });
|
|
32
|
+
}
|
|
33
|
+
let spendLimit = null;
|
|
34
|
+
const s = r.spend_limit;
|
|
35
|
+
const spent = percent(s?.used_percentage);
|
|
36
|
+
if (s && spent !== null) {
|
|
37
|
+
spendLimit = { usedPercent: spent, resetsAt: instant(s.resets_at) };
|
|
38
|
+
const used = num(s.used_usd);
|
|
39
|
+
const limit = num(s.limit_usd);
|
|
40
|
+
if (used !== null && used >= 0)
|
|
41
|
+
spendLimit.usedUsd = Math.round(used * 100) / 100;
|
|
42
|
+
if (limit !== null && limit >= 0)
|
|
43
|
+
spendLimit.limitUsd = Math.round(limit * 100) / 100;
|
|
44
|
+
if (typeof s.period === "string" && /^[a-z_]{1,20}$/.test(s.period))
|
|
45
|
+
spendLimit.period = s.period;
|
|
46
|
+
}
|
|
47
|
+
if (!windows.length && !spendLimit)
|
|
48
|
+
return null;
|
|
49
|
+
return { windows, spendLimit, limitReached: windows.some((w) => w.usedPercent >= 100) || (spendLimit?.usedPercent ?? 0) >= 100 };
|
|
50
|
+
}
|
|
51
|
+
// The figures as the bridge takes them from its socket: rebuilt from the known fields alone, so
|
|
52
|
+
// nothing else ever rides along to Gavel; null when they aren't figures.
|
|
53
|
+
export function planUsageOf(given) {
|
|
54
|
+
const g = given;
|
|
55
|
+
if (!g || typeof g !== "object" || !Array.isArray(g.windows))
|
|
56
|
+
return null;
|
|
57
|
+
const windows = [];
|
|
58
|
+
for (const w of g.windows) {
|
|
59
|
+
const usedPercent = percent(w?.usedPercent);
|
|
60
|
+
const at = typeof w?.resetsAt === "string" ? Date.parse(w.resetsAt) : Number.NaN;
|
|
61
|
+
if ((w?.kind === "five_hour" || w?.kind === "weekly") && usedPercent !== null && Number.isFinite(at) && !windows.some((x) => x.kind === w.kind))
|
|
62
|
+
windows.push({ kind: w.kind, usedPercent, resetsAt: new Date(at).toISOString() });
|
|
63
|
+
}
|
|
64
|
+
const s = g.spendLimit;
|
|
65
|
+
let spendLimit = null;
|
|
66
|
+
const spent = percent(s?.usedPercent);
|
|
67
|
+
if (s && spent !== null) {
|
|
68
|
+
const at = typeof s.resetsAt === "string" ? Date.parse(s.resetsAt) : Number.NaN;
|
|
69
|
+
spendLimit = { usedPercent: spent, resetsAt: Number.isFinite(at) ? new Date(at).toISOString() : null };
|
|
70
|
+
const used = num(s.usedUsd);
|
|
71
|
+
const limit = num(s.limitUsd);
|
|
72
|
+
if (used !== null && used >= 0)
|
|
73
|
+
spendLimit.usedUsd = Math.round(used * 100) / 100;
|
|
74
|
+
if (limit !== null && limit >= 0)
|
|
75
|
+
spendLimit.limitUsd = Math.round(limit * 100) / 100;
|
|
76
|
+
if (typeof s.period === "string" && /^[a-z_]{1,20}$/.test(s.period))
|
|
77
|
+
spendLimit.period = s.period;
|
|
78
|
+
}
|
|
79
|
+
if (!windows.length && !spendLimit)
|
|
80
|
+
return null;
|
|
81
|
+
return { windows, spendLimit, limitReached: windows.some((w) => w.usedPercent >= 100) || (spendLimit?.usedPercent ?? 0) >= 100 };
|
|
82
|
+
}
|
|
83
|
+
// The Claude account signed in on this laptop, as a hash of its ids (~/.claude.json's oauthAccount):
|
|
84
|
+
// compared here, never sent. Null when none is (an API key's session).
|
|
85
|
+
export function claudeAccount(home, env = process.env) {
|
|
86
|
+
const file = env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, ".claude.json") : join(home, ".claude.json");
|
|
87
|
+
try {
|
|
88
|
+
const account = JSON.parse(readFileSync(file, "utf8")).oauthAccount;
|
|
89
|
+
if (typeof account?.accountUuid !== "string" || !account.accountUuid)
|
|
90
|
+
return null;
|
|
91
|
+
return createHash("sha256").update(`claude\0${account.accountUuid}\0${typeof account.organizationUuid === "string" ? account.organizationUuid : ""}`).digest("hex");
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
// Which account first reported under each plan, kept beside the bridge's locks (mode 600).
|
|
98
|
+
function accountsFile(home) {
|
|
99
|
+
return join(home, ".gavel", "bridge", "plan-accounts.json");
|
|
100
|
+
}
|
|
101
|
+
function readAccounts(home) {
|
|
102
|
+
try {
|
|
103
|
+
const kept = JSON.parse(readFileSync(accountsFile(home), "utf8"));
|
|
104
|
+
return kept && typeof kept === "object" ? kept : {};
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return {};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function keepAccount(home, planId, account) {
|
|
111
|
+
const file = accountsFile(home);
|
|
112
|
+
mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
|
|
113
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
114
|
+
writeFileSync(temp, `${JSON.stringify({ ...readAccounts(home), [planId]: account }, null, 2)}\n`, { mode: 0o600 });
|
|
115
|
+
chmodSync(temp, 0o600);
|
|
116
|
+
renameSync(temp, file);
|
|
117
|
+
}
|
|
118
|
+
// Whether the next figures say something the last sent didn't: a window's whole percent, a reset, a
|
|
119
|
+
// window come or gone, or the limit reached.
|
|
120
|
+
export function changed(last, next) {
|
|
121
|
+
if (!last)
|
|
122
|
+
return true;
|
|
123
|
+
const key = (u) => JSON.stringify([
|
|
124
|
+
u.windows.map((w) => [w.kind, Math.floor(w.usedPercent), w.resetsAt]),
|
|
125
|
+
u.spendLimit ? [Math.floor(u.spendLimit.usedPercent), u.spendLimit.resetsAt] : null,
|
|
126
|
+
u.limitReached,
|
|
127
|
+
]);
|
|
128
|
+
return key(last) !== key(next);
|
|
129
|
+
}
|
|
130
|
+
// What Gavel takes (W-247's contract with Agent Twelve, W-258): the plan's id, the machine's name
|
|
131
|
+
// for the person's own list of machines, and Claude's two windows under one limit, by duration.
|
|
132
|
+
const MINUTES = { five_hour: 300, weekly: 10_080 };
|
|
133
|
+
export function usageBody(planId, usage, at, machineName = hostname()) {
|
|
134
|
+
return {
|
|
135
|
+
planId,
|
|
136
|
+
machineName: machineName.slice(0, 200),
|
|
137
|
+
observedAt: at.toISOString(),
|
|
138
|
+
windows: usage.windows.map((w) => ({ limitId: "claude", durationMinutes: MINUTES[w.kind], usedPercent: w.usedPercent, resetsAt: w.resetsAt })),
|
|
139
|
+
limitReached: usage.limitReached,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
export const PLAN_EVERY_MS = 60_000;
|
|
143
|
+
const PLAN_LOOK_AGAIN_MS = 5 * 60_000;
|
|
144
|
+
// The bridge's reporter: fed each status line's figures, it sends them at most once a minute, and
|
|
145
|
+
// only when they changed, onto the plan the agent's link names, while the account that first
|
|
146
|
+
// reported under that plan is still the one signed in.
|
|
147
|
+
export function claudePlanReporter(opts) {
|
|
148
|
+
const now = opts.now ?? Date.now;
|
|
149
|
+
const every = opts.everyMs ?? PLAN_EVERY_MS;
|
|
150
|
+
let plan = null;
|
|
151
|
+
let sent = null;
|
|
152
|
+
// When it last tried: a refusal waits for the next figures, a minute on, never a loop.
|
|
153
|
+
let triedAt = -Infinity;
|
|
154
|
+
let latest = null;
|
|
155
|
+
let timer = null;
|
|
156
|
+
let sending = false;
|
|
157
|
+
let said = "";
|
|
158
|
+
let closed = false;
|
|
159
|
+
const sayOnce = (line) => {
|
|
160
|
+
if (line !== said)
|
|
161
|
+
opts.say(line);
|
|
162
|
+
said = line;
|
|
163
|
+
};
|
|
164
|
+
const planId = async () => {
|
|
165
|
+
if (plan && now() - plan.at < PLAN_LOOK_AGAIN_MS)
|
|
166
|
+
return plan.id;
|
|
167
|
+
const res = await opts.request("GET", "/v1/agents/me/plan");
|
|
168
|
+
if (res.status === 404) {
|
|
169
|
+
void res.body?.cancel();
|
|
170
|
+
plan = { id: null, at: now() };
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
if (!res.ok)
|
|
174
|
+
throw new Error(`Gavel answered ${res.status} to which plan this agent is on`);
|
|
175
|
+
const body = (await res.json());
|
|
176
|
+
plan = { id: typeof body?.planId === "string" ? body.planId : null, at: now() };
|
|
177
|
+
return plan.id;
|
|
178
|
+
};
|
|
179
|
+
const send = async () => {
|
|
180
|
+
timer = null;
|
|
181
|
+
if (sending || closed || !latest || !changed(sent, latest))
|
|
182
|
+
return;
|
|
183
|
+
sending = true;
|
|
184
|
+
triedAt = now();
|
|
185
|
+
const usage = latest;
|
|
186
|
+
try {
|
|
187
|
+
const id = await planId();
|
|
188
|
+
if (!id)
|
|
189
|
+
return sayOnce("Claude Code's plan use isn't sent: no plan in Gavel names this agent (link it under Settings › You › Plans).");
|
|
190
|
+
const account = claudeAccount(opts.home, opts.env);
|
|
191
|
+
if (!account)
|
|
192
|
+
return sayOnce("Claude Code's plan use isn't sent: no Claude account is signed in here.");
|
|
193
|
+
const first = readAccounts(opts.home)[id];
|
|
194
|
+
if (first && first !== account)
|
|
195
|
+
return sayOnce("Claude Code's plan use isn't sent: another Claude account is signed in than the one this plan was first read from. Link that account's plan in Gavel (Settings › You › Plans), or sign back in.");
|
|
196
|
+
const res = await opts.request("POST", "/v1/agents/me/plan/usage", usageBody(id, usage, new Date(now())));
|
|
197
|
+
void res.body?.cancel();
|
|
198
|
+
if (res.status === 403 || res.status === 404 || res.status === 409) {
|
|
199
|
+
plan = null;
|
|
200
|
+
return sayOnce(`Claude Code's plan use isn't sent: Gavel answered ${res.status} for this agent's plan; it looks again in a few minutes.`);
|
|
201
|
+
}
|
|
202
|
+
if (!res.ok)
|
|
203
|
+
return sayOnce(`Claude Code's plan use isn't sent: Gavel answered ${res.status}; it tries again with the next figures.`);
|
|
204
|
+
if (!first)
|
|
205
|
+
keepAccount(opts.home, id, account);
|
|
206
|
+
sent = usage;
|
|
207
|
+
sayOnce("Claude Code's plan use goes to Gavel, for you alone.");
|
|
208
|
+
}
|
|
209
|
+
catch (err) {
|
|
210
|
+
sayOnce(`Claude Code's plan use isn't sent: ${err instanceof Error ? err.message : String(err)}`);
|
|
211
|
+
}
|
|
212
|
+
finally {
|
|
213
|
+
sending = false;
|
|
214
|
+
// Figures that came while it sent go next, a minute after.
|
|
215
|
+
if (sent === usage && latest !== usage)
|
|
216
|
+
schedule();
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
const schedule = () => {
|
|
220
|
+
if (closed || timer || sending || !latest || !changed(sent, latest))
|
|
221
|
+
return;
|
|
222
|
+
timer = setTimeout(() => void send(), Math.max(0, triedAt + every - now()));
|
|
223
|
+
timer.unref?.();
|
|
224
|
+
};
|
|
225
|
+
return {
|
|
226
|
+
observe(usage) {
|
|
227
|
+
if (closed)
|
|
228
|
+
return;
|
|
229
|
+
latest = usage;
|
|
230
|
+
schedule();
|
|
231
|
+
},
|
|
232
|
+
close() {
|
|
233
|
+
closed = true;
|
|
234
|
+
if (timer)
|
|
235
|
+
clearTimeout(timer);
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
}
|
package/dist/bridge/codex-app.js
CHANGED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { hostname } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
const countKeys = ["inputTokens", "cacheWriteTokens", "cacheReadTokens", "outputTokens"];
|
|
6
|
+
const zero = () => ({ inputTokens: 0, cacheWriteTokens: 0, cacheReadTokens: 0, outputTokens: 0 });
|
|
7
|
+
export function codexCounts(value) {
|
|
8
|
+
if (!value || typeof value !== "object")
|
|
9
|
+
return null;
|
|
10
|
+
const { inputTokens, cachedInputTokens, outputTokens } = value;
|
|
11
|
+
if (typeof inputTokens !== "number" || typeof cachedInputTokens !== "number" || typeof outputTokens !== "number")
|
|
12
|
+
return null;
|
|
13
|
+
if (![inputTokens, cachedInputTokens, outputTokens].every((count) => Number.isSafeInteger(count) && count >= 0))
|
|
14
|
+
return null;
|
|
15
|
+
return { inputTokens: Math.max(0, inputTokens - cachedInputTokens), cacheReadTokens: cachedInputTokens, outputTokens, cacheWriteTokens: 0 };
|
|
16
|
+
}
|
|
17
|
+
export function codexWindows(snapshot) {
|
|
18
|
+
const buckets = Object.entries(snapshot.rateLimitsByLimitId ?? {});
|
|
19
|
+
if (!buckets.length && snapshot.rateLimits)
|
|
20
|
+
buckets.push(["codex", snapshot.rateLimits]);
|
|
21
|
+
const windows = new Map();
|
|
22
|
+
for (const [key, bucket] of buckets) {
|
|
23
|
+
if (!bucket || typeof bucket !== "object")
|
|
24
|
+
continue;
|
|
25
|
+
const limitId = typeof bucket.limitId === "string" ? bucket.limitId : key;
|
|
26
|
+
if (!/^[a-z0-9_-]{1,64}$/i.test(limitId))
|
|
27
|
+
continue;
|
|
28
|
+
for (const value of [bucket.primary, bucket.secondary]) {
|
|
29
|
+
if (!value || typeof value !== "object")
|
|
30
|
+
continue;
|
|
31
|
+
const { windowDurationMins, usedPercent, resetsAt } = value;
|
|
32
|
+
if (typeof windowDurationMins !== "number" || !Number.isInteger(windowDurationMins) || windowDurationMins < 1 || windowDurationMins > 100_800)
|
|
33
|
+
continue;
|
|
34
|
+
if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent) || usedPercent < 0 || usedPercent > 10_000)
|
|
35
|
+
continue;
|
|
36
|
+
if (typeof resetsAt !== "number" || !Number.isFinite(resetsAt) || resetsAt <= 0 || resetsAt > 253402300799)
|
|
37
|
+
continue;
|
|
38
|
+
windows.set(`${limitId}:${windowDurationMins}`, {
|
|
39
|
+
limitId, durationMinutes: windowDurationMins, usedPercent, resetsAt: new Date(resetsAt * 1000).toISOString(),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return [...windows.values()].slice(0, 32);
|
|
44
|
+
}
|
|
45
|
+
async function accountOf(app) {
|
|
46
|
+
const { account } = await app.request("account/read", { refreshToken: false });
|
|
47
|
+
return account?.type === "chatgpt" && typeof account.email === "string" ? account.email.trim().toLowerCase() : null;
|
|
48
|
+
}
|
|
49
|
+
function boundAccount(home, planId, account) {
|
|
50
|
+
if (!/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(planId))
|
|
51
|
+
return false;
|
|
52
|
+
const dir = join(home, ".gavel", "plan-accounts");
|
|
53
|
+
const file = join(dir, `codex-${planId}`);
|
|
54
|
+
const fingerprint = createHash("sha256").update(planId).update("\0").update(account).digest("hex");
|
|
55
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
56
|
+
try {
|
|
57
|
+
writeFileSync(file, fingerprint, { mode: 0o600, flag: "wx" });
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
if (err.code !== "EEXIST")
|
|
61
|
+
throw err;
|
|
62
|
+
}
|
|
63
|
+
return readFileSync(file, "utf8") === fingerprint;
|
|
64
|
+
}
|
|
65
|
+
const MINUTE = 60_000;
|
|
66
|
+
const localDate = (date) => [date.getFullYear(), String(date.getMonth() + 1).padStart(2, "0"), String(date.getDate()).padStart(2, "0")].join("-");
|
|
67
|
+
export class CodexPlanUsage {
|
|
68
|
+
home;
|
|
69
|
+
cwd;
|
|
70
|
+
reporter;
|
|
71
|
+
checking = false;
|
|
72
|
+
accountRevision = 0;
|
|
73
|
+
confirmedPlan = null;
|
|
74
|
+
pendingApp = null;
|
|
75
|
+
quotaTimer = null;
|
|
76
|
+
dayTimer = null;
|
|
77
|
+
nextQuota = 0;
|
|
78
|
+
nextDay = 0;
|
|
79
|
+
lastWindows = "";
|
|
80
|
+
warned = new Set();
|
|
81
|
+
totals = new Map();
|
|
82
|
+
pendingDays = new Map();
|
|
83
|
+
sendingDays = false;
|
|
84
|
+
constructor(home, cwd, reporter) {
|
|
85
|
+
this.home = home;
|
|
86
|
+
this.cwd = cwd;
|
|
87
|
+
this.reporter = reporter;
|
|
88
|
+
}
|
|
89
|
+
once(key, line) {
|
|
90
|
+
if (this.warned.has(key))
|
|
91
|
+
return;
|
|
92
|
+
this.warned.add(key);
|
|
93
|
+
console.error(line);
|
|
94
|
+
}
|
|
95
|
+
source() {
|
|
96
|
+
const folder = createHash("sha256").update(this.cwd).digest("hex").slice(0, 16);
|
|
97
|
+
const path = join(this.home, ".gavel", "plan-accounts", `source-${folder}`);
|
|
98
|
+
try {
|
|
99
|
+
writeFileSync(path, randomUUID(), { mode: 0o600, flag: "wx" });
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
if (err.code !== "EEXIST")
|
|
103
|
+
throw err;
|
|
104
|
+
}
|
|
105
|
+
return { folder, sourceId: readFileSync(path, "utf8") };
|
|
106
|
+
}
|
|
107
|
+
observe(thread, usage, count) {
|
|
108
|
+
if (!usage || typeof usage !== "object")
|
|
109
|
+
return;
|
|
110
|
+
const raw = usage;
|
|
111
|
+
const total = codexCounts(raw.total);
|
|
112
|
+
if (!total)
|
|
113
|
+
return;
|
|
114
|
+
const before = this.totals.get(thread);
|
|
115
|
+
this.totals.set(thread, total);
|
|
116
|
+
const planId = this.confirmedPlan;
|
|
117
|
+
if (!count || !planId)
|
|
118
|
+
return;
|
|
119
|
+
const delta = before ? zero() : codexCounts(raw.last);
|
|
120
|
+
if (!delta)
|
|
121
|
+
return;
|
|
122
|
+
if (before)
|
|
123
|
+
for (const key of countKeys)
|
|
124
|
+
delta[key] = Math.max(0, total[key] - before[key]);
|
|
125
|
+
if (countKeys.every((key) => delta[key] === 0))
|
|
126
|
+
return;
|
|
127
|
+
try {
|
|
128
|
+
const date = localDate(new Date());
|
|
129
|
+
const { folder, sourceId } = this.source();
|
|
130
|
+
const file = join(this.home, ".gavel", "plan-accounts", `codex-${planId}-${folder}-${date}.json`);
|
|
131
|
+
let sum = zero();
|
|
132
|
+
try {
|
|
133
|
+
sum = JSON.parse(readFileSync(file, "utf8"));
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
if (err.code !== "ENOENT")
|
|
137
|
+
throw err;
|
|
138
|
+
}
|
|
139
|
+
for (const key of countKeys)
|
|
140
|
+
sum[key] += delta[key];
|
|
141
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
142
|
+
writeFileSync(temp, JSON.stringify(sum), { mode: 0o600 });
|
|
143
|
+
renameSync(temp, file);
|
|
144
|
+
this.pendingDays.set(`${planId}:${date}`, { planId, date, sourceId, ...sum });
|
|
145
|
+
this.scheduleDay();
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
this.once("day-storage", "Gavel could not store local Codex usage counts.");
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
scheduleDay() {
|
|
152
|
+
if (this.dayTimer || this.sendingDays || !this.pendingDays.size)
|
|
153
|
+
return;
|
|
154
|
+
this.dayTimer = setTimeout(() => {
|
|
155
|
+
this.dayTimer = null;
|
|
156
|
+
void this.flushDay();
|
|
157
|
+
}, Math.max(0, this.nextDay - Date.now()));
|
|
158
|
+
this.dayTimer.unref();
|
|
159
|
+
}
|
|
160
|
+
async flushDay() {
|
|
161
|
+
if (this.sendingDays || !this.pendingDays.size)
|
|
162
|
+
return;
|
|
163
|
+
if (this.dayTimer)
|
|
164
|
+
clearTimeout(this.dayTimer);
|
|
165
|
+
this.dayTimer = null;
|
|
166
|
+
this.sendingDays = true;
|
|
167
|
+
this.nextDay = Date.now() + MINUTE;
|
|
168
|
+
try {
|
|
169
|
+
for (const [key, day] of this.pendingDays) {
|
|
170
|
+
if (day.planId !== await this.reporter.linked()) {
|
|
171
|
+
this.pendingDays.delete(key);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
await this.reporter.day(day);
|
|
175
|
+
if (this.pendingDays.get(key) === day)
|
|
176
|
+
this.pendingDays.delete(key);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
this.once("day-refused", "Gavel could not record Codex's daily usage. The bridge will retry.");
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
this.sendingDays = false;
|
|
184
|
+
this.scheduleDay();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
refresh(app, accountChanged = false) {
|
|
188
|
+
if (accountChanged) {
|
|
189
|
+
this.accountRevision++;
|
|
190
|
+
this.confirmedPlan = null;
|
|
191
|
+
this.totals.clear();
|
|
192
|
+
}
|
|
193
|
+
this.pendingApp = app;
|
|
194
|
+
this.scheduleQuota();
|
|
195
|
+
}
|
|
196
|
+
scheduleQuota() {
|
|
197
|
+
if (this.quotaTimer || this.checking || !this.pendingApp)
|
|
198
|
+
return;
|
|
199
|
+
this.quotaTimer = setTimeout(() => {
|
|
200
|
+
this.quotaTimer = null;
|
|
201
|
+
void this.readQuota();
|
|
202
|
+
}, Math.max(0, this.nextQuota - Date.now()));
|
|
203
|
+
this.quotaTimer.unref();
|
|
204
|
+
}
|
|
205
|
+
async readQuota() {
|
|
206
|
+
const app = this.pendingApp;
|
|
207
|
+
if (!app)
|
|
208
|
+
return;
|
|
209
|
+
this.pendingApp = null;
|
|
210
|
+
this.checking = true;
|
|
211
|
+
const revision = this.accountRevision;
|
|
212
|
+
this.nextQuota = Date.now() + MINUTE;
|
|
213
|
+
try {
|
|
214
|
+
const planId = await this.reporter.linked();
|
|
215
|
+
if (!planId) {
|
|
216
|
+
this.confirmedPlan = null;
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const account = await accountOf(app);
|
|
220
|
+
if (!account || !boundAccount(this.home, planId, account)) {
|
|
221
|
+
this.confirmedPlan = null;
|
|
222
|
+
if (account)
|
|
223
|
+
this.once(planId, "Gavel plan usage paused: Codex switched accounts. Link the active plan in Settings.");
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
const snapshot = await app.request("account/rateLimits/read");
|
|
227
|
+
if (await accountOf(app) !== account || revision !== this.accountRevision)
|
|
228
|
+
return;
|
|
229
|
+
this.confirmedPlan = planId;
|
|
230
|
+
const windows = codexWindows(snapshot);
|
|
231
|
+
if (!windows.length)
|
|
232
|
+
return;
|
|
233
|
+
const buckets = Object.values(snapshot.rateLimitsByLimitId ?? {});
|
|
234
|
+
const limitReached = [...buckets, snapshot.rateLimits].some((bucket) => typeof bucket?.rateLimitReachedType === "string");
|
|
235
|
+
const signature = JSON.stringify([planId, windows.map((w) => ({ ...w, usedPercent: Math.floor(w.usedPercent) })), limitReached]);
|
|
236
|
+
if (signature === this.lastWindows)
|
|
237
|
+
return;
|
|
238
|
+
const machineName = hostname().replace(/\p{Cc}/gu, "").slice(0, 64) || "Codex";
|
|
239
|
+
await this.reporter.record({ planId, windows, observedAt: new Date().toISOString(), machineName, ...(limitReached ? { limitReached: true } : {}) });
|
|
240
|
+
this.lastWindows = signature;
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
this.once("quota-refused", "Gavel could not read or record Codex plan usage. The bridge will retry.");
|
|
244
|
+
if (revision === this.accountRevision)
|
|
245
|
+
this.pendingApp ??= app;
|
|
246
|
+
}
|
|
247
|
+
finally {
|
|
248
|
+
this.checking = false;
|
|
249
|
+
this.scheduleQuota();
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
disconnect() {
|
|
253
|
+
this.accountRevision++;
|
|
254
|
+
this.confirmedPlan = null;
|
|
255
|
+
this.pendingApp = null;
|
|
256
|
+
this.totals.clear();
|
|
257
|
+
if (this.quotaTimer)
|
|
258
|
+
clearTimeout(this.quotaTimer);
|
|
259
|
+
this.quotaTimer = null;
|
|
260
|
+
}
|
|
261
|
+
}
|
package/dist/bridge/codex.js
CHANGED
|
@@ -5,6 +5,7 @@ import { basename, join } from "node:path";
|
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
6
|
import { cliVersion, withCodexHooks, writeWhole } from "../hook.js";
|
|
7
7
|
import { connectCodex, controlSocket, startCodexServer } from "./codex-app.js";
|
|
8
|
+
import { CodexPlanUsage } from "./codex-plan.js";
|
|
8
9
|
import { codexSetups } from "./setup.js";
|
|
9
10
|
import { WebSocketError } from "./websocket.js";
|
|
10
11
|
import { cut } from "./words.js";
|
|
@@ -180,8 +181,11 @@ class CodexHarness {
|
|
|
180
181
|
state = null;
|
|
181
182
|
stoppedAt = 0;
|
|
182
183
|
started = null;
|
|
184
|
+
planTurns = new Set();
|
|
185
|
+
planUsage;
|
|
183
186
|
constructor(ctx) {
|
|
184
187
|
this.ctx = ctx;
|
|
188
|
+
this.planUsage = ctx.planReporter ? new CodexPlanUsage(ctx.home, ctx.cwd, ctx.planReporter) : null;
|
|
185
189
|
}
|
|
186
190
|
here(cwd) {
|
|
187
191
|
return cwd === this.ctx.cwd || realpath(cwd) === realpath(this.ctx.cwd);
|
|
@@ -227,10 +231,12 @@ class CodexHarness {
|
|
|
227
231
|
app = await connectCodex(socket, handlers, cliVersion());
|
|
228
232
|
}
|
|
229
233
|
this.app = app;
|
|
234
|
+
this.planUsage?.refresh(app, true);
|
|
230
235
|
void app.closed.then(() => {
|
|
231
236
|
if (this.app !== app)
|
|
232
237
|
return;
|
|
233
238
|
this.app = null;
|
|
239
|
+
this.planUsage?.disconnect();
|
|
234
240
|
if (this.current)
|
|
235
241
|
this.current.subscribed = false;
|
|
236
242
|
this.turnId = null;
|
|
@@ -303,6 +309,10 @@ class CodexHarness {
|
|
|
303
309
|
return { thread: `codex:${current.id}`, label: this.label(), session: current.id, messages: [...this.words.values()].sort((a, b) => a.at.localeCompare(b.at)) };
|
|
304
310
|
}
|
|
305
311
|
notified(method, params) {
|
|
312
|
+
if (this.app && (method === "account/rateLimits/updated" || method === "account/updated")) {
|
|
313
|
+
this.planUsage?.refresh(this.app, method === "account/updated");
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
306
316
|
const threadId = typeof params.threadId === "string" ? params.threadId : null;
|
|
307
317
|
if (method === "thread/started") {
|
|
308
318
|
const thread = params.thread;
|
|
@@ -314,6 +324,10 @@ class CodexHarness {
|
|
|
314
324
|
if (!current || threadId !== current.id)
|
|
315
325
|
return;
|
|
316
326
|
switch (method) {
|
|
327
|
+
case "thread/tokenUsage/updated":
|
|
328
|
+
if (this.app)
|
|
329
|
+
this.planUsage?.observe(current.id, params.tokenUsage, typeof params.turnId === "string" && this.planTurns.has(params.turnId));
|
|
330
|
+
return;
|
|
317
331
|
case "thread/status/changed":
|
|
318
332
|
current.status = params.status;
|
|
319
333
|
this.setState(stateOf(current.status));
|
|
@@ -334,6 +348,8 @@ class CodexHarness {
|
|
|
334
348
|
const item = params.item;
|
|
335
349
|
if (item.type === "agentMessage")
|
|
336
350
|
this.offsets.set(item.id, 0);
|
|
351
|
+
if (item.type === "userMessage" && item.clientId?.startsWith("gavel") && typeof params.turnId === "string")
|
|
352
|
+
this.planTurns.add(params.turnId);
|
|
337
353
|
// Someone typed at the laptop: the session has its person there now.
|
|
338
354
|
if (item.type === "userMessage" && !item.clientId?.startsWith("gavel"))
|
|
339
355
|
this.ownLoaded.delete(current.id);
|
|
@@ -370,6 +386,8 @@ class CodexHarness {
|
|
|
370
386
|
if (turn.status === "failed" && this.unattended.has(turn.id))
|
|
371
387
|
this.listener?.note(`Codex couldn't finish: ${turn.error?.message ?? "the turn failed"}`.slice(0, 300));
|
|
372
388
|
this.unattended.delete(turn.id);
|
|
389
|
+
if (this.planTurns.delete(turn.id))
|
|
390
|
+
void this.planUsage?.flushDay();
|
|
373
391
|
this.listener?.changed();
|
|
374
392
|
if (this.announced.delete(turn.id))
|
|
375
393
|
this.listener?.live({ event: "end", runId: turn.id });
|
|
@@ -402,6 +420,8 @@ class CodexHarness {
|
|
|
402
420
|
if (wake && (this.turnId || current.status.type === "active" || Date.now() - this.stoppedAt < QUIET_AFTER_STOP_MS))
|
|
403
421
|
return "busy";
|
|
404
422
|
const { turn } = await app.request("turn/start", { threadId: current.id, input, clientUserMessageId });
|
|
423
|
+
if (turn.status === "inProgress")
|
|
424
|
+
this.planTurns.add(turn.id);
|
|
405
425
|
if (this.ownLoaded.has(current.id))
|
|
406
426
|
this.unattended.add(turn.id);
|
|
407
427
|
return "in";
|
|
@@ -467,6 +487,7 @@ class CodexHarness {
|
|
|
467
487
|
// Codex's session is heard through its server, whatever the chat: nothing to put in or take out.
|
|
468
488
|
}
|
|
469
489
|
async close() {
|
|
490
|
+
this.planUsage?.disconnect();
|
|
470
491
|
this.app?.close();
|
|
471
492
|
this.app = null;
|
|
472
493
|
}
|
package/dist/gavel.js
CHANGED
|
@@ -9,7 +9,7 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
9
9
|
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
|
|
10
10
|
import { homedir, hostname } from "node:os";
|
|
11
11
|
import { basename, dirname, extname, join } from "node:path";
|
|
12
|
-
import { bridgeStatus, harnessFor, holdBridge, hookEvent, lastingCommand, startBridge, stopBridge } from "./bridge/background.js";
|
|
12
|
+
import { bridgeStatus, bridgeStatusLine, harnessFor, holdBridge, hookEvent, lastingCommand, startBridge, stopBridge } from "./bridge/background.js";
|
|
13
13
|
import { claudeBridgeHooks, claudeHeld, gavelPluginOn } from "./bridge/claude-live.js";
|
|
14
14
|
import { codexBridgeHooks } from "./bridge/codex.js";
|
|
15
15
|
import { claudeSetups } from "./bridge/setup.js";
|
|
@@ -47,6 +47,9 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
|
|
|
47
47
|
gavel bridge event <name> [--harness claude-code|codex] [--server <name>]
|
|
48
48
|
a hook's event for this folder's bridge, its input on stdin
|
|
49
49
|
(run by the hook, not by hand); prints nothing, exits 0
|
|
50
|
+
gavel bridge status-line Claude Code's status line in a folder with the bridge's
|
|
51
|
+
hooks (run by Claude Code, not by hand): your plan's use to
|
|
52
|
+
the bridge, then your own status line, as it prints it
|
|
50
53
|
gavel bridge service install|remove|status [--harness claude-code|codex] [--server <name>]
|
|
51
54
|
the bridge for this folder kept running by the system (a
|
|
52
55
|
LaunchAgent on a Mac, systemd on Linux), so a closed
|
|
@@ -1081,6 +1084,10 @@ export function toRequest(argv) {
|
|
|
1081
1084
|
throw new UsageError(`"${name}" isn't a hook's event`);
|
|
1082
1085
|
return { bridgeBackground: { action, harness, server: f.server, name } };
|
|
1083
1086
|
}
|
|
1087
|
+
if (action === "status-line") {
|
|
1088
|
+
upTo(1);
|
|
1089
|
+
return { bridgeBackground: { action, harness: "claude-code", server: f.server } };
|
|
1090
|
+
}
|
|
1084
1091
|
if (action === "service" || action === "hooks") {
|
|
1085
1092
|
upTo(2);
|
|
1086
1093
|
const what = need(p[1], "install, remove or status");
|
|
@@ -1706,6 +1713,8 @@ async function background(run) {
|
|
|
1706
1713
|
const cwd = process.cwd();
|
|
1707
1714
|
const env = process.env;
|
|
1708
1715
|
const print = (answer) => console.log(JSON.stringify(answer, null, 2));
|
|
1716
|
+
if (run.action === "status-line")
|
|
1717
|
+
return bridgeStatusLine({ home, cwd, env });
|
|
1709
1718
|
if (run.action === "hooks") {
|
|
1710
1719
|
// A folder whose harness can't be told is Claude Code's to answer, refusal and all.
|
|
1711
1720
|
let which = run.harness ?? "claude-code";
|
package/package.json
CHANGED