@getgavel/cli 0.1.19 → 0.1.21

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.19",
3
+ "version": "0.1.21",
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" },
@@ -106,6 +106,13 @@ const PICTURE_KEEP_MS = 15 * 60_000;
106
106
  const LIVE_EVERY_MS = 500;
107
107
  const LIVE_PIECE = 20_000;
108
108
  const PUSH_EVERY_MS = 2000;
109
+ // What changed goes this long after (what changes with it goes along), and pushes that send words
110
+ // stay this far apart while things keep changing: each counts in the agent's 120 calls a minute.
111
+ const PUSH_SOON_MS = 50;
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;
109
116
  const WAKE_AGAIN_MS = 60_000;
110
117
  // Gavel's one-line wake (D-1103, cloud-agents' wakePrompt): each ref once, what has none by its kind.
111
118
  export const wakeLineOf = (items) => {
@@ -167,6 +174,9 @@ async function harnessBridge(h, harness, setup, ctx) {
167
174
  trouble = what;
168
175
  };
169
176
  let syncing = null;
177
+ let pushedAt = 0;
178
+ let urgentUntil = 0;
179
+ const pushes = [];
170
180
  const pushOnce = async () => {
171
181
  if (!on)
172
182
  return;
@@ -182,6 +192,8 @@ async function harnessBridge(h, harness, setup, ctx) {
182
192
  for (let i = 0; i < messages.length; i += 200) {
183
193
  const part = messages.slice(i, i + 200);
184
194
  const res = await call(api, "PUT", "/v1/agents/me/chat/transcript", { thread: t.thread, label: t.label, messages: part });
195
+ pushedAt = Date.now();
196
+ pushes.push(pushedAt);
185
197
  if (!res.ok)
186
198
  throw new Error(`HTTP ${res.status} sending the session's words`);
187
199
  if (!(await res.json()).on)
@@ -199,11 +211,23 @@ async function harnessBridge(h, harness, setup, ctx) {
199
211
  await push();
200
212
  };
201
213
  let soon = null;
214
+ let soonAt = 0;
202
215
  const pushSoon = () => {
203
- 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(() => {
204
228
  soon = null;
205
- void push();
206
- }, 250);
229
+ void pushAfter();
230
+ }, at - now);
207
231
  };
208
232
  const note = async (text) => {
209
233
  await pushAfter();
@@ -212,8 +236,13 @@ async function harnessBridge(h, harness, setup, ctx) {
212
236
  await call(api, "PUT", "/v1/agents/me/chat/transcript", { thread, messages: [{ id: `gavel:${randomUUID()}`, side: "gavel", text, at: new Date().toISOString() }] }).catch(() => undefined);
213
237
  };
214
238
  // Live: the words as they're written and the state, relayed to the person's open chat, never kept.
215
- // A turn's end goes only once its words are kept.
239
+ // A turn's end goes only once its words are kept. One POST at most each LIVE_EVERY_MS, each as soon
240
+ // as that allows: a turn's start or a state change after a quiet moment shows at once, and words
241
+ // batch while they stream.
216
242
  let posting = null;
243
+ let lastPost = 0;
244
+ const posted = [];
245
+ let liveTimer = null;
217
246
  const postLive = async () => {
218
247
  if (!outgoing.length)
219
248
  return;
@@ -222,8 +251,10 @@ async function harnessBridge(h, harness, setup, ctx) {
222
251
  return;
223
252
  }
224
253
  const events = joined(outgoing.splice(0));
225
- if (events.some((e) => e.event === "end"))
254
+ if (events.some((e) => e.event === "end")) {
255
+ urgentUntil = Date.now() + PUSH_URGENT_MS;
226
256
  await pushAfter();
257
+ }
227
258
  for (let i = 0; i < events.length; i += 200) {
228
259
  const res = await call(api, "POST", `/v1/agents/me/chat/live?bridge=${id}`, { ...(thread ? { thread } : {}), events: events.slice(i, i + 200) });
229
260
  void res.body?.cancel();
@@ -233,11 +264,35 @@ async function harnessBridge(h, harness, setup, ctx) {
233
264
  return;
234
265
  }
235
266
  };
236
- const liveTimer = setInterval(() => {
237
- posting ??= postLive()
267
+ const sendLive = () => {
268
+ liveTimer = null;
269
+ if (posting)
270
+ return;
271
+ lastPost = Date.now();
272
+ posted.push(lastPost);
273
+ posting = postLive()
238
274
  .catch(() => undefined)
239
- .finally(() => (posting = null));
240
- }, LIVE_EVERY_MS);
275
+ .finally(() => {
276
+ posting = null;
277
+ liveSoon();
278
+ });
279
+ };
280
+ const liveSoon = () => {
281
+ if (stopping || posting || !outgoing.length)
282
+ return;
283
+ const now = Date.now();
284
+ while (posted.length && posted[0] <= now - 1000)
285
+ posted.shift();
286
+ // A turn's end, with its last words, goes at once even inside the gap: one a turn, and never more
287
+ // than three posts in a second (the route takes 240 a minute).
288
+ const end = outgoing.some((e) => e.event === "end") && posted.length < 3;
289
+ if (liveTimer) {
290
+ if (!end)
291
+ return;
292
+ clearTimeout(liveTimer);
293
+ }
294
+ liveTimer = setTimeout(sendLive, end ? 0 : Math.max(0, lastPost + LIVE_EVERY_MS - now));
295
+ };
241
296
  const pushTimer = setInterval(() => void push(), PUSH_EVERY_MS);
242
297
  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`));
243
298
  // A message's pictures, to private files on the laptop that its software reads (each an hour-long
@@ -267,6 +322,7 @@ async function harnessBridge(h, harness, setup, ctx) {
267
322
  const deliver = async (m) => {
268
323
  try {
269
324
  const { paths, missed } = await fetchPictures(m.images ?? []);
325
+ urgentUntil = Date.now() + PUSH_URGENT_MS;
270
326
  const result = await h.deliver({ id: m.id, text: m.text, decision: m.decision, pictures: paths });
271
327
  if (result.outcome === "left") {
272
328
  if (!left.has(m.id))
@@ -286,7 +342,6 @@ async function harnessBridge(h, harness, setup, ctx) {
286
342
  if (missed)
287
343
  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"}.`);
288
344
  }
289
- pushSoon();
290
345
  }
291
346
  finally {
292
347
  delivering.delete(m.id);
@@ -385,13 +440,17 @@ async function harnessBridge(h, harness, setup, ctx) {
385
440
  const offHooks = onHookEvent((event) => h.hook?.(event.event, event));
386
441
  h.listen({
387
442
  live: (event) => {
388
- if (on && liveRoute)
389
- outgoing.push(event);
443
+ if (!on || !liveRoute)
444
+ return;
445
+ outgoing.push(event);
446
+ liveSoon();
390
447
  },
391
448
  state: (next) => {
392
449
  state = next;
393
- if (on && liveRoute)
450
+ if (on && liveRoute) {
394
451
  outgoing.push({ event: "state", state: next });
452
+ liveSoon();
453
+ }
395
454
  if (next === "idle" || next === "closed")
396
455
  void tryWake();
397
456
  },
@@ -399,7 +458,8 @@ async function harnessBridge(h, harness, setup, ctx) {
399
458
  note: (text) => void note(text),
400
459
  });
401
460
  const timers = () => {
402
- clearInterval(liveTimer);
461
+ if (liveTimer)
462
+ clearTimeout(liveTimer);
403
463
  clearInterval(pushTimer);
404
464
  clearInterval(wakeTimer);
405
465
  if (soon)
@@ -472,6 +532,7 @@ async function harnessBridge(h, harness, setup, ctx) {
472
532
  if (state)
473
533
  outgoing.push({ event: "state", state });
474
534
  await push();
535
+ liveSoon();
475
536
  }
476
537
  else if (ctx.env.GAVEL_BRIDGE_SERVICE !== "1") {
477
538
  stop("The chat is off in Gavel: the bridge stops, and starts again with a session once it's on.");
@@ -4,7 +4,7 @@ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameS
4
4
  import { createServer } from "node:http";
5
5
  import { connect } from "node:net";
6
6
  import { tmpdir } from "node:os";
7
- import { extname, join } from "node:path";
7
+ import { basename, dirname, extname, join } from "node:path";
8
8
  import { promisify } from "node:util";
9
9
  import { bridgePaths } from "./background.js";
10
10
  import { claudeSessions, claudeWords } from "./claude-code.js";
@@ -295,24 +295,39 @@ export class ClaudeCodeHarness {
295
295
  stateNow() {
296
296
  this.setState(this.current()?.state ?? "closed");
297
297
  }
298
+ // A transcript write comes as a few file events at once: one changed() for them, quickly, since the
299
+ // session's copy of a Gavel message is what marks it read.
298
300
  soon() {
299
301
  if (this.changedTimer)
300
302
  return;
301
303
  this.changedTimer = setTimeout(() => {
302
304
  this.changedTimer = null;
303
305
  this.listener?.changed();
304
- }, 50);
306
+ }, 15);
305
307
  }
308
+ // A new session's transcript appears with its first prompt: until then its folder is watched for it.
306
309
  follow(file) {
307
310
  if (file === this.watching)
308
311
  return;
309
312
  this.watcher?.close();
310
313
  this.watcher = null;
311
314
  this.watching = file;
312
- if (!file || !existsSync(file))
315
+ if (!file)
313
316
  return;
314
317
  try {
315
- this.watcher = watch(file, () => this.soon());
318
+ if (existsSync(file)) {
319
+ this.watcher = watch(file, () => this.soon());
320
+ return;
321
+ }
322
+ if (!existsSync(dirname(file)))
323
+ return;
324
+ this.watcher = watch(dirname(file), (_event, name) => {
325
+ if (name !== basename(file) || !existsSync(file) || this.watching !== file)
326
+ return;
327
+ this.watching = null;
328
+ this.follow(file);
329
+ this.soon();
330
+ });
316
331
  }
317
332
  catch {
318
333
  // the core reads every 2 s anyway
@@ -419,10 +434,10 @@ export class ClaudeCodeHarness {
419
434
  async newest() {
420
435
  const open = this.current();
421
436
  const file = open?.transcript && existsSync(open.transcript) ? open.transcript : (claudeSessions(this.ctx.cwd, this.ctx.home, this.ctx.env)[0]?.file ?? null);
437
+ this.follow(open?.transcript ?? file);
422
438
  if (!file)
423
439
  return null;
424
440
  const session = /([0-9a-f-]{36})\.jsonl$/i.exec(file)?.[1] ?? file;
425
- this.follow(file);
426
441
  const prompts = new Map();
427
442
  for (const [id, key] of this.known)
428
443
  if (key)
@@ -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
@@ -132,10 +132,12 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
132
132
  gavel message --conversation <C-12> (<text> | --text <words>) [--no-reply true] [--key <key>]
133
133
  reply in one; --no-reply true: a note, which never wakes
134
134
  them; --key: your own id for it, so a retry sends it once
135
- gavel message --item <W-12> (<text> | --text <words>) [--key <key>]
135
+ gavel message --item <W-12> (<text> | --text <words>) [--no-reply true] [--key <key>]
136
136
  write in a work item's thread, which all on it read
137
137
  gavel conversations [<C-12>] yours, or one with its messages (reads it)
138
- gavel thread <W-12> [join | leave] a work item's thread: who's in and its messages
138
+ gavel thread <W-12> [join | leave | add <agent>]
139
+ a work item's thread: who's in and its messages; add
140
+ (its worker or the coordinator) brings in a reviewer
139
141
  gavel wait-for-reply <C-12> [--timeout <seconds>]
140
142
  until there's a message to you in it (default 60)
141
143
  gavel chat [<text> | --text <words>] what your person wrote you in Gavel (each once), or
@@ -1151,9 +1153,12 @@ export function toRequest(argv) {
1151
1153
  case "message": {
1152
1154
  const text = readText(words("text", p, "what to say"));
1153
1155
  if (f.item) {
1154
- if (f.conversation || f["to-agent"] || f["to-person"] || f.decision !== undefined || f["no-reply"] !== undefined)
1155
- throw new UsageError("--item writes in a work item's thread: give it alone, with --key if you like");
1156
- return { method: "POST", path: `/v1/work/${encodeURIComponent(f.item)}/thread`, body: compact({ text, key: f.key }) };
1156
+ if (f.conversation || f["to-agent"] || f["to-person"] || f.decision !== undefined)
1157
+ throw new UsageError("--item writes in a work item's thread: give it alone, with --no-reply and --key if you like");
1158
+ const quiet = f["no-reply"];
1159
+ if (quiet !== undefined && quiet !== "true" && quiet !== "false")
1160
+ throw new UsageError("--no-reply is true or false");
1161
+ return { method: "POST", path: `/v1/work/${encodeURIComponent(f.item)}/thread`, body: compact({ text, noReply: quiet === undefined ? undefined : quiet === "true", key: f.key }) };
1157
1162
  }
1158
1163
  if ([f.conversation, f["to-agent"], f["to-person"]].filter(Boolean).length !== 1)
1159
1164
  throw new UsageError("give --to-agent or --to-person to start a conversation, --conversation to reply in one, or --item to write in a work item's thread");
@@ -1171,12 +1176,16 @@ export function toRequest(argv) {
1171
1176
  upTo(1);
1172
1177
  return { method: "GET", path: p[0] ? `/v1/conversations/${encodeURIComponent(p[0])}` : "/v1/conversations" };
1173
1178
  case "thread": {
1174
- upTo(2);
1179
+ upTo(3);
1175
1180
  const ref = encodeURIComponent(need(p[0], "the work item (W-12)"));
1176
1181
  if (p[1] === undefined)
1177
1182
  return { method: "GET", path: `/v1/work/${ref}/thread` };
1183
+ if (p[1] === "add")
1184
+ return { method: "POST", path: `/v1/work/${ref}/thread/join`, body: { agent: need(p[2], "the agent to add (its name or id)") } };
1178
1185
  if (p[1] !== "join" && p[1] !== "leave")
1179
- throw new UsageError("after the item, join or leave");
1186
+ throw new UsageError("after the item, join, leave or add <agent>");
1187
+ if (p[2] !== undefined)
1188
+ throw new UsageError(`${p[1]} takes nothing after it`);
1180
1189
  return { method: "POST", path: `/v1/work/${ref}/thread/${p[1]}` };
1181
1190
  }
1182
1191
  case "wait-for-reply":
@@ -1827,6 +1836,8 @@ export function wakeLine(item) {
1827
1836
  return item.type === "ready"
1828
1837
  ? `GAVEL_WAKE task ${item.ref} ready: what it waited on is finished: gavel work show ${item.ref}`
1829
1838
  : `GAVEL_WAKE task ${item.ref} ${item.type ?? "changed"} by someone else: gavel work show ${item.ref}`;
1839
+ case "replaced":
1840
+ 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`;
1830
1841
  default:
1831
1842
  return "GAVEL_WAKE something new: see gavel inbox";
1832
1843
  }
@@ -1842,7 +1853,7 @@ async function watch(token, as) {
1842
1853
  for (;;) {
1843
1854
  let res;
1844
1855
  try {
1845
- res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50&kinds=health,claim,work,drift,task${start ? "&start=true" : ""}`, {
1856
+ res = await fetch(`${base}/v1/inbox/watch?watch=${id}&timeout=50&kinds=health,claim,work,drift,task,replaced${start ? "&start=true" : ""}`, {
1846
1857
  headers: { authorization: `Bearer ${token}`, accept: "application/json", ...agentHeader(as) },
1847
1858
  });
1848
1859
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
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",