@getgavel/cli 0.1.13 → 0.1.15

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/README.md CHANGED
@@ -16,7 +16,9 @@ npx @getgavel/cli pair <code>
16
16
  ```
17
17
 
18
18
  It writes your setup (Cursor's `mcp.json`, Claude Code, Codex, or an env file) and never prints
19
- your token. Or install the command once:
19
+ your token. With `--hook true` it also writes Gavel's end-of-turn hook for Cursor or Claude Code:
20
+ when your turn ends with something waiting for you in Gavel, you carry on (at most three times a
21
+ turn; if Gavel is down, the turn ends as usual). Or install the command once:
20
22
 
21
23
  ```sh
22
24
  npm i -g @getgavel/cli
@@ -31,8 +33,11 @@ gavel search "onboarding copy" # before you ask
31
33
  gavel ask --file decision.json # put a decision to your person
32
34
  gavel wait D-12 --timeout 60 # until it's decided
33
35
  gavel watch # one GAVEL_WAKE line per new thing for you; run it in the background
36
+ gavel waiting # what's waiting for you, in one line, or nothing
34
37
  gavel find "nudge a decision" # the API's routes for what you want, and who may call each
35
38
  gavel work claim # when you're free: your next ready task; work done W-12 when it ships
39
+ gavel claim-folders gavel/web/src/app # before you edit them: the folders you'll change, alone or adding lines
40
+ gavel link-cursor-run # in Cursor, when Gavel didn't start you: link this chat (then --code)
36
41
  gavel help # every command
37
42
  gavel act --help # one command's usage
38
43
  ```
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
- import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { basename, dirname, join, relative } from "node:path";
6
6
  import { claudeOpen, claudeResume, claudeSessions, claudeSettingsFile, claudeWords, withWakeHook } from "./claude-code.js";
@@ -154,7 +154,10 @@ async function bridge(run, ctx) {
154
154
  return;
155
155
  }
156
156
  mkdirSync(dirname(settings), { recursive: true });
157
- writeFileSync(settings, next);
157
+ // Claude Code reads it whenever it likes: it changes whole, through a temp file and a rename.
158
+ const temp = `${settings}.${process.pid}.tmp`;
159
+ writeFileSync(temp, next);
160
+ renameSync(temp, settings);
158
161
  if (want) {
159
162
  const ignored = keepOutOfGit(settingsName, ctx.cwd);
160
163
  say(`Added Gavel's wake hook to ${settingsName}, so an open session hears from ${me.person.name} even while idle; it comes out when the chat is off or the bridge stops.${ignored ? ` (${ignored}.)` : ""}`);
package/dist/gavel.js CHANGED
@@ -10,11 +10,18 @@ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, realpat
10
10
  import { homedir, hostname } from "node:os";
11
11
  import { basename, dirname, extname, join } from "node:path";
12
12
  import { BRIDGE_HARNESSES, runBridge } from "./bridge/bridge.js";
13
+ import { HOOK_HARNESSES, apiOf, claudeAnswer, cliVersion, cursorAnswer, installHook, setupFrom, waitingLine } from "./hook.js";
13
14
  const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
14
15
 
15
- gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>]
16
+ gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>] [--hook true]
16
17
  redeem your person's pairing code and write your setup
17
- (no GAVEL_TOKEN needed; never prints the token)
18
+ (no GAVEL_TOKEN needed; never prints the token); --hook
19
+ true also writes Gavel's end-of-turn hook (Cursor, Claude
20
+ Code): your turn carries on while something waits for you
21
+ gavel waiting [--hook cursor|claude-code] [--server <name> --file <its mcp.json or .claude.json>]
22
+ what's waiting for you in Gavel, in one line, or nothing;
23
+ --hook answers as that software's end-of-turn hook (run by
24
+ the hook, not by hand); always exits 0
18
25
  gavel bridge [--harness claude-code|codex] [--server <name>]
19
26
  run by a person in their agent's folder, beside it, until
20
27
  stopped: its newest Claude Code or Codex session's words in
@@ -54,6 +61,11 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
54
61
  sentence or two in --description; --waiting-on names the
55
62
  person or agent you're blocked on; --item your work item,
56
63
  which follows your state (Building, or Blocked)
