@getgavel/cli 0.1.16 → 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.
@@ -1,11 +1,12 @@
1
- import { execFileSync } from "node:child_process";
2
1
  import { randomUUID } from "node:crypto";
3
- import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
3
  import { tmpdir } from "node:os";
5
- import { basename, dirname, join, relative } from "node:path";
4
+ import { basename, join } from "node:path";
6
5
  import { jsonText } from "../output.js";
7
- import { claudeOpen, claudeResume, claudeSessions, claudeSettingsFile, claudeWords, withWakeHook } from "./claude-code.js";
8
- import { codexOpen, codexQueue, codexResume, codexSessions, codexWords } from "./codex.js";
6
+ import { markChatOff, onHookEvent } from "./background.js";
7
+ import { claudeSessions } from "./claude-code.js";
8
+ import { ClaudeCodeHarness } from "./claude-live.js";
9
+ import { codexHarness, codexSessions } from "./codex.js";
9
10
  import { apiFor, claudeSetups, codexSetups } from "./setup.js";
10
11
  // `gavel bridge` (D-905): run by a person on their laptop, in the folder where their agent works
11
12
  // (Claude Code or Codex), beside it. It shows the newest session's words in the person's Gavel chat
@@ -18,14 +19,11 @@ const NAMES = { "claude-code": "Claude Code", codex: "Codex" };
18
19
  function sessionsHere(harness, ctx) {
19
20
  return harness === "claude-code" ? claudeSessions(ctx.cwd, ctx.home, ctx.env) : codexSessions(ctx.cwd, ctx.home, ctx.env);
20
21
  }
