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