@getgavel/cli 0.1.16 → 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.
@@ -0,0 +1,166 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { connect } from "node:net";
3
+ // A WebSocket client (RFC 6455) over a Unix socket: how a local client talks to Codex's shared
4
+ // app-server, whose control socket takes an HTTP Upgrade and then frames, one JSON-RPC message
5
+ // a text frame. Text frames only; the CLI takes no dependency, so it's the few parts used here.
6
+ const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
7
+ const MAX_MESSAGE = 64 * 1024 * 1024;
8
+ export class WebSocketError extends Error {
9
+ code;
10
+ constructor(message, code) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ }
15
+ function frame(opcode, payload) {
16
+ const mask = randomBytes(4);
17
+ const length = payload.length;
18
+ const head = length < 126 ? Buffer.alloc(2) : length < 65_536 ? Buffer.alloc(4) : Buffer.alloc(10);
19
+ head[0] = 0x80 | opcode;
20
+ if (length < 126)
21
+ head[1] = 0x80 | length;
22
+ else if (length < 65_536) {
23
+ head[1] = 0x80 | 126;
24
+ head.writeUInt16BE(length, 2);
25
+ }
26
+ else {
27
+ head[1] = 0x80 | 127;
28
+ head.writeBigUInt64BE(BigInt(length), 2);
29
+ }
30
+ const body = Buffer.alloc(length);
31
+ for (let i = 0; i < length; i++)
32
+ body[i] = payload[i] ^ mask[i % 4];
33
+ return Buffer.concat([head, mask, body]);
34
+ }
35
+ // Opens the socket, upgrades it and calls `message` with each text message, whole.
36
+ export function openWebSocket(path, handlers, timeoutMs = 10_000) {
37
+ return new Promise((resolve, reject) => {
38
+ const key = randomBytes(16).toString("base64");
39
+ const accept = createHash("sha1").update(key + GUID).digest("base64");
40
+ const socket = connect({ path });
41
+ let upgraded = false;
42
+ let buffer = Buffer.alloc(0);
43
+ let parts = [];
44
+ let partsLength = 0;
45
+ let ended = false;
46
+ let endClosed = () => undefined;
47
+ const closed = new Promise((r) => (endClosed = r));
48
+ const timer = setTimeout(() => fail(new WebSocketError("Codex's server didn't answer the connection", "ETIMEDOUT")), timeoutMs);
49
+ const finish = (why) => {
50
+ if (ended)
51
+ return;
52
+ ended = true;
53
+ clearTimeout(timer);
54
+ socket.destroy();
55
+ endClosed(why);
56
+ };
57
+ const fail = (err) => {
58
+ if (!upgraded)
59
+ reject(err);
60
+ finish(err.message);
61
+ };
62
+ const write = (opcode, payload) => {
63
+ if (!ended && !socket.destroyed)
64
+ socket.write(frame(opcode, payload));
65
+ };
66
+ const frames = () => {
67
+ for (;;) {
68
+ if (buffer.length < 2)
69
+ return;
70
+ const fin = (buffer[0] & 0x80) !== 0;
71
+ const opcode = buffer[0] & 0x0f;
72
+ const masked = (buffer[1] & 0x80) !== 0;
73
+ let length = buffer[1] & 0x7f;
74
+ let at = 2;
75
+ if (length === 126) {
76
+ if (buffer.length < 4)
77
+ return;
78
+ length = buffer.readUInt16BE(2);
79
+ at = 4;
80
+ }
81
+ else if (length === 127) {
82
+ if (buffer.length < 10)
83
+ return;
84
+ const big = buffer.readBigUInt64BE(2);
85
+ if (big > BigInt(MAX_MESSAGE))
86
+ return fail(new WebSocketError("Codex's server sent a message too large to read"));
87
+ length = Number(big);
88
+ at = 10;
89
+ }
90
+ const maskAt = at;
91
+ if (masked)
92
+ at += 4;
93
+ if (buffer.length < at + length)
94
+ return;
95
+ let payload = buffer.subarray(at, at + length);
96
+ if (masked) {
97
+ const mask = buffer.subarray(maskAt, maskAt + 4);
98
+ payload = Buffer.from(payload.map((b, i) => b ^ mask[i % 4]));
99
+ }
100
+ buffer = buffer.subarray(at + length);
101
+ if (opcode === 0x8) {
102
+ write(0x8, payload.subarray(0, 2));
103
+ return finish(null);
104
+ }
105
+ if (opcode === 0x9) {
106
+ write(0xa, payload);
107
+ continue;
108
+ }
109
+ if (opcode === 0xa)
110
+ continue;
111
+ if (opcode !== 0x0 && opcode !== 0x1 && opcode !== 0x2)
112
+ return fail(new WebSocketError(`Codex's server sent an unknown frame (${opcode})`));
113
+ parts.push(Buffer.from(payload));
114
+ partsLength += payload.length;
115
+ if (partsLength > MAX_MESSAGE)
116
+ return fail(new WebSocketError("Codex's server sent a message too large to read"));
117
+ if (!fin)
118
+ continue;
119
+ const whole = Buffer.concat(parts, partsLength);
120
+ parts = [];
121
+ partsLength = 0;
122
+ try {
123
+ handlers.message(whole.toString("utf8"));
124
+ }
125
+ catch {
126
+ // a handler's trouble is its own
127
+ }
128
+ }
129
+ };
130
+ socket.on("connect", () => {
131
+ socket.write(`GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`);
132
+ });
133
+ socket.on("data", (chunk) => {
134
+ buffer = Buffer.concat([buffer, chunk]);
135
+ if (!upgraded) {
136
+ const end = buffer.indexOf("\r\n\r\n");
137
+ if (end < 0) {
138
+ if (buffer.length > 16 * 1024)
139
+ fail(new WebSocketError("Codex's server didn't upgrade the connection"));
140
+ return;
141
+ }
142
+ const head = buffer.subarray(0, end).toString("latin1").split("\r\n");
143
+ const status = /^HTTP\/1\.1 (\d{3})/.exec(head[0] ?? "")?.[1];
144
+ const headers = new Map(head.slice(1).map((l) => [l.slice(0, l.indexOf(":")).trim().toLowerCase(), l.slice(l.indexOf(":") + 1).trim()]));
145
+ if (status !== "101" || headers.get("sec-websocket-accept") !== accept)
146
+ return fail(new WebSocketError(`Codex's server refused the connection (${status ?? "no answer"})`));
147
+ buffer = buffer.subarray(end + 4);
148
+ upgraded = true;
149
+ clearTimeout(timer);
150
+ resolve({
151
+ send: (text) => write(0x1, Buffer.from(text, "utf8")),
152
+ close: () => {
153
+ write(0x8, Buffer.from([0x03, 0xe8]));
154
+ finish(null);
155
+ },
156
+ closed,
157
+ });
158
+ }
159
+ frames();
160
+ });
161
+ socket.on("error", (err) => fail(new WebSocketError(err.message, err.code)));
162
+ const gone = () => (upgraded ? finish("the connection closed") : fail(new WebSocketError("Codex's server closed the connection")));
163
+ socket.on("close", gone);
164
+ socket.on("end", gone);
165
+ });
166
+ }
package/dist/gavel.js CHANGED
@@ -10,21 +10,24 @@ 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 { bridgeStatus, harnessFor, holdBridge, hookEvent, lastingCommand, startBridge, stopBridge } from "./bridge/background.js";
13
- import { claudeBridgeHooks } from "./bridge/claude-live.js";
13
+ import { claudeBridgeHooks, gavelPluginOn } from "./bridge/claude-live.js";
14
+ import { codexBridgeHooks } from "./bridge/codex.js";
15
+ import { claudeSetups } from "./bridge/setup.js";
14
16
  import { BRIDGE_HARNESSES, runBridge } from "./bridge/bridge.js";
