@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,625 @@
1
+ import { execFile, execFileSync, spawn } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync } from "node:fs";
4
+ import { createServer } from "node:http";
5
+ import { connect } from "node:net";
6
+ import { tmpdir } from "node:os";
7
+ import { extname, join } from "node:path";
8
+ import { promisify } from "node:util";
9
+ import { bridgePaths } from "./background.js";
10
+ import { claudeSessions, claudeWords } from "./claude-code.js";
11
+ import { claudeSetups } from "./setup.js";
12
+ // Claude Code live (W-132): what a session tells the bridge through its hooks, and how the bridge
13
+ // reaches it. Relied on, from Claude Code's docs and its 2.1.332 binary:
14
+ // - Each session (2.1.224 and later) binds an inbox socket for messages from other sessions and
15
+ // gives every hook its path and the session's key (CLAUDE_CODE_MESSAGING_SOCKET, _TOKEN). A line
16
+ // {"type":"user","message":{"role":"user","content":"…"},"priority":"next","msg_id":"…"} after
17
+ // {"type":"auth","token":"…"} reaches it: "next" between tool calls mid-turn or as a new turn when
18
+ // idle, "now" interrupting the turn. Content is a string only. The transcript keeps it as a user
19
+ // line with isMeta and origin {kind: "peer", msg_id}, framed for Claude as another session's.
20
+ // The socket takes a line from the same user without the key too: a session the bridge knows
21
+ // only from `claude agents --json` (its pid) is reached at its usual address.
22
+ // - Hooks fire as they happen and settings reload while a session runs: UserPromptSubmit,
23
+ // MessageDisplay (the agent's text as it's shown, whole lines, 2.1.152), PermissionRequest,
24
+ // PostToolUse, Stop, StopFailure and SessionEnd.
25
+ export const BRIDGE_MIN_VERSION = [2, 1, 224];
26
+ // One message into a session's inbox; true once Claude Code took the line.
27
+ export function inboxSend(inbox, text, opts) {
28
+ return new Promise((resolve) => {
29
+ const lines = [
30
+ ...(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 } : {}) }),
32
+ ];
33
+ const conn = connect(inbox.socket, () => conn.end(`${lines.join("\n")}\n`));
34
+ conn.setTimeout(5_000, () => conn.destroy(new Error("timeout")));
35
+ conn.on("close", (hadError) => resolve(!hadError));
36
+ conn.on("error", () => resolve(false));
37
+ });
38
+ }
39
+ export function claudeVersion(text) {
40
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(text);
41
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
42
+ }
43
+ export const atLeast = (version, min) => {
44
+ if (!version)
45
+ return false;
46
+ for (let i = 0; i < min.length; i++)
47
+ if ((version[i] ?? 0) !== min[i])
48
+ return (version[i] ?? 0) > min[i];
49
+ return true;
50
+ };
51
+ // ---------- the bridge's hooks in Claude Code's settings ----------
52
+ // Each hook hands its event to the folder's bridge (`gavel bridge event`), in the background
53
+ // (async), so the session never waits on it; SessionEnd waits a moment, since nothing runs after it.
54
+ export const BRIDGE_HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PermissionRequest", "PostToolUse", "Stop", "StopFailure", "SessionEnd"];
55
+ const DISPLAY_PATH = "/gavel-bridge/";
56
+ // Gavel's wake hook from a bridge before 0.1.17 (`gavel bridge wake`) counts as the bridge's too, so
57
+ // it goes when these go in.
58
+ const isBridgeHook = (h) => (Array.isArray(h.args) && h.args.includes("bridge") && h.args.includes("event")) ||
59
+ (typeof h.url === "string" && h.url.startsWith("http://127.0.0.1:") && h.url.includes(DISPLAY_PATH)) ||
60
+ (typeof h.command === "string" && /\bbridge wake( |$)/.test(h.command));
61
+ // The settings with the bridge's hooks in (its command and the display hook's address) or out
62
+ // (null), every other hook and setting kept; null when nothing changes.
63
+ export function withBridgeHooks(existing, command, displayUrl) {
64
+ let settings = {};
65
+ if (existing?.trim()) {
66
+ try {
67
+ settings = JSON.parse(existing);
68
+ }
69
+ catch {
70
+ throw new Error("Claude Code's settings file isn't plain JSON, so the bridge's hooks can't go in it");
71
+ }
72
+ }
73
+ const hooks = {};
74
+ for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
75
+ const kept = (groups ?? []).map((g) => ({ ...g, hooks: (g.hooks ?? []).filter((h) => !isBridgeHook(h)) })).filter((g) => g.hooks.length);
76
+ if (kept.length)
77
+ hooks[event] = kept;
78
+ }
79
+ if (command) {
80
+ const [exe, ...rest] = command;
81
+ for (const event of BRIDGE_HOOK_EVENTS) {
82
+ const hook = { type: "command", command: exe, args: [...rest, "bridge", "event", event, "--harness", "claude-code"], ...(event === "SessionEnd" ? { timeout: 5 } : { async: true }) };
83
+ hooks[event] = [...(hooks[event] ?? []), { hooks: [hook] }];
84
+ }
85
+ }
86
+ if (displayUrl)
87
+ hooks.MessageDisplay = [...(hooks.MessageDisplay ?? []), { hooks: [{ type: "http", url: displayUrl, timeout: 2 }] }];
88
+ const { hooks: _old, ...rest } = settings;
89
+ const next = Object.keys(hooks).length ? { ...rest, hooks } : rest;
90
+ const text = `${JSON.stringify(next, null, 2)}\n`;
91
+ return text === existing ? null : text;
92
+ }
93
+ // The display hook's address for this folder: a port and a secret path kept beside the bridge's
94
+ // lock (mode 600), the same each time, so the settings name it once.
95
+ export function displayHook(home, cwd) {
96
+ const paths = bridgePaths(home, cwd, "claude-code");
97
+ const file = join(paths.dir, `${paths.key}.display.json`);
98
+ let kept = {};
99
+ try {
100
+ kept = JSON.parse(readFileSync(file, "utf8"));
101
+ }
102
+ catch {
103
+ // made below
104
+ }
105
+ const port = typeof kept.port === "number" ? kept.port : 20_000 + Math.floor(Math.random() * 40_000);
106
+ const secret = typeof kept.secret === "string" && /^[0-9a-f]{32}$/.test(kept.secret) ? kept.secret : randomBytes(16).toString("hex");
107
+ if (kept.port !== port || kept.secret !== secret) {
108
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
109
+ writeFileSync(file, `${JSON.stringify({ port, secret })}\n`, { mode: 0o600 });
110
+ }
111
+ return { port, secret, url: `http://127.0.0.1:${port}${DISPLAY_PATH}${secret}`, file };
112
+ }
113
+ const gitIn = (args, cwd) => {
114
+ try {
115
+ execFileSync("git", args, { cwd, stdio: "ignore" });
116
+ return true;
117
+ }
118
+ catch {
119
+ return false;
120
+ }
121
+ };
122
+ // Whether Gavel's plugin (D-1139) is on for this user: it carries the bridge's hooks and the
123
+ // end-of-turn hook itself, for every folder.
124
+ export function gavelPluginOn(home) {
125
+ try {
126
+ const enabled = JSON.parse(readFileSync(join(home, ".claude", "settings.json"), "utf8")).enabledPlugins ?? {};
127
+ return Object.entries(enabled).some(([id, on]) => on === true && id.startsWith("gavel@"));
128
+ }
129
+ catch {
130
+ return false;
131
+ }
132
+ }
133
+ // `gavel bridge hooks install|remove|status` (and `gavel pair --bridge true`): the bridge's hooks in
134
+ // this folder's local Claude Code settings, beside the agent's own setup that pairing wrote there,
135
+ // in a file git ignores (its .gitignore line added), never one git tracks.
136
+ export async function claudeBridgeHooks(action, opts) {
137
+ const file = join(opts.cwd, ".claude", "settings.local.json");
138
+ const name = ".claude/settings.local.json";
139
+ const existing = existsSync(file) ? readFileSync(file, "utf8") : null;
140
+ const installed = () => {
141
+ try {
142
+ const hooks = JSON.parse(existing ?? "{}").hooks ?? {};
143
+ return Object.values(hooks).some((groups) => (groups ?? []).some((g) => (g.hooks ?? []).some(isBridgeHook)));
144
+ }
145
+ catch {
146
+ return false;
147
+ }
148
+ };
149
+ if (action === "status")
150
+ return { hooks: installed() ? "installed" : "not installed", file: name };
151
+ if (action === "remove") {
152
+ const next = withBridgeHooks(existing, null, null);
153
+ if (next === null || !installed())
154
+ return { hooks: "not installed", file: name };
155
+ writeWhole(file, next);
156
+ return { hooks: "removed", file: name };
157
+ }
158
+ if (!claudeSetups(opts.cwd, opts.home).some((s) => s.where.endsWith("this folder")))
159
+ return { hooks: "refused", file: name, reason: "No Gavel agent is set up for Claude Code in this folder: pair it here first (gavel pair <code>). The bridge's hooks are for an agent's own folder." };
160
+ let version = null;
161
+ try {
162
+ version = claudeVersion((await promisify(execFile)("claude", ["--version"], { cwd: opts.cwd, timeout: 15_000 })).stdout);
163
+ }
164
+ catch {
165
+ return { hooks: "refused", file: name, reason: "Claude Code's claude command doesn't run here: install it, or run this where it runs." };
166
+ }
167
+ if (!atLeast(version, BRIDGE_MIN_VERSION))
168
+ return { hooks: "refused", file: name, reason: `This Claude Code (${version?.join(".") ?? "unknown"}) is older than the bridge's hooks need (${BRIDGE_MIN_VERSION.join(".")}): run claude update, then gavel bridge hooks install.` };
169
+ if (gitIn(["ls-files", "--error-unmatch", name], opts.cwd))
170
+ return { hooks: "refused", file: name, reason: `git tracks ${name}, and the bridge's hooks must stay out of commits: untrack it first.` };
171
+ // With Gavel's plugin on, it runs the bridge's hooks: this folder gets only its own address for
172
+ // the agent's words as they're shown.
173
+ const plugin = gavelPluginOn(opts.home);
174
+ const next = withBridgeHooks(existing, plugin ? null : opts.command, displayHook(opts.home, opts.cwd).url);
175
+ if (next !== null)
176
+ writeWhole(file, next);
177
+ const done = [
178
+ plugin
179
+ ? `Gavel's plugin runs the bridge's hooks here; wrote this folder's hook for the words as they're shown into ${name}`
180
+ : `wrote the bridge's hooks into ${name}: a Claude Code session here starts Gavel's bridge as it starts (and stops it a while after the last one ends), so your person's chat in Gavel reaches it at once, with no terminal open`,
181
+ ];
182
+ if (gitIn(["rev-parse", "--is-inside-work-tree"], opts.cwd) && !gitIn(["check-ignore", "-q", name], opts.cwd)) {
183
+ const gitignore = join(opts.cwd, ".gitignore");
184
+ const text = existsSync(gitignore) ? readFileSync(gitignore, "utf8") : "";
185
+ writeFileSync(gitignore, `${text}${text && !text.endsWith("\n") ? "\n" : ""}${name}\n`);
186
+ done.push(`.gitignore has ${name}`);
187
+ }
188
+ return { hooks: "installed", file: name, done };
189
+ }
190
+ function writeWhole(file, text) {
191
+ mkdirSync(join(file, ".."), { recursive: true });
192
+ const temp = `${file}.${process.pid}.tmp`;
193
+ writeFileSync(temp, text);
194
+ renameSync(temp, file);
195
+ }
196
+ // ---------- the session's words, with Gavel's own messages joined ----------
197
+ const PEER_HEADER = /^Another Claude session sent a message(?: while you were working)?:\n/;
198
+ const PEER_FOOTER = "\n\nThis came from another Claude session";
199
+ const GAVEL_HEADER = /^[^\n]{1,200} wrote to you in Gavel \(they read your answer there, so answer here as you would to them\):\n\n/;
200
+ const PICTURES_FOOTER = /\n\nThe pictures? they sent with it, on this laptop \(open each with Read\):\n[\s\S]*$/;
201
+ // The person's own words in what the bridge put in: without the line saying who wrote, or where
202
+ // their pictures are.
203
+ const theirWords = (text) => text.replace(GAVEL_HEADER, "").replace(PICTURES_FOOTER, "").trim();
204
+ // What joins a resumed run's prompt (a plain user line in the transcript) to its Gavel message.
205
+ export const promptKey = (prompt) => createHash("sha256").update(prompt.trim()).digest("hex").slice(0, 32);
206
+ // A session's words for Gavel: claudeWords' (D-894's filter), plus the session's copy of each
207
+ // message the bridge put in from Gavel, joined to it: through the inbox by its id (msg_id), as a
208
+ // resumed run's prompt by promptKey. Another session's message, and Gavel's own wakes, never show.
209
+ export function sessionWords(jsonl, fromGavel, prompts = new Map()) {
210
+ const words = claudeWords(jsonl).map((w) => {
211
+ if (w.side !== "person" || !GAVEL_HEADER.test(w.text))
212
+ return w;
213
+ const gavelId = prompts.get(promptKey(w.text));
214
+ return { ...w, text: theirWords(w.text) || "(message)", ...(gavelId ? { gavelId } : {}) };
215
+ });
216
+ for (const raw of jsonl.split("\n")) {
217
+ if (!raw.includes('"peer"'))
218
+ continue;
219
+ let line;
220
+ try {
221
+ line = JSON.parse(raw);
222
+ }
223
+ catch {
224
+ continue;
225
+ }
226
+ const id = line.origin?.msg_id;
227
+ if (line.type !== "user" || line.origin?.kind !== "peer" || typeof id !== "string" || !fromGavel.has(id) || !line.uuid || !line.timestamp)
228
+ continue;
229
+ const content = typeof line.message?.content === "string" ? line.message.content : "";
230
+ const body = content.replace(PEER_HEADER, "");
231
+ const end = body.indexOf(PEER_FOOTER);
232
+ const text = theirWords(end >= 0 ? body.slice(0, end) : body);
233
+ words.push({ id: line.uuid, side: "person", text: text || "(message)", at: line.timestamp, gavelId: id });
234
+ }
235
+ return words.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
236
+ }
237
+ const PICTURES_HOURS = 1;
238
+ export class ClaudeCodeHarness {
239
+ ctx;
240
+ name = "Claude Code";
241
+ sessions = new Map();
242
+ // Each Gavel message the bridge put in, with its prompt's key when a resumed run took it.
243
+ known = new Map();
244
+ idsFile;
245
+ pictureDir;
246
+ listener = null;
247
+ watcher = null;
248
+ watching = null;
249
+ display = null;
250
+ resumed = null;
251
+ lastState = null;
252
+ changedTimer = null;
253
+ // The person's name, for the words that say who wrote: the core learns it after it builds the
254
+ // harness, from GET /v1/me.
255
+ setPerson(name) {
256
+ this.ctx.person = name;
257
+ }
258
+ constructor(ctx) {
259
+ this.ctx = ctx;
260
+ const paths = bridgePaths(ctx.home, ctx.cwd, "claude-code");
261
+ this.idsFile = join(paths.dir, `${paths.key}.gavel-ids`);
262
+ this.pictureDir = join(paths.dir, `${paths.key}.pictures`);
263
+ let lines = [];
264
+ try {
265
+ lines = readFileSync(this.idsFile, "utf8").split("\n");
266
+ }
267
+ catch {
268
+ // none yet
269
+ }
270
+ for (const l of lines.slice(-500)) {
271
+ const m = /^([0-9a-f-]{36})(?: ([0-9a-f]{32}))?$/i.exec(l);
272
+ if (m)
273
+ this.known.set(m[1], m[2] ?? null);
274
+ }
275
+ }
276
+ remember(id, key = null) {
277
+ this.known.delete(id);
278
+ this.known.set(id, key);
279
+ const lines = [...this.known].slice(-500).map(([i, k]) => (k ? `${i} ${k}` : i));
280
+ const temp = `${this.idsFile}.${process.pid}.tmp`;
281
+ writeFileSync(temp, `${lines.join("\n")}\n`, { mode: 0o600 });
282
+ renameSync(temp, this.idsFile);
283
+ }
284
+ // The session Gavel shows and writes to: the newest one open, else the folder's newest.
285
+ current() {
286
+ const open = [...this.sessions.values()].filter((s) => s.open).sort((a, b) => b.seen - a.seen);
287
+ return open[0] ?? null;
288
+ }
289
+ setState(next) {
290
+ if (next === this.lastState)
291
+ return;
292
+ this.lastState = next;
293
+ this.listener?.state(next);
294
+ }
295
+ stateNow() {
296
+ this.setState(this.current()?.state ?? "closed");
297
+ }
298
+ soon() {
299
+ if (this.changedTimer)
300
+ return;
301
+ this.changedTimer = setTimeout(() => {
302
+ this.changedTimer = null;
303
+ this.listener?.changed();
304
+ }, 50);
305
+ }
306
+ follow(file) {
307
+ if (file === this.watching)
308
+ return;
309
+ this.watcher?.close();
310
+ this.watcher = null;
311
+ this.watching = file;
312
+ if (!file || !existsSync(file))
313
+ return;
314
+ try {
315
+ this.watcher = watch(file, () => this.soon());
316
+ }
317
+ catch {
318
+ // the core reads every 2 s anyway
319
+ }
320
+ }
321
+ session(id) {
322
+ let s = this.sessions.get(id);
323
+ if (!s) {
324
+ s = { id, inbox: null, transcript: null, open: true, state: "idle", seen: Date.now(), run: null, spoken: new Map() };
325
+ this.sessions.set(id, s);
326
+ }
327
+ return s;
328
+ }
329
+ // The hooks' events, in the order the session sent them (background.ts's HookEvent).
330
+ hook(event, given) {
331
+ const e = given;
332
+ const input = e?.input;
333
+ if (!input || typeof input !== "object")
334
+ return;
335
+ const id = typeof input.session_id === "string" ? input.session_id : null;
336
+ if (!id || typeof input.agent_id === "string")
337
+ return;
338
+ const s = this.session(id);
339
+ s.seen = Date.now();
340
+ if (e.inbox)
341
+ s.inbox = e.inbox;
342
+ if (typeof input.transcript_path === "string")
343
+ s.transcript = input.transcript_path;
344
+ const runId = typeof input.prompt_id === "string" ? input.prompt_id : s.run;
345
+ switch (event) {
346
+ case "SessionStart":
347
+ s.open = true;
348
+ s.state = "idle";
349
+ break;
350
+ case "UserPromptSubmit":
351
+ s.open = true;
352
+ s.state = "working";
353
+ if (runId && runId !== s.run) {
354
+ s.run = runId;
355
+ s.spoken.clear();
356
+ this.listener?.live({ event: "run", runId });
357
+ }
358
+ break;
359
+ case "MessageDisplay": {
360
+ const message = typeof input.message_id === "string" ? input.message_id : null;
361
+ const delta = typeof input.delta === "string" ? input.delta : "";
362
+ if (!message || !runId)
363
+ break;
364
+ if (runId !== s.run) {
365
+ s.run = runId;
366
+ s.spoken.clear();
367
+ this.listener?.live({ event: "run", runId });
368
+ }
369
+ const at = s.spoken.get(message) ?? 0;
370
+ if (delta)
371
+ this.listener?.live({ event: "words", runId, id: message, at, text: delta });
372
+ s.spoken.set(message, at + delta.length);
373
+ s.state = "working";
374
+ break;
375
+ }
376
+ case "PermissionRequest":
377
+ s.state = "waiting";
378
+ break;
379
+ case "PostToolUse":
380
+ s.state = "working";
381
+ break;
382
+ case "Stop":
383
+ case "StopFailure": {
384
+ s.state = "idle";
385
+ const run = s.run;
386
+ s.run = null;
387
+ const last = typeof input.last_assistant_message === "string" ? input.last_assistant_message.trim() : "";
388
+ if (run)
389
+ void this.endOnceKept(s, run, event === "Stop" ? last : "");
390
+ break;
391
+ }
392
+ case "SessionEnd":
393
+ s.open = false;
394
+ s.state = "closed";
395
+ s.inbox = null;
396
+ break;
397
+ }
398
+ this.follow(this.current()?.transcript ?? null);
399
+ this.soon();
400
+ this.stateNow();
401
+ }
402
+ // A turn's end goes once the transcript has its last words (Claude Code writes the file a moment
403
+ // after the Stop hook), so the core's push before it keeps them (Reach's rule for `end`).
404
+ async endOnceKept(s, run, last) {
405
+ const deadline = Date.now() + 3_000;
406
+ while (last && s.transcript && Date.now() < deadline) {
407
+ try {
408
+ if (readFileSync(s.transcript, "utf8").includes(JSON.stringify(last).slice(1, 60)))
409
+ break;
410
+ }
411
+ catch {
412
+ break;
413
+ }
414
+ await new Promise((r) => setTimeout(r, 100));
415
+ }
416
+ this.listener?.changed();
417
+ this.listener?.live({ event: "end", runId: run });
418
+ }
419
+ async newest() {
420
+ const open = this.current();
421
+ const file = open?.transcript && existsSync(open.transcript) ? open.transcript : (claudeSessions(this.ctx.cwd, this.ctx.home, this.ctx.env)[0]?.file ?? null);
422
+ if (!file)
423
+ return null;
424
+ const session = /([0-9a-f-]{36})\.jsonl$/i.exec(file)?.[1] ?? file;
425
+ this.follow(file);
426
+ const prompts = new Map();
427
+ for (const [id, key] of this.known)
428
+ if (key)
429
+ prompts.set(key, id);
430
+ return { thread: `claude-code:${session}`, label: this.ctx.label, session, messages: sessionWords(readFileSync(file, "utf8"), new Set(this.known.keys()), prompts) };
431
+ }
432
+ prompt(m, pictures) {
433
+ const words = m.decision ? `About ${m.decision.ref}: ${m.decision.question}\n\n${m.text}` : m.text;
434
+ const shown = pictures.length ? `\n\nThe ${pictures.length === 1 ? "picture" : "pictures"} they sent with it, on this laptop (open each with Read):\n${pictures.join("\n")}` : "";
435
+ return `${this.ctx.person} wrote to you in Gavel (they read your answer there, so answer here as you would to them):\n\n${words}${shown}`;
436
+ }
437
+ // A message's pictures, kept where the session can open them for an hour (the core's own copies go
438
+ // once delivered).
439
+ keepPictures(m) {
440
+ if (!m.pictures.length)
441
+ return [];
442
+ mkdirSync(this.pictureDir, { recursive: true, mode: 0o700 });
443
+ const cutoff = Date.now() - PICTURES_HOURS * 3_600_000;
444
+ for (const name of readdirSync(this.pictureDir)) {
445
+ const file = join(this.pictureDir, name);
446
+ try {
447
+ if (statSync(file).mtimeMs < cutoff)
448
+ unlinkSync(file);
449
+ }
450
+ catch {
451
+ // gone already
452
+ }
453
+ }
454
+ return m.pictures.map((from, i) => {
455
+ const to = join(this.pictureDir, `${m.id}-${i + 1}${extname(from) || ".png"}`);
456
+ copyFileSync(from, to);
457
+ return to;
458
+ });
459
+ }
460
+ async deliver(m) {
461
+ const pictures = this.keepPictures(m);
462
+ const text = this.prompt(m, pictures);
463
+ let open = this.current();
464
+ if (!open?.inbox)
465
+ open = (await this.liveSession()) ?? this.current();
466
+ if (open?.inbox) {
467
+ this.remember(m.id);
468
+ if (await inboxSend(open.inbox, text, { priority: "next", msgId: m.id }))
469
+ return { outcome: "delivered" };
470
+ open.open = false;
471
+ open.inbox = null;
472
+ this.stateNow();
473
+ }
474
+ if (open)
475
+ return { outcome: "left", say: `${this.ctx.person} wrote in Gavel; your Claude Code session here is open and the bridge can't reach it yet, so it goes in at the session's next step, or once it closes.` };
476
+ return this.resume(m, text);
477
+ }
478
+ // A closed session, resumed with the person's words as a turn of its own (D-905): nothing that
479
+ // would prompt runs. Delivered once the run starts; what it refused, or why it failed, comes after
480
+ // as the bridge's note.
481
+ resume(m, text) {
482
+ const newest = claudeSessions(this.ctx.cwd, this.ctx.home, this.ctx.env)[0] ?? null;
483
+ const args = ["-p", ...(newest ? ["--resume", newest.id] : []), "--permission-prompts", "none", "--output-format", "json"];
484
+ return new Promise((resolve) => {
485
+ const child = spawn("claude", args, { cwd: this.ctx.cwd, stdio: ["pipe", "pipe", "pipe"] });
486
+ this.resumed = child;
487
+ let out = "";
488
+ let err = "";
489
+ let settled = false;
490
+ const settle = (d) => {
491
+ if (!settled)
492
+ resolve(d);
493
+ settled = true;
494
+ };
495
+ child.stdout.on("data", (d) => (out += d));
496
+ child.stderr.on("data", (d) => (err += d));
497
+ child.on("spawn", () => {
498
+ this.remember(m.id, promptKey(text));
499
+ setTimeout(() => settle({ outcome: "delivered" }), 300).unref();
500
+ });
501
+ child.on("error", (e) => settle({ outcome: "failed", reason: e.code === "ENOENT" ? "Claude Code's claude command isn't on the laptop's PATH where the bridge runs." : `Claude Code didn't start: ${e.message}` }));
502
+ child.on("close", (code) => {
503
+ this.resumed = null;
504
+ let result = null;
505
+ try {
506
+ result = JSON.parse(out);
507
+ }
508
+ catch {
509
+ // its reason is on stderr
510
+ }
511
+ const first = (t) => t.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
512
+ if (code === 0 && result && !result.is_error) {
513
+ const refused = [...new Set((result.permission_denials ?? []).map((d) => d?.tool_name).filter((n) => typeof n === "string"))];
514
+ if (refused.length)
515
+ this.listener?.note(`Claude Code didn't do what it would have asked you about first (${refused.join(", ")}): nobody was at the laptop to allow it. Allow it in the session there, or answer here.`);
516
+ settle({ outcome: "delivered" });
517
+ }
518
+ else {
519
+ const said = (typeof result?.result === "string" ? first(result.result) : "") || first(err);
520
+ const reason = (/unknown option.*permission-prompts/i.test(err) ? "The laptop's Claude Code is too old for the bridge: run claude update there." : said ? `Claude Code said: ${said}` : `Claude Code stopped without answering (code ${code}).`).slice(0, 300);
521
+ if (settled)
522
+ this.listener?.note(reason);
523
+ settle({ outcome: "failed", reason });
524
+ }
525
+ this.listener?.changed();
526
+ });
527
+ child.stdin.end(text);
528
+ });
529
+ }
530
+ // The sessions open here, from Claude Code's own list (which settles what the hooks may have
531
+ // missed): the newest one's inbox at its usual address, without the session's key.
532
+ async liveSession() {
533
+ try {
534
+ const { stdout } = await promisify(execFile)("claude", ["agents", "--json"], { cwd: this.ctx.cwd, timeout: 15_000 });
535
+ const live = JSON.parse(stdout).filter((s) => s.cwd === this.ctx.cwd && typeof s.sessionId === "string" && typeof s.pid === "number");
536
+ for (const s of this.sessions.values())
537
+ if (s.open && !live.some((l) => l.sessionId === s.id)) {
538
+ s.open = false;
539
+ s.inbox = null;
540
+ s.state = "closed";
541
+ }
542
+ const newest = live.sort((a, b) => (Number(a.startedAt) || 0) - (Number(b.startedAt) || 0)).at(-1);
543
+ if (!newest) {
544
+ this.stateNow();
545
+ return null;
546
+ }
547
+ const socket = [join("/tmp", "cc-socks", `${newest.pid}.sock`), join(tmpdir(), "cc-socks", `${newest.pid}.sock`)].find((p) => existsSync(p)) ?? null;
548
+ const s = this.session(newest.sessionId);
549
+ s.open = true;
550
+ s.inbox = s.inbox ?? (socket ? { socket, token: null } : null);
551
+ s.state = newest.status === "busy" ? "working" : newest.status === "waiting" ? "waiting" : "idle";
552
+ this.stateNow();
553
+ return s;
554
+ }
555
+ catch {
556
+ return null;
557
+ }
558
+ }
559
+ // Stop in Gavel: the turn interrupted from its inbox (priority now), Claude then reading why; a
560
+ // resumed run is ended. Over when nothing runs.
561
+ async interrupt() {
562
+ if (this.resumed) {
563
+ this.resumed.kill("SIGINT");
564
+ return "stopped";
565
+ }
566
+ const open = this.current();
567
+ if (!open?.inbox || (open.state !== "working" && open.state !== "waiting"))
568
+ return "over";
569
+ 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" });
570
+ return sent ? "stopped" : "over";
571
+ }
572
+ // Gavel's one-line wake (D-1103), into an open session: mid-turn or as a turn of its own.
573
+ async wake(line) {
574
+ const open = this.current();
575
+ return open?.inbox ? inboxSend(open.inbox, line, { priority: "next" }) : false;
576
+ }
577
+ listen(l) {
578
+ this.listener = l;
579
+ this.stateNow();
580
+ void this.liveSession().then(() => this.stateNow());
581
+ const hook = displayHook(this.ctx.home, this.ctx.cwd);
582
+ this.display = createServer((req, res) => {
583
+ let raw = "";
584
+ req.on("data", (c) => {
585
+ raw += c;
586
+ if (raw.length > 1_000_000)
587
+ req.destroy();
588
+ });
589
+ req.on("end", () => {
590
+ res.writeHead(200).end();
591
+ if (req.method !== "POST" || req.url !== `${DISPLAY_PATH}${hook.secret}`)
592
+ return;
593
+ try {
594
+ const input = JSON.parse(raw);
595
+ if (input.hook_event_name === "MessageDisplay")
596
+ this.hook("MessageDisplay", { event: "MessageDisplay", input, inbox: null, at: Date.now() });
597
+ }
598
+ catch {
599
+ // not Claude Code's
600
+ }
601
+ });
602
+ });
603
+ this.display.on("error", () => {
604
+ this.display = null;
605
+ });
606
+ this.display.listen(hook.port, "127.0.0.1");
607
+ this.display.unref();
608
+ }
609
+ // The chat off in Gavel (D-1140): what the bridge kept on the laptop for it goes too, its copies
610
+ // of the person's pictures and the ids it joins by. The hooks stay: they start no bridge while
611
+ // the chat is off (`markChatOff`).
612
+ setChat(on) {
613
+ if (on)
614
+ return;
615
+ rmSync(this.pictureDir, { recursive: true, force: true });
616
+ rmSync(this.idsFile, { force: true });
617
+ this.known.clear();
618
+ }
619
+ async close() {
620
+ this.watcher?.close();
621
+ this.display?.close();
622
+ if (this.changedTimer)
623
+ clearTimeout(this.changedTimer);
624
+ }
625
+ }