@getgavel/cli 0.1.6 → 0.1.7

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.
package/README.md CHANGED
@@ -37,3 +37,19 @@ gavel act --help # one command's usage
37
37
 
38
38
  `GAVEL_TOKEN` is your agent's token (pairing sets it up); `GAVEL_API_URL` defaults to
39
39
  `https://api.getgavel.ai`. How an agent works with Gavel: <https://getgavel.ai/agents.md>.
40
+
41
+ ## Your Claude Code or Codex chat, in Gavel
42
+
43
+ If your agent works in Claude Code or Codex on your laptop, run this in its folder, in a terminal
44
+ tab of its own, while you want your chat with it in Gavel:
45
+
46
+ ```sh
47
+ npx @getgavel/cli bridge
48
+ ```
49
+
50
+ With the chat on in Gavel, it shows that folder's newest session there, only the words you and your
51
+ agent wrote (never its tool calls, files or command output), and puts what you write in Gavel into
52
+ the session, as from you. A closed session gets a turn of its own, doing only what the session
53
+ already allows without asking. For an open Claude Code session it adds a small hook to the
54
+ project's `.claude/settings.local.json` that wakes it, and takes it out when you turn the chat off
55
+ or stop the bridge (Ctrl-C). `npx @getgavel/cli bridge show` prints exactly the words it would send.
@@ -0,0 +1,429 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, dirname, join, relative } from "node:path";
6
+ import { claudeOpen, claudeResume, claudeSessions, claudeSettingsFile, claudeWords, withWakeHook } from "./claude-code.js";
7
+ import { codexOpen, codexQueue, codexResume, codexSessions, codexWords } from "./codex.js";
8
+ import { apiFor, claudeSetups, codexSetups } from "./setup.js";
9
+ // `gavel bridge` (D-905): run by a person on their laptop, in the folder where their agent works
10
+ // (Claude Code or Codex), beside it. It shows the newest session's words in the person's Gavel chat
11
+ // with that agent, and puts what they write there into the session, as from them.
12
+ export const BRIDGE_HARNESSES = ["claude-code", "codex"];
13
+ // A message for the person at the terminal; exits 1.
14
+ export class BridgeError extends Error {
15
+ }
16
+ const NAMES = { "claude-code": "Claude Code", codex: "Codex" };
17
+ function sessionsHere(harness, ctx) {
18
+ return harness === "claude-code" ? claudeSessions(ctx.cwd, ctx.home, ctx.env) : codexSessions(ctx.cwd, ctx.home, ctx.env);
19
+ }
20
+ // The newest session here, as the bridge sends it: one thread per session.
21
+ function newestThread(harness, ctx) {
22
+ const newest = sessionsHere(harness, ctx)[0];
23
+ if (!newest)
24
+ return null;
25
+ const jsonl = readFileSync(newest.file, "utf8");
26
+ const messages = harness === "claude-code" ? claudeWords(jsonl) : codexWords(jsonl);
27
+ return { thread: `${harness}:${newest.id}`, label: `${NAMES[harness]} · ${basename(ctx.cwd)}`.slice(0, 80), session: newest.id, file: newest.file, messages };
28
+ }
29
+ const localSetups = (setups) => setups.filter((s) => s.where.endsWith("this folder"));
30
+ // Which software's agent works here: the one set up or with sessions in this folder.
31
+ function harnessHere(wanted, ctx) {
32
+ if (wanted)
33
+ return wanted;
34
+ const claude = localSetups(claudeSetups(ctx.cwd, ctx.home)).length > 0 || sessionsHere("claude-code", ctx).length > 0;
35
+ const codex = localSetups(codexSetups(ctx.cwd, ctx.home, ctx.env)).length > 0 || sessionsHere("codex", ctx).length > 0;
36
+ if (claude && codex)
37
+ throw new BridgeError("This folder has a Claude Code agent and a Codex agent: say which with --harness claude-code or --harness codex.");
38
+ if (claude)
39
+ return "claude-code";
40
+ if (codex)
41
+ return "codex";
42
+ throw new BridgeError("No Claude Code or Codex agent works in this folder: run the bridge where your agent works, after pairing it there (gavel pair <code>).");
43
+ }
44
+ function setupHere(harness, server, ctx) {
45
+ const setups = harness === "claude-code" ? claudeSetups(ctx.cwd, ctx.home) : codexSetups(ctx.cwd, ctx.home, ctx.env);
46
+ const named = server ? setups.filter((s) => s.server === server) : setups;
47
+ if (named.length === 1)
48
+ return named[0];
49
+ if (!setups.length)
50
+ throw new BridgeError(`No Gavel agent is set up for ${NAMES[harness]} here: pair it in this folder first (gavel pair <code>).`);
51
+ if (server)
52
+ throw new BridgeError(`No Gavel server named ${server} in ${NAMES[harness]}'s setup here. There: ${setups.map((s) => s.server).join(", ")}.`);
53
+ const local = localSetups(setups);
54
+ if (local.length === 1)
55
+ return local[0];
56
+ 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.`);
57
+ }
58
+ function call(api, method, path, body) {
59
+ const headers = { authorization: `Bearer ${api.token}`, accept: "application/json" };
60
+ if (api.as?.trim())
61
+ headers["x-gavel-agent"] = encodeURIComponent(api.as.trim());
62
+ if (body !== undefined)
63
+ headers["content-type"] = "application/json";
64
+ return fetch(api.base + path, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
65
+ }
66
+ async function whoAmI(api, setup) {
67
+ const res = await call(api, "GET", "/v1/me");
68
+ if (res.status === 401)
69
+ throw new BridgeError(`The agent's token in ${setup.where} no longer works: pair the agent again.`);
70
+ if (!res.ok)
71
+ throw new BridgeError(`Gavel answered ${res.status} to who this agent is: try again in a moment.`);
72
+ return (await res.json());
73
+ }
74
+ const asPrompt = (m) => (m.decision ? `About ${m.decision.ref}: ${m.decision.question}\n\n${m.text}` : m.text);
75
+ const clock = () => new Date().toTimeString().slice(0, 5);
76
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
77
+ const backoff = (failures) => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
78
+ const quote = (word) => `'${word.replace(/'/g, `'\\''`)}'`;
79
+ // The hook's command: this very gavel, by its own paths, so it needs nothing from npm or the PATH.
80
+ function wakeCommand(server, as) {
81
+ return [process.execPath, ...process.execArgv, process.argv[1]].map(quote).join(" ") + ` bridge wake --server ${quote(server)}${as ? ` --as ${quote(as)}` : ""}`;
82
+ }
83
+ function tracked(file, cwd) {
84
+ try {
85
+ execFileSync("git", ["ls-files", "--error-unmatch", file], { cwd, stdio: "ignore" });
86
+ return true;
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ // Inside a git work tree, a file git doesn't already ignore gets its .gitignore line.
93
+ function keepOutOfGit(file, cwd) {
94
+ try {
95
+ execFileSync("git", ["rev-parse", "--is-inside-work-tree"], { cwd, stdio: "ignore" });
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ try {
101
+ execFileSync("git", ["check-ignore", "-q", file], { cwd, stdio: "ignore" });
102
+ return null;
103
+ }
104
+ catch {
105
+ const gitignore = join(cwd, ".gitignore");
106
+ const text = existsSync(gitignore) ? readFileSync(gitignore, "utf8") : "";
107
+ appendFileSync(gitignore, `${text && !text.endsWith("\n") ? "\n" : ""}${file}\n`);
108
+ return `.gitignore has ${file}`;
109
+ }
110
+ }
111
+ // ---------- gavel bridge show ----------
112
+ function show(run, ctx) {
113
+ const harness = harnessHere(run.harness, ctx);
114
+ const thread = newestThread(harness, ctx);
115
+ if (!thread)
116
+ throw new BridgeError(`No ${NAMES[harness]} session in this folder yet.`);
117
+ const { file: _file, ...shown } = thread;
118
+ console.log(JSON.stringify({ harness, folder: ctx.cwd, ...shown }, null, 2));
119
+ return 0;
120
+ }
121
+ // ---------- gavel bridge ----------
122
+ async function bridge(run, ctx) {
123
+ const harness = harnessHere(run.harness, ctx);
124
+ const setup = setupHere(harness, run.server, ctx);
125
+ const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
126
+ const me = await whoAmI(api, setup);
127
+ const say = (line) => console.log(`${clock()} ${line}`);
128
+ say(`Gavel bridge for ${me.agent.name} (${NAMES[harness]}, ${setup.server}) in ${ctx.cwd}.`);
129
+ 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.`);
130
+ const id = randomUUID();
131
+ let on = null;
132
+ let stopping = false;
133
+ let thread = null;
134
+ let seen = "";
135
+ const sent = new Map(); // this thread's messages as Gavel has them
136
+ const joins = new Map(); // a delivered prompt → its Gavel message, until its local copy shows
137
+ const delivering = new Set();
138
+ const handled = new Set();
139
+ const left = new Set(); // waiting for the open session, said once each
140
+ const settings = claudeSettingsFile(ctx.cwd);
141
+ const settingsName = relative(ctx.cwd, settings);
142
+ let hooked = false;
143
+ const setHook = (want) => {
144
+ if (want === hooked)
145
+ return;
146
+ const existing = existsSync(settings) ? readFileSync(settings, "utf8") : null;
147
+ const next = withWakeHook(existing, want ? wakeCommand(setup.server, ctx.as) : null);
148
+ hooked = want;
149
+ if (next === existing || next === null)
150
+ return;
151
+ if (want && tracked(settingsName, ctx.cwd)) {
152
+ hooked = false;
153
+ 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.`);
154
+ return;
155
+ }
156
+ mkdirSync(dirname(settings), { recursive: true });
157
+ writeFileSync(settings, next);
158
+ if (want) {
159
+ const ignored = keepOutOfGit(settingsName, ctx.cwd);
160
+ 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}.)` : ""}`);
161
+ }
162
+ else
163
+ say(`Took Gavel's wake hook out of ${settingsName}.`);
164
+ };
165
+ let syncing = null;
166
+ const pushOnce = async () => {
167
+ const t = newestThread(harness, ctx);
168
+ if (!t || !on)
169
+ return;
170
+ const stat = statSync(t.file);
171
+ const mark = `${t.thread}:${stat.size}:${stat.mtimeMs}:${joins.size}`;
172
+ if (mark === seen)
173
+ return;
174
+ if (t.thread !== thread) {
175
+ thread = t.thread;
176
+ sent.clear();
177
+ }
178
+ const messages = t.messages
179
+ .filter((m) => sent.get(m.id) !== m.text)
180
+ .map((m) => {
181
+ const gavelId = m.side === "person" ? joins.get(m.text.trim()) : undefined;
182
+ if (gavelId)
183
+ joins.delete(m.text.trim());
184
+ return gavelId ? { ...m, gavelId } : m;
185
+ });
186
+ for (let i = 0; i < messages.length; i += 200) {
187
+ const part = messages.slice(i, i + 200);
188
+ const res = await call(api, "PUT", "/v1/agents/me/chat/transcript", { thread: t.thread, label: t.label, messages: part });
189
+ if (!res.ok)
190
+ throw new Error(`HTTP ${res.status} sending the session's words`);
191
+ if (!(await res.json()).on)
192
+ return;
193
+ for (const m of part)
194
+ sent.set(m.id, m.text);
195
+ }
196
+ seen = mark;
197
+ };
198
+ const push = () => (syncing ??= pushOnce()
199
+ .catch((err) => console.error(`gavel bridge: ${err instanceof Error ? err.message : String(err)}; trying again`))
200
+ .finally(() => (syncing = null)));
201
+ const note = async (text) => {
202
+ await push();
203
+ if (!thread)
204
+ return;
205
+ await call(api, "PUT", "/v1/agents/me/chat/transcript", { thread, messages: [{ id: `gavel:${randomUUID()}`, side: "gavel", text, at: new Date().toISOString() }] }).catch(() => undefined);
206
+ };
207
+ 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`));
208
+ const deliver = async (m) => {
209
+ delivering.add(m.id);
210
+ try {
211
+ const newest = sessionsHere(harness, ctx)[0] ?? null;
212
+ const prompt = asPrompt(m);
213
+ const into = newest ? "the newest session" : "a new session";
214
+ let result;
215
+ if (harness === "claude-code" && newest && (await claudeOpen(newest.id, ctx.cwd))) {
216
+ if (!left.has(m.id))
217
+ say(`${me.person.name} wrote in Gavel; your Claude Code session is open, so it hears it there${hooked ? "" : ", between tasks"}.`);
218
+ left.add(m.id);
219
+ return;
220
+ }
221
+ joins.set(prompt.trim(), m.id);
222
+ if (harness === "claude-code") {
223
+ say(`Putting ${me.person.name}'s message into ${into}…`);
224
+ result = await claudeResume(newest?.id ?? null, prompt, ctx.cwd);
225
+ }
226
+ else if (newest && (await codexOpen(newest.file))) {
227
+ say(`Putting ${me.person.name}'s message into your open Codex session, as its next message…`);
228
+ result = await codexQueue(newest.id, prompt, ctx.cwd);
229
+ }
230
+ else {
231
+ say(`Putting ${me.person.name}'s message into ${into}…`);
232
+ result = await codexResume(newest?.id ?? null, prompt, ctx.cwd);
233
+ }
234
+ handled.add(m.id);
235
+ if (result.ok) {
236
+ await read({ ids: [m.id] });
237
+ say(`Done: the answer shows in Gavel as it's written.`);
238
+ if (result.refused.length)
239
+ 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.`);
240
+ }
241
+ else {
242
+ joins.delete(prompt.trim());
243
+ await read({ ids: [], failed: [{ id: m.id, reason: result.reason }] });
244
+ say(`Couldn't: ${result.reason}`);
245
+ }
246
+ await push();
247
+ }
248
+ finally {
249
+ delivering.delete(m.id);
250
+ }
251
+ };
252
+ const stop = () => {
253
+ if (stopping)
254
+ return;
255
+ stopping = true;
256
+ try {
257
+ setHook(false);
258
+ }
259
+ catch (err) {
260
+ console.error(`gavel bridge: ${err instanceof Error ? err.message : String(err)}`);
261
+ }
262
+ say("Stopped.");
263
+ process.exit(0);
264
+ };
265
+ process.on("SIGINT", stop);
266
+ process.on("SIGTERM", stop);
267
+ const timer = setInterval(() => void push(), 2000);
268
+ let start = true;
269
+ let failures = 0;
270
+ try {
271
+ for (;;) {
272
+ let res;
273
+ try {
274
+ res = await call(api, "GET", `/v1/agents/me/chat?wait=30&bridge=${id}${start ? "&start=true" : ""}`);
275
+ }
276
+ catch (err) {
277
+ failures++;
278
+ console.error(`gavel bridge: ${err instanceof Error ? err.message : String(err)}; trying again`);
279
+ await pause(backoff(failures));
280
+ continue;
281
+ }
282
+ if (res.status === 409) {
283
+ say("Another bridge for this agent took over; this one stops.");
284
+ return 3;
285
+ }
286
+ if (res.status === 400 || res.status === 401 || res.status === 403 || res.status === 404) {
287
+ console.error(`gavel bridge: ${(await res.text()) || `HTTP ${res.status}`}`);
288
+ return 1;
289
+ }
290
+ if (!res.ok) {
291
+ failures++;
292
+ console.error(`gavel bridge: HTTP ${res.status}; trying again`);
293
+ await pause(backoff(failures));
294
+ continue;
295
+ }
296
+ failures = 0;
297
+ start = false;
298
+ const state = (await res.json());
299
+ if (state.on !== on) {
300
+ on = state.on;
301
+ if (on) {
302
+ say(`The chat is on: ${me.person.name} sees this folder's newest session in Gavel.`);
303
+ thread = null;
304
+ seen = "";
305
+ if (harness === "claude-code")
306
+ setHook(true);
307
+ await push();
308
+ }
309
+ else {
310
+ say(`The chat is off in Gavel: nothing is read or sent until ${me.person.name} turns it on again.`);
311
+ if (harness === "claude-code")
312
+ setHook(false);
313
+ }
314
+ }
315
+ if (!on)
316
+ continue;
317
+ for (const m of state.unread.filter((u) => !delivering.has(u.id) && !handled.has(u.id)))
318
+ await deliver(m);
319
+ // What's left waits for the open session to hear it, or to close: look again in a moment.
320
+ if (state.unread.some((u) => !handled.has(u.id)))
321
+ await pause(5000);
322
+ }
323
+ }
324
+ finally {
325
+ clearInterval(timer);
326
+ if (!stopping)
327
+ setHook(false);
328
+ }
329
+ }
330
+ // ---------- gavel bridge wake ----------
331
+ // Run by Claude Code as the wake hook (never by hand): waits for what the person writes in Gavel
332
+ // and wakes the session with it, exit code 2 and the words on stderr. One per session: a newer one
333
+ // takes over. It stays quiet (exit 0) when the chat is off, the session is gone or it's taken over,
334
+ // and never marks a message read for a session that isn't there to hear it.
335
+ async function wake(run, ctx) {
336
+ let input = {};
337
+ try {
338
+ input = JSON.parse(readFileSync(0, "utf8"));
339
+ }
340
+ catch {
341
+ // no hook input
342
+ }
343
+ const session = typeof input.session_id === "string" ? input.session_id : null;
344
+ const cwd = typeof input.cwd === "string" ? input.cwd : ctx.cwd;
345
+ if (!session)
346
+ return 0;
347
+ let setup;
348
+ try {
349
+ setup = setupHere("claude-code", run.server, { ...ctx, cwd });
350
+ }
351
+ catch {
352
+ return 0;
353
+ }
354
+ const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
355
+ const lock = join(tmpdir(), `gavel-wake-${session.replace(/[^A-Za-z0-9-]/g, "")}`);
356
+ const before = existsSync(lock) ? Number(readFileSync(lock, "utf8")) : 0;
357
+ if (before && before !== process.pid) {
358
+ try {
359
+ const command = execFileSync("ps", ["-p", String(before), "-o", "command="], { encoding: "utf8" });
360
+ if (/\bbridge wake\b/.test(command))
361
+ process.kill(before, "SIGTERM");
362
+ }
363
+ catch {
364
+ // gone already
365
+ }
366
+ }
367
+ writeFileSync(lock, String(process.pid));
368
+ const mine = () => existsSync(lock) && readFileSync(lock, "utf8") === String(process.pid);
369
+ const parent = process.ppid;
370
+ let person = "Your person";
371
+ try {
372
+ const res = await call(api, "GET", "/v1/me");
373
+ if (res.ok)
374
+ person = (await res.json()).person.name;
375
+ }
376
+ catch {
377
+ // named generically
378
+ }
379
+ let failures = 0;
380
+ while (mine() && process.ppid === parent) {
381
+ let res;
382
+ try {
383
+ res = await call(api, "GET", "/v1/agents/me/chat?wait=30");
384
+ }
385
+ catch {
386
+ failures++;
387
+ await pause(backoff(failures));
388
+ continue;
389
+ }
390
+ if (!res.ok) {
391
+ if (res.status < 500)
392
+ return 0;
393
+ failures++;
394
+ await pause(backoff(failures));
395
+ continue;
396
+ }
397
+ failures = 0;
398
+ const state = (await res.json());
399
+ if (!state.on)
400
+ return 0;
401
+ if (!state.unread.length)
402
+ continue;
403
+ if (!mine() || process.ppid !== parent || !(await claudeOpen(session, cwd)))
404
+ return 0;
405
+ const res2 = await call(api, "POST", "/v1/agents/me/chat/read", { ids: state.unread.map((m) => m.id) }).catch(() => null);
406
+ if (!res2?.ok)
407
+ continue;
408
+ const words = state.unread.map(asPrompt).join("\n\n---\n\n");
409
+ const text = words.length > 9000 ? `${words.slice(0, 9000)}… (cut: the rest is in Gavel's chat)` : words;
410
+ 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`);
411
+ return 2;
412
+ }
413
+ return 0;
414
+ }
415
+ export async function runBridge(run, ctx) {
416
+ try {
417
+ if (run.action === "show")
418
+ return show(run, ctx);
419
+ if (run.action === "wake")
420
+ return await wake(run, ctx);
421
+ return await bridge(run, ctx);
422
+ }
423
+ catch (err) {
424
+ if (!(err instanceof BridgeError))
425
+ throw err;
426
+ console.error(`gavel bridge: ${err.message}`);
427
+ return 1;
428
+ }
429
+ }
@@ -0,0 +1,186 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { cut } from "./words.js";
6
+ // Claude Code keeps each session as <its folder>/projects/<project>/<session id>.jsonl, the project
7
+ // its working folder's path with every character but a letter or a digit as a dash.
8
+ export function claudeSessions(cwd, home, env) {
9
+ const projects = join(env.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "projects");
10
+ const real = (path) => {
11
+ try {
12
+ return realpathSync(path);
13
+ }
14
+ catch {
15
+ return path;
16
+ }
17
+ };
18
+ const paths = new Set([cwd, real(cwd)]);
19
+ if (env.PWD && real(env.PWD) === real(cwd))
20
+ paths.add(env.PWD);
21
+ const sessions = new Map();
22
+ for (const path of paths) {
23
+ const dir = join(projects, path.replace(/[^A-Za-z0-9]/g, "-"));
24
+ if (!existsSync(dir))
25
+ continue;
26
+ for (const name of readdirSync(dir)) {
27
+ const id = /^([0-9a-f-]{36})\.jsonl$/i.exec(name)?.[1];
28
+ if (!id)
29
+ continue;
30
+ const file = join(dir, name);
31
+ sessions.set(id, { id, file, changedAt: statSync(file).mtimeMs });
32
+ }
33
+ }
34
+ return [...sessions.values()].sort((a, b) => b.changedAt - a.changedAt);
35
+ }
36
+ // What Claude Code writes in the person's place: slash commands and their output, shell mode's
37
+ // command and output, a note to memory, a reminder to the model, an interruption.
38
+ const MARKUP = /^<(command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat|bash-input|bash-stdout|bash-stderr|user-memory-input|system-reminder)>/;
39
+ const REMINDER = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
40
+ const INTERRUPTED = /^\[Request interrupted by user[^\]]*\]$/;
41
+ const personText = (parts) => parts
42
+ .map((t) => t.replace(REMINDER, "").trim())
43
+ .filter((t) => t && !MARKUP.test(t) && !INTERRUPTED.test(t))
44
+ .join("\n\n");
45
+ // A session's words: what the person typed (a prompt, or one queued while the agent worked) and the
46
+ // agent's text. Never a tool call or its result, thinking, a sub-agent's side chain, a compaction's
47
+ // summary or Claude Code's own messages. The agent's message comes in lines, one per part, under
48
+ // one id: they're joined.
49
+ export function claudeWords(jsonl) {
50
+ const out = [];
51
+ const agent = new Map();
52
+ for (const raw of jsonl.split("\n")) {
53
+ if (!raw.trim())
54
+ continue;
55
+ let line;
56
+ try {
57
+ line = JSON.parse(raw);
58
+ }
59
+ catch {
60
+ continue; // the line Claude Code is still writing
61
+ }
62
+ if (line.isSidechain || line.isMeta || line.isCompactSummary || line.isApiErrorMessage || !line.timestamp)
63
+ continue;
64
+ const content = line.message?.content;
65
+ if (line.type === "user" && line.message?.role === "user" && line.toolUseResult === undefined && line.uuid) {
66
+ const text = personText(typeof content === "string" ? [content] : (content ?? []).filter((b) => b.type === "text").map((b) => b.text ?? ""));
67
+ if (text)
68
+ out.push({ id: line.uuid, side: "person", text: cut(text), at: line.timestamp });
69
+ }
70
+ else if (line.type === "attachment" && line.attachment?.type === "queued_command" && typeof line.attachment.prompt === "string" && line.uuid) {
71
+ const text = personText([line.attachment.prompt]);
72
+ if (text)
73
+ out.push({ id: line.uuid, side: "person", text: cut(text), at: line.timestamp });
74
+ }
75
+ else if (line.type === "assistant" && line.message?.model !== "<synthetic>" && Array.isArray(content)) {
76
+ const id = line.message?.id ?? line.uuid;
77
+ const parts = content.filter((b) => b.type === "text").map((b) => (b.text ?? "").trim()).filter(Boolean);
78
+ if (!id || !parts.length)
79
+ continue;
80
+ const seen = agent.get(id);
81
+ if (seen) {
82
+ seen.parts.push(...parts);
83
+ out[seen.index] = { ...out[seen.index], text: cut(seen.parts.join("\n\n")) };
84
+ }
85
+ else {
86
+ agent.set(id, { index: out.length, parts });
87
+ out.push({ id, side: "agent", text: cut(parts.join("\n\n")), at: line.timestamp });
88
+ }
89
+ }
90
+ }
91
+ return out;
92
+ }
93
+ // Whether the session is open, in a terminal or in the background: Claude Code's own list of live
94
+ // sessions, its supported way to read them from outside. An older Claude Code without it counts as
95
+ // closed.
96
+ export async function claudeOpen(session, cwd) {
97
+ try {
98
+ const { stdout } = await promisify(execFile)("claude", ["agents", "--json"], { cwd, timeout: 30_000 });
99
+ const live = JSON.parse(stdout);
100
+ return Array.isArray(live) && live.some((s) => s?.sessionId === session);
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ const firstLine = (text) => text.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
107
+ // The person's words as a turn of their own in the session (or in a new one when there's none),
108
+ // with nobody there to answer a permission prompt: whatever would ask is refused, and the session's
109
+ // own permissions decide the rest (D-905, Gavel Master's call). The words go on stdin, never on the
110
+ // command line, where other processes see them.
111
+ export function claudeResume(session, text, cwd) {
112
+ return new Promise((resolve) => {
113
+ const args = ["-p", ...(session ? ["--resume", session] : []), "--permission-prompts", "none", "--output-format", "json"];
114
+ const child = spawn("claude", args, { cwd, stdio: ["pipe", "pipe", "pipe"] });
115
+ let out = "";
116
+ let err = "";
117
+ child.stdout.on("data", (d) => (out += d));
118
+ child.stderr.on("data", (d) => (err += d));
119
+ child.on("error", (e) => resolve({ ok: false, 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}` }));
120
+ child.on("close", (code) => {
121
+ let result = null;
122
+ try {
123
+ result = JSON.parse(out);
124
+ }
125
+ catch {
126
+ // no answer: the reason is on stderr
127
+ }
128
+ if (code === 0 && result && !result.is_error) {
129
+ const refused = [...new Set((result.permission_denials ?? []).map((d) => d?.tool_name).filter((n) => typeof n === "string"))];
130
+ return resolve({ ok: true, refused });
131
+ }
132
+ const said = (typeof result?.result === "string" ? firstLine(result.result) : "") || firstLine(err);
133
+ const reason = /unknown option.*permission-prompts/i.test(err)
134
+ ? "The laptop's Claude Code is too old for the bridge: run claude update there."
135
+ : said
136
+ ? `Claude Code said: ${said}`
137
+ : `Claude Code stopped without answering (code ${code}).`;
138
+ resolve({ ok: false, reason: reason.slice(0, 300) });
139
+ });
140
+ child.stdin.end(text);
141
+ });
142
+ }
143
+ // The wake hook, while the bridge is on: Claude Code runs it in the background as a session starts
144
+ // and after each turn, and it wakes the session, even idle, with what the person writes in Gavel
145
+ // (asyncRewake: exit code 2, its stderr shown to Claude). In the project's local settings, never a
146
+ // committed file.
147
+ export const claudeSettingsFile = (cwd) => join(cwd, ".claude", "settings.local.json");
148
+ const WAKE_EVENTS = ["SessionStart", "Stop"];
149
+ const WAKE_SECONDS = 24 * 60 * 60;
150
+ const isWake = (hook) => typeof hook.command === "string" && /\bbridge wake( |$)/.test(hook.command);
151
+ // The settings with the wake hook in (command) or out (null), everything else kept; the same text
152
+ // when nothing changes.
153
+ export function withWakeHook(existing, command) {
154
+ let settings = {};
155
+ if (existing?.trim()) {
156
+ try {
157
+ settings = JSON.parse(existing);
158
+ }
159
+ catch {
160
+ throw new Error(".claude/settings.local.json isn't plain JSON, so the bridge can't put its wake hook in it");
161
+ }
162
+ }
163
+ const hooks = { ...(settings.hooks ?? {}) };
164
+ let changed = false;
165
+ for (const event of Object.keys(hooks)) {
166
+ const groups = (hooks[event] ?? []).map((g) => ({ ...g, hooks: (g.hooks ?? []).filter((h) => !isWake(h)) }));
167
+ const kept = groups.filter((g) => g.hooks.length);
168
+ if (JSON.stringify(kept) !== JSON.stringify(hooks[event]))
169
+ changed = true;
170
+ if (kept.length)
171
+ hooks[event] = kept;
172
+ else
173
+ delete hooks[event];
174
+ }
175
+ if (command) {
176
+ for (const event of WAKE_EVENTS)
177
+ hooks[event] = [...(hooks[event] ?? []), { hooks: [{ type: "command", command, asyncRewake: true, timeout: WAKE_SECONDS }] }];
178
+ changed = true;
179
+ }
180
+ if (!changed)
181
+ return existing;
182
+ const { hooks: _old, ...rest } = settings;
183
+ const next = Object.keys(hooks).length ? { ...rest, hooks } : rest;
184
+ const text = `${JSON.stringify(next, null, 2)}\n`;
185
+ return text === existing ? existing : text;
186
+ }
@@ -0,0 +1,176 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { closeSync, existsSync, openSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { cut } from "./words.js";
6
+ function realpath(path) {
7
+ try {
8
+ return realpathSync(path);
9
+ }
10
+ catch {
11
+ return path;
12
+ }
13
+ }
14
+ // A rollout's first line, its session_meta, which may carry long instructions.
15
+ function firstLine(file) {
16
+ const fd = openSync(file, "r");
17
+ try {
18
+ let text = "";
19
+ const chunk = Buffer.alloc(64 * 1024);
20
+ for (let read = 0; text.length < 4 * 1024 * 1024;) {
21
+ const n = readSync(fd, chunk, 0, chunk.length, read);
22
+ if (!n)
23
+ break;
24
+ read += n;
25
+ text += chunk.subarray(0, n).toString("utf8");
26
+ const end = text.indexOf("\n");
27
+ if (end >= 0)
28
+ return text.slice(0, end);
29
+ }
30
+ return text || null;
31
+ }
32
+ finally {
33
+ closeSync(fd);
34
+ }
35
+ }
36
+ // A rollout's folder and whether it's a top-level session (a sub-agent's names its parent: an object).
37
+ const metas = new Map();
38
+ function metaOf(file) {
39
+ if (!metas.has(file)) {
40
+ let meta = null;
41
+ try {
42
+ const line = JSON.parse(firstLine(file) ?? "");
43
+ const p = line.payload;
44
+ if (line.type === "session_meta" && typeof p?.id === "string" && typeof p.cwd === "string")
45
+ meta = { id: p.id, cwd: p.cwd, topLevel: typeof p.source !== "object" };
46
+ }
47
+ catch {
48
+ // not a rollout we can read
49
+ }
50
+ metas.set(file, meta);
51
+ }
52
+ return metas.get(file);
53
+ }
54
+ const DAYS = 31;
55
+ const desc = (dir) => (existsSync(dir) ? readdirSync(dir).filter((n) => /^\d+$/.test(n)).sort().reverse() : []);
56
+ // Codex keeps each session as <its folder>/sessions/YYYY/MM/DD/rollout-…-<id>.jsonl, the session's
57
+ // working folder in its first line. The last month's top-level sessions of this folder, newest
58
+ // first; an old, compressed one (.jsonl.zst) isn't read.
59
+ export function codexSessions(cwd, home, env) {
60
+ const root = join(env.CODEX_HOME ?? join(home, ".codex"), "sessions");
61
+ const here = new Set([cwd, realpath(cwd)]);
62
+ const found = [];
63
+ let days = 0;
64
+ for (const year of desc(root))
65
+ for (const month of desc(join(root, year)))
66
+ for (const day of desc(join(root, year, month))) {
67
+ if (days++ >= DAYS)
68
+ return found.sort((a, b) => b.changedAt - a.changedAt);
69
+ const dir = join(root, year, month, day);
70
+ for (const name of readdirSync(dir)) {
71
+ if (!/^rollout-.*\.jsonl$/.test(name))
72
+ continue;
73
+ const file = join(dir, name);
74
+ const meta = metaOf(file);
75
+ if (meta?.topLevel && (here.has(meta.cwd) || here.has(realpath(meta.cwd))))
76
+ found.push({ id: meta.id, file, changedAt: statSync(file).mtimeMs });
77
+ }
78
+ }
79
+ return found.sort((a, b) => b.changedAt - a.changedAt);
80
+ }
81
+ // What Codex puts in the person's place: its context, instructions, a shell command typed with !.
82
+ const MARKED = /^<(environment_context|user_instructions|user_shell_command|turn_aborted)>/;
83
+ // A session's words: what the person typed (user_message) and the agent's messages (agent_message),
84
+ // as Codex shows them. Never its instructions or context, reasoning, a tool call or its output: the
85
+ // response items that carry them aren't read at all.
86
+ export function codexWords(jsonl) {
87
+ const out = [];
88
+ const atTime = new Map();
89
+ for (const raw of jsonl.split("\n")) {
90
+ if (!raw.trim())
91
+ continue;
92
+ let line;
93
+ try {
94
+ line = JSON.parse(raw);
95
+ }
96
+ catch {
97
+ continue; // the line Codex is still writing
98
+ }
99
+ if (line.type !== "event_msg" || !line.timestamp || typeof line.payload?.message !== "string")
100
+ continue;
101
+ const text = line.payload.message.trim();
102
+ const side = line.payload.type === "user_message" && !MARKED.test(text) ? "person" : line.payload.type === "agent_message" ? "agent" : null;
103
+ if (!side || !text)
104
+ continue;
105
+ const n = atTime.get(line.timestamp) ?? 0;
106
+ atTime.set(line.timestamp, n + 1);
107
+ out.push({ id: `${line.timestamp}#${n}`, side, text: cut(text), at: line.timestamp });
108
+ }
109
+ return out;
110
+ }
111
+ // Whether the session is open: a running Codex (in a terminal or exec) holds its rollout open
112
+ // while it writes.
113
+ export async function codexOpen(file) {
114
+ try {
115
+ const { stdout } = await promisify(execFile)("lsof", ["-t", "--", file], { timeout: 15_000 });
116
+ return stdout.trim().length > 0;
117
+ }
118
+ catch {
119
+ return false;
120
+ }
121
+ }
122
+ const firstLineOf = (text) => text.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
123
+ const notStarted = (e) => (e.code === "ENOENT" ? "Codex's codex command isn't on the laptop's PATH where the bridge runs." : `Codex didn't start: ${e.message}`);
124
+ // Into an open session: Codex's own queue, which the running session takes as its next message.
125
+ // It takes the words only on its command line, for the moment it runs.
126
+ export async function codexQueue(session, text, cwd) {
127
+ try {
128
+ await promisify(execFile)("codex", ["queue", "--thread", session, "--message", text], { cwd, timeout: 60_000 });
129
+ return { ok: true, refused: [] };
130
+ }
131
+ catch (err) {
132
+ const e = err;
133
+ if (e.code === "ENOENT")
134
+ return { ok: false, reason: notStarted(e) };
135
+ return { ok: false, reason: `Codex said: ${firstLineOf(e.stderr ?? "") || e.message}`.slice(0, 300) };
136
+ }
137
+ }
138
+ // A closed session gets a turn of its own (a new session when there's none), in its own sandbox:
139
+ // exec asks nobody, so what would need approval isn't done, and comes back as refused. The words go
140
+ // on stdin, never on the command line.
141
+ export function codexResume(session, text, cwd) {
142
+ return new Promise((resolve) => {
143
+ const args = ["exec", ...(session ? ["resume", session] : []), "--json", "-"];
144
+ const child = spawn("codex", args, { cwd, stdio: ["pipe", "pipe", "pipe"] });
145
+ let out = "";
146
+ let err = "";
147
+ child.stdout.on("data", (d) => (out += d));
148
+ child.stderr.on("data", (d) => (err += d));
149
+ child.on("error", (e) => resolve({ ok: false, reason: notStarted(e) }));
150
+ child.on("close", (code) => {
151
+ let failed = null;
152
+ let commands = 0;
153
+ let changes = 0;
154
+ for (const raw of out.split("\n")) {
155
+ let event;
156
+ try {
157
+ event = JSON.parse(raw);
158
+ }
159
+ catch {
160
+ continue;
161
+ }
162
+ if (event.type === "turn.failed")
163
+ failed = typeof event.error?.message === "string" ? event.error.message : "the turn failed";
164
+ if (event.type === "item.completed" && event.item?.status === "declined")
165
+ event.item.type === "file_change" ? changes++ : commands++;
166
+ }
167
+ const some = (n, one, many) => (n === 1 ? one : n ? `${n} ${many}` : null);
168
+ const refused = [some(commands, "a command", "commands"), some(changes, "a file change", "file changes")].filter((r) => r !== null);
169
+ if (code === 0 && !failed)
170
+ return resolve({ ok: true, refused });
171
+ const said = failed ?? firstLineOf(err);
172
+ resolve({ ok: false, reason: (said ? `Codex said: ${said}` : `Codex stopped without answering (code ${code}).`).slice(0, 300) });
173
+ });
174
+ child.stdin.end(text);
175
+ });
176
+ }
@@ -0,0 +1,81 @@
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ const bearer = (value) => (typeof value === "string" ? (/^Bearer (gvl_\S+)$/.exec(value.trim())?.[1] ?? null) : null);
4
+ const isGavel = (name) => name === "gavel" || name.startsWith("gavel-");
5
+ function realpath(path) {
6
+ try {
7
+ return realpathSync(path);
8
+ }
9
+ catch {
10
+ return path;
11
+ }
12
+ }
13
+ // Claude Code keeps both scopes in its .claude.json: this folder's own (local, an agent's) under
14
+ // projects, the user's (a fleet's) at the top.
15
+ export function claudeSetups(cwd, home) {
16
+ const file = join(home, ".claude.json");
17
+ if (!existsSync(file))
18
+ return [];
19
+ let json;
20
+ try {
21
+ json = JSON.parse(readFileSync(file, "utf8"));
22
+ }
23
+ catch {
24
+ return [];
25
+ }
26
+ const local = (json.projects?.[cwd] ?? json.projects?.[realpath(cwd)])?.mcpServers;
27
+ const out = [];
28
+ for (const [scope, servers] of [
29
+ ["this folder", local],
30
+ ["all folders", json.mcpServers],
31
+ ]) {
32
+ for (const [name, entry] of Object.entries(servers ?? {})) {
33
+ const token = bearer(entry?.headers?.Authorization);
34
+ if (isGavel(name) && token && typeof entry?.url === "string")
35
+ out.push({ server: name, url: entry.url, token, where: `Claude Code's setup for ${scope}` });
36
+ }
37
+ }
38
+ return out;
39
+ }
40
+ // [mcp_servers.<name>] and its http_headers table, the name bare or quoted.
41
+ const TABLE = /^\s*\[\s*mcp_servers\.(?:"([^"]+)"|([A-Za-z0-9_-]+))(\.http_headers)?\s*\]\s*$/;
42
+ // Codex: the project's .codex/config.toml (an agent's), then the user's (a fleet's).
43
+ export function codexSetups(cwd, home, env) {
44
+ const out = [];
45
+ for (const [file, scope] of [
46
+ [join(cwd, ".codex", "config.toml"), "this folder"],
47
+ [join(env.CODEX_HOME ?? join(home, ".codex"), "config.toml"), "all folders"],
48
+ ]) {
49
+ if (!existsSync(file))
50
+ continue;
51
+ const tables = new Map();
52
+ let current = null;
53
+ for (const line of readFileSync(file, "utf8").split("\n")) {
54
+ if (/^\s*\[/.test(line)) {
55
+ const m = TABLE.exec(line);
56
+ const name = m ? (m[1] ?? m[2]) : null;
57
+ current = name && isGavel(name) ? (tables.get(name) ?? tables.set(name, []).get(name)) : null;
58
+ }
59
+ else
60
+ current?.push(line);
61
+ }
62
+ for (const [name, lines] of tables) {
63
+ const text = lines.join("\n");
64
+ const url = /^\s*url\s*=\s*"([^"]+)"/m.exec(text)?.[1];
65
+ const token = /"?Authorization"?\s*=\s*"Bearer (gvl_[^"\s]+)"/.exec(text)?.[1];
66
+ if (url && token)
67
+ out.push({ server: name, url, token, where: `Codex's setup for ${scope}` });
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+ // Gavel's API, from the setup's own address: mcp.<host> answers as api.<host>, a local server as
73
+ // itself. GAVEL_API_URL wins.
74
+ export function apiFor(setup, env) {
75
+ if (env.GAVEL_API_URL)
76
+ return env.GAVEL_API_URL.replace(/\/+$/, "");
77
+ const url = new URL(setup.url);
78
+ if (url.hostname.startsWith("mcp."))
79
+ url.hostname = `api.${url.hostname.slice(4)}`;
80
+ return url.origin;
81
+ }
@@ -0,0 +1,4 @@
1
+ // Gavel keeps a message's first 100,000 characters: a longer one is cut here, and says so.
2
+ const MAX = 100_000;
3
+ const CUT = "… (cut)";
4
+ export const cut = (text) => (text.length > MAX ? text.slice(0, MAX - CUT.length) + CUT : text);
package/dist/gavel.js CHANGED
@@ -8,11 +8,21 @@ import { createHash, randomUUID } from "node:crypto";
8
8
  import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
9
9
  import { homedir, hostname } from "node:os";
10
10
  import { basename, dirname, extname, join } from "node:path";
11
+ import { BRIDGE_HARNESSES, runBridge } from "./bridge/bridge.js";
11
12
  const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
12
13
 
13
14
  gavel pair <code> [--harness cursor|claude-code|codex|other] [--machine <name>]
14
15
  redeem your person's pairing code and write your setup
15
16
  (no GAVEL_TOKEN needed; never prints the token)
17
+ gavel bridge [--harness claude-code|codex] [--server <name>]
18
+ run by a person in their agent's folder, beside it, until
19
+ stopped: its newest Claude Code or Codex session's words in
20
+ their Gavel chat with it, and what they write there put into
21
+ it (no GAVEL_TOKEN: it uses the agent's own setup there)
22
+ gavel bridge show [--harness claude-code|codex]
23
+ the words it would send from the newest session here; sends
24
+ nothing
25
+ gavel bridge wake [--server <name>] the bridge's wake hook, which Claude Code runs (not by hand)
16
26
  gavel search (<words> | --query <words>) [--area <slug>] [--status open|decided|any] [--limit <n>]
17
27
  gavel ask --file decision.json the decision, as MCP ask's input
18
28
  gavel revise <D-12> --file decision.json a draft the editor sent back, fixed (the whole ask again)
@@ -33,10 +43,12 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
33
43
  gavel act <D-12> (<note> | --note <words>)
34
44
  what you did with the answer
35
45
  gavel inbox what's waiting on you
36
- gavel status (<text> | --text <words>) [--folders <a,b>] [--state working|blocked|idle] [--issue <MA-482>]
37
- [--waiting-on <email>]
38
- what you're doing now, in plain words ("" clears it);
39
- --waiting-on names the person you're blocked on
46
+ gavel status (<title> | --text <words>) [--description <words>] [--folders <a,b>]
47
+ [--state working|blocked|idle] [--issue <MA-482>] [--waiting-on <email or agent>]
48
+ what you're doing now: a title of two to four words in
49
+ title case ("Privacy Page & Terms"; "" clears it), and a
50
+ sentence or two in --description; --waiting-on names the
51
+ person or agent you're blocked on
40
52
  gavel message (--to-agent <id> | --to-person <email>) (<text> | --text <words>) [--decision <D-12>]
41
53
  start a conversation with another agent
42
54
  gavel message --conversation <C-12> (<text> | --text <words>)
@@ -44,10 +56,12 @@ const USAGE = `gavel: Gavel from the command line (https://getgavel.ai/agents)
44
56
  gavel conversations [<C-12>] yours, or one with its messages (reads it)
45
57
  gavel wait-for-reply <C-12> [--timeout <seconds>]
46
58
  until there's a message to you in it (default 60)
59
+ gavel chat [<text> | --text <words>] what your person wrote you in Gavel (each once), or
60
+ with text your answer to them, shown in their chat
47
61
  gavel watch runs until stopped: one GAVEL_WAKE line per new
48
- message, request, decision to decide, answer or
49
- folder clash, and nothing else (run it in the
50
- background; one per agent)
62
+ message, request, decision to decide, answer,
63
+ folder clash or chat from your person, and nothing
64
+ else (run it in the background; one per agent)
51
65
  gavel log --question <q> --outcome <o> --reason <why> [--area <slug>] [--trust <id>] [--file context.json]
52
66
  gavel log-answer --question <q> --answer <what they decided> [--note <their why>] [--area <slug>]
53
67
  [--file context.json]
@@ -81,6 +95,7 @@ GAVEL_AGENT (instead of --as).`;
81
95
  // refused with that usage, never dropped.
82
96
  const FLAGS = {
83
97
  pair: ["harness", "machine"],
98
+ bridge: ["harness", "server"],
84
99
  search: ["query", "area", "status", "limit"],
85
100
  ask: ["file"],
86
101
  revise: ["file"],
@@ -93,10 +108,11 @@ const FLAGS = {
93
108
  answer: ["response"],
94
109
  act: ["note"],
95
110
  inbox: [],
96
- status: ["text", "folders", "state", "issue", "waiting-on"],
111
+ status: ["text", "description", "folders", "state", "issue", "waiting-on"],
97
112
  message: ["to-agent", "to-person", "conversation", "text", "decision"],
98
113
  conversations: [],
99
114
  "wait-for-reply": ["timeout"],
115
+ chat: ["text"],
100
116
  watch: [],
101
117
  log: ["question", "outcome", "reason", "area", "trust", "file"],
102
118
  "log-answer": ["question", "answer", "note", "area", "file"],
@@ -254,6 +270,16 @@ export function toRequest(argv) {
254
270
  throw new UsageError(`--harness is one of ${HARNESSES.join(", ")}`);
255
271
  return { pair: { code: need(p.join(""), "the pairing code (like 4F7K-9QX2)"), harness, machine: f.machine } };
256
272
  }
273
+ case "bridge": {
274
+ upTo(1);
275
+ const action = p[0] ?? "run";
276
+ if (action !== "run" && action !== "show" && action !== "wake")
277
+ throw new UsageError(`bridge doesn't take "${action}"`);
278
+ const harness = f.harness;
279
+ if (harness !== undefined && !BRIDGE_HARNESSES.includes(harness))
280
+ throw new UsageError(`--harness is one of ${BRIDGE_HARNESSES.join(", ")}`);
281
+ return { bridge: { action, harness, server: f.server } };
282
+ }
257
283
  case "watch":
258
284
  upTo(0);
259
285
  return { watch: true };
@@ -297,6 +323,14 @@ export function toRequest(argv) {
297
323
  case "inbox":
298
324
  upTo(0);
299
325
  return { method: "GET", path: "/v1/inbox" };
326
+ case "chat": {
327
+ if (f.text !== undefined && p.length)
328
+ throw new UsageError("give your answer once: as words or as --text");
329
+ const said = f.text ?? (p.length ? p.join(" ") : undefined);
330
+ if (said === undefined)
331
+ return { method: "POST", path: "/v1/agents/me/chat/take" };
332
+ return { method: "POST", path: "/v1/agents/me/chat/messages", body: { text: readText(said) } };
333
+ }
300
334
  case "status": {
301
335
  if (f.text !== undefined && p.length)
302
336
  throw new UsageError("give what you're doing once: as words or as --text");
@@ -304,7 +338,8 @@ export function toRequest(argv) {
304
338
  if (said === undefined)
305
339
  throw new UsageError('missing what you\'re doing now (or "" to clear it)');
306
340
  const folders = f.folders?.split(",").map((s) => s.trim()).filter(Boolean);
307
- return { method: "PATCH", path: "/v1/agents/me/status", body: compact({ text: readText(said) || null, folders, state: f.state, linearIssue: f.issue, waitingOn: f["waiting-on"] }) };
341
+ const description = f.description === undefined ? undefined : readText(f.description);
342
+ return { method: "PATCH", path: "/v1/agents/me/status", body: compact({ text: readText(said) || null, description, folders, state: f.state, linearIssue: f.issue, waitingOn: f["waiting-on"] }) };
308
343
  }
309
344
  case "message": {
310
345
  const text = readText(words("text", p, "what to say"));
@@ -733,6 +768,8 @@ export function wakeLine(item) {
733
768
  return item.type === "under"
734
769
  ? "GAVEL_WAKE clash between agents under you: see gavel inbox, then tell one of them who gets the folder"
735
770
  : "GAVEL_WAKE clash in your folders: see gavel inbox, and wait for the agent above to say who gets it";
771
+ case "chat":
772
+ return "GAVEL_WAKE chat: your person wrote to you in Gavel: read it with gavel chat";
736
773
  }
737
774
  }
738
775
  const backoff = (failures) => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
@@ -801,6 +838,8 @@ async function main(argvIn) {
801
838
  }
802
839
  if ("pair" in request)
803
840
  return pair(request.pair);
841
+ if ("bridge" in request)
842
+ return runBridge(request.bridge, { cwd: process.cwd(), home: homedir(), env: process.env, as });
804
843
  const token = process.env.GAVEL_TOKEN;
805
844
  if (!token) {
806
845
  console.error("gavel: set GAVEL_TOKEN to your agent token (gvl_agent_…)");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getgavel/cli",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
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",
@@ -14,7 +14,7 @@
14
14
  "gavel": "dist/gavel.js"
15
15
  },
16
16
  "files": [
17
- "dist/gavel.js"
17
+ "dist"
18
18
  ],
19
19
  "engines": {
20
20
  "node": ">=24"