@conveno/cli 0.2.0-rc.1 → 0.2.0-rc.11

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.
@@ -0,0 +1,969 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { Gt as startTurnContext, H as endTurnContinuation, K as findOnPath, _t as pendingHookContext, bt as planProgram, dt as ownSession, pt as parseCliVersion, xt as planSpawn } from "./dist-qONHJRJk.js";
6
+ import { n as cs, t as Za } from "./toml-patch-DGzVRdd1.js";
7
+ // ../adapters/codex/dist/index.js
8
+ const SERVER_NAME = "conveno";
9
+ var ConfigParseError = class extends Error {};
10
+ function parseToml(path, text) {
11
+ try {
12
+ return cs(text);
13
+ } catch (err) {
14
+ throw new ConfigParseError(`Cannot parse ${path} as TOML (${err instanceof Error ? err.message : String(err)}). Fix or move the file, then run conveno again. Conveno did not change it.`);
15
+ }
16
+ }
17
+ /** The approval mode Conveno asks for. A mode the user already set on the server is kept instead. */
18
+ const APPROVAL_MODE = "approve";
19
+ function serverOf(doc) {
20
+ const servers = doc.mcp_servers;
21
+ if (servers && typeof servers === "object") {
22
+ const ours = servers[SERVER_NAME];
23
+ if (ours && typeof ours === "object") return ours;
24
+ }
25
+ }
26
+ function matchesSpec(server, spec) {
27
+ return server !== void 0 && server.command === spec.command && JSON.stringify(server.args) === JSON.stringify(spec.args) && server.default_tools_approval_mode === spec.approval;
28
+ }
29
+ const eolOf = (text) => text.includes("\r\n") ? "\r\n" : "\n";
30
+ /** TOML basic strings use the same escapes as JSON for everything we write. */
31
+ const q = (s) => JSON.stringify(s);
32
+ function tableText(spec, eol) {
33
+ return [
34
+ `[mcp_servers.${SERVER_NAME}]`,
35
+ `command = ${q(spec.command)}`,
36
+ `args = [${spec.args.map(q).join(", ")}]`,
37
+ `default_tools_approval_mode = ${q(spec.approval)}`,
38
+ ""
39
+ ].join(eol);
40
+ }
41
+ /** Compare parsed data, treating a missing `mcp_servers` and an empty one as equal. */
42
+ const sameData = (a, b) => {
43
+ const norm = (t) => JSON.stringify(t, (k, v) => k === "mcp_servers" && v && Object.keys(v).length === 0 ? void 0 : v);
44
+ return norm(a) === norm(b);
45
+ };
46
+ /**
47
+ * Add our `[mcp_servers.conveno]` table. The file is left byte-for-byte intact: the table is
48
+ * appended as text. If the result does not parse to the expected data (for example the user
49
+ * already defines `mcp_servers.conveno` inline), fall back to a comment-preserving patch.
50
+ */
51
+ function addServer(path, before, spec) {
52
+ const doc = parseToml(path, before);
53
+ const expected = structuredClone(doc);
54
+ const servers = expected.mcp_servers ?? {};
55
+ servers[SERVER_NAME] = {
56
+ command: spec.command,
57
+ args: spec.args,
58
+ default_tools_approval_mode: spec.approval
59
+ };
60
+ expected.mcp_servers = servers;
61
+ const eol = eolOf(before);
62
+ const appended = before + (before === "" ? "" : before.endsWith("\n") ? eol : eol + eol) + tableText(spec, eol);
63
+ try {
64
+ if (sameData(cs(appended), expected)) return appended;
65
+ } catch {}
66
+ return Za(before, expected);
67
+ }
68
+ /** Remove our table and any `[mcp_servers.conveno.*]` subtables. */
69
+ function removeServer(path, before) {
70
+ const doc = parseToml(path, before);
71
+ const expected = structuredClone(doc);
72
+ const servers = expected.mcp_servers;
73
+ if (servers) delete servers[SERVER_NAME];
74
+ const eol = eolOf(before);
75
+ const lines = before.split(/\r?\n/);
76
+ const out = [];
77
+ let skipping = false;
78
+ for (const line of lines) {
79
+ const header = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/.exec(line);
80
+ if (header) {
81
+ const key = header[1].replace(/["'\s]/g, "");
82
+ const key0 = `mcp_servers.${SERVER_NAME}`;
83
+ skipping = key === key0 || key.startsWith(`${key0}.`);
84
+ }
85
+ if (!skipping) out.push(line);
86
+ }
87
+ let text = out.join(eol);
88
+ if (skipping) text = text.replace(/(\r?\n)+$/, "") + (text.trim() === "" ? "" : eol);
89
+ try {
90
+ if (sameData(cs(text), expected)) return text;
91
+ } catch {}
92
+ return Za(before, expected);
93
+ }
94
+ const EVENT_NAME = {
95
+ session_start: "SessionStart",
96
+ user_prompt_submit: "UserPromptSubmit",
97
+ stop: "Stop",
98
+ permission_request: "PermissionRequest"
99
+ };
100
+ /** A hook key is `<file>:<event>:<group>:<handler>`; null for any other shape. */
101
+ function parseHookKey(key) {
102
+ const m = /^(.*):([a-z_]+):\d+:\d+$/.exec(key);
103
+ const event = m?.[2] ? EVENT_NAME[m[2]] : void 0;
104
+ return m?.[1] && event ? {
105
+ file: m[1],
106
+ event
107
+ } : null;
108
+ }
109
+ /** A path for comparing: one separator, and no case on Windows. */
110
+ const normalizePath = (p, platform) => {
111
+ const slashed = p.replace(/\\/g, "/");
112
+ return platform === "win32" ? slashed.toLowerCase() : slashed;
113
+ };
114
+ /**
115
+ * The hooks Conveno wrote: from the user-level hooks.json only, never managed, running exactly the
116
+ * command Conveno writes for that event. A hook from a project's `.codex/hooks.json`, or one that
117
+ * only ends the same way, is somebody else's and is never trusted here.
118
+ */
119
+ function ownHookFilter(rule) {
120
+ const file = normalizePath(rule.file, rule.platform);
121
+ return (h) => {
122
+ if (h.isManaged) return false;
123
+ const k = parseHookKey(h.key);
124
+ if (!k || normalizePath(k.file, rule.platform) !== file) return false;
125
+ return (h.command ?? "").trim() === rule.commandFor(k.event);
126
+ };
127
+ }
128
+ /** Ends the program and what it started. `child.kill()` alone leaves the real Codex behind a Windows .cmd shim. */
129
+ function killTree(child, spawnFn) {
130
+ try {
131
+ if (process.platform === "win32" && child.pid !== void 0) {
132
+ const t = spawnFn("taskkill", [
133
+ "/T",
134
+ "/F",
135
+ "/PID",
136
+ String(child.pid)
137
+ ], {
138
+ stdio: "ignore",
139
+ windowsHide: true
140
+ });
141
+ t.on("error", () => child.kill());
142
+ t.unref?.();
143
+ return;
144
+ }
145
+ child.kill();
146
+ } catch {}
147
+ }
148
+ async function withAppServer(o, run) {
149
+ const spawnFn = o.spawnFn ?? spawn;
150
+ const child = spawnFn(o.file, o.args, {
151
+ cwd: o.cwd,
152
+ ...o.env ? { env: { ...o.env } } : {},
153
+ windowsHide: true,
154
+ windowsVerbatimArguments: o.windowsVerbatimArguments,
155
+ stdio: [
156
+ "pipe",
157
+ "pipe",
158
+ "pipe"
159
+ ]
160
+ });
161
+ let buf = "";
162
+ let stderr = "";
163
+ let nextId = 1;
164
+ let ended;
165
+ let exited = false;
166
+ const pending = /* @__PURE__ */ new Map();
167
+ /** The program is gone or unusable: every request waiting, and every later one, fails now. */
168
+ const end = (e) => {
169
+ ended ??= e;
170
+ for (const done of [...pending.values()]) done({ error: { message: e.message } });
171
+ pending.clear();
172
+ };
173
+ const tail = () => stderr.trim() ? ` stderr: ${stderr.trim().slice(-300)}` : "";
174
+ child.on("error", (e) => end(e));
175
+ const gone = (code) => {
176
+ exited = true;
177
+ end(/* @__PURE__ */ new Error(`codex app-server exited (${String(code)}).${tail()}`));
178
+ };
179
+ child.on("exit", gone);
180
+ child.on("close", gone);
181
+ child.stdin?.on("error", (e) => end(e));
182
+ child.stderr?.on("data", (d) => {
183
+ stderr += String(d);
184
+ });
185
+ child.stdout?.on("data", (d) => {
186
+ buf += String(d);
187
+ for (;;) {
188
+ const nl = buf.indexOf("\n");
189
+ if (nl < 0) break;
190
+ const line = buf.slice(0, nl).trim();
191
+ buf = buf.slice(nl + 1);
192
+ if (!line.startsWith("{")) continue;
193
+ try {
194
+ const m = JSON.parse(line);
195
+ if (typeof m.id === "number") pending.get(m.id)?.(m);
196
+ } catch {}
197
+ }
198
+ });
199
+ const send = (msg) => {
200
+ try {
201
+ child.stdin?.write(`${JSON.stringify(msg)}\n`);
202
+ } catch (e) {
203
+ end(e instanceof Error ? e : new Error(String(e)));
204
+ }
205
+ };
206
+ const request = (method, params) => new Promise((resolve, reject) => {
207
+ if (ended) return reject(ended);
208
+ const id = nextId++;
209
+ pending.set(id, (m) => {
210
+ if (m.error) reject(/* @__PURE__ */ new Error(`${method}: ${m.error.message ?? "error"}`));
211
+ else resolve(m.result);
212
+ });
213
+ send({
214
+ jsonrpc: "2.0",
215
+ id,
216
+ method,
217
+ params
218
+ });
219
+ });
220
+ const timer = setTimeout(() => end(/* @__PURE__ */ new Error(`codex app-server did not answer in time.${tail()}`)), o.timeoutMs ?? 3e4);
221
+ try {
222
+ await request("initialize", { clientInfo: {
223
+ name: "conveno",
224
+ version: "0.0.0"
225
+ } });
226
+ send({
227
+ jsonrpc: "2.0",
228
+ method: "initialized"
229
+ });
230
+ return await run(request);
231
+ } finally {
232
+ clearTimeout(timer);
233
+ child.stdin?.end();
234
+ if (!exited) {
235
+ const kill = setTimeout(() => killTree(child, spawnFn), 2e3);
236
+ kill.unref();
237
+ child.once("exit", () => clearTimeout(kill));
238
+ }
239
+ }
240
+ }
241
+ const listHooks = async (request, cwd, isOurs) => {
242
+ return ((await request("hooks/list", { cwds: [cwd] })).data?.[0]?.hooks ?? []).filter(isOurs);
243
+ };
244
+ /** Conveno's hooks as Codex sees them now, whatever their trust status. */
245
+ const convenoHooks = (o) => withAppServer(o, (request) => listHooks(request, o.cwd, o.isOurs));
246
+ /** Trusts Conveno's hooks that need it, and nothing else. */
247
+ async function trustConvenoHooks(file, args, cwd, windowsVerbatimArguments, extra) {
248
+ const o = {
249
+ file,
250
+ args,
251
+ cwd,
252
+ ...windowsVerbatimArguments === void 0 ? {} : { windowsVerbatimArguments },
253
+ ...extra
254
+ };
255
+ return withAppServer(o, async (request) => {
256
+ const all = await listHooks(request, cwd, o.isOurs);
257
+ const ours = all.filter((h) => h.trustStatus === "untrusted" || h.trustStatus === "modified");
258
+ if (ours.length === 0) return {
259
+ listed: all.length,
260
+ trusted: [],
261
+ left: all.filter((h) => h.trustStatus !== "trusted").length
262
+ };
263
+ await request("config/batchWrite", {
264
+ edits: [{
265
+ keyPath: "hooks.state",
266
+ value: Object.fromEntries(ours.map((h) => [h.key, { trusted_hash: h.currentHash }])),
267
+ mergeStrategy: "upsert"
268
+ }],
269
+ reloadUserConfig: true
270
+ });
271
+ const after = await listHooks(request, cwd, o.isOurs);
272
+ return {
273
+ listed: all.length,
274
+ trusted: ours.map((h) => h.key),
275
+ left: after.filter((h) => h.trustStatus !== "trusted").length
276
+ };
277
+ });
278
+ }
279
+ /** A TOML quoted key: basic ("...") or literal ('...'). */
280
+ const QUOTED = String.raw`(?:"((?:[^"\\]|\\.)*)"|'([^']*)')`;
281
+ const unquote = (m) => m[2] ?? (m[1] ?? "").replace(/\\(.)/g, "$1");
282
+ /** The key of a `[hooks.state."<key>"]` (or single-quoted) table head, or undefined for any other line. */
283
+ function hookStateKey(line) {
284
+ const m = new RegExp(String.raw`^\[\s*hooks\s*\.\s*state\s*\.\s*${QUOTED}\s*\]\s*(?:#.*)?$`).exec(line.trim());
285
+ return m ? unquote(m) : void 0;
286
+ }
287
+ /**
288
+ * Where `hooks.state` entries are in a config.toml: a `[hooks.state."k"]` table, or a dotted key
289
+ * (`state."k".trusted_hash = ...` under `[hooks]`, `"k".trusted_hash = ...` under
290
+ * `[hooks.state]`, `hooks.state."k"...` before any table).
291
+ */
292
+ function hookStateEntries(toml) {
293
+ const out = [];
294
+ let prefix = String.raw`hooks\s*\.\s*state\s*\.\s*`;
295
+ toml.split("\n").forEach((raw, line) => {
296
+ const t = raw.trim();
297
+ if (t.startsWith("[")) {
298
+ const key = hookStateKey(t);
299
+ if (key !== void 0) out.push({
300
+ line,
301
+ key,
302
+ table: true
303
+ });
304
+ if (/^\[\s*hooks\s*\]\s*(?:#.*)?$/.test(t)) prefix = String.raw`state\s*\.\s*`;
305
+ else if (/^\[\s*hooks\s*\.\s*state\s*\]\s*(?:#.*)?$/.test(t)) prefix = "";
306
+ else prefix = null;
307
+ return;
308
+ }
309
+ if (prefix === null) return;
310
+ const m = new RegExp(`^${prefix}${QUOTED}\\s*(?:\\.\\s*[A-Za-z_-]+\\s*)?=`).exec(t);
311
+ if (m) out.push({
312
+ line,
313
+ key: unquote(m),
314
+ table: false
315
+ });
316
+ });
317
+ return out;
318
+ }
319
+ /** Remove the `hooks.state` entries for these keys from a config.toml text. */
320
+ function untrustHooks(toml, keys) {
321
+ const drop = new Set(keys);
322
+ const dead = hookStateEntries(toml).filter((e) => drop.has(e.key));
323
+ const tables = new Set(dead.filter((e) => e.table).map((e) => e.line));
324
+ const single = new Set(dead.filter((e) => !e.table).map((e) => e.line));
325
+ const out = [];
326
+ let skipping = false;
327
+ toml.split("\n").forEach((line, i) => {
328
+ if (line.trim().startsWith("[")) skipping = tables.has(i);
329
+ if (skipping) {
330
+ if (out.at(-1)?.trim() === "") out.pop();
331
+ return;
332
+ }
333
+ if (single.has(i)) return;
334
+ out.push(line);
335
+ });
336
+ return out.join("\n");
337
+ }
338
+ /** The text of a key as a TOML string, in the quote style the old one had. */
339
+ const requote = (old, key) => old.startsWith("'") ? `'${key}'` : `"${key.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
340
+ /**
341
+ * Give `hooks.state` entries another key. Codex keys trust by position, so when a hook group is
342
+ * removed, the entries of the groups after it follow them down; the hook itself is unchanged, so
343
+ * its hash still matches. `rename` returns the new key, or undefined to leave the entry alone.
344
+ */
345
+ function renameHooks(toml, rename) {
346
+ const lines = toml.split("\n");
347
+ for (const e of hookStateEntries(toml)) {
348
+ const to = rename(e.key);
349
+ if (to === void 0 || to === e.key) continue;
350
+ lines[e.line] = (lines[e.line] ?? "").replace(new RegExp(QUOTED), (tok) => requote(tok, to));
351
+ }
352
+ return lines.join("\n");
353
+ }
354
+ const HOOK_EVENTS = [
355
+ "SessionStart",
356
+ "UserPromptSubmit",
357
+ "Stop"
358
+ ];
359
+ /** Older versions also installed a PermissionRequest hook; uninstall still removes it. */
360
+ const LEGACY_HOOK_EVENTS = ["PermissionRequest"];
361
+ /** Seconds. The hook gives up after 2 s on its own; this leaves room for Node startup. Same as Claude. */
362
+ const HOOK_TIMEOUT_SECONDS = 5;
363
+ const codexDir = (env) => env.env.CODEX_HOME || join(env.home, ".codex");
364
+ const configPath = (env) => join(codexDir(env), "config.toml");
365
+ const hooksPath = (env) => join(codexDir(env), "hooks.json");
366
+ async function readIfExists(path) {
367
+ try {
368
+ return await readFile(path, "utf8");
369
+ } catch (err) {
370
+ if (err.code === "ENOENT") return null;
371
+ throw err;
372
+ }
373
+ }
374
+ /**
375
+ * Quote one word of a hook command. Codex runs the command line with `$SHELL -lc` on Unix and with
376
+ * `%COMSPEC% /C "<line>"` (cmd.exe) on Windows, so Windows words are written for cmd.exe: double
377
+ * quotes, and forward slashes in paths. cmd.exe and every Windows API accept `/`, and it avoids
378
+ * any question of how `\` meets a quote.
379
+ */
380
+ function quoteArg(arg, platform) {
381
+ if (platform === "win32") {
382
+ const word = arg.replace(/\\/g, "/");
383
+ return /^[A-Za-z0-9_./:=@+,-]+$/.test(word) ? word : `"${word.replace(/"/g, "\"\"")}"`;
384
+ }
385
+ if (/^[A-Za-z0-9_./:=@%+,-]+$/.test(arg)) return arg;
386
+ return `'${arg.replace(/'/g, `'\\''`)}'`;
387
+ }
388
+ function hookCommand(env, event) {
389
+ return [
390
+ ...env.conveno.command,
391
+ "hook",
392
+ "codex",
393
+ event
394
+ ].map((a) => quoteArg(a, env.platform)).join(" ");
395
+ }
396
+ /** A handler is ours when it runs `... hook codex <event>`; this lets us find it after the command path changes. */
397
+ const isOurs = (command, event) => typeof command === "string" && new RegExp(`\\bhook codex ${event}\\s*$`).test(command);
398
+ function parseHooksJson(path, text) {
399
+ if (text === null || text.trim() === "") return {};
400
+ try {
401
+ const value = JSON.parse(text);
402
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
403
+ } catch {}
404
+ throw new ConfigParseError(`Cannot parse ${path} as a JSON object. Fix or move the file, then run conveno again. Conveno did not change it.`);
405
+ }
406
+ const asArray = (v) => Array.isArray(v) ? v : [];
407
+ const asObject = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
408
+ function handlersOf(group) {
409
+ return asArray(asObject(group).hooks);
410
+ }
411
+ /** Hook entries for one event with our handlers removed; empty groups are dropped. */
412
+ function withoutOurs(groups, event) {
413
+ return withOursReplaced(groups, event, void 0);
414
+ }
415
+ /**
416
+ * Hook entries for one event with our handlers removed. The first group that held only ours is
417
+ * replaced by `group` where it stood: Codex keys its trust by position, so a group moved to the
418
+ * end would shift the user's groups after it and orphan their trust. With no such group, `group`
419
+ * goes last.
420
+ */
421
+ function withOursReplaced(groups, event, group) {
422
+ const out = [];
423
+ let placed = group === void 0;
424
+ for (const g of groups) {
425
+ const handlers = handlersOf(g);
426
+ const kept = handlers.filter((h) => !isOurs(asObject(h).command, event));
427
+ if (kept.length === handlers.length) out.push(g);
428
+ else if (kept.length > 0) out.push({
429
+ ...asObject(g),
430
+ hooks: kept
431
+ });
432
+ else if (!placed) {
433
+ out.push(group);
434
+ placed = true;
435
+ }
436
+ }
437
+ if (!placed) out.push(group);
438
+ return out;
439
+ }
440
+ /** Where each handler that stays moves to when ours are removed: `group:handler` to `group:handler`. */
441
+ function shiftedHandlers(groups, event) {
442
+ const moved = /* @__PURE__ */ new Map();
443
+ let g2 = 0;
444
+ groups.forEach((g, g1) => {
445
+ let h2 = 0;
446
+ handlersOf(g).forEach((h, h1) => {
447
+ if (isOurs(asObject(h).command, event)) return;
448
+ if (g1 !== g2 || h1 !== h2) moved.set(`${g1}:${h1}`, `${g2}:${h2}`);
449
+ h2++;
450
+ });
451
+ if (h2 > 0) g2++;
452
+ });
453
+ return moved;
454
+ }
455
+ function hasOurs(groups, command) {
456
+ return groups.some((g) => handlersOf(g).some((h) => asObject(h).command === command));
457
+ }
458
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
459
+ async function planHooks(env) {
460
+ const path = hooksPath(env);
461
+ const before = await readIfExists(path);
462
+ const doc = parseHooksJson(path, before);
463
+ const hooks = asObject(doc.hooks);
464
+ let changed = false;
465
+ const next = { ...hooks };
466
+ for (const event of HOOK_EVENTS) {
467
+ const groups = asArray(hooks[event]);
468
+ const command = hookCommand(env, event);
469
+ if (hasOurs(groups, command)) continue;
470
+ changed = true;
471
+ next[event] = withOursReplaced(groups, event, { hooks: [{
472
+ type: "command",
473
+ command,
474
+ timeout: HOOK_TIMEOUT_SECONDS
475
+ }] });
476
+ }
477
+ if (!changed) return [];
478
+ const partKind = (event) => asArray(hooks[event]).some((g) => handlersOf(g).some((h) => isOurs(asObject(h).command, event))) ? "update" : "add";
479
+ const parts = [];
480
+ for (const event of HOOK_EVENTS) if (!hasOurs(asArray(hooks[event]), hookCommand(env, event))) parts.push({
481
+ name: `${event} hook`,
482
+ kind: partKind(event)
483
+ });
484
+ return [{
485
+ component: "hooks",
486
+ kind: [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS].some((event) => asArray(hooks[event]).some((g) => handlersOf(g).some((h) => isOurs(asObject(h).command, event)))) ? "update" : "add",
487
+ parts,
488
+ path,
489
+ before,
490
+ after: json({
491
+ ...doc,
492
+ hooks: next
493
+ }),
494
+ description: `Add SessionStart, UserPromptSubmit and Stop hooks that deliver Conveno messages on the next turn and at the end of a turn. Codex asks you to trust new hooks: review them with /hooks.`
495
+ }];
496
+ }
497
+ async function uninstallHooks(env) {
498
+ const path = hooksPath(env);
499
+ const before = await readIfExists(path);
500
+ if (before === null) return [];
501
+ const doc = parseHooksJson(path, before);
502
+ const hooks = asObject(doc.hooks);
503
+ const next = { ...hooks };
504
+ let changed = false;
505
+ for (const event of [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS]) {
506
+ const groups = asArray(hooks[event]);
507
+ const kept = withoutOurs(groups, event);
508
+ if (JSON.stringify(kept) === JSON.stringify(groups)) continue;
509
+ changed = true;
510
+ if (kept.length > 0) next[event] = kept;
511
+ else delete next[event];
512
+ }
513
+ if (!changed) return [];
514
+ const { hooks: _drop, ...rest } = doc;
515
+ const after = Object.keys(next).length > 0 ? {
516
+ ...rest,
517
+ hooks: next
518
+ } : rest;
519
+ return [{
520
+ component: "hooks",
521
+ kind: "remove",
522
+ path,
523
+ before,
524
+ after: json(after),
525
+ description: "Remove the Conveno SessionStart, UserPromptSubmit, and Stop hooks."
526
+ }];
527
+ }
528
+ function serverSpec(env, existing) {
529
+ const [command, ...rest] = env.conveno.command;
530
+ if (!command) throw new Error("conveno command is empty; cannot build the Codex MCP entry.");
531
+ const chosen = existing?.default_tools_approval_mode;
532
+ return {
533
+ command,
534
+ args: [
535
+ ...rest,
536
+ "mcp",
537
+ "--cli",
538
+ "codex"
539
+ ],
540
+ approval: typeof chosen === "string" ? chosen : APPROVAL_MODE
541
+ };
542
+ }
543
+ async function planMcp(env) {
544
+ const path = configPath(env);
545
+ const before = await readIfExists(path);
546
+ const existing = serverOf(parseToml(path, before ?? ""));
547
+ const spec = serverSpec(env, existing);
548
+ if (matchesSpec(existing, spec)) return [];
549
+ return [{
550
+ component: "mcp",
551
+ kind: existing ? "update" : "add",
552
+ parts: [{
553
+ name: "MCP server",
554
+ kind: existing ? "update" : "add"
555
+ }],
556
+ path,
557
+ before,
558
+ after: addServer(path, before ?? "", spec),
559
+ description: `${existing ? "Update" : "Add"} the "${SERVER_NAME}" MCP server in Codex config (mcp_servers.${SERVER_NAME}). It lets Codex call Conveno's own tools without asking each time (default_tools_approval_mode = "${spec.approval}", this server only).`
560
+ }];
561
+ }
562
+ async function uninstallMcp(env) {
563
+ const path = configPath(env);
564
+ const before = await readIfExists(path);
565
+ if (before === null || !serverOf(parseToml(path, before))) return [];
566
+ return [{
567
+ component: "mcp",
568
+ kind: "remove",
569
+ path,
570
+ before,
571
+ after: removeServer(path, before),
572
+ description: `Remove the "${SERVER_NAME}" MCP server from Codex config.`
573
+ }];
574
+ }
575
+ async function detect(env) {
576
+ const configPaths = [configPath(env), hooksPath(env)];
577
+ try {
578
+ const { code, stdout } = await env.exec("codex", ["--version"]);
579
+ if (code !== 0) return {
580
+ installed: false,
581
+ configPaths
582
+ };
583
+ const version = parseCliVersion(stdout);
584
+ return {
585
+ installed: true,
586
+ binary: "codex",
587
+ ...version ? { version } : {},
588
+ configPaths
589
+ };
590
+ } catch {
591
+ return {
592
+ installed: false,
593
+ configPaths
594
+ };
595
+ }
596
+ }
597
+ const EMPTY = {
598
+ stdout: "",
599
+ exitCode: 0
600
+ };
601
+ /**
602
+ * - SessionStart, UserPromptSubmit: waiting messages as `additionalContext` (UserPromptSubmit also
603
+ * marks the turn started).
604
+ * - Stop: with messages waiting, `decision: "block"` with the framed messages as
605
+ * `reason`, which Codex turns into a continuation prompt in the same turn. This also happens when
606
+ * `stop_hook_active` is set: a message that arrives during a
607
+ * continuation would otherwise wait for the user. Conveno's wake limit bounds the chain.
608
+ */
609
+ async function hook(event, input, ctx) {
610
+ await recordThreadId(input, ctx);
611
+ if (event === "Stop") {
612
+ const reason = await endTurnContinuation(ctx);
613
+ if (reason === null) return EMPTY;
614
+ return {
615
+ stdout: `${JSON.stringify({
616
+ decision: "block",
617
+ reason
618
+ })}\n`,
619
+ exitCode: 0
620
+ };
621
+ }
622
+ if (event !== "SessionStart" && event !== "UserPromptSubmit") return EMPTY;
623
+ const additionalContext = await (event === "SessionStart" ? pendingHookContext(ctx) : startTurnContext(ctx));
624
+ if (additionalContext === null) return EMPTY;
625
+ return {
626
+ stdout: `${JSON.stringify({ hookSpecificOutput: {
627
+ hookEventName: event,
628
+ additionalContext
629
+ } })}\n`,
630
+ exitCode: 0
631
+ };
632
+ }
633
+ /**
634
+ * The hook's `session_id` is the Codex thread id, the id `codex queue --thread` takes. Codex
635
+ * sessions can share one app-server process, so the host pid alone may not tell them apart: tell
636
+ * the daemon the thread id so it can wake this session by it. Best effort; an older daemon
637
+ * without `session.setNative` just keeps the pid lookup.
638
+ */
639
+ async function recordThreadId(input, ctx) {
640
+ const threadId = asObject(input).session_id;
641
+ if (typeof threadId !== "string" || threadId === "") return;
642
+ try {
643
+ const session = await ownSession(ctx);
644
+ if (!session) return;
645
+ const call = ctx.client["session.setNative"];
646
+ if (typeof call === "function") await call({
647
+ sessionId: session.id,
648
+ nativeId: threadId
649
+ });
650
+ } catch {}
651
+ }
652
+ /** How long `codex queue` may take (it probes the shared local app-server) before we give up. */
653
+ const QUEUE_TIMEOUT_MS = 2e4;
654
+ const CUT_NOTE = "\n\n[Cut to fit a command line. Read the full messages with the conveno inbox tool.]";
655
+ const runProcess = (file, args, opts) => new Promise((resolve) => {
656
+ try {
657
+ execFile(file, args, {
658
+ timeout: QUEUE_TIMEOUT_MS,
659
+ windowsHide: true,
660
+ ...opts
661
+ }, (err, _out, stderr) => {
662
+ if (!err) return resolve(0);
663
+ const e = err;
664
+ if (e.code === "ENOENT") return resolve("missing");
665
+ if (e.killed) return resolve("timeout");
666
+ resolve({
667
+ code: typeof e.code === "number" ? e.code : 1,
668
+ stderr: String(stderr ?? "")
669
+ });
670
+ });
671
+ } catch {
672
+ resolve({
673
+ code: 1,
674
+ stderr: ""
675
+ });
676
+ }
677
+ });
678
+ /**
679
+ * Stderr texts of `codex queue` that mean it cannot wake this thread, as opposed to a failure that
680
+ * may pass. A Codex without the subcommand reads `queue` as its prompt and then rejects the flag:
681
+ * "error: unexpected argument '--thread' found" (seen from codex-cli 0.172.0 with an unknown word in
682
+ * place of `queue`); "unrecognized subcommand" is kept for builds without a prompt argument. A running app-server too old
683
+ * for it: `session_queue_commands.rs` ("does not support thread/queue/add"). An ephemeral thread:
684
+ * `thread_queue_processor.rs` `require_thread` ("ephemeral thread does not support queued
685
+ * submissions"). Exit 2 alone is not enough: clap also uses it for an ArgumentConflict.
686
+ */
687
+ const UNSUPPORTED_STDERR = [
688
+ /unexpected argument '--thread' found/i,
689
+ /unrecognized subcommand '?queue'?/i,
690
+ /does not support thread\/queue\/add/i,
691
+ /ephemeral thread does not support queued submissions/i
692
+ ];
693
+ const readText = (path) => {
694
+ try {
695
+ return readFileSync(path, "utf8");
696
+ } catch {
697
+ return;
698
+ }
699
+ };
700
+ const isFileSync = (path) => {
701
+ try {
702
+ return statSync(path).isFile();
703
+ } catch {
704
+ return false;
705
+ }
706
+ };
707
+ /** `text`, cut to `MAX_QUEUE_TEXT` with a note when longer. */
708
+ function fitQueueText(text) {
709
+ if (text.length <= 24e3) return text;
710
+ let head = text.slice(0, 23918);
711
+ if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
712
+ return head + CUT_NOTE;
713
+ }
714
+ /**
715
+ * Wake an idle Codex session: `codex queue --thread <thread id> --message=<text>`. Codex starts a
716
+ * queued message as a turn when the thread is idle and keeps it until the turn ends when it is
717
+ * busy, so the message lands like one the user typed. No `--resume`: a thread nobody has open
718
+ * stays queued and runs when it is resumed.
719
+ *
720
+ * `codex queue` takes the text only as an argument (no stdin, no file), so on Windows the text
721
+ * must never reach a cmd.exe command line, where `"`, `&`, `%VAR%` and line breaks are parsed
722
+ * again by the shim. A `codex.exe` runs directly; an npm `codex.cmd` shim is bypassed by running
723
+ * the script it names with node. Any other `.cmd` gives `unsupported`.
724
+ *
725
+ * `queued`: codex took it. `unknown`: it timed out, so it may have been queued. `unsupported`:
726
+ * no codex, a codex without `queue`, or a thread that cannot be queued to (ephemeral); the
727
+ * daemon stops asking for that session only. `failed`: anything else (including a usage
728
+ * conflict), tried again later.
729
+ *
730
+ * `queued` means Codex stored the message, not that a turn runs: a thread whose turn was
731
+ * interrupted keeps it until the user continues it (`ext/queue/src/service.rs`).
732
+ */
733
+ async function wakeCodexThread(args) {
734
+ if (!args.nativeId) return "unsupported";
735
+ if (args.text.trim() === "") return "failed";
736
+ const platform = args.platform ?? process.platform;
737
+ const env = args.env ?? process.env;
738
+ const program = findOnPath("codex", env, platform, args.isFile);
739
+ if (!program) return "unsupported";
740
+ const argv = [
741
+ "queue",
742
+ "--thread",
743
+ args.nativeId,
744
+ `--message=${fitQueueText(args.text)}`
745
+ ];
746
+ let plan;
747
+ try {
748
+ plan = planProgram(program, argv, {
749
+ platform,
750
+ env,
751
+ io: {
752
+ isFile: args.isFile ?? isFileSync,
753
+ readFile: args.readFile ?? readText
754
+ }
755
+ });
756
+ } catch {
757
+ return "unsupported";
758
+ }
759
+ if (plan.windowsVerbatimArguments) return "unsupported";
760
+ const result = await (args.run ?? runProcess)(plan.file, plan.args, { env: { ...env } });
761
+ if (result === 0) return "queued";
762
+ if (result === "timeout") return "unknown";
763
+ if (result === "missing") return "unsupported";
764
+ return UNSUPPORTED_STDERR.some((re) => re.test(result.stderr)) ? "unsupported" : "failed";
765
+ }
766
+ /** The daemon calls this when a message arrives for an idle Codex session (see WAKE-NOTES). */
767
+ async function daemonWake(a) {
768
+ return wakeCodexThread({
769
+ nativeId: a.nativeId,
770
+ text: a.text
771
+ });
772
+ }
773
+ /** Idle wake goes through `codex queue`; on a Codex without it the message waits for the next hook. */
774
+ const delivery = () => ({
775
+ nextTurn: true,
776
+ endOfTurn: true,
777
+ idleWake: true
778
+ });
779
+ /** The option that has setup trust Conveno's hooks in Codex, so `/hooks` never has to be run. */
780
+ const TRUST_OPTION = "codex-trust-hooks";
781
+ const TRUST_QUESTION = "Approve Conveno in Codex now, so it doesn't ask you the first time you open it?";
782
+ /** hooks/list and config/batchWrite are quick; a stuck Codex should not hold setup for long. */
783
+ const TRUST_TIMEOUT_MS = 15e3;
784
+ function appServerOpts(env, deps) {
785
+ const plan = planSpawn("codex", ["app-server"], {
786
+ platform: env.platform,
787
+ env: env.env
788
+ });
789
+ return {
790
+ file: plan.file,
791
+ args: plan.args,
792
+ cwd: env.cwd,
793
+ timeoutMs: TRUST_TIMEOUT_MS,
794
+ env: env.env,
795
+ isOurs: ownHookFilter({
796
+ file: hooksPath(env),
797
+ platform: env.platform,
798
+ commandFor: (event) => hookCommand(env, event)
799
+ }),
800
+ ...plan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {},
801
+ ...deps.spawnFn ? { spawnFn: deps.spawnFn } : {}
802
+ };
803
+ }
804
+ function createTrustOption(deps) {
805
+ return {
806
+ id: TRUST_OPTION,
807
+ question: TRUST_QUESTION,
808
+ defaultYes: true,
809
+ approval: true,
810
+ async enabled(env) {
811
+ try {
812
+ const hooks = await convenoHooks(appServerOpts(env, deps));
813
+ return hooks.length > 0 && hooks.every((h) => h.trustStatus === "trusted");
814
+ } catch {
815
+ return false;
816
+ }
817
+ },
818
+ applyWrites(env) {
819
+ const path = configPath(env);
820
+ const slashed = path.replace(/\\/g, "/");
821
+ const home = env.home.replace(/\\/g, "/");
822
+ const shown = home && slashed.startsWith(home) ? `~${slashed.slice(home.length)}` : slashed;
823
+ return {
824
+ paths: [path],
825
+ note: `Also approves Conveno's hooks in Codex: Codex writes hooks.state in ${shown}`
826
+ };
827
+ },
828
+ async apply(env) {
829
+ const failed = {
830
+ ok: false,
831
+ message: "Couldn't approve Conveno in Codex. It will ask you the first time you open it."
832
+ };
833
+ try {
834
+ const o = appServerOpts(env, deps);
835
+ const r = await trustConvenoHooks(o.file, o.args, o.cwd, o.windowsVerbatimArguments, {
836
+ timeoutMs: o.timeoutMs,
837
+ env: o.env,
838
+ isOurs: o.isOurs,
839
+ ...o.spawnFn ? { spawnFn: o.spawnFn } : {}
840
+ });
841
+ return r.listed === 0 || r.left > 0 ? failed : { ok: true };
842
+ } catch {
843
+ return failed;
844
+ }
845
+ }
846
+ };
847
+ }
848
+ /** Whether hooks.json has a Conveno handler. */
849
+ async function hasConvenoHooks(env) {
850
+ try {
851
+ const doc = parseHooksJson(hooksPath(env), await readIfExists(hooksPath(env)));
852
+ const hooks = asObject(doc.hooks);
853
+ return [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS].some((e) => asArray(hooks[e]).some((g) => handlersOf(g).some((h) => isOurs(asObject(h).command, e))));
854
+ } catch {
855
+ return false;
856
+ }
857
+ }
858
+ const STATE_EVENTS = {
859
+ SessionStart: "session_start",
860
+ UserPromptSubmit: "user_prompt_submit",
861
+ Stop: "stop",
862
+ PermissionRequest: "permission_request"
863
+ };
864
+ /**
865
+ * Trust entries of Conveno's hooks that can be found without asking Codex. Codex keys them
866
+ * `<hooks.json path>:<event>:<group>:<handler>`. With hooks.json still there, the entries of the
867
+ * handlers that are ours. With hooks.json gone (restored or removed first), every entry of those
868
+ * events for that file: only Conveno's setup trusted hooks there.
869
+ */
870
+ async function ownTrustKeys(env, toml) {
871
+ const file = hooksPath(env);
872
+ const norm = (p) => normalizePath(p, env.platform);
873
+ const raw = await readIfExists(file).catch(() => "");
874
+ const exists = raw !== null;
875
+ const events = Object.keys(STATE_EVENTS);
876
+ const want = /* @__PURE__ */ new Set();
877
+ if (exists) {
878
+ let hooks = {};
879
+ try {
880
+ hooks = asObject(parseHooksJson(file, raw).hooks);
881
+ } catch {
882
+ return [];
883
+ }
884
+ for (const event of events) asArray(hooks[event]).forEach((group, g) => {
885
+ handlersOf(group).forEach((h, i) => {
886
+ if (isOurs(asObject(h).command, event)) want.add(norm(`${file}:${STATE_EVENTS[event]}:${g}:${i}`));
887
+ });
888
+ });
889
+ }
890
+ const out = [];
891
+ for (const { key } of hookStateEntries(toml)) {
892
+ const k = norm(key);
893
+ if (exists ? want.has(k) : events.some((e) => k.startsWith(norm(`${file}:${STATE_EVENTS[e]}:`)))) out.push(key);
894
+ }
895
+ return out;
896
+ }
897
+ /**
898
+ * How the keys of the user's own hooks change when uninstall takes Conveno's handlers out of
899
+ * hooks.json: the groups after a removed one move down, and their trust entries must follow.
900
+ */
901
+ async function shiftedKeys(env) {
902
+ const file = hooksPath(env);
903
+ const moves = /* @__PURE__ */ new Map();
904
+ try {
905
+ const hooks = asObject(parseHooksJson(file, await readIfExists(file)).hooks);
906
+ for (const event of [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS]) for (const [from, to] of shiftedHandlers(asArray(hooks[event]), event)) moves.set(`${STATE_EVENTS[event]}:${from}`, `${STATE_EVENTS[event]}:${to}`);
907
+ } catch {
908
+ return () => void 0;
909
+ }
910
+ const same = normalizePath(file, env.platform);
911
+ return (key) => {
912
+ const k = parseHookKey(key);
913
+ if (!k || normalizePath(k.file, env.platform) !== same) return void 0;
914
+ const tail = /:([a-z_]+:\d+:\d+)$/.exec(key)?.[1];
915
+ const to = tail ? moves.get(tail) : void 0;
916
+ return to === void 0 ? void 0 : `${key.slice(0, key.length - (tail?.length ?? 0))}${to}`;
917
+ };
918
+ }
919
+ /**
920
+ * Takes the trust entries Codex recorded for Conveno's hooks out of config.toml. Found by the
921
+ * file's own keys first, so it works when hooks.json is already gone, and through Codex while
922
+ * the hooks still exist. Folded into the MCP removal when there is one, since both edit the same
923
+ * file. Entries for other hook files stay.
924
+ */
925
+ async function untrustChanges(env, deps, mcp) {
926
+ const path = configPath(env);
927
+ const before = await readIfExists(path);
928
+ if (before === null || hookStateEntries(before).length === 0) return mcp;
929
+ const keys = await ownTrustKeys(env, before);
930
+ if (await hasConvenoHooks(env)) try {
931
+ keys.push(...(await convenoHooks(appServerOpts(env, deps))).map((h) => h.key));
932
+ } catch {}
933
+ const first = mcp[0];
934
+ const base = first ? first.after : before;
935
+ const after = renameHooks(untrustHooks(base, keys), await shiftedKeys(env));
936
+ if (after === base) return mcp;
937
+ if (first) return [{
938
+ ...first,
939
+ after
940
+ }];
941
+ return [{
942
+ component: "hooks",
943
+ kind: "remove",
944
+ path,
945
+ before,
946
+ after,
947
+ description: "Remove the approval of Conveno's hooks from Codex config."
948
+ }];
949
+ }
950
+ function createCodexAdapter(deps = {}) {
951
+ return {
952
+ cli: "codex",
953
+ displayName: "Codex",
954
+ deliveryTier: "next_turn",
955
+ detect,
956
+ async plan(env) {
957
+ return [...await planMcp(env), ...await planHooks(env)];
958
+ },
959
+ optional: [createTrustOption(deps)],
960
+ async uninstallPlan(env) {
961
+ return [...await untrustChanges(env, deps, await uninstallMcp(env)), ...await uninstallHooks(env)];
962
+ },
963
+ hook,
964
+ delivery,
965
+ daemonWake
966
+ };
967
+ }
968
+ const codexAdapter = createCodexAdapter();
969
+ export { codexAdapter as t };