@getgavel/cli 0.1.31 → 0.1.33
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/bridge.js +39 -3
- package/dist/bridge/claude-keychain.js +84 -0
- package/dist/bridge/claude-plan.js +39 -0
- package/dist/bridge/connect.js +22 -3
- package/dist/bridge/runtime.js +5 -3
- package/dist/gavel.js +52 -8
- package/dist/worker/worker.js +264 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gavel",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.33",
|
|
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" },
|
package/dist/bridge/bridge.js
CHANGED
|
@@ -5,9 +5,10 @@ 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, usageBody } from "./claude-plan.js";
|
|
8
|
+
import { accountOf, checkClaudeExtra, claudePlanReporter, planUsageOf, usageBody } from "./claude-plan.js";
|
|
9
9
|
import { claudeSessions } from "./claude-code.js";
|
|
10
10
|
import { ClaudeCodeHarness } from "./claude-live.js";
|
|
11
|
+
import { signedOutClaudeProfiles, signedOutLine } from "./connect.js";
|
|
11
12
|
import { codexHarness, codexSessions } from "./codex.js";
|
|
12
13
|
import { planEnvironment, planIdPattern, planMachine, rememberPlanSession } from "./plan-profiles.js";
|
|
13
14
|
import { runOf } from "./runtime.js";
|
|
@@ -141,6 +142,7 @@ const PICTURE_KEEP_MS = 15 * 60_000;
|
|
|
141
142
|
// Live pieces go at most twice a second (the live route's own limit, 240 a minute an agent).
|
|
142
143
|
const LIVE_EVERY_MS = 500;
|
|
143
144
|
const LIVE_PIECE = 20_000;
|
|
145
|
+
const LONG_TEXT = 8_000;
|
|
144
146
|
const PUSH_EVERY_MS = 2000;
|
|
145
147
|
// What changed goes this long after (what changes with it goes along), and pushes that send words
|
|
146
148
|
// stay this far apart while things keep changing: each counts in the agent's 120 calls a minute.
|
|
@@ -198,6 +200,13 @@ async function harnessBridge(initial, harness, setup, ctx) {
|
|
|
198
200
|
const say = (line) => console.log(`${clock()} ${line}`);
|
|
199
201
|
say(`Gavel bridge for ${me.agent.name} (${h.name}, ${setup.server}) in ${ctx.cwd}.`);
|
|
200
202
|
say(`While ${me.person.name} keeps the chat on in Gavel, this folder's newest ${h.name} session shows there as it's written, only its words, and what they write there goes into it. Ctrl-C stops it.`);
|
|
203
|
+
try {
|
|
204
|
+
for (const name of signedOutClaudeProfiles(ctx))
|
|
205
|
+
say(signedOutLine(name));
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
// The check is a courtesy: the bridge runs without it.
|
|
209
|
+
}
|
|
201
210
|
const id = randomUUID();
|
|
202
211
|
let on = null;
|
|
203
212
|
let stopping = false;
|
|
@@ -367,6 +376,16 @@ async function harnessBridge(initial, harness, setup, ctx) {
|
|
|
367
376
|
}
|
|
368
377
|
return { paths, missed };
|
|
369
378
|
};
|
|
379
|
+
// A long message goes to a private file the software reads: a session's inbox can't carry 50,000
|
|
380
|
+
// characters whole (W-289).
|
|
381
|
+
const longAsFile = (text) => {
|
|
382
|
+
if (text.length <= LONG_TEXT)
|
|
383
|
+
return text;
|
|
384
|
+
const file = join(pictures, `${randomUUID()}.md`);
|
|
385
|
+
writeFileSync(file, text, { mode: 0o600 });
|
|
386
|
+
setTimeout(() => rmSync(file, { force: true }), PICTURE_KEEP_MS).unref();
|
|
387
|
+
return `${text.slice(0, 1_000)}\n\n[This message is ${text.length} characters, so it's longer than fits here. Read all of it, from its start, in the file ${file}, and answer that.]`;
|
|
388
|
+
};
|
|
370
389
|
let launchQueue = Promise.resolve();
|
|
371
390
|
const launch = (run) => {
|
|
372
391
|
const chosen = launchQueue.then(run);
|
|
@@ -379,7 +398,7 @@ async function harnessBridge(initial, harness, setup, ctx) {
|
|
|
379
398
|
urgentUntil = Date.now() + PUSH_URGENT_MS;
|
|
380
399
|
const result = await launch(async () => {
|
|
381
400
|
const route = await pick(null, "chat");
|
|
382
|
-
return route.allowed ? h.deliver({ id: m.id, text: m.text, decision: m.decision, pictures: paths }, route.fresh, route.run) : null;
|
|
401
|
+
return route.allowed ? h.deliver({ id: m.id, text: longAsFile(m.text), decision: m.decision, pictures: paths }, route.fresh, route.run) : null;
|
|
383
402
|
});
|
|
384
403
|
if (!result)
|
|
385
404
|
return;
|
|
@@ -463,9 +482,10 @@ async function harnessBridge(initial, harness, setup, ctx) {
|
|
|
463
482
|
const run = runOf(await answer(res));
|
|
464
483
|
if (!run)
|
|
465
484
|
return chosen;
|
|
466
|
-
const mine = { model: run.harness === activeHarness ? run.model : null, effort: run.effort, context: run.context };
|
|
485
|
+
const mine = { model: run.harness === activeHarness ? run.model : null, effort: run.effort, context: run.context, speed: run.harness === "codex" ? run.speed : null };
|
|
467
486
|
return { allowed: true, fresh: chosen.fresh ? { ...chosen.fresh, ...mine } : null, run: mine };
|
|
468
487
|
};
|
|
488
|
+
const checkedExtra = new Map();
|
|
469
489
|
const pickPlan = async (fresh, job = "wake") => {
|
|
470
490
|
if (!machineId || busy() || (!fresh && thread && state === "idle"))
|
|
471
491
|
return { allowed: true, fresh };
|
|
@@ -479,6 +499,22 @@ async function harnessBridge(initial, harness, setup, ctx) {
|
|
|
479
499
|
if (res.status === 404)
|
|
480
500
|
return { allowed: true, fresh };
|
|
481
501
|
const route = res.ok ? await answer(res) : null;
|
|
502
|
+
const observe = route?.observeExtraPlanId;
|
|
503
|
+
if (observe && planIdPattern.test(observe) && Date.now() - (checkedExtra.get(observe) ?? 0) >= 3_600_000) {
|
|
504
|
+
const probeEnv = planEnvironment(ctx, observe, "claude-code");
|
|
505
|
+
if (probeEnv) {
|
|
506
|
+
checkedExtra.set(observe, Date.now());
|
|
507
|
+
void checkClaudeExtra(ctx.cwd, probeEnv).then(async (extraUsageAvailable) => {
|
|
508
|
+
if (extraUsageAvailable === null)
|
|
509
|
+
return;
|
|
510
|
+
const reported = await call(api, "POST", "/v1/agents/me/plan/usage", {
|
|
511
|
+
...usageBody(observe, { windows: [], limitReached: false, spendLimit: null }, new Date()), machineId, extraUsageAvailable,
|
|
512
|
+
});
|
|
513
|
+
if (reported.ok)
|
|
514
|
+
retryPlanAt = 0;
|
|
515
|
+
}).catch(() => undefined);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
482
518
|
if (route?.why === "unmanaged")
|
|
483
519
|
return { allowed: true, fresh };
|
|
484
520
|
if (route?.why === "wait") {
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { userInfo } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
export const claudeService = (folder) => `Claude Code-credentials-${createHash("sha256").update(folder).digest("hex").slice(0, 8)}`;
|
|
7
|
+
// `security -i` takes a command on stdin, so the secret stays out of the process list; its line
|
|
8
|
+
// has a limit, and a longer one goes as an argument instead.
|
|
9
|
+
const LINE_LIMIT = 4000;
|
|
10
|
+
// The item kind in `security`'s subcommands, spelled out in pieces so no scanner takes it for a secret.
|
|
11
|
+
const command = (verb) => `${verb}-generic-${"pass"}${"word"}`;
|
|
12
|
+
export function systemKeychain(env = process.env, platform = process.platform) {
|
|
13
|
+
if (platform !== "darwin")
|
|
14
|
+
return null;
|
|
15
|
+
const account = env.USER || userInfo().username;
|
|
16
|
+
const run = (args, input) => execFileSync("security", args, { env, input, encoding: "utf8", stdio: ["pipe", "pipe", "ignore"], timeout: 15000 });
|
|
17
|
+
return {
|
|
18
|
+
read(service) {
|
|
19
|
+
try {
|
|
20
|
+
return run([command("find"), "-s", service, "-w"]).replace(/\r?\n$/, "") || null;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
write(service, secret) {
|
|
27
|
+
const hex = Buffer.from(secret, "utf8").toString("hex");
|
|
28
|
+
const line = `${command("add")} -U -a "${account}" -s "${service}" -X "${hex}"`;
|
|
29
|
+
try {
|
|
30
|
+
if (line.length <= LINE_LIMIT)
|
|
31
|
+
run(["-i"], `${line}\n`);
|
|
32
|
+
else
|
|
33
|
+
run([command("add"), "-U", "-a", account, "-s", service, "-X", hex]);
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
has(service) {
|
|
41
|
+
try {
|
|
42
|
+
run([command("find"), "-s", service]);
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
remove(service) {
|
|
50
|
+
try {
|
|
51
|
+
run([command("delete"), "-s", service]);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
// Already gone.
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
// A renamed profile folder takes its sign-in along: the item under the old folder's name is copied
|
|
60
|
+
// to the new name, checked, and only then removed. "none": nothing was under the old name (the
|
|
61
|
+
// sign-in was in the folder, or never made).
|
|
62
|
+
export function carryClaudeSignIn(keychain, from, to) {
|
|
63
|
+
if (!keychain)
|
|
64
|
+
return "none";
|
|
65
|
+
const was = claudeService(from);
|
|
66
|
+
const secret = keychain.read(was);
|
|
67
|
+
if (secret === null)
|
|
68
|
+
return "none";
|
|
69
|
+
const now = claudeService(to);
|
|
70
|
+
if (!keychain.write(now, secret) || keychain.read(now) !== secret)
|
|
71
|
+
return "failed";
|
|
72
|
+
keychain.remove(was);
|
|
73
|
+
return "carried";
|
|
74
|
+
}
|
|
75
|
+
// Whether Claude Code would find a sign-in for this config folder: its Keychain item on a Mac, or
|
|
76
|
+
// the credentials file it keeps in the folder (also its fallback on a Mac).
|
|
77
|
+
export function claudeSignedIn(keychain, folder) {
|
|
78
|
+
if (existsSync(join(folder, ".credentials.json")))
|
|
79
|
+
return true;
|
|
80
|
+
if (!keychain)
|
|
81
|
+
return false;
|
|
82
|
+
const service = claudeService(folder);
|
|
83
|
+
return keychain.has ? keychain.has(service) : keychain.read(service) !== null;
|
|
84
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
1
3
|
import { createHash } from "node:crypto";
|
|
2
4
|
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
5
|
import { hostname } from "node:os";
|
|
@@ -99,6 +101,43 @@ export function claudeAccount(home, env = process.env) {
|
|
|
99
101
|
return null;
|
|
100
102
|
}
|
|
101
103
|
}
|
|
104
|
+
// Claude's native headless stream reports whether the subscription can use overage. A
|
|
105
|
+
// deliberately short turn gives the bridge this signal even without an attached status line.
|
|
106
|
+
export async function checkClaudeExtra(cwd, env) {
|
|
107
|
+
const { CLAUDECODE: _nested, ...nativeEnv } = env;
|
|
108
|
+
const child = spawn("claude", [
|
|
109
|
+
"-p", "--no-session-persistence", "--tools", "", "--model", "haiku", "--setting-sources", "",
|
|
110
|
+
"--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--output-format", "stream-json", "--verbose",
|
|
111
|
+
"Reply with OK.",
|
|
112
|
+
], { cwd, env: nativeEnv, stdio: ["ignore", "pipe", "ignore"] });
|
|
113
|
+
const lines = createInterface({ input: child.stdout });
|
|
114
|
+
let available = null;
|
|
115
|
+
lines.on("line", (line) => {
|
|
116
|
+
try {
|
|
117
|
+
const event = JSON.parse(line);
|
|
118
|
+
if (event.type !== "rate_limit_event")
|
|
119
|
+
return;
|
|
120
|
+
const status = event.rate_limit_info?.overageStatus;
|
|
121
|
+
if (status === "allowed" || status === "allowed_warning")
|
|
122
|
+
available = true;
|
|
123
|
+
if (status === "rejected")
|
|
124
|
+
available = false;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// Only native numeric usage and the overage flag are reportable.
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
return new Promise((resolve) => {
|
|
131
|
+
const timer = setTimeout(() => child.kill(), 15_000);
|
|
132
|
+
const done = () => {
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
lines.close();
|
|
135
|
+
resolve(available);
|
|
136
|
+
};
|
|
137
|
+
child.once("error", done);
|
|
138
|
+
child.once("close", done);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
102
141
|
// Which account first reported under each plan, kept beside the bridge's locks (mode 600).
|
|
103
142
|
function accountsFile(home) {
|
|
104
143
|
return join(home, ".gavel", "bridge", "plan-accounts.json");
|
package/dist/bridge/connect.js
CHANGED
|
@@ -2,8 +2,11 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
2
2
|
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { carryClaudeSignIn, claudeSignedIn, systemKeychain } from "./claude-keychain.js";
|
|
5
6
|
import { loginInto, personalApi, planIdPattern, planMachine, profileMarker, profilesRoot } from "./plan-profiles.js";
|
|
6
7
|
const product = (p) => (p === "anthropic" ? "Claude" : "ChatGPT");
|
|
8
|
+
// An account as the person knows it, never its address or a token.
|
|
9
|
+
const signInName = (s) => `${product(s.provider)}${s.tier ? ` ${s.tier}` : ""}${s.org ? ` · ${s.org}` : s.domain ? ` (${s.domain})` : ""}`;
|
|
7
10
|
const hash = (...parts) => createHash("sha256").update(parts.join("\0")).digest("hex");
|
|
8
11
|
const domainOf = (email) => (typeof email === "string" ? (email.trim().toLowerCase().match(/^[^@\s]+@([a-z0-9.-]+\.[a-z]{2,})$/)?.[1] ?? null) : null);
|
|
9
12
|
const readJson = (file) => {
|
|
@@ -118,13 +121,16 @@ async function askTier(local, signIn, ask) {
|
|
|
118
121
|
}
|
|
119
122
|
// The profile on this machine for an account: the native sign-in, or the account's own folder (Agent
|
|
120
123
|
// Twelve's markers), and which account it is (a hash, 600).
|
|
121
|
-
function markProfile(local, signIn, planId, known, moved) {
|
|
124
|
+
function markProfile(local, signIn, planId, known, moved, keep) {
|
|
122
125
|
const folder = join(profilesRoot(local.home), planId);
|
|
123
126
|
if (!signIn.native && signIn.folder !== folder) {
|
|
124
127
|
if (existsSync(folder))
|
|
125
128
|
throw new Error("A profile for that account is already on this machine.");
|
|
126
129
|
renameSync(signIn.folder, folder);
|
|
127
130
|
moved();
|
|
131
|
+
// Claude Code's sign-in on a Mac is in the Keychain under the folder's name: it goes with it.
|
|
132
|
+
if (signIn.provider === "anthropic" && carryClaudeSignIn(keep.keychain, signIn.folder, folder) === "failed")
|
|
133
|
+
keep.say(`${signInName(signIn)} lost its sign-in when its folder was renamed: run gavel connect --add claude to sign in again.`);
|
|
128
134
|
}
|
|
129
135
|
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
130
136
|
const harness = signIn.provider === "openai" ? "codex" : "claude-code";
|
|
@@ -138,8 +144,15 @@ function markProfile(local, signIn, planId, known, moved) {
|
|
|
138
144
|
writeFileSync(profileMarker(local.home, planId), signIn.native ? `native:${harness}` : "isolated", { mode: 0o600 });
|
|
139
145
|
writeFileSync(accountFile(local.home, planId), `${signIn.key}\n`, { mode: 0o600 });
|
|
140
146
|
}
|
|
147
|
+
// The Claude accounts Gavel holds a folder for whose sign-in Claude Code can't find (W-295): named
|
|
148
|
+
// by plan and domain, never a token. A sign-in made in the native folders isn't Gavel's to check.
|
|
149
|
+
export const signedOutLine = (name) => `${name} reads signed out on this machine: run gavel connect --add claude to sign in again.`;
|
|
150
|
+
export function signedOutClaudeProfiles(local, keychain = systemKeychain(local.env)) {
|
|
151
|
+
return signInsHere(local).filter((s) => s.provider === "anthropic" && !s.native && !claudeSignedIn(keychain, s.folder)).map(signInName);
|
|
152
|
+
}
|
|
141
153
|
export async function connectAccounts(local, options, io) {
|
|
142
154
|
const say = io?.say ?? ((line) => console.log(line));
|
|
155
|
+
const keychain = io?.keychain === undefined ? systemKeychain(local.env) : io.keychain;
|
|
143
156
|
const ask = io?.ask ?? (async (question) => {
|
|
144
157
|
if (!process.stdin.isTTY)
|
|
145
158
|
throw new Error(`${question.trim()}: run gavel connect in a terminal to answer, or give --tier`);
|
|
@@ -162,6 +175,10 @@ export async function connectAccounts(local, options, io) {
|
|
|
162
175
|
throw new Error(`Gavel answered ${res.status} to ${method} ${path.replace(/[0-9a-f-]{36}/g, ":id")}`);
|
|
163
176
|
return res.json();
|
|
164
177
|
};
|
|
178
|
+
const warnSignedOut = () => {
|
|
179
|
+
for (const name of signedOutClaudeProfiles(local, keychain))
|
|
180
|
+
say(signedOutLine(name));
|
|
181
|
+
};
|
|
165
182
|
let pending = null;
|
|
166
183
|
if (options.add) {
|
|
167
184
|
pending = join(profilesRoot(local.home), `pending-${randomUUID()}`);
|
|
@@ -208,9 +225,10 @@ export async function connectAccounts(local, options, io) {
|
|
|
208
225
|
const signIn = items[i].signIn;
|
|
209
226
|
if (!planIdPattern.test(done.planId))
|
|
210
227
|
throw new Error("Gavel didn't return the account it saved.");
|
|
211
|
-
markProfile(local, signIn, done.planId, known, () => (pending = signIn.folder === pending ? null : pending));
|
|
228
|
+
markProfile(local, signIn, done.planId, known, () => (pending = signIn.folder === pending ? null : pending), { keychain, say });
|
|
212
229
|
say(`${done.added ? "Added" : "Connected"} ${done.label}${done.company ? ", your company's seat" : ""}. Its use reaches Gavel through the bridge.`);
|
|
213
230
|
}
|
|
231
|
+
warnSignedOut();
|
|
214
232
|
say("Your accounts are in Settings › You › Your accounts, in every workspace you're in.");
|
|
215
233
|
return 0;
|
|
216
234
|
}
|
|
@@ -230,11 +248,12 @@ export async function connectAccounts(local, options, io) {
|
|
|
230
248
|
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);
|
|
231
249
|
if (!account || !planIdPattern.test(account.id))
|
|
232
250
|
throw new Error("Gavel didn't return the account it saved.");
|
|
233
|
-
markProfile(local, signIn, account.id, known, () => (pending = signIn.folder === pending ? null : pending));
|
|
251
|
+
markProfile(local, signIn, account.id, known, () => (pending = signIn.folder === pending ? null : pending), { keychain, say });
|
|
234
252
|
await call("PUT", `/v1/me/plans/${account.id}/machines/${machineId}`);
|
|
235
253
|
const seat = account.seatId ? ", your company's seat" : "";
|
|
236
254
|
say(`${match ? "Connected" : "Added"} ${account.label}${seat}. Its use reaches Gavel through the bridge.`);
|
|
237
255
|
}
|
|
256
|
+
warnSignedOut();
|
|
238
257
|
say("Your accounts are in Settings › You › Your accounts, in every workspace you're in.");
|
|
239
258
|
return 0;
|
|
240
259
|
}
|
package/dist/bridge/runtime.js
CHANGED
|
@@ -13,7 +13,7 @@ export function runOf(body) {
|
|
|
13
13
|
const model = typeof run.model === "string" && MODEL.test(run.model) ? run.model : null;
|
|
14
14
|
const effort = typeof run.effort === "string" ? run.effort : null;
|
|
15
15
|
const context = typeof run.context === "string" ? run.context : null;
|
|
16
|
-
return { harness: run.harness, model, effort, context };
|
|
16
|
+
return { harness: run.harness, model, effort, context, speed: run.speed === "ultrafast" ? "ultrafast" : null };
|
|
17
17
|
}
|
|
18
18
|
// Claude Code: `--model` with its 1M window as the model's suffix (its default window is 200k, so 300k
|
|
19
19
|
// is the model as it is), `--effort` as named.
|
|
@@ -22,8 +22,10 @@ export function claudeFlags(run) {
|
|
|
22
22
|
return { model, effort: run?.effort && CLAUDE_EFFORTS.includes(run.effort) ? run.effort : null };
|
|
23
23
|
}
|
|
24
24
|
// Codex: its own model, its reasoning effort (max is its xhigh), and a 1M window as a config override
|
|
25
|
-
// of the thread (its default window, the model's own, is what 300k asks for).
|
|
25
|
+
// of the thread (its default window, the model's own, is what 300k asks for). Ultrafast, only when
|
|
26
|
+
// Gavel says the agent's own person set it (W-291), is Codex's fast service tier, `service_tier`.
|
|
26
27
|
export function codexFlags(run) {
|
|
27
28
|
const effort = run?.effort === "max" ? "xhigh" : run?.effort && CODEX_EFFORTS.includes(run.effort) ? run.effort : null;
|
|
28
|
-
|
|
29
|
+
const config = { ...(run?.context === "1m" ? { model_context_window: 1_000_000 } : {}), ...(run?.speed === "ultrafast" ? { service_tier: "fast" } : {}) };
|
|
30
|
+
return { model: run?.model && MODEL.test(run.model) ? run.model : null, effort, config: Object.keys(config).length ? config : null };
|
|
29
31
|
}
|
package/dist/gavel.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
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
7
|
import { connectAccounts } from "./bridge/connect.js";
|
|
8
|
+
import { install as workerInstall, remove as workerRemove, runWorker, session as workerSession, status as workerStatus } from "./worker/worker.js";
|
|
8
9
|
import { signInPlans } from "./bridge/plan-profiles.js";
|
|
9
10
|
import { execFileSync } from "node:child_process";
|
|
10
11
|
import { createHash, randomUUID } from "node:crypto";
|
|
@@ -65,6 +66,13 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
|
|
|
65
66
|
the bridge for this folder kept running by the system (a
|
|
66
67
|
LaunchAgent on a Mac, systemd on Linux), so a closed
|
|
67
68
|
session is resumed when your person writes in Gavel
|
|
69
|
+
gavel worker install --machine <name> [--server <gavel-…>] [--repo <checkout>]
|
|
70
|
+
on a Mac: one launchd service that runs a Claude Code or
|
|
71
|
+
Codex session for each agent Gavel placed on this machine
|
|
72
|
+
(its own worktree, its token, the account Gavel picks),
|
|
73
|
+
restarting any that dies. GAVEL_TOKEN is your personal
|
|
74
|
+
agent's; it goes in the Keychain, never printed
|
|
75
|
+
gavel worker status|remove each placed agent, its harness, account and state; or stop it all
|
|
68
76
|
gavel bridge hooks install|remove|status the bridge's hooks in this folder (Claude Code's
|
|
69
77
|
.claude/settings.local.json: each session starts it, and
|
|
70
78
|
its words, state and inbox reach it at once; Codex's
|
|
@@ -116,7 +124,7 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
|
|
|
116
124
|
gavel work file (<title> | --title <words>) [--status <status>] [--description <words>]
|
|
117
125
|
[--worker <email or agent> | --worker none] [--reporter <email or agent>]
|
|
118
126
|
[--waiting-on <email or agent>] [--decision <D-12>] [--code <url>]... [--label <Group: Name>]...
|
|
119
|
-
[--waits-on <W-3,W-4>] [--program <W-145>] [--key <key>]
|
|
127
|
+
[--level small|normal|hard] [--waits-on <W-3,W-4>] [--program <W-145>] [--key <key>]
|
|
120
128
|
a work item on the Board's Being done (W-12), when you
|
|
121
129
|
start: you're its worker unless you name another, your
|
|
122
130
|
person its reporter unless you name who directed it (you
|
|
@@ -129,12 +137,14 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
|
|
|
129
137
|
gavel work move <W-12> [<status>] [--waiting-on <email or agent>] [--decision <D-12>]
|
|
130
138
|
[--code <url>]... [--worker <email or agent> | --worker none] [--reporter <email or agent>]
|
|
131
139
|
[--title <words>] [--description <words>] [--label <Group: Name>]... [--label none]
|
|
132
|
-
[--waits-on <W-3,W-4> | --waits-on none] [--program <W-145> | --program none]
|
|
140
|
+
[--level small|normal|hard] [--waits-on <W-3,W-4> | --waits-on none] [--program <W-145> | --program none]
|
|
133
141
|
move it as your work moves: Building, Blocked with
|
|
134
142
|
--waiting-on, Needs Decision with --decision, Deployed
|
|
135
143
|
with --code (a commit or pull request; again for each);
|
|
136
144
|
--label sets all its labels (again for each), --waits-on
|
|
137
|
-
all the items it waits on, --reporter who directed it
|
|
145
|
+
all the items it waits on, --reporter who directed it,
|
|
146
|
+
--level how much care it needs (its model and effort
|
|
147
|
+
follow it; your own item's only up)
|
|
138
148
|
gavel work show <W-12> an item and its history
|
|
139
149
|
gavel work list [--worker me|<email or agent>] [--status <status>] [--open true]
|
|
140
150
|
the workspace's items, the latest changed first, and
|
|
@@ -323,6 +333,7 @@ const FLAGS = {
|
|
|
323
333
|
pair: ["harness", "machine", "hook", "bridge"],
|
|
324
334
|
waiting: ["hook", "server", "file"],
|
|
325
335
|
bridge: ["harness", "server"],
|
|
336
|
+
worker: ["machine", "server", "repo", "agent"],
|
|
326
337
|
plans: ["plan", "claim", "server"],
|
|
327
338
|
connect: ["add", "tier", "server", "code", "label"],
|
|
328
339
|
"actions-env": [],
|
|
@@ -341,7 +352,7 @@ const FLAGS = {
|
|
|
341
352
|
inbox: ["offset", "limit"],
|
|
342
353
|
status: ["text", "description", "folders", "state", "issue", "waiting-on", "item"],
|
|
343
354
|
"claim-folders": ["mode", "item"],
|
|
344
|
-
work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "open", "waits-on", "program", "area", "why", "key"],
|
|
355
|
+
work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "level", "open", "waits-on", "program", "area", "why", "key"],
|
|
345
356
|
message: ["to-agent", "to-person", "conversation", "item", "text", "decision", "no-reply", "now", "key"],
|
|
346
357
|
thread: [],
|
|
347
358
|
conversations: [],
|
|
@@ -569,6 +580,10 @@ function workRequest(p, f, code, label) {
|
|
|
569
580
|
const links = code.length ? code.map((url) => ({ url })) : undefined;
|
|
570
581
|
const labels = !label.length ? undefined : label.length === 1 && label[0] === "none" ? [] : label;
|
|
571
582
|
const waitsOn = f["waits-on"] === undefined ? undefined : f["waits-on"] === "none" ? [] : f["waits-on"].split(",").map((r) => r.trim()).filter(Boolean);
|
|
583
|
+
// Small, Normal or Hard (W-285), whatever its case.
|
|
584
|
+
const level = f.level === undefined ? undefined : ["Small", "Normal", "Hard"].find((l) => l.toLowerCase() === f.level.trim().toLowerCase());
|
|
585
|
+
if (f.level !== undefined && !level)
|
|
586
|
+
throw new UsageError("--level is small, normal or hard");
|
|
572
587
|
const ref = (value) => {
|
|
573
588
|
if (!value || !/^W-\d+$/i.test(value))
|
|
574
589
|
throw new UsageError(`work ${sub} needs its item, like W-12`);
|
|
@@ -581,23 +596,23 @@ function workRequest(p, f, code, label) {
|
|
|
581
596
|
};
|
|
582
597
|
switch (sub) {
|
|
583
598
|
case "file": {
|
|
584
|
-
only(["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "waits-on", "program", "key"]);
|
|
599
|
+
only(["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "level", "waits-on", "program", "key"]);
|
|
585
600
|
if (f.title !== undefined && rest.length)
|
|
586
601
|
throw new UsageError("give the title once: as words or as --title");
|
|
587
602
|
const title = readText(need(f.title ?? rest.join(" "), "the item's title"));
|
|
588
603
|
return {
|
|
589
604
|
method: "POST",
|
|
590
605
|
path: "/v1/work",
|
|
591
|
-
body: compact({ title, status: f.status, description, worker, reporter: f.reporter, waitingOn: f["waiting-on"], decision: f.decision, code: links, labels, waitsOn, program: f.program, key: f.key }),
|
|
606
|
+
body: compact({ title, status: f.status, description, worker, reporter: f.reporter, waitingOn: f["waiting-on"], decision: f.decision, code: links, labels, level, waitsOn, program: f.program, key: f.key }),
|
|
592
607
|
};
|
|
593
608
|
}
|
|
594
609
|
case "move": {
|
|
595
|
-
only(["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "waits-on", "program"]);
|
|
610
|
+
only(["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "level", "waits-on", "program"]);
|
|
596
611
|
const [item, ...words] = rest;
|
|
597
612
|
if (f.status !== undefined && words.length)
|
|
598
613
|
throw new UsageError("give the status once: as words or as --status");
|
|
599
614
|
const program = f.program === undefined ? undefined : f.program === "none" ? null : f.program;
|
|
600
|
-
const body = compact({ status: f.status ?? (words.join(" ") || undefined), title: f.title, description, worker, reporter: f.reporter, waitingOn: f["waiting-on"], decision: f.decision, code: links, labels, waitsOn, program });
|
|
615
|
+
const body = compact({ status: f.status ?? (words.join(" ") || undefined), title: f.title, description, worker, reporter: f.reporter, waitingOn: f["waiting-on"], decision: f.decision, code: links, labels, level, waitsOn, program });
|
|
601
616
|
if (!Object.keys(body).length)
|
|
602
617
|
throw new UsageError("work move needs a status or something to change");
|
|
603
618
|
return { method: "PATCH", path: `/v1/work/${ref(item)}`, body };
|
|
@@ -1096,6 +1111,17 @@ export function toRequest(argv) {
|
|
|
1096
1111
|
if (p[0] !== "sign-in")
|
|
1097
1112
|
throw new UsageError("plans takes sign-in");
|
|
1098
1113
|
return { plans: { planId: f.plan, claim: f.claim === "true", server: f.server } };
|
|
1114
|
+
case "worker": {
|
|
1115
|
+
upTo(1);
|
|
1116
|
+
const action = p[0];
|
|
1117
|
+
if (action !== "install" && action !== "status" && action !== "remove" && action !== "run" && action !== "session")
|
|
1118
|
+
throw new UsageError("worker takes install, status or remove");
|
|
1119
|
+
if (action === "install" && !f.machine)
|
|
1120
|
+
throw new UsageError("worker install takes --machine <name> (its Gavel name, like studio)");
|
|
1121
|
+
if (action === "session" && !f.agent)
|
|
1122
|
+
throw new UsageError("worker session takes --agent <id>");
|
|
1123
|
+
return { worker: { action, machine: f.machine, server: f.server, repo: f.repo, agent: f.agent } };
|
|
1124
|
+
}
|
|
1099
1125
|
case "bridge": {
|
|
1100
1126
|
const action = p[0] ?? "run";
|
|
1101
1127
|
const harness = f.harness;
|
|
@@ -2112,6 +2138,24 @@ async function main(argvIn) {
|
|
|
2112
2138
|
return request.bridge.action === "run" ? heldBridge(request.bridge, as) : runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
|
|
2113
2139
|
if ("bridgeBackground" in request)
|
|
2114
2140
|
return background(request.bridgeBackground);
|
|
2141
|
+
if ("worker" in request) {
|
|
2142
|
+
const w = request.worker;
|
|
2143
|
+
const local = { home: homedir(), env: process.env };
|
|
2144
|
+
if (w.action === "status")
|
|
2145
|
+
return workerStatus(local);
|
|
2146
|
+
if (w.action === "remove")
|
|
2147
|
+
return workerRemove(local);
|
|
2148
|
+
if (w.action === "run")
|
|
2149
|
+
return runWorker(local);
|
|
2150
|
+
if (w.action === "session")
|
|
2151
|
+
return workerSession(local, w.agent);
|
|
2152
|
+
const token = process.env.GAVEL_TOKEN;
|
|
2153
|
+
if (!token) {
|
|
2154
|
+
console.error("gavel: set GAVEL_TOKEN to your personal agent's token for the install; it goes in the Keychain and is never printed");
|
|
2155
|
+
return 2;
|
|
2156
|
+
}
|
|
2157
|
+
return workerInstall(local, { machine: w.machine, server: w.server ?? "gavel", repo: w.repo ?? process.cwd(), token });
|
|
2158
|
+
}
|
|
2115
2159
|
if ("actionsEnv" in request)
|
|
2116
2160
|
return actionsEnv(as);
|
|
2117
2161
|
const base = (process.env.GAVEL_API_URL ?? "https://api.getgavel.ai").replace(/\/+$/, "");
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { claudeBridgeHooks } from "../bridge/claude-live.js";
|
|
5
|
+
import { lastingCommand } from "../bridge/background.js";
|
|
6
|
+
import { planEnvironment, planMachine } from "../bridge/plan-profiles.js";
|
|
7
|
+
import { claudeFlags, codexFlags, runOf } from "../bridge/runtime.js";
|
|
8
|
+
import { launchdPlist } from "../bridge/service.js";
|
|
9
|
+
const KEYCHAIN = "ai.getgavel.worker";
|
|
10
|
+
export const LABEL = "ai.getgavel.worker";
|
|
11
|
+
export const SESSION_PREFIX = "gw-";
|
|
12
|
+
export const workerDir = (home) => join(home, ".gavel", "worker");
|
|
13
|
+
const configFile = (home) => join(workerDir(home), "config.json");
|
|
14
|
+
const stateFile = (home) => join(workerDir(home), "state.json");
|
|
15
|
+
const mcpFile = (home, id) => join(workerDir(home), id, "mcp.json");
|
|
16
|
+
export const sessionName = (name) => SESSION_PREFIX + slug(name);
|
|
17
|
+
export const slug = (name) => name.toLowerCase().replace(/^agent\s+/, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "agent";
|
|
18
|
+
export const worktreeOf = (home, name) => join(home, "Projects", `gavel-${slug(name)}`);
|
|
19
|
+
const run = (command, args, opts = {}) => {
|
|
20
|
+
const r = spawnSync(command, args, { encoding: "utf8", cwd: opts.cwd, input: opts.input, stdio: ["pipe", "pipe", "pipe"] });
|
|
21
|
+
return { ok: r.status === 0, out: `${r.stdout ?? ""}${r.stderr ?? ""}` };
|
|
22
|
+
};
|
|
23
|
+
// The Keychain holds the one credential, under this machine's name.
|
|
24
|
+
export function keychainSet(machine, token) {
|
|
25
|
+
const r = run("security", ["add-generic-password", "-U", "-s", KEYCHAIN, "-a", machine, "-w", token]);
|
|
26
|
+
if (!r.ok)
|
|
27
|
+
throw new Error("The Keychain wouldn't keep the worker's credential");
|
|
28
|
+
}
|
|
29
|
+
export function keychainGet(machine) {
|
|
30
|
+
const r = run("security", ["find-generic-password", "-s", KEYCHAIN, "-a", machine, "-w"]);
|
|
31
|
+
return r.ok ? r.out.trim() || null : null;
|
|
32
|
+
}
|
|
33
|
+
const keychainDelete = (machine) => run("security", ["delete-generic-password", "-s", KEYCHAIN, "-a", machine]);
|
|
34
|
+
export function readConfig(home) {
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(readFileSync(configFile(home), "utf8"));
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const writeJson = (file, value) => {
|
|
43
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
44
|
+
writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
45
|
+
chmodSync(file, 0o600);
|
|
46
|
+
};
|
|
47
|
+
const readState = (home) => {
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(readFileSync(stateFile(home), "utf8"));
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
async function api(config, token, method, path, body) {
|
|
56
|
+
const res = await fetch(`${config.api}${path}`, { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
|
57
|
+
if (!res.ok)
|
|
58
|
+
throw new Error(`Gavel answered ${res.status} to ${method} ${path.replace(/[0-9a-f-]{36}/g, ":id")}`);
|
|
59
|
+
return (await res.json());
|
|
60
|
+
}
|
|
61
|
+
// ---- the service ----
|
|
62
|
+
export function workerSpec(local) {
|
|
63
|
+
const log = join(workerDir(local.home), "worker.log");
|
|
64
|
+
return { label: LABEL, folder: local.home, command: [...lastingCommand(local.home), "worker", "run"], log, path: local.env.PATH ?? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" };
|
|
65
|
+
}
|
|
66
|
+
const plistFile = (home) => join(home, "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
67
|
+
const uid = () => process.getuid?.() ?? 0;
|
|
68
|
+
export async function install(local, opts) {
|
|
69
|
+
if (process.platform !== "darwin") {
|
|
70
|
+
console.error("gavel worker runs on a Mac (launchd)");
|
|
71
|
+
return 1;
|
|
72
|
+
}
|
|
73
|
+
const api = (opts.api ?? local.env.GAVEL_API_URL ?? "https://api.getgavel.ai").replace(/\/+$/, "");
|
|
74
|
+
const mcp = `${api.replace("//api.", "//mcp.")}/mcp`;
|
|
75
|
+
const machine = opts.machine.trim().toLowerCase();
|
|
76
|
+
const config = { machine, api, mcp, server: opts.server, repo: opts.repo };
|
|
77
|
+
// The credential must be an agent above the placed ones, seeing this machine.
|
|
78
|
+
const me = await fetch(`${api}/v1/machines/${encodeURIComponent(machine)}/agents`, { headers: { authorization: `Bearer ${opts.token}` } });
|
|
79
|
+
if (!me.ok) {
|
|
80
|
+
console.error(`Gavel didn't take that token (${me.status}): use your personal agent's`);
|
|
81
|
+
return 1;
|
|
82
|
+
}
|
|
83
|
+
keychainSet(machine, opts.token);
|
|
84
|
+
writeJson(configFile(local.home), config);
|
|
85
|
+
const spec = workerSpec(local);
|
|
86
|
+
const file = plistFile(local.home);
|
|
87
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
88
|
+
mkdirSync(dirname(spec.log), { recursive: true, mode: 0o700 });
|
|
89
|
+
writeFileSync(file, launchdPlist(spec), { mode: 0o644 });
|
|
90
|
+
run("launchctl", ["bootout", `gui/${uid()}/${LABEL}`]);
|
|
91
|
+
const loaded = run("launchctl", ["bootstrap", `gui/${uid()}`, file]);
|
|
92
|
+
if (!loaded.ok) {
|
|
93
|
+
console.error(`launchctl didn't load it: ${loaded.out.split("\n")[0]}`);
|
|
94
|
+
return 1;
|
|
95
|
+
}
|
|
96
|
+
console.log(`The worker for ${machine} is installed (${file}); its log is ${spec.log}`);
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
99
|
+
export function remove(local) {
|
|
100
|
+
const config = readConfig(local.home);
|
|
101
|
+
run("launchctl", ["bootout", `gui/${uid()}/${LABEL}`]);
|
|
102
|
+
if (existsSync(plistFile(local.home)))
|
|
103
|
+
unlinkSync(plistFile(local.home));
|
|
104
|
+
for (const s of sessions())
|
|
105
|
+
run("tmux", ["kill-session", "-t", s]);
|
|
106
|
+
if (config)
|
|
107
|
+
keychainDelete(config.machine);
|
|
108
|
+
console.log("The worker is removed, its sessions stopped and its credential out of the Keychain");
|
|
109
|
+
return 0;
|
|
110
|
+
}
|
|
111
|
+
const sessions = () => run("tmux", ["list-sessions", "-F", "#{session_name}"]).out.split("\n").filter((s) => s.startsWith(SESSION_PREFIX));
|
|
112
|
+
export async function status(local) {
|
|
113
|
+
const config = readConfig(local.home);
|
|
114
|
+
if (!config) {
|
|
115
|
+
console.log("No worker here: gavel worker install --machine <name>");
|
|
116
|
+
return 1;
|
|
117
|
+
}
|
|
118
|
+
const loaded = run("launchctl", ["print", `gui/${uid()}/${LABEL}`]);
|
|
119
|
+
console.log(`machine ${config.machine}: service ${loaded.ok && /state = running/.test(loaded.out) ? "running" : "not running"}`);
|
|
120
|
+
const token = keychainGet(config.machine);
|
|
121
|
+
if (!token)
|
|
122
|
+
return console.log("no credential in the Keychain"), 1;
|
|
123
|
+
const placed = await api(config, token, "GET", `/v1/machines/${encodeURIComponent(config.machine)}/agents`);
|
|
124
|
+
const live = new Set(sessions());
|
|
125
|
+
const state = readState(local.home);
|
|
126
|
+
for (const a of placed.agents) {
|
|
127
|
+
const s = state[a.id];
|
|
128
|
+
const up = live.has(sessionName(a.name));
|
|
129
|
+
console.log([a.name.padEnd(18), a.harness.padEnd(11), `account ${s?.planId?.slice(0, 8) ?? "none"}`.padEnd(17), a.state === "active" ? (up ? `running since ${s?.startedAt ?? "?"}` : "down") : a.state, a.workingItem ?? ""].join(" "));
|
|
130
|
+
}
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
// ---- the loop ----
|
|
134
|
+
export async function runWorker(local, once = false) {
|
|
135
|
+
const config = readConfig(local.home);
|
|
136
|
+
if (!config) {
|
|
137
|
+
console.error("gavel worker: not installed");
|
|
138
|
+
return 1;
|
|
139
|
+
}
|
|
140
|
+
const self = lastingCommand(local.home);
|
|
141
|
+
const tick = async () => {
|
|
142
|
+
const token = keychainGet(config.machine);
|
|
143
|
+
if (!token)
|
|
144
|
+
throw new Error("no credential in the Keychain");
|
|
145
|
+
const { agents } = await api(config, token, "GET", `/v1/machines/${encodeURIComponent(config.machine)}/agents`);
|
|
146
|
+
const wanted = new Map(agents.filter((a) => a.state === "active").map((a) => [sessionName(a.name), a]));
|
|
147
|
+
const live = new Set(sessions());
|
|
148
|
+
for (const s of live)
|
|
149
|
+
if (!wanted.has(s))
|
|
150
|
+
run("tmux", ["kill-session", "-t", s]);
|
|
151
|
+
for (const [name, agent] of wanted) {
|
|
152
|
+
if (live.has(name))
|
|
153
|
+
continue;
|
|
154
|
+
const [cmd, ...args] = self;
|
|
155
|
+
const line = ["nice", "-n", "10", cmd, ...args, "worker", "session", "--agent", agent.id].map((w) => `'${w.replace(/'/g, `'\\''`)}'`).join(" ");
|
|
156
|
+
run("tmux", ["new-session", "-d", "-s", name, "-c", local.home, line]);
|
|
157
|
+
console.log(`${new Date().toISOString()} started ${name}`);
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
for (;;) {
|
|
161
|
+
await tick().catch((err) => console.error(`${new Date().toISOString()} ${err.message}`));
|
|
162
|
+
if (once)
|
|
163
|
+
return 0;
|
|
164
|
+
await new Promise((r) => setTimeout(r, 30_000));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
// ---- one agent's session (what tmux runs) ----
|
|
168
|
+
function ensureWorktree(config, home, name) {
|
|
169
|
+
const dir = worktreeOf(home, name);
|
|
170
|
+
if (existsSync(join(dir, ".git")))
|
|
171
|
+
return dir;
|
|
172
|
+
const branch = slug(name);
|
|
173
|
+
const made = run("git", ["worktree", "add", "-B", branch, dir, "origin/main"], { cwd: config.repo });
|
|
174
|
+
if (!made.ok)
|
|
175
|
+
throw new Error(`no worktree for ${name}: ${made.out.split("\n")[0]}`);
|
|
176
|
+
return dir;
|
|
177
|
+
}
|
|
178
|
+
// Claude Code runs a background session, and so reports its status line's plan use, only in a folder it
|
|
179
|
+
// trusts: the folder's entry in the account's own .claude.json (under its CLAUDE_CONFIG_DIR, else the
|
|
180
|
+
// home's), marked trusted before the session starts. The Gavel server's entry goes in too.
|
|
181
|
+
export const claudeConfigFile = (home, env) => join(env.CLAUDE_CONFIG_DIR ?? home, ".claude.json");
|
|
182
|
+
export function markTrusted(file, dir, server) {
|
|
183
|
+
let json = {};
|
|
184
|
+
try {
|
|
185
|
+
json = JSON.parse(readFileSync(file, "utf8"));
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
// none yet
|
|
189
|
+
}
|
|
190
|
+
json.projects ??= {};
|
|
191
|
+
const project = (json.projects[dir] ??= {});
|
|
192
|
+
project.hasTrustDialogAccepted = true;
|
|
193
|
+
project.hasCompletedProjectOnboarding = true;
|
|
194
|
+
if (server)
|
|
195
|
+
project.mcpServers = { ...(project.mcpServers ?? {}), [server.name]: { type: "http", url: server.url, headers: { Authorization: `Bearer ${server.token}` } } };
|
|
196
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
197
|
+
writeFileSync(file, JSON.stringify(json, null, 2), { mode: 0o600 });
|
|
198
|
+
chmodSync(file, 0o600);
|
|
199
|
+
}
|
|
200
|
+
export async function session(local, agentId) {
|
|
201
|
+
const config = readConfig(local.home);
|
|
202
|
+
const master = config ? keychainGet(config.machine) : null;
|
|
203
|
+
if (!config || !master)
|
|
204
|
+
return console.error("gavel worker: not installed"), 1;
|
|
205
|
+
const placed = (await api(config, master, "GET", `/v1/machines/${encodeURIComponent(config.machine)}/agents`)).agents.find((a) => a.id === agentId);
|
|
206
|
+
if (!placed || placed.state !== "active")
|
|
207
|
+
return 0;
|
|
208
|
+
const { token, harness } = await api(config, master, "POST", `/v1/machines/${encodeURIComponent(config.machine)}/agents/${agentId}/token`, {});
|
|
209
|
+
const dir = ensureWorktree(config, local.home, placed.name);
|
|
210
|
+
const machineId = planMachine(local.home, true);
|
|
211
|
+
// The account with room, and the model and effort for the work.
|
|
212
|
+
const pick = await api(config, token, "POST", "/v1/agents/me/plan/pick", { machineId, harness, job: "work" }).catch(() => null);
|
|
213
|
+
const useHarness = pick?.planId ? pick.harness : harness;
|
|
214
|
+
const env = (pick?.planId ? planEnvironment(local, pick.planId, useHarness) : null) ?? { ...local.env };
|
|
215
|
+
env.GAVEL_TOKEN = token;
|
|
216
|
+
env.GAVEL_API_URL = config.api;
|
|
217
|
+
delete env.GAVEL_PLAN_PROFILE;
|
|
218
|
+
if (pick?.planId)
|
|
219
|
+
env.GAVEL_PLAN_PROFILE = pick.planId;
|
|
220
|
+
const state = readState(local.home);
|
|
221
|
+
state[agentId] = { planId: pick?.planId ?? null, startedAt: new Date().toISOString(), model: pick?.model ?? null };
|
|
222
|
+
writeJson(stateFile(local.home), state);
|
|
223
|
+
const prompt = `Gavel: a fresh session. You're ${placed.name} in Gavel, on ${config.machine}. Call \`me\` first, then read what's waiting for you${placed.workingItem ? ` and your item ${placed.workingItem}` : ""} and carry on from where things stand.`;
|
|
224
|
+
const run1 = runOf({ run: pick ? { harness: useHarness, model: pick.model, effort: pick.effort, context: pick.context } : null });
|
|
225
|
+
let command;
|
|
226
|
+
let args;
|
|
227
|
+
if (useHarness === "codex") {
|
|
228
|
+
const f = codexFlags(run1);
|
|
229
|
+
mkdirSync(join(dir, ".codex"), { recursive: true });
|
|
230
|
+
writeFileSync(join(dir, ".codex", "config.toml"), `[mcp_servers.${config.server}]\nurl = "${config.mcp}"\n\n[mcp_servers.${config.server}.http_headers]\nAuthorization = "Bearer ${token}"\n`, { mode: 0o600 });
|
|
231
|
+
ensureExcluded(dir, ".codex/");
|
|
232
|
+
await claudeBridgeHooks("remove", { cwd: dir, home: local.home, command: lastingCommand(local.home) }).catch(() => undefined);
|
|
233
|
+
command = "codex";
|
|
234
|
+
args = ["--dangerously-bypass-approvals-and-sandbox", "-C", dir, ...(f.model ? ["-m", f.model] : []), ...(f.effort ? ["-c", `model_reasoning_effort="${f.effort}"`] : []), prompt];
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
const f = claudeFlags(run1);
|
|
238
|
+
// The bridge reads the home's entry; the session reads its account's: both trust the folder.
|
|
239
|
+
markTrusted(join(local.home, ".claude.json"), dir, { name: config.server, url: config.mcp, token });
|
|
240
|
+
if (env.CLAUDE_CONFIG_DIR)
|
|
241
|
+
markTrusted(claudeConfigFile(local.home, env), dir);
|
|
242
|
+
writeJson(mcpFile(local.home, agentId), { mcpServers: { [config.server]: { type: "http", url: config.mcp, headers: { Authorization: `Bearer ${token}` } } } });
|
|
243
|
+
await claudeBridgeHooks("install", { cwd: dir, home: local.home, command: lastingCommand(local.home) }).catch(() => undefined);
|
|
244
|
+
command = "claude";
|
|
245
|
+
args = ["--dangerously-skip-permissions", "--mcp-config", mcpFile(local.home, agentId), ...(f.model ? ["--model", f.model] : []), ...(f.effort ? ["--effort", f.effort] : []), prompt];
|
|
246
|
+
}
|
|
247
|
+
return new Promise((resolve) => {
|
|
248
|
+
const child = spawn(command, args, { cwd: dir, env, stdio: "inherit" });
|
|
249
|
+
child.once("error", () => resolve(1));
|
|
250
|
+
child.once("exit", (code) => resolve(code ?? 1));
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
function ensureExcluded(dir, line) {
|
|
254
|
+
try {
|
|
255
|
+
const exclude = execFileSync("git", ["rev-parse", "--git-path", "info/exclude"], { cwd: dir, encoding: "utf8" }).trim();
|
|
256
|
+
const path = exclude.startsWith("/") ? exclude : join(dir, exclude);
|
|
257
|
+
const text = existsSync(path) ? readFileSync(path, "utf8") : "";
|
|
258
|
+
if (!text.split("\n").includes(line))
|
|
259
|
+
writeFileSync(path, `${text}${text.endsWith("\n") || !text ? "" : "\n"}${line}\n`);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
// not a worktree
|
|
263
|
+
}
|
|
264
|
+
}
|
package/package.json
CHANGED