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