@getgavel/cli 0.1.24 → 0.1.25

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gavel",
3
- "version": "0.1.24",
3
+ "version": "0.1.25",
4
4
  "displayName": "Gavel",
5
5
  "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.",
6
6
  "author": { "name": "Gavel", "url": "https://getgavel.ai" },
@@ -2,6 +2,7 @@ import { execFileSync, spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import { chmodSync, closeSync, copyFileSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { connect, createServer } from "node:net";
5
+ import { tmpdir } from "node:os";
5
6
  import { dirname, join } from "node:path";
6
7
  import { claudeSetups, codexSetups } from "./setup.js";
7
8
  // How long a bridge a hook started stays after its folder's last session ends: long enough for a
@@ -19,15 +20,29 @@ const realpath = (path) => {
19
20
  }
20
21
  };
21
22
  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.
23
+ // One key per folder and harness: a short hash, so the socket's path stays under the bytes a Unix
24
+ // socket's address allows.
24
25
  export function bridgeKey(cwd, harness) {
25
26
  return createHash("sha256").update(`${realpath(cwd)}\0${harness}`).digest("hex").slice(0, 16);
26
27
  }
28
+ // The longest path a Unix socket can listen on: macOS's address holds 104 bytes with its closing
29
+ // zero (Linux's 108), and past it listen fails (W-244).
30
+ export const MAX_SOCKET_PATH = 103;
31
+ // The hook socket beside the lock, unless a long home folder pushes it past the limit: then in a
32
+ // private folder of the user's own under the system's temporary folder, which the lock names.
33
+ function socketPath(dir, key) {
34
+ const beside = join(dir, `${key}.sock`);
35
+ if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH)
36
+ return beside;
37
+ return join(tmpdir(), `gavel-bridge-${process.getuid?.() ?? "user"}`, `${key}.sock`);
38
+ }
27
39
  export function bridgePaths(home, cwd, harness) {
28
40
  const dir = bridgeDir(home);
29
41
  const key = bridgeKey(cwd, harness);
30
- return { dir, key, lock: join(dir, `${key}.json`), log: join(dir, `${key}.log`), socket: join(dir, `${key}.sock`) };
42
+ return { dir, key, lock: join(dir, `${key}.json`), log: join(dir, `${key}.log`), socket: socketPath(dir, key) };
43
+ }
44
+ // Says why the hook socket can't be made, in words a person can act on.
45
+ export class BridgeSocketError extends Error {
31
46
  }
