@getgavel/cli 0.1.27 → 0.1.29
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 +6 -4
- package/dist/bridge/bridge.js +173 -13
- package/dist/bridge/claude-days.js +11 -5
- package/dist/bridge/claude-live.js +21 -7
- package/dist/bridge/codex-plan.js +24 -5
- package/dist/bridge/codex.js +62 -7
- package/dist/bridge/connect.js +232 -0
- package/dist/bridge/plan-profiles.js +171 -0
- package/dist/bridge/runtime.js +29 -0
- package/dist/gavel.js +33 -1
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gavel",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.29",
|
|
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" },
|
|
@@ -418,13 +418,15 @@ export async function hookEvent(opts) {
|
|
|
418
418
|
input,
|
|
419
419
|
inbox: socket ? { socket, token: opts.env.CLAUDE_CODE_MESSAGING_TOKEN || null } : null,
|
|
420
420
|
at: Date.now(),
|
|
421
|
+
...(opts.env.GAVEL_PLAN_PROFILE ? { planId: opts.env.GAVEL_PLAN_PROFILE } : {}),
|
|
421
422
|
};
|
|
422
|
-
|
|
423
|
+
const ownerHarness = opts.env.GAVEL_BRIDGE_OWNER_HARNESS === "codex" ? "codex" : opts.harness;
|
|
424
|
+
let live = runningBridge(opts.home, cwd, ownerHarness);
|
|
423
425
|
// Hooks a plugin or the user's settings give every folder start a bridge only where this
|
|
424
426
|
// harness has a Gavel agent set up.
|
|
425
427
|
const setUp = (opts.harness === "codex" ? codexSetups(cwd, opts.home, opts.env) : claudeSetups(cwd, opts.home)).some((s) => s.where.endsWith("this folder"));
|
|
426
428
|
const looksAgain = opts.name === "SessionStart" || !offRecently(opts.home, cwd, opts.harness);
|
|
427
|
-
if (!live && setUp && STARTS.has(opts.name) && looksAgain) {
|
|
429
|
+
if (!live && !opts.env.GAVEL_PLAN_PROFILE && setUp && STARTS.has(opts.name) && looksAgain) {
|
|
428
430
|
const started = await startBridge({ home: opts.home, cwd, harness: opts.harness, server: opts.server, untilClosed: true, env: opts.env });
|
|
429
431
|
if (started.bridge !== "failed")
|
|
430
432
|
live = runningBridge(opts.home, cwd, opts.harness);
|
|
@@ -506,11 +508,11 @@ export async function bridgeStatusLine(opts) {
|
|
|
506
508
|
const usage = statusLineUsage(input);
|
|
507
509
|
const handed = (async () => {
|
|
508
510
|
try {
|
|
509
|
-
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;
|
|
510
512
|
// The account is read here, with the session's own environment (its CLAUDE_CONFIG_DIR), not
|
|
511
513
|
// the bridge's: handed over as its hash alone, beside the figures.
|
|
512
514
|
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`);
|
|
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`);
|
|
514
516
|
}
|
|
515
517
|
catch {
|
|
516
518
|
// never the status line's failure
|
package/dist/bridge/bridge.js
CHANGED
|
@@ -5,10 +5,12 @@ 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
7
|
import { claudeDayReporter, DAYS_EVERY_MS } from "./claude-days.js";
|
|
8
|
-
import { accountOf, claudePlanReporter, planUsageOf } from "./claude-plan.js";
|
|
8
|
+
import { accountOf, claudePlanReporter, planUsageOf, usageBody } from "./claude-plan.js";
|
|
9
9
|
import { claudeSessions } from "./claude-code.js";
|
|
10
10
|
import { ClaudeCodeHarness } from "./claude-live.js";
|
|
11
11
|
import { codexHarness, codexSessions } from "./codex.js";
|
|
12
|
+
import { planEnvironment, planIdPattern, planMachine, rememberPlanSession } from "./plan-profiles.js";
|
|
13
|
+
import { runOf } from "./runtime.js";
|
|
12
14
|
import { apiFor, claudeSetups, codexSetups } from "./setup.js";
|
|
13
15
|
// `gavel bridge` (D-905): run by a person on their laptop, in the folder where their agent works
|
|
14
16
|
// (Claude Code or Codex), beside it. It shows the newest session's words in the person's Gavel chat
|
|
@@ -128,7 +130,9 @@ async function bridge(run, ctx) {
|
|
|
128
130
|
day: (input) => report("PUT", "/v1/agents/me/plan/days", input),
|
|
129
131
|
record: (input) => report("POST", "/v1/agents/me/plan/usage", input),
|
|
130
132
|
};
|
|
131
|
-
|
|
133
|
+
const managed = !!planMachine(ctx.home);
|
|
134
|
+
const bridgeContext = { ...ctx, planReporter: managed ? undefined : planReporter };
|
|
135
|
+
return harnessBridge(harnessOf(harness, bridgeContext), harness, setup, bridgeContext);
|
|
132
136
|
}
|
|
133
137
|
const PICTURE_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp" };
|
|
134
138
|
const PICTURE_MAX = 15 * 1024 * 1024;
|
|
@@ -178,8 +182,16 @@ async function answer(res) {
|
|
|
178
182
|
// The Gavel side for a harness: the one peek (presence, the person's messages, Stop), their messages
|
|
179
183
|
// put in beside it with their pictures, the session's words kept (the transcript) and shown as written
|
|
180
184
|
// (live), its state, and wakes for what waits in Gavel.
|
|
181
|
-
async function harnessBridge(
|
|
185
|
+
async function harnessBridge(initial, harness, setup, ctx) {
|
|
182
186
|
const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
|
|
187
|
+
let h = initial;
|
|
188
|
+
const machineId = planMachine(ctx.home);
|
|
189
|
+
let activeHarness = harness;
|
|
190
|
+
let activePlan = null;
|
|
191
|
+
let activeEnv = ctx.env;
|
|
192
|
+
let retryPlanAt = 0;
|
|
193
|
+
let lastManagedUsage = 0;
|
|
194
|
+
let lastManagedWindows = "";
|
|
183
195
|
const me = await whoAmI(api, setup);
|
|
184
196
|
if (h instanceof ClaudeCodeHarness)
|
|
185
197
|
h.setPerson(me.person.name);
|
|
@@ -355,11 +367,22 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
355
367
|
}
|
|
356
368
|
return { paths, missed };
|
|
357
369
|
};
|
|
370
|
+
let launchQueue = Promise.resolve();
|
|
371
|
+
const launch = (run) => {
|
|
372
|
+
const chosen = launchQueue.then(run);
|
|
373
|
+
launchQueue = chosen.then(() => undefined, () => undefined);
|
|
374
|
+
return chosen;
|
|
375
|
+
};
|
|
358
376
|
const deliver = async (m) => {
|
|
359
377
|
try {
|
|
360
378
|
const { paths, missed } = await fetchPictures(m.images ?? []);
|
|
361
379
|
urgentUntil = Date.now() + PUSH_URGENT_MS;
|
|
362
|
-
const result = await
|
|
380
|
+
const result = await launch(async () => {
|
|
381
|
+
const route = await pick(null, "chat");
|
|
382
|
+
return route.allowed ? h.deliver({ id: m.id, text: m.text, decision: m.decision, pictures: paths }, route.fresh, route.run) : null;
|
|
383
|
+
});
|
|
384
|
+
if (!result)
|
|
385
|
+
return;
|
|
363
386
|
if (result.outcome === "left") {
|
|
364
387
|
if (!left.has(m.id))
|
|
365
388
|
say(result.say);
|
|
@@ -423,6 +446,102 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
423
446
|
return { waiting: true, fresh: null };
|
|
424
447
|
}
|
|
425
448
|
};
|
|
449
|
+
const busy = () => state === "working" || state === "waiting";
|
|
450
|
+
// What a run about to start goes with (W-249): the model, effort and context Gavel's router or an
|
|
451
|
+
// override chose for the agent's kind of job. A session already open takes none, nor does one the
|
|
452
|
+
// bridge keeps going; a Gavel with no such route, or an agent not on a bridge harness, none either.
|
|
453
|
+
const pick = async (fresh, job = "wake") => {
|
|
454
|
+
const kind = fresh?.per === "item" ? "work" : job;
|
|
455
|
+
const chosen = await pickPlan(fresh, job);
|
|
456
|
+
if (!chosen.allowed || busy() || (!chosen.fresh && thread && state === "idle"))
|
|
457
|
+
return chosen;
|
|
458
|
+
const res = await call(api, "GET", `/v1/agents/me/runtime?job=${kind}`).catch(() => null);
|
|
459
|
+
if (!res?.ok) {
|
|
460
|
+
void res?.body?.cancel();
|
|
461
|
+
return chosen;
|
|
462
|
+
}
|
|
463
|
+
const run = runOf(await answer(res));
|
|
464
|
+
if (!run)
|
|
465
|
+
return chosen;
|
|
466
|
+
const mine = { model: run.harness === activeHarness ? run.model : null, effort: run.effort, context: run.context };
|
|
467
|
+
return { allowed: true, fresh: chosen.fresh ? { ...chosen.fresh, ...mine } : null, run: mine };
|
|
468
|
+
};
|
|
469
|
+
const pickPlan = async (fresh, job = "wake") => {
|
|
470
|
+
if (!machineId || busy() || (!fresh && thread && state === "idle"))
|
|
471
|
+
return { allowed: true, fresh };
|
|
472
|
+
if (state === null)
|
|
473
|
+
await h.newest().catch(() => null);
|
|
474
|
+
if (busy())
|
|
475
|
+
return { allowed: true, fresh };
|
|
476
|
+
if (Date.now() < retryPlanAt)
|
|
477
|
+
return { allowed: false, fresh };
|
|
478
|
+
const res = await call(api, "POST", "/v1/agents/me/plan/pick", { machineId, harness: activeHarness, job });
|
|
479
|
+
if (res.status === 404)
|
|
480
|
+
return { allowed: true, fresh };
|
|
481
|
+
const route = res.ok ? await answer(res) : null;
|
|
482
|
+
if (route?.why === "unmanaged")
|
|
483
|
+
return { allowed: true, fresh };
|
|
484
|
+
if (route?.why === "wait") {
|
|
485
|
+
const reset = route.resetsAt ? Date.parse(route.resetsAt) : Number.NaN;
|
|
486
|
+
retryPlanAt = Number.isFinite(reset) ? Math.min(reset, Date.now() + 60_000) : Date.now() + 60_000;
|
|
487
|
+
const at = Number.isFinite(reset) ? new Date(reset).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : null;
|
|
488
|
+
const words = `Waiting for your ${activeHarness === "codex" ? "ChatGPT" : "Claude"} plans${at ? `, back at ${at}.` : ". Reset time unavailable."}`;
|
|
489
|
+
if (words !== trouble)
|
|
490
|
+
void note(words);
|
|
491
|
+
complain(words);
|
|
492
|
+
return { allowed: false, fresh };
|
|
493
|
+
}
|
|
494
|
+
const selected = route?.planId;
|
|
495
|
+
const nextHarness = route?.harness;
|
|
496
|
+
if (!selected || !planIdPattern.test(selected) || (nextHarness !== "codex" && nextHarness !== "claude-code")) {
|
|
497
|
+
retryPlanAt = Date.now() + 30_000;
|
|
498
|
+
complain("No signed-in plan is available for a fresh session on this machine.");
|
|
499
|
+
return { allowed: false, fresh };
|
|
500
|
+
}
|
|
501
|
+
const env = planEnvironment(ctx, selected, nextHarness);
|
|
502
|
+
if (!env) {
|
|
503
|
+
retryPlanAt = Date.now() + 30_000;
|
|
504
|
+
complain("Gavel selected a plan whose local profile is missing. Run gavel plans sign-in for that plan.");
|
|
505
|
+
return { allowed: false, fresh };
|
|
506
|
+
}
|
|
507
|
+
if (activePlan !== selected || activeHarness !== nextHarness) {
|
|
508
|
+
const previous = h;
|
|
509
|
+
env.GAVEL_BRIDGE_OWNER_HARNESS = harness;
|
|
510
|
+
activeHarness = nextHarness;
|
|
511
|
+
activePlan = selected;
|
|
512
|
+
activeEnv = env;
|
|
513
|
+
lastManagedUsage = 0;
|
|
514
|
+
lastManagedWindows = "";
|
|
515
|
+
const reporter = {
|
|
516
|
+
linked: async () => selected,
|
|
517
|
+
async hit(resetsAt) {
|
|
518
|
+
await call(api, "POST", "/v1/agents/me/plan/limit", { planId: selected, machineId, resetsAt });
|
|
519
|
+
},
|
|
520
|
+
async record(input) {
|
|
521
|
+
const result = await call(api, "POST", "/v1/agents/me/plan/usage", { ...input, machineId });
|
|
522
|
+
if (!result.ok)
|
|
523
|
+
throw new Error("Gavel refused the managed plan usage report");
|
|
524
|
+
},
|
|
525
|
+
async day(input) {
|
|
526
|
+
const result = await call(api, "PUT", "/v1/agents/me/plan/days", { ...input, machineId });
|
|
527
|
+
if (!result.ok)
|
|
528
|
+
throw new Error("Gavel refused the managed plan usage day");
|
|
529
|
+
},
|
|
530
|
+
};
|
|
531
|
+
h = harnessOf(nextHarness, { ...ctx, env, planReporter: reporter });
|
|
532
|
+
if (h instanceof ClaudeCodeHarness)
|
|
533
|
+
h.setPerson(me.person.name);
|
|
534
|
+
previous.listen({ live() { }, state() { }, changed() { }, note() { } });
|
|
535
|
+
await previous.close();
|
|
536
|
+
h.listen(listener);
|
|
537
|
+
h.setChat(!!on);
|
|
538
|
+
resetReporters(reporter);
|
|
539
|
+
}
|
|
540
|
+
const model = typeof route?.model === "string" && /^[A-Za-z0-9][\w.:[\]-]{0,79}$/.test(route.model) ? route.model : null;
|
|
541
|
+
const effort = typeof route?.effort === "string" ? route.effort : null;
|
|
542
|
+
const context = typeof route?.context === "string" ? route.context : null;
|
|
543
|
+
return { allowed: true, fresh: { per: fresh?.per ?? "batch", item: fresh?.item ?? null, brief: fresh?.brief ?? "", model: model ?? fresh?.model ?? null, effort, context } };
|
|
544
|
+
};
|
|
426
545
|
const tryWake = async () => {
|
|
427
546
|
if (waking || stopping || !pending.length)
|
|
428
547
|
return;
|
|
@@ -434,7 +553,10 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
434
553
|
return;
|
|
435
554
|
}
|
|
436
555
|
const line = wakeLineOf(pending);
|
|
437
|
-
if (await
|
|
556
|
+
if (await launch(async () => {
|
|
557
|
+
const chosen = await pick(still.fresh);
|
|
558
|
+
return chosen.allowed && await h.wake(line, chosen.fresh);
|
|
559
|
+
})) {
|
|
438
560
|
say(`Woke ${h.name} for what waits in Gavel: ${line}`);
|
|
439
561
|
pending = [];
|
|
440
562
|
}
|
|
@@ -452,7 +574,7 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
452
574
|
while (watching && !stopping) {
|
|
453
575
|
let res;
|
|
454
576
|
try {
|
|
455
|
-
res = await call(api, "GET", `/v1/inbox/watch?watch=${watchId}&timeout=50&kinds=health,claim,work,drift
|
|
577
|
+
res = await call(api, "GET", `/v1/inbox/watch?watch=${watchId}&timeout=50&kinds=health,claim,work,drift${machineId ? "" : `&planProvider=${planProvider}`}${start ? "&start=true" : ""}`);
|
|
456
578
|
}
|
|
457
579
|
catch {
|
|
458
580
|
failures++;
|
|
@@ -485,21 +607,58 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
485
607
|
};
|
|
486
608
|
const wakeTimer = setInterval(() => void tryWake(), WAKE_AGAIN_MS);
|
|
487
609
|
// Claude Code's plan use, from its status line (W-258): to the plan the agent's link names.
|
|
488
|
-
|
|
610
|
+
let plan = !machineId && harness === "claude-code" ? claudePlanReporter({ home: ctx.home, request: (method, path, body) => call(api, method, path, body), say }) : null;
|
|
489
611
|
// Its tokens for each day, summed from the agent's transcripts here (W-247, for the plan's share).
|
|
490
|
-
|
|
491
|
-
const daysTimer = days ? setInterval(() => days
|
|
612
|
+
let days = harness === "claude-code" && ctx.planReporter ? claudeDayReporter({ home: ctx.home, cwd: ctx.cwd, env: ctx.env, reporter: ctx.planReporter, say }) : null;
|
|
613
|
+
const daysTimer = days || machineId ? setInterval(() => days?.poke(), DAYS_EVERY_MS) : null;
|
|
614
|
+
const resetReporters = (reporter) => {
|
|
615
|
+
plan?.close();
|
|
616
|
+
days?.close();
|
|
617
|
+
plan = null;
|
|
618
|
+
days = activeHarness === "claude-code" ? claudeDayReporter({ home: ctx.home, cwd: ctx.cwd, env: activeEnv, reporter, say }) : null;
|
|
619
|
+
};
|
|
492
620
|
days?.poke();
|
|
493
621
|
// The harness's own hooks, through `gavel bridge event` (background.ts), and the status line's.
|
|
494
622
|
const offHooks = onHookEvent((event) => {
|
|
495
|
-
if (event.event !== STATUS_LINE_EVENT)
|
|
623
|
+
if (event.event !== STATUS_LINE_EVENT) {
|
|
624
|
+
if (activePlan && activeHarness === "claude-code" && event.planId === activePlan && event.event === "SessionStart" && typeof event.input.session_id === "string") {
|
|
625
|
+
try {
|
|
626
|
+
rememberPlanSession(ctx.home, activePlan, event.input.session_id);
|
|
627
|
+
}
|
|
628
|
+
catch {
|
|
629
|
+
say("Gavel could not record this Claude session for daily plan usage.");
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (machineId && activePlan && event.planId === activePlan && event.event === "StopFailure" && event.input.error === "rate_limit") {
|
|
633
|
+
const text = event.input.last_assistant_message;
|
|
634
|
+
if (typeof text === "string" && /(?:usage limit|hit your limit|session limit|weekly limit)/i.test(text)) {
|
|
635
|
+
const details = event.input.error_details;
|
|
636
|
+
const detailsText = typeof details === "string" ? details : "";
|
|
637
|
+
const stamp = detailsText.match(/reset(?:s|_at)?(?: at)?[: ]+([0-9]{4}-[0-9]{2}-[0-9]{2}T[^\s,;]+)/i)?.[1];
|
|
638
|
+
const reset = stamp ? Date.parse(stamp) : Number.NaN;
|
|
639
|
+
void call(api, "POST", "/v1/agents/me/plan/limit", { planId: activePlan, machineId, resetsAt: reset > Date.now() ? new Date(reset).toISOString() : null }).catch(() => undefined);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
496
642
|
return h.hook?.(event.event, event);
|
|
643
|
+
}
|
|
497
644
|
const usage = planUsageOf(event.input);
|
|
498
|
-
if (plan && usage)
|
|
645
|
+
if (plan && usage && !activePlan)
|
|
499
646
|
plan.observe(usage, accountOf(event.input));
|
|
647
|
+
if (usage && machineId && activePlan && activeHarness === "claude-code" && event.input.planId === activePlan) {
|
|
648
|
+
const now = Date.now();
|
|
649
|
+
const windows = JSON.stringify(usage.windows.map((window) => [window.kind, Math.floor(window.usedPercent), window.resetsAt]));
|
|
650
|
+
if (usage.windows.length && windows !== lastManagedWindows && now - lastManagedUsage >= 60_000) {
|
|
651
|
+
lastManagedUsage = now;
|
|
652
|
+
const planId = activePlan;
|
|
653
|
+
void call(api, "POST", "/v1/agents/me/plan/usage", { ...usageBody(planId, usage, new Date(now)), machineId }).then((result) => {
|
|
654
|
+
if (result.ok && activePlan === planId)
|
|
655
|
+
lastManagedWindows = windows;
|
|
656
|
+
}).catch(() => undefined);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
500
659
|
days?.poke();
|
|
501
660
|
});
|
|
502
|
-
|
|
661
|
+
const listener = {
|
|
503
662
|
live: (event) => {
|
|
504
663
|
if (event.event === "end")
|
|
505
664
|
days?.poke();
|
|
@@ -520,7 +679,8 @@ async function harnessBridge(h, harness, setup, ctx) {
|
|
|
520
679
|
},
|
|
521
680
|
changed: pushSoon,
|
|
522
681
|
note: (text) => void note(text),
|
|
523
|
-
}
|
|
682
|
+
};
|
|
683
|
+
h.listen(listener);
|
|
524
684
|
const timers = () => {
|
|
525
685
|
if (liveTimer)
|
|
526
686
|
clearTimeout(liveTimer);
|
|
@@ -3,6 +3,7 @@ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync,
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { claudeProjectDirs } from "./claude-code.js";
|
|
5
5
|
import { accountPin, claudeAccount } from "./claude-plan.js";
|
|
6
|
+
import { isPlanSession } from "./plan-profiles.js";
|
|
6
7
|
// Claude Code's tokens for each day (W-247, for the plan's share in W-248): the four counts the
|
|
7
8
|
// agent's own sessions in this folder used, summed here from their transcripts, once for each
|
|
8
9
|
// answer (a message id: an answer written in several parts repeats its usage) and by the laptop's
|
|
@@ -23,7 +24,7 @@ const startOfDay = (ms) => {
|
|
|
23
24
|
};
|
|
24
25
|
const whole = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? v : 0);
|
|
25
26
|
// The transcripts that can hold the last two days' answers: each session's file and its sub-agents'.
|
|
26
|
-
function transcripts(dirs, since) {
|
|
27
|
+
function transcripts(dirs, since, include) {
|
|
27
28
|
const files = [];
|
|
28
29
|
const add = (file) => {
|
|
29
30
|
try {
|
|
@@ -36,6 +37,8 @@ function transcripts(dirs, since) {
|
|
|
36
37
|
};
|
|
37
38
|
for (const dir of dirs) {
|
|
38
39
|
for (const name of readdirSync(dir)) {
|
|
40
|
+
if (!include(name.replace(/\.jsonl$/, "")))
|
|
41
|
+
continue;
|
|
39
42
|
if (name.endsWith(".jsonl"))
|
|
40
43
|
add(join(dir, name));
|
|
41
44
|
else {
|
|
@@ -53,16 +56,18 @@ function transcripts(dirs, since) {
|
|
|
53
56
|
export class DaySums {
|
|
54
57
|
dirs;
|
|
55
58
|
now;
|
|
59
|
+
include;
|
|
56
60
|
offsets = new Map();
|
|
57
61
|
answers = new Map();
|
|
58
62
|
changed = new Set();
|
|
59
|
-
constructor(dirs, now = Date.now) {
|
|
63
|
+
constructor(dirs, now = Date.now, include = () => true) {
|
|
60
64
|
this.dirs = dirs;
|
|
61
65
|
this.now = now;
|
|
66
|
+
this.include = include;
|
|
62
67
|
}
|
|
63
68
|
scan() {
|
|
64
69
|
const today = startOfDay(this.now());
|
|
65
|
-
for (const file of transcripts(this.dirs(), today - DAY_MS))
|
|
70
|
+
for (const file of transcripts(this.dirs(), today - DAY_MS, this.include))
|
|
66
71
|
this.read(file, today - DAY_MS);
|
|
67
72
|
}
|
|
68
73
|
read(file, from) {
|
|
@@ -169,7 +174,8 @@ function sourceId(home, cwd) {
|
|
|
169
174
|
export function claudeDayReporter(opts) {
|
|
170
175
|
const now = opts.now ?? Date.now;
|
|
171
176
|
const every = opts.everyMs ?? DAYS_EVERY_MS;
|
|
172
|
-
const
|
|
177
|
+
const profile = opts.env.GAVEL_PLAN_PROFILE;
|
|
178
|
+
const sums = new DaySums(() => claudeProjectDirs(opts.cwd, opts.home, opts.env), now, profile ? (id) => isPlanSession(opts.home, profile, id) : undefined);
|
|
173
179
|
let timer = null;
|
|
174
180
|
let sentAt = -Infinity;
|
|
175
181
|
let sending = false;
|
|
@@ -196,7 +202,7 @@ export function claudeDayReporter(opts) {
|
|
|
196
202
|
const planId = await opts.reporter.linked();
|
|
197
203
|
if (!planId)
|
|
198
204
|
return void sums.again(pending.map(([d]) => d));
|
|
199
|
-
const pin = accountPin(opts.home, planId, claudeAccount(opts.home, opts.env));
|
|
205
|
+
const pin = profile ? (profile === planId ? "match" : "other") : accountPin(opts.home, planId, claudeAccount(opts.home, opts.env));
|
|
200
206
|
if (pin !== "match") {
|
|
201
207
|
sums.again(pending.map(([d]) => d));
|
|
202
208
|
return sayOnce(pin === "unpinned"
|
|
@@ -8,6 +8,7 @@ import { basename, dirname, extname, join } from "node:path";
|
|
|
8
8
|
import { promisify } from "node:util";
|
|
9
9
|
import { bridgePaths, isBridgeStatusLine, ownStatusLineEntry } from "./background.js";
|
|
10
10
|
import { claudeSessions, claudeWords } from "./claude-code.js";
|
|
11
|
+
import { claudeFlags } from "./runtime.js";
|
|
11
12
|
import { claudeSetups } from "./setup.js";
|
|
12
13
|
// Claude Code live (W-132): what a session tells the bridge through its hooks, and how the bridge
|
|
13
14
|
// reaches it. Relied on, from Claude Code's docs and its 2.1.332 binary:
|
|
@@ -670,7 +671,7 @@ export class ClaudeCodeHarness {
|
|
|
670
671
|
return to;
|
|
671
672
|
});
|
|
672
673
|
}
|
|
673
|
-
async deliver(m) {
|
|
674
|
+
async deliver(m, fresh, run) {
|
|
674
675
|
const pictures = this.keepPictures(m);
|
|
675
676
|
const text = this.prompt(m, pictures);
|
|
676
677
|
let open = this.current();
|
|
@@ -686,7 +687,7 @@ export class ClaudeCodeHarness {
|
|
|
686
687
|
}
|
|
687
688
|
if (open)
|
|
688
689
|
return { outcome: "left", say: `${this.ctx.person} wrote in Gavel; your Claude Code session here is open and the bridge can't reach it yet, so it goes in at the session's next step, or once it closes.` };
|
|
689
|
-
return this.resume(m, text);
|
|
690
|
+
return this.resume(m, text, fresh, run);
|
|
690
691
|
}
|
|
691
692
|
// A closed session, resumed with the person's words as a turn of its own in the background
|
|
692
693
|
// (D-1174, changing D-905's "nothing that would prompt runs"): it runs under their own permission
|
|
@@ -694,9 +695,9 @@ export class ClaudeCodeHarness {
|
|
|
694
695
|
// edits stay in the folder, as their own session's: no worktree of its own (Master Gavel's call).
|
|
695
696
|
// The words go on stdin, never in its arguments. Delivered once Claude Code says it's backgrounded;
|
|
696
697
|
// from then the session's own hooks name it, so their next words go through its inbox.
|
|
697
|
-
async resume(m, text) {
|
|
698
|
+
async resume(m, text, fresh, run) {
|
|
698
699
|
const newest = claudeSessions(this.ctx.cwd, this.ctx.home, this.ctx.env)[0] ?? null;
|
|
699
|
-
const started = await this.background(text, { resume: newest?.id ?? null,
|
|
700
|
+
const started = await this.background(text, { resume: fresh ? null : newest?.id ?? null, run: fresh ?? run ?? null });
|
|
700
701
|
if ("reason" in started)
|
|
701
702
|
return { outcome: "failed", reason: started.reason };
|
|
702
703
|
this.remember(m.id, promptKey(text));
|
|
@@ -705,8 +706,21 @@ export class ClaudeCodeHarness {
|
|
|
705
706
|
}
|
|
706
707
|
// `claude [--resume <id>] --bg` with the words on stdin: the short id Claude Code names the
|
|
707
708
|
// background session by, or why it didn't start.
|
|
708
|
-
|
|
709
|
-
|
|
709
|
+
// A model or effort this Claude Code refuses starts the session without them, so what Gavel chose can
|
|
710
|
+
// never keep the person's message from reaching it.
|
|
711
|
+
async background(text, opts) {
|
|
712
|
+
const started = await this.spawnBackground(text, opts);
|
|
713
|
+
if ("short" in started || !opts.run || !/model|effort/i.test(started.reason))
|
|
714
|
+
return started;
|
|
715
|
+
return this.spawnBackground(text, { ...opts, run: null });
|
|
716
|
+
}
|
|
717
|
+
spawnBackground(text, opts) {
|
|
718
|
+
const { model, effort } = claudeFlags(opts.run);
|
|
719
|
+
const settings = JSON.stringify({ worktree: { bgIsolation: "none" } });
|
|
720
|
+
const command = process.argv[1] ? [process.execPath, process.argv[1]] : null;
|
|
721
|
+
const managed = this.ctx.env.GAVEL_PLAN_PROFILE && (this.ctx.env.CLAUDE_CONFIG_DIR || this.ctx.env.GAVEL_BRIDGE_OWNER_HARNESS === "codex");
|
|
722
|
+
const launchSettings = managed && command ? withBridgeHooks(settings, command, null, command) ?? settings : settings;
|
|
723
|
+
const args = [...(opts.resume ? ["--resume", opts.resume] : []), ...(model ? ["--model", model] : []), ...(effort ? ["--effort", effort] : []), "--bg", "--settings", launchSettings];
|
|
710
724
|
return new Promise((resolve) => {
|
|
711
725
|
const child = spawn("claude", args, { cwd: this.ctx.cwd, env: this.ctx.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
712
726
|
let out = "";
|
|
@@ -799,7 +813,7 @@ export class ClaudeCodeHarness {
|
|
|
799
813
|
if (!there && Date.now() - last.at < STARTING_MS)
|
|
800
814
|
return false;
|
|
801
815
|
}
|
|
802
|
-
const started = await this.background(`${fresh.brief}\n\n${line}`, { resume: null,
|
|
816
|
+
const started = await this.background(`${fresh.brief}\n\n${line}`, { resume: null, run: fresh });
|
|
803
817
|
if ("reason" in started)
|
|
804
818
|
throw new Error(started.reason);
|
|
805
819
|
this.backgrounded.add(started.short);
|
|
@@ -68,6 +68,7 @@ export class CodexPlanUsage {
|
|
|
68
68
|
home;
|
|
69
69
|
cwd;
|
|
70
70
|
reporter;
|
|
71
|
+
nativeProfile;
|
|
71
72
|
checking = false;
|
|
72
73
|
accountRevision = 0;
|
|
73
74
|
confirmedPlan = null;
|
|
@@ -81,10 +82,11 @@ export class CodexPlanUsage {
|
|
|
81
82
|
totals = new Map();
|
|
82
83
|
pendingDays = new Map();
|
|
83
84
|
sendingDays = false;
|
|
84
|
-
constructor(home, cwd, reporter) {
|
|
85
|
+
constructor(home, cwd, reporter, nativeProfile) {
|
|
85
86
|
this.home = home;
|
|
86
87
|
this.cwd = cwd;
|
|
87
88
|
this.reporter = reporter;
|
|
89
|
+
this.nativeProfile = nativeProfile;
|
|
88
90
|
}
|
|
89
91
|
once(key, line) {
|
|
90
92
|
if (this.warned.has(key))
|
|
@@ -94,7 +96,9 @@ export class CodexPlanUsage {
|
|
|
94
96
|
}
|
|
95
97
|
source() {
|
|
96
98
|
const folder = createHash("sha256").update(this.cwd).digest("hex").slice(0, 16);
|
|
97
|
-
const
|
|
99
|
+
const dir = join(this.home, ".gavel", "plan-accounts");
|
|
100
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
101
|
+
const path = join(dir, `source-${folder}`);
|
|
98
102
|
try {
|
|
99
103
|
writeFileSync(path, randomUUID(), { mode: 0o600, flag: "wx" });
|
|
100
104
|
}
|
|
@@ -216,15 +220,16 @@ export class CodexPlanUsage {
|
|
|
216
220
|
this.confirmedPlan = null;
|
|
217
221
|
return;
|
|
218
222
|
}
|
|
219
|
-
const
|
|
220
|
-
|
|
223
|
+
const managed = this.nativeProfile === planId;
|
|
224
|
+
const account = managed ? null : await accountOf(app);
|
|
225
|
+
if (!managed && (!account || !boundAccount(this.home, planId, account))) {
|
|
221
226
|
this.confirmedPlan = null;
|
|
222
227
|
if (account)
|
|
223
228
|
this.once(planId, "Gavel plan usage paused: Codex switched accounts. Link the active plan in Settings.");
|
|
224
229
|
return;
|
|
225
230
|
}
|
|
226
231
|
const snapshot = await app.request("account/rateLimits/read");
|
|
227
|
-
if (await accountOf(app) !== account || revision !== this.accountRevision)
|
|
232
|
+
if ((!managed && await accountOf(app) !== account) || revision !== this.accountRevision)
|
|
228
233
|
return;
|
|
229
234
|
this.confirmedPlan = planId;
|
|
230
235
|
const windows = codexWindows(snapshot);
|
|
@@ -249,6 +254,20 @@ export class CodexPlanUsage {
|
|
|
249
254
|
this.scheduleQuota();
|
|
250
255
|
}
|
|
251
256
|
}
|
|
257
|
+
async hit(app) {
|
|
258
|
+
if (!this.reporter.hit)
|
|
259
|
+
return;
|
|
260
|
+
let reset = null;
|
|
261
|
+
try {
|
|
262
|
+
const snapshot = await app.request("account/rateLimits/read");
|
|
263
|
+
reset = codexWindows(snapshot).filter((window) => window.usedPercent >= 90 && Date.parse(window.resetsAt) > Date.now())
|
|
264
|
+
.map((window) => window.resetsAt).sort().at(-1) ?? null;
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
// The provider can report the hit without a reset time.
|
|
268
|
+
}
|
|
269
|
+
await this.reporter.hit(reset);
|
|
270
|
+
}
|
|
252
271
|
disconnect() {
|
|
253
272
|
this.accountRevision++;
|
|
254
273
|
this.confirmedPlan = null;
|
package/dist/bridge/codex.js
CHANGED
|
@@ -6,6 +6,7 @@ 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
8
|
import { CodexPlanUsage } from "./codex-plan.js";
|
|
9
|
+
import { codexFlags } from "./runtime.js";
|
|
9
10
|
import { codexSetups } from "./setup.js";
|
|
10
11
|
import { WebSocketError } from "./websocket.js";
|
|
11
12
|
import { cut } from "./words.js";
|
|
@@ -185,7 +186,7 @@ class CodexHarness {
|
|
|
185
186
|
planUsage;
|
|
186
187
|
constructor(ctx) {
|
|
187
188
|
this.ctx = ctx;
|
|
188
|
-
this.planUsage = ctx.planReporter ? new CodexPlanUsage(ctx.home, ctx.cwd, ctx.planReporter) : null;
|
|
189
|
+
this.planUsage = ctx.planReporter ? new CodexPlanUsage(ctx.home, ctx.cwd, ctx.planReporter, ctx.env.GAVEL_PLAN_PROFILE) : null;
|
|
189
190
|
}
|
|
190
191
|
here(cwd) {
|
|
191
192
|
return cwd === this.ctx.cwd || realpath(cwd) === realpath(this.ctx.cwd);
|
|
@@ -383,6 +384,8 @@ class CodexHarness {
|
|
|
383
384
|
this.turnId = null;
|
|
384
385
|
if (turn.status === "interrupted")
|
|
385
386
|
this.stoppedAt = Date.now();
|
|
387
|
+
if (this.app && turn.error?.codexErrorInfo === "usageLimitExceeded")
|
|
388
|
+
void this.planUsage?.hit(this.app).catch(() => undefined);
|
|
386
389
|
if (turn.status === "failed" && this.unattended.has(turn.id))
|
|
387
390
|
this.listener?.note(`Codex couldn't finish: ${turn.error?.message ?? "the turn failed"}`.slice(0, 300));
|
|
388
391
|
this.unattended.delete(turn.id);
|
|
@@ -397,11 +400,15 @@ class CodexHarness {
|
|
|
397
400
|
}
|
|
398
401
|
// Into the newest session: started on its turn when idle, steering it while it runs (turn/start does
|
|
399
402
|
// either); loaded first when nobody has it open, or a new session when the folder has none.
|
|
400
|
-
async put(app, input, clientUserMessageId, words, wake) {
|
|
403
|
+
async put(app, input, clientUserMessageId, words, wake, run) {
|
|
401
404
|
await this.newest();
|
|
402
405
|
let current = this.current;
|
|
406
|
+
// What a session started or loaded here goes with (W-249); one already loaded, whose turn may run
|
|
407
|
+
// and which the person may have open, keeps its own.
|
|
408
|
+
let flags = null;
|
|
403
409
|
if (!current) {
|
|
404
|
-
|
|
410
|
+
flags = run ?? null;
|
|
411
|
+
const { thread } = await this.starting(app, flags);
|
|
405
412
|
current = this.current = { id: thread.id, status: thread.status, path: thread.path, subscribed: true };
|
|
406
413
|
this.started = { id: thread.id, at: Date.now() };
|
|
407
414
|
this.words.clear();
|
|
@@ -416,17 +423,38 @@ class CodexHarness {
|
|
|
416
423
|
current.subscribed = true;
|
|
417
424
|
current.status = { type: "idle" };
|
|
418
425
|
this.ownLoaded.add(current.id);
|
|
426
|
+
flags = run ?? null;
|
|
419
427
|
}
|
|
420
428
|
if (wake && (this.turnId || current.status.type === "active" || Date.now() - this.stoppedAt < QUIET_AFTER_STOP_MS))
|
|
421
429
|
return "busy";
|
|
422
|
-
const { turn } = await
|
|
430
|
+
const { turn } = await this.turning(app, { threadId: current.id, input, clientUserMessageId }, flags);
|
|
423
431
|
if (turn.status === "inProgress")
|
|
424
432
|
this.planTurns.add(turn.id);
|
|
425
433
|
if (this.ownLoaded.has(current.id))
|
|
426
434
|
this.unattended.add(turn.id);
|
|
427
435
|
return "in";
|
|
428
436
|
}
|
|
429
|
-
|
|
437
|
+
// A new thread with the model and the 1M window asked for; one Codex refuses them for starts without,
|
|
438
|
+
// so a model it doesn't offer never keeps a message from reaching it.
|
|
439
|
+
async starting(app, run) {
|
|
440
|
+
const { model, config } = codexFlags(run);
|
|
441
|
+
const params = { cwd: this.ctx.cwd };
|
|
442
|
+
if (!model && !config)
|
|
443
|
+
return app.request("thread/start", params);
|
|
444
|
+
return app
|
|
445
|
+
.request("thread/start", { ...params, ...(model ? { model } : {}), ...(config ? { config } : {}) })
|
|
446
|
+
.catch(() => app.request("thread/start", params));
|
|
447
|
+
}
|
|
448
|
+
// A turn with the effort (and model) asked for, the same way: without them if Codex refuses them.
|
|
449
|
+
async turning(app, params, run) {
|
|
450
|
+
const { model, effort } = codexFlags(run);
|
|
451
|
+
if (!model && !effort)
|
|
452
|
+
return app.request("turn/start", params);
|
|
453
|
+
return app
|
|
454
|
+
.request("turn/start", { ...params, ...(model ? { model } : {}), ...(effort ? { effort } : {}) })
|
|
455
|
+
.catch(() => app.request("turn/start", params));
|
|
456
|
+
}
|
|
457
|
+
async deliver(message, fresh, run) {
|
|
430
458
|
const words = message.decision ? `About ${message.decision.ref}: ${message.decision.question}\n\n${message.text}` : message.text;
|
|
431
459
|
const input = [{ type: "text", text: words, text_elements: [] }, ...message.pictures.map((path) => ({ type: "localImage", path }))];
|
|
432
460
|
let app;
|
|
@@ -437,7 +465,19 @@ class CodexHarness {
|
|
|
437
465
|
return { outcome: "failed", reason: reasonOf(err).slice(0, 300) };
|
|
438
466
|
}
|
|
439
467
|
try {
|
|
440
|
-
|
|
468
|
+
if (fresh && this.ctx.env.GAVEL_PLAN_PROFILE && !this.turnId && this.current?.status.type !== "active") {
|
|
469
|
+
const { thread } = await this.starting(app, fresh);
|
|
470
|
+
this.current = { id: thread.id, status: thread.status, path: thread.path, subscribed: true };
|
|
471
|
+
this.started = { id: thread.id, at: Date.now() };
|
|
472
|
+
this.words.clear();
|
|
473
|
+
this.ownLoaded.add(thread.id);
|
|
474
|
+
const { turn } = await this.turning(app, { threadId: thread.id, input, clientUserMessageId: `${FROM_GAVEL}${message.id}` }, { model: null, effort: fresh.effort });
|
|
475
|
+
if (turn.status === "inProgress")
|
|
476
|
+
this.planTurns.add(turn.id);
|
|
477
|
+
this.unattended.add(turn.id);
|
|
478
|
+
return { outcome: "delivered", read: true };
|
|
479
|
+
}
|
|
480
|
+
const into = await this.put(app, input, `${FROM_GAVEL}${message.id}`, words, false, run);
|
|
441
481
|
if (into === "queued") {
|
|
442
482
|
this.queued.set(words.trim(), message.id);
|
|
443
483
|
if (message.pictures.length)
|
|
@@ -470,9 +510,24 @@ class CodexHarness {
|
|
|
470
510
|
return "over";
|
|
471
511
|
}
|
|
472
512
|
}
|
|
473
|
-
async wake(line) {
|
|
513
|
+
async wake(line, fresh) {
|
|
474
514
|
try {
|
|
475
515
|
const app = await this.connect();
|
|
516
|
+
if (fresh && this.ctx.env.GAVEL_PLAN_PROFILE) {
|
|
517
|
+
if (this.turnId || this.current?.status.type === "active")
|
|
518
|
+
return false;
|
|
519
|
+
const { thread } = await this.starting(app, fresh);
|
|
520
|
+
this.current = { id: thread.id, status: thread.status, path: thread.path, subscribed: true };
|
|
521
|
+
this.started = { id: thread.id, at: Date.now() };
|
|
522
|
+
this.words.clear();
|
|
523
|
+
this.ownLoaded.add(thread.id);
|
|
524
|
+
const text = [fresh.brief, line].filter(Boolean).join("\n\n");
|
|
525
|
+
const { turn } = await this.turning(app, { threadId: thread.id, input: [{ type: "text", text, text_elements: [] }], clientUserMessageId: `${WAKE}${randomUUID()}` }, { model: null, effort: fresh.effort });
|
|
526
|
+
if (turn.status === "inProgress")
|
|
527
|
+
this.planTurns.add(turn.id);
|
|
528
|
+
this.unattended.add(turn.id);
|
|
529
|
+
return true;
|
|
530
|
+
}
|
|
476
531
|
const into = await this.put(app, [{ type: "text", text: line, text_elements: [] }], `${WAKE}${randomUUID()}`, line, true);
|
|
477
532
|
return into !== "busy";
|
|
478
533
|
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { loginInto, personalApi, planIdPattern, planMachine, profileMarker, profilesRoot } from "./plan-profiles.js";
|
|
6
|
+
const product = (p) => (p === "anthropic" ? "Claude" : "ChatGPT");
|
|
7
|
+
const hash = (...parts) => createHash("sha256").update(parts.join("\0")).digest("hex");
|
|
8
|
+
const domainOf = (email) => (typeof email === "string" ? (email.trim().toLowerCase().match(/^[^@\s]+@([a-z0-9.-]+\.[a-z]{2,})$/)?.[1] ?? null) : null);
|
|
9
|
+
const readJson = (file) => {
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
// Claude Code's sign-in in a config folder (its .claude.json; ~/.claude.json for the native one):
|
|
18
|
+
// the plan from the account's organization type and rate-limit tier.
|
|
19
|
+
export function claudeSignIn(file, folder, native) {
|
|
20
|
+
const account = readJson(file)?.oauthAccount;
|
|
21
|
+
if (!account || typeof account.accountUuid !== "string" || !account.accountUuid)
|
|
22
|
+
return null;
|
|
23
|
+
const type = String(account.organizationType ?? "");
|
|
24
|
+
const limit = String(account.userRateLimitTier ?? "");
|
|
25
|
+
const tier = type === "claude_max" ? (/20x/.test(limit) ? "Max 20x" : "Max 5x")
|
|
26
|
+
: type === "claude_pro" ? "Pro"
|
|
27
|
+
: type === "claude_enterprise" ? "Enterprise"
|
|
28
|
+
: null;
|
|
29
|
+
// A Team seat with Max limits is Premium; otherwise it doesn't say whether it's Standard or Premium.
|
|
30
|
+
const team = type === "claude_team" ? (/max/.test(limit) ? "Team Premium" : null) : undefined;
|
|
31
|
+
const choices = type === "claude_team" ? (team ? [] : ["Team", "Team Premium"]) : tier ? [] : ["Pro", "Max 5x", "Max 20x", "Team", "Team Premium", "Enterprise"];
|
|
32
|
+
return {
|
|
33
|
+
provider: "anthropic", key: hash("claude", account.accountUuid, typeof account.organizationUuid === "string" ? account.organizationUuid : ""),
|
|
34
|
+
tier: team ?? tier, choices, domain: domainOf(account.emailAddress),
|
|
35
|
+
org: type === "claude_team" || type === "claude_enterprise" ? (typeof account.organizationName === "string" ? account.organizationName.slice(0, 60) : null) : null,
|
|
36
|
+
folder, native,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
// Codex's sign-in in a CODEX_HOME (auth.json): the plan from its ID token's claims, read here and
|
|
40
|
+
// never sent. An API key's sign-in has no plan.
|
|
41
|
+
export function codexSignIn(folder, native) {
|
|
42
|
+
const tokens = readJson(join(folder, "auth.json"))?.tokens;
|
|
43
|
+
const token = typeof tokens?.id_token === "string" ? tokens.id_token : null;
|
|
44
|
+
if (!token)
|
|
45
|
+
return null;
|
|
46
|
+
let claims;
|
|
47
|
+
try {
|
|
48
|
+
claims = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8"));
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
const auth = (claims["https://api.openai.com/auth"] ?? {});
|
|
54
|
+
const account = typeof auth.chatgpt_account_id === "string" ? auth.chatgpt_account_id : null;
|
|
55
|
+
if (!account)
|
|
56
|
+
return null;
|
|
57
|
+
const plan = String(auth.chatgpt_plan_type ?? "");
|
|
58
|
+
const tier = plan === "plus" ? "Plus" : plan === "pro" ? "Pro" : plan === "team" || plan === "business" ? "Business" : plan === "enterprise" ? "Enterprise" : null;
|
|
59
|
+
return {
|
|
60
|
+
provider: "openai", key: hash("codex", account, typeof auth.chatgpt_user_id === "string" ? auth.chatgpt_user_id : ""),
|
|
61
|
+
tier, choices: tier ? [] : ["Plus", "Pro", "Business", "Enterprise"], domain: domainOf(claims.email), org: null, folder, native,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
// Every sign-in on this machine: the native ones, and each of Gavel's own profile folders.
|
|
65
|
+
export function signInsHere(local) {
|
|
66
|
+
const claudeDir = local.env.CLAUDE_CONFIG_DIR || join(local.home, ".claude");
|
|
67
|
+
const claudeFile = local.env.CLAUDE_CONFIG_DIR ? join(local.env.CLAUDE_CONFIG_DIR, ".claude.json") : join(local.home, ".claude.json");
|
|
68
|
+
const found = [claudeSignIn(claudeFile, claudeDir, true), codexSignIn(local.env.CODEX_HOME || join(local.home, ".codex"), true)];
|
|
69
|
+
const root = profilesRoot(local.home);
|
|
70
|
+
for (const id of existsSync(root) ? readdirSync(root) : []) {
|
|
71
|
+
const folder = join(root, id);
|
|
72
|
+
if (!existsSync(join(folder, "profile")) && !id.startsWith("pending-"))
|
|
73
|
+
continue;
|
|
74
|
+
if (existsSync(join(folder, "profile")) && readFileSync(join(folder, "profile"), "utf8") !== "isolated")
|
|
75
|
+
continue;
|
|
76
|
+
found.push(claudeSignIn(join(folder, ".claude.json"), folder, false), codexSignIn(folder, false));
|
|
77
|
+
}
|
|
78
|
+
const seen = new Set();
|
|
79
|
+
return found.filter((s) => !!s && !seen.has(s.key) && !!seen.add(s.key));
|
|
80
|
+
}
|
|
81
|
+
// Which of the person's accounts a sign-in is: the one this machine connected it to before, else one
|
|
82
|
+
// already there for its plan and domain that no sign-in here claims (a company seat made it), else none.
|
|
83
|
+
export function matchAccount(signIn, tier, accounts, keyOf) {
|
|
84
|
+
const mine = accounts.filter((a) => a.provider === signIn.provider);
|
|
85
|
+
const known = mine.find((a) => keyOf(a.id) === signIn.key);
|
|
86
|
+
if (known)
|
|
87
|
+
return known;
|
|
88
|
+
const free = mine.filter((a) => !keyOf(a.id) && a.tier.toLowerCase() === tier.toLowerCase() && (!signIn.domain || !a.domain || a.domain === signIn.domain));
|
|
89
|
+
return free.length === 1 ? free[0] : null;
|
|
90
|
+
}
|
|
91
|
+
const accountFile = (home, planId) => join(profilesRoot(home), planId, "account");
|
|
92
|
+
const keyOf = (home) => (planId) => {
|
|
93
|
+
try {
|
|
94
|
+
return readFileSync(accountFile(home, planId), "utf8").trim() || null;
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
// What a sign-in's plan is when it doesn't say: asked once, kept on this machine by its account.
|
|
101
|
+
async function askTier(local, signIn, ask) {
|
|
102
|
+
const answers = join(profilesRoot(local.home), "answers.json");
|
|
103
|
+
const kept = (readJson(answers) ?? {});
|
|
104
|
+
if (kept[signIn.key])
|
|
105
|
+
return kept[signIn.key];
|
|
106
|
+
const options = signIn.choices.map((c, i) => `${i + 1}) ${c}`).join(" ");
|
|
107
|
+
const reply = (await ask(`Which ${product(signIn.provider)} plan is ${signIn.domain ? `the account at ${signIn.domain}` : "this sign-in"}? ${options} `)).trim();
|
|
108
|
+
const picked = signIn.choices[Number(reply) - 1] ?? signIn.choices.find((c) => c.toLowerCase() === reply.toLowerCase());
|
|
109
|
+
if (!picked)
|
|
110
|
+
throw new Error(`Choose one of: ${signIn.choices.join(", ")}`);
|
|
111
|
+
mkdirSync(profilesRoot(local.home), { recursive: true, mode: 0o700 });
|
|
112
|
+
writeFileSync(answers, `${JSON.stringify({ ...kept, [signIn.key]: picked }, null, 2)}\n`, { mode: 0o600 });
|
|
113
|
+
return picked;
|
|
114
|
+
}
|
|
115
|
+
// The profile on this machine for an account: the native sign-in, or the account's own folder (Agent
|
|
116
|
+
// Twelve's markers), and which account it is (a hash, 600).
|
|
117
|
+
function markProfile(local, signIn, planId, known, moved) {
|
|
118
|
+
const folder = join(profilesRoot(local.home), planId);
|
|
119
|
+
if (!signIn.native && signIn.folder !== folder) {
|
|
120
|
+
if (existsSync(folder))
|
|
121
|
+
throw new Error("A profile for that account is already on this machine.");
|
|
122
|
+
renameSync(signIn.folder, folder);
|
|
123
|
+
moved();
|
|
124
|
+
}
|
|
125
|
+
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
126
|
+
const harness = signIn.provider === "openai" ? "codex" : "claude-code";
|
|
127
|
+
if (signIn.native) {
|
|
128
|
+
// The native sign-in is one account's at a time: another account's claim on it goes.
|
|
129
|
+
for (const id of readdirSync(profilesRoot(local.home)).filter((id) => planIdPattern.test(id) && id !== planId)) {
|
|
130
|
+
if (existsSync(profileMarker(local.home, id)) && readFileSync(profileMarker(local.home, id), "utf8") === `native:${harness}` && known(id) !== signIn.key)
|
|
131
|
+
writeFileSync(profileMarker(local.home, id), "unclaimed", { mode: 0o600 });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
writeFileSync(profileMarker(local.home, planId), signIn.native ? `native:${harness}` : "isolated", { mode: 0o600 });
|
|
135
|
+
writeFileSync(accountFile(local.home, planId), `${signIn.key}\n`, { mode: 0o600 });
|
|
136
|
+
}
|
|
137
|
+
export async function connectAccounts(local, options, io) {
|
|
138
|
+
const say = io?.say ?? ((line) => console.log(line));
|
|
139
|
+
const ask = io?.ask ?? (async (question) => {
|
|
140
|
+
if (!process.stdin.isTTY)
|
|
141
|
+
throw new Error(`${question.trim()}: run gavel connect in a terminal to answer, or give --tier`);
|
|
142
|
+
const terminal = createInterface({ input: process.stdin, output: process.stdout });
|
|
143
|
+
try {
|
|
144
|
+
return await terminal.question(question);
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
terminal.close();
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
const http = io?.fetch ?? fetch;
|
|
151
|
+
// With a code from Your accounts, no token at all; else the paired personal agent's, acting for them.
|
|
152
|
+
const { base, headers } = options.code
|
|
153
|
+
? { base: (local.env.GAVEL_API_URL ?? "https://api.getgavel.ai").replace(/\/+$/, ""), headers: {} }
|
|
154
|
+
: personalApi(local, options.server);
|
|
155
|
+
const call = async (method, path, body) => {
|
|
156
|
+
const res = await http(`${base}${path}`, { method, headers: { ...headers, ...(body ? { "content-type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
|
157
|
+
if (!res.ok)
|
|
158
|
+
throw new Error(`Gavel answered ${res.status} to ${method} ${path.replace(/[0-9a-f-]{36}/g, ":id")}`);
|
|
159
|
+
return res.json();
|
|
160
|
+
};
|
|
161
|
+
let pending = null;
|
|
162
|
+
if (options.add) {
|
|
163
|
+
pending = join(profilesRoot(local.home), `pending-${randomUUID()}`);
|
|
164
|
+
say(`Sign in to the other ${options.add === "codex" ? "ChatGPT" : "Claude"} account. The link works from your phone; the sign-in stays in its own folder on this machine.`);
|
|
165
|
+
if (!(await (io?.login ?? loginInto)(local, pending, options.add === "codex" ? "openai" : "anthropic"))) {
|
|
166
|
+
say("The sign-in didn't finish: nothing was connected.");
|
|
167
|
+
return 1;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const signIns = signInsHere(local);
|
|
171
|
+
if (!signIns.length) {
|
|
172
|
+
say("No Claude Code or Codex sign-in on this machine. Sign in to either, or run gavel connect --add claude (or codex).");
|
|
173
|
+
return 1;
|
|
174
|
+
}
|
|
175
|
+
const machineId = planMachine(local.home, true);
|
|
176
|
+
if (!machineId)
|
|
177
|
+
throw new Error("This machine's Gavel ID couldn't be read.");
|
|
178
|
+
const known = keyOf(local.home);
|
|
179
|
+
if (options.code) {
|
|
180
|
+
// Every sign-in's plan first (asking here), then one request with the code.
|
|
181
|
+
const ids = existsSync(profilesRoot(local.home)) ? readdirSync(profilesRoot(local.home)).filter((id) => planIdPattern.test(id)) : [];
|
|
182
|
+
const items = [];
|
|
183
|
+
for (const signIn of signIns) {
|
|
184
|
+
const tier = signIn.tier ?? (options.tier && signIn.choices.includes(options.tier) ? options.tier : await askTier(local, signIn, ask));
|
|
185
|
+
const label = `${product(signIn.provider)} ${tier}${signIn.org ? ` · ${signIn.org}` : signIn.domain ? ` (${signIn.domain})` : ""}`;
|
|
186
|
+
items.push({ signIn, body: { planId: ids.find((id) => known(id) === signIn.key) ?? null, provider: signIn.provider, tier, label, domain: signIn.domain } });
|
|
187
|
+
}
|
|
188
|
+
const res = await http(`${base}/v1/plans/connect`, {
|
|
189
|
+
method: "POST", headers: { "content-type": "application/json" },
|
|
190
|
+
body: JSON.stringify({ code: options.code, machineId, signIns: items.map((i) => i.body) }),
|
|
191
|
+
});
|
|
192
|
+
if (res.status === 404 || res.status === 410) {
|
|
193
|
+
say("That code is wrong, used or run out: take a new one from Settings › You › Your accounts.");
|
|
194
|
+
return 1;
|
|
195
|
+
}
|
|
196
|
+
if (!res.ok)
|
|
197
|
+
throw new Error(`Gavel answered ${res.status} to connecting your accounts`);
|
|
198
|
+
const { accounts } = (await res.json());
|
|
199
|
+
for (const [i, done] of accounts.entries()) {
|
|
200
|
+
const signIn = items[i].signIn;
|
|
201
|
+
if (!planIdPattern.test(done.planId))
|
|
202
|
+
throw new Error("Gavel didn't return the account it saved.");
|
|
203
|
+
markProfile(local, signIn, done.planId, known, () => (pending = signIn.folder === pending ? null : pending));
|
|
204
|
+
say(`${done.added ? "Added" : "Connected"} ${done.label}${done.company ? ", your company's seat" : ""}. Its use reaches Gavel through the bridge.`);
|
|
205
|
+
}
|
|
206
|
+
say("Your accounts are in Settings › You › Your accounts, in every workspace you're in.");
|
|
207
|
+
return 0;
|
|
208
|
+
}
|
|
209
|
+
let accounts = (await call("GET", "/v1/me/plans")).plans ?? [];
|
|
210
|
+
for (const signIn of signIns) {
|
|
211
|
+
const tier = signIn.tier ?? (options.tier && signIn.choices.includes(options.tier) ? options.tier : await askTier(local, signIn, ask));
|
|
212
|
+
const match = matchAccount(signIn, tier, accounts, known);
|
|
213
|
+
const name = `${product(signIn.provider)} ${tier}${signIn.org ? ` · ${signIn.org}` : signIn.domain ? ` (${signIn.domain})` : ""}`;
|
|
214
|
+
const body = {
|
|
215
|
+
provider: signIn.provider, tier, label: match?.label ?? name,
|
|
216
|
+
// An account's own price stays; the list price is Gavel's to say.
|
|
217
|
+
monthlyCents: match && match.monthlyCents !== match.listCents && !match.seatId ? match.monthlyCents : null,
|
|
218
|
+
...(signIn.domain ? { domain: signIn.domain } : {}),
|
|
219
|
+
};
|
|
220
|
+
const answer = match ? await call("PATCH", `/v1/me/plans/${match.id}`, body) : await call("POST", "/v1/me/plans", body);
|
|
221
|
+
accounts = answer.plans ?? accounts;
|
|
222
|
+
const account = match ? accounts.find((a) => a.id === match.id) : accounts.find((a) => a.provider === signIn.provider && !known(a.id) && a.label === body.label && a.tier === tier);
|
|
223
|
+
if (!account || !planIdPattern.test(account.id))
|
|
224
|
+
throw new Error("Gavel didn't return the account it saved.");
|
|
225
|
+
markProfile(local, signIn, account.id, known, () => (pending = signIn.folder === pending ? null : pending));
|
|
226
|
+
await call("PUT", `/v1/me/plans/${account.id}/machines/${machineId}`);
|
|
227
|
+
const seat = account.seatId ? ", your company's seat" : "";
|
|
228
|
+
say(`${match ? "Connected" : "Added"} ${account.label}${seat}. Its use reaches Gavel through the bridge.`);
|
|
229
|
+
}
|
|
230
|
+
say("Your accounts are in Settings › You › Your accounts, in every workspace you're in.");
|
|
231
|
+
return 0;
|
|
232
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { apiFor, claudeSetups, codexSetups } from "./setup.js";
|
|
7
|
+
export const planIdPattern = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
8
|
+
export const profilesRoot = (home) => join(home, ".gavel", "plans");
|
|
9
|
+
const root = profilesRoot;
|
|
10
|
+
export const profileMarker = (home, id) => join(root(home), id, "profile");
|
|
11
|
+
const marker = profileMarker;
|
|
12
|
+
export function planMachine(home, create = false) {
|
|
13
|
+
const folder = root(home);
|
|
14
|
+
const file = join(folder, "machine-id");
|
|
15
|
+
if (create) {
|
|
16
|
+
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
17
|
+
try {
|
|
18
|
+
writeFileSync(file, randomUUID(), { flag: "wx", mode: 0o600 });
|
|
19
|
+
}
|
|
20
|
+
catch (err) {
|
|
21
|
+
if (err.code !== "EEXIST")
|
|
22
|
+
throw err;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (!existsSync(file))
|
|
26
|
+
return null;
|
|
27
|
+
const id = readFileSync(file, "utf8").trim();
|
|
28
|
+
return planIdPattern.test(id) ? id : null;
|
|
29
|
+
}
|
|
30
|
+
export function planEnvironment(local, id, harness) {
|
|
31
|
+
if (!planIdPattern.test(id) || !existsSync(marker(local.home, id)))
|
|
32
|
+
return null;
|
|
33
|
+
const location = readFileSync(marker(local.home, id), "utf8");
|
|
34
|
+
const native = location === `native:${harness}`;
|
|
35
|
+
if (!native && location !== "isolated")
|
|
36
|
+
return null;
|
|
37
|
+
const env = { ...local.env, GAVEL_PLAN_PROFILE: id };
|
|
38
|
+
delete env.OPENAI_API_KEY;
|
|
39
|
+
delete env.ANTHROPIC_API_KEY;
|
|
40
|
+
delete env.ANTHROPIC_AUTH_TOKEN;
|
|
41
|
+
delete env.CLAUDE_CODE_OAUTH_TOKEN;
|
|
42
|
+
delete env.CODEX_ACCESS_TOKEN;
|
|
43
|
+
delete env.GAVEL_TOKEN;
|
|
44
|
+
if (harness === "codex")
|
|
45
|
+
env.CODEX_HOME = native ? join(local.home, ".codex") : join(root(local.home), id);
|
|
46
|
+
else if (native)
|
|
47
|
+
delete env.CLAUDE_CONFIG_DIR;
|
|
48
|
+
else
|
|
49
|
+
env.CLAUDE_CONFIG_DIR = join(root(local.home), id);
|
|
50
|
+
return env;
|
|
51
|
+
}
|
|
52
|
+
// The native login into a folder of its own (CLAUDE_CONFIG_DIR or CODEX_HOME), so each account's
|
|
53
|
+
// sign-in stays in its own: Codex's device login and Claude's both give a link that works from a phone.
|
|
54
|
+
export function loginInto(local, folder, provider) {
|
|
55
|
+
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
56
|
+
const env = { ...local.env };
|
|
57
|
+
delete env.OPENAI_API_KEY;
|
|
58
|
+
delete env.ANTHROPIC_API_KEY;
|
|
59
|
+
delete env.ANTHROPIC_AUTH_TOKEN;
|
|
60
|
+
delete env.CLAUDE_CODE_OAUTH_TOKEN;
|
|
61
|
+
delete env.CODEX_ACCESS_TOKEN;
|
|
62
|
+
delete env.GAVEL_TOKEN;
|
|
63
|
+
const codex = provider === "openai";
|
|
64
|
+
if (codex)
|
|
65
|
+
env.CODEX_HOME = folder;
|
|
66
|
+
else
|
|
67
|
+
env.CLAUDE_CONFIG_DIR = folder;
|
|
68
|
+
return new Promise((resolve) => {
|
|
69
|
+
const child = spawn(codex ? "codex" : "claude", codex ? ["login", "--device-auth"] : ["auth", "login", "--claudeai"], { env, stdio: "inherit" });
|
|
70
|
+
child.once("error", () => resolve(false));
|
|
71
|
+
child.once("exit", (code) => resolve(code === 0));
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function login(local, plan) {
|
|
75
|
+
const folder = join(root(local.home), plan.id);
|
|
76
|
+
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
77
|
+
const env = { ...local.env };
|
|
78
|
+
delete env.OPENAI_API_KEY;
|
|
79
|
+
delete env.ANTHROPIC_API_KEY;
|
|
80
|
+
delete env.ANTHROPIC_AUTH_TOKEN;
|
|
81
|
+
delete env.CLAUDE_CODE_OAUTH_TOKEN;
|
|
82
|
+
delete env.CODEX_ACCESS_TOKEN;
|
|
83
|
+
delete env.GAVEL_TOKEN;
|
|
84
|
+
const codex = plan.provider === "openai";
|
|
85
|
+
if (codex)
|
|
86
|
+
env.CODEX_HOME = folder;
|
|
87
|
+
else
|
|
88
|
+
env.CLAUDE_CONFIG_DIR = folder;
|
|
89
|
+
return new Promise((resolve) => {
|
|
90
|
+
const child = spawn(codex ? "codex" : "claude", codex ? ["login", "--device-auth"] : ["auth", "login", "--claudeai"], { env, stdio: "inherit" });
|
|
91
|
+
child.once("error", () => resolve(false));
|
|
92
|
+
child.once("exit", (code) => resolve(code === 0));
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
// Keep session IDs on this machine so a claimed profile only counts managed sessions.
|
|
96
|
+
const sessionMarker = (home, planId, sessionId) => join(root(home), planId, "sessions", sessionId);
|
|
97
|
+
export function rememberPlanSession(home, planId, sessionId) {
|
|
98
|
+
if (!planIdPattern.test(planId) || !planIdPattern.test(sessionId))
|
|
99
|
+
return;
|
|
100
|
+
mkdirSync(join(root(home), planId, "sessions"), { recursive: true, mode: 0o700 });
|
|
101
|
+
writeFileSync(sessionMarker(home, planId, sessionId), "", { mode: 0o600 });
|
|
102
|
+
}
|
|
103
|
+
export function isPlanSession(home, planId, sessionId) {
|
|
104
|
+
return planIdPattern.test(planId) && planIdPattern.test(sessionId) && existsSync(sessionMarker(home, planId, sessionId));
|
|
105
|
+
}
|
|
106
|
+
// Gavel as the person: GAVEL_TOKEN, else the one personal agent paired in this folder, acting for them.
|
|
107
|
+
export function personalApi(local, server) {
|
|
108
|
+
const configured = local.env.GAVEL_TOKEN;
|
|
109
|
+
const cwd = process.cwd();
|
|
110
|
+
const setups = configured ? [] : [...claudeSetups(cwd, local.home), ...codexSetups(cwd, local.home, local.env)];
|
|
111
|
+
const localSetups = setups.filter((setup) => setup.where.endsWith("this folder") && (!server || setup.server === server));
|
|
112
|
+
const available = [...new Map(localSetups.map((setup) => [setup.token, setup])).values()];
|
|
113
|
+
const setup = available.length === 1 ? available[0] : null;
|
|
114
|
+
const token = configured ?? setup?.token;
|
|
115
|
+
if (!token)
|
|
116
|
+
throw new Error("Run from the folder of one paired personal agent allowed to act for you, or select its entry with --server.");
|
|
117
|
+
const base = setup ? apiFor(setup, local.env) : (local.env.GAVEL_API_URL ?? "https://api.getgavel.ai").replace(/\/+$/, "");
|
|
118
|
+
return { base, headers: { authorization: `Bearer ${token}`, ...(token.startsWith("gvl_agent_") ? { "x-gavel-for-person": "true" } : {}) } };
|
|
119
|
+
}
|
|
120
|
+
export async function signInPlans(local, options) {
|
|
121
|
+
const { base, headers } = personalApi(local, options.server);
|
|
122
|
+
const response = await fetch(`${base}/v1/me/plans`, { headers });
|
|
123
|
+
if (!response.ok)
|
|
124
|
+
throw new Error("Gavel could not read your plans. Use your own workspace sign-in or personal agent.");
|
|
125
|
+
const plans = (await response.json()).plans;
|
|
126
|
+
const machineId = planMachine(local.home, true);
|
|
127
|
+
if (!machineId)
|
|
128
|
+
throw new Error("The local Gavel machine ID could not be read.");
|
|
129
|
+
const wanted = plans.filter((plan) => planIdPattern.test(plan.id) && (options.planId ? plan.id === options.planId : !existsSync(marker(local.home, plan.id))));
|
|
130
|
+
if (options.claim && !options.planId)
|
|
131
|
+
throw new Error("Choose a plan ID with --plan to claim the existing sign-in.");
|
|
132
|
+
if (!wanted.length) {
|
|
133
|
+
console.log(options.planId ? "That plan is not in this workspace." : "All your plans have a local profile on this machine.");
|
|
134
|
+
return options.planId ? 1 : 0;
|
|
135
|
+
}
|
|
136
|
+
for (const plan of wanted)
|
|
137
|
+
console.log(`${plan.id} ${plan.provider === "openai" ? "ChatGPT" : "Claude"} ${plan.tier} · ${plan.label.replace(/\p{Cc}/gu, "")}`);
|
|
138
|
+
for (const plan of wanted) {
|
|
139
|
+
const file = marker(local.home, plan.id);
|
|
140
|
+
if (options.claim || !existsSync(file)) {
|
|
141
|
+
const native = `native:${plan.provider === "openai" ? "codex" : "claude-code"}`;
|
|
142
|
+
if (options.claim) {
|
|
143
|
+
for (const id of readdirSync(root(local.home)).filter((id) => planIdPattern.test(id) && id !== plan.id)) {
|
|
144
|
+
if (existsSync(marker(local.home, id)) && readFileSync(marker(local.home, id), "utf8") === native)
|
|
145
|
+
throw new Error("The default sign-in is already claimed by another plan on this machine.");
|
|
146
|
+
}
|
|
147
|
+
const terminal = createInterface({ input: process.stdin, output: process.stdout });
|
|
148
|
+
let reply;
|
|
149
|
+
try {
|
|
150
|
+
reply = await terminal.question(`Use the existing ${plan.provider === "openai" ? "Codex" : "Claude Code"} sign-in for this plan? [y/N] `);
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
terminal.close();
|
|
154
|
+
}
|
|
155
|
+
if (reply.trim().toLowerCase() !== "y")
|
|
156
|
+
return 1;
|
|
157
|
+
}
|
|
158
|
+
else if (!(await login(local, plan))) {
|
|
159
|
+
console.error("The native login did not complete.");
|
|
160
|
+
return 1;
|
|
161
|
+
}
|
|
162
|
+
mkdirSync(join(root(local.home), plan.id), { recursive: true, mode: 0o700 });
|
|
163
|
+
writeFileSync(file, options.claim ? native : "isolated", { mode: 0o600 });
|
|
164
|
+
}
|
|
165
|
+
const registered = await fetch(`${base}/v1/me/plans/${plan.id}/machines/${machineId}`, { method: "PUT", headers });
|
|
166
|
+
if (!registered.ok)
|
|
167
|
+
throw new Error("Gavel could not register the local profile. Run this command with --plan and its ID to retry.");
|
|
168
|
+
console.log("Plan is available on this machine.");
|
|
169
|
+
}
|
|
170
|
+
return 0;
|
|
171
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// What a run the bridge starts goes with (W-249): the model, thinking effort and context Gavel's router
|
|
2
|
+
// or an override chose for the agent's kind of job (GET /v1/agents/me/runtime), as each harness takes
|
|
3
|
+
// them. Gavel names them in its own words; each harness gets the nearest it offers, and a value it has
|
|
4
|
+
// no way to take is left out, never sent.
|
|
5
|
+
const MODEL = /^[A-Za-z0-9][\w.:[\]-]{0,79}$/;
|
|
6
|
+
const CLAUDE_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
7
|
+
const CODEX_EFFORTS = ["low", "medium", "high", "xhigh"];
|
|
8
|
+
// The run as an answer from Gavel says it, rebuilt from its known fields; null when it names nothing.
|
|
9
|
+
export function runOf(body) {
|
|
10
|
+
const run = body?.run;
|
|
11
|
+
if (!run || (run.harness !== "claude-code" && run.harness !== "codex"))
|
|
12
|
+
return null;
|
|
13
|
+
const model = typeof run.model === "string" && MODEL.test(run.model) ? run.model : null;
|
|
14
|
+
const effort = typeof run.effort === "string" ? run.effort : null;
|
|
15
|
+
const context = typeof run.context === "string" ? run.context : null;
|
|
16
|
+
return { harness: run.harness, model, effort, context };
|
|
17
|
+
}
|
|
18
|
+
// Claude Code: `--model` with its 1M window as the model's suffix (its default window is 200k, so 300k
|
|
19
|
+
// is the model as it is), `--effort` as named.
|
|
20
|
+
export function claudeFlags(run) {
|
|
21
|
+
const model = run?.model && MODEL.test(run.model) ? (run.context === "1m" && !run.model.endsWith("]") ? `${run.model}[1m]` : run.model) : null;
|
|
22
|
+
return { model, effort: run?.effort && CLAUDE_EFFORTS.includes(run.effort) ? run.effort : null };
|
|
23
|
+
}
|
|
24
|
+
// Codex: its own model, its reasoning effort (max is its xhigh), and a 1M window as a config override
|
|
25
|
+
// of the thread (its default window, the model's own, is what 300k asks for).
|
|
26
|
+
export function codexFlags(run) {
|
|
27
|
+
const effort = run?.effort === "max" ? "xhigh" : run?.effort && CODEX_EFFORTS.includes(run.effort) ? run.effort : null;
|
|
28
|
+
return { model: run?.model && MODEL.test(run.model) ? run.model : null, effort, config: run?.context === "1m" ? { model_context_window: 1_000_000 } : null };
|
|
29
|
+
}
|
package/dist/gavel.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
// on a fleet token, the chat's name with --as or GAVEL_AGENT (sent as X-Gavel-Agent). In a GitHub
|
|
5
5
|
// Actions job with id-token: write and no GAVEL_TOKEN, the run's own token, traded for GitHub's.
|
|
6
6
|
// Prints the API's JSON; on an error, prints it to stderr and exits 1.
|
|
7
|
+
import { connectAccounts } from "./bridge/connect.js";
|
|
8
|
+
import { signInPlans } from "./bridge/plan-profiles.js";
|
|
7
9
|
import { execFileSync } from "node:child_process";
|
|
8
10
|
import { createHash, randomUUID } from "node:crypto";
|
|
9
11
|
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
|
|
@@ -31,6 +33,15 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
|
|
|
31
33
|
what's waiting for you in Gavel, in one line, or nothing;
|
|
32
34
|
--hook answers as that software's end-of-turn hook (run by
|
|
33
35
|
the hook, not by hand); always exits 0
|
|
36
|
+
gavel connect [--code <code>] [--add claude|codex] [--tier <plan>] [--server <name>]
|
|
37
|
+
the Claude Code and Codex sign-ins on this machine become
|
|
38
|
+
your accounts in Gavel, once (D-1349), with the one-time
|
|
39
|
+
code from Settings › You › Your accounts (from any folder,
|
|
40
|
+
no token), or as this folder's personal agent: only each one's plan,
|
|
41
|
+
a name and its email's domain go, never a sign-in; --add
|
|
42
|
+
signs in another account first, with a link that works
|
|
43
|
+
from your phone, in a folder of its own
|
|
44
|
+
gavel plans sign-in [--plan <id>] [--claim true] [--server <name>]
|
|
34
45
|
gavel bridge [--harness claude-code|codex] [--server <name>]
|
|
35
46
|
run by a person in their agent's folder, beside it, until
|
|
36
47
|
stopped: its newest Claude Code or Codex session's words in
|
|
@@ -312,6 +323,8 @@ const FLAGS = {
|
|
|
312
323
|
pair: ["harness", "machine", "hook", "bridge"],
|
|
313
324
|
waiting: ["hook", "server", "file"],
|
|
314
325
|
bridge: ["harness", "server"],
|
|
326
|
+
plans: ["plan", "claim", "server"],
|
|
327
|
+
connect: ["add", "tier", "server", "code"],
|
|
315
328
|
"actions-env": [],
|
|
316
329
|
search: ["query", "area", "status", "limit"],
|
|
317
330
|
ask: ["file"],
|
|
@@ -1072,6 +1085,17 @@ export function toRequest(argv) {
|
|
|
1072
1085
|
throw new UsageError("--server and --file go together: the entry pairing wrote, and the file it's in");
|
|
1073
1086
|
return { waiting: { hook, server: f.server, file: f.file } };
|
|
1074
1087
|
}
|
|
1088
|
+
case "connect": {
|
|
1089
|
+
upTo(0);
|
|
1090
|
+
if (f.add !== undefined && f.add !== "claude" && f.add !== "codex")
|
|
1091
|
+
throw new UsageError("--add takes claude or codex");
|
|
1092
|
+
return { connect: { ...(f.add ? { add: f.add } : {}), ...(f.tier ? { tier: f.tier } : {}), ...(f.server ? { server: f.server } : {}), ...(f.code ? { code: f.code } : {}) } };
|
|
1093
|
+
}
|
|
1094
|
+
case "plans":
|
|
1095
|
+
upTo(1);
|
|
1096
|
+
if (p[0] !== "sign-in")
|
|
1097
|
+
throw new UsageError("plans takes sign-in");
|
|
1098
|
+
return { plans: { planId: f.plan, claim: f.claim === "true", server: f.server } };
|
|
1075
1099
|
case "bridge": {
|
|
1076
1100
|
const action = p[0] ?? "run";
|
|
1077
1101
|
const harness = f.harness;
|
|
@@ -1914,6 +1938,10 @@ export function wakeLine(item) {
|
|
|
1914
1938
|
: `GAVEL_WAKE task ${item.ref} ${item.type ?? "changed"} by someone else: gavel work show ${item.ref}`;
|
|
1915
1939
|
case "replaced":
|
|
1916
1940
|
return `GAVEL_WAKE replaced ${item.ref}: it no longer holds, ${item.type ?? "a newer decision"} replaces it: gavel get ${item.type ?? item.ref}, and follow that one`;
|
|
1941
|
+
case "budget":
|
|
1942
|
+
return `GAVEL_WAKE budget: ${item.type === "over" ? "a budget ran out" : "a budget reached 80%"}: gavel inbox budget, then tell your person`;
|
|
1943
|
+
case "deployed":
|
|
1944
|
+
return `GAVEL_WAKE deployed ${item.ref}: it went live, and your person asked for it: gavel work show ${item.ref}, then tell them`;
|
|
1917
1945
|
case "thread":
|
|
1918
1946
|
return `GAVEL_WAKE thread ${item.ref}: ${THREAD_WAKES[item.type ?? ""] ?? "a message"}: read it with gavel thread ${item.ref}`;
|
|
1919
1947
|
default:
|
|
@@ -1931,7 +1959,7 @@ async function watch(token, as) {
|
|
|
1931
1959
|
for (;;) {
|
|
1932
1960
|
let res;
|
|
1933
1961
|
try {
|
|
1934
|
-
res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50&kinds=health,claim,work,drift,task,replaced,thread${start ? "&start=true" : ""}`, {
|
|
1962
|
+
res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50&kinds=health,claim,work,drift,task,replaced,thread,deployed,budget${start ? "&start=true" : ""}`, {
|
|
1935
1963
|
headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) },
|
|
1936
1964
|
});
|
|
1937
1965
|
}
|
|
@@ -2069,6 +2097,10 @@ async function main(argvIn) {
|
|
|
2069
2097
|
return pair(request.pair);
|
|
2070
2098
|
if ("waiting" in request)
|
|
2071
2099
|
return waiting(request.waiting, as);
|
|
2100
|
+
if ("plans" in request)
|
|
2101
|
+
return signInPlans({ home: homedir(), env: process.env }, request.plans);
|
|
2102
|
+
if ("connect" in request)
|
|
2103
|
+
return connectAccounts({ home: homedir(), env: process.env }, request.connect);
|
|
2072
2104
|
if ("bridge" in request)
|
|
2073
2105
|
return request.bridge.action === "run" ? heldBridge(request.bridge, as) : runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
|
|
2074
2106
|
if ("bridgeBackground" in request)
|
package/package.json
CHANGED