64
+ gavel claim-folders <folder>... [--mode adding|alone] [--item <W-12>]
65
+ claim the folders you'll edit before editing (repo, then
66
+ path), beside those you hold: adding lines (shared with
67
+ others who only add) or alone; each overlap answered by
68
+ the workspace's rules, one they can't settle refused
57
69
  gavel work file (<title> | --title <words>) [--status <status>] [--description <words>]
58
70
  [--worker <email or agent> | --worker none] [--reporter <email or agent>]
59
71
  [--waiting-on <email or agent>] [--decision <D-12>] [--code <url>]... [--label <Group: Name>]...
@@ -77,7 +89,7 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
77
89
  its labels
78
90
  gavel work claim [--label <Group: Name>] [--area <area>]
79
91
  when you're free: the next ready item, yours in Building
80
- while you work (any call keeps it; 10 minutes quiet and
92
+ while you work (any call keeps it; 30 minutes quiet and
81
93
  it goes back to Queued); none ready, what's waiting
82
94
  gavel work renew <W-12> keep your claim through a long quiet stretch
83
95
  gavel work release <W-12> [--why <words>] let it go: back to Queued, the why in its history
@@ -120,6 +132,10 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
120
132
  gavel call <GET|POST|PUT|PATCH|DELETE> </v1/path> [--query <name=value>] [--body <file.json>]
121
133
  [--for-person true] any route of the API as you, or as your person with
122
134
  --for-person: MCP's do_action, the answer as it comes
135
+ gavel link-cursor-run [<bc-…> | none] [--code <code>]
136
+ your own Cursor run, when Gavel didn't start you (this
137
+ one by default, in a Cursor agent's shell): Gavel sends a
138
+ code into that chat; link again with --code; none unlinks
123
139
  gavel find (<words> | --query <words>) [--limit <n>]
124
140
  the API's routes for what you want to do, who may call each
125
141
  gavel me
@@ -186,6 +202,7 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
186
202
  gavel workspace-settings its name, triage person, depth and untrusted areas
187
203
  gavel edit-workspace [--name <name>] [--triage-person <person id>|none] [--sub-agent-depth <n>]
188
204
  [--never-trusted <area id,area id>|none] [--coordinator <agent id>|none]
205
+ [--first-in-line <agent id,agent id>|none] [--adding-shares true|false]
189
206
  Admins and Owners; only what you give changes
190
207
  gavel workspace-people everyone, with their role
191
208
  gavel set-role <person id> --role owner|admin|member
@@ -235,7 +252,8 @@ when its repository asks in more than one).`;
235
252
  // What each command takes besides its words, as its usage above names them: anything else is
236
253
  // refused with that usage, never dropped.
237
254
  const FLAGS = {
238
- pair: ["harness", "machine"],
255
+ pair: ["harness", "machine", "hook"],
256
+ waiting: ["hook", "server", "file"],
239
257
  bridge: ["harness", "server"],
240
258
  "actions-env": [],
241
259
  search: ["query", "area", "status", "limit"],
@@ -251,6 +269,7 @@ const FLAGS = {
251
269
  act: ["note"],
252
270
  inbox: [],
253
271
  status: ["text", "description", "folders", "state", "issue", "waiting-on", "item"],
272
+ "claim-folders": ["mode", "item"],
254
273
  work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "open", "waits-on", "area", "why"],
255
274
  message: ["to-agent", "to-person", "conversation", "text", "decision"],
256
275
  conversations: [],
@@ -270,6 +289,7 @@ const FLAGS = {
270
289
  "move-agent": ["under"],
271
290
  call: ["query", "body", "for-person"],
272
291
  find: ["query", "limit"],
292
+ "link-cursor-run": ["code"],
273
293
  me: [],
274
294
  "my-queue": ["view", "before", "limit"],
275
295
  "decide-mine": ["option", "text", "note", "their-words"],
@@ -309,7 +329,7 @@ const FLAGS = {
309
329
  "nudge-mine": [],
310
330
  reassign: ["to-person", "to-agent", "note"],
311
331
  "workspace-settings": [],
312
- "edit-workspace": ["name", "triage-person", "sub-agent-depth", "never-trusted", "coordinator"],
332
+ "edit-workspace": ["name", "triage-person", "sub-agent-depth", "never-trusted", "coordinator", "first-in-line", "adding-shares"],
313
333
  "workspace-people": [],
314
334
  "set-role": ["role"],
315
335
  invitations: [],
@@ -741,6 +761,8 @@ function personRequest(command, p, f, options) {
741
761
  subAgentMaxDepth: depth === undefined ? undefined : Number(depth),
742
762
  neverTrustableAreaIds: untrusted === undefined ? undefined : untrusted === "none" ? [] : list(untrusted),
743
763
  coordinatorAgentId: orNone("coordinator"),
764
+ firstInLineAgentIds: f["first-in-line"] === undefined ? undefined : f["first-in-line"] === "none" ? [] : list(f["first-in-line"]),
765
+ addingShares: yesNo("adding-shares"),
744
766
  });
745
767
  if (!Object.keys(body).length)
746
768
  throw new UsageError("edit-workspace needs something to change");
@@ -948,7 +970,18 @@ export function toRequest(argv) {
948
970
  const harness = f.harness;
949
971
  if (harness !== undefined && !HARNESSES.includes(harness))
950
972
  throw new UsageError(`--harness is one of ${HARNESSES.join(", ")}`);
951
- return { pair: { code: need(p.join(""), "the pairing code (like 4F7K-9QX2)"), harness, machine: f.machine } };
973
+ if (f.hook !== undefined && f.hook !== "true" && f.hook !== "false")
974
+ throw new UsageError("--hook is true or false");
975
+ return { pair: { code: need(p.join(""), "the pairing code (like 4F7K-9QX2)"), harness, machine: f.machine, hook: f.hook === "true" } };
976
+ }
977
+ case "waiting": {
978
+ upTo(0);
979
+ const hook = f.hook;
980
+ if (hook !== undefined && !HOOK_HARNESSES.includes(hook))
981
+ throw new UsageError(`--hook is one of ${HOOK_HARNESSES.join(", ")}`);
982
+ if ((f.server === undefined) !== (f.file === undefined))
983
+ throw new UsageError("--server and --file go together: the entry pairing wrote, and the file it's in");
984
+ return { waiting: { hook, server: f.server, file: f.file } };
952
985
  }
953
986
  case "bridge": {
954
987
  upTo(1);
@@ -1024,6 +1057,13 @@ export function toRequest(argv) {
1024
1057
  const description = f.description === undefined ? undefined : readText(f.description);
1025
1058
  return { method: "PATCH", path: "/v1/agents/me/status", body: compact({ text: readText(said) || null, description, folders, state: f.state, linearIssue: f.issue, waitingOn: f["waiting-on"], item: f.item }) };
1026
1059
  }
1060
+ case "claim-folders": {
1061
+ if (!p.length)
1062
+ throw new UsageError("missing the folders: each its repo's name, then the path (gavel/server/src/features/org)");
1063
+ if (f.mode !== undefined && f.mode !== "adding" && f.mode !== "alone")
1064
+ throw new UsageError("--mode is adding or alone");
1065
+ return { method: "POST", path: "/v1/agents/me/folders", body: compact({ folders: p, mode: f.mode, item: f.item }) };
1066
+ }
1027
1067
  case "work":
1028
1068
  return workRequest(p, f, lists.code ?? [], lists.label ?? []);
1029
1069
  case "message": {
@@ -1114,6 +1154,20 @@ export function toRequest(argv) {
1114
1154
  agentId: f.agent,
1115
1155
  }),
1116
1156
  };
1157
+ case "link-cursor-run": {
1158
+ upTo(1);
1159
+ if ((lists.code ?? []).length > 1)
1160
+ throw new UsageError("give --code once");
1161
+ if (p[0] === "none") {
1162
+ if (f.code !== undefined)
1163
+ throw new UsageError("--code goes with a run, not with none");
1164
+ return { linkRun: { cursorAgentId: null } };
1165
+ }
1166
+ const run = need(p[0] ?? cursorRunHere(process.env), "your Cursor run (bc-…, as cursor.com/agents/bc-… shows it), or none to unlink");
1167
+ if (!CURSOR_RUN.test(run))
1168
+ throw new UsageError(`a Cursor run is bc-…, as cursor.com/agents/bc-… shows it, not "${run}"`);
1169
+ return { linkRun: { cursorAgentId: run, ...(f.code !== undefined ? { code: need(f.code, "the code Gavel sent into that chat") } : {}) } };
1170
+ }
1117
1171
  case "find": {
1118
1172
  const q = words("query", p, "what you want to do, in words");
1119
1173
  const limit = f.limit;
@@ -1430,9 +1484,59 @@ async function pair(input) {
1430
1484
  }
1431
1485
  if (body.legacy && body.legacy.server !== body.setup.server)
1432
1486
  done.push(...(await dropLegacy(body.setup, body.legacy, { ...opts, apiUrl: base })));
1487
+ const setup = body.setup;
1488
+ if (input.hook) {
1489
+ const scope = setup.harness === "claude-code" ? (setup.ifExists.split(" ").pop() ?? null) : null;
1490
+ done.push(installHook({ harness: setup.harness, server: setup.server, file: setup.harness === "claude-code" ? null : setup.file, scope }, { ...opts, version: cliVersion() }));
1491
+ }
1492
+ else if (setup.harness === "cursor" || setup.harness === "claude-code") {
1493
+ done.push("Gavel's end-of-turn hook isn't on: pair with --hook true to have your turn carry on while something waits for you in Gavel");
1494
+ }
1433
1495
  console.log(JSON.stringify({ paired: true, kind: body.kind, agent: body.agent, harness, done, then: body.then }, null, 2));
1434
1496
  return 0;
1435
1497
  }
1498
+ // ---------- gavel waiting ----------
1499
+ // What the hook's software wrote on stdin, if anything, without waiting on a stdin that stays open.
1500
+ async function hookInput() {
1501
+ if (process.stdin.isTTY)
1502
+ return null;
1503
+ const read = (async () => {
1504
+ let text = "";
1505
+ for await (const chunk of process.stdin)
1506
+ text += String(chunk);
1507
+ return text;
1508
+ })();
1509
+ const text = await Promise.race([read, new Promise((resolve) => setTimeout(() => resolve(""), 2_000).unref())]).catch(() => "");
1510
+ try {
1511
+ return text.trim() ? JSON.parse(text) : null;
1512
+ }
1513
+ catch {
1514
+ return null;
1515
+ }
1516
+ }
1517
+ // What's waiting for the agent, or nothing; as a hook, that software's answer. The token is
1518
+ // GAVEL_TOKEN, else the entry pairing wrote (--server, --file), never printed. Always exits 0: a
1519
+ // failure lets the turn end.
1520
+ async function waiting(input, as) {
1521
+ const given = input.hook ? await hookInput() : null;
1522
+ const entry = !process.env.GAVEL_TOKEN && input.server && input.file ? setupFrom(input.file, input.server, process.cwd(), homedir()) : null;
1523
+ const token = process.env.GAVEL_TOKEN ?? entry?.token ?? null;
1524
+ let line = null;
1525
+ try {
1526
+ const api = (process.env.GAVEL_API_URL ?? (entry ? apiOf(entry.url) : "https://api.getgavel.ai")).replace(/\/+$/, "");
1527
+ line = token ? await waitingLine(api, token, agentHeader(as)) : null;
1528
+ }
1529
+ catch {
1530
+ line = null;
1531
+ }
1532
+ if (input.hook === "cursor")
1533
+ console.log(JSON.stringify(cursorAnswer(given, line)));
1534
+ else if (input.hook === "claude-code")
1535
+ console.log(JSON.stringify(claudeAnswer(given, line)));
1536
+ else if (line)
1537
+ console.log(line);
1538
+ return 0;
1539
+ }
1436
1540
  // ---------- gavel upload ----------
1437
1541
  const TYPES = {
1438
1542
  ".png": "image/png",
@@ -1600,6 +1704,39 @@ async function actionsEnv(as) {
1600
1704
  console.log(JSON.stringify({ set: ["GAVEL_TOKEN", "GAVEL_API_URL", "GAVEL_MCP_URL"], agent: run.agent, workspace: run.workspace, server: run.server, expiresAt: run.expiresAt }, null, 2));
1601
1705
  return 0;
1602
1706
  }
1707
+ // ---------- gavel link-cursor-run ----------
1708
+ // A Cursor agent's shell names its own run in CURSOR_CONVERSATION_ID, "bc-…" on Cursor's cloud and on
1709
+ // a worker; any other id there isn't a run a link takes.
1710
+ const CURSOR_RUN = /^bc-[A-Za-z0-9-]{1,100}$/;
1711
+ function cursorRunHere(env) {
1712
+ const id = env.CURSOR_CONVERSATION_ID?.trim();
1713
+ return id && CURSOR_RUN.test(id) ? id : undefined;
1714
+ }
1715
+ // The route names the agent, so the caller's own id comes first (GET /v1/me); an exit code when it
1716
+ // can't be had.
1717
+ async function linkRunRequest(base, token, as, { cursorAgentId, code }) {
1718
+ const res = await fetch(`${base}/v1/me`, { headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) } });
1719
+ const text = await res.text();
1720
+ if (!res.ok) {
1721
+ console.error(pretty(text) || `HTTP ${res.status}`);
1722
+ return 1;
1723
+ }
1724
+ const id = JSON.parse(text).agent?.id;
1725
+ if (typeof id !== "string") {
1726
+ console.error("gavel: link-cursor-run links an agent's own run: GAVEL_TOKEN must be its agent token");
1727
+ return 2;
1728
+ }
1729
+ const path = `/v1/agents/${encodeURIComponent(id)}/cursor-run`;
1730
+ return cursorAgentId === null ? { method: "DELETE", path } : { method: "PUT", path, body: { cursorAgentId, ...(code !== undefined ? { code } : {}) } };
1731
+ }
1732
+ function pretty(text) {
1733
+ try {
1734
+ return JSON.stringify(JSON.parse(text), null, 2);
1735
+ }
1736
+ catch {
1737
+ return text;
1738
+ }
1739
+ }
1603
1740
  async function main(argvIn) {
1604
1741
  let request;
1605
1742
  let as = null;
@@ -1624,6 +1761,8 @@ async function main(argvIn) {
1624
1761
  }
1625
1762
  if ("pair" in request)
1626
1763
  return pair(request.pair);
1764
+ if ("waiting" in request)
1765
+ return waiting(request.waiting, as);
1627
1766
  if ("bridge" in request)
1628
1767
  return runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
1629
1768
  if ("actionsEnv" in request)
@@ -1638,26 +1777,28 @@ async function main(argvIn) {
1638
1777
  return watch(token, as);
1639
1778
  if ("upload" in request)
1640
1779
  return upload(token, as, request.upload);
1641
- const res = await fetch(base + request.path, {
1642
- method: request.method,
1780
+ let call;
1781
+ if ("linkRun" in request) {
1782
+ const linking = await linkRunRequest(base, token, as, request.linkRun);
1783
+ if (typeof linking === "number")
1784
+ return linking;
1785
+ call = linking;
1786
+ }
1787
+ else
1788
+ call = request;
1789
+ const res = await fetch(base + call.path, {
1790
+ method: call.method,
1643
1791
  headers: {
1644
1792
  authorization: `Bearer ${token}`,
1645
1793
  accept: "application/json",
1646
1794
  "x-gavel-waiting": "1",
1647
1795
  ...agentHeader(as),
1648
- ...(request.forPerson ? { "x-gavel-for-person": "true" } : {}),
1649
- ...(request.body !== undefined ? { "content-type": "application/json" } : {}),
1796
+ ...(call.forPerson ? { "x-gavel-for-person": "true" } : {}),
1797
+ ...(call.body !== undefined ? { "content-type": "application/json" } : {}),
1650
1798
  },
1651
- ...(request.body !== undefined ? { body: JSON.stringify(request.body) } : {}),
1799
+ ...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}),
1652
1800
  });
1653
- const text = await res.text();
1654
- let out = text;
1655
- try {
1656
- out = JSON.stringify(JSON.parse(text), null, 2);
1657
- }
1658
- catch {
1659
- // not JSON: print as it came
1660
- }
1801
+ const out = pretty(await res.text());
1661
1802
  if (!res.ok) {
1662
1803
  console.error(out || `HTTP ${res.status}`);
1663
1804
  return 1;
@@ -1665,9 +1806,9 @@ async function main(argvIn) {
1665
1806
  console.log(out);
1666
1807
  // What's waiting for you (the server's own words), on stderr so stdout stays the answer's JSON. A
1667
1808
  // failed call's stderr stays its error alone.
1668
- const waiting = res.headers.get("x-gavel-waiting");
1669
- if (waiting)
1670
- console.error(waiting);
1809
+ const waitingNow = res.headers.get("x-gavel-waiting");
1810
+ if (waitingNow)
1811
+ console.error(waitingNow);
1671
1812
  return 0;
1672
1813
  }
1673
1814
  main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
package/dist/hook.js ADDED
@@ -0,0 +1,150 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ // Gavel's end-of-turn hook (D-1024): when an agent's turn ends with something waiting for it in
7
+ // Gavel, the hook asks its software to carry on, with Gavel's own counts and tool names alone, at most
8
+ // three times a turn; anything going wrong lets the turn end as it would have. `gavel waiting --hook`
9
+ // is what the hook runs; `gavel pair --hook true` writes it.
10
+ export const HOOK_HARNESSES = ["cursor", "claude-code"];
11
+ export const HOOK_TRIES = 3;
12
+ const HOOK_SECONDS = 15;
13
+ const OPENING = "Gavel: something is waiting for you.";
14
+ const FETCH_MS = 5_000;
15
+ // This command's own version, so a hook runs the release that wrote it, never whatever npm has next.
16
+ export function cliVersion() {
17
+ const file = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
18
+ return JSON.parse(readFileSync(file, "utf8")).version;
19
+ }
20
+ const expand = (file, home) => (file.startsWith("~/") ? join(home, file.slice(2)) : file);
21
+ function realpath(path) {
22
+ try {
23
+ return realpathSync(path);
24
+ }
25
+ catch {
26
+ return path;
27
+ }
28
+ }
29
+ // The named server's entry where pairing wrote it (Cursor's mcp.json, Claude Code's .claude.json: this
30
+ // folder's own first, then the user's), and only that entry. Nothing of the file is ever printed: a
31
+ // file that's missing, isn't JSON or lacks the entry gives null.
32
+ export function setupFrom(file, server, cwd, home) {
33
+ try {
34
+ const json = JSON.parse(readFileSync(expand(file, home), "utf8"));
35
+ const own = (json.projects?.[cwd] ?? json.projects?.[realpath(cwd)])?.mcpServers?.[server];
36
+ const entry = own ?? json.mcpServers?.[server];
37
+ const auth = entry?.headers?.Authorization;
38
+ const token = typeof auth === "string" ? (/^Bearer (gvl_\S+)$/.exec(auth.trim())?.[1] ?? null) : null;
39
+ return token && typeof entry?.url === "string" ? { token, url: entry.url } : null;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ // Gavel's API from the server's own address: mcp.<host> answers as api.<host>, a local one as itself.
46
+ export function apiOf(url) {
47
+ const parsed = new URL(url);
48
+ if (parsed.hostname.startsWith("mcp."))
49
+ parsed.hostname = `api.${parsed.hostname.slice(4)}`;
50
+ return parsed.origin;
51
+ }
52
+ // The line the server gives with any agent call that asks (X-Gavel-Waiting), or null: nothing waits,
53
+ // or anything went wrong.
54
+ export async function waitingLine(apiUrl, token, agent = {}) {
55
+ try {
56
+ const res = await fetch(`${apiUrl}/v1/me`, {
57
+ headers: { authorization: `Bearer ${token}`, accept: "application/json", "x-gavel-waiting": "1", ...agent },
58
+ signal: AbortSignal.timeout(FETCH_MS),
59
+ });
60
+ void res.body?.cancel();
61
+ return res.ok ? res.headers.get("x-gavel-waiting") : null;
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ }
67
+ // Cursor's stop hook: carry on with the line when the turn ended on its own (never after its person
68
+ // stopped it); its loop_limit holds it to three.
69
+ export function cursorAnswer(input, line) {
70
+ const { status, loop_count: loops } = (input ?? {});
71
+ if (!line || (status !== undefined && status !== "completed") || (typeof loops === "number" && loops >= HOOK_TRIES))
72
+ return {};
73
+ return { followup_message: `${OPENING} ${line}` };
74
+ }
75
+ // Claude Code's Stop hook: block the stop with the line, at most three times in a row a session (a
76
+ // count in the temp folder, by the session id's hash, cleared once nothing waits).
77
+ export function claudeAnswer(input, line, dir = tmpdir()) {
78
+ const session = input?.session_id;
79
+ const count = join(dir, `gavel-stop-${createHash("sha256").update(typeof session === "string" ? session : "").digest("hex").slice(0, 32)}`);
80
+ try {
81
+ if (!line) {
82
+ rmSync(count, { force: true });
83
+ return {};
84
+ }
85
+ const sofar = existsSync(count) ? Number(readFileSync(count, "utf8")) || 0 : 0;
86
+ if (sofar >= HOOK_TRIES)
87
+ return {};
88
+ writeFileSync(count, String(sofar + 1));
89
+ return { decision: "block", reason: `${OPENING} ${line}` };
90
+ }
91
+ catch {
92
+ return {};
93
+ }
94
+ }
95
+ // A file written whole, through a temporary file and a rename, so a reader never sees half of it.
96
+ function writeWhole(path, text) {
97
+ mkdirSync(dirname(path), { recursive: true });
98
+ const temp = `${path}.gavel-${process.pid}.tmp`;
99
+ writeFileSync(temp, text);
100
+ renameSync(temp, path);
101
+ }
102
+ const isOurs = (command) => typeof command === "string" && /@getgavel\/cli(@\S+)? waiting --hook /.test(command);
103
+ function parsed(existing, name) {
104
+ if (!existing?.trim())
105
+ return {};
106
+ try {
107
+ return JSON.parse(existing);
108
+ }
109
+ catch {
110
+ throw new Error(`${name} isn't plain JSON, so Gavel left its hook out: add it by hand, or fix the file and pair again`);
111
+ }
112
+ }
113
+ // Cursor's hooks.json with Gavel's stop hook in: every other hook kept, an earlier one of Gavel's replaced.
114
+ export function withCursorHook(existing, command, name = "hooks.json") {
115
+ const json = parsed(existing, name);
116
+ const stop = (json.hooks?.stop ?? []).filter((h) => !isOurs(h.command));
117
+ return `${JSON.stringify({ ...json, version: json.version ?? 1, hooks: { ...(json.hooks ?? {}), stop: [...stop, { command, loop_limit: HOOK_TRIES, timeout: HOOK_SECONDS }] } }, null, 2)}\n`;
118
+ }
119
+ // Claude Code's settings with Gavel's Stop hook in: everything else kept, an earlier one of Gavel's replaced.
120
+ export function withClaudeHook(existing, command, name = "settings.json") {
121
+ const json = parsed(existing, name);
122
+ const groups = (json.hooks?.Stop ?? []).map((g) => ({ ...g, hooks: (g.hooks ?? []).filter((h) => !isOurs(h.command)) })).filter((g) => g.hooks.length);
123
+ return `${JSON.stringify({ ...json, hooks: { ...(json.hooks ?? {}), Stop: [...groups, { hooks: [{ type: "command", command, timeout: HOOK_SECONDS }] }] } }, null, 2)}\n`;
124
+ }
125
+ // Writes Gavel's hook beside the setup pairing wrote, in the same scope; says what it did, or why not.
126
+ export function installHook(place, opts) {
127
+ const at = (f) => {
128
+ const expanded = expand(f, opts.home);
129
+ return expanded.startsWith("/") ? expanded : join(opts.cwd, expanded);
130
+ };
131
+ const npx = `npx -y @getgavel/cli@${opts.version} waiting`;
132
+ try {
133
+ if (place.harness === "cursor" && place.file) {
134
+ const file = join(dirname(place.file), "hooks.json");
135
+ const path = at(file);
136
+ writeWhole(path, withCursorHook(existsSync(path) ? readFileSync(path, "utf8") : null, `${npx} --hook cursor --server ${place.server} --file ${place.file}`, file));
137
+ return `wrote Gavel's end-of-turn hook into ${file} (stop, at most ${HOOK_TRIES} a turn)`;
138
+ }
139
+ if (place.harness === "claude-code") {
140
+ const file = place.scope === "user" ? "~/.claude/settings.json" : place.scope === "project" ? ".claude/settings.json" : ".claude/settings.local.json";
141
+ const path = at(file);
142
+ writeWhole(path, withClaudeHook(existsSync(path) ? readFileSync(path, "utf8") : null, `${npx} --hook claude-code --server ${place.server} --file ~/.claude.json`, file));
143
+ return `wrote Gavel's end-of-turn hook into ${file} (Stop, at most ${HOOK_TRIES} in a row)`;
144
+ }
145
+ return `left out Gavel's end-of-turn hook: ${place.harness === "codex" ? "Codex" : "this software"} has none`;
146
+ }
147
+ catch (err) {
148
+ return `left out Gavel's end-of-turn hook: ${err instanceof Error ? err.message : String(err)}`;
149
+ }
150
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.13",
3
+ "version": "0.1.15",
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",