@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
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { execFile, spawn } from "node:child_process";
|
|
2
1
|
import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
3
2
|
import { join } from "node:path";
|
|
4
|
-
import { promisify } from "node:util";
|
|
5
3
|
import { cut } from "./words.js";
|
|
6
4
|
// Claude Code keeps each session as <its folder>/projects/<project>/<session id>.jsonl, the project
|
|
7
5
|
// its working folder's path with every character but a letter or a digit as a dash.
|
|
@@ -90,97 +88,3 @@ export function claudeWords(jsonl) {
|
|
|
90
88
|
}
|
|
91
89
|
return out;
|
|
92
90
|
}
|
|
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
|
-
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { execFile, execFileSync, spawn } from "node:child_process";
|
|
2
|
-
import { randomBytes } from "node:crypto";
|
|
3
|
-
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, watch, writeFileSync } from "node:fs";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync } from "node:fs";
|
|
4
4
|
import { createServer } from "node:http";
|
|
5
5
|
import { connect } from "node:net";
|
|
6
6
|
import { tmpdir } from "node:os";
|
|
@@ -17,6 +17,8 @@ import { claudeSetups } from "./setup.js";
|
|
|
17
17
|
// {"type":"auth","token":"…"} reaches it: "next" between tool calls mid-turn or as a new turn when
|
|
18
18
|
// idle, "now" interrupting the turn. Content is a string only. The transcript keeps it as a user
|
|
19
19
|
// line with isMeta and origin {kind: "peer", msg_id}, framed for Claude as another session's.
|
|
20
|
+
// The socket takes a line from the same user without the key too: a session the bridge knows
|
|
21
|
+
// only from `claude agents --json` (its pid) is reached at its usual address.
|
|
20
22
|
// - Hooks fire as they happen and settings reload while a session runs: UserPromptSubmit,
|
|
21
23
|
// MessageDisplay (the agent's text as it's shown, whole lines, 2.1.152), PermissionRequest,
|
|
22
24
|
// PostToolUse, Stop, StopFailure and SessionEnd.
|
|
@@ -51,7 +53,11 @@ export const atLeast = (version, min) => {
|
|
|
51
53
|
// (async), so the session never waits on it; SessionEnd waits a moment, since nothing runs after it.
|
|
52
54
|
export const BRIDGE_HOOK_EVENTS = ["SessionStart", "UserPromptSubmit", "PermissionRequest", "PostToolUse", "Stop", "StopFailure", "SessionEnd"];
|
|
53
55
|
const DISPLAY_PATH = "/gavel-bridge/";
|
|
54
|
-
|
|
56
|
+
// Gavel's wake hook from a bridge before 0.1.17 (`gavel bridge wake`) counts as the bridge's too, so
|
|
57
|
+
// it goes when these go in.
|
|
58
|
+
const isBridgeHook = (h) => (Array.isArray(h.args) && h.args.includes("bridge") && h.args.includes("event")) ||
|
|
59
|
+
(typeof h.url === "string" && h.url.startsWith("http://127.0.0.1:") && h.url.includes(DISPLAY_PATH)) ||
|
|
60
|
+
(typeof h.command === "string" && /\bbridge wake( |$)/.test(h.command));
|
|
55
61
|
// The settings with the bridge's hooks in (its command and the display hook's address) or out
|
|
56
62
|
// (null), every other hook and setting kept; null when nothing changes.
|
|
57
63
|
export function withBridgeHooks(existing, command, displayUrl) {
|
|
@@ -76,9 +82,9 @@ export function withBridgeHooks(existing, command, displayUrl) {
|
|
|
76
82
|
const hook = { type: "command", command: exe, args: [...rest, "bridge", "event", event, "--harness", "claude-code"], ...(event === "SessionEnd" ? { timeout: 5 } : { async: true }) };
|
|
77
83
|
hooks[event] = [...(hooks[event] ?? []), { hooks: [hook] }];
|
|
78
84
|
}
|
|
79
|
-
if (displayUrl)
|
|
80
|
-
hooks.MessageDisplay = [...(hooks.MessageDisplay ?? []), { hooks: [{ type: "http", url: displayUrl, timeout: 2 }] }];
|
|
81
85
|
}
|
|
86
|
+
if (displayUrl)
|
|
87
|
+
hooks.MessageDisplay = [...(hooks.MessageDisplay ?? []), { hooks: [{ type: "http", url: displayUrl, timeout: 2 }] }];
|
|
82
88
|
const { hooks: _old, ...rest } = settings;
|
|
83
89
|
const next = Object.keys(hooks).length ? { ...rest, hooks } : rest;
|
|
84
90
|
const text = `${JSON.stringify(next, null, 2)}\n`;
|
|
@@ -113,6 +119,17 @@ const gitIn = (args, cwd) => {
|
|
|
113
119
|
return false;
|
|
114
120
|
}
|
|
115
121
|
};
|
|
122
|
+
// Whether Gavel's plugin (D-1139) is on for this user: it carries the bridge's hooks and the
|
|
123
|
+
// end-of-turn hook itself, for every folder.
|
|
124
|
+
export function gavelPluginOn(home) {
|
|
125
|
+
try {
|
|
126
|
+
const enabled = JSON.parse(readFileSync(join(home, ".claude", "settings.json"), "utf8")).enabledPlugins ?? {};
|
|
127
|
+
return Object.entries(enabled).some(([id, on]) => on === true && id.startsWith("gavel@"));
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
116
133
|
// `gavel bridge hooks install|remove|status` (and `gavel pair --bridge true`): the bridge's hooks in
|
|
117
134
|
// this folder's local Claude Code settings, beside the agent's own setup that pairing wrote there,
|
|
118
135
|
// in a file git ignores (its .gitignore line added), never one git tracks.
|
|
@@ -151,10 +168,17 @@ export async function claudeBridgeHooks(action, opts) {
|
|
|
151
168
|
return { hooks: "refused", file: name, reason: `This Claude Code (${version?.join(".") ?? "unknown"}) is older than the bridge's hooks need (${BRIDGE_MIN_VERSION.join(".")}): run claude update, then gavel bridge hooks install.` };
|
|
152
169
|
if (gitIn(["ls-files", "--error-unmatch", name], opts.cwd))
|
|
153
170
|
return { hooks: "refused", file: name, reason: `git tracks ${name}, and the bridge's hooks must stay out of commits: untrack it first.` };
|
|
154
|
-
|
|
171
|
+
// With Gavel's plugin on, it runs the bridge's hooks: this folder gets only its own address for
|
|
172
|
+
// the agent's words as they're shown.
|
|
173
|
+
const plugin = gavelPluginOn(opts.home);
|
|
174
|
+
const next = withBridgeHooks(existing, plugin ? null : opts.command, displayHook(opts.home, opts.cwd).url);
|
|
155
175
|
if (next !== null)
|
|
156
176
|
writeWhole(file, next);
|
|
157
|
-
const done = [
|
|
177
|
+
const done = [
|
|
178
|
+
plugin
|
|
179
|
+
? `Gavel's plugin runs the bridge's hooks here; wrote this folder's hook for the words as they're shown into ${name}`
|
|
180
|
+
: `wrote the bridge's hooks into ${name}: a Claude Code session here starts Gavel's bridge as it starts (and stops it a while after the last one ends), so your person's chat in Gavel reaches it at once, with no terminal open`,
|
|
181
|
+
];
|
|
158
182
|
if (gitIn(["rev-parse", "--is-inside-work-tree"], opts.cwd) && !gitIn(["check-ignore", "-q", name], opts.cwd)) {
|
|
159
183
|
const gitignore = join(opts.cwd, ".gitignore");
|
|
160
184
|
const text = existsSync(gitignore) ? readFileSync(gitignore, "utf8") : "";
|
|
@@ -172,11 +196,23 @@ function writeWhole(file, text) {
|
|
|
172
196
|
// ---------- the session's words, with Gavel's own messages joined ----------
|
|
173
197
|
const PEER_HEADER = /^Another Claude session sent a message(?: while you were working)?:\n/;
|
|
174
198
|
const PEER_FOOTER = "\n\nThis came from another Claude session";
|
|
199
|
+
const GAVEL_HEADER = /^[^\n]{1,200} wrote to you in Gavel \(they read your answer there, so answer here as you would to them\):\n\n/;
|
|
200
|
+
const PICTURES_FOOTER = /\n\nThe pictures? they sent with it, on this laptop \(open each with Read\):\n[\s\S]*$/;
|
|
201
|
+
// The person's own words in what the bridge put in: without the line saying who wrote, or where
|
|
202
|
+
// their pictures are.
|
|
203
|
+
const theirWords = (text) => text.replace(GAVEL_HEADER, "").replace(PICTURES_FOOTER, "").trim();
|
|
204
|
+
// What joins a resumed run's prompt (a plain user line in the transcript) to its Gavel message.
|
|
205
|
+
export const promptKey = (prompt) => createHash("sha256").update(prompt.trim()).digest("hex").slice(0, 32);
|
|
175
206
|
// A session's words for Gavel: claudeWords' (D-894's filter), plus the session's copy of each
|
|
176
|
-
// message the bridge put in from Gavel, joined to it by its id (msg_id)
|
|
177
|
-
// message, and Gavel's own wakes, never show.
|
|
178
|
-
export function sessionWords(jsonl, fromGavel) {
|
|
179
|
-
const words = claudeWords(jsonl)
|
|
207
|
+
// message the bridge put in from Gavel, joined to it: through the inbox by its id (msg_id), as a
|
|
208
|
+
// resumed run's prompt by promptKey. Another session's message, and Gavel's own wakes, never show.
|
|
209
|
+
export function sessionWords(jsonl, fromGavel, prompts = new Map()) {
|
|
210
|
+
const words = claudeWords(jsonl).map((w) => {
|
|
211
|
+
if (w.side !== "person" || !GAVEL_HEADER.test(w.text))
|
|
212
|
+
return w;
|
|
213
|
+
const gavelId = prompts.get(promptKey(w.text));
|
|
214
|
+
return { ...w, text: theirWords(w.text) || "(message)", ...(gavelId ? { gavelId } : {}) };
|
|
215
|
+
});
|
|
180
216
|
for (const raw of jsonl.split("\n")) {
|
|
181
217
|
if (!raw.includes('"peer"'))
|
|
182
218
|
continue;
|
|
@@ -193,7 +229,7 @@ export function sessionWords(jsonl, fromGavel) {
|
|
|
193
229
|
const content = typeof line.message?.content === "string" ? line.message.content : "";
|
|
194
230
|
const body = content.replace(PEER_HEADER, "");
|
|
195
231
|
const end = body.indexOf(PEER_FOOTER);
|
|
196
|
-
const text = (end >= 0 ? body.slice(0, end) : body)
|
|
232
|
+
const text = theirWords(end >= 0 ? body.slice(0, end) : body);
|
|
197
233
|
words.push({ id: line.uuid, side: "person", text: text || "(message)", at: line.timestamp, gavelId: id });
|
|
198
234
|
}
|
|
199
235
|
return words.sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
|
|
@@ -201,8 +237,10 @@ export function sessionWords(jsonl, fromGavel) {
|
|
|
201
237
|
const PICTURES_HOURS = 1;
|
|
202
238
|
export class ClaudeCodeHarness {
|
|
203
239
|
ctx;
|
|
240
|
+
name = "Claude Code";
|
|
204
241
|
sessions = new Map();
|
|
205
|
-
|
|
242
|
+
// Each Gavel message the bridge put in, with its prompt's key when a resumed run took it.
|
|
243
|
+
known = new Map();
|
|
206
244
|
idsFile;
|
|
207
245
|
pictureDir;
|
|
208
246
|
listener = null;
|
|
@@ -212,25 +250,35 @@ export class ClaudeCodeHarness {
|
|
|
212
250
|
resumed = null;
|
|
213
251
|
lastState = null;
|
|
214
252
|
changedTimer = null;
|
|
253
|
+
// The person's name, for the words that say who wrote: the core learns it after it builds the
|
|
254
|
+
// harness, from GET /v1/me.
|
|
255
|
+
setPerson(name) {
|
|
256
|
+
this.ctx.person = name;
|
|
257
|
+
}
|
|
215
258
|
constructor(ctx) {
|
|
216
259
|
this.ctx = ctx;
|
|
217
260
|
const paths = bridgePaths(ctx.home, ctx.cwd, "claude-code");
|
|
218
261
|
this.idsFile = join(paths.dir, `${paths.key}.gavel-ids`);
|
|
219
262
|
this.pictureDir = join(paths.dir, `${paths.key}.pictures`);
|
|
220
|
-
let
|
|
263
|
+
let lines = [];
|
|
221
264
|
try {
|
|
222
|
-
|
|
265
|
+
lines = readFileSync(this.idsFile, "utf8").split("\n");
|
|
223
266
|
}
|
|
224
267
|
catch {
|
|
225
268
|
// none yet
|
|
226
269
|
}
|
|
227
|
-
|
|
270
|
+
for (const l of lines.slice(-500)) {
|
|
271
|
+
const m = /^([0-9a-f-]{36})(?: ([0-9a-f]{32}))?$/i.exec(l);
|
|
272
|
+
if (m)
|
|
273
|
+
this.known.set(m[1], m[2] ?? null);
|
|
274
|
+
}
|
|
228
275
|
}
|
|
229
|
-
remember(id) {
|
|
230
|
-
this.
|
|
231
|
-
|
|
276
|
+
remember(id, key = null) {
|
|
277
|
+
this.known.delete(id);
|
|
278
|
+
this.known.set(id, key);
|
|
279
|
+
const lines = [...this.known].slice(-500).map(([i, k]) => (k ? `${i} ${k}` : i));
|
|
232
280
|
const temp = `${this.idsFile}.${process.pid}.tmp`;
|
|
233
|
-
writeFileSync(temp, `${
|
|
281
|
+
writeFileSync(temp, `${lines.join("\n")}\n`, { mode: 0o600 });
|
|
234
282
|
renameSync(temp, this.idsFile);
|
|
235
283
|
}
|
|
236
284
|
// The session Gavel shows and writes to: the newest one open, else the folder's newest.
|
|
@@ -278,9 +326,12 @@ export class ClaudeCodeHarness {
|
|
|
278
326
|
}
|
|
279
327
|
return s;
|
|
280
328
|
}
|
|
281
|
-
// The hooks' events, in the order the session sent them.
|
|
282
|
-
hook(event,
|
|
283
|
-
const
|
|
329
|
+
// The hooks' events, in the order the session sent them (background.ts's HookEvent).
|
|
330
|
+
hook(event, given) {
|
|
331
|
+
const e = given;
|
|
332
|
+
const input = e?.input;
|
|
333
|
+
if (!input || typeof input !== "object")
|
|
334
|
+
return;
|
|
284
335
|
const id = typeof input.session_id === "string" ? input.session_id : null;
|
|
285
336
|
if (!id || typeof input.agent_id === "string")
|
|
286
337
|
return;
|
|
@@ -372,7 +423,11 @@ export class ClaudeCodeHarness {
|
|
|
372
423
|
return null;
|
|
373
424
|
const session = /([0-9a-f-]{36})\.jsonl$/i.exec(file)?.[1] ?? file;
|
|
374
425
|
this.follow(file);
|
|
375
|
-
|
|
426
|
+
const prompts = new Map();
|
|
427
|
+
for (const [id, key] of this.known)
|
|
428
|
+
if (key)
|
|
429
|
+
prompts.set(key, id);
|
|
430
|
+
return { thread: `claude-code:${session}`, label: this.ctx.label, session, messages: sessionWords(readFileSync(file, "utf8"), new Set(this.known.keys()), prompts) };
|
|
376
431
|
}
|
|
377
432
|
prompt(m, pictures) {
|
|
378
433
|
const words = m.decision ? `About ${m.decision.ref}: ${m.decision.question}\n\n${m.text}` : m.text;
|
|
@@ -405,7 +460,9 @@ export class ClaudeCodeHarness {
|
|
|
405
460
|
async deliver(m) {
|
|
406
461
|
const pictures = this.keepPictures(m);
|
|
407
462
|
const text = this.prompt(m, pictures);
|
|
408
|
-
|
|
463
|
+
let open = this.current();
|
|
464
|
+
if (!open?.inbox)
|
|
465
|
+
open = (await this.liveSession()) ?? this.current();
|
|
409
466
|
if (open?.inbox) {
|
|
410
467
|
this.remember(m.id);
|
|
411
468
|
if (await inboxSend(open.inbox, text, { priority: "next", msgId: m.id }))
|
|
@@ -415,7 +472,7 @@ export class ClaudeCodeHarness {
|
|
|
415
472
|
this.stateNow();
|
|
416
473
|
}
|
|
417
474
|
if (open)
|
|
418
|
-
return { outcome: "left", say: `${this.ctx.person} wrote in Gavel; your Claude Code session is open, so it
|
|
475
|
+
return { outcome: "left", say: `${this.ctx.person} wrote in Gavel; your Claude Code session here is open and the bridge can't reach it yet, so it goes in at the session's next step, or once it closes.` };
|
|
419
476
|
return this.resume(m, text);
|
|
420
477
|
}
|
|
421
478
|
// A closed session, resumed with the person's words as a turn of its own (D-905): nothing that
|
|
@@ -438,7 +495,7 @@ export class ClaudeCodeHarness {
|
|
|
438
495
|
child.stdout.on("data", (d) => (out += d));
|
|
439
496
|
child.stderr.on("data", (d) => (err += d));
|
|
440
497
|
child.on("spawn", () => {
|
|
441
|
-
this.remember(m.id);
|
|
498
|
+
this.remember(m.id, promptKey(text));
|
|
442
499
|
setTimeout(() => settle({ outcome: "delivered" }), 300).unref();
|
|
443
500
|
});
|
|
444
501
|
child.on("error", (e) => settle({ outcome: "failed", 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}` }));
|
|
@@ -470,19 +527,29 @@ export class ClaudeCodeHarness {
|
|
|
470
527
|
child.stdin.end(text);
|
|
471
528
|
});
|
|
472
529
|
}
|
|
473
|
-
//
|
|
474
|
-
// inbox at its usual address, without the session's key.
|
|
530
|
+
// The sessions open here, from Claude Code's own list (which settles what the hooks may have
|
|
531
|
+
// missed): the newest one's inbox at its usual address, without the session's key.
|
|
475
532
|
async liveSession() {
|
|
476
533
|
try {
|
|
477
534
|
const { stdout } = await promisify(execFile)("claude", ["agents", "--json"], { cwd: this.ctx.cwd, timeout: 15_000 });
|
|
478
535
|
const live = JSON.parse(stdout).filter((s) => s.cwd === this.ctx.cwd && typeof s.sessionId === "string" && typeof s.pid === "number");
|
|
536
|
+
for (const s of this.sessions.values())
|
|
537
|
+
if (s.open && !live.some((l) => l.sessionId === s.id)) {
|
|
538
|
+
s.open = false;
|
|
539
|
+
s.inbox = null;
|
|
540
|
+
s.state = "closed";
|
|
541
|
+
}
|
|
479
542
|
const newest = live.sort((a, b) => (Number(a.startedAt) || 0) - (Number(b.startedAt) || 0)).at(-1);
|
|
480
|
-
if (!newest)
|
|
543
|
+
if (!newest) {
|
|
544
|
+
this.stateNow();
|
|
481
545
|
return null;
|
|
546
|
+
}
|
|
482
547
|
const socket = [join("/tmp", "cc-socks", `${newest.pid}.sock`), join(tmpdir(), "cc-socks", `${newest.pid}.sock`)].find((p) => existsSync(p)) ?? null;
|
|
483
548
|
const s = this.session(newest.sessionId);
|
|
484
|
-
s.
|
|
549
|
+
s.open = true;
|
|
550
|
+
s.inbox = s.inbox ?? (socket ? { socket, token: null } : null);
|
|
485
551
|
s.state = newest.status === "busy" ? "working" : newest.status === "waiting" ? "waiting" : "idle";
|
|
552
|
+
this.stateNow();
|
|
486
553
|
return s;
|
|
487
554
|
}
|
|
488
555
|
catch {
|
|
@@ -539,8 +606,15 @@ export class ClaudeCodeHarness {
|
|
|
539
606
|
this.display.listen(hook.port, "127.0.0.1");
|
|
540
607
|
this.display.unref();
|
|
541
608
|
}
|
|
542
|
-
|
|
543
|
-
|
|
609
|
+
// The chat off in Gavel (D-1140): what the bridge kept on the laptop for it goes too, its copies
|
|
610
|
+
// of the person's pictures and the ids it joins by. The hooks stay: they start no bridge while
|
|
611
|
+
// the chat is off (`markChatOff`).
|
|
612
|
+
setChat(on) {
|
|
613
|
+
if (on)
|
|
614
|
+
return;
|
|
615
|
+
rmSync(this.pictureDir, { recursive: true, force: true });
|
|
616
|
+
rmSync(this.idsFile, { force: true });
|
|
617
|
+
this.known.clear();
|
|
544
618
|
}
|
|
545
619
|
async close() {
|
|
546
620
|
this.watcher?.close();
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { openWebSocket } from "./websocket.js";
|
|
5
|
+
// A client of Codex's app-server (developers.openai.com/codex/app-server): JSON-RPC 2.0 without its
|
|
6
|
+
// "jsonrpc" field, over the shared background server's control socket that every Codex terminal
|
|
7
|
+
// attaches to (Codex's daemon, `daemon_auto_start`, 0.158 and later), so the bridge sees and steers
|
|
8
|
+
// the very session the person has open.
|
|
9
|
+
export const CLIENT_NAME = "gavel_bridge";
|
|
10
|
+
// Notifications the bridge never reads: reasoning, commands' and files' output, plans, diffs and the
|
|
11
|
+
// like. Codex leaves them off this connection, so they never even reach the bridge (D-894).
|
|
12
|
+
const UNREAD = [
|
|
13
|
+
"item/reasoning/summaryTextDelta",
|
|
14
|
+
"item/reasoning/summaryPartAdded",
|
|
15
|
+
"item/reasoning/textDelta",
|
|
16
|
+
"item/commandExecution/outputDelta",
|
|
17
|
+
"item/commandExecution/terminalInteraction",
|
|
18
|
+
"item/fileChange/outputDelta",
|
|
19
|
+
"item/fileChange/patchUpdated",
|
|
20
|
+
"item/plan/delta",
|
|
21
|
+
"item/mcpToolCall/progress",
|
|
22
|
+
"turn/diff/updated",
|
|
23
|
+
"turn/plan/updated",
|
|
24
|
+
"thread/tokenUsage/updated",
|
|
25
|
+
"command/exec/outputDelta",
|
|
26
|
+
"process/outputDelta",
|
|
27
|
+
"process/exited",
|
|
28
|
+
"rawResponseItem/completed",
|
|
29
|
+
"rawResponse/completed",
|
|
30
|
+
"fs/changed",
|
|
31
|
+
"thread/realtime/item/transcript/delta",
|
|
32
|
+
"thread/realtime/transcript/delta",
|
|
33
|
+
"thread/realtime/outputAudio/delta",
|
|
34
|
+
];
|
|
35
|
+
// Codex's own default: $CODEX_HOME/app-server-control/app-server-control.sock.
|
|
36
|
+
export const controlSocket = (env, home) => join(env.CODEX_HOME ?? join(home, ".codex"), "app-server-control", "app-server-control.sock");
|
|
37
|
+
export class CodexRpcError extends Error {
|
|
38
|
+
code;
|
|
39
|
+
constructor(message, code) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.code = code;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
// The socket where it really is: Codex keeps it as a link to a short path, since a socket's own path
|
|
45
|
+
// can't be longer than about 100 bytes (macOS's limit), which a deep CODEX_HOME passes.
|
|
46
|
+
function resolved(path) {
|
|
47
|
+
try {
|
|
48
|
+
return realpathSync(path);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return path;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export async function connectCodex(socketPath, handlers, clientVersion) {
|
|
55
|
+
const pending = new Map();
|
|
56
|
+
let next = 1;
|
|
57
|
+
const socket = await openWebSocket(resolved(socketPath), {
|
|
58
|
+
message(text) {
|
|
59
|
+
let msg;
|
|
60
|
+
try {
|
|
61
|
+
msg = JSON.parse(text);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (msg.method && msg.id !== undefined)
|
|
67
|
+
handlers.serverRequest({ id: msg.id, method: msg.method, params: msg.params ?? {} });
|
|
68
|
+
else if (msg.method)
|
|
69
|
+
handlers.notification(msg.method, msg.params ?? {});
|
|
70
|
+
else if (typeof msg.id === "number") {
|
|
71
|
+
const waiting = pending.get(msg.id);
|
|
72
|
+
if (!waiting)
|
|
73
|
+
return;
|
|
74
|
+
pending.delete(msg.id);
|
|
75
|
+
clearTimeout(waiting.timer);
|
|
76
|
+
if (msg.error)
|
|
77
|
+
waiting.reject(new CodexRpcError(msg.error.message ?? "Codex refused the request", msg.error.code ?? 0));
|
|
78
|
+
else
|
|
79
|
+
waiting.resolve(msg.result);
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
void socket.closed.then((why) => {
|
|
84
|
+
for (const [id, waiting] of pending) {
|
|
85
|
+
clearTimeout(waiting.timer);
|
|
86
|
+
waiting.reject(new CodexRpcError(`Codex's server went away (${why ?? "closed"})`, -1));
|
|
87
|
+
pending.delete(id);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
const request = (method, params, timeoutMs = 30_000) => new Promise((resolve, reject) => {
|
|
91
|
+
const id = next++;
|
|
92
|
+
const timer = setTimeout(() => {
|
|
93
|
+
pending.delete(id);
|
|
94
|
+
reject(new CodexRpcError(`Codex didn't answer ${method} in time`, -2));
|
|
95
|
+
}, timeoutMs);
|
|
96
|
+
pending.set(id, { resolve: resolve, reject, timer });
|
|
97
|
+
socket.send(JSON.stringify(params === undefined ? { method, id } : { method, id, params }));
|
|
98
|
+
});
|
|
99
|
+
try {
|
|
100
|
+
const init = await request("initialize", {
|
|
101
|
+
clientInfo: { name: CLIENT_NAME, title: "Gavel bridge", version: clientVersion },
|
|
102
|
+
capabilities: { experimentalApi: false, requestAttestation: false, optOutNotificationMethods: UNREAD },
|
|
103
|
+
}, 10_000);
|
|
104
|
+
socket.send(JSON.stringify({ method: "initialized" }));
|
|
105
|
+
return {
|
|
106
|
+
request,
|
|
107
|
+
respond: (id, result) => socket.send(JSON.stringify({ id, result })),
|
|
108
|
+
version: /\/(\d+\.\d+\.\d+)/.exec(init.userAgent ?? "")?.[1] ?? null,
|
|
109
|
+
closed: socket.closed,
|
|
110
|
+
close: () => socket.close(),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
socket.close();
|
|
115
|
+
throw err;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const firstLine = (text) => text.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
|
|
119
|
+
// Starts Codex's own background server when none runs (what a Codex terminal does by itself):
|
|
120
|
+
// idempotent, back once it answers on the control socket. Null when it started; else why not.
|
|
121
|
+
export function startCodexServer(cwd, env) {
|
|
122
|
+
return new Promise((resolve) => {
|
|
123
|
+
execFile("codex", ["app-server", "daemon", "start"], { cwd, env, timeout: 90_000 }, (err, _stdout, stderr) => {
|
|
124
|
+
if (!err)
|
|
125
|
+
return resolve(null);
|
|
126
|
+
const e = err;
|
|
127
|
+
if (e.code === "ENOENT")
|
|
128
|
+
return resolve("Codex's codex command isn't on the laptop's PATH where the bridge runs.");
|
|
129
|
+
const said = firstLine(String(stderr ?? ""));
|
|
130
|
+
if (/unrecognized subcommand|unexpected argument|invalid value/i.test(said))
|
|
131
|
+
return resolve("This Codex has no background server for the bridge to join: run codex update.");
|
|
132
|
+
resolve(`Codex's background server didn't start${said ? `: ${said}` : "."}`.slice(0, 300));
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
}
|