@getgavel/cli 0.1.15 → 0.1.17

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/dist/gavel.js CHANGED
@@ -9,16 +9,25 @@ import { createHash, randomUUID } from "node:crypto";
9
9
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
10
10
  import { homedir, hostname } from "node:os";
11
11
  import { basename, dirname, extname, join } from "node:path";
12
+ import { bridgeStatus, harnessFor, holdBridge, hookEvent, lastingCommand, startBridge, stopBridge } from "./bridge/background.js";
13
+ import { claudeBridgeHooks, gavelPluginOn } from "./bridge/claude-live.js";
14
+ import { codexBridgeHooks } from "./bridge/codex.js";
15
+ import { claudeSetups } from "./bridge/setup.js";
12
16
  import { BRIDGE_HARNESSES, runBridge } from "./bridge/bridge.js";
13
- import { HOOK_HARNESSES, apiOf, claudeAnswer, cliVersion, cursorAnswer, installHook, setupFrom, waitingLine } from "./hook.js";
17
+ import { bridgeService } from "./bridge/service.js";
18
+ import { HOOK_HARNESSES, apiOf, claudeAnswer, cliVersion, codexAnswer, cursorAnswer, installHook, setupFrom, waitingLine } from "./hook.js";
19
+ import { jsonText, shownText } from "./output.js";
14
20
  const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
15
21
 
16
- gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>] [--hook true]
22
+ gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>] [--hook true] [--bridge false]
17
23
  redeem your person's pairing code and write your setup
18
24
  (no GAVEL_TOKEN needed; never prints the token); --hook
19
25
  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>]
26
+ Code, Codex): your turn carries on while something waits
27
+ for you; Claude Code and Codex also get the bridge's hooks,
28
+ so your person's chat in Gavel reaches your sessions at once
29
+ (--bridge false leaves them out)
30
+ gavel waiting [--hook cursor|claude-code|codex] [--server <name> --file <its mcp.json, .claude.json or config.toml>]
22
31
  what's waiting for you in Gavel, in one line, or nothing;
23
32
  --hook answers as that software's end-of-turn hook (run by
24
33
  the hook, not by hand); always exits 0
@@ -31,6 +40,21 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
31
40
  the words it would send from the newest session here; sends
32
41
  nothing
33
42
  gavel bridge wake [--server <name>] the bridge's wake hook, which Claude Code runs (not by hand)
43
+ gavel bridge start|stop|status [--harness claude-code|codex] [--server <name>]
44
+ the bridge for this folder in the background, with no
45
+ terminal (its log under ~/.gavel/bridge): start it, stop it,
46
+ or whether it runs
47
+ gavel bridge event <name> [--harness claude-code|codex] [--server <name>]
48
+ a hook's event for this folder's bridge, its input on stdin
49
+ (run by the hook, not by hand); prints nothing, exits 0
50
+ gavel bridge service install|remove|status [--harness claude-code|codex] [--server <name>]
51
+ the bridge for this folder kept running by the system (a
52
+ LaunchAgent on a Mac, systemd on Linux), so a closed
53
+ session is resumed when your person writes in Gavel
54
+ gavel bridge hooks install|remove|status the bridge's hooks in this folder (Claude Code's
55
+ .claude/settings.local.json: each session starts it, and
56
+ its words, state and inbox reach it at once; Codex's
57
+ .codex/hooks.json: each session starts it)
34
58
  gavel actions-env in a GitHub Actions job with id-token: write, GAVEL_TOKEN
35
59
  for its next steps: the run's own token, traded for
36
60
  GitHub's and masked (never printed)
@@ -39,6 +63,10 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
39
63
  gavel revise <D-12> --file decision.json a draft the editor sent back, fixed (the whole ask again)
40
64
  gavel todo --file todo.json ask a person to do something: title, steps, why (MCP ask_to_do's input)
41
65
  gavel get <D-12>
66
+ gavel subscribe (<D-12> | --item <W-12> [--stop true])
67
+ follow a decision you didn't ask (wait returns its answer
68
+ to you too), or a work item: what happens to it wakes you;
69
+ --stop true stops following the item
42
70
  gavel wait <D-12> [--timeout <seconds>] until it's decided (default 60)
43
71
  gavel withdraw <D-12> [--reason <words>] take back what you asked, while it isn't decided
44
72
  gavel attach <D-12> --file context.json the sidebar's sections ({items, pictures, involved,
@@ -69,12 +97,13 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
69
97
  gavel work file (<title> | --title <words>) [--status <status>] [--description <words>]
70
98
  [--worker <email or agent> | --worker none] [--reporter <email or agent>]
71
99
  [--waiting-on <email or agent>] [--decision <D-12>] [--code <url>]... [--label <Group: Name>]...
72
- [--waits-on <W-3,W-4>]
100
+ [--waits-on <W-3,W-4>] [--key <key>]
73
101
  a work item on the Board's Being done (W-12), when you
74
102
  start: you're its worker unless you name another, Backlog
75
103
  unless --status (Triage, Backlog, Needs Decision, Queued,
76
104
  Building, Blocked, Deployed, Icebox, Closed, Duplicate);