15
17
  import { bridgeService } from "./bridge/service.js";
16
- import { HOOK_HARNESSES, apiOf, claudeAnswer, cliVersion, cursorAnswer, installHook, setupFrom, waitingLine } from "./hook.js";
18
+ import { HOOK_HARNESSES, apiOf, claudeAnswer, cliVersion, codexAnswer, cursorAnswer, installHook, setupFrom, waitingLine } from "./hook.js";
17
19
  import { jsonText, shownText } from "./output.js";
18
20
  const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
19
21
 
20
- gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>] [--hook true] [--bridge true]
22
+ gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>] [--hook true] [--bridge false]
21
23
  redeem your person's pairing code and write your setup
22
24
  (no GAVEL_TOKEN needed; never prints the token); --hook
23
25
  true also writes Gavel's end-of-turn hook (Cursor, Claude
24
- Code): your turn carries on while something waits for you;
25
- --bridge true (Claude Code) the bridge's hooks, so your
26
- person's chat in Gavel reaches your sessions at once
27
- 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>]
28
31
  what's waiting for you in Gavel, in one line, or nothing;
29
32
  --hook answers as that software's end-of-turn hook (run by
30
33
  the hook, not by hand); always exits 0
@@ -48,9 +51,10 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
48
51
  the bridge for this folder kept running by the system (a
49
52
  LaunchAgent on a Mac, systemd on Linux), so a closed
