@getgavel/cli 0.1.15 → 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.
- package/.claude-plugin/plugin.json +9 -0
- package/README.md +1 -0
- package/dist/bridge/background.js +397 -0
- package/dist/bridge/bridge.js +324 -247
- package/dist/bridge/claude-code.js +0 -96
- package/dist/bridge/claude-live.js +625 -0
- package/dist/bridge/codex-app.js +135 -0
- package/dist/bridge/codex.js +440 -77
- package/dist/bridge/harness.js +1 -0
- package/dist/bridge/service.js +134 -0
- package/dist/bridge/setup.js +27 -18
- package/dist/bridge/websocket.js +166 -0
- package/dist/gavel.js +251 -42
- package/dist/hook.js +67 -7
- package/dist/output.js +14 -0
- package/hooks/hooks.json +30 -0
- package/package.json +5 -2
- package/skills/gavel/SKILL.md +30 -0
package/dist/bridge/bridge.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { execFileSync } from "node:child_process";
|
|
2
1
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import {
|
|
2
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
4
3
|
import { tmpdir } from "node:os";
|
|
5
|
-
import { basename,
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
4
|
+
import { basename, join } from "node:path";
|
|
5
|
+
import { jsonText } from "../output.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";
|
|
8
10
|
import { apiFor, claudeSetups, codexSetups } from "./setup.js";
|
|
9
11
|
// `gavel bridge` (D-905): run by a person on their laptop, in the folder where their agent works
|
|
10
12
|
// (Claude Code or Codex), beside it. It shows the newest session's words in the person's Gavel chat
|
|
@@ -17,14 +19,11 @@ const NAMES = { "claude-code": "Claude Code", codex: "Codex" };
|
|
|
17
19
|
function sessionsHere(harness, ctx) {
|
|
18
20
|
return harness === "claude-code" ? claudeSessions(ctx.cwd, ctx.home, ctx.env) : codexSessions(ctx.cwd, ctx.home, ctx.env);
|
|
19
21
|
}
|
|
20
|
-
//
|
|
21
|
-
function
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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 };
|
|
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) });
|
|
28
27
|
}
|
|
29
28
|
const localSetups = (setups) => setups.filter((s) => s.where.endsWith("this folder"));
|
|
30
29
|
// Which software's agent works here: the one set up or with sessions in this folder.
|
|
@@ -55,8 +54,8 @@ function setupHere(harness, server, ctx) {
|
|
|
55
54
|
return local[0];
|
|
56
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.`);
|
|
57
56
|
}
|
|
58
|
-
function call(api, method, path, body) {
|
|
59
|
-
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 };
|
|
60
59
|
if (api.as?.trim())
|
|
61
60
|
headers["x-gavel-agent"] = encodeURIComponent(api.as.trim());
|
|
62
61
|
if (body !== undefined)
|
|
@@ -71,121 +70,104 @@ async function whoAmI(api, setup) {
|
|
|
71
70
|
throw new BridgeError(`Gavel answered ${res.status} to who this agent is: try again in a moment.`);
|
|
72
71
|
return (await res.json());
|
|
73
72
|
}
|
|
74
|
-
const asPrompt = (m) => (m.decision ? `About ${m.decision.ref}: ${m.decision.question}\n\n${m.text}` : m.text);
|
|
75
73
|
const clock = () => new Date().toTimeString().slice(0, 5);
|
|
76
74
|
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
77
75
|
const backoff = (failures) => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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) {
|
|
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;
|
|
94
81
|
try {
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
catch {
|
|
98
|
-
return null;
|
|
82
|
+
shown = await h.newest();
|
|
99
83
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
return null;
|
|
84
|
+
catch (err) {
|
|
85
|
+
throw new BridgeError(err instanceof Error ? err.message : String(err));
|
|
103
86
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const text = existsSync(gitignore) ? readFileSync(gitignore, "utf8") : "";
|
|
107
|
-
appendFileSync(gitignore, `${text && !text.endsWith("\n") ? "\n" : ""}${file}\n`);
|
|
108
|
-
return `.gitignore has ${file}`;
|
|
87
|
+
finally {
|
|
88
|
+
await h.close();
|
|
109
89
|
}
|
|
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)
|
|
90
|
+
if (!shown)
|
|
116
91
|
throw new BridgeError(`No ${NAMES[harness]} session in this folder yet.`);
|
|
117
|
-
|
|
118
|
-
console.log(JSON.stringify({ harness, folder: ctx.cwd, ...shown }, null, 2));
|
|
92
|
+
console.log(jsonText({ harness, folder: ctx.cwd, ...shown }));
|
|
119
93
|
return 0;
|
|
120
94
|
}
|
|
121
95
|
// ---------- gavel bridge ----------
|
|
122
96
|
async function bridge(run, ctx) {
|
|
123
97
|
const harness = harnessHere(run.harness, ctx);
|
|
124
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) {
|
|
125
132
|
const api = { base: apiFor(setup, ctx.env), token: setup.token, as: ctx.as };
|
|
126
133
|
const me = await whoAmI(api, setup);
|
|
134
|
+
if (h instanceof ClaudeCodeHarness)
|
|
135
|
+
h.setPerson(me.person.name);
|
|
127
136
|
const say = (line) => console.log(`${clock()} ${line}`);
|
|
128
|
-
say(`Gavel bridge for ${me.agent.name} (${
|
|
129
|
-
say(`While ${me.person.name} keeps the chat on in Gavel, this folder's newest ${
|
|
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.`);
|
|
130
139
|
const id = randomUUID();
|
|
131
140
|
let on = null;
|
|
132
141
|
let stopping = false;
|
|
133
142
|
let thread = null;
|
|
134
|
-
let
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const
|
|
143
|
+
let state = null;
|
|
144
|
+
let liveRoute = true;
|
|
145
|
+
let outgoing = [];
|
|
146
|
+
const sent = new Map();
|
|
138
147
|
const handled = new Set();
|
|
139
|
-
const
|
|
140
|
-
const
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
-
// Claude Code reads it whenever it likes: it changes whole, through a temp file and a rename.
|
|
158
|
-
const temp = `${settings}.${process.pid}.tmp`;
|
|
159
|
-
writeFileSync(temp, next);
|
|
160
|
-
renameSync(temp, settings);
|
|
161
|
-
if (want) {
|
|
162
|
-
const ignored = keepOutOfGit(settingsName, ctx.cwd);
|
|
163
|
-
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}.)` : ""}`);
|
|
164
|
-
}
|
|
165
|
-
else
|
|
166
|
-
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;
|
|
167
157
|
};
|
|
168
158
|
let syncing = null;
|
|
169
159
|
const pushOnce = async () => {
|
|
170
|
-
|
|
171
|
-
if (!t || !on)
|
|
160
|
+
if (!on)
|
|
172
161
|
return;
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
if (
|
|
162
|
+
const t = await h.newest();
|
|
163
|
+
trouble = "";
|
|
164
|
+
if (!t || !on)
|
|
176
165
|
return;
|
|
177
166
|
if (t.thread !== thread) {
|
|
178
167
|
thread = t.thread;
|
|
179
168
|
sent.clear();
|
|
180
169
|
}
|
|
181
|
-
const messages = t.messages
|
|
182
|
-
.filter((m) => sent.get(m.id) !== m.text)
|
|
183
|
-
.map((m) => {
|
|
184
|
-
const gavelId = m.side === "person" ? joins.get(m.text.trim()) : undefined;
|
|
185
|
-
if (gavelId)
|
|
186
|
-
joins.delete(m.text.trim());
|
|
187
|
-
return gavelId ? { ...m, gavelId } : m;
|
|
188
|
-
});
|
|
170
|
+
const messages = t.messages.filter((m) => sent.get(m.id) !== sentKey(m));
|
|
189
171
|
for (let i = 0; i < messages.length; i += 200) {
|
|
190
172
|
const part = messages.slice(i, i + 200);
|
|
191
173
|
const res = await call(api, "PUT", "/v1/agents/me/chat/transcript", { thread: t.thread, label: t.label, messages: part });
|
|
@@ -194,84 +176,242 @@ async function bridge(run, ctx) {
|
|
|
194
176
|
if (!(await res.json()).on)
|
|
195
177
|
return;
|
|
196
178
|
for (const m of part)
|
|
197
|
-
sent.set(m.id, m
|
|
179
|
+
sent.set(m.id, sentKey(m));
|
|
198
180
|
}
|
|
199
|
-
seen = mark;
|
|
200
181
|
};
|
|
201
182
|
const push = () => (syncing ??= pushOnce()
|
|
202
|
-
.catch((err) =>
|
|
183
|
+
.catch((err) => complain(`${err instanceof Error ? err.message : String(err)}; trying again`))
|
|
203
184
|
.finally(() => (syncing = null)));
|
|
204
|
-
|
|
185
|
+
// After whatever push is going: one that surely holds what changed before it was asked for.
|
|
186
|
+
const pushAfter = async () => {
|
|
187
|
+
await syncing;
|
|
205
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();
|
|
206
199
|
if (!thread)
|
|
207
200
|
return;
|
|
208
201
|
await call(api, "PUT", "/v1/agents/me/chat/transcript", { thread, messages: [{ id: `gavel:${randomUUID()}`, side: "gavel", text, at: new Date().toISOString() }] }).catch(() => undefined);
|
|
209
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);
|
|
210
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
|
+
};
|
|
211
256
|
const deliver = async (m) => {
|
|
212
|
-
delivering.add(m.id);
|
|
213
257
|
try {
|
|
214
|
-
const
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
let result;
|
|
218
|
-
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") {
|
|
219
261
|
if (!left.has(m.id))
|
|
220
|
-
say(
|
|
262
|
+
say(result.say);
|
|
221
263
|
left.add(m.id);
|
|
222
264
|
return;
|
|
223
265
|
}
|
|
224
|
-
joins.set(prompt.trim(), m.id);
|
|
225
|
-
if (harness === "claude-code") {
|
|
226
|
-
say(`Putting ${me.person.name}'s message into ${into}…`);
|
|
227
|
-
result = await claudeResume(newest?.id ?? null, prompt, ctx.cwd);
|
|
228
|
-
}
|
|
229
|
-
else if (newest && (await codexOpen(newest.file))) {
|
|
230
|
-
say(`Putting ${me.person.name}'s message into your open Codex session, as its next message…`);
|
|
231
|
-
result = await codexQueue(newest.id, prompt, ctx.cwd);
|
|
232
|
-
}
|
|
233
|
-
else {
|
|
234
|
-
say(`Putting ${me.person.name}'s message into ${into}…`);
|
|
235
|
-
result = await codexResume(newest?.id ?? null, prompt, ctx.cwd);
|
|
236
|
-
}
|
|
237
266
|
handled.add(m.id);
|
|
238
|
-
if (result.
|
|
239
|
-
await read({ ids: [m.id] });
|
|
240
|
-
say(`Done: the answer shows in Gavel as it's written.`);
|
|
241
|
-
if (result.refused.length)
|
|
242
|
-
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.`);
|
|
243
|
-
}
|
|
244
|
-
else {
|
|
245
|
-
joins.delete(prompt.trim());
|
|
267
|
+
if (result.outcome === "failed") {
|
|
246
268
|
await read({ ids: [], failed: [{ id: m.id, reason: result.reason }] });
|
|
247
269
|
say(`Couldn't: ${result.reason}`);
|
|
248
270
|
}
|
|
249
|
-
|
|
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();
|
|
250
279
|
}
|
|
251
280
|
finally {
|
|
252
281
|
delivering.delete(m.id);
|
|
253
282
|
}
|
|
254
283
|
};
|
|
255
|
-
|
|
256
|
-
|
|
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))
|
|
257
291
|
return;
|
|
258
|
-
|
|
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 () => {
|
|
259
304
|
try {
|
|
260
|
-
|
|
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;
|
|
261
308
|
}
|
|
262
|
-
catch
|
|
263
|
-
|
|
309
|
+
catch {
|
|
310
|
+
return true;
|
|
264
311
|
}
|
|
265
|
-
say("Stopped.");
|
|
266
|
-
process.exit(0);
|
|
267
312
|
};
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
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();
|
|
271
411
|
let start = true;
|
|
272
412
|
let failures = 0;
|
|
273
413
|
try {
|
|
274
|
-
|
|
414
|
+
while (!stopping) {
|
|
275
415
|
let res;
|
|
276
416
|
try {
|
|
277
417
|
res = await call(api, "GET", `/v1/agents/me/chat?wait=30&bridge=${id}${start ? "&start=true" : ""}`);
|
|
@@ -282,6 +422,9 @@ async function bridge(run, ctx) {
|
|
|
282
422
|
await pause(backoff(failures));
|
|
283
423
|
continue;
|
|
284
424
|
}
|
|
425
|
+
// Stopping: nothing more goes out but the goodbye, and the process ends with it.
|
|
426
|
+
if (stopping)
|
|
427
|
+
await new Promise(() => undefined);
|
|
285
428
|
if (res.status === 409) {
|
|
286
429
|
say("Another bridge for this agent took over; this one stops.");
|
|
287
430
|
return 3;
|
|
@@ -298,129 +441,63 @@ async function bridge(run, ctx) {
|
|
|
298
441
|
}
|
|
299
442
|
failures = 0;
|
|
300
443
|
start = false;
|
|
301
|
-
const
|
|
302
|
-
if (
|
|
303
|
-
|
|
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);
|
|
304
453
|
if (on) {
|
|
305
|
-
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.`);
|
|
306
455
|
thread = null;
|
|
307
|
-
|
|
308
|
-
if (
|
|
309
|
-
|
|
456
|
+
sent.clear();
|
|
457
|
+
if (state)
|
|
458
|
+
outgoing.push({ event: "state", state });
|
|
310
459
|
await push();
|
|
311
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
|
+
}
|
|
312
465
|
else {
|
|
313
466
|
say(`The chat is off in Gavel: nothing is read or sent until ${me.person.name} turns it on again.`);
|
|
314
|
-
|
|
315
|
-
setHook(false);
|
|
467
|
+
outgoing = [];
|
|
316
468
|
}
|
|
317
469
|
}
|
|
318
470
|
if (!on)
|
|
319
471
|
continue;
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
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);
|
|
325
481
|
}
|
|
326
|
-
}
|
|
327
|
-
finally {
|
|
328
|
-
clearInterval(timer);
|
|
329
|
-
if (!stopping)
|
|
330
|
-
setHook(false);
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
// ---------- gavel bridge wake ----------
|
|
334
|
-
// Run by Claude Code as the wake hook (never by hand): waits for what the person writes in Gavel
|
|
335
|
-
// and wakes the session with it, exit code 2 and the words on stderr. One per session: a newer one
|
|
336
|
-
// takes over. It stays quiet (exit 0) when the chat is off, the session is gone or it's taken over,
|
|
337
|
-
// and never marks a message read for a session that isn't there to hear it.
|
|
338
|
-
async function wake(run, ctx) {
|
|
339
|
-
let input = {};
|
|
340
|
-
try {
|
|
341
|
-
input = JSON.parse(readFileSync(0, "utf8"));
|
|
342
|
-
}
|
|
343
|
-
catch {
|
|
344
|
-
// no hook input
|
|
345
|
-
}
|
|
346
|
-
const session = typeof input.session_id === "string" ? input.session_id : null;
|
|
347
|
-
const cwd = typeof input.cwd === "string" ? input.cwd : ctx.cwd;
|
|
348
|
-
if (!session)
|
|
349
|
-
return 0;
|
|
350
|
-
let setup;
|
|
351
|
-
try {
|
|
352
|
-
setup = setupHere("claude-code", run.server, { ...ctx, cwd });
|
|
353
|
-
}
|
|
354
|
-
catch {
|
|
355
482
|
return 0;
|
|
356
483
|
}
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
if (/\bbridge wake\b/.test(command))
|
|
364
|
-
process.kill(before, "SIGTERM");
|
|
365
|
-
}
|
|
366
|
-
catch {
|
|
367
|
-
// gone already
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
writeFileSync(lock, String(process.pid));
|
|
371
|
-
const mine = () => existsSync(lock) && readFileSync(lock, "utf8") === String(process.pid);
|
|
372
|
-
const parent = process.ppid;
|
|
373
|
-
let person = "Your person";
|
|
374
|
-
try {
|
|
375
|
-
const res = await call(api, "GET", "/v1/me");
|
|
376
|
-
if (res.ok)
|
|
377
|
-
person = (await res.json()).person.name;
|
|
378
|
-
}
|
|
379
|
-
catch {
|
|
380
|
-
// named generically
|
|
381
|
-
}
|
|
382
|
-
let failures = 0;
|
|
383
|
-
while (mine() && process.ppid === parent) {
|
|
384
|
-
let res;
|
|
385
|
-
try {
|
|
386
|
-
res = await call(api, "GET", "/v1/agents/me/chat?wait=30");
|
|
387
|
-
}
|
|
388
|
-
catch {
|
|
389
|
-
failures++;
|
|
390
|
-
await pause(backoff(failures));
|
|
391
|
-
continue;
|
|
392
|
-
}
|
|
393
|
-
if (!res.ok) {
|
|
394
|
-
if (res.status < 500)
|
|
395
|
-
return 0;
|
|
396
|
-
failures++;
|
|
397
|
-
await pause(backoff(failures));
|
|
398
|
-
continue;
|
|
484
|
+
finally {
|
|
485
|
+
if (!stopping) {
|
|
486
|
+
watching = false;
|
|
487
|
+
timers();
|
|
488
|
+
rmSync(pictures, { recursive: true, force: true });
|
|
489
|
+
await h.close();
|
|
399
490
|
}
|
|
400
|
-
failures = 0;
|
|
401
|
-
const state = (await res.json());
|
|
402
|
-
if (!state.on)
|
|
403
|
-
return 0;
|
|
404
|
-
if (!state.unread.length)
|
|
405
|
-
continue;
|
|
406
|
-
if (!mine() || process.ppid !== parent || !(await claudeOpen(session, cwd)))
|
|
407
|
-
return 0;
|
|
408
|
-
const res2 = await call(api, "POST", "/v1/agents/me/chat/read", { ids: state.unread.map((m) => m.id) }).catch(() => null);
|
|
409
|
-
if (!res2?.ok)
|
|
410
|
-
continue;
|
|
411
|
-
const words = state.unread.map(asPrompt).join("\n\n---\n\n");
|
|
412
|
-
const text = words.length > 9000 ? `${words.slice(0, 9000)}… (cut: the rest is in Gavel's chat)` : words;
|
|
413
|
-
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`);
|
|
414
|
-
return 2;
|
|
415
491
|
}
|
|
416
|
-
return 0;
|
|
417
492
|
}
|
|
418
493
|
export async function runBridge(run, ctx) {
|
|
419
494
|
try {
|
|
420
495
|
if (run.action === "show")
|
|
421
|
-
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.
|
|
422
499
|
if (run.action === "wake")
|
|
423
|
-
return
|
|
500
|
+
return 0;
|
|
424
501
|
return await bridge(run, ctx);
|
|
425
502
|
}
|
|
426
503
|
catch (err) {
|