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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,574 +1,8 @@
1
- import { Ft as relayPermission, Gt as startTurnContext, H as entriesNewestFirst, Ht as samePath, I as describeToolCall, Jt as tailJsonl, Mt as readTailLines, Ot as readHeadLine, Pt as recordCliInfo, V as endTurnContinuation, X as formatPermissionDecision, Zt as toIso, _ as asString, dt as notFound, it as isTranscriptPath, pt as parseCliVersion, qt as subdirsNewestFirst, rn as waitForWork, rt as isRecord, vt as pendingHookContext, yt as pickNewestSince } from "./dist-DUqXHTRg.js";
2
- import { isAbsolute, join } from "node:path";
3
- import { readFile, stat } from "node:fs/promises";
4
- import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
5
- // ../adapters/claude/dist/index.js
6
- const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7
- /** Read a JSON object file. Missing or blank files give `{}`; anything else that is not a JSON object throws. */
8
- async function loadJson(path) {
9
- let raw;
10
- try {
11
- raw = await readFile(path, "utf8");
12
- } catch (err) {
13
- if (err.code === "ENOENT") raw = null;
14
- else throw new Error(`Cannot read ${path}: ${err.message}. Check its permissions.`);
15
- }
16
- if (raw === null || raw.trim() === "") return {
17
- raw,
18
- value: {},
19
- indent: 2,
20
- trailingNewline: true
21
- };
22
- let value;
23
- try {
24
- value = JSON.parse(raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw);
25
- } catch (err) {
26
- throw new Error(`${path} is not valid JSON (${err.message}). Fix or remove the file, then run the install again. Nothing was changed.`);
27
- }
28
- if (!isObject(value)) throw new Error(`${path} must contain a JSON object at the top level. Fix the file, then run the install again. Nothing was changed.`);
29
- return {
30
- raw,
31
- value,
32
- indent: detectIndent(raw),
33
- trailingNewline: raw.endsWith("\n")
34
- };
35
- }
36
- function detectIndent(raw) {
37
- const m = /^([ \t]+)\S/m.exec(raw);
38
- if (!m?.[1]) return 2;
39
- return m[1].startsWith(" ") ? " " : m[1].length;
40
- }
41
- /**
42
- * Apply edits to the file's own text. Only the touched keys change: other keys, duplicate keys,
43
- * escapes, key order and line endings stay as they were, byte for byte.
44
- */
45
- function editJson(file, edits) {
46
- const bom = file.raw?.charCodeAt(0) === 65279;
47
- let text = file.raw === null || file.raw.trim() === "" ? "{}\n" : file.raw;
48
- if (bom) text = text.slice(1);
49
- const eol = text.includes("\r\n") ? "\r\n" : "\n";
50
- const formattingOptions = {
51
- insertSpaces: file.indent !== " ",
52
- tabSize: typeof file.indent === "number" ? file.indent : 2,
53
- eol
54
- };
55
- for (const e of edits) text = applyEdits(text, modify(text, e.path, e.value, { formattingOptions }));
56
- return (bom ? "" : "") + text;
57
- }
58
- /**
59
- * EXPERIMENTAL permission relay for Claude Code. The `PermissionRequest` hook runs when Claude
60
- * Code is about to ask the user for permission; printing no decision leaves the normal prompt in
61
- * place, and printing `behavior: allow` or `deny` answers it. See
62
- * https://code.claude.com/docs/en/hooks#permissionrequest and its decision control section.
63
- */
64
- const PERMISSION_EVENT$1 = "PermissionRequest";
65
- /** Seconds, in the hook config: longer than the relay's own wait, so Claude never cuts it first. */
66
- const PERMISSION_TIMEOUT_SECONDS$1 = 100;
67
- const EMPTY$1$3 = {
68
- stdout: "",
69
- exitCode: 0
70
- };
71
- const asObject$2 = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
72
- const text$1 = (v) => typeof v === "string" && v ? v : void 0;
73
- /** Claude's tools that touch one file, and the `tool_input` field naming it. */
74
- const FILE_FIELD = {
75
- Edit: "file_path",
76
- Write: "file_path",
77
- MultiEdit: "file_path",
78
- NotebookEdit: "notebook_path"
79
- };
80
- /** The request in the shape the relay takes, or null when the hook input is not one. */
81
- function callFromInput$1(input) {
82
- const body = asObject$2(input);
83
- const tool = text$1(body.tool_name);
84
- if (!tool) return null;
85
- const toolInput = asObject$2(body.tool_input);
86
- const call = { tool };
87
- const command = text$1(toolInput.command);
88
- if (command) call.command = command;
89
- const file = text$1(toolInput[FILE_FIELD[tool] ?? ""]);
90
- if (file) call.paths = [file];
91
- const description = text$1(toolInput.description);
92
- if (description) call.description = description;
93
- const cwd = text$1(body.cwd);
94
- if (cwd) call.cwd = cwd;
95
- return call;
96
- }
97
- /** Never throws. No output means Claude Code shows its own prompt. */
98
- async function permissionHook$1(input, ctx) {
99
- const call = callFromInput$1(input);
100
- if (!call) return EMPTY$1$3;
101
- const decision = await relayPermission(ctx, call);
102
- if (!decision) return EMPTY$1$3;
103
- return {
104
- stdout: formatPermissionDecision(decision, PERMISSION_EVENT$1),
105
- exitCode: 0
106
- };
107
- }
108
- /**
109
- * Claude Code keeps each session as a JSONL file at `<config dir>/projects/<project>/<session-id>.jsonl`,
110
- * where `<project>` is the working directory with every character that is not a letter or digit
111
- * replaced by `-` (a longer name is cut and hashed; on Windows it can be a hash).
112
- * https://code.claude.com/docs/en/sessions (reference/docs/claude-code, "Where transcripts are stored")
113
- *
114
- * Hooks receive `session_id` and `transcript_path` (https://code.claude.com/docs/en/hooks, common
115
- * input fields), which is the exact file. The line format is internal to Claude Code and changes
116
- * between versions, so only the fields below are read and anything else is skipped.
117
- */
118
- /** Claude Code's project directory name for a working directory. */
119
- const projectSlug = (cwd) => cwd.replace(/[^A-Za-z0-9]/g, "-");
120
- const configDir$1 = (env) => env.env.CLAUDE_CONFIG_DIR?.trim() || join(env.home, ".claude");
121
- const fileExists$1 = (p) => stat(p).then((s) => s.isFile(), () => false);
122
- /** Text of a user or tool_result content block list, without system reminders. */
123
- function blockText(content) {
124
- if (typeof content === "string") return content;
125
- if (!Array.isArray(content)) return "";
126
- const parts = [];
127
- for (const b of content) {
128
- if (!isRecord(b)) continue;
129
- if (b.type === "text" && typeof b.text === "string") parts.push(b.text);
130
- }
131
- return parts.join("\n");
132
- }
133
- const isReminder = (text) => text.trimStart().startsWith("<system-reminder>");
134
- /** Normalize one JSONL record. Exported for tests. */
135
- function parseClaudeLine(obj) {
136
- const type = obj.type;
137
- if (type !== "user" && type !== "assistant") return [];
138
- if (obj.isSidechain === true || obj.isMeta === true) return [];
139
- const message = obj.message;
140
- if (!isRecord(message)) return [];
141
- const at = toIso(obj.timestamp);
142
- const stamp = at ? { at } : {};
143
- const content = message.content;
144
- if (typeof content === "string") return content === "" || isReminder(content) ? [] : [{
145
- role: type,
146
- text: content,
147
- ...stamp
148
- }];
149
- if (!Array.isArray(content)) return [];
150
- const out = [];
151
- const text = [];
152
- for (const b of content) {
153
- if (!isRecord(b)) continue;
154
- if (b.type === "text" && typeof b.text === "string") {
155
- if (b.text !== "" && !isReminder(b.text)) text.push(b.text);
156
- } else if (b.type === "tool_use" && type === "assistant") {
157
- if (text.length > 0) out.push({
158
- role: "assistant",
159
- text: text.join("\n"),
160
- ...stamp
161
- });
162
- text.length = 0;
163
- out.push({
164
- role: "tool",
165
- text: describeToolCall(asString(b.name) ?? "tool", b.input),
166
- ...stamp
167
- });
168
- } else if (b.type === "tool_result" && type === "user") {
169
- const result = blockText(b.content);
170
- out.push({
171
- role: "tool",
172
- text: result === "" ? "(no output)" : result,
173
- ...stamp
174
- });
175
- }
176
- }
177
- if (text.length > 0) out.push({
178
- role: type,
179
- text: text.join("\n"),
180
- ...stamp
181
- });
182
- return out;
183
- }
184
- /** The `cwd` recorded in a transcript's records (each carries one), for directories whose name is a hash. */
185
- async function recordedCwd(path) {
186
- try {
187
- const { lines } = await readTailLines(path, () => true, 65536);
188
- for (const line of lines.slice(0, 40)) {
189
- const obj = JSON.parse(line);
190
- if (isRecord(obj) && typeof obj.cwd === "string") return obj.cwd;
191
- }
192
- } catch {}
193
- }
194
- async function jsonlIn(dir) {
195
- return (await entriesNewestFirst(dir)).filter((e) => !e.dir && e.name.endsWith(".jsonl"));
196
- }
197
- /** Find the transcript file for a session, or the reason there is none. */
198
- async function locateClaudeTranscript(q, env) {
199
- if (q.transcriptPath && isTranscriptPath(q.transcriptPath, ".jsonl")) {
200
- if (await fileExists$1(q.transcriptPath)) return { path: q.transcriptPath };
201
- }
202
- const projects = join(configDir$1(env), "projects");
203
- if (q.cliSessionId && /^[A-Za-z0-9_-]{1,200}$/.test(q.cliSessionId)) {
204
- const direct = join(projects, projectSlug(q.cwd), `${q.cliSessionId}.jsonl`);
205
- if (await fileExists$1(direct)) return { path: direct };
206
- for (const dir of await subdirsNewestFirst(projects)) {
207
- const p = join(dir, `${q.cliSessionId}.jsonl`);
208
- if (await fileExists$1(p)) return { path: p };
209
- }
210
- }
211
- const here = pickNewestSince(await jsonlIn(join(projects, projectSlug(q.cwd))), q.startedAt);
212
- if (here) return { path: here.path };
213
- for (const dir of await subdirsNewestFirst(projects)) {
214
- const newest = pickNewestSince(await jsonlIn(dir), q.startedAt);
215
- if (newest && await recordedCwd(newest.path) === q.cwd) return { path: newest.path };
216
- }
217
- return { error: "no transcript for this working directory since the session started" };
218
- }
219
- const claudeTranscript = { async read(q, env) {
220
- try {
221
- const found = await locateClaudeTranscript(q, env);
222
- if ("error" in found) return notFound("Claude Code", found.error);
223
- const { entries, more } = await tailJsonl(found.path, q.lastTurns, parseClaudeLine);
224
- return {
225
- ok: true,
226
- entries,
227
- more
228
- };
229
- } catch (e) {
230
- return notFound("Claude Code", e instanceof Error ? e.message : "read failed");
231
- }
232
- } };
233
- const SERVER_NAME$2 = "conveno";
234
- /** Claude Code events Conveno installs hooks for. */
235
- const HOOK_EVENTS$1 = [
236
- "SessionStart",
237
- "UserPromptSubmit",
238
- "Stop"
239
- ];
240
- /**
241
- * PermissionRequest is the experimental permission relay. It is planned only when asked for
242
- * (`conveno init --with-permission-relay`, or the first `conveno permissions relay on`), and does
243
- * nothing until a session turns the relay on. Uninstall always knows it.
244
- */
245
- const ALL_HOOK_EVENTS$1 = [...HOOK_EVENTS$1, PERMISSION_EVENT$1];
246
- /** The background listener's `conveno hook claude <arg>`. It is armed on SessionStart and Stop. */
247
- const LISTEN_EVENT = "Listen";
248
- /**
249
- * Seconds. Claude Code enforces `timeout` on an `asyncRewake` hook
250
- * (https://code.claude.com/docs/en/hooks, "Run hooks in the background"), so one armed listener
251
- * waits at most a day. Every SessionStart and Stop arms a fresh one, which replaces the old.
252
- */
253
- const LISTEN_TIMEOUT_SECONDS = 86400;
254
- /** The listener gives up on its own a few minutes before Claude Code's timeout, so it exits 0 instead of being killed. */
255
- const LISTEN_MAX_MS = 861e5;
256
- /** The handlers Conveno wants on each event, in order: the hook itself, then a listener where one is armed. */
257
- const HANDLERS = {
258
- SessionStart: ["SessionStart", LISTEN_EVENT],
259
- UserPromptSubmit: ["UserPromptSubmit"],
260
- Stop: ["Stop", LISTEN_EVENT],
261
- [PERMISSION_EVENT$1]: [PERMISSION_EVENT$1]
262
- };
263
- const EMPTY$4 = {
264
- stdout: "",
265
- exitCode: 0
266
- };
267
- /** `~/.claude.json` holds user-scope MCP servers; settings.json holds hooks. Both honor CLAUDE_CONFIG_DIR. */
268
- function paths(env) {
269
- const dir = env.env.CLAUDE_CONFIG_DIR;
270
- if (dir) return {
271
- mcp: join(dir, ".claude.json"),
272
- settings: join(dir, "settings.json")
273
- };
274
- return {
275
- mcp: join(env.home, ".claude.json"),
276
- settings: join(env.home, ".claude", "settings.json")
277
- };
278
- }
279
- /**
280
- * Quote one word of a hook command for the shell Claude Code runs it in. On Windows that is Git
281
- * Bash (PowerShell only when Git Bash is not installed), so the word is written for bash. Windows
282
- * paths use forward slashes there: bash would read `\P` inside double quotes as an escape, and
283
- * Windows accepts `/` in every API Node and Git Bash use, so `C:/Program Files/nodejs/node.exe`
284
- * means the same file and needs no escaping.
285
- */
286
- function quoteHookWord(arg, platform) {
287
- const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
288
- return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
289
- }
290
- const hookCommand$1 = (env, event) => [
291
- ...env.conveno.command,
292
- "hook",
293
- "claude",
294
- event
295
- ].map((w) => quoteHookWord(w, env.platform)).join(" ");
296
- /** One hook handler as written to settings.json. The listener runs in the background (`asyncRewake`). */
297
- function handlerFor(env, arg) {
298
- const command = hookCommand$1(env, arg);
299
- return arg === "Listen" ? {
300
- type: "command",
301
- command,
302
- asyncRewake: true,
303
- timeout: LISTEN_TIMEOUT_SECONDS
304
- } : {
305
- type: "command",
306
- command,
307
- timeout: arg === "PermissionRequest" ? PERMISSION_TIMEOUT_SECONDS$1 : 5
308
- };
309
- }
310
- const mcpArgs = (env) => [
311
- ...env.conveno.command,
312
- "mcp",
313
- "--cli",
314
- "claude"
315
- ];
316
- const desiredServer = (env) => {
317
- const [command = "conveno", ...args] = mcpArgs(env);
318
- return {
319
- type: "stdio",
320
- command,
321
- args,
322
- env: {}
323
- };
324
- };
325
- /** Recognizes our hook command even if the conveno path changed since install. */
326
- const isOurHookCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook claude (SessionStart|UserPromptSubmit|Stop|Listen|PermissionRequest)$/.test(cmd.trim());
327
- const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
328
- function groupsOf(hooks, event) {
329
- const g = hooks[event];
330
- return Array.isArray(g) ? g : [];
331
- }
332
- function hasExactHook(hooks, event, handler) {
333
- return groupsOf(hooks, event).some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => sameJson(h, handler)));
334
- }
335
- /** Every handler Conveno wants on `event` is there, exactly. */
336
- const eventComplete = (env, hooks, event) => HANDLERS[event].every((arg) => hasExactHook(hooks, event, handlerFor(env, arg)));
337
- /** Drop our hook handlers (and groups left empty by that). */
338
- function stripOurHooks(groups) {
339
- const out = [];
340
- for (const g of groups) {
341
- if (!isObject(g) || !Array.isArray(g.hooks)) {
342
- out.push(g);
343
- continue;
344
- }
345
- const kept = g.hooks.filter((h) => !(isObject(h) && isOurHookCommand(h.command)));
346
- if (kept.length === g.hooks.length) out.push(g);
347
- else if (kept.length > 0) out.push({
348
- ...g,
349
- hooks: kept
350
- });
351
- }
352
- return out;
353
- }
354
- function hooksObject(settings, path) {
355
- const h = settings.hooks;
356
- if (h === void 0) return {};
357
- if (!isObject(h)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
358
- return h;
359
- }
360
- function mcpObject(config, path) {
361
- const s = config.mcpServers;
362
- if (s === void 0) return {};
363
- if (!isObject(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
364
- return s;
365
- }
366
- async function detect$2(env) {
367
- const p = paths(env);
368
- const configPaths = [p.mcp, p.settings];
369
- try {
370
- const r = await env.exec("claude", ["--version"]);
371
- if (r.code !== 0) return {
372
- installed: false,
373
- configPaths
374
- };
375
- const version = parseCliVersion(r.stdout);
376
- return {
377
- installed: true,
378
- binary: "claude",
379
- ...version ? { version } : {},
380
- configPaths
381
- };
382
- } catch {
383
- return {
384
- installed: false,
385
- configPaths
386
- };
387
- }
388
- }
389
- /** `A`, `A and B`, `A, B and C`. */
390
- const listed = (words) => words.length < 2 ? words[0] ?? "" : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;
391
- async function plan$1(env) {
392
- const p = paths(env);
393
- const changes = [];
394
- const mcpFile = await loadJson(p.mcp);
395
- const servers = mcpObject(mcpFile.value, p.mcp);
396
- const want = desiredServer(env);
397
- if (!sameJson(servers["conveno"], want)) {
398
- const after = editJson(mcpFile, [{
399
- path: ["mcpServers", SERVER_NAME$2],
400
- value: want
401
- }]);
402
- changes.push({
403
- component: "mcp",
404
- kind: servers["conveno"] === void 0 ? "add" : "update",
405
- path: p.mcp,
406
- before: mcpFile.raw,
407
- after,
408
- description: `Register the "${SERVER_NAME$2}" MCP server at user scope (conveno mcp --cli claude).`,
409
- viaCommand: [
410
- "claude",
411
- "mcp",
412
- "add",
413
- "--scope",
414
- "user",
415
- SERVER_NAME$2,
416
- "--",
417
- ...mcpArgs(env)
418
- ]
419
- });
420
- }
421
- const setFile = await loadJson(p.settings);
422
- const hooks = hooksObject(setFile.value, p.settings);
423
- const missing = (env.permissionRelay ? ALL_HOOK_EVENTS$1 : HOOK_EVENTS$1).filter((e) => !eventComplete(env, hooks, e));
424
- if (missing.length > 0) {
425
- const next = { ...hooks };
426
- for (const e of missing) next[e] = [...stripOurHooks(groupsOf(hooks, e)), ...HANDLERS[e].map((arg) => ({ hooks: [handlerFor(env, arg)] }))];
427
- const installed = ALL_HOOK_EVENTS$1.some((e) => groupsOf(hooks, e).some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject(h) && isOurHookCommand(h.command))));
428
- changes.push({
429
- component: "hooks",
430
- kind: installed ? "update" : "add",
431
- path: p.settings,
432
- before: setFile.raw,
433
- after: editJson(setFile, missing.map((e) => ({
434
- path: ["hooks", e],
435
- value: next[e]
436
- }))),
437
- description: `Add Conveno's ${listed(missing)} hooks to Claude Code. They deliver messages at the next prompt and, in auto mode, at the end of a turn or by waking an idle session through a background listener.${missing.includes("PermissionRequest") ? " PermissionRequest is the experimental permission relay and does nothing until you turn it on for a session." : ""}`
438
- });
439
- }
440
- return changes;
441
- }
442
- async function uninstallPlan$1(env) {
443
- const p = paths(env);
444
- const changes = [];
445
- const mcpFile = await loadJson(p.mcp);
446
- if ("conveno" in mcpObject(mcpFile.value, p.mcp)) changes.push({
447
- component: "mcp",
448
- kind: "remove",
449
- path: p.mcp,
450
- before: mcpFile.raw,
451
- after: editJson(mcpFile, [{
452
- path: ["mcpServers", SERVER_NAME$2],
453
- value: void 0
454
- }]),
455
- description: `Remove the "${SERVER_NAME$2}" MCP server from user scope.`,
456
- viaCommand: [
457
- "claude",
458
- "mcp",
459
- "remove",
460
- "--scope",
461
- "user",
462
- SERVER_NAME$2
463
- ]
464
- });
465
- const setFile = await loadJson(p.settings);
466
- const hooks = hooksObject(setFile.value, p.settings);
467
- const next = { ...hooks };
468
- const edits = [];
469
- for (const e of ALL_HOOK_EVENTS$1) {
470
- const groups = groupsOf(hooks, e);
471
- const stripped = stripOurHooks(groups);
472
- if (sameJson(groups, stripped)) continue;
473
- if (stripped.length > 0) next[e] = stripped;
474
- else delete next[e];
475
- edits.push({
476
- path: ["hooks", e],
477
- value: stripped.length > 0 ? stripped : void 0
478
- });
479
- }
480
- if (edits.length > 0) {
481
- if (Object.keys(next).length === 0) edits.push({
482
- path: ["hooks"],
483
- value: void 0
484
- });
485
- changes.push({
486
- component: "hooks",
487
- kind: "remove",
488
- path: p.settings,
489
- before: setFile.raw,
490
- after: editJson(setFile, edits),
491
- description: "Remove the Conveno SessionStart, UserPromptSubmit, Stop and PermissionRequest hooks and the listener."
492
- });
493
- }
494
- return changes;
495
- }
496
- /** `stop_hook_active` from the Stop input: Claude Code is already continuing because of a Stop hook. */
497
- const stopHookActive = (input) => isObject(input) && input.stop_hook_active === true;
498
- /**
499
- * Never throws: any failure means "deliver nothing this time".
500
- *
501
- * - SessionStart: waiting messages as `additionalContext`.
502
- * - UserPromptSubmit: the turn starts (the session is busy), waiting messages as `additionalContext`.
503
- * - Stop: in auto mode with messages waiting, `decision: "block"` with the framed messages as
504
- * `reason`, so Claude continues with them. When `stop_hook_active` is set (Claude is already
505
- * continuing because of a Stop hook) it never blocks; it only records that the turn ended, and the
506
- * listener armed on this Stop wakes the session with what waits, as a new turn.
507
- * - Listen: the background listener (`asyncRewake`). Waits for work and exits 2 with the framed
508
- * messages on stderr, which wakes Claude even when the session is idle. Exit 0, silent, when it
509
- * stops for any other reason, and at once in `claude -p` (`CLAUDE_CODE_ENTRYPOINT=sdk-cli`).
510
- */
511
- async function hook$2(event, input, ctx) {
512
- switch (event) {
513
- case "SessionStart":
514
- case "UserPromptSubmit": {
515
- const [additionalContext] = await Promise.all([event === "SessionStart" ? pendingHookContext(ctx) : startTurnContext(ctx), recordCliInfo(ctx, input)]);
516
- if (additionalContext === null) return EMPTY$4;
517
- return {
518
- stdout: JSON.stringify({ hookSpecificOutput: {
519
- hookEventName: event,
520
- additionalContext
521
- } }),
522
- exitCode: 0
523
- };
524
- }
525
- case "Stop": {
526
- const reason = await endTurnContinuation(ctx, { allowContinue: !stopHookActive(input) });
527
- if (reason === null) return EMPTY$4;
528
- return {
529
- stdout: JSON.stringify({
530
- decision: "block",
531
- reason
532
- }),
533
- exitCode: 0
534
- };
535
- }
536
- case PERMISSION_EVENT$1: return permissionHook$1(input, ctx);
537
- case LISTEN_EVENT: {
538
- if (process.env.CLAUDE_CODE_ENTRYPOINT === "sdk-cli") return EMPTY$4;
539
- const text = await waitForWork(ctx, { maxMs: LISTEN_MAX_MS });
540
- return text === null ? EMPTY$4 : {
541
- stdout: "",
542
- stderr: text,
543
- exitCode: 2
544
- };
545
- }
546
- default: return EMPTY$4;
547
- }
548
- }
549
- /** Is our PermissionRequest hook in settings.json. */
550
- async function permissionHookInstalled$1(env) {
551
- const file = await loadJson(paths(env).settings);
552
- return groupsOf(isObject(file.value.hooks) ? file.value.hooks : {}, PERMISSION_EVENT$1).some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject(h) && isOurHookCommand(h.command)));
553
- }
554
- const delivery$2 = () => ({
555
- nextTurn: true,
556
- endOfTurn: true,
557
- idleWake: true
558
- });
559
- const claudeAdapter = {
560
- cli: "claude",
561
- displayName: "Claude Code",
562
- deliveryTier: "next_turn",
563
- detect: detect$2,
564
- plan: plan$1,
565
- uninstallPlan: uninstallPlan$1,
566
- hook: hook$2,
567
- permissionHookInstalled: permissionHookInstalled$1,
568
- listenEvents: [LISTEN_EVENT],
569
- delivery: delivery$2,
570
- transcript: claudeTranscript
571
- };
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 { It as startTurnContext, U as findOnPath, at as parseCliVersion, dt as planProgram, lt as pendingHookContext, rt as ownSession, z as endTurnContinuation } from "./dist-BTLBO1Rp.js";
572
6
  // ../../node_modules/.pnpm/@decimalturn+toml-patch@3.3.3/node_modules/@decimalturn/toml-patch/dist/toml-patch.js
