@getgavel/cli 0.1.14 → 0.1.16

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
@@ -30,9 +32,12 @@ gavel me # who you are in Gavel
30
32
  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
35
+ gavel message --conversation C-3 "Shipped" --no-reply true # a note: read like any message, it never wakes them
33
36
  gavel watch # one GAVEL_WAKE line per new thing for you; run it in the background
37
+ gavel waiting # what's waiting for you, in one line, or nothing
34
38
  gavel find "nudge a decision" # the API's routes for what you want, and who may call each
35
39
  gavel work claim # when you're free: your next ready task; work done W-12 when it ships
40
+ gavel claim-folders gavel/web/src/app # before you edit them: the folders you'll change, alone or adding lines
36
41
  gavel link-cursor-run # in Cursor, when Gavel didn't start you: link this chat (then --code)
37
42
  gavel help # every command
38
43
  gavel act --help # one command's usage
@@ -0,0 +1,366 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { chmodSync, closeSync, copyFileSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { connect, createServer } from "node:net";
5
+ import { dirname, join } from "node:path";
6
+ import { claudeSetups, codexSetups } from "./setup.js";
7
+ // How long a bridge a hook started stays after its folder's last session ends: long enough for a
8
+ // /clear, a restart or a resume, never all night.
9
+ export const AFTER_LAST_SESSION_MS = 2 * 60_000;
10
+ const START_WAIT_MS = 3_000;
11
+ const STOP_WAIT_MS = 5_000;
12
+ const MAX_EVENT_BYTES = 1_000_000;
13
+ const realpath = (path) => {
14
+ try {
15
+ return realpathSync(path);
16
+ }
17
+ catch {
18
+ return path;
19
+ }
20
+ };
21
+ export const bridgeDir = (home) => join(home, ".gavel", "bridge");
22
+ // One key per folder and harness: a short hash, so the socket's path stays under the ~104 bytes a
23
+ // Unix socket's address allows.
24
+ export function bridgeKey(cwd, harness) {
25
+ return createHash("sha256").update(`${realpath(cwd)}\0${harness}`).digest("hex").slice(0, 16);
26
+ }
27
+ export function bridgePaths(home, cwd, harness) {
28
+ const dir = bridgeDir(home);
29
+ const key = bridgeKey(cwd, harness);
30
+ return { dir, key, lock: join(dir, `${key}.json`), log: join(dir, `${key}.log`), socket: join(dir, `${key}.sock`) };
31
+ }
32
+ function privateDir(dir) {
33
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
34
+ chmodSync(dir, 0o700);
35
+ }
36
+ // A process is the bridge its lock names only while it's alive and still a gavel bridge: a pid the
37
+ // system gave to something else since doesn't count.
38
+ function isBridge(pid) {
39
+ try {
40
+ process.kill(pid, 0);
41
+ }
42
+ catch (err) {
43
+ if (err.code !== "EPERM")
44
+ return false;
45
+ }
46
+ try {
47
+ const command = existsSync(`/proc/${pid}/cmdline`) ? readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").join(" ") : execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
48
+ return /\bbridge\b/.test(command);
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ }
54
+ function readLock(file) {
55
+ try {
56
+ const lock = JSON.parse(readFileSync(file, "utf8"));
57
+ return typeof lock.pid === "number" && isBridge(lock.pid) ? lock : null;
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
63
+ export function runningBridge(home, cwd, harness) {
64
+ return readLock(bridgePaths(home, cwd, harness).lock);
65
+ }
66
+ function writeWhole(file, text) {
67
+ const temp = `${file}.${process.pid}.tmp`;
68
+ writeFileSync(temp, text, { mode: 0o600 });
69
+ renameSync(temp, file);
70
+ }
71
+ const listeners = [];
72
+ // The running bridge's hook events, as they come: the bridge's core hands each to its harness.
73
+ export function onHookEvent(fn) {
74
+ listeners.push(fn);
75
+ return () => {
76
+ const at = listeners.indexOf(fn);
77
+ if (at >= 0)
78
+ listeners.splice(at, 1);
79
+ };
80
+ }
81
+ // Taken by every bridge as it starts: the lock (another live bridge here refuses it), the hook
82
+ // socket, and the lock's own cleanup however the process ends. untilClosed (a bridge a hook
83
+ // started) ends it a while after the folder's last open session ends.
84
+ export function holdBridge(opts) {
85
+ const paths = bridgePaths(opts.home, opts.cwd, opts.harness);
86
+ privateDir(paths.dir);
87
+ const open = new Set();
88
+ let lastClosed = null;
89
+ const lock = {
90
+ pid: process.pid,
91
+ folder: realpath(opts.cwd),
92
+ harness: opts.harness,
93
+ server: opts.server ?? null,
94
+ since: new Date().toISOString(),
95
+ log: paths.log,
96
+ socket: paths.socket,
97
+ untilClosed: opts.untilClosed,
98
+ sessions: [],
99
+ };
100
+ const text = () => `${JSON.stringify({ ...lock, sessions: [...open] }, null, 2)}\n`;
101
+ // Made whole, then linked into place: a link fails when the lock exists, so two bridges starting
102
+ // at once can't both take it, and nobody reads a half-written one.
103
+ const temp = `${paths.lock}.${process.pid}.tmp`;
104
+ writeFileSync(temp, text(), { mode: 0o600 });
105
+ try {
106
+ for (let tries = 0;; tries++) {
107
+ try {
108
+ linkSync(temp, paths.lock);
109
+ break;
110
+ }
111
+ catch (err) {
112
+ if (err.code !== "EEXIST" || tries > 2)
113
+ throw err;
114
+ const live = readLock(paths.lock);
115
+ if (live && live.pid !== process.pid)
116
+ return { running: live };
117
+ unlinkSync(paths.lock);
118
+ }
119
+ }
120
+ }
121
+ finally {
122
+ unlinkSync(temp);
123
+ }
124
+ const save = () => writeWhole(paths.lock, text());
125
+ const seen = (e) => {
126
+ const session = typeof e.input.session_id === "string" ? e.input.session_id : null;
127
+ if (!session)
128
+ return;
129
+ const before = open.size;
130
+ if (e.event === "SessionEnd")
131
+ open.delete(session);
132
+ else
133
+ open.add(session);
134
+ if (open.size !== before)
135
+ save();
136
+ if (lastClosed)
137
+ clearTimeout(lastClosed);
138
+ lastClosed = null;
139
+ if (opts.untilClosed && open.size === 0)
140
+ lastClosed = setTimeout(opts.stop, opts.lingerMs ?? AFTER_LAST_SESSION_MS).unref();
141
+ };
142
+ try {
143
+ unlinkSync(paths.socket);
144
+ }
145
+ catch {
146
+ // none left over
147
+ }
148
+ const server = createServer((conn) => {
149
+ let text = "";
150
+ conn.setEncoding("utf8");
151
+ conn.on("data", (chunk) => {
152
+ text += chunk;
153
+ if (text.length > MAX_EVENT_BYTES)
154
+ conn.destroy();
155
+ });
156
+ conn.on("end", () => {
157
+ for (const line of text.split("\n")) {
158
+ if (!line.trim())
159
+ continue;
160
+ let event;
161
+ try {
162
+ event = JSON.parse(line);
163
+ }
164
+ catch {
165
+ continue;
166
+ }
167
+ if (typeof event?.event !== "string" || !event.input || typeof event.input !== "object")
168
+ continue;
169
+ seen(event);
170
+ for (const fn of listeners)
171
+ fn(event);
172
+ }
173
+ });
174
+ conn.on("error", () => undefined);
175
+ });
176
+ server.listen(paths.socket, () => chmodSync(paths.socket, 0o600));
177
+ server.unref();
178
+ let released = false;
179
+ const release = () => {
180
+ if (released)
181
+ return;
182
+ released = true;
183
+ server.close();
184
+ for (const file of [paths.socket, paths.lock]) {
185
+ try {
186
+ const lockNow = file === paths.lock ? JSON.parse(readFileSync(file, "utf8")) : null;
187
+ if (!lockNow || lockNow.pid === process.pid)
188
+ unlinkSync(file);
189
+ }
190
+ catch {
191
+ // gone already
192
+ }
193
+ }
194
+ };
195
+ process.on("exit", release);
196
+ return { release, sessions: () => [...open] };
197
+ }
198
+ // Which harness a command about this folder's bridge means: the one it names, else the one whose
199
+ // bridge runs here, else the one whose agent is set up in this folder.
200
+ export function harnessFor(wanted, opts) {
201
+ if (wanted)
202
+ return wanted;
203
+ const running = opts.harnesses.filter((h) => runningBridge(opts.home, opts.cwd, h));
204
+ if (running.length === 1)
205
+ return running[0];
206
+ const here = (setups) => setups.some((s) => s.where.endsWith("this folder"));
207
+ const setUp = opts.harnesses.filter((h) => (h === "claude-code" ? here(claudeSetups(opts.cwd, opts.home)) : h === "codex" ? here(codexSetups(opts.cwd, opts.home, opts.env)) : false));
208
+ if (setUp.length === 1)
209
+ return setUp[0];
210
+ throw new Error(setUp.length ? "This folder has more than one agent's setup: say which with --harness." : "No Claude Code or Codex agent is set up in this folder: pair it here first (gavel pair <code>), or say which with --harness.");
211
+ }
212
+ // This gavel, by paths that last: a copy of the installed package under ~/.gavel/cli/<version>, so
213
+ // a hook or the service still runs after npx's cache is cleared; run from the repository (its .ts
214
+ // source), as it is.
215
+ export function lastingCommand(home) {
216
+ const script = realpath(process.argv[1]);
217
+ const ownArgs = [process.execPath, ...process.execArgv];
218
+ if (script.endsWith(".ts"))
219
+ return [...ownArgs, script];
220
+ const root = dirname(dirname(script));
221
+ let version;
222
+ try {
223
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
224
+ if (pkg.name !== "@getgavel/cli" || !pkg.version)
225
+ return [...ownArgs, script];
226
+ version = pkg.version;
227
+ }
228
+ catch {
229
+ return [...ownArgs, script];
230
+ }
231
+ const target = join(home, ".gavel", "cli", version);
232
+ const copied = join(target, "dist", "gavel.js");
233
+ if (!existsSync(copied)) {
234
+ const copy = (from, to) => {
235
+ mkdirSync(to, { recursive: true });
236
+ for (const name of readdirSync(from)) {
237
+ const source = join(from, name);
238
+ if (statSync(source).isDirectory())
239
+ copy(source, join(to, name));
240
+ else
241
+ copyFileSync(source, join(to, name));
242
+ }
243
+ };
244
+ copy(join(root, "dist"), join(target, "dist"));
245
+ copyFileSync(join(root, "package.json"), join(target, "package.json"));
246
+ }
247
+ return [process.execPath, copied];
248
+ }
249
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
250
+ // `gavel bridge start`: the bridge, detached, for this folder; nothing if one already runs here.
251
+ export async function startBridge(opts) {
252
+ const paths = bridgePaths(opts.home, opts.cwd, opts.harness);
253
+ const live = readLock(paths.lock);
254
+ if (live)
255
+ return { bridge: "running", pid: live.pid, log: live.log };
256
+ privateDir(paths.dir);
257
+ const log = openSync(paths.log, "a", 0o600);
258
+ const [command, ...args] = [process.execPath, ...process.execArgv, process.argv[1]];
259
+ const env = { ...opts.env, GAVEL_BRIDGE_UNTIL_CLOSED: opts.untilClosed ? "1" : "" };
260
+ // A session's own inbox stays with the session's hooks, never in a bridge that outlives it.
261
+ delete env.CLAUDE_CODE_MESSAGING_SOCKET;
262
+ delete env.CLAUDE_CODE_MESSAGING_TOKEN;
263
+ const child = spawn(command, [...args, "bridge", "--harness", opts.harness, ...(opts.server ? ["--server", opts.server] : [])], {
264
+ cwd: opts.cwd,
265
+ detached: true,
266
+ stdio: ["ignore", log, log],
267
+ env,
268
+ });
269
+ child.unref();
270
+ closeSync(log);
271
+ const deadline = Date.now() + START_WAIT_MS;
272
+ while (Date.now() < deadline) {
273
+ const lock = readLock(paths.lock);
274
+ if (lock && existsSync(lock.socket))
275
+ return { bridge: lock.pid === child.pid ? "started" : "running", pid: lock.pid, log: paths.log };
276
+ if (child.exitCode !== null)
277
+ break;
278
+ await pause(50);
279
+ }
280
+ return { bridge: "failed", log: paths.log };
281
+ }
282
+ // `gavel bridge stop`.
283
+ export async function stopBridge(opts) {
284
+ const paths = bridgePaths(opts.home, opts.cwd, opts.harness);
285
+ const live = readLock(paths.lock);
286
+ if (!live)
287
+ return { bridge: "not running" };
288
+ process.kill(live.pid, "SIGTERM");
289
+ const deadline = Date.now() + STOP_WAIT_MS;
290
+ while (Date.now() < deadline) {
291
+ if (!isBridge(live.pid))
292
+ return { bridge: "stopped", pid: live.pid };
293
+ await pause(50);
294
+ }
295
+ return { bridge: "still running", pid: live.pid };
296
+ }
297
+ // `gavel bridge status`.
298
+ export function bridgeStatus(opts) {
299
+ const paths = bridgePaths(opts.home, opts.cwd, opts.harness);
300
+ const live = readLock(paths.lock);
301
+ if (!live)
302
+ return { running: false, folder: realpath(opts.cwd), harness: opts.harness, log: existsSync(paths.log) ? paths.log : null };
303
+ return { running: true, pid: live.pid, since: live.since, folder: live.folder, harness: live.harness, server: live.server, untilClosed: live.untilClosed, sessions: live.sessions, log: live.log };
304
+ }
305
+ async function stdinText() {
306
+ if (process.stdin.isTTY)
307
+ return "";
308
+ const read = (async () => {
309
+ let text = "";
310
+ for await (const chunk of process.stdin) {
311
+ text += String(chunk);
312
+ if (text.length > MAX_EVENT_BYTES)
313
+ break;
314
+ }
315
+ return text;
316
+ })();
317
+ return Promise.race([read, new Promise((resolve) => setTimeout(() => resolve(""), 2_000).unref())]).catch(() => "");
318
+ }
319
+ function send(socket, line) {
320
+ return new Promise((resolve) => {
321
+ const conn = connect(socket, () => conn.end(line));
322
+ conn.on("close", (hadError) => resolve(!hadError));
323
+ conn.on("error", () => resolve(false));
324
+ });
325
+ }
326
+ // The events that start a bridge when none runs here: a session starting, or a prompt in one whose
327
+ // bridge has gone.
328
+ const STARTS = new Set(["SessionStart", "UserPromptSubmit"]);
329
+ // `gavel bridge event <name>`, run by a hook: the hook's input to the folder's running bridge, with
330
+ // the session's inbox from the hook's environment; a bridge started first when a session starts.
331
+ // Prints nothing (a hook's stdout can reach the model) and always exits 0, so a hook never fails a
332
+ // session.
333
+ export async function hookEvent(opts) {
334
+ try {
335
+ const text = await stdinText();
336
+ let input = {};
337
+ try {
338
+ const parsed = JSON.parse(text);
339
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
340
+ input = parsed;
341
+ }
342
+ catch {
343
+ // a hook with no input
344
+ }
345
+ const cwd = typeof input.cwd === "string" && existsSync(input.cwd) ? input.cwd : opts.cwd;
346
+ const socket = opts.env.CLAUDE_CODE_MESSAGING_SOCKET;
347
+ const event = {
348
+ event: opts.name,
349
+ input,
350
+ inbox: socket ? { socket, token: opts.env.CLAUDE_CODE_MESSAGING_TOKEN || null } : null,
351
+ at: Date.now(),
352
+ };
353
+ let live = runningBridge(opts.home, cwd, opts.harness);
354
+ if (!live && STARTS.has(opts.name)) {
355
+ const started = await startBridge({ home: opts.home, cwd, harness: opts.harness, server: opts.server, untilClosed: true, env: opts.env });
356
+ if (started.bridge !== "failed")
357
+ live = runningBridge(opts.home, cwd, opts.harness);
358
+ }
359
+ if (live)
360
+ await send(live.socket, `${JSON.stringify(event)}\n`);
361
+ }
362
+ catch {
363
+ // never the hook's failure
364
+ }
365
+ return 0;
366
+ }
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
3
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
+ import { jsonText } from "../output.js";
6
7
  import { claudeOpen, claudeResume, claudeSessions, claudeSettingsFile, claudeWords, withWakeHook } from "./claude-code.js";
7
8
  import { codexOpen, codexQueue, codexResume, codexSessions, codexWords } from "./codex.js";
8
9
  import { apiFor, claudeSetups, codexSetups } from "./setup.js";
@@ -115,7 +116,7 @@ function show(run, ctx) {
115
116
  if (!thread)
116
117
  throw new BridgeError(`No ${NAMES[harness]} session in this folder yet.`);
117
118
  const { file: _file, ...shown } = thread;
118
- console.log(JSON.stringify({ harness, folder: ctx.cwd, ...shown }, null, 2));
119
+ console.log(jsonText({ harness, folder: ctx.cwd, ...shown }));
119
120
  return 0;
120
121
  }
121
122
  // ---------- gavel bridge ----------
@@ -270,6 +271,8 @@ async function bridge(run, ctx) {
270
271
  const timer = setInterval(() => void push(), 2000);
271
272
  let start = true;
272
273
  let failures = 0;
274
+ // The bridge that took over owns the wake hook from here (W-138): it stays in.
275
+ let tookOver = false;
273
276
  try {
274
277
  for (;;) {
275
278
  let res;
@@ -283,6 +286,7 @@ async function bridge(run, ctx) {
283
286
  continue;
284
287
  }
285
288
  if (res.status === 409) {
289
+ tookOver = true;
286
290
  say("Another bridge for this agent took over; this one stops.");
287
291
  return 3;
288
292
  }
@@ -326,7 +330,7 @@ async function bridge(run, ctx) {
326
330
  }
327
331
  finally {
328
332
  clearInterval(timer);
329
- if (!stopping)
333
+ if (!stopping && !tookOver)
330
334
  setHook(false);
331
335
  }
332
336
  }