@getgavel/cli 0.1.32 → 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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gavel",
3
- "version": "0.1.32",
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" },
@@ -8,6 +8,7 @@ import { claudeDayReporter, DAYS_EVERY_MS } from "./claude-days.js";
8
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";
@@ -199,6 +200,13 @@ async function harnessBridge(initial, harness, setup, ctx) {
199
200
  const say = (line) => console.log(`${clock()} ${line}`);
200
201
  say(`Gavel bridge for ${me.agent.name} (${h.name}, ${setup.server}) in ${ctx.cwd}.`);
201
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
+ }
202
210
  const id = randomUUID();
203
211
  let on = null;
204
212
  let stopping = false;
@@ -474,7 +482,7 @@ async function harnessBridge(initial, harness, setup, ctx) {
474
482
  const run = runOf(await answer(res));
475
483
  if (!run)
476
484
  return chosen;
477
- 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 };
478
486
  return { allowed: true, fresh: chosen.fresh ? { ...chosen.fresh, ...mine } : null, run: mine };
479
487
  };
480
488
  const checkedExtra = new Map();
@@ -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
+ }
@@ -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
  }
@@ -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
- return { model: run?.model && MODEL.test(run.model) ? run.model : null, effort, config: run?.context === "1m" ? { model_context_window: 1_000_000 } : null };
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.32",
3
+ "version": "0.1.33",
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",