@getgavel/cli 0.1.26 → 0.1.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/dist/bridge/background.js +38 -14
- package/dist/bridge/bridge.js +188 -17
- package/dist/bridge/claude-code.js +5 -5
- package/dist/bridge/claude-days.js +242 -0
- package/dist/bridge/claude-live.js +79 -17
- package/dist/bridge/claude-plan.js +27 -8
- package/dist/bridge/codex-plan.js +24 -5
- package/dist/bridge/codex.js +36 -3
- package/dist/bridge/connect.js +195 -0
- package/dist/bridge/plan-profiles.js +171 -0
- package/dist/gavel.js +48 -10
- package/package.json +1 -1
package/dist/bridge/codex.js
CHANGED
|
@@ -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
|
|
@@ -86,7 +95,10 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
|
|
|
86
95
|
answer an Ask someone
|
|
87
96
|
gavel act <D-12> (<note> | --note <words>)
|
|
88
97
|
what you did with the answer
|
|
89
|
-
gavel inbox
|
|
98
|
+
gavel inbox [<section>] [--offset <n>] [--limit <n>]
|
|
99
|
+
what's waiting on you, each list's first 10 (counts has
|
|
100
|
+
every total); with a section (requests, decisions, …),
|
|
101
|
+
that list's next page
|
|
90
102
|
gavel status (<title> | --text <words>) [--description <words>] [--folders <a,b>]
|
|
91
103
|
[--state working|blocked|idle] [--issue <MA-482>] [--waiting-on <email or agent>] [--item <W-12>]
|
|
92
104
|
what you're doing now: a title of two to four words in
|
|
@@ -219,7 +231,8 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
|
|
|
219
231
|
[--snooze-until <time>|none]
|
|
220
232
|
gavel set-my-reports [--weekly-report true|false] [--slack-messages true|false]
|
|
221
233
|
gavel set-agent-runtime <agent id> [--model <id>|cursor-default|none] [--effort low|medium|high|xhigh|max|none]
|
|
222
|
-
[--context 300k|1m|none]
|
|
234
|
+
[--context 300k|1m|none] [--sessions item|batch|continuous|none]
|
|
235
|
+
a Cursor agent's model, effort, context and sessions (none: the router's)
|
|
223
236
|
gavel set-area-runtime <area id> [--model <id>|cursor-default|none] [--effort <effort>|none] [--context 300k|1m|none]
|
|
224
237
|
gavel set-job-runtime work|wake|chat|night [--model <id>|cursor-default|none] [--effort <effort>|none] [--context 300k|1m|none]
|
|
225
238
|
gavel my-notifications [--limit <n>] what went out to them, and how many are unread
|
|
@@ -308,6 +321,8 @@ const FLAGS = {
|
|
|
308
321
|
pair: ["harness", "machine", "hook", "bridge"],
|
|
309
322
|
waiting: ["hook", "server", "file"],
|
|
310
323
|
bridge: ["harness", "server"],
|
|
324
|
+
plans: ["plan", "claim", "server"],
|
|
325
|
+
connect: ["add", "tier", "server"],
|
|
311
326
|
"actions-env": [],
|
|
312
327
|
search: ["query", "area", "status", "limit"],
|
|
313
328
|
ask: ["file"],
|
|
@@ -321,7 +336,7 @@ const FLAGS = {
|
|
|
321
336
|
upload: ["type"],
|
|
322
337
|
answer: ["response"],
|
|
323
338
|
act: ["note"],
|
|
324
|
-
inbox: [],
|
|
339
|
+
inbox: ["offset", "limit"],
|
|
325
340
|
status: ["text", "description", "folders", "state", "issue", "waiting-on", "item"],
|
|
326
341
|
"claim-folders": ["mode", "item"],
|
|
327
342
|
work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "open", "waits-on", "program", "area", "why", "key"],
|
|
@@ -363,7 +378,7 @@ const FLAGS = {
|
|
|
363
378
|
"set-my-day": ["timezone", "day-start", "day-end", "morning", "later-every"],
|
|
364
379
|
"set-my-alerts": ["on-call", "sounds", "sound", "later-like-now", "muted", "workspace-sound", "snooze-until"],
|
|
365
380
|
"set-my-reports": ["weekly-report", "slack-messages"],
|
|
366
|
-
"set-agent-runtime": ["model", "effort", "context"],
|
|
381
|
+
"set-agent-runtime": ["model", "effort", "context", "sessions"],
|
|
367
382
|
"set-area-runtime": ["model", "effort", "context"],
|
|
368
383
|
"set-job-runtime": ["model", "effort", "context"],
|
|
369
384
|
"my-notifications": ["limit"],
|
|
@@ -729,9 +744,9 @@ function personRequest(command, p, f, options) {
|
|
|
729
744
|
case "set-area-runtime":
|
|
730
745
|
case "set-job-runtime": {
|
|
731
746
|
upTo(1);
|
|
732
|
-
const body = compact({ model: orNone("model"), effort: orNone("effort"), context: orNone("context") });
|
|
747
|
+
const body = compact({ model: orNone("model"), effort: orNone("effort"), context: orNone("context"), ...(command === "set-agent-runtime" ? { sessions: orNone("sessions") } : {}) });
|
|
733
748
|
if (!Object.keys(body).length)
|
|
734
|
-
throw new UsageError(
|
|
749
|
+
throw new UsageError(`give --model, --effort${command === "set-agent-runtime" ? ", --context or --sessions" : " or --context"}: none sets one back to the router's pick`);
|
|
735
750
|
if (command === "set-agent-runtime")
|
|
736
751
|
return asThem("PUT", `/v1/agents/${encodeURIComponent(need(p[0], "the agent's id"))}/runtime`, body);
|
|
737
752
|
if (command === "set-area-runtime")
|
|
@@ -1068,6 +1083,17 @@ export function toRequest(argv) {
|
|
|
1068
1083
|
throw new UsageError("--server and --file go together: the entry pairing wrote, and the file it's in");
|
|
1069
1084
|
return { waiting: { hook, server: f.server, file: f.file } };
|
|
1070
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 } };
|
|
1071
1097
|
case "bridge": {
|
|
1072
1098
|
const action = p[0] ?? "run";
|
|
1073
1099
|
const harness = f.harness;
|
|
@@ -1166,9 +1192,13 @@ export function toRequest(argv) {
|
|
|
1166
1192
|
return { method: "POST", path: `/v1/requests/${encodeURIComponent(need(p[0], "the request id"))}/answer`, body: { response: readText(words("response", p.slice(1), "the response")) } };
|
|
1167
1193
|
case "act":
|
|
1168
1194
|
return { method: "POST", path: `/v1/decisions/${ref(p[0])}/act`, body: { note: readText(words("note", p.slice(1), "the note")) } };
|
|
1169
|
-
case "inbox":
|
|
1170
|
-
upTo(
|
|
1171
|
-
|
|
1195
|
+
case "inbox": {
|
|
1196
|
+
upTo(1);
|
|
1197
|
+
if (!p[0] && (f.offset !== undefined || f.limit !== undefined))
|
|
1198
|
+
throw new UsageError("--offset and --limit go with a section: gavel inbox requests --offset 10");
|
|
1199
|
+
const query = new URLSearchParams(compact({ section: p[0], offset: f.offset, limit: f.limit }));
|
|
1200
|
+
return { method: "GET", path: `/v1/inbox${query.size ? `?${query}` : ""}` };
|
|
1201
|
+
}
|
|
1172
1202
|
case "chat": {
|
|
1173
1203
|
if (f.text !== undefined && p.length)
|
|
1174
1204
|
throw new UsageError("give your answer once: as words or as --text");
|
|
@@ -1906,6 +1936,10 @@ export function wakeLine(item) {
|
|
|
1906
1936
|
: `GAVEL_WAKE task ${item.ref} ${item.type ?? "changed"} by someone else: gavel work show ${item.ref}`;
|
|
1907
1937
|
case "replaced":
|
|
1908
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`;
|
|
1909
1943
|
case "thread":
|
|
1910
1944
|
return `GAVEL_WAKE thread ${item.ref}: ${THREAD_WAKES[item.type ?? ""] ?? "a message"}: read it with gavel thread ${item.ref}`;
|
|
1911
1945
|
default:
|
|
@@ -1923,7 +1957,7 @@ async function watch(token, as) {
|
|
|
1923
1957
|
for (;;) {
|
|
1924
1958
|
let res;
|
|
1925
1959
|
try {
|
|
1926
|
-
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" : ""}`, {
|
|
1927
1961
|
headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) },
|
|
1928
1962
|
});
|
|
1929
1963
|
}
|
|
@@ -2061,6 +2095,10 @@ async function main(argvIn) {
|
|
|
2061
2095
|
return pair(request.pair);
|
|
2062
2096
|
if ("waiting" in request)
|
|
2063
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);
|
|
2064
2102
|
if ("bridge" in request)
|
|
2065
2103
|
return request.bridge.action === "run" ? heldBridge(request.bridge, as) : runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
|
|
2066
2104
|
if ("bridgeBackground" in request)
|
package/package.json
CHANGED