573
7
  //! @decimalturn/toml-patch v3.3.3 - https://github.com/DecimalTurn/toml-patch - @license: MIT
574
8
  function e(e) {
@@ -7325,56 +6759,7 @@ function cs(e, t) {
7325
6759
  });
7326
6760
  }
7327
6761
  // ../adapters/codex/dist/index.js
7328
- /**
7329
- * EXPERIMENTAL permission relay for Codex. The `PermissionRequest` hook runs when Codex is about
7330
- * to ask for approval; printing no decision lets the normal approval prompt continue, and
7331
- * `behavior: allow` or `deny` decides it. Codex also reads `updatedInput`, `updatedPermissions`
7332
- * and `interrupt` as errors for this event, so the relay never prints them. See
7333
- * https://developers.openai.com/codex/hooks (PermissionRequest).
7334
- */
7335
- const PERMISSION_EVENT = "PermissionRequest";
7336
- /** Seconds, in the hook config: longer than the relay's own wait, so Codex never cuts it first. */
7337
- const PERMISSION_TIMEOUT_SECONDS = 100;
7338
- const EMPTY$1 = {
7339
- stdout: "",
7340
- exitCode: 0
7341
- };
7342
- const asObject$1 = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
7343
- const text = (v) => typeof v === "string" && v ? v : void 0;
7344
- /** Files an `apply_patch` envelope adds, updates, deletes or moves to. */
7345
- function patchPaths(patch) {
7346
- const paths = [];
7347
- for (const m of patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+?)\s*$/gm)) if (m[1]) paths.push(m[1]);
7348
- return paths;
7349
- }
7350
- /** The request in the shape the relay takes, or null when the hook input is not one. */
7351
- function callFromInput(input) {
7352
- const body = asObject$1(input);
7353
- const tool = text(body.tool_name);
7354
- if (!tool) return null;
7355
- const toolInput = asObject$1(body.tool_input);
7356
- const call = { tool };
7357
- const command = text(toolInput.command);
7358
- if (tool === "apply_patch") call.paths = command ? patchPaths(command) : [];
7359
- else if (command) call.command = command;
7360
- const description = text(toolInput.description);
7361
- if (description) call.description = description;
7362
- const cwd = text(body.cwd);
7363
- if (cwd) call.cwd = cwd;
7364
- return call;
7365
- }
7366
- /** Never throws. No output means Codex shows its own approval prompt. */
7367
- async function permissionHook(input, ctx) {
7368
- const call = callFromInput(input);
7369
- if (!call) return EMPTY$1;
7370
- const decision = await relayPermission(ctx, call);
7371
- if (!decision) return EMPTY$1;
7372
- return {
7373
- stdout: `${formatPermissionDecision(decision, PERMISSION_EVENT)}\n`,
7374
- exitCode: 0
7375
- };
7376
- }
7377
- const SERVER_NAME$1 = "conveno";
6762
+ const SERVER_NAME = "conveno";
7378
6763
  var ConfigParseError = class extends Error {};
