@conveno/cli 0.2.0-rc.8 → 0.2.0

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