@getgavel/cli 0.1.27 → 0.1.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gavel",
3
- "version": "0.1.27",
3
+ "version": "0.1.28",
4
4
  "displayName": "Gavel",
5
5
  "description": "Gavel in Claude Code: your person's chat in Gavel reaches your sessions at once (Gavel's bridge, started with each session), the end-of-turn reminder of what's waiting for you, and how to work with Gavel.",
6
6
  "author": { "name": "Gavel", "url": "https://getgavel.ai" },
@@ -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
- let live = runningBridge(opts.home, cwd, opts.harness);
423
+ const ownerHarness = opts.env.GAVEL_BRIDGE_OWNER_HARNESS === "codex" ? "codex" : opts.harness;
424
+ let live = runningBridge(opts.home, cwd, ownerHarness);
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
@@ -5,10 +5,11 @@ 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";
12
13
  import { apiFor, claudeSetups, codexSetups } from "./setup.js";
13
14
  // `gavel bridge` (D-905): run by a person on their laptop, in the folder where their agent works
14
15
  // (Claude Code or Codex), beside it. It shows the newest session's words in the person's Gavel chat
@@ -128,7 +129,9 @@ async function bridge(run, ctx) {
128
129
  day: (input) => report("PUT", "/v1/agents/me/plan/days", input),
129
130
  record: (input) => report("POST", "/v1/agents/me/plan/usage", input),
130
131
  };
131
- return harnessBridge(harnessOf(harness, { ...ctx, planReporter }), harness, setup, ctx);
132
+ const managed = !!planMachine(ctx.home);
133
+ const bridgeContext = { ...ctx, planReporter: managed ? undefined : planReporter };
134
+ return harnessBridge(harnessOf(harness, bridgeContext), harness, setup, bridgeContext);
132
135
  }
133
136
  const PICTURE_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp" };
134
137
  const PICTURE_MAX = 15 * 1024 * 1024;