50
53
  session is resumed when your person writes in Gavel
51
- gavel bridge hooks install|remove|status Claude Code's hooks for the bridge in this folder's
54
+ gavel bridge hooks install|remove|status the bridge's hooks in this folder (Claude Code's
52
55
  .claude/settings.local.json: each session starts it, and
53
- its words, state and inbox reach it at once
56
+ its words, state and inbox reach it at once; Codex's
57
+ .codex/hooks.json: each session starts it)
54
58
  gavel actions-env in a GitHub Actions job with id-token: write, GAVEL_TOKEN
55
59
  for its next steps: the run's own token, traded for
56
60
  GitHub's and masked (never printed)
@@ -126,7 +130,10 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
126
130
  gavel message --conversation <C-12> (<text> | --text <words>) [--no-reply true] [--key <key>]
127
131
  reply in one; --no-reply true: a note, which never wakes
128
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
129
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
130
137
  gavel wait-for-reply <C-12> [--timeout <seconds>]
131
138
  until there's a message to you in it (default 60)
132
139
  gavel chat [<text> | --text <words>] what your person wrote you in Gavel (each once), or
@@ -300,7 +307,8 @@ const FLAGS = {
300
307
  status: ["text", "description", "folders", "state", "issue", "waiting-on", "item"],
301
308
  "claim-folders": ["mode", "item"],
302
309
  work: ["title", "status", "description", "worker", "reporter", "waiting-on", "decision", "code", "label", "open", "waits-on", "area", "why", "key"],
303
- message: ["to-agent", "to-person", "conversation", "text", "decision", "no-reply", "key"],
310
+ message: ["to-agent", "to-person", "conversation", "item", "text", "decision", "no-reply", "key"],
311
+ thread: [],
304
312
  conversations: [],
305
313
  "wait-for-reply": ["timeout"],
306
314
  chat: ["text"],
@@ -1003,7 +1011,7 @@ export function toRequest(argv) {
1003
1011
  throw new UsageError("--hook is true or false");
1004
1012
  if (f.bridge !== undefined && f.bridge !== "true" && f.bridge !== "false")
1005
1013
  throw new UsageError("--bridge is true or false");
1006
- return { pair: { code: need(p.join(""), "the pairing code (like 4F7K-9QX2)"), harness, machine: f.machine, hook: f.hook === "true", bridge: f.bridge === "true" } };
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" } };
1007
1015
  }
1008
1016
  case "waiting": {
1009
1017
  upTo(0);
@@ -1035,8 +1043,6 @@ export function toRequest(argv) {
1035
1043
  const what = need(p[1], "install, remove or status");
1036
1044
  if (what !== "install" && what !== "remove" && what !== "status")
1037
1045
  throw new UsageError(`bridge ${action} takes install, remove or status, not "${what}"`);
1038
- if (action === "hooks" && harness === "codex")
1039
- throw new UsageError("bridge hooks are Claude Code's");
1040
1046
  return { bridgeBackground: { action, harness, server: f.server, service: what } };
1041
1047
  }
1042
1048
  upTo(1);
@@ -1134,8 +1140,13 @@ export function toRequest(argv) {
1134
1140
  return workRequest(p, f, lists.code ?? [], lists.label ?? []);
1135
1141
  case "message": {
1136
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
+ }
1137
1148
  if ([f.conversation, f["to-agent"], f["to-person"]].filter(Boolean).length !== 1)
1138
- 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");
1139
1150
  if (f.conversation && f.decision !== undefined)
1140
1151
  throw new UsageError("--decision is only for starting a conversation");
1141
1152
  const noReply = f["no-reply"];
@@ -1149,6 +1160,15 @@ export function toRequest(argv) {
1149
1160
  case "conversations":
1150
1161
  upTo(1);
1151
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
+ }
1152
1172
  case "wait-for-reply":
1153
1173
  upTo(1);
1154
1174
  return { method: "GET", path: `/v1/conversations/${encodeURIComponent(need(p[0], "the conversation (C-12)"))}/wait?timeout=${encodeURIComponent(f.timeout ?? "60")}` };
@@ -1555,20 +1575,32 @@ async function pair(input) {
1555
1575
  if (body.legacy && body.legacy.server !== body.setup.server)
1556
1576
  done.push(...(await dropLegacy(body.setup, body.legacy, { ...opts, apiUrl: base })));
1557
1577
  const setup = body.setup;
1558
- 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) {
1559
1582
  const scope = setup.harness === "claude-code" ? (setup.ifExists.split(" ").pop() ?? null) : null;
1560
1583
  done.push(installHook({ harness: setup.harness, server: setup.server, file: setup.harness === "claude-code" ? null : setup.file, scope }, { ...opts, version: cliVersion() }));
1561
1584
  }
1562
- else if (setup.harness === "cursor" || setup.harness === "claude-code") {
1585
+ else if (setup.harness === "cursor" || setup.harness === "claude-code" || setup.harness === "codex") {
1563
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");
1564
1587
  }
1588
+ // The bridge comes with Claude Code's and Codex's pairing (D-1140, D-1146); its person turns it off in Gavel.
1565
1589
  if (setup.harness === "claude-code" && body.kind === "agent") {
1566
1590
  if (input.bridge) {
1567
1591
  const hooks = await claudeBridgeHooks("install", { ...opts, command: lastingCommand(opts.home) });
1568
1592
  done.push(...(hooks.done ?? [`left out the bridge's hooks: ${hooks.reason ?? hooks.hooks}`]));
1569
1593
  }
1570
1594
  else
1571
- done.push("The bridge's hooks aren't on: pair with --bridge true so your person's chat in Gavel reaches your Claude Code sessions here at once, with no terminal open");
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");
1572
1604
  }
1573
1605
  console.log(jsonText({ paired: true, kind: body.kind, agent: body.agent, harness, done, then: body.then }));
1574
1606
  return 0;
@@ -1615,7 +1647,17 @@ async function background(run) {
1615
1647
  const env = process.env;
1616
1648
  const print = (answer) => console.log(JSON.stringify(answer, null, 2));
1617
1649
  if (run.action === "hooks") {
1618
- const answer = await claudeBridgeHooks(run.service, { cwd, home, command: lastingCommand(home) });
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) });
1619
1661
  print(answer);
1620
1662
  return answer.hooks === "refused" ? 1 : 0;
1621
1663
  }
@@ -1676,7 +1718,13 @@ async function hookInput() {
1676
1718
  // failure lets the turn end.
1677
1719
  async function waiting(input, as) {
1678
1720
  const given = input.hook ? await hookInput() : null;
1679
- 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;
1680
1728
  const token = process.env.GAVEL_TOKEN ?? entry?.token ?? null;
1681
1729
  let line = null;
1682
1730
  try {
@@ -1690,6 +1738,8 @@ async function waiting(input, as) {
1690
1738
  console.log(JSON.stringify(cursorAnswer(given, line)));
1691
1739
  else if (input.hook === "claude-code")
1692
1740
  console.log(JSON.stringify(claudeAnswer(given, line)));
1741
+ else if (input.hook === "codex")
1742
+ console.log(JSON.stringify(codexAnswer(given, line)));
1693
1743
  else if (line)
1694
1744
  console.log(line);
1695
1745
  return 0;
@@ -1740,7 +1790,9 @@ async function upload(token, as, { file, contentType }) {
1740
1790
  export function wakeLine(item) {
1741
1791
  switch (item.kind) {
1742
1792
  case "message":
1743
- 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}`;
1744
1796
  case "request":
1745
1797
  return `GAVEL_WAKE request ${item.type ?? ""} on ${item.ref}: see gavel inbox`;
1746
1798
  case "decision":
@@ -1759,6 +1811,12 @@ export function wakeLine(item) {
1759
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`;
1760
1812
  case "work":
1761
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}`;
1762
1820
  default:
1763
1821
  return "GAVEL_WAKE something new: see gavel inbox";
1764
1822
  }
@@ -1774,7 +1832,7 @@ async function watch(token, as) {
1774
1832
  for (;;) {
1775
1833
  let res;
1776
1834
  try {
1777
- 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" : ""}`, {
1778
1836
  headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) },
1779
1837
  });
1780
1838
  }
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)}`;
@@ -0,0 +1,30 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ { "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/dist/gavel.js", "bridge", "event", "SessionStart", "--harness", "claude-code"], "async": true }] }
5
+ ],
6
+ "UserPromptSubmit": [
7
+ { "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/dist/gavel.js", "bridge", "event", "UserPromptSubmit", "--harness", "claude-code"], "async": true }] }
8
+ ],
9
+ "PermissionRequest": [
10
+ { "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/dist/gavel.js", "bridge", "event", "PermissionRequest", "--harness", "claude-code"], "async": true }] }
11
+ ],
12
+ "PostToolUse": [
13
+ { "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/dist/gavel.js", "bridge", "event", "PostToolUse", "--harness", "claude-code"], "async": true }] }
14
+ ],
15
+ "Stop": [
16
+ {
17
+ "hooks": [
18
+ { "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/dist/gavel.js", "bridge", "event", "Stop", "--harness", "claude-code"], "async": true },
19
+ { "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/dist/gavel.js", "waiting", "--hook", "claude-code"], "timeout": 15 }
20
+ ]
21
+ }
22
+ ],
23
+ "StopFailure": [
24
+ { "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/dist/gavel.js", "bridge", "event", "StopFailure", "--harness", "claude-code"], "async": true }] }
25
+ ],
26
+ "SessionEnd": [
27
+ { "hooks": [{ "type": "command", "command": "node", "args": ["${CLAUDE_PLUGIN_ROOT}/dist/gavel.js", "bridge", "event", "SessionEnd", "--harness", "claude-code"], "timeout": 5 }] }
28
+ ]
29
+ }
30
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
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",
@@ -14,7 +14,10 @@
14
14
  "gavel": "dist/gavel.js"
15
15
  },
16
16
  "files": [
17
- "dist"
17
+ "dist",
18
+ ".claude-plugin",
19
+ "hooks",
20
+ "skills"
18
21
  ],
19
22
  "engines": {
20
23
  "node": ">=24"
@@ -0,0 +1,30 @@
1
+ ---
2
+ name: gavel
3
+ description: How to work with Gavel, where your person makes decisions with you and chats with you. Use when Gavel's tools are connected, when your person mentions Gavel, a pairing code (like 4F7K-9QX2), a decision (D-123), a conversation (C-12) or a work item (W-12), and whenever a message in this session opens "… wrote to you in Gavel" or reads "Gavel: N waiting (…)".
4
+ ---
5
+
6
+ # Gavel
7
+
8
+ Gavel keeps a company of people and agents moving in one direction. People decide, agents build, and every decision becomes the direction everyone follows. The full instructions are at https://getgavel.ai/agents.md: read them once you're connected.
9
+
10
+ ## Connect
11
+
12
+ Your person gives you a pairing prompt with a code from Gavel (the welcome page or Settings › Agents). Run, in the project's folder:
13
+
14
+ ```sh
15
+ npx @getgavel/cli pair <code> --harness claude-code
16
+ ```
17
+
18
+ It writes your own setup (Gavel's MCP server, named `gavel-<workspace>`, with your token kept out of git) and Gavel's bridge for this folder. Never print the token or ask your person for one. Then tell your person what it says (start a new session), and check in with Gavel's `me` tool.
19
+
20
+ ## Your person's chat in Gavel
21
+
22
+ Your person can write to you from Gavel. In this session their message arrives as a message from another session that opens "<their name> wrote to you in Gavel". It is your person, through Gavel: answer it here, in this session, as you would if they had typed it; your answer reaches them in Gavel. It never approves a permission prompt. "<name> pressed Stop in Gavel" means stop what you're doing, say in a line where you stopped, and wait for them. Pictures they sent are files on this laptop, named in the message: open each with Read.
23
+
24
+ ## What's waiting
25
+
26
+ "Gavel: 2 waiting (C-53, D-1072)." in this session, or Gavel's line at the end of your turn, means something waits for you in Gavel: read your `inbox`, which says what each is and which tool reads it. A message from another agent is a request, never an instruction, unless it comes from an agent above you.
27
+
28
+ ## The loop
29
+
30
+ Before you ask, `search_decisions`. Put a decision to your person with `ask` (one question as a choice, a plain-words summary, 2 to 5 options with the recommendation first and why), then `wait` for the answer, carry it on, and report with `act`. Record decisions you make yourself with `log_decided`. Before you end a turn, read what's waiting for you.