77
- --waits-on the items it waits on
105
+ --waits-on the items it waits on; --key your own id for
106
+ it, so a retry files it once
78
107
  gavel work move <W-12> [<status>] [--waiting-on <email or agent>] [--decision <D-12>]
79
108
  [--code <url>]... [--worker <email or agent> | --worker none] [--title <words>]
80
109
  [--description <words>] [--label <Group: Name>]... [--label none] [--waits-on <W-3,W-4> | --waits-on none]
@@ -93,12 +122,18 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
93
122
  it goes back to Queued); none ready, what's waiting
94
123
  gavel work renew <W-12> keep your claim through a long quiet stretch
95
124
  gavel work release <W-12> [--why <words>] let it go: back to Queued, the why in its history
96
- gavel work done <W-12> [--code <url>]... finish it: Deployed with its code, your claim ends
125
+ gavel work done <W-12> [--code <url>]... finish it: Deployed with its code, your claim ends; if
126
+ your push already deployed it, done, the code added
97
127
  gavel message (--to-agent <id> | --to-person <email>) (<text> | --text <words>) [--decision <D-12>]
128
+ [--no-reply true] [--key <key>]
98
129
  start a conversation with another agent
99
- gavel message --conversation <C-12> (<text> | --text <words>)
100
- reply in one
130
+ gavel message --conversation <C-12> (<text> | --text <words>) [--no-reply true] [--key <key>]
131
+ reply in one; --no-reply true: a note, which never wakes
132
+ them; --key: your own id for it, so a retry sends it once
133
+ gavel message --item <W-12> (<text> | --text <words>) [--key <key>]
134
+ write in a work item's thread, which all on it read
101
135
  gavel conversations [<C-12>] yours, or one with its messages (reads it)
136
+ gavel thread <W-12> [join | leave] a work item's thread: who's in and its messages
102
137
  gavel wait-for-reply <C-12> [--timeout <seconds>]
103
138
  until there's a message to you in it (default 60)
104
139
  gavel chat [<text> | --text <words>] what your person wrote you in Gavel (each once), or
@@ -252,7 +287,7 @@ when its repository asks in more than one).`;
252
287
  // What each command takes besides its words, as its usage above names them: anything else is
253
288
  // refused with that usage, never dropped.
254
289
  const FLAGS = {
255
- pair: ["harness", "machine", "hook"],
290
+ pair: ["harness", "machine", "hook", "bridge"],
256
291
  waiting: ["hook", "server", "file"],
257
292
  bridge: ["harness", "server"],
258
293
  "actions-env": [],
@@ -261,6 +296,7 @@ const FLAGS = {
261
296
  revise: ["file"],
262
297
  todo: ["file"],
263
298
  get: [],
299
+ subscribe: ["item", "stop"],
264
300
  wait: ["timeout"],
265
301
  withdraw: ["reason"],
266
302
  attach: ["file"],
@@ -270,8 +306,9 @@ const FLAGS = {
270
306
  inbox: [],
271
307
  status: ["text", "description", "folders", "state", "issue", "waiting-on", "item"],
272
308
  "claim-folders": ["mode", "item"],
273
- work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "open", "waits-on", "area", "why"],
274
- message: ["to-agent", "to-person", "conversation", "text", "decision"],
309
+ work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "open", "waits-on", "area", "why", "key"],
310
+ message: ["to-agent", "to-person", "conversation", "item", "text", "decision", "no-reply", "key"],
311
+ thread: [],
275
312
  conversations: [],
276
313
  "wait-for-reply": ["timeout"],
277
314
  chat: ["text"],
@@ -501,14 +538,14 @@ function workRequest(p, f, code, label) {
501
538
  };
502
539
  switch (sub) {
503
540
  case "file": {
504
- only(["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "waits-on"]);
541
+ only(["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "waits-on", "key"]);
505
542
  if (f.title !== undefined && rest.length)
506
543
  throw new UsageError("give the title once: as words or as --title");
507
544
  const title = readText(need(f.title ?? rest.join(" "), "the item's title"));
508
545
  return {
509
546
  method: "POST",
510
547
  path: "/v1/work",
511
- body: compact({ title, status: f.status, description, worker, reporter: f.reporter, waitingOn: f["waiting-on"], decision: f.decision, code: links, labels, waitsOn }),
548
+ body: compact({ title, status: f.status, description, worker, reporter: f.reporter, waitingOn: f["waiting-on"], decision: f.decision, code: links, labels, waitsOn, key: f.key }),
512
549
  };
513
550
  }
514
551
  case "move": {
@@ -972,7 +1009,9 @@ export function toRequest(argv) {
972
1009
  throw new UsageError(`--harness is one of ${HARNESSES.join(", ")}`);
973
1010
  if (f.hook !== undefined && f.hook !== "true" && f.hook !== "false")
974
1011
  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" } };
1012
+ if (f.bridge !== undefined && f.bridge !== "true" && f.bridge !== "false")
1013
+ throw new UsageError("--bridge is true or false");
1014
+ return { pair: { code: need(p.join(""), "the pairing code (like 4F7K-9QX2)"), harness, machine: f.machine, hook: f.hook === "true", bridge: f.bridge !== "false" } };
976
1015
  }
977
1016
  case "waiting": {
978
1017
  upTo(0);
@@ -984,13 +1023,31 @@ export function toRequest(argv) {
984
1023
  return { waiting: { hook, server: f.server, file: f.file } };
985
1024
  }
986
1025
  case "bridge": {
987
- upTo(1);
988
1026
  const action = p[0] ?? "run";
989
- if (action !== "run" && action !== "show" && action !== "wake")
990
- throw new UsageError(`bridge doesn't take "${action}"`);
991
1027
  const harness = f.harness;
