@getgavel/cli 0.1.20 → 0.1.22

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.20",
3
+ "version": "0.1.22",
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" },
@@ -110,6 +110,9 @@ const PUSH_EVERY_MS = 2000;
110
110
  // stay this far apart while things keep changing: each counts in the agent's 120 calls a minute.
111
111
  const PUSH_SOON_MS = 50;
112
112
  const PUSH_GAP_MS = 500;
113
+ // For this long after a delivery or a turn's end, the session's copy of the message or the turn's
114
+ // last words skip the gap (still never more than three pushes in a second).
115
+ const PUSH_URGENT_MS = 2000;
113
116
  const WAKE_AGAIN_MS = 60_000;
114
117
  // Gavel's one-line wake (D-1103, cloud-agents' wakePrompt): each ref once, what has none by its kind.
115
118
  export const wakeLineOf = (items) => {
@@ -172,6 +175,8 @@ async function harnessBridge(h, harness, setup, ctx) {
172
175
  };
173
176
  let syncing = null;
174
177
  let pushedAt = 0;
178
+ let urgentUntil = 0;
179
+ const pushes = [];
175
180
  const pushOnce = async () => {
176
181
  if (!on)
177
182
  return;
@@ -188,6 +193,7 @@ async function harnessBridge(h, harness, setup, ctx) {
188
193
  const part = messages.slice(i, i + 200);
189
194
  const res = await call(api, "PUT", "/v1/agents/me/chat/transcript", { thread: t.thread, label: t.label, messages: part });
190
195
  pushedAt = Date.now();
196
+ pushes.push(pushedAt);
191
197
  if (!res.ok)
192
198
  throw new Error(`HTTP ${res.status} sending the session's words`);
193
199
  if (!(await res.json()).on)
@@ -205,11 +211,23 @@ async function harnessBridge(h, harness, setup, ctx) {
205
211
  await push();
206
212
  };
207
213
  let soon = null;
214
+ let soonAt = 0;
208
215
  const pushSoon = () => {
209
- soon ??= setTimeout(() => {
216
+ const now = Date.now();
217
+ while (pushes.length && pushes[0] <= now - 1000)
218
+ pushes.shift();
219
+ const gap = now < urgentUntil && pushes.length < 3 ? 0 : PUSH_GAP_MS;
220
+ const at = now + Math.max(PUSH_SOON_MS, pushedAt + gap - now);
221
+ if (soon) {
222
+ if (soonAt <= at)
223
+ return;
224
+ clearTimeout(soon);
225
+ }
226
+ soonAt = at;
227
+ soon = setTimeout(() => {
210
228
  soon = null;
211
229
  void pushAfter();
212
- }, Math.max(PUSH_SOON_MS, pushedAt + PUSH_GAP_MS - Date.now()));
230
+ }, at - now);
213
231
  };
214
232
  const note = async (text) => {
215
233
  await pushAfter();
@@ -233,8 +251,10 @@ async function harnessBridge(h, harness, setup, ctx) {
233
251
  return;
234
252
  }
235
253
  const events = joined(outgoing.splice(0));
236
- if (events.some((e) => e.event === "end"))
254
+ if (events.some((e) => e.event === "end")) {
255
+ urgentUntil = Date.now() + PUSH_URGENT_MS;
237
256
  await pushAfter();
257
+ }
238
258
  for (let i = 0; i < events.length; i += 200) {
239
259
  const res = await call(api, "POST", `/v1/agents/me/chat/live?bridge=${id}`, { ...(thread ? { thread } : {}), events: events.slice(i, i + 200) });
240
260
  void res.body?.cancel();
@@ -302,6 +322,7 @@ async function harnessBridge(h, harness, setup, ctx) {
302
322
  const deliver = async (m) => {
303
323
  try {
304
324
  const { paths, missed } = await fetchPictures(m.images ?? []);
325
+ urgentUntil = Date.now() + PUSH_URGENT_MS;
305
326
  const result = await h.deliver({ id: m.id, text: m.text, decision: m.decision, pictures: paths });
306
327
  if (result.outcome === "left") {
307
328
  if (!left.has(m.id))
@@ -1,6 +1,6 @@
1
1
  import { execFile, execFileSync, spawn } from "node:child_process";
2
2
  import { createHash, randomBytes } from "node:crypto";
3
- import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync } from "node:fs";
3
+ import { closeSync, copyFileSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync } from "node:fs";
4
4
  import { createServer } from "node:http";
5
5
  import { connect } from "node:net";
6
6
  import { tmpdir } from "node:os";
@@ -234,6 +234,69 @@ export function sessionWords(jsonl, fromGavel, prompts = new Map()) {
234
234
  }
235
235
  return words.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
236
236
  }
237
+ const sizeOf = (file) => {
238
+ try {
239
+ return statSync(file).size;
240
+ }
241
+ catch {
242
+ return 0;
243
+ }
244
+ };
245
+ const READ_MAX = 8 * 1024 * 1024;
246
+ // A file from an offset to its end (READ_MAX at most), without reading the whole transcript; null
247
+ // when it can't be read.
248
+ function readFrom(file, offset, max = READ_MAX) {
249
+ try {
250
+ const fd = openSync(file, "r");
251
+ try {
252
+ const length = Math.max(0, Math.min(fstatSync(fd).size - offset, max));
253
+ const buffer = Buffer.alloc(length);
254
+ readSync(fd, buffer, 0, length, offset);
255
+ return buffer;
256
+ }
257
+ finally {
258
+ closeSync(fd);
259
+ }
260
+ }
261
+ catch {
262
+ return null;
263
+ }
264
+ }
265
+ // The first and the last of an answer's words as its transcript line has them (JSON), each within
266
+ // one line of it: Claude Code joins a message's parts with a newline for the Stop hook, so neither
267
+ // spans two parts.
268
+ function wordsOf(last) {
269
+ const lines = last.split("\n");
270
+ const json = (text) => Array.from(JSON.stringify(text).slice(1, -1));
271
+ return [Buffer.from(json(lines[0]).slice(0, 59).join("")), Buffer.from(json(lines.at(-1)).slice(-59).join(""))];
272
+ }
273
+ // Where a turn's prompt line starts (Claude Code keeps the prompt's id in it) in the transcript's
274
+ // last 16 MB; null when it isn't there.
275
+ function promptLine(file, prompt) {
276
+ const from = Math.max(0, sizeOf(file) - 2 * READ_MAX);
277
+ const read = readFrom(file, from, 2 * READ_MAX);
278
+ const at = read?.lastIndexOf(`"promptId":${JSON.stringify(prompt)}`) ?? -1;
279
+ return read && at >= 0 ? from + read.lastIndexOf(10, at) + 1 : null;
280
+ }
281
+ // Whether a transcript read's whole lines hold the agent's line with these words (a line Claude Code
282
+ // is still writing doesn't count), and how far its whole lines go.
283
+ function agentLine(read, words) {
284
+ let start = 0;
285
+ for (let end = read.indexOf(10); end >= 0; start = end + 1, end = read.indexOf(10, start)) {
286
+ const raw = read.subarray(start, end);
287
+ if (!words.every((w) => raw.includes(w)))
288
+ continue;
289
+ try {
290
+ const line = JSON.parse(raw.toString("utf8"));
291
+ if (line.type === "assistant" && !line.isSidechain)
292
+ return { found: true, through: end + 1 };
293
+ }
294
+ catch {
295
+ // a line read from its middle
296
+ }
297
+ }
298
+ return { found: false, through: start };
299
+ }
237
300
  const PICTURES_HOURS = 1;
238
301
  export class ClaudeCodeHarness {
239
302
  ctx;
@@ -336,7 +399,7 @@ export class ClaudeCodeHarness {
336
399
  session(id) {
337
400
  let s = this.sessions.get(id);
338
401
  if (!s) {
339
- s = { id, inbox: null, transcript: null, open: true, state: "idle", seen: Date.now(), run: null, spoken: new Map() };
402
+ s = { id, inbox: null, transcript: null, open: true, hooked: false, state: "idle", seen: Date.now(), run: null, spoken: new Map() };
340
403
  this.sessions.set(id, s);
341
404
  }
342
405
  return s;
@@ -352,6 +415,7 @@ export class ClaudeCodeHarness {
352
415
  return;
353
416
  const s = this.session(id);
354
417
  s.seen = Date.now();
418
+ s.hooked = true;
355
419
  if (e.inbox)
356
420
  s.inbox = e.inbox;
357
421
  if (typeof input.transcript_path === "string")
@@ -401,7 +465,7 @@ export class ClaudeCodeHarness {
401
465
  s.run = null;
402
466
  const last = typeof input.last_assistant_message === "string" ? input.last_assistant_message.trim() : "";
403
467
  if (run)
404
- void this.endOnceKept(s, run, event === "Stop" ? last : "");
468
+ void this.endOnceKept(s, run, event === "Stop" ? last : "", typeof input.prompt_id === "string" ? input.prompt_id : null);
405
469
  break;
406
470
  }
407
471
  case "SessionEnd":
@@ -414,19 +478,28 @@ export class ClaudeCodeHarness {
414
478
  this.soon();
415
479
  this.stateNow();
416
480
  }
417
- // A turn's end goes once the transcript has its last words (Claude Code writes the file a moment
418
- // after the Stop hook), so the core's push before it keeps them (Reach's rule for `end`).
419
- async endOnceKept(s, run, last) {
420
- const deadline = Date.now() + 3_000;
421
- while (last && s.transcript && Date.now() < deadline) {
422
- try {
423
- if (readFileSync(s.transcript, "utf8").includes(JSON.stringify(last).slice(1, 60)))
481
+ // A turn's end goes once the transcript has its last words in a whole line (Claude Code writes the
482
+ // file a moment after the Stop hook, and a line sometimes in two writes), so the core's push before
483
+ // it keeps them (Reach's rule for `end`). Looked for after the turn's own prompt line, so an earlier
484
+ // answer in the same words isn't taken for it; without one, from a little before where the file
485
+ // ended at the Stop hook: Claude Code writes large lines after the last words too (a session's
486
+ // first turn adds a prompt snapshot of tens of KB).
487
+ async endOnceKept(s, run, last, prompt) {
488
+ const file = s.transcript;
489
+ if (last && file) {
490
+ const deadline = Date.now() + 3_000;
491
+ const words = wordsOf(last);
492
+ let from = (prompt ? promptLine(file, prompt) : null) ?? Math.max(0, sizeOf(file) - 8 * last.length - 1_048_576);
493
+ while (Date.now() < deadline) {
494
+ const read = readFrom(file, from);
495
+ if (!read)
424
496
  break;
497
+ const scan = agentLine(read, words);
498
+ if (scan.found)
499
+ break;
500
+ from += scan.through || (read.length >= READ_MAX ? read.length : 0);
501
+ await new Promise((r) => setTimeout(r, 20));
425
502
  }
426
- catch {
427
- break;
428
- }
429
- await new Promise((r) => setTimeout(r, 100));
430
503
  }
431
504
  this.listener?.changed();
432
505
  this.listener?.live({ event: "end", runId: run });
@@ -546,10 +619,10 @@ export class ClaudeCodeHarness {
546
619
  // missed): the newest one's inbox at its usual address, without the session's key.
547
620
  async liveSession() {
548
621
  try {
549
- const { stdout } = await promisify(execFile)("claude", ["agents", "--json"], { cwd: this.ctx.cwd, timeout: 15_000 });
622
+ const { stdout } = await promisify(execFile)("claude", ["agents", "--json"], { cwd: this.ctx.cwd, env: this.ctx.env, timeout: 15_000 });
550
623
  const live = JSON.parse(stdout).filter((s) => s.cwd === this.ctx.cwd && typeof s.sessionId === "string" && typeof s.pid === "number");
551
624
  for (const s of this.sessions.values())
552
- if (s.open && !live.some((l) => l.sessionId === s.id)) {
625
+ if (s.open && !s.hooked && !live.some((l) => l.sessionId === s.id)) {
553
626
  s.open = false;
554
627
  s.inbox = null;
555
628
  s.state = "closed";
@@ -163,6 +163,9 @@ const SOURCES = ["cli", "vscode", "exec", "appServer"];
163
163
  const HISTORY_TURNS = 30;
164
164
  // After the person stops a turn at the laptop, Gavel's wake waits this long.
165
165
  const QUIET_AFTER_STOP_MS = 2 * 60_000;
166
+ // A thread the bridge started isn't in thread/list at first (60 to 200 ms in Codex 0.172.0); until
167
+ // it is, for at most this long, it stays the session.
168
+ const UNLISTED_MS = 10_000;
166
169
  const reasonOf = (err) => (err instanceof Error ? err.message : String(err));
167
170
  const notRunning = (err) => err instanceof WebSocketError && (err.code === "ENOENT" || err.code === "ECONNREFUSED");
168
171
  class CodexHarness {
@@ -185,6 +188,7 @@ class CodexHarness {
185
188
  queued = new Map();
186
189
  state = null;
187
190
  stoppedAt = 0;
191
+ started = null;
188
192
  constructor(ctx) {
189
193
  this.ctx = ctx;
190
194
  }
@@ -276,23 +280,27 @@ class CodexHarness {
276
280
  const app = await this.connect();
277
281
  const cwd = [...new Set([this.ctx.cwd, realpath(this.ctx.cwd)])];
278
282
  const { data } = await app.request("thread/list", { cwd, sortKey: "updated_at", sortDirection: "desc", limit: 10, sourceKinds: SOURCES, useStateDbOnly: true });
279
- const top = data.find((t) => !t.parentThreadId && !t.ephemeral);
280
- if (!top) {
281
- this.current = null;
282
- this.setState("closed");
283
- return null;
284
- }
285
- if (this.current?.id !== top.id) {
286
- this.current = { id: top.id, status: top.status, path: top.path, subscribed: false };
287
- this.words.clear();
288
- this.offsets.clear();
289
- this.turnId = null;
290
- await this.history(app, top.id, HISTORY_TURNS);
291
- }
292
- else if (!this.current.subscribed) {
293
- this.current.status = top.status;
294
- // Not heard live (open elsewhere, or closed): its newest turns, read again.
295
- await this.history(app, top.id, 3);
283
+ const tops = data.filter((t) => !t.parentThreadId && !t.ephemeral);
284
+ const mine = this.current && this.started?.id === this.current.id && Date.now() - this.started.at < UNLISTED_MS ? this.current : null;
285
+ if (!mine || tops.some((t) => t.id === mine.id)) {
286
+ const top = tops[0];
287
+ if (!top) {
288
+ this.current = null;
289
+ this.setState("closed");
290
+ return null;
291
+ }
292
+ if (this.current?.id !== top.id) {
293
+ this.current = { id: top.id, status: top.status, path: top.path, subscribed: false };
294
+ this.words.clear();
295
+ this.offsets.clear();
296
+ this.turnId = null;
297
+ await this.history(app, top.id, HISTORY_TURNS);
298
+ }
299
+ else if (!this.current.subscribed) {
300
+ this.current.status = top.status;
301
+ // Not heard live (open elsewhere, or closed): its newest turns, read again.
302
+ await this.history(app, top.id, 3);
303
+ }
296
304
  }
297
305
  const current = this.current;
298
306
  if (!current.subscribed && current.status.type !== "notLoaded")
@@ -400,6 +408,7 @@ class CodexHarness {
400
408
  if (!current) {
401
409
  const { thread } = await app.request("thread/start", { cwd: this.ctx.cwd });
402
410
  current = this.current = { id: thread.id, status: thread.status, path: thread.path, subscribed: true };
411
+ this.started = { id: thread.id, at: Date.now() };
403
412
  this.words.clear();
404
413
  this.ownLoaded.add(thread.id);
405
414
  }
package/dist/gavel.js CHANGED
@@ -1803,6 +1803,13 @@ async function upload(token, as, { file, contentType }) {
1803
1803
  console.log(jsonText(await finished.json()));
1804
1804
  return 0;
1805
1805
  }
1806
+ const THREAD_WAKES = {
1807
+ added: "you were added to it",
1808
+ mention: "a message names you",
1809
+ answer: "an answer to what you asked",
1810
+ note: "a note, it needs no answer",
1811
+ acknowledgment: "an acknowledgment",
1812
+ };
1806
1813
  // One line per thing that should wake the chat: refs and Gavel's own words only, never a message's
1807
1814
  // text, so the line itself is never someone else's instructions. A kind newer than this command
1808
1815
  // still wakes it, with a line that sends it to the inbox.
@@ -1838,6 +1845,8 @@ export function wakeLine(item) {
1838
1845
  : `GAVEL_WAKE task ${item.ref} ${item.type ?? "changed"} by someone else: gavel work show ${item.ref}`;
1839
1846
  case "replaced":
1840
1847
  return `GAVEL_WAKE replaced ${item.ref}: it no longer holds, ${item.type ?? "a newer decision"} replaces it: gavel get ${item.type ?? item.ref}, and follow that one`;
1848
+ case "thread":
1849
+ return `GAVEL_WAKE thread ${item.ref}: ${THREAD_WAKES[item.type ?? ""] ?? "a message"}: read it with gavel thread ${item.ref}`;
1841
1850
  default:
1842
1851
  return "GAVEL_WAKE something new: see gavel inbox";
1843
1852
  }
@@ -1853,7 +1862,7 @@ async function watch(token, as) {
1853
1862
  for (;;) {
1854
1863
  let res;
1855
1864
  try {
1856
- res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50&kinds=health,claim,work,drift,task,replaced${start ? "&start=true" : ""}`, {
1865
+ res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50&kinds=health,claim,work,drift,task,replaced,thread${start ? "&start=true" : ""}`, {
1857
1866
  headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) },
1858
1867
  });
1859
1868
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.20",
3
+ "version": "0.1.22",
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",