7379
6764
  function parseToml(path, text) {
7380
6765
  try {
@@ -7388,7 +6773,7 @@ const APPROVAL_MODE = "approve";
7388
6773
  function serverOf(doc) {
7389
6774
  const servers = doc.mcp_servers;
7390
6775
  if (servers && typeof servers === "object") {
7391
- const ours = servers[SERVER_NAME$1];
6776
+ const ours = servers[SERVER_NAME];
7392
6777
  if (ours && typeof ours === "object") return ours;
7393
6778
  }
7394
6779
  }
@@ -7400,7 +6785,7 @@ const eolOf = (text) => text.includes("\r\n") ? "\r\n" : "\n";
7400
6785
  const q = (s) => JSON.stringify(s);
7401
6786
  function tableText(spec, eol) {
7402
6787
  return [
7403
- `[mcp_servers.${SERVER_NAME$1}]`,
6788
+ `[mcp_servers.${SERVER_NAME}]`,
7404
6789
  `command = ${q(spec.command)}`,
7405
6790
  `args = [${spec.args.map(q).join(", ")}]`,
7406
6791
  `default_tools_approval_mode = ${q(spec.approval)}`,
@@ -7421,7 +6806,7 @@ function addServer(path, before, spec) {
7421
6806
  const doc = parseToml(path, before);
7422
6807
  const expected = structuredClone(doc);
7423
6808
  const servers = expected.mcp_servers ?? {};
7424
- servers[SERVER_NAME$1] = {
6809
+ servers[SERVER_NAME] = {
7425
6810
  command: spec.command,
7426
6811
  args: spec.args,
7427
6812
  default_tools_approval_mode: spec.approval
@@ -7439,7 +6824,7 @@ function removeServer(path, before) {
7439
6824
  const doc = parseToml(path, before);
7440
6825
  const expected = structuredClone(doc);
7441
6826
  const servers = expected.mcp_servers;
7442
- if (servers) delete servers[SERVER_NAME$1];
6827
+ if (servers) delete servers[SERVER_NAME];
7443
6828
  const eol = eolOf(before);
7444
6829
  const lines = before.split(/\r?\n/);
7445
6830
  const out = [];
@@ -7448,7 +6833,7 @@ function removeServer(path, before) {
7448
6833
  const header = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/.exec(line);
7449
6834
  if (header) {
7450
6835
  const key = header[1].replace(/["'\s]/g, "");
7451
- const key0 = `mcp_servers.${SERVER_NAME$1}`;
6836
+ const key0 = `mcp_servers.${SERVER_NAME}`;
7452
6837
  skipping = key === key0 || key.startsWith(`${key0}.`);
7453
6838
  }
7454
6839
  if (!skipping) out.push(line);
@@ -7460,162 +6845,13 @@ function removeServer(path, before) {
7460
6845
  } catch {}
7461
6846
  return Za(before, expected);
7462
6847
  }
7463
- /**
7464
- * Codex writes one rollout file per session at
7465
- * `$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<timestamp>-<thread id>.jsonl` (default `~/.codex`).
7466
- * reference/src/codex: codex-rs/rollout/src/recorder.rs (directory layout),
7467
- * codex-rs/rollout/src/rollout_file_name.rs (file name).
7468
- *
7469
- * Each line is `{ timestamp, type, payload }` (codex-rs/history/src/rollout_payload.rs). The first
7470
- * line is `session_meta` with the thread `id` and the `cwd`. Messages, tool calls and tool outputs
7471
- * are `response_item` lines (codex-rs/protocol/src/models.rs, `ResponseItem`). Hooks receive
7472
- * `session_id` and `transcript_path` (codex-rs/hooks/src/schema.rs). Old rollouts can be compressed
7473
- * to `.jsonl.zst`; those are not read (a running session's file is plain).
7474
- */
7475
- const codexHome = (env) => env.env.CODEX_HOME?.trim() || join(env.home, ".codex");
7476
- const fileExists = (p) => stat(p).then((s) => s.isFile(), () => false);
7477
- /** Text parts the CLI injects ahead of the user's own words (environment, instructions, reminders). */
7478
- const INJECTED = /^\s*(?:<environment_context>|<user_instructions>|<permissions|<turn_aborted>|<user_action>|# AGENTS\.md instructions|<INSTRUCTIONS>)/;
7479
- function contentText(content) {
7480
- if (typeof content === "string") return content;
7481
- if (!Array.isArray(content)) return "";
7482
- const parts = [];
7483
- for (const c of content) {
7484
- if (!isRecord(c)) continue;
7485
- const t = c.type;
7486
- if ((t === "input_text" || t === "output_text" || t === "text") && typeof c.text === "string") parts.push(c.text);
7487
- }
7488
- return parts.join("\n");
7489
- }
7490
- /** Output of a tool call: a string, or an object holding the text. */
7491
- function outputText(output) {
7492
- if (typeof output === "string") return output;
7493
- if (Array.isArray(output)) return contentText(output);
7494
- if (isRecord(output)) return asString(output.content) ?? asString(output.text) ?? contentText(output.content_items);
7495
- return "";
7496
- }
7497
- /** Normalize one rollout line. Exported for tests. */
7498
- function parseCodexLine(obj) {
7499
- if (obj.type !== "response_item") return [];
7500
- const p = obj.payload;
7501
- if (!isRecord(p)) return [];
7502
- const at = toIso(obj.timestamp);
7503
- const stamp = at ? { at } : {};
7504
- switch (p.type) {
7505
- case "message": {
7506
- if (p.role !== "user" && p.role !== "assistant") return [];
7507
- const text = contentText(p.content);
7508
- if (text === "" || p.role === "user" && INJECTED.test(text)) return [];
7509
- return [{
7510
- role: p.role,
7511
- text,
7512
- ...stamp
7513
- }];
7514
- }
7515
- case "function_call":
7516
- case "custom_tool_call": {
7517
- const name = asString(p.name) ?? "tool";
7518
- return [{
7519
- role: "tool",
7520
- text: describeToolCall(name, p.arguments ?? p.input),
7521
- ...stamp
7522
- }];
7523
- }
7524
- case "local_shell_call": {
7525
- const action = isRecord(p.action) ? p.action : {};
7526
- const command = Array.isArray(action.command) ? action.command.join(" ") : action.command;
7527
- return [{
7528
- role: "tool",
7529
- text: describeToolCall("shell", command),
7530
- ...stamp
7531
- }];
7532
- }
7533
- case "function_call_output":
7534
- case "custom_tool_call_output": {
7535
- const text = outputText(p.output);
7536
- return [{
7537
- role: "tool",
7538
- text: text === "" ? "(no output)" : text,
7539
- ...stamp
7540
- }];
7541
- }
7542
- default: return [];
7543
- }
7544
- }
7545
- const ROLLOUT = /^rollout-.*\.jsonl$/;
7546
- /** Day directories under `sessions/`, newest first, for the days from `startedAt` on. */
7547
- async function dayDirs(root, startedAt) {
7548
- const since = Date.parse(startedAt);
7549
- const floor = Number.isFinite(since) ? /* @__PURE__ */ new Date(since - 1296e5) : /* @__PURE__ */ new Date(0);
7550
- const out = [];
7551
- const years = (await subdirsNewestFirst(root)).sort().reverse();
7552
- for (const y of years) for (const m of (await subdirsNewestFirst(y)).sort().reverse()) for (const d of (await subdirsNewestFirst(m)).sort().reverse()) {
7553
- const key = `${y.split(/[\\/]/).pop()}-${m.split(/[\\/]/).pop()}-${d.split(/[\\/]/).pop()}`;
7554
- const day = Date.parse(`${key}T23:59:59Z`);
7555
- if (Number.isFinite(day) && day < floor.getTime()) return out;
7556
- out.push(d);
7557
- }
7558
- return out;
7559
- }
7560
- /** Find the rollout file for a session, or the reason there is none. */
7561
- async function locateCodexRollout(q, env) {
7562
- if (q.transcriptPath && isTranscriptPath(q.transcriptPath, ".jsonl")) {
7563
- if (await fileExists(q.transcriptPath)) return { path: q.transcriptPath };
7564
- }
7565
- const root = join(codexHome(env), "sessions");
7566
- const since = Date.parse(q.startedAt);
7567
- const floor = Number.isFinite(since) ? since - 5e3 : 0;
7568
- let best;
7569
- for (const dir of await dayDirs(root, q.cliSessionId ? "" : q.startedAt)) for (const f of await entriesNewestFirst(dir)) {
7570
- if (f.dir || !ROLLOUT.test(f.name)) continue;
7571
- if (q.cliSessionId) {
7572
- if (f.name.includes(q.cliSessionId)) return { path: f.path };
7573
- continue;
7574
- }
7575
- if (f.mtimeMs < floor) continue;
7576
- if (best && best.mtimeMs >= f.mtimeMs) continue;
7577
- let cwd;
7578
- try {
7579
- const head = await readHeadLine(f.path);
7580
- const meta = head ? JSON.parse(head) : null;
7581
- const payload = isRecord(meta) && meta.type === "session_meta" ? meta.payload : void 0;
7582
- cwd = isRecord(payload) ? asString(payload.cwd) : void 0;
7583
- } catch {
7584
- continue;
7585
- }
7586
- if (cwd !== void 0 && samePath(cwd, q.cwd, env.platform)) best = {
7587
- path: f.path,
7588
- mtimeMs: f.mtimeMs
7589
- };
7590
- }
7591
- if (best) return { path: best.path };
7592
- return { error: q.cliSessionId ? "no rollout file has that session id" : "no rollout for this working directory since the session started" };
7593
- }
7594
- const codexTranscript = { async read(q, env) {
7595
- try {
7596
- const found = await locateCodexRollout(q, env);
7597
- if ("error" in found) return notFound("Codex", found.error);
7598
- const { entries, more } = await tailJsonl(found.path, q.lastTurns, parseCodexLine);
7599
- return {
7600
- ok: true,
7601
- entries,
7602
- more
7603
- };
7604
- } catch (e) {
7605
- return notFound("Codex", e instanceof Error ? e.message : "read failed");
7606
- }
7607
- } };
7608
6848
  const HOOK_EVENTS = [
7609
6849
  "SessionStart",
7610
6850
  "UserPromptSubmit",
7611
6851
  "Stop"
7612
6852
  ];
7613
- /**
7614
- * PermissionRequest is the experimental permission relay. It is planned only when asked for
7615
- * (`conveno init --with-permission-relay`, or the first `conveno permissions relay on`), and does
7616
- * nothing until a session turns the relay on. Uninstall always knows it.
7617
- */
7618
- const ALL_HOOK_EVENTS = [...HOOK_EVENTS, PERMISSION_EVENT];
6853
+ /** Older versions also installed a PermissionRequest hook; uninstall still removes it. */
6854
+ const LEGACY_HOOK_EVENTS = ["PermissionRequest"];
7619
6855
  /** Seconds. The hook gives up after 2 s on its own; this leaves room for Node startup. Same as Claude. */
7620
6856
  const HOOK_TIMEOUT_SECONDS = 5;
7621
6857
  const codexDir = (env) => env.env.CODEX_HOME || join(env.home, ".codex");
@@ -7683,7 +6919,7 @@ function withoutOurs(groups, event) {
7683
6919
  function hasOurs(groups, command) {
7684
6920
  return groups.some((g) => handlersOf(g).some((h) => asObject(h).command === command));
7685
6921
  }
7686
- const json$1 = (value) => `${JSON.stringify(value, null, 2)}\n`;
6922
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
7687
6923
  async function planHooks(env) {
7688
6924
  const path = hooksPath(env);
7689
6925
  const before = await readIfExists(path);
@@ -7691,7 +6927,7 @@ async function planHooks(env) {
7691
6927
  const hooks = asObject(doc.hooks);
7692
6928
  let changed = false;
7693
6929
  const next = { ...hooks };
7694
- for (const event of env.permissionRelay ? ALL_HOOK_EVENTS : HOOK_EVENTS) {
6930
+ for (const event of HOOK_EVENTS) {
7695
6931
  const groups = asArray(hooks[event]);
7696
6932
  const command = hookCommand(env, event);
7697
6933
  if (hasOurs(groups, command)) continue;
@@ -7699,20 +6935,27 @@ async function planHooks(env) {
7699
6935
  next[event] = [...withoutOurs(groups, event), { hooks: [{
7700
6936
  type: "command",
7701
6937
  command,
7702
- timeout: event === "PermissionRequest" ? PERMISSION_TIMEOUT_SECONDS : HOOK_TIMEOUT_SECONDS
6938
+ timeout: HOOK_TIMEOUT_SECONDS
7703
6939
  }] }];
7704
6940
  }
7705
6941
  if (!changed) return [];
6942
+ const partKind = (event) => asArray(hooks[event]).some((g) => handlersOf(g).some((h) => isOurs(asObject(h).command, event))) ? "update" : "add";
6943
+ const parts = [];
6944
+ for (const event of HOOK_EVENTS) if (!hasOurs(asArray(hooks[event]), hookCommand(env, event))) parts.push({
6945
+ name: `${event} hook`,
6946
+ kind: partKind(event)
6947
+ });
7706
6948
  return [{
7707
6949
  component: "hooks",
7708
- kind: ALL_HOOK_EVENTS.some((event) => asArray(hooks[event]).some((g) => handlersOf(g).some((h) => isOurs(asObject(h).command, event)))) ? "update" : "add",
6950
+ kind: [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS].some((event) => asArray(hooks[event]).some((g) => handlersOf(g).some((h) => isOurs(asObject(h).command, event)))) ? "update" : "add",
6951
+ parts,
7709
6952
  path,
7710
6953
  before,
7711
- after: json$1({
6954
+ after: json({
7712
6955
  ...doc,
7713
6956
  hooks: next
7714
6957
  }),
7715
- description: `Add ${env.permissionRelay ? "a PermissionRequest hook for the experimental permission relay (it does nothing until you turn the relay on for a session) and, if missing, " : ""}SessionStart, UserPromptSubmit and Stop hooks that deliver Conveno messages on the next turn and, in auto mode, at the end of a turn. Codex asks you to trust new hooks: review them with /hooks.`
6958
+ 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.`
7716
6959
  }];
7717
6960
  }
7718
6961
  async function uninstallHooks(env) {
@@ -7723,7 +6966,7 @@ async function uninstallHooks(env) {
7723
6966
  const hooks = asObject(doc.hooks);
7724
6967
  const next = { ...hooks };
7725
6968
  let changed = false;
7726
- for (const event of ALL_HOOK_EVENTS) {
6969
+ for (const event of [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS]) {
7727
6970
  const groups = asArray(hooks[event]);
7728
6971
  const kept = withoutOurs(groups, event);
7729
6972
  if (JSON.stringify(kept) === JSON.stringify(groups)) continue;
@@ -7742,8 +6985,8 @@ async function uninstallHooks(env) {
7742
6985
  kind: "remove",
7743
6986
  path,
7744
6987
  before,
7745
- after: json$1(after),
7746
- description: "Remove the Conveno SessionStart, UserPromptSubmit, Stop and PermissionRequest hooks."
6988
+ after: json(after),
6989
+ description: "Remove the Conveno SessionStart, UserPromptSubmit, and Stop hooks."
7747
6990
  }];
7748
6991
  }
7749
6992
  function serverSpec(env, existing) {
@@ -7761,7 +7004,7 @@ function serverSpec(env, existing) {
7761
7004
  approval: typeof chosen === "string" ? chosen : APPROVAL_MODE
7762
7005
  };
7763
7006
  }
7764
- async function planMcp$1(env) {
7007
+ async function planMcp(env) {
7765
7008
  const path = configPath(env);
7766
7009
  const before = await readIfExists(path);
7767
7010
  const existing = serverOf(parseToml(path, before ?? ""));
@@ -7770,13 +7013,17 @@ async function planMcp$1(env) {
7770
7013
  return [{
7771
7014
  component: "mcp",
7772
7015
  kind: existing ? "update" : "add",
7016
+ parts: [{
7017
+ name: "MCP server",
7018
+ kind: existing ? "update" : "add"
7019
+ }],
7773
7020
  path,
7774
7021
  before,
7775
7022
  after: addServer(path, before ?? "", spec),
7776
- description: `${existing ? "Update" : "Add"} the "${SERVER_NAME$1}" MCP server in Codex config (mcp_servers.${SERVER_NAME$1}). It lets Codex call Conveno's own tools without asking each time (default_tools_approval_mode = "${spec.approval}", this server only).`
7023
+ 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).`
7777
7024
  }];
7778
7025
  }
7779
- async function uninstallMcp$1(env) {
7026
+ async function uninstallMcp(env) {
7780
7027
  const path = configPath(env);
7781
7028
  const before = await readIfExists(path);
7782
7029
  if (before === null || !serverOf(parseToml(path, before))) return [];
@@ -7786,10 +7033,10 @@ async function uninstallMcp$1(env) {
7786
7033
  path,
7787
7034
  before,
7788
7035
  after: removeServer(path, before),
7789
- description: `Remove the "${SERVER_NAME$1}" MCP server from Codex config.`
7036
+ description: `Remove the "${SERVER_NAME}" MCP server from Codex config.`
7790
7037
  }];
7791
7038
  }
7792
- async function detect$1(env) {
7039
+ async function detect(env) {
7793
7040
  const configPaths = [configPath(env), hooksPath(env)];
7794
7041
  try {
7795
7042
  const { code, stdout } = await env.exec("codex", ["--version"]);
@@ -7811,23 +7058,23 @@ async function detect$1(env) {
7811
7058
  };
7812
7059
  }
7813
7060
  }
7814
- const EMPTY$2 = {
7061
+ const EMPTY = {
7815
7062
  stdout: "",
7816
7063
  exitCode: 0
7817
7064
  };
7818
7065
  /**
7819
7066
  * - SessionStart, UserPromptSubmit: waiting messages as `additionalContext` (UserPromptSubmit also
7820
7067
  * marks the turn started).
7821
- * - Stop: in auto mode with messages waiting, `decision: "block"` with the framed messages as
7068
+ * - Stop: with messages waiting, `decision: "block"` with the framed messages as
7822
7069
  * `reason`, which Codex turns into a continuation prompt in the same turn. This also happens when
7823
- * `stop_hook_active` is set: Codex has no idle wake, so a message that arrives during a
7824
- * continuation would otherwise wait for the user. Conveno's auto-mode limit bounds the chain.
7070
+ * `stop_hook_active` is set: a message that arrives during a
7071
+ * continuation would otherwise wait for the user. Conveno's wake limit bounds the chain.
7825
7072
  */
7826
- async function hook$1(event, input, ctx) {
7827
- if (event === "PermissionRequest") return permissionHook(input, ctx);
7073
+ async function hook(event, input, ctx) {
7074
+ await recordThreadId(input, ctx);
7828
7075
  if (event === "Stop") {
7829
7076
  const reason = await endTurnContinuation(ctx);
7830
- if (reason === null) return EMPTY$2;
7077
+ if (reason === null) return EMPTY;
7831
7078
  return {
7832
7079
  stdout: `${JSON.stringify({
7833
7080
  decision: "block",
@@ -7836,9 +7083,9 @@ async function hook$1(event, input, ctx) {
7836
7083
  exitCode: 0
7837
7084
  };
7838
7085
  }
7839
- if (event !== "SessionStart" && event !== "UserPromptSubmit") return EMPTY$2;
7840
- const [additionalContext] = await Promise.all([event === "SessionStart" ? pendingHookContext(ctx) : startTurnContext(ctx), recordCliInfo(ctx, input)]);
7841
- if (additionalContext === null) return EMPTY$2;
7086
+ if (event !== "SessionStart" && event !== "UserPromptSubmit") return EMPTY;
7087
+ const additionalContext = await (event === "SessionStart" ? pendingHookContext(ctx) : startTurnContext(ctx));
7088
+ if (additionalContext === null) return EMPTY;
7842
7089
  return {
7843
7090
  stdout: `${JSON.stringify({ hookSpecificOutput: {
7844
7091
  hookEventName: event,
@@ -7847,780 +7094,140 @@ async function hook$1(event, input, ctx) {
7847
7094
  exitCode: 0
7848
7095
  };
7849
7096
  }
7850
- /** Is our PermissionRequest hook in hooks.json. */
7851
- async function permissionHookInstalled(env) {
7852
- const path = hooksPath(env);
7853
- const doc = parseHooksJson(path, await readIfExists(path));
7854
- return asArray(asObject(doc.hooks)[PERMISSION_EVENT]).some((g) => handlersOf(g).some((h) => isOurs(asObject(h).command, PERMISSION_EVENT)));
7855
- }
7856
- /** No idle wake: a Codex session in auto mode gets waiting messages when its current turn ends. */
7857
- const delivery$1 = () => ({
7858
- nextTurn: true,
7859
- endOfTurn: true,
7860
- idleWake: false
7861
- });
7862
- const codexAdapter = {
7863
- cli: "codex",
7864
- displayName: "Codex",
7865
- deliveryTier: "next_turn",
7866
- detect: detect$1,
7867
- async plan(env) {
7868
- return [...await planMcp$1(env), ...await planHooks(env)];
7869
- },
7870
- async uninstallPlan(env) {
7871
- return [...await uninstallMcp$1(env), ...await uninstallHooks(env)];
7872
- },
7873
- hook: hook$1,
7874
- permissionHookInstalled,
7875
- delivery: delivery$1,
7876
- transcript: codexTranscript
7877
- };
7878
- // ../adapters/opencode/dist/index.js
7879
- /**
7880
- * The OpenCode 1.x plugin Conveno installs as `<config dir>/plugins/conveno.js`. OpenCode 1.x loads
7881
- * every `.js` file in the global `plugins/` folder at startup (https://opencode.ai/docs/plugins/,
7882
- * "From local files") and calls each exported function with a context that holds an SDK `client`.
7883
- *
7884
- * The plugin does no Conveno work itself; it runs `conveno hook opencode <event>`, which finds the
7885
- * session by its host process (this OpenCode process) like every other hook:
7886
- *
7887
- * - On `session.idle` of a top-level session it runs `Idle`. In auto mode with messages waiting,
7888
- * that prints the continuation prompt, and the plugin sends it with `client.session.promptAsync`.
7889
- * - Otherwise it starts `Listen`, which waits in the background and prints a prompt when work
7890
- * arrives while the session is idle; the plugin sends that the same way.
7891
- * - When the session turns busy, the plugin is disposed, or a newer listener starts, the listener
7892
- * is stopped. It also stops by itself when OpenCode exits.
7893
- */
7894
- /** Start of the first line of every Conveno plugin file, whatever the OpenCode line it is for. */
7895
- const PLUGIN_MARKER_PREFIX = "// conveno-plugin:";
7896
- /** First line of the 1.x plugin. Uninstall and re-install recognise a plugin by the marker prefix. */
7897
- const PLUGIN_MARKER = `${PLUGIN_MARKER_PREFIX} 1`;
7898
7097
  /**
7899
- * The part both plugins share: the import, the baked-in command, and `run`, which starts
7900
- * `conveno hook opencode <event>` and resolves with what it prints. Plain JavaScript source text.
7098
+ * The hook's `session_id` is the Codex thread id, the id `codex queue --thread` takes. Codex
7099
+ * sessions can share one app-server process, so the host pid alone may not tell them apart: tell
7100
+ * the daemon the thread id so it can wake this session by it. Best effort; an older daemon
7101
+ * without `session.setNative` just keeps the pid lookup.
7901
7102
  */
7902
- function runHelper(command) {
7903
- return `import { spawn } from "node:child_process";
7904
-
7905
- const COMMAND = ${JSON.stringify(command)};
7906
- // A bare \`conveno\` on Windows is a .cmd shim, which only a shell can start. Every argument is a plain word.
7907
- const SHELL = process.platform === "win32" && !/\\.exe$/i.test(COMMAND[0]);
7908
-
7909
- function run(event, sessionID, directory) {
7910
- const [file, ...args] = COMMAND;
7911
- const child = spawn(file, [...args, "hook", "opencode", event], {
7912
- stdio: ["pipe", "pipe", "ignore"],
7913
- shell: SHELL,
7914
- windowsHide: true,
7915
- });
7916
- let out = "";
7917
- child.stdout.setEncoding("utf8");
7918
- child.stdout.on("data", (chunk) => {
7919
- out += chunk;
7920
- });
7921
- const done = new Promise((resolve) => {
7922
- child.once("error", () => resolve(""));
7923
- child.once("close", (code) => resolve(code === 0 ? out.trim() : ""));
7924
- });
7925
- child.stdin.on("error", () => {});
7926
- child.stdin.end(JSON.stringify({ hook_event_name: event, sessionID, directory }));
7927
- return { child, done };
7928
- }`;
7929
- }
7930
- /** The plugin source with the conveno command baked in. Plain JavaScript, no imports beyond Node built-ins. */
7931
- function pluginSource(command) {
7932
- return `${PLUGIN_MARKER}
7933
- // Conveno plugin for OpenCode. Written by \`conveno init\`; \`conveno uninstall\` removes it.
7934
- // It hands Conveno messages to an idle session in auto mode. See https://conveno.dev.
7935
- ${runHelper(command)}
7936
-
7937
- export const ConvenoPlugin = async ({ client }) => {
7938
- let listener;
7939
-
7940
- const stop = () => {
7941
- if (!listener) return;
7942
- listener.child.kill();
7943
- listener = undefined;
7944
- };
7945
-
7946
- const prompt = async (sessionID, text) => {
7947
- try {
7948
- await client.session.promptAsync({
7949
- path: { id: sessionID },
7950
- body: { parts: [{ type: "text", text }] },
7951
- });
7952
- } catch {
7953
- // The session is gone or busy again: the messages stay in the Conveno inbox.
7954
- }
7955
- };
7956
-
7957
- const topLevel = async (sessionID) => {
7958
- try {
7959
- const res = await client.session.get({ path: { id: sessionID } });
7960
- return !res?.data?.parentID;
7961
- } catch {
7962
- return false;
7963
- }
7964
- };
7965
-
7966
- const onIdle = async (sessionID) => {
7967
- if (!(await topLevel(sessionID))) return;
7968
- stop();
7969
- const now = await run("Idle", sessionID).done;
7970
- if (now) return prompt(sessionID, now);
7971
- const current = { ...run("Listen", sessionID), sessionID };
7972
- listener = current;
7973
- const text = await current.done;
7974
- if (listener === current) listener = undefined;
7975
- if (text) await prompt(sessionID, text);
7976
- };
7977
-
7978
- return {
7979
- event: async ({ event }) => {
7980
- if (event.type === "session.idle") void onIdle(event.properties.sessionID);
7981
- else if (
7982
- event.type === "session.status" &&
7983
- event.properties.status?.type === "busy" &&
7984
- event.properties.sessionID === listener?.sessionID
7985
- ) {
7986
- stop();
7987
- }
7988
- },
7989
- dispose: async () => stop(),
7990
- };
7991
- };
7992
- `;
7993
- }
7994
- /**
7995
- * The OpenCode 2.x plugin Conveno installs as `<config dir>/plugins/conveno.js`, the same path as
7996
- * the 1.x one. OpenCode 2.x loads every `.js` and `.ts` file in the global `plugins/` folder
7997
- * (https://opencode.ai/docs/plugins/, "Discover"; `packages/core/src/plugin/module.ts` at tag
7998
- * v2.4.3 accepts a standalone file whose default export is `{ id, setup }`, the object
7999
- * `Plugin.define` returns, so the file needs no import of `@opencode/plugin`).
8000
- *
8001
- * The plugin runs inside the OpenCode server process, which is also the parent of the MCP server
8002
- * it starts, so `conveno hook opencode <event>` finds the session by host process like every other
8003
- * hook. It does no Conveno work itself:
8004
- *
8005
- * - When an execution of a top-level session in this plugin's directory ends
8006
- * (`session.execution.succeeded`) it runs `Idle`. In auto mode with messages waiting, that prints
8007
- * the continuation prompt, and the plugin sends it with `ctx.session.prompt`
8008
- * (`POST /api/session/{id}/prompt`).
8009
- * - After a failed or interrupted execution it runs `Stopped`, which records the end without
8010
- * continuing. An execution that a newer one superseded, or that a shutdown cut off, does nothing.
8011
- * - Then it starts `Listen`, which waits in the background and prints a prompt when work arrives
8012
- * while the session is idle; the plugin sends that the same way.
8013
- * - `session.execution.started`, a newer listener, or unloading the plugin stops the listener.
8014
- *
8015
- * `session.status` and `session.idle` are not used: 2.4.3 does not deliver them to plugins.
8016
- */
8017
- /** First line of the 2.x plugin. */
8018
- const PLUGIN_MARKER_V2 = `${PLUGIN_MARKER_PREFIX} 2`;
8019
- /** The plugin source with the conveno command baked in. Plain JavaScript, no imports beyond Node built-ins. */
8020
- function pluginSourceV2(command) {
8021
- return `${PLUGIN_MARKER_V2}
8022
- // Conveno plugin for OpenCode 2.x. Written by \`conveno init\`; \`conveno uninstall\` removes it.
8023
- // It hands Conveno messages to an idle session in auto mode. See https://conveno.dev.
8024
- ${runHelper(command)}
8025
-
8026
- export default {
8027
- id: "conveno",
8028
- setup(ctx) {
8029
- const controller = new AbortController();
8030
- let listener;
8031
-
8032
- const stop = () => {
8033
- if (!listener) return;
8034
- listener.child.kill();
8035
- listener = undefined;
8036
- };
8037
-
8038
- const prompt = async (sessionID, text) => {
8039
- try {
8040
- await ctx.session.prompt({ sessionID, text });
8041
- } catch {
8042
- // The session is gone or busy again: the messages stay in the Conveno inbox.
8043
- }
8044
- };
8045
-
8046
- // The server sends every plugin the events of every location it serves. Only top-level
8047
- // sessions of this plugin's own directory are ours.
8048
- const ours = async (sessionID) => {
8049
- try {
8050
- const info = await ctx.session.get({ sessionID });
8051
- return !info.parentID && info.location.directory === ctx.location.directory;
8052
- } catch {
8053
- return false;
8054
- }
8055
- };
8056
-
8057
- const onEnd = async (sessionID, event) => {
8058
- if (!(await ours(sessionID))) return;
8059
- stop();
8060
- const now = await run(event, sessionID, ctx.location.directory).done;
8061
- if (now) return prompt(sessionID, now);
8062
- const current = { ...run("Listen", sessionID, ctx.location.directory), sessionID };
8063
- listener = current;
8064
- const text = await current.done;
8065
- if (listener === current) listener = undefined;
8066
- if (text) await prompt(sessionID, text);
8067
- };
8068
-
8069
- void (async () => {
8070
- try {
8071
- for await (const event of ctx.event.subscribe({
8072
- types: [
8073
- "session.execution.started",
8074
- "session.execution.succeeded",
8075
- "session.execution.failed",
8076
- "session.execution.interrupted",
8077
- ],
8078
- signal: controller.signal,
8079
- })) {
8080
- const { sessionID } = event.data;
8081
- if (event.type === "session.execution.started") {
8082
- if (sessionID === listener?.sessionID) stop();
8083
- } else if (event.type === "session.execution.succeeded") {
8084
- void onEnd(sessionID, "Idle");
8085
- } else if (
8086
- event.type === "session.execution.failed" ||
8087
- (event.type === "session.execution.interrupted" &&
8088
- (event.data.reason === "user" || event.data.reason === "inactivity"))
8089
- ) {
8090
- void onEnd(sessionID, "Stopped");
8091
- }
8092
- }
8093
- } catch {
8094
- // The subscription ended with the plugin.
8095
- }
8096
- })();
8097
-
8098
- return () => {
8099
- controller.abort();
8100
- stop();
8101
- };
8102
- },
8103
- };
8104
- `;
8105
- }
8106
- /**
8107
- * OpenCode keeps sessions in SQLite: `opencode.db` in the XDG data directory, `<data>/opencode/`
8108
- * (`~/.local/share/opencode` unless XDG_DATA_HOME is set; the same on every platform because it
8109
- * uses xdg-basedir). A build from a channel other than latest, beta or prod writes
8110
- * `opencode-<channel>.db`, and OPENCODE_DB overrides the file.
8111
- * reference/src/opencode/packages/core/src/database/database.ts (path),
8112
- * packages/core/src/global.ts (data directory).
8113
- *
8114
- * The tables are `session` (id, directory, parent_id, time_created, time_updated), `message` (id,
8115
- * session_id, time_created, data JSON with `role`) and `part` (id, message_id, data JSON with
8116
- * `type`: text, tool, reasoning, ...). packages/core/src/session/sql.ts, packages/schema/src/v1/session.ts.
8117
- *
8118
- * OpenCode 2.x writes the same file with different tables: `session_v2` (id, directory, parent_id,
8119
- * time_updated), `session_message` (id, session_id, type `user`, `assistant`, `synthetic`, `idle`, ...,
8120
- * time_created, data JSON) and `session_part` (message_id, ordinal, type `text`, `reasoning`, `tool`, data JSON),
8121
- * as `opencode.db` in the same directory on Linux, macOS and Windows (`packages/util/src/global-roots.ts` at
8122
- * v2.4.3: `XDG_DATA_HOME` or `~/.local/share`). A fresh 2.x database has no `session` table; one carried
8123
- * over from 1.x has both, so each file is tried as 2.x first, then as 1.x.
8124
- * reference/src/opencode (v2.4.3) packages/core/src/session/sql.ts, packages/schema/src/session-message.ts.
8125
- * The database is opened read-only and never written.
8126
- */
8127
- const dataDir = (env) => join(env.env.XDG_DATA_HOME?.trim() || join(env.home, ".local", "share"), "opencode");
8128
- /** Database files to try, the most recently written first (the write-ahead log counts as a write). */
8129
- async function openCodeDatabases(env) {
8130
- const override = env.env.OPENCODE_DB?.trim();
8131
- if (override && override !== ":memory:") return [isAbsolute(override) ? override : join(dataDir(env), override)];
8132
- const files = (await entriesNewestFirst(dataDir(env))).filter((e) => !e.dir && /^opencode(?:-[A-Za-z0-9._-]+)?\.db$/.test(e.name));
8133
- return (await Promise.all(files.map(async (f) => {
8134
- const wal = await stat(`${f.path}-wal`).then((s) => s.mtimeMs, () => 0);
8135
- return {
8136
- path: f.path,
8137
- mtimeMs: Math.max(f.mtimeMs, wal)
8138
- };
8139
- }))).sort((a, b) => b.mtimeMs - a.mtimeMs).map((f) => f.path);
8140
- }
8141
- const slash = (p) => p.replace(/\\/g, "/");
8142
- const sameDir = (a, b, platform) => {
8143
- const norm = (p) => {
8144
- const s = slash(p).replace(/\/+$/, "");
8145
- return platform === "win32" ? s.toLowerCase() : s;
8146
- };
8147
- return norm(a) === norm(b);
8148
- };
8149
- function json(v) {
8150
- if (typeof v !== "string") return void 0;
7103
+ async function recordThreadId(input, ctx) {
7104
+ const threadId = asObject(input).session_id;
7105
+ if (typeof threadId !== "string" || threadId === "") return;
8151
7106
  try {
8152
- const o = JSON.parse(v);
8153
- return isRecord(o) ? o : void 0;
8154
- } catch {
8155
- return;
8156
- }
8157
- }
8158
- /** Entries for one message: its role and its parts. Exported for tests. */
8159
- function messageEntries(role, createdMs, parts) {
8160
- if (role !== "user" && role !== "assistant") return [];
8161
- const at = toIso(createdMs);
8162
- const stamp = at ? { at } : {};
8163
- const out = [];
8164
- for (const p of parts) if (p.type === "text") {
8165
- if (p.synthetic === true || p.ignored === true) continue;
8166
- const text = asString(p.text);
8167
- if (text) out.push({
8168
- role,
8169
- text,
8170
- ...stamp
8171
- });
8172
- } else if (p.type === "tool") {
8173
- const state = isRecord(p.state) ? p.state : {};
8174
- out.push({
8175
- role: "tool",
8176
- text: describeToolCall(asString(p.tool) ?? "tool", state.input),
8177
- ...stamp
7107
+ const session = await ownSession(ctx);
7108
+ if (!session) return;
7109
+ const call = ctx.client["session.setNative"];
7110
+ if (typeof call === "function") await call({
7111
+ sessionId: session.id,
7112
+ nativeId: threadId
8178
7113
  });
8179
- const result = asString(state.output) ?? asString(state.error);
8180
- if (result !== void 0 && result !== "") out.push({
8181
- role: "tool",
8182
- text: result,
8183
- ...stamp
8184
- });
8185
- }
8186
- return out;
8187
- }
8188
- async function openReadOnly(path) {
8189
- const { DatabaseSync } = await import("node:sqlite");
8190
- return new DatabaseSync(path, { readOnly: true });
8191
- }
8192
- function findSessionV1(db, q, platform) {
8193
- if (q.cliSessionId) {
8194
- const r = db.prepare("SELECT id FROM session WHERE id = ?").all(q.cliSessionId)[0];
8195
- return asString(r?.id);
8196
- }
8197
- const since = Date.parse(q.startedAt);
8198
- const floor = Number.isFinite(since) ? since - 5e3 : 0;
8199
- const rows = db.prepare("SELECT id, directory FROM session WHERE parent_id IS NULL AND time_updated >= ? ORDER BY time_updated DESC LIMIT 200").all(floor);
8200
- return asString(rows.find((r) => sameDir(asString(r.directory) ?? "", q.cwd, platform))?.id);
8201
- }
8202
- function readSessionV1(db, sessionId, n) {
8203
- const fetch = n * 4 + 20;
8204
- const messages = db.prepare("SELECT id, time_created, data FROM message WHERE session_id = ? ORDER BY time_created DESC, id DESC LIMIT ?").all(sessionId, fetch + 1).reverse();
8205
- const more = messages.length > fetch;
8206
- const used = more ? messages.slice(1) : messages;
8207
- const entries = [];
8208
- for (const m of used) {
8209
- const data = json(m.data);
8210
- const role = asString(data?.role);
8211
- if (!role) continue;
8212
- const parts = db.prepare("SELECT data FROM part WHERE message_id = ? ORDER BY id").all(asString(m.id) ?? "").map((p) => json(p.data)).filter((p) => p !== void 0);
8213
- entries.push(...messageEntries(role, m.time_created, parts));
8214
- }
8215
- return {
8216
- entries: entries.slice(-n),
8217
- more: more || entries.length > n
8218
- };
8219
- }
8220
- const hasTable = (db, name) => db.prepare("SELECT 1 AS x FROM sqlite_master WHERE type = 'table' AND name = ?").all(name).length > 0;
8221
- function findSessionV2(db, q, platform) {
8222
- if (q.cliSessionId) {
8223
- const r = db.prepare("SELECT id FROM session_v2 WHERE id = ?").all(q.cliSessionId)[0];
8224
- return asString(r?.id);
8225
- }
8226
- const since = Date.parse(q.startedAt);
8227
- const floor = Number.isFinite(since) ? since - 5e3 : 0;
8228
- const rows = db.prepare("SELECT id, directory FROM session_v2 WHERE parent_id IS NULL AND time_updated >= ? ORDER BY time_updated DESC LIMIT 200").all(floor);
8229
- return asString(rows.find((r) => sameDir(asString(r.directory) ?? "", q.cwd, platform))?.id);
8230
- }
8231
- /** Entries for one 2.x message: user text, or the text and tool parts of an assistant message. Exported for tests. */
8232
- function messageEntriesV2(type, createdMs, data, parts) {
8233
- const at = toIso(createdMs);
8234
- const stamp = at ? { at } : {};
8235
- if (type === "user") {
8236
- const text = asString(data?.text);
8237
- return text ? [{
8238
- role: "user",
8239
- text,
8240
- ...stamp
8241
- }] : [];
8242
- }
8243
- if (type !== "assistant") return [];
8244
- const out = [];
8245
- for (const p of parts) if (p.type === "text") {
8246
- const text = asString(p.text);
8247
- if (text) out.push({
8248
- role: "assistant",
8249
- text,
8250
- ...stamp
8251
- });
8252
- } else if (p.type === "tool") {
8253
- const state = isRecord(p.state) ? p.state : {};
8254
- out.push({
8255
- role: "tool",
8256
- text: describeToolCall(asString(p.name) ?? "tool", state.input),
8257
- ...stamp
8258
- });
8259
- const result = (Array.isArray(state.content) ? state.content : []).map((c) => isRecord(c) && c.type === "text" ? asString(c.text) : void 0).filter((t) => t !== void 0 && t !== "").join("\n") || (isRecord(state.error) ? asString(state.error.message) : void 0);
8260
- if (result) out.push({
8261
- role: "tool",
8262
- text: result,
8263
- ...stamp
8264
- });
8265
- }
8266
- return out;
8267
- }
8268
- function readSessionV2(db, sessionId, n) {
8269
- const fetch = n * 4 + 20;
8270
- const messages = db.prepare("SELECT id, type, time_created, data FROM session_message WHERE session_id = ? ORDER BY time_created DESC, id DESC LIMIT ?").all(sessionId, fetch + 1).reverse();
8271
- const more = messages.length > fetch;
8272
- const used = more ? messages.slice(1) : messages;
8273
- const entries = [];
8274
- for (const m of used) {
8275
- const type = asString(m.type);
8276
- if (!type) continue;
8277
- const parts = type === "assistant" ? db.prepare("SELECT data FROM session_part WHERE message_id = ? ORDER BY ordinal").all(asString(m.id) ?? "").map((p) => json(p.data)).filter((p) => p !== void 0) : [];
8278
- entries.push(...messageEntriesV2(type, m.time_created, json(m.data), parts));
8279
- }
8280
- return {
8281
- entries: entries.slice(-n),
8282
- more: more || entries.length > n
8283
- };
7114
+ } catch {}
8284
7115
  }
8285
- const openCodeTranscript = { async read(q, env) {
8286
- let dbs;
7116
+ /** How long `codex queue` may take (it starts or finds the shared app-server) before we give up. */
7117
+ const QUEUE_TIMEOUT_MS = 2e4;
7118
+ const CUT_NOTE = "\n\n[Cut to fit a command line. Read the full messages with the conveno inbox tool.]";
7119
+ const runProcess = (file, args, opts) => new Promise((resolve) => {
8287
7120
  try {
8288
- dbs = await openCodeDatabases(env);
7121
+ execFile(file, args, {
7122
+ timeout: QUEUE_TIMEOUT_MS,
7123
+ windowsHide: true,
7124
+ ...opts
7125
+ }, (err) => {
7126
+ if (!err) return resolve(0);
7127
+ const e = err;
7128
+ if (e.code === "ENOENT") return resolve("missing");
7129
+ if (e.killed) return resolve("timeout");
7130
+ resolve(typeof e.code === "number" ? e.code : 1);
7131
+ });
8289
7132
  } catch {
8290
- dbs = [];
8291
- }
8292
- if (dbs.length === 0) return notFound("OpenCode", "no OpenCode database in the data directory");
8293
- for (const path of dbs) {
8294
- let db;
8295
- try {
8296
- db = await openReadOnly(path);
8297
- if (hasTable(db, "session_v2") && hasTable(db, "session_message")) {
8298
- const id2 = findSessionV2(db, q, env.platform);
8299
- if (id2 !== void 0) {
8300
- const { entries, more } = readSessionV2(db, id2, q.lastTurns);
8301
- return {
8302
- ok: true,
8303
- entries,
8304
- more
8305
- };
8306
- }
8307
- }
8308
- if (!hasTable(db, "session")) continue;
8309
- const id = findSessionV1(db, q, env.platform);
8310
- if (id === void 0) continue;
8311
- const { entries, more } = readSessionV1(db, id, q.lastTurns);
8312
- return {
8313
- ok: true,
8314
- entries,
8315
- more
8316
- };
8317
- } catch {} finally {
8318
- try {
8319
- db?.close();
8320
- } catch {}
8321
- }
7133
+ resolve(1);
8322
7134
  }
8323
- return notFound("OpenCode", q.cliSessionId ? "no session with that id" : "no session for this working directory since it started");
8324
- } };
8325
- const SERVER_NAME = "conveno";
8326
- const FORMAT = {
8327
- insertSpaces: true,
8328
- tabSize: 2,
8329
- eol: "\n"
8330
- };
8331
- /** First OpenCode release that reads `mcp.servers`. There were no 2.0.x or 2.1.x releases. */
8332
- const V2_MIN = [
8333
- 2,
8334
- 2,
8335
- 0
8336
- ];
8337
- /** `$XDG_CONFIG_HOME/opencode` when XDG_CONFIG_HOME is an absolute path, else `~/.config/opencode`. */
8338
- function configDir(env) {
8339
- const xdg = env.env.XDG_CONFIG_HOME;
8340
- const base = xdg && isAbsolute(xdg) ? xdg : join(env.home, ".config");
8341
- return join(base, "opencode");
8342
- }
8343
- /** `OPENCODE_CONFIG` names one config file; when set it is the only file we touch. */
8344
- const customConfig = (env) => env.env.OPENCODE_CONFIG || void 0;
8345
- /**
8346
- * `OPENCODE_CONFIG` when set. Otherwise an existing opencode.jsonc, then opencode.json, else a
8347
- * new opencode.json in the config directory.
8348
- */
8349
- async function locateConfig(env) {
8350
- const custom = customConfig(env);
8351
- if (custom) try {
8352
- return {
8353
- path: custom,
8354
- text: await readFile(custom, "utf8")
8355
- };
8356
- } catch (err) {
8357
- if (err.code !== "ENOENT") throw err;
8358
- return {
8359
- path: custom,
8360
- text: null
8361
- };
8362
- }
8363
- const dir = configDir(env);
8364
- for (const name of ["opencode.jsonc", "opencode.json"]) {
8365
- const path = join(dir, name);
8366
- try {
8367
- return {
8368
- path,
8369
- text: await readFile(path, "utf8")
8370
- };
8371
- } catch (err) {
8372
- if (err.code !== "ENOENT") throw err;
8373
- }
8374
- }
8375
- return {
8376
- path: join(dir, "opencode.json"),
8377
- text: null
8378
- };
8379
- }
8380
- function parseConfig(file) {
8381
- if (file.text === null || file.text.trim() === "") return {};
8382
- const errors = [];
8383
- const value = parse(file.text, errors, { allowTrailingComma: true });
8384
- const first = errors[0];
8385
- if (first) throw new Error(`Cannot read ${file.path}: ${printParseErrorCode(first.error)} at offset ${first.offset}. Fix the syntax or move the file aside, then run conveno again. The file was not changed.`);
8386
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`Cannot read ${file.path}: the top level must be a JSON object. The file was not changed.`);
8387
- return value;
8388
- }
8389
- function serverEntry(env, shape) {
8390
- const command = [
8391
- ...env.conveno.command,
8392
- "mcp",
8393
- "--cli",
8394
- "opencode"
8395
- ];
8396
- return shape === "v1" ? {
8397
- type: "local",
8398
- command,
8399
- enabled: true
8400
- } : {
8401
- type: "local",
8402
- command
8403
- };
8404
- }
8405
- function parseVersion(text) {
8406
- const m = /(\d+)\.(\d+)\.(\d+)/.exec(text);
8407
- return m ? [
8408
- Number(m[1]),
8409
- Number(m[2]),
8410
- Number(m[3])
8411
- ] : void 0;
8412
- }
8413
- function isV2OrLater(v) {
8414
- for (let i = 0; i < 3; i++) if (v[i] !== V2_MIN[i]) return v[i] > V2_MIN[i];
8415
- return true;
8416
- }
8417
- async function installedVersion(env) {
7135
+ });
7136
+ const readText = (path) => {
8418
7137
  try {
8419
- const res = await env.exec("opencode", ["--version"]);
8420
- return res.code === 0 ? parseVersion(res.stdout) : void 0;
7138
+ return readFileSync(path, "utf8");
8421
7139
  } catch {
8422
7140
  return;
8423
7141
  }
8424
- }
8425
- async function chooseShape(config, version) {
8426
- if (version) return isV2OrLater(version) ? "v2" : "v1";
8427
- return servers(config) !== void 0 ? "v2" : "v1";
8428
- }
8429
- function v1Entry(config) {
8430
- const mcp = config.mcp;
8431
- if (mcp === null || typeof mcp !== "object" || Array.isArray(mcp)) return void 0;
8432
- return mcp[SERVER_NAME];
8433
- }
8434
- function pathFor(shape) {
8435
- return shape === "v1" ? ["mcp", SERVER_NAME] : [
8436
- "mcp",
8437
- "servers",
8438
- SERVER_NAME
8439
- ];
8440
- }
8441
- function sameEntry(found, want) {
8442
- if (found === null || typeof found !== "object") return false;
8443
- const f = found;
8444
- return f.type === want.type && f.disabled !== true && (want.enabled === void 0 || f.enabled === true) && Array.isArray(f.command) && f.command.length === want.command.length && f.command.every((c, i) => c === want.command[i]);
8445
- }
8446
- function servers(config) {
8447
- const mcp = config.mcp;
8448
- if (mcp === null || typeof mcp !== "object" || Array.isArray(mcp)) return void 0;
8449
- const s = mcp.servers;
8450
- if (s === null || typeof s !== "object" || Array.isArray(s)) return void 0;
8451
- return s;
8452
- }
8453
- async function detect(env) {
8454
- const custom = customConfig(env);
8455
- const configPaths = custom ? [custom] : [join(configDir(env), "opencode.jsonc"), join(configDir(env), "opencode.json")];
7142
+ };
7143
+ const isFileSync = (path) => {
8456
7144
  try {
8457
- const res = await env.exec("opencode", ["--version"]);
8458
- if (res.code !== 0) return {
8459
- installed: false,
8460
- configPaths
8461
- };
8462
- const version = parseCliVersion(res.stdout);
8463
- return {
8464
- installed: true,
8465
- binary: "opencode",
8466
- configPaths,
8467
- ...version ? { version } : {}
8468
- };
7145
+ return statSync(path).isFile();
8469
7146
  } catch {
8470
- return {
8471
- installed: false,
8472
- configPaths
8473
- };
7147
+ return false;
8474
7148
  }
8475
- }
8476
- /** `<config dir>/plugins/conveno.js`, the global plugin folder OpenCode 1.x and 2.x load. */
8477
- const pluginPath = (env) => join(configDir(env), "plugins", "conveno.js");
8478
- async function readText(path) {
8479
- try {
8480
- return await readFile(path, "utf8");
8481
- } catch (err) {
8482
- if (err.code === "ENOENT") return null;
8483
- throw err;
8484
- }
8485
- }
8486
- /**
8487
- * The plugin API differs between the lines (https://opencode.ai/docs/build/plugins/migrate-v1/), so
8488
- * each gets its own source at the same path. An unknown version gets nothing rather than a file
8489
- * that might not load.
8490
- */
8491
- const pluginFor = (env, version) => {
8492
- if (version === void 0) return void 0;
8493
- return isV2OrLater(version) ? pluginSourceV2(env.conveno.command) : pluginSource(env.conveno.command);
8494
7149
  };
8495
- async function planPlugin(env, version) {
8496
- const want = pluginFor(env, version);
8497
- if (want === void 0) return [];
8498
- const path = pluginPath(env);
8499
- const before = await readText(path);
8500
- if (before === want) return [];
8501
- if (before !== null && !before.startsWith("// conveno-plugin:")) throw new Error(`${path} exists and was not written by Conveno. Move or rename it, then run conveno again. The file was not changed.`);
8502
- return [{
8503
- component: "hooks",
8504
- kind: before === null ? "add" : "update",
8505
- path,
8506
- before,
8507
- after: want,
8508
- description: `${before === null ? "Add" : "Update"} the Conveno plugin for OpenCode ${version && isV2OrLater(version) ? "2.x" : "1.x"}. In auto mode it hands waiting messages to a session when its turn ends or while it is idle.`
8509
- }];
8510
- }
8511
- async function uninstallPlugin(env) {
8512
- const path = pluginPath(env);
8513
- const before = await readText(path);
8514
- if (before === null || !before.startsWith("// conveno-plugin:")) return [];
8515
- return [{
8516
- component: "hooks",
8517
- kind: "remove",
8518
- path,
8519
- before,
8520
- after: "",
8521
- deleteFile: true,
8522
- description: "Remove the Conveno plugin for OpenCode."
8523
- }];
8524
- }
8525
- async function plan(env) {
8526
- const version = await installedVersion(env);
8527
- return [...await planMcp(env, version), ...await planPlugin(env, version)];
8528
- }
8529
- async function uninstallPlan(env) {
8530
- return [...await uninstallMcp(env), ...await uninstallPlugin(env)];
8531
- }
8532
- async function planMcp(env, version) {
8533
- const file = await locateConfig(env);
8534
- const config = parseConfig(file);
8535
- const shape = await chooseShape(config, version);
8536
- const want = serverEntry(env, shape);
8537
- const current = shape === "v1" ? v1Entry(config) : servers(config)?.[SERVER_NAME];
8538
- if (sameEntry(current, want)) return [];
8539
- let text = file.text === null || file.text.trim() === "" ? "{}\n" : file.text;
8540
- const otherShape = shape === "v1" ? "v2" : "v1";
8541
- const other = otherShape === "v1" ? v1Entry(config) : servers(config)?.[SERVER_NAME];
8542
- if (other !== void 0) text = applyEdits(text, modify(text, pathFor(otherShape), void 0, { formattingOptions: FORMAT }));
8543
- let after = applyEdits(text, modify(text, pathFor(shape), want, { formattingOptions: FORMAT }));
8544
- if (!after.endsWith("\n")) after += "\n";
8545
- const where = shape === "v1" ? `mcp.${SERVER_NAME}` : `mcp.servers.${SERVER_NAME}`;
8546
- return [{
8547
- component: "mcp",
8548
- kind: current !== void 0 || other !== void 0 ? "update" : "add",
8549
- path: file.path,
8550
- before: file.text,
8551
- after,
8552
- description: `Add the conveno MCP server (${where}) to the OpenCode global config`
8553
- }];
7150
+ /** `text`, cut to `MAX_QUEUE_TEXT` with a note when longer. */
7151
+ function fitQueueText(text) {
7152
+ if (text.length <= 24e3) return text;
7153
+ let head = text.slice(0, 23918);
7154
+ if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
7155
+ return head + CUT_NOTE;
8554
7156
  }
8555
- async function uninstallMcp(env) {
8556
- const file = await locateConfig(env);
8557
- if (file.text === null) return [];
8558
- const config = parseConfig(file);
8559
- let text = file.text;
8560
- const removed = [];
8561
- if (servers(config)?.[SERVER_NAME] !== void 0) {
8562
- text = applyEdits(text, modify(text, pathFor("v2"), void 0, { formattingOptions: FORMAT }));
8563
- removed.push(`mcp.servers.${SERVER_NAME}`);
8564
- }
8565
- if (v1Entry(config) !== void 0) {
8566
- text = applyEdits(text, modify(text, pathFor("v1"), void 0, { formattingOptions: FORMAT }));
8567
- removed.push(`mcp.${SERVER_NAME}`);
8568
- }
8569
- if (removed.length === 0) return [];
8570
- return [{
8571
- component: "mcp",
8572
- kind: "remove",
8573
- path: file.path,
8574
- before: file.text,
8575
- after: text,
8576
- description: `Remove the conveno MCP server (${removed.join(", ")}) from the OpenCode global config`
8577
- }];
8578
- }
8579
- const EMPTY = {
8580
- stdout: "",
8581
- exitCode: 0
8582
- };
8583
7157
  /**
8584
- * Run by the plugin, never by OpenCode itself. Each prints the prompt to send as plain text, which
8585
- * the plugin sends to the session (1.x `client.session.promptAsync`, 2.x `ctx.session.prompt`).
8586
- * - Idle: the session's turn ended. In auto mode with messages waiting, the prompt to continue with.
8587
- * - Stopped: the turn failed or the user interrupted it. Records the end and never continues.
8588
- * - Listen: the background listener. Waits for work while the session is idle.
7158
+ * Wake an idle Codex session: `codex queue --thread <thread id> --message <text>`. Codex starts a
7159
+ * queued message as a turn when the thread is idle and keeps it until the turn ends when it is
7160
+ * busy, so the message lands like one the user typed. No `--resume`: a thread nobody has open
7161
+ * stays queued and runs when it is resumed.
7162
+ *
7163
+ * `codex queue` takes the text only as an argument (no stdin, no file), so on Windows the text
7164
+ * must never reach a cmd.exe command line, where `"`, `&`, `%VAR%` and line breaks are parsed
7165
+ * again by the shim. A `codex.exe` runs directly; an npm `codex.cmd` shim is bypassed by running
7166
+ * the script it names with node. Any other `.cmd` gives `unsupported`.
7167
+ *
7168
+ * `queued`: codex took it. `unknown`: it timed out, so it may have been queued. `unsupported`:
7169
+ * no codex, or one too old for `queue` (a usage error). `failed`: anything else.
8589
7170
  */
8590
- async function hook(event, input, ctx) {
8591
- const dir = typeof input === "object" && input !== null ? input.directory : void 0;
8592
- if (typeof dir === "string" && dir !== "") ctx = {
8593
- ...ctx,
8594
- cwd: dir
8595
- };
8596
- let text = null;
8597
- if (event === "Idle") text = await endTurnContinuation(ctx);
8598
- else if (event === "Stopped") await endTurnContinuation(ctx, { allowContinue: false });
8599
- else if (event === "Listen") text = await waitForWork(ctx);
8600
- return text === null ? EMPTY : {
8601
- stdout: text,
8602
- exitCode: 0
8603
- };
8604
- }
8605
- /** Only the plugin delivers, on 1.x and 2.x alike; it adds nothing to a prompt the user types. */
8606
- function delivery(detection) {
8607
- const supported = detection.version !== void 0 && parseVersion(detection.version) !== void 0;
8608
- return {
8609
- nextTurn: false,
8610
- endOfTurn: supported,
8611
- idleWake: supported
8612
- };
7171
+ async function wakeCodexThread(args) {
7172
+ if (!args.nativeId) return "unsupported";
7173
+ if (args.text.trim() === "") return "failed";
7174
+ const platform = args.platform ?? process.platform;
7175
+ const env = args.env ?? process.env;
7176
+ const program = findOnPath("codex", env, platform, args.isFile);
7177
+ if (!program) return "unsupported";
7178
+ const argv = [
7179
+ "queue",
7180
+ "--thread",
7181
+ args.nativeId,
7182
+ "--message",
7183
+ fitQueueText(args.text)
7184
+ ];
7185
+ let plan;
7186
+ try {
7187
+ plan = planProgram(program, argv, {
7188
+ platform,
7189
+ env,
7190
+ io: {
7191
+ isFile: args.isFile ?? isFileSync,
7192
+ readFile: args.readFile ?? readText
7193
+ }
7194
+ });
7195
+ } catch {
7196
+ return "unsupported";
7197
+ }
7198
+ if (plan.windowsVerbatimArguments) return "unsupported";
7199
+ const result = await (args.run ?? runProcess)(plan.file, plan.args, { env: { ...env } });
7200
+ if (result === 0) return "queued";
7201
+ if (result === "timeout") return "unknown";
7202
+ if (result === "missing" || result === 2) return "unsupported";
7203
+ return "failed";
7204
+ }
7205
+ /** The daemon calls this when a message arrives for an idle Codex session (see WAKE-NOTES). */
7206
+ async function daemonWake(a) {
7207
+ return wakeCodexThread({
7208
+ nativeId: a.nativeId,
7209
+ text: a.text
7210
+ });
8613
7211
  }
8614
- const opencodeAdapter = {
8615
- cli: "opencode",
8616
- displayName: "OpenCode",
8617
- deliveryTier: "inbox",
7212
+ /** Idle wake goes through `codex queue`; on a Codex without it the message waits for the next hook. */
7213
+ const delivery = () => ({
7214
+ nextTurn: true,
7215
+ endOfTurn: true,
7216
+ idleWake: true
7217
+ });
7218
+ const codexAdapter = {
7219
+ cli: "codex",
7220
+ displayName: "Codex",
7221
+ deliveryTier: "next_turn",
8618
7222
  detect,
8619
- plan,
8620
- uninstallPlan,
7223
+ async plan(env) {
7224
+ return [...await planMcp(env), ...await planHooks(env)];
7225
+ },
7226
+ async uninstallPlan(env) {
7227
+ return [...await uninstallMcp(env), ...await uninstallHooks(env)];
7228
+ },
8621
7229
  hook,
8622
- listenEvents: ["Listen"],
8623
7230
  delivery,
8624
- transcript: openCodeTranscript
7231
+ daemonWake
8625
7232
  };
8626
- export { Za as a, claudeTranscript as c, codexTranscript as i, opencodeAdapter as n, cs as o, codexAdapter as r, claudeAdapter as s, openCodeTranscript as t };
7233
+ export { Za as n, cs as r, codexAdapter as t };