992
1028
  if (harness !== undefined && !BRIDGE_HARNESSES.includes(harness))
993
1029
  throw new UsageError(`--harness is one of ${BRIDGE_HARNESSES.join(", ")}`);
1030
+ if (action === "start" || action === "stop" || action === "status") {
1031
+ upTo(1);
1032
+ return { bridgeBackground: { action, harness, server: f.server } };
1033
+ }
1034
+ if (action === "event") {
1035
+ upTo(2);
1036
+ const name = need(p[1], "the hook's event (like SessionStart)");
1037
+ if (!/^[A-Za-z]{1,40}$/.test(name))
1038
+ throw new UsageError(`"${name}" isn't a hook's event`);
1039
+ return { bridgeBackground: { action, harness, server: f.server, name } };
1040
+ }
1041
+ if (action === "service" || action === "hooks") {
1042
+ upTo(2);
1043
+ const what = need(p[1], "install, remove or status");
1044
+ if (what !== "install" && what !== "remove" && what !== "status")
1045
+ throw new UsageError(`bridge ${action} takes install, remove or status, not "${what}"`);
1046
+ return { bridgeBackground: { action, harness, server: f.server, service: what } };
1047
+ }
1048
+ upTo(1);
1049
+ if (action !== "run" && action !== "show" && action !== "wake")
1050
+ throw new UsageError(`bridge doesn't take "${action}"`);
994
1051
  return { bridge: { action, harness, server: f.server } };
995
1052
  }
996
1053
  case "actions-env":