32
47
  function privateDir(dir) {
33
48
  mkdirSync(dir, { recursive: true, mode: 0o700 });
@@ -84,6 +99,11 @@ export function onHookEvent(fn) {
84
99
  export function holdBridge(opts) {
85
100
  const paths = bridgePaths(opts.home, opts.cwd, opts.harness);
86
101
  privateDir(paths.dir);
102
+ if (Buffer.byteLength(paths.socket) > MAX_SOCKET_PATH) {
103
+ throw new BridgeSocketError(`the bridge's socket path (${paths.socket}) is longer than the ${MAX_SOCKET_PATH} bytes a Unix socket allows: set TMPDIR to a shorter folder, such as /tmp`);
104
+ }
105
+ if (dirname(paths.socket) !== paths.dir)
106
+ privateDir(dirname(paths.socket));
87
107
  const open = new Set();
88
108
  let lastClosed = null;
89
109
  const lock = {
@@ -173,6 +193,12 @@ export function holdBridge(opts) {
173
193
  });
174
194
  conn.on("error", () => undefined);
175
195
  });
196
+ // A socket that can't listen is said, never a silent exit (W-244).
197
+ server.on("error", (err) => {
198
+ console.error(`gavel bridge: can't listen for hooks at ${paths.socket} (${err.code ?? err.message}).`);
199
+ release();
200
+ process.exit(1);
201
+ });
176
202
  server.listen(paths.socket, () => chmodSync(paths.socket, 0o600));
177
203
  server.unref();
178
204
  let released = false;
@@ -24,11 +24,22 @@ import { claudeSetups } from "./setup.js";
24
24
  // PostToolUse, Stop, StopFailure and SessionEnd.
25
25
  export const BRIDGE_MIN_VERSION = [2, 1, 224];
26
26
  // One message into a session's inbox; true once Claude Code took the line.
27
+ const ENVELOPE = "cross-session-message";
28
+ // Claude Code (2.1.332) holds another session's message for approval in a session that bypasses
29
+ // permission prompts, unless the sender says it bypasses them too, in the message's own envelope
30
+ // (`from-mode`); the bridge says so for a session it knows bypasses them (W-256), carrying its
31
+ // person's own words and Gavel's wakes. Only that: said to a session that prompts, `bypass` is held
32
+ // as a mismatch, and saying nothing it takes. Words holding the envelope's closing tag go as they are.
33
+ export function attested(text, bypass) {
34
+ if (!bypass || new RegExp(`</${ENVELOPE}`, "i").test(text))
35
+ return text;
36
+ return `<${ENVELOPE} from-name="Gavel" from-mode="bypass">\n${text}\n</${ENVELOPE}>`;
37
+ }
27
38
  export function inboxSend(inbox, text, opts) {
28
39
  return new Promise((resolve) => {
29
40
  const lines = [
30
41
  ...(inbox.token ? [JSON.stringify({ type: "auth", token: inbox.token })] : []),
31
- JSON.stringify({ type: "user", message: { role: "user", content: text }, priority: opts.priority, ...(opts.msgId ? { msg_id: opts.msgId } : {}) }),
42
+ JSON.stringify({ type: "user", message: { role: "user", content: attested(text, opts.bypass === true) }, priority: opts.priority, ...(opts.msgId ? { msg_id: opts.msgId } : {}) }),
32
43
  ];
33
44
  const conn = connect(inbox.socket, () => conn.end(`${lines.join("\n")}\n`));
34
45
  conn.setTimeout(5_000, () => conn.destroy(new Error("timeout")));
@@ -252,8 +263,9 @@ export function sessionWords(jsonl, fromGavel, prompts = new Map()) {
252
263
  const id = line.origin?.msg_id;
253
264
  if (line.type !== "user" || line.origin?.kind !== "peer" || typeof id !== "string" || !fromGavel.has(id) || !line.uuid || !line.timestamp)
254
265
  continue;
266
+ // An attested message's words are its envelope's body, which Claude Code keeps beside it.
255
267
  const content = typeof line.message?.content === "string" ? line.message.content : "";
256
- const body = content.replace(PEER_HEADER, "");
268
+ const body = typeof line.origin.body === "string" ? line.origin.body : content.replace(PEER_HEADER, "");
257
269
  const end = body.indexOf(PEER_FOOTER);
258
270
  const text = theirWords(end >= 0 ? body.slice(0, end) : body);
259
271
  words.push({ id: line.uuid, side: "person", text: text || "(message)", at: line.timestamp, gavelId: id });
@@ -288,6 +300,54 @@ function readFrom(file, offset, max = READ_MAX) {
288
300
  return null;
289
301
  }
290
302
  }
303
+ // A session's permission mode as its transcript last noted it (Claude Code writes it as the file
304
+ // starts and with each prompt), from the file's last 256 KB; null when it says none.
305
+ export function lastMode(file) {
306
+ const read = readFrom(file, Math.max(0, sizeOf(file) - 262_144), 262_144);
307
+ const all = read ? [...read.toString("utf8").matchAll(/"permissionMode":"([A-Za-z]+)"/g)] : [];
308
+ return all.at(-1)?.[1] ?? null;
309
+ }
310
+ // What Claude Code held of the messages other sessions sent this one, as its transcript notes each
311
+ // ("Held peer message", a notice for the person); how many, and when the last was.
312
+ export function heldNotices(file) {
313
+ let held = 0;
314
+ let lastAt = null;
315
+ let text = "";
316
+ try {
317
+ text = readFileSync(file, "utf8");
318
+ }
319
+ catch {
320
+ return { held, lastAt };
321
+ }
322
+ for (const raw of text.split("\n")) {
323
+ if (!raw.includes("Held peer message"))
324
+ continue;
325
+ try {
326
+ const line = JSON.parse(raw);
327
+ if (line.type !== "system" || typeof line.content !== "string" || !line.content.startsWith("Held peer message"))
328
+ continue;
329
+ held++;
330
+ if (typeof line.timestamp === "string")
331
+ lastAt = line.timestamp;
332
+ }
333
+ catch {
334
+ // a line read as it was written
335
+ }
336
+ }
337
+ return { held, lastAt };
338
+ }
339
+ // For `gavel bridge status`: what Claude Code held in the folder's newest session of the messages
340
+ // other sessions sent it (the bridge's before it said who it is, W-256), and how they go through.
341
+ export function claudeHeld(cwd, home, env) {
342
+ const newest = claudeSessions(cwd, home, env)[0];
343
+ const notes = newest ? heldNotices(newest.file) : null;
344
+ if (!notes?.held)
345
+ return null;
346
+ return {
347
+ ...notes,
348
+ release: "Claude Code holds messages from other sessions while this session bypasses permission prompts. Let them through in the session's dialog (Deliver), or in /config, Messages from your other sessions. The bridge from 0.1.25 says who it is, so its messages aren't held.",
349
+ };
350
+ }
291
351
  // The first and the last of an answer's words as its transcript line has them (JSON), each within
292
352
  // one line of it: Claude Code joins a message's parts with a newline for the Stop hook, so neither
293
353
  // spans two parts.
@@ -372,6 +432,11 @@ export class ClaudeCodeHarness {
372
432
  renameSync(temp, this.idsFile);
373
433
  }
374
434
  // The session Gavel shows and writes to: the newest one open, else the folder's newest.
435
+ // Whether a session bypasses permission prompts, as its hooks or else its transcript last said.
436
+ bypasses(s) {
437
+ const file = s.transcript ?? claudeSessions(this.ctx.cwd, this.ctx.home, this.ctx.env).find((c) => c.id === s.id)?.file ?? null;
438
+ return (s.mode ?? (file ? lastMode(file) : null)) === "bypassPermissions";
439
+ }
375
440
  current() {
376
441
  const open = [...this.sessions.values()].filter((s) => s.open).sort((a, b) => Number(b.begun) - Number(a.begun) || b.seen - a.seen);
377
442
  return open[0] ?? null;
@@ -430,7 +495,7 @@ export class ClaudeCodeHarness {
430
495
  session(id) {
431
496
  let s = this.sessions.get(id);
432
497
  if (!s) {
433
- s = { id, inbox: null, transcript: null, open: true, hooked: false, background: false, begun: false, state: "idle", seen: Date.now(), run: null, spoken: new Map() };
498
+ s = { id, inbox: null, transcript: null, open: true, hooked: false, background: false, begun: false, mode: null, state: "idle", seen: Date.now(), run: null, spoken: new Map() };
434
499
  this.sessions.set(id, s);
435
500
  }
436
501
  return s;
@@ -454,6 +519,8 @@ export class ClaudeCodeHarness {
454
519
  s.inbox = e.inbox;
455
520
  if (typeof input.transcript_path === "string")
456
521
  s.transcript = input.transcript_path;
522
+ if (typeof input.permission_mode === "string")
523
+ s.mode = input.permission_mode;
457
524
  const runId = typeof input.prompt_id === "string" ? input.prompt_id : s.run;
458
525
  switch (event) {
459
526
  case "SessionStart":
@@ -587,7 +654,7 @@ export class ClaudeCodeHarness {
587
654
  open = (await this.liveSession()) ?? this.current();
588
655
  if (open?.inbox) {
589
656
  this.remember(m.id);
590
- if (await inboxSend(open.inbox, text, { priority: "next", msgId: m.id }))
657
+ if (await inboxSend(open.inbox, text, { priority: "next", msgId: m.id, bypass: this.bypasses(open) }))
591
658
  return { outcome: "delivered" };
592
659
  open.open = false;
593
660
  open.inbox = null;
@@ -676,13 +743,13 @@ export class ClaudeCodeHarness {
676
743
  const open = this.current();
677
744
  if (!open?.inbox || (open.state !== "working" && open.state !== "waiting"))
678
745
  return "over";
679
- const sent = await inboxSend(open.inbox, `${this.ctx.person} pressed Stop in Gavel: stop what you're doing, say in a line where you stopped, and wait for them.`, { priority: "now" });
746
+ const sent = await inboxSend(open.inbox, `${this.ctx.person} pressed Stop in Gavel: stop what you're doing, say in a line where you stopped, and wait for them.`, { priority: "now", bypass: this.bypasses(open) });
680
747
  return sent ? "stopped" : "over";
681
748
  }
682
749
  // Gavel's one-line wake (D-1103), into an open session: mid-turn or as a turn of its own.
683
750
  async wake(line) {
684
751
  const open = this.current();
685
- return open?.inbox ? inboxSend(open.inbox, line, { priority: "next" }) : false;
752
+ return open?.inbox ? inboxSend(open.inbox, line, { priority: "next", bypass: this.bypasses(open) }) : false;
686
753
  }
687
754
  listen(l) {
688
755
  this.listener = l;
package/dist/gavel.js CHANGED
@@ -10,7 +10,7 @@ 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, gavelPluginOn } from "./bridge/claude-live.js";
13
+ import { claudeBridgeHooks, claudeHeld, gavelPluginOn } from "./bridge/claude-live.js";
14
14
  import { codexBridgeHooks } from "./bridge/codex.js";
15
15
  import { claudeSetups } from "./bridge/setup.js";
16
16
  import { BRIDGE_HARNESSES, runBridge } from "./bridge/bridge.js";
@@ -1736,17 +1736,26 @@ async function background(run) {
1736
1736
  return hookEvent({ home, cwd, harness, server: run.server, name: run.name, env });
1737
1737
  case "start": {
1738
1738
  const started = await startBridge({ home, cwd, harness, server: run.server, untilClosed: false, env });
1739
- print(started.bridge === "failed" ? { ...started, reason: lastLine(started.log) } : started);
1740
- return started.bridge === "failed" ? 1 : 0;
1739
+ if (started.bridge !== "failed") {
1740
+ print(started);
1741
+ return 0;
1742
+ }
1743
+ const reason = lastLine(started.log);
1744
+ print({ ...started, reason });
1745
+ // On stderr too, so a failed start always says why (W-244).
1746
+ console.error(`gavel bridge: it didn't start${reason ? `: ${reason}` : ""} (its log: ${started.log}).`);
1747
+ return 1;
1741
1748
  }
1742
1749
  case "stop": {
1743
1750
  const stopped = await stopBridge({ home, cwd, harness });
1744
1751
  print(stopped);
1745
1752
  return stopped.bridge === "still running" ? 1 : 0;
1746
1753
  }
1747
- case "status":
1748
- print(bridgeStatus({ home, cwd, harness }));
1754
+ case "status": {
1755
+ const held = harness === "claude-code" ? claudeHeld(cwd, home, env) : null;
1756
+ print({ ...bridgeStatus({ home, cwd, harness }), ...(held ? { held } : {}) });
1749
1757
  return 0;
1758
+ }
1750
1759
  case "service": {
1751
1760
  const answer = bridgeService(run.service, { home, cwd, harness, server: run.server, env });
1752
1761
  print(answer);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.24",
3
+ "version": "0.1.25",
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",