@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.
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "gavel",
3
+ "displayName": "Gavel",
4
+ "description": "Gavel in Claude Code: your person's chat in Gavel reaches your sessions at once (Gavel's bridge, started with each session), the end-of-turn reminder of what's waiting for you, and how to work with Gavel.",
5
+ "author": { "name": "Gavel", "url": "https://getgavel.ai" },
6
+ "homepage": "https://getgavel.ai/agents",
7
+ "repository": "https://github.com/ntommarello/gavel",
8
+ "keywords": ["gavel", "decisions", "chat"]
9
+ }
package/README.md CHANGED
@@ -32,6 +32,7 @@ gavel me # who you are in Gavel
32
32
  gavel search "onboarding copy" # before you ask
33
33
  gavel ask --file decision.json # put a decision to your person
34
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
35
36
  gavel watch # one GAVEL_WAKE line per new thing for you; run it in the background
36
37
  gavel waiting # what's waiting for you, in one line, or nothing
37
38
  gavel find "nudge a decision" # the API's routes for what you want, and who may call each
@@ -0,0 +1,397 @@
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
+ // The chat off in Gavel stops the bridge (D-1140): it leaves this mark as it goes, and while the
330
+ // chat stays off a prompt starts it again (to look) at most once a minute; a session's start always
331
+ // looks.
332
+ const OFF_RECHECK_MS = 60_000;
333
+ const offMark = (home, cwd, harness) => join(bridgeDir(home), `${bridgeKey(cwd, harness)}.off`);
334
+ export function markChatOff(opts, off) {
335
+ const file = offMark(opts.home, opts.cwd, opts.harness);
336
+ try {
337
+ if (off) {
338
+ privateDir(bridgeDir(opts.home));
339
+ writeFileSync(file, `${new Date().toISOString()}\n`, { mode: 0o600 });
340
+ }
341
+ else
342
+ unlinkSync(file);
343
+ }
344
+ catch {
345
+ // nothing to mark or clear
346
+ }
347
+ }
348
+ function offRecently(home, cwd, harness) {
349
+ try {
350
+ return Date.now() - statSync(offMark(home, cwd, harness)).mtimeMs < OFF_RECHECK_MS;
351
+ }
352
+ catch {
353
+ return false;
354
+ }
355
+ }
356
+ // `gavel bridge event <name>`, run by a hook: the hook's input to the folder's running bridge, with
357
+ // the session's inbox from the hook's environment; a bridge started first when a session starts.
358
+ // Prints nothing (a hook's stdout can reach the model) and always exits 0, so a hook never fails a
359
+ // session.
360
+ export async function hookEvent(opts) {
361
+ try {
362
+ const text = await stdinText();
363
+ let input = {};
364
+ try {
365
+ const parsed = JSON.parse(text);
366
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
367
+ input = parsed;
368
+ }
369
+ catch {
370
+ // a hook with no input
371
+ }
372
+ const cwd = typeof input.cwd === "string" && existsSync(input.cwd) ? input.cwd : opts.cwd;
373
+ const socket = opts.env.CLAUDE_CODE_MESSAGING_SOCKET;
374
+ const event = {
375
+ event: opts.name,
376
+ input,
377
+ inbox: socket ? { socket, token: opts.env.CLAUDE_CODE_MESSAGING_TOKEN || null } : null,
378
+ at: Date.now(),
379
+ };
380
+ let live = runningBridge(opts.home, cwd, opts.harness);
381
+ // Hooks a plugin or the user's settings give every folder start a bridge only where this
382
+ // harness has a Gavel agent set up.
383
+ const setUp = (opts.harness === "codex" ? codexSetups(cwd, opts.home, opts.env) : claudeSetups(cwd, opts.home)).some((s) => s.where.endsWith("this folder"));
384
+ const looksAgain = opts.name === "SessionStart" || !offRecently(opts.home, cwd, opts.harness);
385
+ if (!live && setUp && STARTS.has(opts.name) && looksAgain) {
386
+ const started = await startBridge({ home: opts.home, cwd, harness: opts.harness, server: opts.server, untilClosed: true, env: opts.env });
387
+ if (started.bridge !== "failed")
388
+ live = runningBridge(opts.home, cwd, opts.harness);
389
+ }
390
+ if (live)
391
+ await send(live.socket, `${JSON.stringify(event)}\n`);
392
+ }
393
+ catch {
394
+ // never the hook's failure
395
+ }
396
+ return 0;
397
+ }