@getgavel/cli 0.1.16 → 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.
@@ -1,8 +1,16 @@
1
- import { execFile, spawn } from "node:child_process";
2
- import { closeSync, existsSync, openSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
3
- import { join } from "node:path";
1
+ import { execFile } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
4
+ import { basename, join } from "node:path";
4
5
  import { promisify } from "node:util";
6
+ import { cliVersion, withCodexHooks, writeWhole } from "../hook.js";
7
+ import { connectCodex, controlSocket, startCodexServer } from "./codex-app.js";
8
+ import { codexSetups } from "./setup.js";
9
+ import { WebSocketError } from "./websocket.js";
5
10
  import { cut } from "./words.js";
11
+ // Codex, through its shared app-server (codex-app.ts): the folder's newest session's words, live as
12
+ // Codex writes them; the person's messages put in with turn/start, which steers a running turn or
13
+ // starts one; Stop as turn/interrupt; Gavel's wake into an idle session.
6
14
  function realpath(path) {
7
15
  try {
8
16
  return realpathSync(path);
@@ -11,6 +19,7 @@ function realpath(path) {
11
19
  return path;
12
20
  }
13
21
  }
22
+ // ---------- Which folders Codex works in (the bridge's harness detection) ----------
14
23
  // A rollout's first line, its session_meta, which may carry long instructions.
15
24
  function firstLine(file) {
16
25
  const fd = openSync(file, "r");
@@ -55,7 +64,7 @@ const DAYS = 31;
55
64
  const desc = (dir) => (existsSync(dir) ? readdirSync(dir).filter((n) => /^\d+$/.test(n)).sort().reverse() : []);
56
65
  // Codex keeps each session as <its folder>/sessions/YYYY/MM/DD/rollout-…-<id>.jsonl, the session's
57
66
  // working folder in its first line. The last month's top-level sessions of this folder, newest
58
- // first; an old, compressed one (.jsonl.zst) isn't read.
67
+ // first: only whether Codex works here, its words come from Codex itself.
59
68
  export function codexSessions(cwd, home, env) {
60
69
  const root = join(env.CODEX_HOME ?? join(home, ".codex"), "sessions");
61
70
  const here = new Set([cwd, realpath(cwd)]);
@@ -78,38 +87,46 @@ export function codexSessions(cwd, home, env) {
78
87
  }
79
88
  return found.sort((a, b) => b.changedAt - a.changedAt);
80
89
  }
81
- // What Codex puts in the person's place: its context, instructions, a shell command typed with !.
90
+ // The bridge's own client message ids: a person's message from Gavel ("gavel:<its id>"), whose copy
91
+ // in the session joins it, and Gavel's wake, which never shows in their chat (D-1103).
92
+ const FROM_GAVEL = "gavel:";
93
+ const WAKE = "gavel-wake:";
94
+ const WAKE_LINE = /^Gavel: \d+ waiting \([^)]*\)\.$/;
95
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
96
+ // What Codex can put in the person's place: its context, instructions, a shell command typed with !.
82
97
  const MARKED = /^<(environment_context|user_instructions|user_shell_command|turn_aborted)>/;
83
- // A session's words: what the person typed (user_message) and the agent's messages (agent_message),
84
- // as Codex shows them. Never its instructions or context, reasoning, a tool call or its output: the
85
- // response items that carry them aren't read at all.
86
- export function codexWords(jsonl) {
87
- const out = [];
88
- const atTime = new Map();
89
- for (const raw of jsonl.split("\n")) {
90
- if (!raw.trim())
91
- continue;
92
- let line;
93
- try {
94
- line = JSON.parse(raw);
95
- }
96
- catch {
97
- continue; // the line Codex is still writing
98
- }
99
- if (line.type !== "event_msg" || !line.timestamp || typeof line.payload?.message !== "string")
100
- continue;
101
- const text = line.payload.message.trim();
102
- const side = line.payload.type === "user_message" && !MARKED.test(text) ? "person" : line.payload.type === "agent_message" ? "agent" : null;
103
- if (!side || !text)
104
- continue;
105
- const n = atTime.get(line.timestamp) ?? 0;
106
- atTime.set(line.timestamp, n + 1);
107
- out.push({ id: `${line.timestamp}#${n}`, side, text: cut(text), at: line.timestamp });
108
- }
109
- return out;
98
+ // One item's words, as Gavel keeps them: what the person typed (a user message's text, never its
99
+ // pictures) and Codex's messages. Everything else (reasoning, a command, a file change, a tool call
100
+ // or its output, a hook's prompt, Gavel's own wake) isn't words, and stays on the laptop (D-894).
101
+ export function codexItemWords(item, turnStartedAt) {
102
+ const at = new Date(item.startedAtMs ?? (turnStartedAt ? turnStartedAt * 1000 : Date.now())).toISOString();
103
+ if (item.type === "agentMessage") {
104
+ const text = (item.text ?? "").trim();
105
+ return text ? { id: item.id, side: "agent", text: cut(text), at } : null;
106
+ }
107
+ if (item.type !== "userMessage" || item.clientId?.startsWith(WAKE))
108
+ return null;
109
+ const text = (item.content ?? [])
110
+ .filter((c) => c.type === "text" && typeof c.text === "string")
111
+ .map((c) => c.text.trim())
112
+ .filter(Boolean)
113
+ .join("\n\n");
114
+ if (!text || MARKED.test(text) || WAKE_LINE.test(text))
115
+ return null;
116
+ const gavelId = item.clientId?.startsWith(FROM_GAVEL) ? item.clientId.slice(FROM_GAVEL.length) : null;
117
+ return { id: item.id, side: "person", text: cut(text), at, ...(gavelId && UUID.test(gavelId) ? { gavelId } : {}) };
110
118
  }
111
- // Whether the session is open: a running Codex (in a terminal or exec) holds its rollout open
112
- // while it writes.
119
+ export const codexTurnWords = (turn) => turn.items.map((i) => codexItemWords(i, turn.startedAt)).filter((s) => s !== null);
120
+ const stateOf = (status) => status.type === "active"
121
+ ? status.activeFlags?.some((f) => f === "waitingOnApproval" || f === "waitingOnUserInput")
122
+ ? "waiting"
123
+ : "working"
124
+ : status.type === "notLoaded"
125
+ ? "closed"
126
+ : "idle";
127
+ // ---------- A session open outside Codex's shared server ----------
128
+ // Whether a running Codex holds the session's file open: one with its own server (an editor, a
129
+ // terminal run without the shared one), which the bridge mustn't load a second time.
113
130
  export async function codexOpen(file) {
114
131
  try {
115
132
  const { stdout } = await promisify(execFile)("lsof", ["-t", "--", file], { timeout: 15_000 });
@@ -120,57 +137,403 @@ export async function codexOpen(file) {
120
137
  }
121
138
  }
122
139
  const firstLineOf = (text) => text.split("\n").map((l) => l.trim()).find(Boolean) ?? "";
123
- const notStarted = (e) => (e.code === "ENOENT" ? "Codex's codex command isn't on the laptop's PATH where the bridge runs." : `Codex didn't start: ${e.message}`);
124
- // Into an open session: Codex's own queue, which the running session takes as its next message.
125
- // It takes the words only on its command line, for the moment it runs.
126
- export async function codexQueue(session, text, cwd) {
140
+ // Into a session open outside the shared server: Codex's own queue, which it takes as its next
141
+ // message. Words only, on its command line for the moment it runs.
142
+ async function codexQueue(session, text, cwd) {
127
143
  try {
128
144
  await promisify(execFile)("codex", ["queue", "--thread", session, "--message", text], { cwd, timeout: 60_000 });
129
- return { ok: true, refused: [] };
130
145
  }
131
146
  catch (err) {
132
147
  const e = err;
133
148
  if (e.code === "ENOENT")
134
- return { ok: false, reason: notStarted(e) };
135
- return { ok: false, reason: `Codex said: ${firstLineOf(e.stderr ?? "") || e.message}`.slice(0, 300) };
149
+ throw new Error("Codex's codex command isn't on the laptop's PATH where the bridge runs.");
150
+ throw new Error(firstLineOf(e.stderr ?? "") || e.message);
136
151
  }
137
152
  }
138
- // A closed session gets a turn of its own (a new session when there's none), in its own sandbox:
139
- // exec asks nobody, so what would need approval isn't done, and comes back as refused. The words go
140
- // on stdin, never on the command line.
141
- export function codexResume(session, text, cwd) {
142
- return new Promise((resolve) => {
143
- const args = ["exec", ...(session ? ["resume", session] : []), "--json", "-"];
144
- const child = spawn("codex", args, { cwd, stdio: ["pipe", "pipe", "pipe"] });
145
- let out = "";
146
- let err = "";
147
- child.stdout.on("data", (d) => (out += d));
148
- child.stderr.on("data", (d) => (err += d));
149
- child.on("error", (e) => resolve({ ok: false, reason: notStarted(e) }));
150
- child.on("close", (code) => {
151
- let failed = null;
152
- let commands = 0;
153
- let changes = 0;
154
- for (const raw of out.split("\n")) {
155
- let event;
156
- try {
157
- event = JSON.parse(raw);
158
- }
159
- catch {
160
- continue;
153
+ // What the bridge answers for Codex on a turn it started while nobody had the session open: no.
154
+ // Nobody is at the laptop to allow it; the person hears what wasn't done (D-905, as exec did).
155
+ const DECLINE = {
156
+ "item/commandExecution/requestApproval": { result: { decision: "decline" }, what: "a command" },
157
+ "item/fileChange/requestApproval": { result: { decision: "decline" }, what: "a file change" },
158
+ "item/permissions/requestApproval": { result: { permissions: {}, scope: "turn" }, what: "more access" },
159
+ "item/tool/requestUserInput": { result: { answers: {} }, what: "a question for you" },
160
+ "mcpServer/elicitation/request": { result: { action: "decline", content: null, _meta: null }, what: "a tool's question" },
161
+ };
162
+ const SOURCES = ["cli", "vscode", "exec", "appServer"];
163
+ const HISTORY_TURNS = 30;
164
+ // After the person stops a turn at the laptop, Gavel's wake waits this long.
165
+ const QUIET_AFTER_STOP_MS = 2 * 60_000;
166
+ const reasonOf = (err) => (err instanceof Error ? err.message : String(err));
167
+ const notRunning = (err) => err instanceof WebSocketError && (err.code === "ENOENT" || err.code === "ECONNREFUSED");
168
+ class CodexHarness {
169
+ ctx;
170
+ name = "Codex";
171
+ app = null;
172
+ connecting = null;
173
+ listener = null;
174
+ current = null;
175
+ words = new Map();
176
+ turnId = null;
177
+ offsets = new Map();
178
+ // Runs the person's chat has heard start: one joined mid-turn starts at its first words.
179
+ announced = new Set();
180
+ // Threads the bridge loaded itself, with nobody at the laptop, and the turns it started there.
181
+ ownLoaded = new Set();
182
+ unattended = new Set();
183
+ declined = new Map();
184
+ // A message put in through Codex's queue has no client id: its copy joins it by its words.
185
+ queued = new Map();
186
+ state = null;
187
+ stoppedAt = 0;
188
+ constructor(ctx) {
189
+ this.ctx = ctx;
190
+ }
191
+ here(cwd) {
192
+ return cwd === this.ctx.cwd || realpath(cwd) === realpath(this.ctx.cwd);
193
+ }
194
+ label() {
195
+ return `Codex · ${basename(this.ctx.cwd)}`.slice(0, 80);
196
+ }
197
+ announce(runId) {
198
+ if (!runId || this.announced.has(runId))
199
+ return;
200
+ this.announced.add(runId);
201
+ this.listener?.live({ event: "run", runId });
202
+ }
203
+ setState(state) {
204
+ if (state === this.state)
205
+ return;
206
+ this.state = state;
207
+ this.listener?.state(state);
208
+ }
209
+ connect() {
210
+ if (this.app)
211
+ return Promise.resolve(this.app);
212
+ this.connecting ??= this.open().finally(() => (this.connecting = null));
213
+ return this.connecting;
214
+ }
215
+ // Codex's shared server, started first if none runs, as a Codex terminal does by itself.
216
+ async open() {
217
+ const socket = controlSocket(this.ctx.env, this.ctx.home);
218
+ const handlers = { notification: (method, params) => this.notified(method, params), serverRequest: (r) => this.asked(r) };
219
+ let app;
220
+ try {
221
+ app = await connectCodex(socket, handlers, cliVersion());
222
+ }
223
+ catch (err) {
224
+ if (!notRunning(err))
225
+ throw new Error(`Codex's background server didn't answer: ${reasonOf(err)}`);
226
+ const why = await startCodexServer(this.ctx.cwd, this.ctx.env);
227
+ if (why)
228
+ throw new Error(why);
229
+ app = await connectCodex(socket, handlers, cliVersion());
230
+ }
231
+ this.app = app;
232
+ void app.closed.then(() => {
233
+ if (this.app !== app)
234
+ return;
235
+ this.app = null;
236
+ if (this.current)
237
+ this.current.subscribed = false;
238
+ this.turnId = null;
239
+ this.setState("closed");
240
+ });
241
+ return app;
242
+ }
243
+ remember(said) {
244
+ if (!said)
245
+ return;
246
+ if (said.side === "person" && !said.gavelId) {
247
+ const joined = this.queued.get(said.text.trim());
248
+ if (joined)
249
+ said = { ...said, gavelId: joined };
250
+ }
251
+ this.words.set(said.id, said);
252
+ }
253
+ async history(app, threadId, turns) {
254
+ const { data } = await app.request("thread/turns/list", { threadId, itemsView: "full", sortDirection: "desc", limit: turns });
255
+ for (const turn of [...data].reverse()) {
256
+ for (const said of codexTurnWords(turn))
257
+ this.remember(said);
258
+ if (turn.status === "inProgress")
259
+ this.turnId = turn.id;
260
+ }
261
+ }
262
+ // Joins a thread loaded in the shared server, to hear it live: Codex sends its events to every
263
+ // client that resumed it, the person's terminal included.
264
+ async join(app, current) {
265
+ await app.request("thread/resume", { threadId: current.id, excludeTurns: true });
266
+ current.subscribed = true;
267
+ if (current.status.type === "active" && !this.turnId) {
268
+ const { data } = await app.request("thread/turns/list", { threadId: current.id, itemsView: "notLoaded", sortDirection: "desc", limit: 1 });
269
+ if (data[0]?.status === "inProgress")
270
+ this.turnId = data[0].id;
271
+ }
272
+ if (this.turnId)
273
+ this.announce(this.turnId);
274
+ }
275
+ async newest() {
276
+ const app = await this.connect();
277
+ const cwd = [...new Set([this.ctx.cwd, realpath(this.ctx.cwd)])];
278
+ const { data } = await app.request("thread/list", { cwd, sortKey: "updated_at", sortDirection: "desc", limit: 10, sourceKinds: SOURCES, useStateDbOnly: true });
279
+ const top = data.find((t) => !t.parentThreadId && !t.ephemeral);
280
+ if (!top) {
281
+ this.current = null;
282
+ this.setState("closed");
283
+ return null;
284
+ }
285
+ if (this.current?.id !== top.id) {
286
+ this.current = { id: top.id, status: top.status, path: top.path, subscribed: false };
287
+ this.words.clear();
288
+ this.offsets.clear();
289
+ this.turnId = null;
290
+ await this.history(app, top.id, HISTORY_TURNS);
291
+ }
292
+ else if (!this.current.subscribed) {
293
+ this.current.status = top.status;
294
+ // Not heard live (open elsewhere, or closed): its newest turns, read again.
295
+ await this.history(app, top.id, 3);
296
+ }
297
+ const current = this.current;
298
+ if (!current.subscribed && current.status.type !== "notLoaded")
299
+ await this.join(app, current);
300
+ this.setState(stateOf(current.status));
301
+ return { thread: `codex:${current.id}`, label: this.label(), session: current.id, messages: [...this.words.values()].sort((a, b) => a.at.localeCompare(b.at)) };
302
+ }
303
+ notified(method, params) {
304
+ const threadId = typeof params.threadId === "string" ? params.threadId : null;
305
+ if (method === "thread/started") {
306
+ const thread = params.thread;
307
+ if (thread && !thread.parentThreadId && !thread.ephemeral && this.here(thread.cwd))
308
+ this.listener?.changed();
309
+ return;
310
+ }
311
+ const current = this.current;
312
+ if (!current || threadId !== current.id)
313
+ return;
314
+ switch (method) {
315
+ case "thread/status/changed":
316
+ current.status = params.status;
317
+ this.setState(stateOf(current.status));
318
+ return;
319
+ case "thread/closed":
320
+ current.subscribed = false;
321
+ current.status = { type: "notLoaded" };
322
+ this.turnId = null;
323
+ this.setState("closed");
324
+ return;
325
+ case "turn/started": {
326
+ const turn = params.turn;
327
+ this.turnId = turn.id;
328
+ this.announce(turn.id);
329
+ return;
330
+ }
331
+ case "item/started": {
332
+ const item = params.item;
333
+ if (item.type === "agentMessage")
334
+ this.offsets.set(item.id, 0);
335
+ // Someone typed at the laptop: the session has its person there now.
336
+ if (item.type === "userMessage" && !item.clientId?.startsWith("gavel"))
337
+ this.ownLoaded.delete(current.id);
338
+ return;
339
+ }
340
+ case "item/agentMessage/delta": {
341
+ const itemId = String(params.itemId ?? "");
342
+ const delta = typeof params.delta === "string" ? params.delta : "";
343
+ if (!itemId || !delta)
344
+ return;
345
+ const at = this.offsets.get(itemId) ?? 0;
346
+ this.offsets.set(itemId, at + delta.length);
347
+ const runId = String(params.turnId ?? this.turnId ?? "");
348
+ this.announce(runId);
349
+ this.listener?.live({ event: "words", runId, id: itemId, at, text: delta });
350
+ return;
351
+ }
352
+ case "item/completed": {
353
+ const item = params.item;
354
+ const said = codexItemWords(item, null);
355
+ if (!said)
356
+ return;
357
+ this.remember(said);
358
+ this.offsets.delete(item.id);
359
+ this.listener?.changed();
360
+ return;
361
+ }
362
+ case "turn/completed": {
363
+ const turn = params.turn;
364
+ if (this.turnId === turn.id)
365
+ this.turnId = null;
366
+ if (turn.status === "interrupted")
367
+ this.stoppedAt = Date.now();
368
+ const declined = this.declined.get(turn.id);
369
+ if (declined?.length) {
370
+ const some = [...new Set(declined)].join(", ");
371
+ this.listener?.note(`Codex didn't do what it would have asked you about first (${some}): nobody was at the laptop to allow it. Allow it in the session there, or answer here.`);
161
372
  }
162
- if (event.type === "turn.failed")
163
- failed = typeof event.error?.message === "string" ? event.error.message : "the turn failed";
164
- if (event.type === "item.completed" && event.item?.status === "declined")
165
- event.item.type === "file_change" ? changes++ : commands++;
373
+ if (turn.status === "failed" && this.unattended.has(turn.id))
374
+ this.listener?.note(`Codex couldn't finish: ${turn.error?.message ?? "the turn failed"}`.slice(0, 300));
375
+ this.declined.delete(turn.id);
376
+ this.unattended.delete(turn.id);
377
+ this.listener?.changed();
378
+ if (this.announced.delete(turn.id))
379
+ this.listener?.live({ event: "end", runId: turn.id });
380
+ return;
166
381
  }
167
- const some = (n, one, many) => (n === 1 ? one : n ? `${n} ${many}` : null);
168
- const refused = [some(commands, "a command", "commands"), some(changes, "a file change", "file changes")].filter((r) => r !== null);
169
- if (code === 0 && !failed)
170
- return resolve({ ok: true, refused });
171
- const said = failed ?? firstLineOf(err);
172
- resolve({ ok: false, reason: (said ? `Codex said: ${said}` : `Codex stopped without answering (code ${code}).`).slice(0, 300) });
173
- });
174
- child.stdin.end(text);
175
- });
382
+ }
383
+ }
384
+ // A request Codex puts to its clients. The person's own Codex gets it too and answers it; the bridge
385
+ // answers only in a session it opened itself, which nobody has typed in at the laptop since.
386
+ asked(request) {
387
+ const threadId = typeof request.params.threadId === "string" ? request.params.threadId : null;
388
+ const turnId = typeof request.params.turnId === "string" ? request.params.turnId : null;
389
+ const decline = DECLINE[request.method];
390
+ if (!threadId || !turnId || !decline || !this.ownLoaded.has(threadId))
391
+ return;
392
+ this.app?.respond(request.id, decline.result);
393
+ this.declined.set(turnId, [...(this.declined.get(turnId) ?? []), decline.what]);
394
+ }
395
+ // Into the newest session: started on its turn when idle, steering it while it runs (turn/start does
396
+ // either); loaded first when nobody has it open, or a new session when the folder has none.
397
+ async put(app, input, clientUserMessageId, words, wake) {
398
+ await this.newest();
399
+ let current = this.current;
400
+ if (!current) {
401
+ const { thread } = await app.request("thread/start", { cwd: this.ctx.cwd });
402
+ current = this.current = { id: thread.id, status: thread.status, path: thread.path, subscribed: true };
403
+ this.words.clear();
404
+ this.ownLoaded.add(thread.id);
405
+ }
406
+ else if (current.status.type === "notLoaded") {
407
+ if (current.path && (await codexOpen(current.path))) {
408
+ await codexQueue(current.id, words, this.ctx.cwd);
409
+ return "queued";
410
+ }
411
+ await app.request("thread/resume", { threadId: current.id, excludeTurns: true });
412
+ current.subscribed = true;
413
+ current.status = { type: "idle" };
414
+ this.ownLoaded.add(current.id);
415
+ }
416
+ if (wake && (this.turnId || current.status.type === "active" || Date.now() - this.stoppedAt < QUIET_AFTER_STOP_MS))
417
+ return "busy";
418
+ const { turn } = await app.request("turn/start", { threadId: current.id, input, clientUserMessageId });
419
+ if (this.ownLoaded.has(current.id))
420
+ this.unattended.add(turn.id);
421
+ return "in";
422
+ }
423
+ async deliver(message) {
424
+ const words = message.decision ? `About ${message.decision.ref}: ${message.decision.question}\n\n${message.text}` : message.text;
425
+ const input = [{ type: "text", text: words, text_elements: [] }, ...message.pictures.map((path) => ({ type: "localImage", path }))];
426
+ let app;
427
+ try {
428
+ app = await this.connect();
429
+ }
430
+ catch (err) {
431
+ return { outcome: "failed", reason: reasonOf(err).slice(0, 300) };
432
+ }
433
+ try {
434
+ const into = await this.put(app, input, `${FROM_GAVEL}${message.id}`, words, false);
435
+ if (into === "queued") {
436
+ this.queued.set(words.trim(), message.id);
437
+ if (message.pictures.length)
438
+ this.listener?.note("Codex took your words through its own queue, which takes no pictures: the session is open outside Codex's background server. Send them again once it's closed, or add them there.");
439
+ return { outcome: "delivered" };
440
+ }
441
+ return { outcome: "delivered", read: true };
442
+ }
443
+ catch (err) {
444
+ return { outcome: "failed", reason: `Codex said: ${reasonOf(err)}`.slice(0, 300) };
445
+ }
446
+ }
447
+ async interrupt() {
448
+ const app = this.app;
449
+ const current = this.current;
450
+ if (!app || !current?.subscribed)
451
+ return "over";
452
+ let turnId = this.turnId;
453
+ if (!turnId && current.status.type === "active") {
454
+ const { data } = await app.request("thread/turns/list", { threadId: current.id, itemsView: "notLoaded", sortDirection: "desc", limit: 1 }).catch(() => ({ data: [] }));
455
+ turnId = data[0]?.status === "inProgress" ? data[0].id : null;
456
+ }
457
+ if (!turnId)
458
+ return "over";
459
+ try {
460
+ await app.request("turn/interrupt", { threadId: current.id, turnId });
461
+ return "stopped";
462
+ }
463
+ catch {
464
+ return "over";
465
+ }
466
+ }
467
+ async wake(line) {
468
+ try {
469
+ const app = await this.connect();
470
+ const into = await this.put(app, [{ type: "text", text: line, text_elements: [] }], `${WAKE}${randomUUID()}`, line, true);
471
+ return into !== "busy";
472
+ }
473
+ catch {
474
+ return false;
475
+ }
476
+ }
477
+ listen(listener) {
478
+ this.listener = listener;
479
+ }
480
+ setChat() {
481
+ // Codex's session is heard through its server, whatever the chat: nothing to put in or take out.
482
+ }
483
+ async close() {
484
+ this.app?.close();
485
+ this.app = null;
486
+ }
487
+ }
488
+ export function codexHarness(ctx) {
489
+ return new CodexHarness(ctx);
490
+ }
491
+ // ---------- The bridge's hooks in Codex ----------
492
+ const isBridgeEvent = (command) => typeof command === "string" && /@getgavel\/cli(@\S+)? bridge event /.test(command);
493
+ // `gavel bridge hooks install|remove|status` (and `gavel pair --bridge`) for Codex: in the project's
494
+ // .codex/hooks.json, beside its own hooks, SessionStart (in the background) and SessionEnd run `gavel
495
+ // bridge event` (background.ts), so a session here starts the bridge and the last one's end ends it.
496
+ // The commands are the release that wrote them, through npx, so the file holds no path of this
497
+ // machine's; Codex runs them once its person trusts them in /hooks.
498
+ export function codexBridgeHooks(action, opts) {
499
+ const name = ".codex/hooks.json";
500
+ const file = join(opts.cwd, name);
501
+ const existing = existsSync(file) ? readFileSync(file, "utf8") : null;
502
+ const installed = () => {
503
+ try {
504
+ const hooks = JSON.parse(existing ?? "{}").hooks ?? {};
505
+ return Object.values(hooks).some((groups) => (groups ?? []).some((g) => (g.hooks ?? []).some((h) => isBridgeEvent(h.command))));
506
+ }
507
+ catch {
508
+ return false;
509
+ }
510
+ };
511
+ if (action === "status")
512
+ return { hooks: installed() ? "installed" : "not installed", file: name };
513
+ try {
514
+ if (action === "remove") {
515
+ if (!installed())
516
+ return { hooks: "not installed", file: name };
517
+ writeWhole(file, withCodexHooks(existing, {}, isBridgeEvent, name));
518
+ return { hooks: "removed", file: name };
519
+ }
520
+ const local = codexSetups(opts.cwd, opts.home, opts.env).filter((s) => s.where.endsWith("this folder"));
521
+ const server = opts.server ?? (local.length === 1 ? local[0].server : undefined);
522
+ if (!local.length || (server && !local.some((s) => s.server === server)))
523
+ return { hooks: "refused", file: name, reason: "No Gavel agent is set up for Codex in this folder: pair it here first (gavel pair <code>). The bridge's hooks are for an agent's own folder." };
524
+ const event = (on) => `npx -y @getgavel/cli@${opts.version} bridge event ${on} --harness codex${server ? ` --server ${server}` : ""}`;
525
+ const ours = {
526
+ SessionStart: { matcher: "startup|resume", hooks: [{ type: "command", command: event("SessionStart"), async: true, timeout: 60 }] },
527
+ SessionEnd: { hooks: [{ type: "command", command: event("SessionEnd"), timeout: 3 }] },
528
+ };
529
+ writeWhole(file, withCodexHooks(existing, ours, isBridgeEvent, name));
530
+ }
531
+ catch (err) {
532
+ return { hooks: "refused", file: name, reason: reasonOf(err) };
533
+ }
534
+ return {
535
+ hooks: "installed",
536
+ file: name,
537
+ done: [`wrote the bridge's hooks into ${name}: a Codex 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; Codex runs them once your person trusts them in /hooks`],
538
+ };
176
539
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -39,6 +39,31 @@ export function claudeSetups(cwd, home) {
39
39
  }
40
40
  // [mcp_servers.<name>] and its http_headers table, the name bare or quoted.
41
41
  const TABLE = /^\s*\[\s*mcp_servers\.(?:"([^"]+)"|([A-Za-z0-9_-]+))(\.http_headers)?\s*\]\s*$/;
42
+ // Each Gavel server's entry in a Codex config.toml, by name: its address and its token.
43
+ function codexEntries(toml) {
44
+ const tables = new Map();
45
+ let current = null;
46
+ for (const line of toml.split("\n")) {
47
+ if (/^\s*\[/.test(line)) {
48
+ const m = TABLE.exec(line);
49
+ const name = m ? (m[1] ?? m[2]) : null;
50
+ current = name && isGavel(name) ? (tables.get(name) ?? tables.set(name, []).get(name)) : null;
51
+ }
52
+ else
53
+ current?.push(line);
54
+ }
55
+ const out = new Map();
56
+ for (const [name, lines] of tables) {
57
+ const text = lines.join("\n");
58
+ const url = /^\s*url\s*=\s*"([^"]+)"/m.exec(text)?.[1];
59
+ const token = /"?Authorization"?\s*=\s*"Bearer (gvl_[^"\s]+)"/.exec(text)?.[1];
60
+ if (url && token)
61
+ out.set(name, { url, token });
62
+ }
63
+ return out;
64
+ }
65
+ // The named server's entry in a Codex config.toml's text, or null.
66
+ export const codexEntry = (toml, server) => codexEntries(toml).get(server) ?? null;
42
67
  // Codex: the project's .codex/config.toml (an agent's), then the user's (a fleet's).
43
68
  export function codexSetups(cwd, home, env) {
44
69
  const out = [];
@@ -48,24 +73,8 @@ export function codexSetups(cwd, home, env) {
48
73
  ]) {
49
74
  if (!existsSync(file))
50
75
  continue;
51
- const tables = new Map();
52
- let current = null;
53
- for (const line of readFileSync(file, "utf8").split("\n")) {
54
- if (/^\s*\[/.test(line)) {
55
- const m = TABLE.exec(line);
56
- const name = m ? (m[1] ?? m[2]) : null;
57
- current = name && isGavel(name) ? (tables.get(name) ?? tables.set(name, []).get(name)) : null;
58
- }
59
- else
60
- current?.push(line);
61
- }
62
- for (const [name, lines] of tables) {
63
- const text = lines.join("\n");
64
- const url = /^\s*url\s*=\s*"([^"]+)"/m.exec(text)?.[1];
65
- const token = /"?Authorization"?\s*=\s*"Bearer (gvl_[^"\s]+)"/.exec(text)?.[1];
66
- if (url && token)
67
- out.push({ server: name, url, token, where: `Codex's setup for ${scope}` });
68
- }
76
+ for (const [server, entry] of codexEntries(readFileSync(file, "utf8")))
77
+ out.push({ server, ...entry, where: `Codex's setup for ${scope}` });
69
78
  }
70
79
  return out;
71
80
  }