21
- // The newest session here, as the bridge sends it: one thread per session.
22
- function newestThread(harness, ctx) {
23
- const newest = sessionsHere(harness, ctx)[0];
24
- if (!newest)
25
- return null;
26
- const jsonl = readFileSync(newest.file, "utf8");
27
- const messages = harness === "claude-code" ? claudeWords(jsonl) : codexWords(jsonl);
28
- return { thread: `${harness}:${newest.id}`, label: `${NAMES[harness]} · ${basename(ctx.cwd)}`.slice(0, 80), session: newest.id, file: newest.file, messages };
22
+ // Each harness the bridge's Gavel side drives through harness.ts.
23
+ function harnessOf(harness, ctx) {
24
+ if (harness === "codex")
25
+ return codexHarness(ctx);
26
+ return new ClaudeCodeHarness({ cwd: ctx.cwd, home: ctx.home, env: ctx.env, person: "Your person", label: `${NAMES[harness]} · ${basename(ctx.cwd)}`.slice(0, 80) });
29
27
  }
30
28
  const localSetups = (setups) => setups.filter((s) => s.where.endsWith("this folder"));
31
29
  // Which software's agent works here: the one set up or with sessions in this folder.
@@ -56,8 +54,8 @@ function setupHere(harness, server, ctx) {
56
54
  return local[0];
57
55
  throw new BridgeError(`More than one Gavel server is set up for ${NAMES[harness]} here (${setups.map((s) => s.server).join(", ")}): say which with --server.`);
58
56
  }
59
- function call(api, method, path, body) {
60
- const headers = { authorization: `Bearer ${api.token}`, accept: "application/json" };
57
+ function call(api, method, path, body, extra = {}) {
58
+ const headers = { authorization: `Bearer ${api.token}`, accept: "application/json", ...extra };
61
59
  if (api.as?.trim())
62
60
  headers["x-gavel-agent"] = encodeURIComponent(api.as.trim());
63
61
  if (body !== undefined)
@@ -72,50 +70,25 @@ async function whoAmI(api, setup) {
72
70
  throw new BridgeError(`Gavel answered ${res.status} to who this agent is: try again in a moment.`);
73
71
  return (await res.json());
74
72
  }
75
- const asPrompt = (m) => (m.decision ? `About ${m.decision.ref}: ${m.decision.question}\n\n${m.text}` : m.text);
76
73
  const clock = () => new Date().toTimeString().slice(0, 5);
77
74
  const pause = (ms) => new Promise((r) => setTimeout(r, ms));
78
75
  const backoff = (failures) => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
79
- const quote = (word) => `'${word.replace(/'/g, `'\\''`)}'`;
80
- // The hook's command: this very gavel, by its own paths, so it needs nothing from npm or the PATH.
81
- function wakeCommand(server, as) {
82
- return [process.execPath, ...process.execArgv, process.argv[1]].map(quote).join(" ") + ` bridge wake --server ${quote(server)}${as ? ` --as ${quote(as)}` : ""}`;
83
- }
84
- function tracked(file, cwd) {
85
- try {
86
- execFileSync("git", ["ls-files", "--error-unmatch", file], { cwd, stdio: "ignore" });
87
- return true;
88
- }
89
- catch {
90
- return false;
91
- }
92
- }
93
- // Inside a git work tree, a file git doesn't already ignore gets its .gitignore line.
94
- function keepOutOfGit(file, cwd) {
76
+ // ---------- gavel bridge show ----------
77
+ async function show(run, ctx) {
78
+ const harness = harnessHere(run.harness, ctx);
79
+ const h = harnessOf(harness, ctx);
80
+ let shown;
95
81
  try {
96
- execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd, stdio: "ignore" });
97
- }
98
- catch {
99
- return null;
82
+ shown = await h.newest();
100
83
  }
101
- try {
102
- execFileSync("git", ["check-ignore", "-q", file], { cwd, stdio: "ignore" });
103
- return null;
84
+ catch (err) {
85
+ throw new BridgeError(err instanceof Error ? err.message : String(err));
104
86
  }
105
- catch {
106
- const gitignore = join(cwd, ".gitignore");
107
- const text = existsSync(gitignore) ? readFileSync(gitignore, "utf8") : "";
108
- appendFileSync(gitignore, `${text && !text.endsWith("\n") ? "\n" : ""}${file}\n`);
109
- return `.gitignore has ${file}`;
87
+ finally {
88
+ await h.close();
110
89
  }
111
- }
112
- // ---------- gavel bridge show ----------
113
- function show(run, ctx) {
114
- const harness = harnessHere(run.harness, ctx);
115
- const thread = newestThread(harness, ctx);
116
- if (!thread)
90
+ if (!shown)
117
91
  throw new BridgeError(`No ${NAMES[harness]} session in this folder yet.`);
118
- const { file: _file, ...shown } = thread;
119
92
  console.log(jsonText({ harness, folder: ctx.cwd, ...shown }));
120
93
  return 0;
121
94
  }
@@ -123,70 +96,78 @@ function show(run, ctx) {
123
96
  async function bridge(run, ctx) {
124
97
  const harness = harnessHere(run.harness, ctx);
125
98
  const setup = setupHere(harness, run.server, ctx);
99
+ return harnessBridge(harnessOf(harness, ctx), harness, setup, ctx);
100
+ }
101
+ const PICTURE_EXT = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp" };
102
+ const PICTURE_MAX = 15 * 1024 * 1024;
103
+ // A picture stays on the laptop this long after it went in, for the agent's software to read.
104
+ const PICTURE_KEEP_MS = 15 * 60_000;
105
+ // Live pieces go at most twice a second (the live route's own limit, 240 a minute an agent).
106
+ const LIVE_EVERY_MS = 500;
107
+ const LIVE_PIECE = 20_000;
108
+ const PUSH_EVERY_MS = 2000;
109
+ const WAKE_AGAIN_MS = 60_000;
110
+ // Gavel's one-line wake (D-1103, cloud-agents' wakePrompt): each ref once, what has none by its kind.
111
+ export const wakeLineOf = (items) => {
112
+ const named = [...new Set(items.map((i) => i.ref || i.kind))];
113
+ return `Gavel: ${named.length} waiting (${named.join(", ")}).`;
114
+ };
115
+ // Pieces of one bubble that follow each other go as one.
116
+ function joined(events) {
117
+ const out = [];
118
+ for (const e of events) {
119
+ const last = out[out.length - 1];
120
+ if (e.event === "words" && last?.event === "words" && last.runId === e.runId && last.id === e.id && last.at + last.text.length === e.at && last.text.length + e.text.length <= LIVE_PIECE)
121
+ out[out.length - 1] = { ...last, text: last.text + e.text };
122
+ else
123
+ out.push(e);
124
+ }
125
+ return out;
126
+ }
127
+ const sentKey = (m) => `${m.text}\u0000${m.gavelId ?? ""}`;
128
+ // The Gavel side for a harness: the one peek (presence, the person's messages, Stop), their messages
129
+ // put in beside it with their pictures, the session's words kept (the transcript) and shown as written
130
+ // (live), its state, and wakes for what waits in Gavel.
131
+ async function harnessBridge(h, harness, setup, ctx) {
126
132
  const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
127
133
  const me = await whoAmI(api, setup);
134
+ if (h instanceof ClaudeCodeHarness)
135
+ h.setPerson(me.person.name);
128
136
  const say = (line) => console.log(`${clock()} ${line}`);
129
- say(`Gavel bridge for ${me.agent.name} (${NAMES[harness]}, ${setup.server}) in ${ctx.cwd}.`);
130
- say(`While ${me.person.name} keeps the chat on in Gavel, this folder's newest ${NAMES[harness]} session shows there, only its words, and what they write there goes into it. Ctrl-C stops it.`);
137
+ say(`Gavel bridge for ${me.agent.name} (${h.name}, ${setup.server}) in ${ctx.cwd}.`);
138
+ say(`While ${me.person.name} keeps the chat on in Gavel, this folder's newest ${h.name} session shows there as it's written, only its words, and what they write there goes into it. Ctrl-C stops it.`);
131
139
  const id = randomUUID();
132
140
  let on = null;
133
141
  let stopping = false;
134
142
  let thread = null;
135
- let seen = "";
136
- const sent = new Map(); // this thread's messages as Gavel has them
137
- const joins = new Map(); // a delivered prompt → its Gavel message, until its local copy shows
138
- const delivering = new Set();
143
+ let state = null;
144
+ let liveRoute = true;
145
+ let outgoing = [];
146
+ const sent = new Map();
139
147
  const handled = new Set();
140
- const left = new Set(); // waiting for the open session, said once each
141
- const settings = claudeSettingsFile(ctx.cwd);
142
- const settingsName = relative(ctx.cwd, settings);
143
- let hooked = false;
144
- const setHook = (want) => {
145
- if (want === hooked)
146
- return;
147
- const existing = existsSync(settings) ? readFileSync(settings, "utf8") : null;
148
- const next = withWakeHook(existing, want ? wakeCommand(setup.server, ctx.as) : null);
149
- hooked = want;
150
- if (next === existing || next === null)
151
- return;
152
- if (want && tracked(settingsName, ctx.cwd)) {
153
- hooked = false;
154
- say(`Left out Gavel's wake hook: git tracks ${settingsName}, and it must stay out of commits. An open session hears from ${me.person.name} between tasks only.`);
155
- return;
156
- }
157
- mkdirSync(dirname(settings), { recursive: true });
158
- // Claude Code reads it whenever it likes: it changes whole, through a temp file and a rename.
159
- const temp = `${settings}.${process.pid}.tmp`;
160
- writeFileSync(temp, next);
161
- renameSync(temp, settings);
162
- if (want) {
163
- const ignored = keepOutOfGit(settingsName, ctx.cwd);
164
- say(`Added Gavel's wake hook to ${settingsName}, so an open session hears from ${me.person.name} even while idle; it comes out when the chat is off or the bridge stops.${ignored ? ` (${ignored}.)` : ""}`);
165
- }
166
- else
167
- say(`Took Gavel's wake hook out of ${settingsName}.`);
148
+ const delivering = new Set();
149
+ const left = new Set();
150
+ const stops = new Set();
151
+ const pictures = mkdtempSync(join(tmpdir(), "gavel-pictures-"));
152
+ let trouble = "";
153
+ const complain = (what) => {
154
+ if (what !== trouble)
155
+ console.error(`gavel bridge: ${what}`);
156
+ trouble = what;
168
157
  };
169
158
  let syncing = null;
170
159
  const pushOnce = async () => {
171
- const t = newestThread(harness, ctx);
172
- if (!t || !on)
160
+ if (!on)
173
161
  return;
174
- const stat = statSync(t.file);
175
- const mark = `${t.thread}:${stat.size}:${stat.mtimeMs}:${joins.size}`;
176
- if (mark === seen)
162
+ const t = await h.newest();
163
+ trouble = "";
164
+ if (!t || !on)
177
165
  return;
178
166
  if (t.thread !== thread) {
179
167
  thread = t.thread;
180
168
  sent.clear();
181
169
  }
182
- const messages = t.messages
183
- .filter((m) => sent.get(m.id) !== m.text)
184
- .map((m) => {
185
- const gavelId = m.side === "person" ? joins.get(m.text.trim()) : undefined;
186
- if (gavelId)
187
- joins.delete(m.text.trim());
188
- return gavelId ? { ...m, gavelId } : m;
189
- });
170
+ const messages = t.messages.filter((m) => sent.get(m.id) !== sentKey(m));
190
171
  for (let i = 0; i < messages.length; i += 200) {
191
172
  const part = messages.slice(i, i + 200);
192
173
  const res = await call(api, "PUT", "/v1/agents/me/chat/transcript", { thread: t.thread, label: t.label, messages: part });
@@ -195,86 +176,242 @@ async function bridge(run, ctx) {
195
176
  if (!(await res.json()).on)
196
177
  return;
197
178
  for (const m of part)
198
- sent.set(m.id, m.text);
179
+ sent.set(m.id, sentKey(m));
199
180
  }
200
- seen = mark;
201
181
  };
202
182
  const push = () => (syncing ??= pushOnce()
203
- .catch((err) => console.error(`gavel bridge: ${err instanceof Error ? err.message : String(err)}; trying again`))
183
+ .catch((err) => complain(`${err instanceof Error ? err.message : String(err)}; trying again`))
204
184
  .finally(() => (syncing = null)));
205
- const note = async (text) => {
185
+ // After whatever push is going: one that surely holds what changed before it was asked for.
186
+ const pushAfter = async () => {
187
+ await syncing;
206
188
  await push();
189
+ };
190
+ let soon = null;
191
+ const pushSoon = () => {
192
+ soon ??= setTimeout(() => {
193
+ soon = null;
194
+ void push();
195
+ }, 250);
196
+ };
197
+ const note = async (text) => {
198
+ await pushAfter();
207
199
  if (!thread)
208
200
  return;
209
201
  await call(api, "PUT", "/v1/agents/me/chat/transcript", { thread, messages: [{ id: `gavel:${randomUUID()}`, side: "gavel", text, at: new Date().toISOString() }] }).catch(() => undefined);
210
202
  };
203
+ // Live: the words as they're written and the state, relayed to the person's open chat, never kept.
204
+ // A turn's end goes only once its words are kept.
205
+ let posting = null;
206
+ const postLive = async () => {
207
+ if (!outgoing.length)
208
+ return;
209
+ if (!on || !liveRoute) {
210
+ outgoing = [];
211
+ return;
212
+ }
213
+ const events = joined(outgoing.splice(0));
214
+ if (events.some((e) => e.event === "end"))
215
+ await pushAfter();
216
+ for (let i = 0; i < events.length; i += 200) {
217
+ const res = await call(api, "POST", `/v1/agents/me/chat/live?bridge=${id}`, { ...(thread ? { thread } : {}), events: events.slice(i, i + 200) });
218
+ void res.body?.cancel();
219
+ if (res.status === 404)
220
+ liveRoute = false; // this Gavel has no live words yet: the transcript shows them
221
+ if (!res.ok)
222
+ return;
223
+ }
224
+ };
225
+ const liveTimer = setInterval(() => {
226
+ posting ??= postLive()
227
+ .catch(() => undefined)
228
+ .finally(() => (posting = null));
229
+ }, LIVE_EVERY_MS);
230
+ const pushTimer = setInterval(() => void push(), PUSH_EVERY_MS);
211
231
  const read = (body) => call(api, "POST", "/v1/agents/me/chat/read", body).then((res) => res.ok || console.error(`gavel bridge: HTTP ${res.status} marking a message read`), (err) => console.error(`gavel bridge: ${err instanceof Error ? err.message : String(err)} marking a message read`));
232
+ // A message's pictures, to private files on the laptop that its software reads (each an hour-long
233
+ // link Gavel gave); deleted a while after.
234
+ const fetchPictures = async (images) => {
235
+ const paths = [];
236
+ let missed = 0;
237
+ for (const image of images) {
238
+ try {
239
+ const res = await fetch(image.url, { signal: AbortSignal.timeout(30_000) });
240
+ if (!res.ok)
241
+ throw new Error(`HTTP ${res.status}`);
242
+ const bytes = Buffer.from(await res.arrayBuffer());
243
+ if (bytes.length > PICTURE_MAX)
244
+ throw new Error("too large");
245
+ const file = join(pictures, `${randomUUID()}.${PICTURE_EXT[image.contentType] ?? "png"}`);
246
+ writeFileSync(file, bytes, { mode: 0o600 });
247
+ paths.push(file);
248
+ setTimeout(() => rmSync(file, { force: true }), PICTURE_KEEP_MS).unref();
249
+ }
250
+ catch {
251
+ missed++;
252
+ }
253
+ }
254
+ return { paths, missed };
255
+ };
212
256
  const deliver = async (m) => {
213
- delivering.add(m.id);
214
257
  try {
215
- const newest = sessionsHere(harness, ctx)[0] ?? null;
216
- const prompt = asPrompt(m);
217
- const into = newest ? "the newest session" : "a new session";
218
- let result;
219
- if (harness === "claude-code" && newest && (await claudeOpen(newest.id, ctx.cwd))) {
258
+ const { paths, missed } = await fetchPictures(m.images ?? []);
259
+ const result = await h.deliver({ id: m.id, text: m.text, decision: m.decision, pictures: paths });
260
+ if (result.outcome === "left") {
220
261
  if (!left.has(m.id))
221
- say(`${me.person.name} wrote in Gavel; your Claude Code session is open, so it hears it there${hooked ? "" : ", between tasks"}.`);
262
+ say(result.say);
222
263
  left.add(m.id);
223
264
  return;
224
265
  }
225
- joins.set(prompt.trim(), m.id);
226
- if (harness === "claude-code") {
227
- say(`Putting ${me.person.name}'s message into ${into}…`);
228
- result = await claudeResume(newest?.id ?? null, prompt, ctx.cwd);
229
- }
230
- else if (newest && (await codexOpen(newest.file))) {
231
- say(`Putting ${me.person.name}'s message into your open Codex session, as its next message…`);
232
- result = await codexQueue(newest.id, prompt, ctx.cwd);
233
- }
234
- else {
235
- say(`Putting ${me.person.name}'s message into ${into}…`);
236
- result = await codexResume(newest?.id ?? null, prompt, ctx.cwd);
237
- }
238
266
  handled.add(m.id);
239
- if (result.ok) {
240
- await read({ ids: [m.id] });
241
- say(`Done: the answer shows in Gavel as it's written.`);
242
- if (result.refused.length)
243
- await note(`${NAMES[harness]} didn't do what it would have asked you about first (${result.refused.join(", ")}): nobody was at the laptop to allow it. Allow it in the session there, or answer here.`);
244
- }
245
- else {
246
- joins.delete(prompt.trim());
267
+ if (result.outcome === "failed") {
247
268
  await read({ ids: [], failed: [{ id: m.id, reason: result.reason }] });
248
269
  say(`Couldn't: ${result.reason}`);
249
270
  }
250
- await push();
271
+ else {
272
+ await read(result.read ? { ids: [m.id] } : { ids: [], delivered: [m.id] });
273
+ const with_ = paths.length ? ` with ${paths.length === 1 ? "its picture" : `its ${paths.length} pictures`}` : "";
274
+ say(`Put ${me.person.name}'s message into ${h.name}${with_}: the answer shows in Gavel as it's written.`);
275
+ if (missed)
276
+ await note(`${missed === 1 ? "A picture" : `${missed} pictures`} from your message didn't reach the laptop, so ${h.name} got your words without ${missed === 1 ? "it" : "them"}.`);
277
+ }
278
+ pushSoon();
251
279
  }
252
280
  finally {
253
281
  delivering.delete(m.id);
254
282
  }
255
283
  };
256
- const stop = () => {
257
- if (stopping)
284
+ let deliveries = Promise.resolve();
285
+ const enqueue = (m) => {
286
+ delivering.add(m.id);
287
+ deliveries = deliveries.then(() => deliver(m)).catch((err) => console.error(`gavel bridge: ${err instanceof Error ? err.message : String(err)}`));
288
+ };
289
+ const stopTurn = async (stopId) => {
290
+ if (stops.has(stopId))
258
291
  return;
259
- stopping = true;
292
+ stops.add(stopId);
293
+ const outcome = await h.interrupt().catch(() => "over");
294
+ say(outcome === "stopped" ? `${me.person.name} pressed Stop in Gavel: ${h.name}'s turn stopped.` : `${me.person.name} pressed Stop in Gavel, with nothing running.`);
295
+ await call(api, "POST", `/v1/agents/me/chat/stop/${encodeURIComponent(stopId)}`, { outcome }).then((res) => void res.body?.cancel(), () => undefined);
296
+ };
297
+ // Wakes: what waits for the agent in Gavel (an answer to what it waits on, a message, a request),
298
+ // as Gavel's one line into the session once it's idle. The person's own messages it puts in itself.
299
+ const watchId = randomUUID();
300
+ let watching = true;
301
+ let pending = [];
302
+ let waking = false;
303
+ const stillWaiting = async () => {
260
304
  try {
261
- setHook(false);
305
+ const res = await call(api, "GET", "/v1/me", undefined, { "x-gavel-waiting": "1" });
306
+ void res.body?.cancel();
307
+ return !res.ok || res.headers.get("x-gavel-waiting") !== null;
262
308
  }
263
- catch (err) {
264
- console.error(`gavel bridge: ${err instanceof Error ? err.message : String(err)}`);
309
+ catch {
310
+ return true;
265
311
  }
266
- say("Stopped.");
267
- process.exit(0);
268
312
  };
269
- process.on("SIGINT", stop);
270
- process.on("SIGTERM", stop);
271
- const timer = setInterval(() => void push(), 2000);
313
+ const tryWake = async () => {
314
+ if (waking || stopping || !pending.length)
315
+ return;
316
+ waking = true;
317
+ try {
318
+ if (!(await stillWaiting())) {
319
+ pending = [];
320
+ return;
321
+ }
322
+ const line = wakeLineOf(pending);
323
+ if (await h.wake(line)) {
324
+ say(`Woke ${h.name} for what waits in Gavel: ${line}`);
325
+ pending = [];
326
+ }
327
+ }
328
+ finally {
329
+ waking = false;
330
+ }
331
+ };
332
+ const watchLoop = async () => {
333
+ let start = true;
334
+ let failures = 0;
335
+ while (watching && !stopping) {
336
+ let res;
337
+ try {
338
+ res = await call(api, "GET", `/v1/inbox/watch?watch=${watchId}&timeout=50&kinds=health,claim,work,drift${start ? "&start=true" : ""}`);
339
+ }
340
+ catch {
341
+ failures++;
342
+ await pause(backoff(failures));
343
+ continue;
344
+ }
345
+ if (stopping)
346
+ return;
347
+ if (res.status === 409) {
348
+ say(`Another watch for this agent took over waking it, so the bridge no longer wakes ${h.name} for what waits in Gavel.`);
349
+ return;
350
+ }
351
+ if (res.status >= 400 && res.status < 500) {
352
+ console.error(`gavel bridge: HTTP ${res.status} watching what waits in Gavel; ${h.name} isn't woken for it`);
353
+ return;
354
+ }
355
+ if (!res.ok) {
356
+ failures++;
357
+ await pause(backoff(failures));
358
+ continue;
359
+ }
360
+ failures = 0;
361
+ start = false;
362
+ const { items } = (await res.json());
363
+ const known = new Set(pending.map((i) => `${i.kind}:${i.id}`));
364
+ pending.push(...items.filter((i) => i.kind !== "chat" && !known.has(`${i.kind}:${i.id}`)));
365
+ await tryWake();
366
+ }
367
+ };
368
+ const wakeTimer = setInterval(() => void tryWake(), WAKE_AGAIN_MS);
369
+ // The harness's own hooks, through `gavel bridge event` (background.ts).
370
+ const offHooks = onHookEvent((event) => h.hook?.(event.event, event));
371
+ h.listen({
372
+ live: (event) => {
373
+ if (on && liveRoute)
374
+ outgoing.push(event);
375
+ },
376
+ state: (next) => {
377
+ state = next;
378
+ if (on && liveRoute)
379
+ outgoing.push({ event: "state", state: next });
380
+ if (next === "idle" || next === "closed")
381
+ void tryWake();
382
+ },
383
+ changed: pushSoon,
384
+ note: (text) => void note(text),
385
+ });
386
+ const timers = () => {
387
+ clearInterval(liveTimer);
388
+ clearInterval(pushTimer);
389
+ clearInterval(wakeTimer);
390
+ if (soon)
391
+ clearTimeout(soon);
392
+ offHooks();
393
+ };
394
+ const stop = (said = "Stopped.") => {
395
+ if (stopping)
396
+ return;
397
+ stopping = true;
398
+ watching = false;
399
+ timers();
400
+ say(said);
401
+ // The chat says at once that the bridge stopped, rather than after its minute.
402
+ void Promise.race([call(api, "DELETE", `/v1/agents/me/chat/bridge?bridge=${id}`).catch(() => undefined), pause(3000)]).finally(() => {
403
+ rmSync(pictures, { recursive: true, force: true });
404
+ void h.close().finally(() => process.exit(0));
405
+ });
406
+ };
407
+ process.on("SIGINT", () => stop());
408
+ process.on("SIGTERM", () => stop());
409
+ const here = { home: ctx.home, cwd: ctx.cwd, harness };
410
+ void watchLoop();
272
411
  let start = true;
273
412
  let failures = 0;
274
- // The bridge that took over owns the wake hook from here (W-138): it stays in.
275
- let tookOver = false;
276
413
  try {
277
- for (;;) {
414
+ while (!stopping) {
278
415
  let res;
279
416
  try {
280
417
  res = await call(api, "GET", `/v1/agents/me/chat?wait=30&bridge=${id}${start ? "&start=true" : ""}`);
@@ -285,8 +422,10 @@ async function bridge(run, ctx) {
285
422
  await pause(backoff(failures));
286
423
  continue;
287
424
  }
425
+ // Stopping: nothing more goes out but the goodbye, and the process ends with it.
426
+ if (stopping)
427
+ await new Promise(() => undefined);
288
428
  if (res.status === 409) {
289
- tookOver = true;
290
429
  say("Another bridge for this agent took over; this one stops.");
291
430
  return 3;
292
431
  }
@@ -302,129 +441,63 @@ async function bridge(run, ctx) {
302
441
  }
303
442
  failures = 0;
304
443
  start = false;
305
- const state = (await res.json());
306
- if (state.on !== on) {
307
- on = state.on;
444
+ const peeked = (await res.json());
445
+ if (peeked.stop?.id)
446
+ void stopTurn(peeked.stop.id);
447
+ if (peeked.on !== on) {
448
+ on = peeked.on;
449
+ h.setChat(on);
450
+ // Off stops the bridge (D-1140): marked, so a session's start looks again rather than
451
+ // running it; the service stays, its peek waiting for the chat to come back on.
452
+ markChatOff(here, !on);
308
453
  if (on) {
309
- say(`The chat is on: ${me.person.name} sees this folder's newest session in Gavel.`);
454
+ say(`The chat is on: ${me.person.name} sees this folder's newest ${h.name} session in Gavel.`);
310
455
  thread = null;
311
- seen = "";
312
- if (harness === "claude-code")
313
- setHook(true);
456
+ sent.clear();
457
+ if (state)
458
+ outgoing.push({ event: "state", state });
314
459
  await push();
315
460
  }
461
+ else if (ctx.env.GAVEL_BRIDGE_SERVICE !== "1") {
462
+ stop("The chat is off in Gavel: the bridge stops, and starts again with a session once it's on.");
463
+ await new Promise(() => undefined);
464
+ }
316
465
  else {
317
466
  say(`The chat is off in Gavel: nothing is read or sent until ${me.person.name} turns it on again.`);
318
- if (harness === "claude-code")
319
- setHook(false);
467
+ outgoing = [];
320
468
  }
321
469
  }
322
470
  if (!on)
323
471
  continue;
324
- for (const m of state.unread.filter((u) => !delivering.has(u.id) && !handled.has(u.id)))
325
- await deliver(m);
326
- // What's left waits for the open session to hear it, or to close: look again in a moment.
327
- if (state.unread.some((u) => !handled.has(u.id)))
328
- await pause(5000);
472
+ const waiting = peeked.unread.filter((u) => !handled.has(u.id));
473
+ for (const m of waiting)
474
+ if (!delivering.has(m.id))
475
+ enqueue(m);
476
+ // What's still going in, or left for the session to hear: look again in a moment.
477
+ if (waiting.some((m) => left.has(m.id)))
478
+ await pause(2000);
479
+ else if (waiting.length)
480
+ await pause(300);
329
481
  }
330
- }
331
- finally {
332
- clearInterval(timer);
333
- if (!stopping && !tookOver)
334
- setHook(false);
335
- }
336
- }
337
- // ---------- gavel bridge wake ----------
338
- // Run by Claude Code as the wake hook (never by hand): waits for what the person writes in Gavel
339
- // and wakes the session with it, exit code 2 and the words on stderr. One per session: a newer one
340
- // takes over. It stays quiet (exit 0) when the chat is off, the session is gone or it's taken over,
341
- // and never marks a message read for a session that isn't there to hear it.
342
- async function wake(run, ctx) {
343
- let input = {};
344
- try {
345
- input = JSON.parse(readFileSync(0, "utf8"));
346
- }
347
- catch {
348
- // no hook input
349
- }
350
- const session = typeof input.session_id === "string" ? input.session_id : null;
351
- const cwd = typeof input.cwd === "string" ? input.cwd : ctx.cwd;
352
- if (!session)
353
- return 0;
354
- let setup;
355
- try {
356
- setup = setupHere("claude-code", run.server, { ...ctx, cwd });
357
- }
358
- catch {
359
482
  return 0;
360
483
  }
361
- const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
362
- const lock = join(tmpdir(), `gavel-wake-${session.replace(/[^A-Za-z0-9-]/g, "")}`);
363
- const before = existsSync(lock) ? Number(readFileSync(lock, "utf8")) : 0;
364
- if (before && before !== process.pid) {
365
- try {
366
- const command = execFileSync("ps", ["-p", String(before), "-o", "command="], { encoding: "utf8" });
367
- if (/\bbridge wake\b/.test(command))
368
- process.kill(before, "SIGTERM");
369
- }
370
- catch {
371
- // gone already
372
- }
373
- }
374
- writeFileSync(lock, String(process.pid));
375
- const mine = () => existsSync(lock) && readFileSync(lock, "utf8") === String(process.pid);
376
- const parent = process.ppid;
377
- let person = "Your person";
378
- try {
379
- const res = await call(api, "GET", "/v1/me");
380
- if (res.ok)
381
- person = (await res.json()).person.name;
382
- }
383
- catch {
384
- // named generically
385
- }
386
- let failures = 0;
387
- while (mine() && process.ppid === parent) {
388
- let res;
389
- try {
390
- res = await call(api, "GET", "/v1/agents/me/chat?wait=30");
391
- }
392
- catch {
393
- failures++;
394
- await pause(backoff(failures));
395
- continue;
396
- }
397
- if (!res.ok) {
398
- if (res.status < 500)
399
- return 0;
400
- failures++;
401
- await pause(backoff(failures));
402
- continue;
484
+ finally {
485
+ if (!stopping) {
486
+ watching = false;
487
+ timers();
488
+ rmSync(pictures, { recursive: true, force: true });
489
+ await h.close();
403
490
  }
404
- failures = 0;
405
- const state = (await res.json());
406
- if (!state.on)
407
- return 0;
408
- if (!state.unread.length)
409
- continue;
410
- if (!mine() || process.ppid !== parent || !(await claudeOpen(session, cwd)))
411
- return 0;
412
- const res2 = await call(api, "POST", "/v1/agents/me/chat/read", { ids: state.unread.map((m) => m.id) }).catch(() => null);
413
- if (!res2?.ok)
414
- continue;
415
- const words = state.unread.map(asPrompt).join("\n\n---\n\n");
416
- const text = words.length > 9000 ? `${words.slice(0, 9000)}… (cut: the rest is in Gavel's chat)` : words;
417
- process.stderr.write(`${person} wrote to you in Gavel (they read your answer there, so answer here as you would to them):\n\n${text}\n`);
418
- return 2;
419
491
  }
420
- return 0;
421
492
  }
422
493
  export async function runBridge(run, ctx) {
423
494
  try {
424
495
  if (run.action === "show")
425
- return show(run, ctx);
496
+ return await show(run, ctx);
497
+ // The wake hook an older bridge put in a folder's settings, left there: it does nothing now (the
498
+ // bridge reaches the session through its inbox), and the bridge's hooks take it out as they go in.
426
499
  if (run.action === "wake")
427
- return await wake(run, ctx);
500
+ return 0;
428
501
  return await bridge(run, ctx);
429
502
  }
430
503
  catch (err) {