@@ -178,8 +181,16 @@ async function answer(res) {
178
181
  // The Gavel side for a harness: the one peek (presence, the person's messages, Stop), their messages
179
182
  // put in beside it with their pictures, the session's words kept (the transcript) and shown as written
180
183
  // (live), its state, and wakes for what waits in Gavel.
181
- async function harnessBridge(h, harness, setup, ctx) {
184
+ async function harnessBridge(initial, harness, setup, ctx) {
182
185
  const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
186
+ let h = initial;
187
+ const machineId = planMachine(ctx.home);
188
+ let activeHarness = harness;
189
+ let activePlan = null;
190
+ let activeEnv = ctx.env;
191
+ let retryPlanAt = 0;
192
+ let lastManagedUsage = 0;
193
+ let lastManagedWindows = "";
183
194
  const me = await whoAmI(api, setup);
184
195
  if (h instanceof ClaudeCodeHarness)
185
196
  h.setPerson(me.person.name);
@@ -355,11 +366,22 @@ async function harnessBridge(h, harness, setup, ctx) {
355
366
  }
356
367
  return { paths, missed };
357
368
  };
369
+ let launchQueue = Promise.resolve();
370
+ const launch = (run) => {
371
+ const chosen = launchQueue.then(run);
372
+ launchQueue = chosen.then(() => undefined, () => undefined);
373
+ return chosen;
374
+ };
358
375
  const deliver = async (m) => {
359
376
  try {
360
377
  const { paths, missed } = await fetchPictures(m.images ?? []);
361
378
  urgentUntil = Date.now() + PUSH_URGENT_MS;
362
- const result = await h.deliver({ id: m.id, text: m.text, decision: m.decision, pictures: paths });
379
+ const result = await launch(async () => {
380
+ const route = await pick(null, "chat");
381
+ return route.allowed ? h.deliver({ id: m.id, text: m.text, decision: m.decision, pictures: paths }, route.fresh) : null;
382
+ });
383
+ if (!result)
384
+ return;
363
385
  if (result.outcome === "left") {
364
386
  if (!left.has(m.id))
365
387
  say(result.say);
@@ -423,6 +445,83 @@ async function harnessBridge(h, harness, setup, ctx) {
423
445
  return { waiting: true, fresh: null };
424
446
  }
425
447
  };
448
+ const busy = () => state === "working" || state === "waiting";
449
+ const pick = async (fresh, job = "wake") => {
450
+ if (!machineId || busy() || (!fresh && thread && state === "idle"))
451
+ return { allowed: true, fresh };
452
+ if (state === null)
453
+ await h.newest().catch(() => null);
454
+ if (busy())
455
+ return { allowed: true, fresh };
456
+ if (Date.now() < retryPlanAt)
457
+ return { allowed: false, fresh };
458
+ const res = await call(api, "POST", "/v1/agents/me/plan/pick", { machineId, harness: activeHarness, job });
459
+ if (res.status === 404)
460
+ return { allowed: true, fresh };
461
+ const route = res.ok ? await answer(res) : null;
462
+ if (route?.why === "unmanaged")
463
+ return { allowed: true, fresh };
464
+ if (route?.why === "wait") {
465
+ const reset = route.resetsAt ? Date.parse(route.resetsAt) : Number.NaN;
466
+ retryPlanAt = Number.isFinite(reset) ? Math.min(reset, Date.now() + 60_000) : Date.now() + 60_000;
467
+ const at = Number.isFinite(reset) ? new Date(reset).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : null;
468
+ const words = `Waiting for your ${activeHarness === "codex" ? "ChatGPT" : "Claude"} plans${at ? `, back at ${at}.` : ". Reset time unavailable."}`;
469
+ if (words !== trouble)
470
+ void note(words);
471
+ complain(words);
472
+ return { allowed: false, fresh };
473
+ }
474
+ const selected = route?.planId;
475
+ const nextHarness = route?.harness;
476
+ if (!selected || !planIdPattern.test(selected) || (nextHarness !== "codex" && nextHarness !== "claude-code")) {
477
+ retryPlanAt = Date.now() + 30_000;
478
+ complain("No signed-in plan is available for a fresh session on this machine.");
479
+ return { allowed: false, fresh };
480
+ }
481
+ const env = planEnvironment(ctx, selected, nextHarness);
482
+ if (!env) {
483
+ retryPlanAt = Date.now() + 30_000;
484
+ complain("Gavel selected a plan whose local profile is missing. Run gavel plans sign-in for that plan.");
485
+ return { allowed: false, fresh };
486
+ }
487
+ if (activePlan !== selected || activeHarness !== nextHarness) {
488
+ const previous = h;
489
+ env.GAVEL_BRIDGE_OWNER_HARNESS = harness;
490
+ activeHarness = nextHarness;
491
+ activePlan = selected;
492
+ activeEnv = env;
493
+ lastManagedUsage = 0;
494
+ lastManagedWindows = "";
495
+ const reporter = {
496
+ linked: async () => selected,
497
+ async hit(resetsAt) {
498
+ await call(api, "POST", "/v1/agents/me/plan/limit", { planId: selected, machineId, resetsAt });
499
+ },
500
+ async record(input) {
501
+ const result = await call(api, "POST", "/v1/agents/me/plan/usage", { ...input, machineId });
502
+ if (!result.ok)
503
+ throw new Error("Gavel refused the managed plan usage report");
504
+ },
505
+ async day(input) {
506
+ const result = await call(api, "PUT", "/v1/agents/me/plan/days", { ...input, machineId });
507
+ if (!result.ok)
508
+ throw new Error("Gavel refused the managed plan usage day");
509
+ },
510
+ };
511
+ h = harnessOf(nextHarness, { ...ctx, env, planReporter: reporter });
512
+ if (h instanceof ClaudeCodeHarness)
513
+ h.setPerson(me.person.name);
514
+ previous.listen({ live() { }, state() { }, changed() { }, note() { } });
515
+ await previous.close();
516
+ h.listen(listener);
517
+ h.setChat(!!on);
518
+ resetReporters(reporter);
519
+ }
520
+ const model = typeof route?.model === "string" && /^[A-Za-z0-9][\w.:[\]-]{0,79}$/.test(route.model) ? route.model : null;
521
+ const effort = typeof route?.effort === "string" ? route.effort : null;
522
+ const context = typeof route?.context === "string" ? route.context : null;
523
+ return { allowed: true, fresh: { per: fresh?.per ?? "batch", item: fresh?.item ?? null, brief: fresh?.brief ?? "", model: model ?? fresh?.model ?? null, effort, context } };
524
+ };
426
525
  const tryWake = async () => {
427
526
  if (waking || stopping || !pending.length)
428
527
  return;
@@ -434,7 +533,10 @@ async function harnessBridge(h, harness, setup, ctx) {
434
533
  return;
435
534
  }
436
535
  const line = wakeLineOf(pending);
437
- if (await h.wake(line, still.fresh)) {
536
+ if (await launch(async () => {
537
+ const chosen = await pick(still.fresh);
538
+ return chosen.allowed && await h.wake(line, chosen.fresh);
539
+ })) {
438
540
  say(`Woke ${h.name} for what waits in Gavel: ${line}`);
439
541
  pending = [];
440
542
  }
@@ -452,7 +554,7 @@ async function harnessBridge(h, harness, setup, ctx) {
452
554
  while (watching && !stopping) {
453
555
  let res;
454
556
  try {
455
- res = await call(api, "GET", `/v1/inbox/watch?watch=${watchId}&timeout=50&kinds=health,claim,work,drift&planProvider=${planProvider}${start ? "&start=true" : ""}`);
557
+ res = await call(api, "GET", `/v1/inbox/watch?watch=${watchId}&timeout=50&kinds=health,claim,work,drift${machineId ? "" : `&planProvider=${planProvider}`}${start ? "&start=true" : ""}`);
456
558
  }
457
559
  catch {
458
560
  failures++;
@@ -485,21 +587,58 @@ async function harnessBridge(h, harness, setup, ctx) {
485
587
  };
486
588
  const wakeTimer = setInterval(() => void tryWake(), WAKE_AGAIN_MS);
487
589
  // Claude Code's plan use, from its status line (W-258): to the plan the agent's link names.
488
- const plan = harness === "claude-code" ? claudePlanReporter({ home: ctx.home, request: (method, path, body) => call(api, method, path, body), say }) : null;
590
+ let plan = !machineId && harness === "claude-code" ? claudePlanReporter({ home: ctx.home, request: (method, path, body) => call(api, method, path, body), say }) : null;
489
591
  // Its tokens for each day, summed from the agent's transcripts here (W-247, for the plan's share).
490
- const days = harness === "claude-code" && ctx.planReporter ? claudeDayReporter({ home: ctx.home, cwd: ctx.cwd, env: ctx.env, reporter: ctx.planReporter, say }) : null;
491
- const daysTimer = days ? setInterval(() => days.poke(), DAYS_EVERY_MS) : null;
592
+ let days = harness === "claude-code" && ctx.planReporter ? claudeDayReporter({ home: ctx.home, cwd: ctx.cwd, env: ctx.env, reporter: ctx.planReporter, say }) : null;
593
+ const daysTimer = days || machineId ? setInterval(() => days?.poke(), DAYS_EVERY_MS) : null;
594
+ const resetReporters = (reporter) => {
595
+ plan?.close();
596
+ days?.close();
597
+ plan = null;
598
+ days = activeHarness === "claude-code" ? claudeDayReporter({ home: ctx.home, cwd: ctx.cwd, env: activeEnv, reporter, say }) : null;
599
+ };
492
600
  days?.poke();
493
601
  // The harness's own hooks, through `gavel bridge event` (background.ts), and the status line's.
494
602
  const offHooks = onHookEvent((event) => {
495
- if (event.event !== STATUS_LINE_EVENT)
603
+ if (event.event !== STATUS_LINE_EVENT) {
604
+ if (activePlan && activeHarness === "claude-code" && event.planId === activePlan && event.event === "SessionStart" && typeof event.input.session_id === "string") {
605
+ try {
606
+ rememberPlanSession(ctx.home, activePlan, event.input.session_id);
607
+ }
608
+ catch {
609
+ say("Gavel could not record this Claude session for daily plan usage.");
610
+ }
611
+ }
612
+ if (machineId && activePlan && event.planId === activePlan && event.event === "StopFailure" && event.input.error === "rate_limit") {
613
+ const text = event.input.last_assistant_message;
614
+ if (typeof text === "string" && /(?:usage limit|hit your limit|session limit|weekly limit)/i.test(text)) {
615
+ const details = event.input.error_details;
616
+ const detailsText = typeof details === "string" ? details : "";
617
+ const stamp = detailsText.match(/reset(?:s|_at)?(?: at)?[: ]+([0-9]{4}-[0-9]{2}-[0-9]{2}T[^\s,;]+)/i)?.[1];
618
+ const reset = stamp ? Date.parse(stamp) : Number.NaN;
619
+ void call(api, "POST", "/v1/agents/me/plan/limit", { planId: activePlan, machineId, resetsAt: reset > Date.now() ? new Date(reset).toISOString() : null }).catch(() => undefined);
620
+ }
621
+ }
496
622
  return h.hook?.(event.event, event);
623
+ }
497
624
  const usage = planUsageOf(event.input);
498
- if (plan && usage)
625
+ if (plan && usage && !activePlan)
499
626
  plan.observe(usage, accountOf(event.input));
627
+ if (usage && machineId && activePlan && activeHarness === "claude-code" && event.input.planId === activePlan) {
628
+ const now = Date.now();
629
+ const windows = JSON.stringify(usage.windows.map((window) => [window.kind, Math.floor(window.usedPercent), window.resetsAt]));
630
+ if (usage.windows.length && windows !== lastManagedWindows && now - lastManagedUsage >= 60_000) {
631
+ lastManagedUsage = now;
632
+ const planId = activePlan;
633
+ void call(api, "POST", "/v1/agents/me/plan/usage", { ...usageBody(planId, usage, new Date(now)), machineId }).then((result) => {
634
+ if (result.ok && activePlan === planId)
635
+ lastManagedWindows = windows;
636
+ }).catch(() => undefined);
637
+ }
638
+ }
500
639
  days?.poke();
501
640
  });
502
- h.listen({
641
+ const listener = {
503
642
  live: (event) => {
504
643
  if (event.event === "end")
505
644
  days?.poke();
@@ -520,7 +659,8 @@ async function harnessBridge(h, harness, setup, ctx) {
520
659
  },
521
660
  changed: pushSoon,
522
661
  note: (text) => void note(text),
523
- });
662
+ };
663
+ h.listen(listener);
524
664
  const timers = () => {
525
665
  if (liveTimer)
526
666
  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 sums = new DaySums(() => claudeProjectDirs(opts.cwd, opts.home, opts.env), now);
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"
@@ -670,7 +670,7 @@ export class ClaudeCodeHarness {
670
670
  return to;
671
671
  });
672
672
  }
673
- async deliver(m) {
673
+ async deliver(m, fresh) {
674
674
  const pictures = this.keepPictures(m);
675
675
  const text = this.prompt(m, pictures);
676
676
  let open = this.current();
@@ -686,7 +686,7 @@ export class ClaudeCodeHarness {
686
686
  }
687
687
  if (open)
688
688
  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);
689
+ return this.resume(m, text, fresh);
690
690
  }
691
691
  // A closed session, resumed with the person's words as a turn of its own in the background
692
692
  // (D-1174, changing D-905's "nothing that would prompt runs"): it runs under their own permission
@@ -694,9 +694,9 @@ export class ClaudeCodeHarness {
694
694
  // edits stay in the folder, as their own session's: no worktree of its own (Master Gavel's call).
695
695
  // The words go on stdin, never in its arguments. Delivered once Claude Code says it's backgrounded;
696
696
  // from then the session's own hooks name it, so their next words go through its inbox.
697
- async resume(m, text) {
697
+ async resume(m, text, fresh) {
698
698
  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, model: null });
699
+ const started = await this.background(text, { resume: fresh ? null : newest?.id ?? null, model: fresh?.model ?? null, effort: fresh?.effort });
700
700
  if ("reason" in started)
701
701
  return { outcome: "failed", reason: started.reason };
702
702
  this.remember(m.id, promptKey(text));
@@ -706,7 +706,11 @@ export class ClaudeCodeHarness {
706
706
  // `claude [--resume <id>] --bg` with the words on stdin: the short id Claude Code names the
707
707
  // background session by, or why it didn't start.
708
708
  background(text, opts) {
709
- const args = [...(opts.resume ? ["--resume", opts.resume] : []), ...(opts.model ? ["--model", opts.model] : []), "--bg", "--settings", JSON.stringify({ worktree: { bgIsolation: "none" } })];
709
+ const settings = JSON.stringify({ worktree: { bgIsolation: "none" } });
710
+ const command = process.argv[1] ? [process.execPath, process.argv[1]] : null;
711
+ const managed = this.ctx.env.GAVEL_PLAN_PROFILE && (this.ctx.env.CLAUDE_CONFIG_DIR || this.ctx.env.GAVEL_BRIDGE_OWNER_HARNESS === "codex");
712
+ const launchSettings = managed && command ? withBridgeHooks(settings, command, null, command) ?? settings : settings;
713
+ const args = [...(opts.resume ? ["--resume", opts.resume] : []), ...(opts.model ? ["--model", opts.model] : []), ...(opts.effort ? ["--effort", opts.effort] : []), "--bg", "--settings", launchSettings];
710
714
  return new Promise((resolve) => {
711
715
  const child = spawn("claude", args, { cwd: this.ctx.cwd, env: this.ctx.env, stdio: ["pipe", "pipe", "pipe"] });
712
716
  let out = "";
@@ -799,7 +803,7 @@ export class ClaudeCodeHarness {
799
803
  if (!there && Date.now() - last.at < STARTING_MS)
800
804
  return false;
801
805
  }
802
- const started = await this.background(`${fresh.brief}\n\n${line}`, { resume: null, model: fresh.model });
806
+ const started = await this.background(`${fresh.brief}\n\n${line}`, { resume: null, model: fresh.model, effort: fresh.effort });
803
807
  if ("reason" in started)
804
808
  throw new Error(started.reason);
805
809
  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 path = join(this.home, ".gavel", "plan-accounts", `source-${folder}`);
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 account = await accountOf(app);
220
- if (!account || !boundAccount(this.home, planId, account)) {
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;
@@ -185,7 +185,7 @@ class CodexHarness {
185
185
  planUsage;
186
186
  constructor(ctx) {
187
187
  this.ctx = ctx;
188
- this.planUsage = ctx.planReporter ? new CodexPlanUsage(ctx.home, ctx.cwd, ctx.planReporter) : null;
188
+ this.planUsage = ctx.planReporter ? new CodexPlanUsage(ctx.home, ctx.cwd, ctx.planReporter, ctx.env.GAVEL_PLAN_PROFILE) : null;
189
189
  }
190
190
  here(cwd) {
191
191
  return cwd === this.ctx.cwd || realpath(cwd) === realpath(this.ctx.cwd);
@@ -383,6 +383,8 @@ class CodexHarness {
383
383
  this.turnId = null;
384
384
  if (turn.status === "interrupted")
385
385
  this.stoppedAt = Date.now();
386
+ if (this.app && turn.error?.codexErrorInfo === "usageLimitExceeded")
387
+ void this.planUsage?.hit(this.app).catch(() => undefined);
386
388
  if (turn.status === "failed" && this.unattended.has(turn.id))
387
389
  this.listener?.note(`Codex couldn't finish: ${turn.error?.message ?? "the turn failed"}`.slice(0, 300));
388
390
  this.unattended.delete(turn.id);
@@ -426,7 +428,7 @@ class CodexHarness {
426
428
  this.unattended.add(turn.id);
427
429
  return "in";
428
430
  }
429
- async deliver(message) {
431
+ async deliver(message, fresh) {
430
432
  const words = message.decision ? `About ${message.decision.ref}: ${message.decision.question}\n\n${message.text}` : message.text;
431
433
  const input = [{ type: "text", text: words, text_elements: [] }, ...message.pictures.map((path) => ({ type: "localImage", path }))];
432
434
  let app;
@@ -437,6 +439,18 @@ class CodexHarness {
437
439
  return { outcome: "failed", reason: reasonOf(err).slice(0, 300) };
438
440
  }
439
441
  try {
442
+ if (fresh && this.ctx.env.GAVEL_PLAN_PROFILE && !this.turnId && this.current?.status.type !== "active") {
443
+ const { thread } = await app.request("thread/start", { cwd: this.ctx.cwd, model: fresh.model ?? undefined });
444
+ this.current = { id: thread.id, status: thread.status, path: thread.path, subscribed: true };
445
+ this.started = { id: thread.id, at: Date.now() };
446
+ this.words.clear();
447
+ this.ownLoaded.add(thread.id);
448
+ const { turn } = await app.request("turn/start", { threadId: thread.id, input, clientUserMessageId: `${FROM_GAVEL}${message.id}`, effort: fresh.effort ?? undefined });
449
+ if (turn.status === "inProgress")
450
+ this.planTurns.add(turn.id);
451
+ this.unattended.add(turn.id);
452
+ return { outcome: "delivered", read: true };
453
+ }
440
454
  const into = await this.put(app, input, `${FROM_GAVEL}${message.id}`, words, false);
441
455
  if (into === "queued") {
442
456
  this.queued.set(words.trim(), message.id);
@@ -470,9 +484,28 @@ class CodexHarness {
470
484
  return "over";
471
485
  }
472
486
  }
473
- async wake(line) {
487
+ async wake(line, fresh) {
474
488
  try {
475
489
  const app = await this.connect();
490
+ if (fresh && this.ctx.env.GAVEL_PLAN_PROFILE) {
491
+ if (this.turnId || this.current?.status.type === "active")
492
+ return false;
493
+ const model = fresh.model ?? undefined;
494
+ const { thread } = await app.request("thread/start", { cwd: this.ctx.cwd, model });
495
+ this.current = { id: thread.id, status: thread.status, path: thread.path, subscribed: true };
496
+ this.started = { id: thread.id, at: Date.now() };
497
+ this.words.clear();
498
+ this.ownLoaded.add(thread.id);
499
+ const text = [fresh.brief, line].filter(Boolean).join("\n\n");
500
+ const { turn } = await app.request("turn/start", {
501
+ threadId: thread.id, input: [{ type: "text", text, text_elements: [] }], clientUserMessageId: `${WAKE}${randomUUID()}`,
502
+ effort: fresh.effort ?? undefined,
503
+ });
504
+ if (turn.status === "inProgress")
505
+ this.planTurns.add(turn.id);
506
+ this.unattended.add(turn.id);
507
+ return true;
508
+ }
476
509
  const into = await this.put(app, [{ type: "text", text: line, text_elements: [] }], `${WAKE}${randomUUID()}`, line, true);
477
510
  return into !== "busy";
478
511
  }
@@ -0,0 +1,195 @@
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 doesn't say whether it's Standard or Premium.
30
+ const choices = type === "claude_team" ? ["Team", "Team Premium"] : tier ? [] : ["Pro", "Max 5x", "Max 20x", "Team", "Team Premium", "Enterprise"];
31
+ return {
32
+ provider: "anthropic", key: hash("claude", account.accountUuid, typeof account.organizationUuid === "string" ? account.organizationUuid : ""),
33
+ tier, choices, domain: domainOf(account.emailAddress),
34
+ org: type === "claude_team" || type === "claude_enterprise" ? (typeof account.organizationName === "string" ? account.organizationName.slice(0, 60) : null) : null,
35
+ folder, native,
36
+ };
37
+ }
38
+ // Codex's sign-in in a CODEX_HOME (auth.json): the plan from its ID token's claims, read here and
39
+ // never sent. An API key's sign-in has no plan.
40
+ export function codexSignIn(folder, native) {
41
+ const tokens = readJson(join(folder, "auth.json"))?.tokens;
42
+ const token = typeof tokens?.id_token === "string" ? tokens.id_token : null;
43
+ if (!token)
44
+ return null;
45
+ let claims;
46
+ try {
47
+ claims = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8"));
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ const auth = (claims["https://api.openai.com/auth"] ?? {});
53
+ const account = typeof auth.chatgpt_account_id === "string" ? auth.chatgpt_account_id : null;
54
+ if (!account)
55
+ return null;
56
+ const plan = String(auth.chatgpt_plan_type ?? "");
57
+ const tier = plan === "plus" ? "Plus" : plan === "pro" ? "Pro" : plan === "team" || plan === "business" ? "Business" : plan === "enterprise" ? "Enterprise" : null;
58
+ return {
59
+ provider: "openai", key: hash("codex", account, typeof auth.chatgpt_user_id === "string" ? auth.chatgpt_user_id : ""),
60
+ tier, choices: tier ? [] : ["Plus", "Pro", "Business", "Enterprise"], domain: domainOf(claims.email), org: null, folder, native,
61
+ };
62
+ }
63
+ // Every sign-in on this machine: the native ones, and each of Gavel's own profile folders.
64
+ export function signInsHere(local) {
65
+ const claudeDir = local.env.CLAUDE_CONFIG_DIR || join(local.home, ".claude");
66
+ const claudeFile = local.env.CLAUDE_CONFIG_DIR ? join(local.env.CLAUDE_CONFIG_DIR, ".claude.json") : join(local.home, ".claude.json");
67
+ const found = [claudeSignIn(claudeFile, claudeDir, true), codexSignIn(local.env.CODEX_HOME || join(local.home, ".codex"), true)];
68
+ const root = profilesRoot(local.home);
69
+ for (const id of existsSync(root) ? readdirSync(root) : []) {
70
+ const folder = join(root, id);
71
+ if (!existsSync(join(folder, "profile")) && !id.startsWith("pending-"))
72
+ continue;
73
+ if (existsSync(join(folder, "profile")) && readFileSync(join(folder, "profile"), "utf8") !== "isolated")
74
+ continue;
75
+ found.push(claudeSignIn(join(folder, ".claude.json"), folder, false), codexSignIn(folder, false));
76
+ }
77
+ const seen = new Set();
78
+ return found.filter((s) => !!s && !seen.has(s.key) && !!seen.add(s.key));
79
+ }
80
+ // Which of the person's accounts a sign-in is: the one this machine connected it to before, else one
81
+ // already there for its plan and domain that no sign-in here claims (a company seat made it), else none.
82
+ export function matchAccount(signIn, tier, accounts, keyOf) {
83
+ const mine = accounts.filter((a) => a.provider === signIn.provider);
84
+ const known = mine.find((a) => keyOf(a.id) === signIn.key);
85
+ if (known)
86
+ return known;
87
+ const free = mine.filter((a) => !keyOf(a.id) && a.tier.toLowerCase() === tier.toLowerCase() && (!signIn.domain || !a.domain || a.domain === signIn.domain));
88
+ return free.length === 1 ? free[0] : null;
89
+ }
90
+ const accountFile = (home, planId) => join(profilesRoot(home), planId, "account");
91
+ const keyOf = (home) => (planId) => {
92
+ try {
93
+ return readFileSync(accountFile(home, planId), "utf8").trim() || null;
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ };
99
+ // What a sign-in's plan is when it doesn't say: asked once, kept on this machine by its account.
100
+ async function askTier(local, signIn, ask) {
101
+ const answers = join(profilesRoot(local.home), "answers.json");
102
+ const kept = (readJson(answers) ?? {});
103
+ if (kept[signIn.key])
104
+ return kept[signIn.key];
105
+ const options = signIn.choices.map((c, i) => `${i + 1}) ${c}`).join(" ");
106
+ const reply = (await ask(`Which ${product(signIn.provider)} plan is ${signIn.domain ? `the account at ${signIn.domain}` : "this sign-in"}? ${options} `)).trim();
107
+ const picked = signIn.choices[Number(reply) - 1] ?? signIn.choices.find((c) => c.toLowerCase() === reply.toLowerCase());
108
+ if (!picked)
109
+ throw new Error(`Choose one of: ${signIn.choices.join(", ")}`);
110
+ mkdirSync(profilesRoot(local.home), { recursive: true, mode: 0o700 });
111
+ writeFileSync(answers, `${JSON.stringify({ ...kept, [signIn.key]: picked }, null, 2)}\n`, { mode: 0o600 });
112
+ return picked;
113
+ }
114
+ export async function connectAccounts(local, options, io) {
115
+ const say = io?.say ?? ((line) => console.log(line));
116
+ const ask = io?.ask ?? (async (question) => {
117
+ if (!process.stdin.isTTY)
118
+ throw new Error(`${question.trim()}: run gavel connect in a terminal to answer, or give --tier`);
119
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
120
+ try {
121
+ return await terminal.question(question);
122
+ }
123
+ finally {
124
+ terminal.close();
125
+ }
126
+ });
127
+ const http = io?.fetch ?? fetch;
128
+ const { base, headers } = personalApi(local, options.server);
129
+ const call = async (method, path, body) => {
130
+ const res = await http(`${base}${path}`, { method, headers: { ...headers, ...(body ? { "content-type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) });
131
+ if (!res.ok)
132
+ throw new Error(`Gavel answered ${res.status} to ${method} ${path.replace(/[0-9a-f-]{36}/g, ":id")}`);
133
+ return res.json();
134
+ };
135
+ let pending = null;
136
+ if (options.add) {
137
+ pending = join(profilesRoot(local.home), `pending-${randomUUID()}`);
138
+ 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.`);
139
+ if (!(await (io?.login ?? loginInto)(local, pending, options.add === "codex" ? "openai" : "anthropic"))) {
140
+ say("The sign-in didn't finish: nothing was connected.");
141
+ return 1;
142
+ }
143
+ }
144
+ const signIns = signInsHere(local);
145
+ if (!signIns.length) {
146
+ say("No Claude Code or Codex sign-in on this machine. Sign in to either, or run gavel connect --add claude (or codex).");
147
+ return 1;
148
+ }
149
+ const machineId = planMachine(local.home, true);
150
+ if (!machineId)
151
+ throw new Error("This machine's Gavel ID couldn't be read.");
152
+ let accounts = (await call("GET", "/v1/me/plans")).plans ?? [];
153
+ const known = keyOf(local.home);
154
+ for (const signIn of signIns) {
155
+ const tier = signIn.tier ?? (options.tier && signIn.choices.includes(options.tier) ? options.tier : await askTier(local, signIn, ask));
156
+ const match = matchAccount(signIn, tier, accounts, known);
157
+ const name = `${product(signIn.provider)} ${tier}${signIn.org ? ` · ${signIn.org}` : signIn.domain ? ` (${signIn.domain})` : ""}`;
158
+ const body = {
159
+ provider: signIn.provider, tier, label: match?.label ?? name,
160
+ // An account's own price stays; the list price is Gavel's to say.
161
+ monthlyCents: match && match.monthlyCents !== match.listCents && !match.seatId ? match.monthlyCents : null,
162
+ ...(signIn.domain ? { domain: signIn.domain } : {}),
163
+ };
164
+ const answer = match ? await call("PATCH", `/v1/me/plans/${match.id}`, body) : await call("POST", "/v1/me/plans", body);
165
+ accounts = answer.plans ?? accounts;
166
+ 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);
167
+ if (!account || !planIdPattern.test(account.id))
168
+ throw new Error("Gavel didn't return the account it saved.");
169
+ // The profile on this machine: the native sign-in, or the account's own folder.
170
+ const folder = join(profilesRoot(local.home), account.id);
171
+ if (!signIn.native && signIn.folder !== folder) {
172
+ if (existsSync(folder))
173
+ throw new Error(`A profile for ${account.label} is already on this machine.`);
174
+ renameSync(signIn.folder, folder);
175
+ if (signIn.folder === pending)
176
+ pending = null;
177
+ }
178
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
179
+ const harness = signIn.provider === "openai" ? "codex" : "claude-code";
180
+ if (signIn.native) {
181
+ // The native sign-in is one account's at a time: another account's claim on it goes.
182
+ for (const id of readdirSync(profilesRoot(local.home)).filter((id) => planIdPattern.test(id) && id !== account.id)) {
183
+ if (existsSync(profileMarker(local.home, id)) && readFileSync(profileMarker(local.home, id), "utf8") === `native:${harness}` && known(id) !== signIn.key)
184
+ writeFileSync(profileMarker(local.home, id), "unclaimed", { mode: 0o600 });
185
+ }
186
+ }
187
+ writeFileSync(profileMarker(local.home, account.id), signIn.native ? `native:${harness}` : "isolated", { mode: 0o600 });
188
+ writeFileSync(accountFile(local.home, account.id), `${signIn.key}\n`, { mode: 0o600 });
189
+ await call("PUT", `/v1/me/plans/${account.id}/machines/${machineId}`);
190
+ const seat = account.seatId ? ", your company's seat" : "";
191
+ say(`${match ? "Connected" : "Added"} ${account.label}${seat}. Its use reaches Gavel through the bridge.`);
192
+ }
193
+ say("Your accounts are in Settings › You › Your accounts, in every workspace you're in.");
194
+ return 0;
195
+ }
@@ -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
+ }
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,13 @@ 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 [--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): only each one's plan,
39
+ a name and its email's domain go, never a sign-in; --add
40
+ signs in another account first, with a link that works
41
+ from your phone, in a folder of its own
42
+ gavel plans sign-in [--plan <id>] [--claim true] [--server <name>]
34
43
  gavel bridge [--harness claude-code|codex] [--server <name>]
35
44
  run by a person in their agent's folder, beside it, until
36
45
  stopped: its newest Claude Code or Codex session's words in
@@ -312,6 +321,8 @@ const FLAGS = {
312
321
  pair: ["harness", "machine", "hook", "bridge"],
313
322
  waiting: ["hook", "server", "file"],
314
323
  bridge: ["harness", "server"],
324
+ plans: ["plan", "claim", "server"],
325
+ connect: ["add", "tier", "server"],
315
326
  "actions-env": [],
316
327
  search: ["query", "area", "status", "limit"],
317
328
  ask: ["file"],
@@ -1072,6 +1083,17 @@ export function toRequest(argv) {
1072
1083
  throw new UsageError("--server and --file go together: the entry pairing wrote, and the file it's in");
1073
1084
  return { waiting: { hook, server: f.server, file: f.file } };
1074
1085
  }
1086
+ case "connect": {
1087
+ upTo(0);
1088
+ if (f.add !== undefined && f.add !== "claude" && f.add !== "codex")
1089
+ throw new UsageError("--add takes claude or codex");
1090
+ return { connect: { ...(f.add ? { add: f.add } : {}), ...(f.tier ? { tier: f.tier } : {}), ...(f.server ? { server: f.server } : {}) } };
1091
+ }
1092
+ case "plans":
1093
+ upTo(1);
1094
+ if (p[0] !== "sign-in")
1095
+ throw new UsageError("plans takes sign-in");
1096
+ return { plans: { planId: f.plan, claim: f.claim === "true", server: f.server } };
1075
1097
  case "bridge": {
1076
1098
  const action = p[0] ?? "run";
1077
1099
  const harness = f.harness;
@@ -1914,6 +1936,10 @@ export function wakeLine(item) {
1914
1936
  : `GAVEL_WAKE task ${item.ref} ${item.type ?? "changed"} by someone else: gavel work show ${item.ref}`;
1915
1937
  case "replaced":
1916
1938
  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`;
1939
+ case "budget":
1940
+ return `GAVEL_WAKE budget: ${item.type === "over" ? "a budget ran out" : "a budget reached 80%"}: gavel inbox budget, then tell your person`;
1941
+ case "deployed":
1942
+ return `GAVEL_WAKE deployed ${item.ref}: it went live, and your person asked for it: gavel work show ${item.ref}, then tell them`;
1917
1943
  case "thread":
1918
1944
  return `GAVEL_WAKE thread ${item.ref}: ${THREAD_WAKES[item.type ?? ""] ?? "a message"}: read it with gavel thread ${item.ref}`;
1919
1945
  default:
@@ -1931,7 +1957,7 @@ async function watch(token, as) {
1931
1957
  for (;;) {
1932
1958
  let res;
1933
1959
  try {
1934
- res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50&kinds=health,claim,work,drift,task,replaced,thread${start ? "&start=true" : ""}`, {
1960
+ 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
1961
  headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) },
1936
1962
  });
1937
1963
  }
@@ -2069,6 +2095,10 @@ async function main(argvIn) {
2069
2095
  return pair(request.pair);
2070
2096
  if ("waiting" in request)
2071
2097
  return waiting(request.waiting, as);
2098
+ if ("plans" in request)
2099
+ return signInPlans({ home: homedir(), env: process.env }, request.plans);
2100
+ if ("connect" in request)
2101
+ return connectAccounts({ home: homedir(), env: process.env }, request.connect);
2072
2102
  if ("bridge" in request)
2073
2103
  return request.bridge.action === "run" ? heldBridge(request.bridge, as) : runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
2074
2104
  if ("bridgeBackground" in request)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.27",
3
+ "version": "0.1.28",
4
4
  "description": "The gavel command: an agent's Gavel from a shell (pair, ask, wait, watch and the rest)",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://getgavel.ai/agents",