@conveno/cli 0.2.0-rc.6 → 0.2.0-rc.7

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,504 @@
1
+ import { execFile } 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 { Rt as startTurnContext, U as findOnPath, ft as planProgram, it as ownSession, ot as parseCliVersion, ut as pendingHookContext, z as endTurnContinuation } from "./dist-D2hMvcZu.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 HOOK_EVENTS = [
95
+ "SessionStart",
96
+ "UserPromptSubmit",
97
+ "Stop"
98
+ ];
99
+ /** Older versions also installed a PermissionRequest hook; uninstall still removes it. */
100
+ const LEGACY_HOOK_EVENTS = ["PermissionRequest"];
101
+ /** Seconds. The hook gives up after 2 s on its own; this leaves room for Node startup. Same as Claude. */
102
+ const HOOK_TIMEOUT_SECONDS = 5;
103
+ const codexDir = (env) => env.env.CODEX_HOME || join(env.home, ".codex");
104
+ const configPath = (env) => join(codexDir(env), "config.toml");
105
+ const hooksPath = (env) => join(codexDir(env), "hooks.json");
106
+ async function readIfExists(path) {
107
+ try {
108
+ return await readFile(path, "utf8");
109
+ } catch (err) {
110
+ if (err.code === "ENOENT") return null;
111
+ throw err;
112
+ }
113
+ }
114
+ /**
115
+ * Quote one word of a hook command. Codex runs the command line with `$SHELL -lc` on Unix and with
116
+ * `%COMSPEC% /C "<line>"` (cmd.exe) on Windows, so Windows words are written for cmd.exe: double
117
+ * quotes, and forward slashes in paths. cmd.exe and every Windows API accept `/`, and it avoids
118
+ * any question of how `\` meets a quote.
119
+ */
120
+ function quoteArg(arg, platform) {
121
+ if (platform === "win32") {
122
+ const word = arg.replace(/\\/g, "/");
123
+ return /^[A-Za-z0-9_./:=@+,-]+$/.test(word) ? word : `"${word.replace(/"/g, "\"\"")}"`;
124
+ }
125
+ if (/^[A-Za-z0-9_./:=@%+,-]+$/.test(arg)) return arg;
126
+ return `'${arg.replace(/'/g, `'\\''`)}'`;
127
+ }
128
+ function hookCommand(env, event) {
129
+ return [
130
+ ...env.conveno.command,
131
+ "hook",
132
+ "codex",
133
+ event
134
+ ].map((a) => quoteArg(a, env.platform)).join(" ");
135
+ }
136
+ /** A handler is ours when it runs `... hook codex <event>`; this lets us find it after the command path changes. */
137
+ const isOurs = (command, event) => typeof command === "string" && new RegExp(`\\bhook codex ${event}\\s*$`).test(command);
138
+ function parseHooksJson(path, text) {
139
+ if (text === null || text.trim() === "") return {};
140
+ try {
141
+ const value = JSON.parse(text);
142
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
143
+ } catch {}
144
+ throw new ConfigParseError(`Cannot parse ${path} as a JSON object. Fix or move the file, then run conveno again. Conveno did not change it.`);
145
+ }
146
+ const asArray = (v) => Array.isArray(v) ? v : [];
147
+ const asObject = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
148
+ function handlersOf(group) {
149
+ return asArray(asObject(group).hooks);
150
+ }
151
+ /** Hook entries for one event with our handlers removed; empty groups are dropped. */
152
+ function withoutOurs(groups, event) {
153
+ const out = [];
154
+ for (const group of groups) {
155
+ const handlers = handlersOf(group);
156
+ const kept = handlers.filter((h) => !isOurs(asObject(h).command, event));
157
+ if (kept.length === handlers.length) out.push(group);
158
+ else if (kept.length > 0) out.push({
159
+ ...asObject(group),
160
+ hooks: kept
161
+ });
162
+ }
163
+ return out;
164
+ }
165
+ function hasOurs(groups, command) {
166
+ return groups.some((g) => handlersOf(g).some((h) => asObject(h).command === command));
167
+ }
168
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
169
+ async function planHooks(env) {
170
+ const path = hooksPath(env);
171
+ const before = await readIfExists(path);
172
+ const doc = parseHooksJson(path, before);
173
+ const hooks = asObject(doc.hooks);
174
+ let changed = false;
175
+ const next = { ...hooks };
176
+ for (const event of HOOK_EVENTS) {
177
+ const groups = asArray(hooks[event]);
178
+ const command = hookCommand(env, event);
179
+ if (hasOurs(groups, command)) continue;
180
+ changed = true;
181
+ next[event] = [...withoutOurs(groups, event), { hooks: [{
182
+ type: "command",
183
+ command,
184
+ timeout: HOOK_TIMEOUT_SECONDS
185
+ }] }];
186
+ }
187
+ if (!changed) return [];
188
+ const partKind = (event) => asArray(hooks[event]).some((g) => handlersOf(g).some((h) => isOurs(asObject(h).command, event))) ? "update" : "add";
189
+ const parts = [];
190
+ for (const event of HOOK_EVENTS) if (!hasOurs(asArray(hooks[event]), hookCommand(env, event))) parts.push({
191
+ name: `${event} hook`,
192
+ kind: partKind(event)
193
+ });
194
+ return [{
195
+ component: "hooks",
196
+ kind: [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS].some((event) => asArray(hooks[event]).some((g) => handlersOf(g).some((h) => isOurs(asObject(h).command, event)))) ? "update" : "add",
197
+ parts,
198
+ path,
199
+ before,
200
+ after: json({
201
+ ...doc,
202
+ hooks: next
203
+ }),
204
+ 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.`
205
+ }];
206
+ }
207
+ async function uninstallHooks(env) {
208
+ const path = hooksPath(env);
209
+ const before = await readIfExists(path);
210
+ if (before === null) return [];
211
+ const doc = parseHooksJson(path, before);
212
+ const hooks = asObject(doc.hooks);
213
+ const next = { ...hooks };
214
+ let changed = false;
215
+ for (const event of [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS]) {
216
+ const groups = asArray(hooks[event]);
217
+ const kept = withoutOurs(groups, event);
218
+ if (JSON.stringify(kept) === JSON.stringify(groups)) continue;
219
+ changed = true;
220
+ if (kept.length > 0) next[event] = kept;
221
+ else delete next[event];
222
+ }
223
+ if (!changed) return [];
224
+ const { hooks: _drop, ...rest } = doc;
225
+ const after = Object.keys(next).length > 0 ? {
226
+ ...rest,
227
+ hooks: next
228
+ } : rest;
229
+ return [{
230
+ component: "hooks",
231
+ kind: "remove",
232
+ path,
233
+ before,
234
+ after: json(after),
235
+ description: "Remove the Conveno SessionStart, UserPromptSubmit, and Stop hooks."
236
+ }];
237
+ }
238
+ function serverSpec(env, existing) {
239
+ const [command, ...rest] = env.conveno.command;
240
+ if (!command) throw new Error("conveno command is empty; cannot build the Codex MCP entry.");
241
+ const chosen = existing?.default_tools_approval_mode;
242
+ return {
243
+ command,
244
+ args: [
245
+ ...rest,
246
+ "mcp",
247
+ "--cli",
248
+ "codex"
249
+ ],
250
+ approval: typeof chosen === "string" ? chosen : APPROVAL_MODE
251
+ };
252
+ }
253
+ async function planMcp(env) {
254
+ const path = configPath(env);
255
+ const before = await readIfExists(path);
256
+ const existing = serverOf(parseToml(path, before ?? ""));
257
+ const spec = serverSpec(env, existing);
258
+ if (matchesSpec(existing, spec)) return [];
259
+ return [{
260
+ component: "mcp",
261
+ kind: existing ? "update" : "add",
262
+ parts: [{
263
+ name: "MCP server",
264
+ kind: existing ? "update" : "add"
265
+ }],
266
+ path,
267
+ before,
268
+ after: addServer(path, before ?? "", spec),
269
+ 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).`
270
+ }];
271
+ }
272
+ async function uninstallMcp(env) {
273
+ const path = configPath(env);
274
+ const before = await readIfExists(path);
275
+ if (before === null || !serverOf(parseToml(path, before))) return [];
276
+ return [{
277
+ component: "mcp",
278
+ kind: "remove",
279
+ path,
280
+ before,
281
+ after: removeServer(path, before),
282
+ description: `Remove the "${SERVER_NAME}" MCP server from Codex config.`
283
+ }];
284
+ }
285
+ async function detect(env) {
286
+ const configPaths = [configPath(env), hooksPath(env)];
287
+ try {
288
+ const { code, stdout } = await env.exec("codex", ["--version"]);
289
+ if (code !== 0) return {
290
+ installed: false,
291
+ configPaths
292
+ };
293
+ const version = parseCliVersion(stdout);
294
+ return {
295
+ installed: true,
296
+ binary: "codex",
297
+ ...version ? { version } : {},
298
+ configPaths
299
+ };
300
+ } catch {
301
+ return {
302
+ installed: false,
303
+ configPaths
304
+ };
305
+ }
306
+ }
307
+ const EMPTY = {
308
+ stdout: "",
309
+ exitCode: 0
310
+ };
311
+ /**
312
+ * - SessionStart, UserPromptSubmit: waiting messages as `additionalContext` (UserPromptSubmit also
313
+ * marks the turn started).
314
+ * - Stop: with messages waiting, `decision: "block"` with the framed messages as
315
+ * `reason`, which Codex turns into a continuation prompt in the same turn. This also happens when
316
+ * `stop_hook_active` is set: a message that arrives during a
317
+ * continuation would otherwise wait for the user. Conveno's wake limit bounds the chain.
318
+ */
319
+ async function hook(event, input, ctx) {
320
+ await recordThreadId(input, ctx);
321
+ if (event === "Stop") {
322
+ const reason = await endTurnContinuation(ctx);
323
+ if (reason === null) return EMPTY;
324
+ return {
325
+ stdout: `${JSON.stringify({
326
+ decision: "block",
327
+ reason
328
+ })}\n`,
329
+ exitCode: 0
330
+ };
331
+ }
332
+ if (event !== "SessionStart" && event !== "UserPromptSubmit") return EMPTY;
333
+ const additionalContext = await (event === "SessionStart" ? pendingHookContext(ctx) : startTurnContext(ctx));
334
+ if (additionalContext === null) return EMPTY;
335
+ return {
336
+ stdout: `${JSON.stringify({ hookSpecificOutput: {
337
+ hookEventName: event,
338
+ additionalContext
339
+ } })}\n`,
340
+ exitCode: 0
341
+ };
342
+ }
343
+ /**
344
+ * The hook's `session_id` is the Codex thread id, the id `codex queue --thread` takes. Codex
345
+ * sessions can share one app-server process, so the host pid alone may not tell them apart: tell
346
+ * the daemon the thread id so it can wake this session by it. Best effort; an older daemon
347
+ * without `session.setNative` just keeps the pid lookup.
348
+ */
349
+ async function recordThreadId(input, ctx) {
350
+ const threadId = asObject(input).session_id;
351
+ if (typeof threadId !== "string" || threadId === "") return;
352
+ try {
353
+ const session = await ownSession(ctx);
354
+ if (!session) return;
355
+ const call = ctx.client["session.setNative"];
356
+ if (typeof call === "function") await call({
357
+ sessionId: session.id,
358
+ nativeId: threadId
359
+ });
360
+ } catch {}
361
+ }
362
+ /** How long `codex queue` may take (it probes the shared local app-server) before we give up. */
363
+ const QUEUE_TIMEOUT_MS = 2e4;
364
+ const CUT_NOTE = "\n\n[Cut to fit a command line. Read the full messages with the conveno inbox tool.]";
365
+ const runProcess = (file, args, opts) => new Promise((resolve) => {
366
+ try {
367
+ execFile(file, args, {
368
+ timeout: QUEUE_TIMEOUT_MS,
369
+ windowsHide: true,
370
+ ...opts
371
+ }, (err, _out, stderr) => {
372
+ if (!err) return resolve(0);
373
+ const e = err;
374
+ if (e.code === "ENOENT") return resolve("missing");
375
+ if (e.killed) return resolve("timeout");
376
+ resolve({
377
+ code: typeof e.code === "number" ? e.code : 1,
378
+ stderr: String(stderr ?? "")
379
+ });
380
+ });
381
+ } catch {
382
+ resolve({
383
+ code: 1,
384
+ stderr: ""
385
+ });
386
+ }
387
+ });
388
+ /**
389
+ * Stderr texts of `codex queue` that mean it cannot wake this thread, as opposed to a failure that
390
+ * may pass. A Codex without the subcommand reads `queue` as its prompt and then rejects the flag:
391
+ * "error: unexpected argument '--thread' found" (seen from codex-cli 0.172.0 with an unknown word in
392
+ * place of `queue`); "unrecognized subcommand" is kept for builds without a prompt argument. A running app-server too old
393
+ * for it: `session_queue_commands.rs` ("does not support thread/queue/add"). An ephemeral thread:
394
+ * `thread_queue_processor.rs` `require_thread` ("ephemeral thread does not support queued
395
+ * submissions"). Exit 2 alone is not enough: clap also uses it for an ArgumentConflict.
396
+ */
397
+ const UNSUPPORTED_STDERR = [
398
+ /unexpected argument '--thread' found/i,
399
+ /unrecognized subcommand '?queue'?/i,
400
+ /does not support thread\/queue\/add/i,
401
+ /ephemeral thread does not support queued submissions/i
402
+ ];
403
+ const readText = (path) => {
404
+ try {
405
+ return readFileSync(path, "utf8");
406
+ } catch {
407
+ return;
408
+ }
409
+ };
410
+ const isFileSync = (path) => {
411
+ try {
412
+ return statSync(path).isFile();
413
+ } catch {
414
+ return false;
415
+ }
416
+ };
417
+ /** `text`, cut to `MAX_QUEUE_TEXT` with a note when longer. */
418
+ function fitQueueText(text) {
419
+ if (text.length <= 24e3) return text;
420
+ let head = text.slice(0, 23918);
421
+ if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
422
+ return head + CUT_NOTE;
423
+ }
424
+ /**
425
+ * Wake an idle Codex session: `codex queue --thread <thread id> --message=<text>`. Codex starts a
426
+ * queued message as a turn when the thread is idle and keeps it until the turn ends when it is
427
+ * busy, so the message lands like one the user typed. No `--resume`: a thread nobody has open
428
+ * stays queued and runs when it is resumed.
429
+ *
430
+ * `codex queue` takes the text only as an argument (no stdin, no file), so on Windows the text
431
+ * must never reach a cmd.exe command line, where `"`, `&`, `%VAR%` and line breaks are parsed
432
+ * again by the shim. A `codex.exe` runs directly; an npm `codex.cmd` shim is bypassed by running
433
+ * the script it names with node. Any other `.cmd` gives `unsupported`.
434
+ *
435
+ * `queued`: codex took it. `unknown`: it timed out, so it may have been queued. `unsupported`:
436
+ * no codex, a codex without `queue`, or a thread that cannot be queued to (ephemeral); the
437
+ * daemon stops asking for that session only. `failed`: anything else (including a usage
438
+ * conflict), tried again later.
439
+ *
440
+ * `queued` means Codex stored the message, not that a turn runs: a thread whose turn was
441
+ * interrupted keeps it until the user continues it (`ext/queue/src/service.rs`).
442
+ */
443
+ async function wakeCodexThread(args) {
444
+ if (!args.nativeId) return "unsupported";
445
+ if (args.text.trim() === "") return "failed";
446
+ const platform = args.platform ?? process.platform;
447
+ const env = args.env ?? process.env;
448
+ const program = findOnPath("codex", env, platform, args.isFile);
449
+ if (!program) return "unsupported";
450
+ const argv = [
451
+ "queue",
452
+ "--thread",
453
+ args.nativeId,
454
+ `--message=${fitQueueText(args.text)}`
455
+ ];
456
+ let plan;
457
+ try {
458
+ plan = planProgram(program, argv, {
459
+ platform,
460
+ env,
461
+ io: {
462
+ isFile: args.isFile ?? isFileSync,
463
+ readFile: args.readFile ?? readText
464
+ }
465
+ });
466
+ } catch {
467
+ return "unsupported";
468
+ }
469
+ if (plan.windowsVerbatimArguments) return "unsupported";
470
+ const result = await (args.run ?? runProcess)(plan.file, plan.args, { env: { ...env } });
471
+ if (result === 0) return "queued";
472
+ if (result === "timeout") return "unknown";
473
+ if (result === "missing") return "unsupported";
474
+ return UNSUPPORTED_STDERR.some((re) => re.test(result.stderr)) ? "unsupported" : "failed";
475
+ }
476
+ /** The daemon calls this when a message arrives for an idle Codex session (see WAKE-NOTES). */
477
+ async function daemonWake(a) {
478
+ return wakeCodexThread({
479
+ nativeId: a.nativeId,
480
+ text: a.text
481
+ });
482
+ }
483
+ /** Idle wake goes through `codex queue`; on a Codex without it the message waits for the next hook. */
484
+ const delivery = () => ({
485
+ nextTurn: true,
486
+ endOfTurn: true,
487
+ idleWake: true
488
+ });
489
+ const codexAdapter = {
490
+ cli: "codex",
491
+ displayName: "Codex",
492
+ deliveryTier: "next_turn",
493
+ detect,
494
+ async plan(env) {
495
+ return [...await planMcp(env), ...await planHooks(env)];
496
+ },
497
+ async uninstallPlan(env) {
498
+ return [...await uninstallMcp(env), ...await uninstallHooks(env)];
499
+ },
500
+ hook,
501
+ delivery,
502
+ daemonWake
503
+ };
504
+ export { codexAdapter as t };
@@ -1,5 +1,5 @@
1
- import { n as connect } from "./dist-BYVibI3a.js";
2
- import { Ht as updateSpawnRecord, J as isAllowed, Jt as CliKind, Rt as takeAcpLaunchFile, W as formatContinuation, i as DEFAULT_ALLOW_RULES, in as RpcErrorCode, it as parseAllowPatterns, on as SessionId, r as ConvenoError } from "./dist-BTLBO1Rp.js";
1
+ import { n as connect } from "./dist-ftx5RNCp.js";
2
+ import { Bt as takeAcpLaunchFile, Gt as updateSpawnRecord, W as formatContinuation, Y as isAllowed, Zt as CliKind, at as parseAllowPatterns, i as DEFAULT_ALLOW_RULES, ln as SessionId, r as ConvenoError, sn as RpcErrorCode } from "./dist-D2hMvcZu.js";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { existsSync, rmSync } from "node:fs";
5
5
  import { Readable, Writable } from "node:stream";
@@ -71,7 +71,7 @@ var ToolTracker = class {
71
71
  return u.sessionUpdate === "tool_call" ? next.title ?? next.kind ?? "tool" : void 0;
72
72
  }
73
73
  };
74
- const HOST_VERSION = "0.2.0-rc.6";
74
+ const HOST_VERSION = "0.2.0-rc.7";
75
75
  /** A stop request file: `conveno stop` writes it next to the spawn record. */
76
76
  const stopRequestPath = (recordPath) => recordPath.replace(/\.json$/, ".stop");
77
77
  function withTimeout(p, ms, what) {