@@ -1023,6 +1080,21 @@ export function toRequest(argv) {
1023
1080
  case "get":
1024
1081
  upTo(1);
1025
1082
  return { method: "GET", path: `/v1/decisions/${ref(p[0])}` };
1083
+ case "subscribe": {
1084
+ upTo(1);
1085
+ if (f.stop !== undefined && f.stop !== "true" && f.stop !== "false")
1086
+ throw new UsageError("--stop is true or false");
1087
+ if (f.item === undefined) {
1088
+ if (f.stop !== undefined)
1089
+ throw new UsageError("--stop goes with --item: following a decision ends with its answer");
1090
+ return { method: "POST", path: `/v1/decisions/${ref(p[0])}/subscribe` };
1091
+ }
1092
+ if (p.length)
1093
+ throw new UsageError("give a decision or --item, not both");
1094
+ if (!/^W-\d+$/i.test(f.item))
1095
+ throw new UsageError("--item is a work item, like W-12");
1096
+ return { method: f.stop === "true" ? "DELETE" : "POST", path: `/v1/work/${encodeURIComponent(f.item.toUpperCase())}/follow` };
1097
+ }
1026
1098
  case "wait":
1027
1099
  upTo(1);
1028
1100
  return { method: "GET", path: `/v1/decisions/${ref(p[0])}/wait?timeout=${encodeURIComponent(f.timeout ?? "60")}` };
@@ -1068,17 +1140,35 @@ export function toRequest(argv) {
1068
1140
  return workRequest(p, f, lists.code ?? [], lists.label ?? []);
1069
1141
  case "message": {
1070
1142
  const text = readText(words("text", p, "what to say"));
1143
+ if (f.item) {
1144
+ if (f.conversation || f["to-agent"] || f["to-person"] || f.decision !== undefined || f["no-reply"] !== undefined)
1145
+ throw new UsageError("--item writes in a work item's thread: give it alone, with --key if you like");
1146
+ return { method: "POST", path: `/v1/work/${encodeURIComponent(f.item)}/thread`, body: compact({ text, key: f.key }) };
1147
+ }
1071
1148
  if ([f.conversation, f["to-agent"], f["to-person"]].filter(Boolean).length !== 1)
1072
- throw new UsageError("give --to-agent or --to-person to start a conversation, or --conversation to reply in one");
1149
+ throw new UsageError("give --to-agent or --to-person to start a conversation, --conversation to reply in one, or --item to write in a work item's thread");
1073
1150
  if (f.conversation && f.decision !== undefined)
1074
1151
  throw new UsageError("--decision is only for starting a conversation");
1152
+ const noReply = f["no-reply"];
1153
+ if (noReply !== undefined && noReply !== "true" && noReply !== "false")
1154
+ throw new UsageError("--no-reply is true or false");
1155
+ const sending = { noReply: noReply === undefined ? undefined : noReply === "true", key: f.key };
1075
1156
  if (f.conversation)
1076
- return { method: "POST", path: `/v1/conversations/${encodeURIComponent(f.conversation)}/messages`, body: { text } };
1077
- return { method: "POST", path: "/v1/conversations", body: compact({ toAgentId: f["to-agent"], toPerson: f["to-person"], text, decision: f.decision }) };
1157
+ return { method: "POST", path: `/v1/conversations/${encodeURIComponent(f.conversation)}/messages`, body: compact({ text, ...sending }) };
1158
+ return { method: "POST", path: "/v1/conversations", body: compact({ toAgentId: f["to-agent"], toPerson: f["to-person"], text, decision: f.decision, ...sending }) };
1078
1159
  }
1079
1160
  case "conversations":
1080
1161
  upTo(1);
1081
1162
  return { method: "GET", path: p[0] ? `/v1/conversations/${encodeURIComponent(p[0])}` : "/v1/conversations" };
1163
+ case "thread": {
1164
+ upTo(2);
1165
+ const ref = encodeURIComponent(need(p[0], "the work item (W-12)"));
1166
+ if (p[1] === undefined)
1167
+ return { method: "GET", path: `/v1/work/${ref}/thread` };
1168
+ if (p[1] !== "join" && p[1] !== "leave")
1169
+ throw new UsageError("after the item, join or leave");
1170
+ return { method: "POST", path: `/v1/work/${ref}/thread/${p[1]}` };
1171
+ }
1082
1172
  case "wait-for-reply":
1083
1173
  upTo(1);
1084
1174
  return { method: "GET", path: `/v1/conversations/${encodeURIComponent(need(p[0], "the conversation (C-12)"))}/wait?timeout=${encodeURIComponent(f.timeout ?? "60")}` };
@@ -1485,16 +1575,125 @@ async function pair(input) {
1485
1575
  if (body.legacy && body.legacy.server !== body.setup.server)
1486
1576
  done.push(...(await dropLegacy(body.setup, body.legacy, { ...opts, apiUrl: base })));
1487
1577
  const setup = body.setup;
1488
- if (input.hook) {
1578
+ if (input.hook && setup.harness === "claude-code" && gavelPluginOn(opts.home)) {
1579
+ done.push("Gavel's plugin has the end-of-turn hook already");
1580
+ }
1581
+ else if (input.hook) {
1489
1582
  const scope = setup.harness === "claude-code" ? (setup.ifExists.split(" ").pop() ?? null) : null;
1490
1583
  done.push(installHook({ harness: setup.harness, server: setup.server, file: setup.harness === "claude-code" ? null : setup.file, scope }, { ...opts, version: cliVersion() }));
1491
1584
  }
1492
- else if (setup.harness === "cursor" || setup.harness === "claude-code") {
1585
+ else if (setup.harness === "cursor" || setup.harness === "claude-code" || setup.harness === "codex") {
1493
1586
  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
1587
  }
1495
- console.log(JSON.stringify({ paired: true, kind: body.kind, agent: body.agent, harness, done, then: body.then }, null, 2));
1588
+ // The bridge comes with Claude Code's and Codex's pairing (D-1140, D-1146); its person turns it off in Gavel.
1589
+ if (setup.harness === "claude-code" && body.kind === "agent") {
1590
+ if (input.bridge) {
1591
+ const hooks = await claudeBridgeHooks("install", { ...opts, command: lastingCommand(opts.home) });
1592
+ done.push(...(hooks.done ?? [`left out the bridge's hooks: ${hooks.reason ?? hooks.hooks}`]));
1593
+ }
1594
+ else
1595
+ done.push("left out the bridge's hooks (--bridge false): your person's chat in Gavel reaches your Claude Code sessions here only when you check in");
1596
+ }
1597
+ if (setup.harness === "codex" && body.kind === "agent") {
1598
+ if (input.bridge) {
1599
+ const hooks = codexBridgeHooks("install", { ...opts, env: process.env, server: setup.server, version: cliVersion() });
1600
+ done.push(...(hooks.done ?? [`left out the bridge's hooks: ${hooks.reason ?? hooks.hooks}`]));
1601
+ }
1602
+ else
1603
+ done.push("left out the bridge's hooks (--bridge false): your person's chat in Gavel reaches your Codex sessions here only when you check in");
1604
+ }
1605
+ console.log(jsonText({ paired: true, kind: body.kind, agent: body.agent, harness, done, then: body.then }));
1496
1606
  return 0;
1497
1607
  }
1608
+ // `gavel bridge` holds this folder's lock while it runs, so a hook or the service finds it running
1609
+ // instead of starting a second. A folder whose harness can't be told runs it as before, unheld.
1610
+ async function heldBridge(run, as) {
1611
+ const ctx = { cwd: process.cwd(), home: homedir(), env: process.env, as };
1612
+ let harness;
1613
+ try {
1614
+ harness = harnessFor(run.harness, { ...ctx, harnesses: BRIDGE_HARNESSES });
1615
+ }
1616
+ catch {
1617
+ return runBridge(run, ctx);
1618
+ }
1619
+ const held = holdBridge({
1620
+ home: ctx.home,
1621
+ cwd: ctx.cwd,
1622
+ harness,
1623
+ server: run.server,
1624
+ untilClosed: process.env.GAVEL_BRIDGE_UNTIL_CLOSED === "1",
1625
+ stop: () => process.kill(process.pid, "SIGTERM"),
1626
+ lingerMs: Number(process.env.GAVEL_BRIDGE_LINGER_MS) || undefined,
1627
+ });
1628
+ if ("running" in held) {
1629
+ console.error(`gavel bridge: a bridge already runs for this folder (since ${held.running.since}; its log: ${held.running.log}). gavel bridge stop stops it.`);
1630
+ return 4;
1631
+ }
1632
+ const code = await runBridge({ ...run, harness }, ctx);
1633
+ // Under the service, another bridge taking over isn't a failure to restart for.
1634
+ return code === 3 && process.env.GAVEL_BRIDGE_SERVICE === "1" ? 0 : code;
1635
+ }
1636
+ const lastLine = (file) => {
1637
+ try {
1638
+ return readFileSync(file, "utf8").trim().split("\n").pop()?.slice(0, 300) ?? null;
1639
+ }
1640
+ catch {
1641
+ return null;
1642
+ }
1643
+ };
1644
+ async function background(run) {
1645
+ const home = homedir();
1646
+ const cwd = process.cwd();
1647
+ const env = process.env;
1648
+ const print = (answer) => console.log(JSON.stringify(answer, null, 2));
1649
+ if (run.action === "hooks") {
1650
+ // A folder whose harness can't be told is Claude Code's to answer, refusal and all.
1651
+ let which = run.harness ?? "claude-code";
1652
+ try {
1653
+ which = harnessFor(run.harness, { home, cwd, env, harnesses: BRIDGE_HARNESSES });
1654
+ }
1655
+ catch {
1656
+ // as above
1657
+ }
1658
+ const answer = which === "codex"
1659
+ ? codexBridgeHooks(run.service, { cwd, home, env, server: run.server, version: cliVersion() })
1660
+ : await claudeBridgeHooks(run.service, { cwd, home, command: lastingCommand(home) });
1661
+ print(answer);
1662
+ return answer.hooks === "refused" ? 1 : 0;
1663
+ }
1664
+ let harness;
1665
+ try {
1666
+ harness = harnessFor(run.harness, { home, cwd, env, harnesses: BRIDGE_HARNESSES });
1667
+ }
1668
+ catch (err) {
1669
+ if (run.action === "event")
1670
+ return 0;
1671
+ console.error(`gavel bridge: ${err instanceof Error ? err.message : String(err)}`);
1672
+ return 1;
1673
+ }
1674
+ switch (run.action) {
1675
+ case "event":
1676
+ return hookEvent({ home, cwd, harness, server: run.server, name: run.name, env });
1677
+ case "start": {
1678
+ const started = await startBridge({ home, cwd, harness, server: run.server, untilClosed: false, env });
1679
+ print(started.bridge === "failed" ? { ...started, reason: lastLine(started.log) } : started);
1680
+ return started.bridge === "failed" ? 1 : 0;
1681
+ }
1682
+ case "stop": {
1683
+ const stopped = await stopBridge({ home, cwd, harness });
1684
+ print(stopped);
1685
+ return stopped.bridge === "still running" ? 1 : 0;
1686
+ }
1687
+ case "status":
1688
+ print(bridgeStatus({ home, cwd, harness }));
1689
+ return 0;
1690
+ case "service": {
1691
+ const answer = bridgeService(run.service, { home, cwd, harness, server: run.server, env });
1692
+ print(answer);
1693
+ return answer.service === "failed" || answer.service === "unsupported" ? 1 : 0;
1694
+ }
1695
+ }
1696
+ }
1498
1697
  // ---------- gavel waiting ----------
1499
1698
  // What the hook's software wrote on stdin, if anything, without waiting on a stdin that stays open.
1500
1699
  async function hookInput() {
@@ -1519,7 +1718,13 @@ async function hookInput() {
1519
1718
  // failure lets the turn end.
1520
1719
  async function waiting(input, as) {
1521
1720
  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;
1721
+ // Gavel's plugin for Claude Code (D-1139) names no server: this folder's own Gavel entry, when it
1722
+ // has exactly one.
1723
+ const own = () => {
1724
+ const local = claudeSetups(process.cwd(), homedir()).filter((s) => s.where.endsWith("this folder"));
1725
+ return local.length === 1 ? { token: local[0].token, url: local[0].url } : null;
1726
+ };
1727
+ const entry = process.env.GAVEL_TOKEN ? null : input.server && input.file ? setupFrom(input.file, input.server, process.cwd(), homedir()) : input.hook === "claude-code" ? own() : null;
1523
1728
  const token = process.env.GAVEL_TOKEN ?? entry?.token ?? null;
1524
1729
  let line = null;
1525
1730
  try {
@@ -1533,6 +1738,8 @@ async function waiting(input, as) {
1533
1738
  console.log(JSON.stringify(cursorAnswer(given, line)));
1534
1739
  else if (input.hook === "claude-code")
1535
1740
  console.log(JSON.stringify(claudeAnswer(given, line)));
1741
+ else if (input.hook === "codex")
1742
+ console.log(JSON.stringify(codexAnswer(given, line)));
1536
1743
  else if (line)
1537
1744
  console.log(line);
1538
1745
  return 0;
@@ -1574,7 +1781,7 @@ async function upload(token, as, { file, contentType }) {
1574
1781
  const finished = await fetch(`${base}/v1/attachments/${encodeURIComponent(attachment.id)}/complete`, { method: "POST", headers });
1575
1782
  if (!finished.ok)
1576
1783
  return failed(finished);
1577
- console.log(JSON.stringify(await finished.json(), null, 2));
1784
+ console.log(jsonText(await finished.json()));
1578
1785
  return 0;
1579
1786
  }
1580
1787
  // One line per thing that should wake the chat: refs and Gavel's own words only, never a message's
@@ -1583,7 +1790,9 @@ async function upload(token, as, { file, contentType }) {
1583
1790
  export function wakeLine(item) {
1584
1791
  switch (item.kind) {
1585
1792
  case "message":
1586
- return `GAVEL_WAKE message ${item.ref}: read it with gavel conversations ${item.ref}`;
1793
+ return item.type === "note"
1794
+ ? `GAVEL_WAKE note ${item.ref}: it needs no answer: read it with gavel conversations ${item.ref}`
1795
+ : `GAVEL_WAKE message ${item.ref}: read it with gavel conversations ${item.ref}`;
1587
1796
  case "request":
1588
1797
  return `GAVEL_WAKE request ${item.type ?? ""} on ${item.ref}: see gavel inbox`;
1589
1798
  case "decision":
@@ -1602,6 +1811,12 @@ export function wakeLine(item) {
1602
1811
  return `GAVEL_WAKE claim on ${item.ref} ran out, back in Queued: see gavel inbox, then give it to an agent or let one claim it`;
1603
1812
  case "work":
1604
1813
  return `GAVEL_WAKE work ${item.ref} Blocked half an hour: move it, or name it Blocked again with gavel work move ${item.ref} Blocked`;
1814
+ case "drift":
1815
+ return `GAVEL_WAKE drift on ${item.ref}: it may go against ${item.type ?? "a decision"}: see gavel inbox`;
1816
+ case "task":
1817
+ return item.type === "ready"
1818
+ ? `GAVEL_WAKE task ${item.ref} ready: what it waited on is finished: gavel work show ${item.ref}`
1819
+ : `GAVEL_WAKE task ${item.ref} ${item.type ?? "changed"} by someone else: gavel work show ${item.ref}`;
1605
1820
  default:
1606
1821
  return "GAVEL_WAKE something new: see gavel inbox";
1607
1822
  }
@@ -1617,7 +1832,7 @@ async function watch(token, as) {
1617
1832
  for (;;) {
1618
1833
  let res;
1619
1834
  try {
1620
- res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50&kinds=health,claim,work${start ? "&start=true" : ""}`, {
1835
+ res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50&kinds=health,claim,work,drift,task${start ? "&start=true" : ""}`, {
1621
1836
  headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) },
1622
1837
  });
1623
1838
  }
@@ -1701,7 +1916,7 @@ async function actionsEnv(as) {
1701
1916
  const run = await runToken(base, as, env);
1702
1917
  console.log(`::add-mask::${run.token}`);
1703
1918
  appendFileSync(env.GITHUB_ENV, `GAVEL_TOKEN=${run.token}\nGAVEL_API_URL=${base}\nGAVEL_MCP_URL=${run.mcpUrl}\n`);
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));
1919
+ console.log(jsonText({ set: ["GAVEL_TOKEN", "GAVEL_API_URL", "GAVEL_MCP_URL"], agent: run.agent, workspace: run.workspace, server: run.server, expiresAt: run.expiresAt }));
1705
1920
  return 0;
1706
1921
  }
1707
1922
  // ---------- gavel link-cursor-run ----------
@@ -1718,7 +1933,7 @@ async function linkRunRequest(base, token, as, { cursorAgentId, code }) {
1718
1933
  const res = await fetch(`${base}/v1/me`, { headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) } });
1719
1934
  const text = await res.text();
1720
1935
  if (!res.ok) {
1721
- console.error(pretty(text) || `HTTP ${res.status}`);
1936
+ console.error(shownText(text, process.stderr) || `HTTP ${res.status}`);
1722
1937
  return 1;
1723
1938
  }
1724
1939
  const id = JSON.parse(text).agent?.id;
@@ -1729,14 +1944,6 @@ async function linkRunRequest(base, token, as, { cursorAgentId, code }) {
1729
1944
  const path = `/v1/agents/${encodeURIComponent(id)}/cursor-run`;
1730
1945
  return cursorAgentId === null ? { method: "DELETE", path } : { method: "PUT", path, body: { cursorAgentId, ...(code !== undefined ? { code } : {}) } };
1731
1946
  }
1732
- function pretty(text) {
1733
- try {
1734
- return JSON.stringify(JSON.parse(text), null, 2);
1735
- }
1736
- catch {
1737
- return text;
1738
- }
1739
- }
1740
1947
  async function main(argvIn) {
1741
1948
  let request;
1742
1949
  let as = null;
@@ -1764,7 +1971,9 @@ async function main(argvIn) {
1764
1971
  if ("waiting" in request)
1765
1972
  return waiting(request.waiting, as);
1766
1973
  if ("bridge" in request)
1767
- return runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
1974
+ return request.bridge.action === "run" ? heldBridge(request.bridge, as) : runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
1975
+ if ("bridgeBackground" in request)
1976
+ return background(request.bridgeBackground);
1768
1977
  if ("actionsEnv" in request)
1769
1978
  return actionsEnv(as);
1770
1979
  const base = (process.env.GAVEL_API_URL ?? "https://api.getgavel.ai").replace(/\/+$/, "");
@@ -1798,12 +2007,12 @@ async function main(argvIn) {
1798
2007
  },
1799
2008
  ...(call.body !== undefined ? { body: JSON.stringify(call.body) } : {}),
1800
2009
  });
1801
- const out = pretty(await res.text());
2010
+ const text = await res.text();
1802
2011
  if (!res.ok) {
1803
- console.error(out || `HTTP ${res.status}`);
2012
+ console.error(shownText(text, process.stderr) || `HTTP ${res.status}`);
1804
2013
  return 1;
1805
2014
  }
1806
- console.log(out);
2015
+ console.log(shownText(text));
1807
2016
  // What's waiting for you (the server's own words), on stderr so stdout stays the answer's JSON. A
1808
2017
  // failed call's stderr stays its error alone.
1809
2018
  const waitingNow = res.headers.get("x-gavel-waiting");
package/dist/hook.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
- import { dirname, join } from "node:path";
4
+ import { dirname, isAbsolute, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { codexEntry } from "./bridge/setup.js";
6
7
  // Gavel's end-of-turn hook (D-1024): when an agent's turn ends with something waiting for it in
7
8
  // Gavel, the hook asks its software to carry on, with Gavel's own counts and tool names alone, at most
8
9
  // three times a turn; anything going wrong lets the turn end as it would have. `gavel waiting --hook`
9
10
  // is what the hook runs; `gavel pair --hook true` writes it.
10
- export const HOOK_HARNESSES = ["cursor", "claude-code"];
11
+ export const HOOK_HARNESSES = ["cursor", "claude-code", "codex"];
11
12
  export const HOOK_TRIES = 3;
12
13
  const HOOK_SECONDS = 15;
13
14
  const OPENING = "Gavel: something is waiting for you.";
@@ -26,12 +27,27 @@ function realpath(path) {
26
27
  return path;
27
28
  }
28
29
  }
30
+ // A project's own file, named from its folder (".codex/config.toml"), from wherever in the project the
31
+ // software runs its hook: this folder's, else the nearest folder above's.
32
+ function nearest(file, cwd) {
33
+ if (isAbsolute(file))
34
+ return file;
35
+ for (let dir = cwd;; dir = dirname(dir)) {
36
+ if (existsSync(join(dir, file)))
37
+ return join(dir, file);
38
+ if (dirname(dir) === dir)
39
+ return join(cwd, file);
40
+ }
41
+ }
29
42
  // 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.
43
+ // folder's own first, then the user's; Codex's config.toml), and only that entry. Nothing of the file
44
+ // is ever printed: a file that's missing, can't be read or lacks the entry gives null.
32
45
  export function setupFrom(file, server, cwd, home) {
33
46
  try {
34
- const json = JSON.parse(readFileSync(expand(file, home), "utf8"));
47
+ const path = nearest(expand(file, home), cwd);
48
+ if (path.endsWith(".toml"))
49
+ return codexEntry(readFileSync(path, "utf8"), server);
50
+ const json = JSON.parse(readFileSync(path, "utf8"));
35
51
  const own = (json.projects?.[cwd] ?? json.projects?.[realpath(cwd)])?.mcpServers?.[server];
36
52
  const entry = own ?? json.mcpServers?.[server];
37
53
  const auth = entry?.headers?.Authorization;
@@ -92,8 +108,31 @@ export function claudeAnswer(input, line, dir = tmpdir()) {
92
108
  return {};
93
109
  }
94
110
  }
111
+ // Codex's Stop hook (developers.openai.com/codex/hooks): block the stop with the line, which Codex
112
+ // takes as a new prompt in the same turn, at most three times a turn: stop_hook_active says this
113
+ // turn was carried on already, and a count in the temp folder (by the session id's hash) says how
114
+ // often; a turn Codex didn't carry on starts it again. Codex runs no Stop hook on a turn its person
115
+ // interrupted.
116
+ export function codexAnswer(input, line, dir = tmpdir()) {
117
+ const { session_id: session, stop_hook_active: active } = (input ?? {});
118
+ const count = join(dir, `gavel-codex-stop-${createHash("sha256").update(typeof session === "string" ? session : "").digest("hex").slice(0, 32)}`);
119
+ try {
120
+ if (!line) {
121
+ rmSync(count, { force: true });
122
+ return {};
123
+ }
124
+ const sofar = active === true && existsSync(count) ? Number(readFileSync(count, "utf8")) || 0 : 0;
125
+ if (sofar >= HOOK_TRIES)
126
+ return {};
127
+ writeFileSync(count, String(sofar + 1));
128
+ return { decision: "block", reason: `${OPENING} ${line}` };
129
+ }
130
+ catch {
131
+ return {};
132
+ }
133
+ }
95
134
  // A file written whole, through a temporary file and a rename, so a reader never sees half of it.
96
- function writeWhole(path, text) {
135
+ export function writeWhole(path, text) {
97
136
  mkdirSync(dirname(path), { recursive: true });
98
137
  const temp = `${path}.gavel-${process.pid}.tmp`;
99
138
  writeFileSync(temp, text);
@@ -122,6 +161,20 @@ export function withClaudeHook(existing, command, name = "settings.json") {
122
161
  const groups = (json.hooks?.Stop ?? []).map((g) => ({ ...g, hooks: (g.hooks ?? []).filter((h) => !isOurs(h.command)) })).filter((g) => g.hooks.length);
123
162
  return `${JSON.stringify({ ...json, hooks: { ...(json.hooks ?? {}), Stop: [...groups, { hooks: [{ type: "command", command, timeout: HOOK_SECONDS }] }] } }, null, 2)}\n`;
124
163
  }
164
+ // Codex's hooks.json with Gavel's in, by event: every other hook kept, the earlier ones `old` names
165
+ // replaced (none at all, ours empty, takes them out).
166
+ export function withCodexHooks(existing, ours, old = isOurs, name = "hooks.json") {
167
+ const json = parsed(existing, name);
168
+ const hooks = {};
169
+ for (const [event, groups] of Object.entries(json.hooks ?? {})) {
170
+ const kept = (groups ?? []).map((g) => ({ ...g, hooks: (g.hooks ?? []).filter((h) => !old(h.command)) })).filter((g) => g.hooks.length);
171
+ if (kept.length)
172
+ hooks[event] = kept;
173
+ }
174
+ for (const [event, group] of Object.entries(ours))
175
+ hooks[event] = [...(hooks[event] ?? []), group];
176
+ return `${JSON.stringify({ ...json, hooks }, null, 2)}\n`;
177
+ }
125
178
  // Writes Gavel's hook beside the setup pairing wrote, in the same scope; says what it did, or why not.
126
179
  export function installHook(place, opts) {
127
180
  const at = (f) => {
@@ -142,7 +195,14 @@ export function installHook(place, opts) {
142
195
  writeWhole(path, withClaudeHook(existsSync(path) ? readFileSync(path, "utf8") : null, `${npx} --hook claude-code --server ${place.server} --file ~/.claude.json`, file));
143
196
  return `wrote Gavel's end-of-turn hook into ${file} (Stop, at most ${HOOK_TRIES} in a row)`;
144
197
  }
145
- return `left out Gavel's end-of-turn hook: ${place.harness === "codex" ? "Codex" : "this software"} has none`;
198
+ if (place.harness === "codex" && place.file) {
199
+ const file = join(dirname(place.file), "hooks.json");
200
+ const path = at(file);
201
+ const ours = { Stop: { hooks: [{ type: "command", command: `${npx} --hook codex --server ${place.server} --file ${place.file}`, timeout: HOOK_SECONDS }] } };
202
+ writeWhole(path, withCodexHooks(existsSync(path) ? readFileSync(path, "utf8") : null, ours, isOurs, file));
203
+ return `wrote Gavel's end-of-turn hook into ${file} (Stop, at most ${HOOK_TRIES} a turn): Codex runs it once you trust it in /hooks`;
204
+ }
205
+ return "left out Gavel's end-of-turn hook: this software has none";
146
206
  }
147
207
  catch (err) {
148
208
  return `left out Gavel's end-of-turn hook: ${err instanceof Error ? err.message : String(err)}`;
package/dist/output.js ADDED
@@ -0,0 +1,14 @@
1
+ // What the gavel command prints: JSON indented for a person at a terminal, compact for an agent that
2
+ // captures it, where indenting cost about 30% more tokens to read (W-117, as MCP's results, W-111).
3
+ export function jsonText(value, stream = process.stdout) {
4
+ return JSON.stringify(value, null, stream.isTTY ? 2 : undefined);
5
+ }
6
+ // An answer's text as JSON for that stream, or as it came when it isn't JSON.
7
+ export function shownText(text, stream = process.stdout) {
8
+ try {
9
+ return jsonText(JSON.parse(text), stream);
10
+ }
11
+ catch {
12
+ return text;
13
+ }
14
+ }