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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1320 @@
1
+ import { homedir } from "node:os";
2
+ import { n as antigravityAdapter } from "./dist-KWlFKO7H.js";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { Et as readAncestry, Ft as requeueMessages, Gt as startTurnContext, H as endTurnContinuation, P as dataDir, _t as pendingHookContext, dt as ownSession, nn as waitForWorkBatch, pt as parseCliVersion, tn as waitForWork } from "./dist-qONHJRJk.js";
5
+ import { readFile } from "node:fs/promises";
6
+ import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
7
+ import { t as codexAdapter } from "./dist-DEjU_KXC.js";
8
+ import { t as grokAdapter } from "./dist-Y0JDSJP_.js";
9
+ import { n as connect } from "./dist-n6XMTlyN.js";
10
+ import { t as runHook } from "./hook-CDF1A8AY.js";
11
+ // ../adapters/claude/dist/index.js
12
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
13
+ /** Read a JSON object file. Missing or blank files give `{}`; anything else that is not a JSON object throws. */
14
+ async function loadJson(path) {
15
+ let raw;
16
+ try {
17
+ raw = await readFile(path, "utf8");
18
+ } catch (err) {
19
+ if (err.code === "ENOENT") raw = null;
20
+ else throw new Error(`Cannot read ${path}: ${err.message}. Check its permissions.`);
21
+ }
22
+ if (raw === null || raw.trim() === "") return {
23
+ raw,
24
+ value: {},
25
+ indent: 2,
26
+ trailingNewline: true
27
+ };
28
+ let value;
29
+ try {
30
+ value = JSON.parse(raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw);
31
+ } catch (err) {
32
+ throw new Error(`${path} is not valid JSON (${err.message}). Fix or remove the file, then run the install again. Nothing was changed.`);
33
+ }
34
+ 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.`);
35
+ return {
36
+ raw,
37
+ value,
38
+ indent: detectIndent(raw),
39
+ trailingNewline: raw.endsWith("\n")
40
+ };
41
+ }
42
+ function detectIndent(raw) {
43
+ const m = /^([ \t]+)\S/m.exec(raw);
44
+ if (!m?.[1]) return 2;
45
+ return m[1].startsWith(" ") ? " " : m[1].length;
46
+ }
47
+ /**
48
+ * Apply edits to the file's own text. Only the touched keys change: other keys, duplicate keys,
49
+ * escapes, key order and line endings stay as they were, byte for byte.
50
+ */
51
+ function editJson(file, edits) {
52
+ const bom = file.raw?.charCodeAt(0) === 65279;
53
+ let text = file.raw === null || file.raw.trim() === "" ? "{}\n" : file.raw;
54
+ if (bom) text = text.slice(1);
55
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
56
+ const formattingOptions = {
57
+ insertSpaces: file.indent !== " ",
58
+ tabSize: typeof file.indent === "number" ? file.indent : 2,
59
+ eol
60
+ };
61
+ for (const e of edits) text = applyEdits(text, modify(text, e.path, e.value, { formattingOptions }));
62
+ return (bom ? "" : "") + text;
63
+ }
64
+ const SERVER_NAME$1 = "conveno";
65
+ /** Claude Code events Conveno installs hooks for. */
66
+ const HOOK_EVENTS = [
67
+ "SessionStart",
68
+ "UserPromptSubmit",
69
+ "PostToolUse",
70
+ "Stop"
71
+ ];
72
+ /** Older versions also installed a PermissionRequest hook; uninstall still removes it. */
73
+ const LEGACY_HOOK_EVENTS = ["PermissionRequest"];
74
+ /** The background listener's `conveno hook claude <arg>`. It is armed on SessionStart and Stop. */
75
+ const LISTEN_EVENT = "Listen";
76
+ /**
77
+ * Seconds. Claude Code kills a hook at its `timeout` (SIGTERM, exit 143, which wakes nothing) and
78
+ * does not cap the value for a local command hook (checked in Claude Code 2.1.332: the schema is
79
+ * `timeout: positive().optional()` and the runner arms `setTimeout(timeout * 1000)`). An idle
80
+ * session must stay wakeable for as long as it is open, so one armed listener waits 20 days. That
81
+ * stays under the largest timer delay (2^31 - 1 ms, about 24.8 days); a longer one fires at once.
82
+ * Every SessionStart and Stop arms a fresh listener, which replaces the old.
83
+ */
84
+ const LISTEN_TIMEOUT_SECONDS = 1728e3;
85
+ /** The listener gives up on its own a few minutes before Claude Code's timeout, so it exits 0 instead of being killed. */
86
+ const LISTEN_MAX_MS = 17277e5;
87
+ /**
88
+ * A listener armed on SessionStart can start before Claude Code's MCP server registered the
89
+ * session. It looks for its session this long before it gives up.
90
+ */
91
+ const LISTEN_REGISTER_WAIT_MS = 12e4;
92
+ /**
93
+ * First wait before a listener that lost the daemon (it restarted or was stopped) tries again;
94
+ * doubles up to a minute. The listener keeps the session wakeable instead of exiting.
95
+ */
96
+ const LISTEN_RECONNECT_MS = 5e3;
97
+ /**
98
+ * `CLAUDE_CODE_ENTRYPOINT` values of a non-interactive run: `claude -p` sets `sdk-cli`, the Agent
99
+ * SDKs `sdk-ts` and `sdk-py`. Claude Code's own check for an SDK entrypoint is this set (2.1.332
100
+ * bundle: `e==="sdk-ts"||e==="sdk-py"||e==="sdk-cli"`; `claude -p` turns `cli` into `sdk-cli`).
101
+ */
102
+ const NON_INTERACTIVE_ENTRYPOINTS = /* @__PURE__ */ new Set([
103
+ "sdk-cli",
104
+ "sdk-ts",
105
+ "sdk-py"
106
+ ]);
107
+ /**
108
+ * Claude Code shows the stderr of a waking hook after its own "Stop hook blocking error from
109
+ * command" prefix. This first line tells the model what the text is.
110
+ */
111
+ const WAKE_LEAD = "Conveno messages for this session follow. This is not an error and no hook failed: Claude Code labels every wake from a background hook this way.";
112
+ /**
113
+ * Characters a hook prints at most. Claude Code caps a hook's `additionalContext` and plain stdout
114
+ * at 10,000 characters; past that it saves the text to a file and shows Claude a 2,000-character
115
+ * preview without asking it to read the rest (docs, hooks: "capped at 10,000 characters"). Kept
116
+ * under the cap with room to spare; messages past it stay queued for the next delivery.
117
+ */
118
+ const OUTPUT_MAX_CHARS = 9e3;
119
+ /** The listener's framed batch, after `WAKE_LEAD` and a blank line, within `OUTPUT_MAX_CHARS`. */
120
+ const WAKE_MAX_CHARS = 8853;
121
+ /**
122
+ * Milliseconds from the start of a hook by which it must have its messages: `conveno hook` gives up
123
+ * after 2 s, counted from before it connected and found the host, and a hook that has given up
124
+ * prints nothing. Messages the daemon hands over later are put back to queued.
125
+ */
126
+ const DELIVER_DEADLINE_MS = 1200;
127
+ /** The handlers Conveno wants on each event, in order: the hook itself, then a listener where one is armed. */
128
+ const HANDLERS = {
129
+ SessionStart: ["SessionStart", LISTEN_EVENT],
130
+ UserPromptSubmit: ["UserPromptSubmit"],
131
+ PostToolUse: ["PostToolUse"],
132
+ Stop: ["Stop", LISTEN_EVENT]
133
+ };
134
+ const EMPTY$1 = {
135
+ stdout: "",
136
+ exitCode: 0
137
+ };
138
+ /** `~/.claude.json` holds user-scope MCP servers; settings.json holds hooks. Both honor CLAUDE_CONFIG_DIR. */
139
+ function paths(env) {
140
+ const dir = env.env.CLAUDE_CONFIG_DIR;
141
+ if (dir) return {
142
+ mcp: join(dir, ".claude.json"),
143
+ settings: join(dir, "settings.json")
144
+ };
145
+ return {
146
+ mcp: join(env.home, ".claude.json"),
147
+ settings: join(env.home, ".claude", "settings.json")
148
+ };
149
+ }
150
+ /**
151
+ * The program and arguments of one hook, in exec form: Claude Code spawns `command` with `args` and
152
+ * no shell, so nothing is quoted and Git Bash, PowerShell and `sh` read it alike
153
+ * (https://code.claude.com/docs/en/hooks, "Exec form and shell form"; `args` since Claude Code
154
+ * 2.1.139, older than the 2.1.332 minimum). On Windows `command` must be a real executable, not an
155
+ * npm `.cmd` shim, so a bare `conveno` there becomes `node <conveno's script>`, the pattern the
156
+ * docs give for npm tools.
157
+ */
158
+ function hookProgram(env, event) {
159
+ let [command = "conveno", ...rest] = env.conveno.command;
160
+ if (env.platform === "win32" && rest.length === 0 && env.conveno.bin) {
161
+ command = "node";
162
+ rest = [env.conveno.bin];
163
+ }
164
+ return {
165
+ command,
166
+ args: [
167
+ ...rest,
168
+ "hook",
169
+ "claude",
170
+ event
171
+ ]
172
+ };
173
+ }
174
+ /** One hook handler as written to settings.json. The listener runs in the background (`asyncRewake`). */
175
+ function handlerFor(env, arg) {
176
+ const { command, args } = hookProgram(env, arg);
177
+ return arg === "Listen" ? {
178
+ type: "command",
179
+ command,
180
+ args,
181
+ asyncRewake: true,
182
+ timeout: LISTEN_TIMEOUT_SECONDS
183
+ } : {
184
+ type: "command",
185
+ command,
186
+ args,
187
+ timeout: 5
188
+ };
189
+ }
190
+ const mcpArgs = (env) => [
191
+ ...env.conveno.command,
192
+ "mcp",
193
+ "--cli",
194
+ "claude"
195
+ ];
196
+ const desiredServer = (env) => {
197
+ const [command = "conveno", ...args] = mcpArgs(env);
198
+ return {
199
+ type: "stdio",
200
+ command,
201
+ args,
202
+ env: {}
203
+ };
204
+ };
205
+ const OUR_EVENTS = /^(SessionStart|UserPromptSubmit|PostToolUse|Stop|Listen|PermissionRequest)$/;
206
+ /**
207
+ * Recognizes our hook handler even if the conveno path changed since install: exec form (`args`
208
+ * ending in `hook claude <event>`) or the shell form older versions wrote.
209
+ */
210
+ function isOurHook(h) {
211
+ if (!isObject(h)) return false;
212
+ if (Array.isArray(h.args)) {
213
+ const [a, b, c] = h.args.slice(-3);
214
+ return a === "hook" && b === "claude" && typeof c === "string" && OUR_EVENTS.test(c);
215
+ }
216
+ const m = typeof h.command === "string" && /(?:^|\s)hook claude (\S+)$/.exec(h.command.trim());
217
+ return m ? OUR_EVENTS.test(m[1] ?? "") : false;
218
+ }
219
+ const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
220
+ function groupsOf(hooks, event) {
221
+ const g = hooks[event];
222
+ return Array.isArray(g) ? g : [];
223
+ }
224
+ function hasExactHook(hooks, event, handler) {
225
+ return groupsOf(hooks, event).some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => sameJson(h, handler)));
226
+ }
227
+ /** Every handler Conveno wants on `event` is there, exactly. */
228
+ const eventComplete = (env, hooks, event) => HANDLERS[event].every((arg) => hasExactHook(hooks, event, handlerFor(env, arg)));
229
+ /** The name `conveno doctor --verbose` shows for one event. Start and Stop also arm the listener. */
230
+ const hookPartName = (e) => HANDLERS[e].includes("Listen") ? `${e} hook and listener` : `${e} hook`;
231
+ const hasOurHandler = (g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isOurHook);
232
+ /** Drop our hook handlers (and groups left empty by that). */
233
+ function stripOurHooks(groups) {
234
+ const out = [];
235
+ for (const g of groups) {
236
+ if (!isObject(g) || !Array.isArray(g.hooks)) {
237
+ out.push(g);
238
+ continue;
239
+ }
240
+ const kept = g.hooks.filter((h) => !isOurHook(h));
241
+ if (kept.length === g.hooks.length) out.push(g);
242
+ else if (kept.length > 0) out.push({
243
+ ...g,
244
+ hooks: kept
245
+ });
246
+ }
247
+ return out;
248
+ }
249
+ function hooksObject(settings, path) {
250
+ const h = settings.hooks;
251
+ if (h === void 0) return {};
252
+ if (!isObject(h)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
253
+ return h;
254
+ }
255
+ function mcpObject(config, path) {
256
+ const s = config.mcpServers;
257
+ if (s === void 0) return {};
258
+ if (!isObject(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
259
+ return s;
260
+ }
261
+ async function detect$1(env) {
262
+ const p = paths(env);
263
+ const configPaths = [p.mcp, p.settings];
264
+ try {
265
+ const r = await env.exec("claude", ["--version"]);
266
+ if (r.code !== 0) return {
267
+ installed: false,
268
+ configPaths
269
+ };
270
+ const version = parseCliVersion(r.stdout);
271
+ return {
272
+ installed: true,
273
+ binary: "claude",
274
+ ...version ? { version } : {},
275
+ configPaths
276
+ };
277
+ } catch {
278
+ return {
279
+ installed: false,
280
+ configPaths
281
+ };
282
+ }
283
+ }
284
+ /** `A`, `A and B`, `A, B and C`. */
285
+ const listed = (words) => words.length < 2 ? words[0] ?? "" : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;
286
+ async function plan$1(env) {
287
+ const p = paths(env);
288
+ const changes = [];
289
+ const mcpFile = await loadJson(p.mcp);
290
+ const servers = mcpObject(mcpFile.value, p.mcp);
291
+ const want = desiredServer(env);
292
+ if (!sameJson(servers["conveno"], want)) {
293
+ const after = editJson(mcpFile, [{
294
+ path: ["mcpServers", SERVER_NAME$1],
295
+ value: want
296
+ }]);
297
+ changes.push({
298
+ component: "mcp",
299
+ kind: servers["conveno"] === void 0 ? "add" : "update",
300
+ path: p.mcp,
301
+ before: mcpFile.raw,
302
+ after,
303
+ parts: [{
304
+ name: "MCP server",
305
+ kind: servers["conveno"] === void 0 ? "add" : "update"
306
+ }],
307
+ description: `Register the "${SERVER_NAME$1}" MCP server at user scope (conveno mcp --cli claude).`,
308
+ viaCommand: [
309
+ "claude",
310
+ "mcp",
311
+ "add",
312
+ "--scope",
313
+ "user",
314
+ SERVER_NAME$1,
315
+ "--",
316
+ ...mcpArgs(env)
317
+ ]
318
+ });
319
+ }
320
+ const setFile = await loadJson(p.settings);
321
+ const hooks = hooksObject(setFile.value, p.settings);
322
+ const missing = HOOK_EVENTS.filter((e) => !eventComplete(env, hooks, e));
323
+ if (missing.length > 0) {
324
+ const next = { ...hooks };
325
+ for (const e of missing) next[e] = [...stripOurHooks(groupsOf(hooks, e)), ...HANDLERS[e].map((arg) => ({ hooks: [handlerFor(env, arg)] }))];
326
+ const installed = [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS].some((e) => groupsOf(hooks, e).some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some(isOurHook)));
327
+ changes.push({
328
+ component: "hooks",
329
+ kind: installed ? "update" : "add",
330
+ parts: missing.map((e) => ({
331
+ name: hookPartName(e),
332
+ kind: groupsOf(hooks, e).some(hasOurHandler) ? "update" : "add"
333
+ })),
334
+ path: p.settings,
335
+ before: setFile.raw,
336
+ after: editJson(setFile, missing.map((e) => ({
337
+ path: ["hooks", e],
338
+ value: next[e]
339
+ }))),
340
+ description: `Add Conveno's ${listed(missing)} hooks to Claude Code. They deliver messages at the next prompt, after a tool call, at the end of a turn, or by waking an idle session through a background listener.`
341
+ });
342
+ }
343
+ return changes;
344
+ }
345
+ async function uninstallPlan$1(env) {
346
+ const p = paths(env);
347
+ const changes = [];
348
+ const mcpFile = await loadJson(p.mcp);
349
+ if ("conveno" in mcpObject(mcpFile.value, p.mcp)) changes.push({
350
+ component: "mcp",
351
+ kind: "remove",
352
+ path: p.mcp,
353
+ before: mcpFile.raw,
354
+ after: editJson(mcpFile, [{
355
+ path: ["mcpServers", SERVER_NAME$1],
356
+ value: void 0
357
+ }]),
358
+ description: `Remove the "${SERVER_NAME$1}" MCP server from user scope.`,
359
+ viaCommand: [
360
+ "claude",
361
+ "mcp",
362
+ "remove",
363
+ "--scope",
364
+ "user",
365
+ SERVER_NAME$1
366
+ ]
367
+ });
368
+ const setFile = await loadJson(p.settings);
369
+ const hooks = hooksObject(setFile.value, p.settings);
370
+ const next = { ...hooks };
371
+ const edits = [];
372
+ for (const e of [...HOOK_EVENTS, ...LEGACY_HOOK_EVENTS]) {
373
+ const groups = groupsOf(hooks, e);
374
+ const stripped = stripOurHooks(groups);
375
+ if (sameJson(groups, stripped)) continue;
376
+ if (stripped.length > 0) next[e] = stripped;
377
+ else delete next[e];
378
+ edits.push({
379
+ path: ["hooks", e],
380
+ value: stripped.length > 0 ? stripped : void 0
381
+ });
382
+ }
383
+ if (edits.length > 0) {
384
+ if (Object.keys(next).length === 0) edits.push({
385
+ path: ["hooks"],
386
+ value: void 0
387
+ });
388
+ changes.push({
389
+ component: "hooks",
390
+ kind: "remove",
391
+ path: p.settings,
392
+ before: setFile.raw,
393
+ after: editJson(setFile, edits),
394
+ description: "Remove the Conveno SessionStart, UserPromptSubmit, PostToolUse and Stop hooks and the listener."
395
+ });
396
+ }
397
+ return changes;
398
+ }
399
+ /** `stop_hook_active` from the Stop input: Claude Code is already continuing because of a Stop hook. */
400
+ const stopHookActive = (input) => isObject(input) && input.stop_hook_active === true;
401
+ /** `agent_id` is in a hook's input only when it fires inside a subagent (docs, "Common input fields"). */
402
+ const inSubagent = (input) => isObject(input) && typeof input.agent_id === "string" && input.agent_id !== "";
403
+ const contextOutput = (event, additionalContext) => additionalContext === null ? EMPTY$1 : {
404
+ stdout: JSON.stringify({ hookSpecificOutput: {
405
+ hookEventName: event,
406
+ additionalContext
407
+ } }),
408
+ exitCode: 0
409
+ };
410
+ /**
411
+ * Claude Code's id for this session: `CLAUDE_CODE_SESSION_ID`, which hook processes get and which
412
+ * matches the input's `session_id` (docs, env-vars); the input field when the variable is missing.
413
+ */
414
+ function claudeSessionId(input) {
415
+ const env = process.env.CLAUDE_CODE_SESSION_ID;
416
+ if (env) return env;
417
+ return isObject(input) && typeof input.session_id === "string" && input.session_id !== "" ? input.session_id : void 0;
418
+ }
419
+ /**
420
+ * Finds the session by Claude Code's own session id where the daemon knows it, with the host pid as
421
+ * the fallback. The MCP server records the id it was started with, but that id is not the hooks'
422
+ * after `/clear`, and after `--continue` or `--resume` without an id it can be the startup one
423
+ * (docs, `CLAUDE_CODE_SESSION_ID`). So on a miss the hook looks the session up by pid and, when that
424
+ * finds this host's Claude session, records the hooks' id on it, so later hooks match it directly.
425
+ * Never throws: on any failure the pid lookup of the helpers applies.
426
+ */
427
+ async function withSessionId(ctx, input) {
428
+ const nativeId = claudeSessionId(input);
429
+ if (nativeId === void 0 || ctx.nativeId !== void 0) return ctx;
430
+ try {
431
+ const { client, hostPid: pid } = ctx;
432
+ if ((await client["session.byHost"]({
433
+ pid,
434
+ nativeId
435
+ })).session) return {
436
+ ...ctx,
437
+ nativeId
438
+ };
439
+ const byPid = await client["session.byHost"]({ pid });
440
+ if (byPid.session?.cli !== "claude") return ctx;
441
+ await client["session.setNative"]({
442
+ sessionId: byPid.session.id,
443
+ nativeId
444
+ });
445
+ return {
446
+ ...ctx,
447
+ nativeId
448
+ };
449
+ } catch {
450
+ return ctx;
451
+ }
452
+ }
453
+ /**
454
+ * Never throws: any failure means "deliver nothing this time". What a hook prints stays within
455
+ * `OUTPUT_MAX_CHARS`, and messages handed over after `DELIVER_DEADLINE_MS` go back to queued.
456
+ *
457
+ * - SessionStart: waiting messages as `additionalContext`.
458
+ * - UserPromptSubmit: the turn starts (the session is busy), waiting messages as `additionalContext`.
459
+ * - PostToolUse: mid-turn, waiting messages as `additionalContext`, which Claude Code puts next to
460
+ * the tool result. Not inside a subagent, whose context the main conversation does not see.
461
+ * - Stop: with messages waiting, `hookSpecificOutput.additionalContext` with the framed messages,
462
+ * so Claude continues with them, shown as hook feedback rather than a hook error. When
463
+ * `stop_hook_active` is set (Claude is already continuing because of a Stop hook) it never
464
+ * continues; it only records that the turn ended, and the listener armed on this Stop wakes the
465
+ * session with what waits, as a new turn.
466
+ * - Listen: the background listener (`asyncRewake`). Waits for its session to register, then for
467
+ * work, and exits 2 with the framed messages on stderr (after `WAKE_LEAD`), which wakes Claude
468
+ * even when the session is idle. A lost daemon connection is retried, so a daemon restart does
469
+ * not leave the session unwakeable. Exit 0, silent, when it stops for any other reason, and at
470
+ * once in a non-interactive run (`NON_INTERACTIVE_ENTRYPOINTS`). A batch taken just as Claude
471
+ * Code exited is requeued.
472
+ */
473
+ async function hook$1(event, input, ctx) {
474
+ const opts = {
475
+ maxChars: OUTPUT_MAX_CHARS,
476
+ deadline: Date.now() + DELIVER_DEADLINE_MS
477
+ };
478
+ switch (event) {
479
+ case "SessionStart": return contextOutput(event, await pendingHookContext(await withSessionId(ctx, input), opts));
480
+ case "UserPromptSubmit": return contextOutput(event, await startTurnContext(await withSessionId(ctx, input), opts));
481
+ case "PostToolUse":
482
+ if (inSubagent(input)) return EMPTY$1;
483
+ return contextOutput(event, await pendingHookContext(await withSessionId(ctx, input), opts));
484
+ case "Stop": {
485
+ const reason = await endTurnContinuation(await withSessionId(ctx, input), {
486
+ ...opts,
487
+ allowContinue: !stopHookActive(input)
488
+ });
489
+ return contextOutput(event, reason);
490
+ }
491
+ case LISTEN_EVENT: {
492
+ const entry = process.env.CLAUDE_CODE_ENTRYPOINT;
493
+ if (entry !== void 0 && NON_INTERACTIVE_ENTRYPOINTS.has(entry)) return EMPTY$1;
494
+ const own = await withSessionId(ctx, input);
495
+ const r = await waitForWorkBatch(own, {
496
+ maxMs: LISTEN_MAX_MS,
497
+ registerWaitMs: LISTEN_REGISTER_WAIT_MS,
498
+ reconnectMs: LISTEN_RECONNECT_MS,
499
+ maxChars: WAKE_MAX_CHARS
500
+ });
501
+ if (r === null) return EMPTY$1;
502
+ if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) {
503
+ await requeueMessages(ctx.client, r.sessionId, r.batch.messages);
504
+ return EMPTY$1;
505
+ }
506
+ return {
507
+ stdout: "",
508
+ stderr: `${WAKE_LEAD}\n\n${r.batch.text}`,
509
+ exitCode: 2
510
+ };
511
+ }
512
+ default: return EMPTY$1;
513
+ }
514
+ }
515
+ const delivery$1 = () => ({
516
+ nextTurn: true,
517
+ endOfTurn: true,
518
+ idleWake: true
519
+ });
520
+ const claudeAdapter = {
521
+ cli: "claude",
522
+ displayName: "Claude Code",
523
+ deliveryTier: "next_turn",
524
+ detect: detect$1,
525
+ plan: plan$1,
526
+ uninstallPlan: uninstallPlan$1,
527
+ hook: hook$1,
528
+ listenEvents: [LISTEN_EVENT],
529
+ delivery: delivery$1
530
+ };
531
+ // ../adapters/opencode/dist/index.js
532
+ /**
533
+ * The OpenCode 1.x plugin Conveno installs as `<config dir>/plugins/conveno.js`. OpenCode 1.x loads
534
+ * every `.js` file in the global `plugins/` folder at startup (https://opencode.ai/docs/plugins/,
535
+ * "From local files") and calls each exported function with a context that holds an SDK `client`.
536
+ *
537
+ * The plugin does no Conveno work itself; it runs `conveno hook opencode <event>`, which finds the
538
+ * session by its host process (this OpenCode process) like every other hook:
539
+ *
540
+ * - On `session.idle` of a top-level session it runs `Idle`. With messages waiting,
541
+ * that prints the continuation prompt, and the plugin sends it with `client.session.promptAsync`.
542
+ * - Otherwise it starts `Listen`, which waits in the background and prints a prompt when work
543
+ * arrives while the session is idle; the plugin sends that the same way.
544
+ * - `promptAsync` always answers 204, so a prompt that cannot run shows up later as a `session.error`
545
+ * event. The plugin remembers the ids it just sent and hands them back with `Requeue` if that
546
+ * event arrives before the session turns busy. (The event shape is `{ sessionID?, error }`,
547
+ * `packages/schema/src/v1/session.ts` at v2.4.3; that it comes before `busy` is UNVERIFIED.)
548
+ * - When the session turns busy, the plugin is disposed, or a newer listener starts, the listener
549
+ * is stopped. It also stops by itself when OpenCode exits.
550
+ */
551
+ /** Start of the first line of every Conveno plugin file, whatever the OpenCode line it is for. */
552
+ const PLUGIN_MARKER_PREFIX = "// conveno-plugin:";
553
+ /** First line of the 1.x plugin. Uninstall and re-install recognise a plugin by the marker prefix. */
554
+ const PLUGIN_MARKER = `${PLUGIN_MARKER_PREFIX} 1`;
555
+ /**
556
+ * The part both plugins share: the import, the baked-in command, and `run`, which starts
557
+ * `conveno hook opencode <event>` and resolves with what it prints. Plain JavaScript source text.
558
+ */
559
+ function runHelper(command) {
560
+ return `import { spawn } from "node:child_process";
561
+
562
+ const COMMAND = ${JSON.stringify(command)};
563
+ // A bare \`conveno\` on Windows is a .cmd shim, which only a shell can start. Every argument is a plain word.
564
+ const SHELL = process.platform === "win32" && !/\\.exe$/i.test(COMMAND[0]);
565
+
566
+ // A hook that hands messages over starts its output with "#conveno-ids <id>,<id>" and the prompt
567
+ // follows. If sending the prompt fails, the plugin hands those ids back with \`Requeue\`.
568
+ function split(out) {
569
+ const m = /^#conveno-ids ([^\\n]*)\\n/.exec(out);
570
+ if (!m) return { ids: [], text: out };
571
+ return { ids: m[1].split(",").filter(Boolean), text: out.slice(m[0].length).trim() };
572
+ }
573
+
574
+ function run(event, sessionID, directory, extra) {
575
+ const [file, ...args] = COMMAND;
576
+ const child = spawn(file, [...args, "hook", "opencode", event], {
577
+ stdio: ["pipe", "pipe", "ignore"],
578
+ shell: SHELL,
579
+ windowsHide: true,
580
+ });
581
+ let out = "";
582
+ child.stdout.setEncoding("utf8");
583
+ child.stdout.on("data", (chunk) => {
584
+ out += chunk;
585
+ });
586
+ const done = new Promise((resolve) => {
587
+ child.once("error", () => resolve(""));
588
+ child.once("close", (code) => resolve(code === 0 ? out.trim() : ""));
589
+ });
590
+ child.stdin.on("error", () => {});
591
+ child.stdin.end(JSON.stringify({ hook_event_name: event, sessionID, directory, ...extra }));
592
+ return { child, done };
593
+ }`;
594
+ }
595
+ /** The plugin source with the conveno command baked in. Plain JavaScript, no imports beyond Node built-ins. */
596
+ function pluginSource(command) {
597
+ return `${PLUGIN_MARKER}
598
+ // Conveno plugin for OpenCode. Written by \`conveno init\`; \`conveno uninstall\` removes it.
599
+ // It hands Conveno messages to an idle session. See https://conveno.dev.
600
+ ${runHelper(command)}
601
+
602
+ export const ConvenoPlugin = async ({ client }) => {
603
+ let listener;
604
+
605
+ const stop = () => {
606
+ if (!listener) return;
607
+ listener.child.kill();
608
+ listener = undefined;
609
+ };
610
+
611
+ // Ids of the batch just sent to a session, until it turns busy, the next prompt replaces it, or
612
+ // SENT_TTL_MS pass. A session.error before that means the prompt did not run. An idle event does
613
+ // not clear it: a cancel with no runner can publish one before the error. The TTL stops a much
614
+ // later error (of a turn that did run) from requeueing messages that were delivered.
615
+ const SENT_TTL_MS = 30000;
616
+ const sent = new Map();
617
+ const requeue = (sessionID, ids) =>
618
+ ids.length > 0 ? run("Requeue", sessionID, undefined, { ids }).done : undefined;
619
+
620
+ const prompt = async (sessionID, out) => {
621
+ const { ids, text } = split(out);
622
+ try {
623
+ sent.delete(sessionID);
624
+ if (ids.length > 0) sent.set(sessionID, { ids, at: Date.now() });
625
+ const res = await client.session.promptAsync({
626
+ path: { id: sessionID },
627
+ body: { parts: [{ type: "text", text }] },
628
+ });
629
+ if (res?.error) throw new Error("prompt failed");
630
+ } catch {
631
+ // The session is gone or busy again: hand the messages back so the next turn gets them.
632
+ sent.delete(sessionID);
633
+ await requeue(sessionID, ids);
634
+ }
635
+ };
636
+
637
+ const titles = new Map();
638
+ const retitle = async (sessionID) => {
639
+ try {
640
+ const name = await run("Title", sessionID).done;
641
+ if (!name || titles.get(sessionID) === name) return;
642
+ await client.session.update({ path: { id: sessionID }, body: { title: name } });
643
+ titles.set(sessionID, name);
644
+ } catch {
645
+ // The title is cosmetic.
646
+ }
647
+ };
648
+
649
+ const topLevel = async (sessionID) => {
650
+ try {
651
+ const res = await client.session.get({ path: { id: sessionID } });
652
+ return !res?.data?.parentID;
653
+ } catch {
654
+ return false;
655
+ }
656
+ };
657
+
658
+ const onIdle = async (sessionID) => {
659
+ if (!(await topLevel(sessionID))) return;
660
+ stop();
661
+ void retitle(sessionID);
662
+ const now = await run("Idle", sessionID).done;
663
+ if (now) return prompt(sessionID, now);
664
+ const current = { ...run("Listen", sessionID), sessionID };
665
+ listener = current;
666
+ const text = await current.done;
667
+ if (listener === current) listener = undefined;
668
+ if (text) await prompt(sessionID, text);
669
+ };
670
+
671
+ return {
672
+ event: async ({ event }) => {
673
+ if (event.type === "session.idle") void onIdle(event.properties.sessionID);
674
+ else if (event.type === "session.error") {
675
+ const id = event.properties?.sessionID;
676
+ const entry = id && sent.get(id);
677
+ if (entry) {
678
+ sent.delete(id);
679
+ if (Date.now() - entry.at <= SENT_TTL_MS) await requeue(id, entry.ids);
680
+ }
681
+ } else if (event.type === "session.status" && event.properties.status?.type === "busy") {
682
+ sent.delete(event.properties.sessionID);
683
+ if (event.properties.sessionID === listener?.sessionID) stop();
684
+ }
685
+ },
686
+ dispose: async () => stop(),
687
+ };
688
+ };
689
+ `;
690
+ }
691
+ /**
692
+ * The OpenCode 2.x plugin Conveno installs as `<config dir>/plugins/conveno.js`, the same path as
693
+ * the 1.x one. OpenCode 2.x loads every `.js` and `.ts` file in the global `plugins/` folder
694
+ * (https://opencode.ai/docs/plugins/, "Discover"; `packages/core/src/plugin/module.ts` at tag
695
+ * v2.4.3 accepts a standalone file whose default export is `{ id, setup }`, the object
696
+ * `Plugin.define` returns, so the file needs no import of `@opencode/plugin`).
697
+ *
698
+ * The plugin runs inside the OpenCode server process, which is also the parent of the MCP server
699
+ * it starts, so `conveno hook opencode <event>` finds the session by host process like every other
700
+ * hook. It does no Conveno work itself:
701
+ *
702
+ * - Just before a session goes idle (`experimental.idle`, `packages/plugin/src/promise/session.ts`
703
+ * at v2.4.3) it runs `Idle` and admits waiting messages into the same execution. Every prompt
704
+ * uses `delivery: "queue"`, so it never cuts into a running turn.
705
+ * - The session title follows the Conveno name (`ctx.session.update`).
706
+ * - When an execution of a top-level session in this plugin's directory ends
707
+ * (`session.execution.succeeded`) it runs `Idle`. With messages waiting, that prints
708
+ * the continuation prompt, and the plugin sends it with `ctx.session.prompt`
709
+ * (`POST /api/session/{id}/prompt`).
710
+ * - After a failed or interrupted execution it runs `Stopped`, which records the end without
711
+ * continuing. An execution that a newer one superseded, or that a shutdown cut off, does nothing.
712
+ * - Then it starts `Listen`, which waits in the background and prints a prompt when work arrives
713
+ * while the session is idle; the plugin sends that the same way.
714
+ * - `session.execution.started`, a newer listener, or unloading the plugin stops the listener.
715
+ *
716
+ * - When a session is deleted (`session.deleted`) it runs `Deleted`, which releases the Conveno
717
+ * session so it goes offline at once instead of waiting for the MCP server to lapse it.
718
+ *
719
+ * A prompt sent while the session is busy (between `session.execution.started` and the end event)
720
+ * uses `delivery: "steer"`, which reaches the agent before its next model call
721
+ * (`packages/schema/src/session-inbox.ts` at v2.4.3); an idle session gets `"queue"`.
722
+ *
723
+ * `session.idle` (deprecated) and `session.status` are not used: 2.4.3 does not deliver them to
724
+ * plugins (README, "Events"); the durable `session.execution.*` events replace them. Of the APIs
725
+ * used here, `experimental.idle`, `delivery` and the execution events are feature-detected at run
726
+ * time; the first 2.x release that has all three is UNVERIFIED.
727
+ */
728
+ /** First line of the 2.x plugin. */
729
+ const PLUGIN_MARKER_V2 = `${PLUGIN_MARKER_PREFIX} 2`;
730
+ /** The plugin source with the conveno command baked in. Plain JavaScript, no imports beyond Node built-ins. */
731
+ function pluginSourceV2(command) {
732
+ return `${PLUGIN_MARKER_V2}
733
+ // Conveno plugin for OpenCode 2.x. Written by \`conveno init\`; \`conveno uninstall\` removes it.
734
+ // It hands Conveno messages to an idle session. See https://conveno.dev.
735
+ ${runHelper(command)}
736
+
737
+ export default {
738
+ id: "conveno",
739
+ setup(ctx) {
740
+ const controller = new AbortController();
741
+ let listener;
742
+ // Sessions with a running execution, from the execution events.
743
+ const busy = new Set();
744
+
745
+ const stop = () => {
746
+ if (!listener) return;
747
+ listener.child.kill();
748
+ listener = undefined;
749
+ };
750
+
751
+ const prompt = async (sessionID, out, forceQueue) => {
752
+ const { ids, text } = split(out);
753
+ // "steer" reaches a busy agent before its next model call; "queue" waits for it to finish.
754
+ // The idle hook runs while the execution is still open but about to end, so it queues.
755
+ const delivery = !forceQueue && busy.has(sessionID) ? "steer" : "queue";
756
+ try {
757
+ try {
758
+ await ctx.session.prompt({ sessionID, text, delivery });
759
+ } catch (err) {
760
+ // A server that does not know \`delivery\` rejects it; send without it (the server's default).
761
+ if (!/delivery/i.test(String(err?.message ?? err))) throw err;
762
+ await ctx.session.prompt({ sessionID, text });
763
+ }
764
+ } catch {
765
+ // The session is gone or busy again: hand the messages back so the next turn gets them.
766
+ if (ids.length > 0) await run("Requeue", sessionID, ctx.location.directory, { ids }).done;
767
+ }
768
+ };
769
+
770
+ // The server sends every plugin the events of every location it serves. Only top-level
771
+ // sessions of this plugin's own directory are ours.
772
+ const ours = async (sessionID) => {
773
+ try {
774
+ const info = await ctx.session.get({ sessionID });
775
+ return !info.parentID && info.location.directory === ctx.location.directory;
776
+ } catch {
777
+ return false;
778
+ }
779
+ };
780
+
781
+ // The session title follows the Conveno name; it is cosmetic, so failures are ignored.
782
+ const titles = new Map();
783
+ const retitle = async (sessionID) => {
784
+ try {
785
+ const name = await run("Title", sessionID, ctx.location.directory).done;
786
+ if (!name || titles.get(sessionID) === name) return;
787
+ await ctx.session.update({ sessionID, title: name });
788
+ titles.set(sessionID, name);
789
+ } catch {
790
+ // Ignored.
791
+ }
792
+ };
793
+
794
+ // Runs just before the session goes idle. Messages that arrived during the turn are admitted
795
+ // here, so the same execution carries on instead of the session going idle first.
796
+ if (typeof ctx.session.hook === "function") {
797
+ void ctx.session
798
+ .hook("experimental.idle", async ({ sessionID }) => {
799
+ if (!(await ours(sessionID))) return;
800
+ const now = await run("Idle", sessionID, ctx.location.directory).done;
801
+ if (now) await prompt(sessionID, now, true);
802
+ })
803
+ .catch(() => {});
804
+ }
805
+
806
+ const onEnd = async (sessionID, event) => {
807
+ if (!(await ours(sessionID))) return;
808
+ stop();
809
+ void retitle(sessionID);
810
+ const now = await run(event, sessionID, ctx.location.directory).done;
811
+ if (now) return prompt(sessionID, now);
812
+ const current = { ...run("Listen", sessionID, ctx.location.directory), sessionID };
813
+ listener = current;
814
+ const text = await current.done;
815
+ if (listener === current) listener = undefined;
816
+ if (text) await prompt(sessionID, text);
817
+ };
818
+
819
+ void (async () => {
820
+ try {
821
+ if (typeof ctx.event?.subscribe !== "function") return;
822
+ for await (const event of ctx.event.subscribe({
823
+ types: [
824
+ "session.execution.started",
825
+ "session.execution.succeeded",
826
+ "session.execution.failed",
827
+ "session.execution.interrupted",
828
+ "session.deleted",
829
+ ],
830
+ signal: controller.signal,
831
+ })) {
832
+ const { sessionID } = event.data;
833
+ if (event.type === "session.execution.started") busy.add(sessionID);
834
+ else busy.delete(sessionID);
835
+ if (event.type === "session.deleted") {
836
+ // The session is gone: release its Conveno session so it goes offline now.
837
+ if (sessionID === listener?.sessionID) stop();
838
+ void run("Deleted", sessionID, ctx.location.directory).done;
839
+ } else if (event.type === "session.execution.started") {
840
+ if (sessionID === listener?.sessionID) stop();
841
+ } else if (event.type === "session.execution.succeeded") {
842
+ void onEnd(sessionID, "Idle");
843
+ } else if (
844
+ event.type === "session.execution.failed" ||
845
+ (event.type === "session.execution.interrupted" &&
846
+ (event.data.reason === "user" || event.data.reason === "inactivity"))
847
+ ) {
848
+ void onEnd(sessionID, "Stopped");
849
+ }
850
+ }
851
+ } catch {
852
+ // The subscription ended with the plugin.
853
+ }
854
+ })();
855
+
856
+ return () => {
857
+ controller.abort();
858
+ stop();
859
+ };
860
+ },
861
+ };
862
+ `;
863
+ }
864
+ const SERVER_NAME = "conveno";
865
+ const FORMAT = {
866
+ insertSpaces: true,
867
+ tabSize: 2,
868
+ eol: "\n"
869
+ };
870
+ /**
871
+ * First OpenCode release that reads `mcp.servers` and gets the 2.x plugin. There were no 2.0.x or
872
+ * 2.1.x releases.
873
+ */
874
+ const V2_MIN = [
875
+ 2,
876
+ 2,
877
+ 0
878
+ ];
879
+ /**
880
+ * The 2.x release Conveno is checked against (the 2.4.3 source). Older 2.x still gets the right
881
+ * config, but waking is only supported from here; doctor says so.
882
+ */
883
+ const V2_SUPPORTED = [
884
+ 2,
885
+ 4,
886
+ 0
887
+ ];
888
+ /** `$XDG_CONFIG_HOME/opencode` when XDG_CONFIG_HOME is an absolute path, else `~/.config/opencode`. */
889
+ function configDir(env) {
890
+ const xdg = env.env.XDG_CONFIG_HOME;
891
+ const base = xdg && isAbsolute(xdg) ? xdg : join(env.home, ".config");
892
+ return join(base, "opencode");
893
+ }
894
+ /** `OPENCODE_CONFIG` names one config file; when set it is the only file we touch. */
895
+ const customConfig = (env) => env.env.OPENCODE_CONFIG || void 0;
896
+ /**
897
+ * `OPENCODE_CONFIG` when set. Otherwise an existing opencode.jsonc, then opencode.json, else a
898
+ * new opencode.json in the config directory.
899
+ */
900
+ async function locateConfig(env) {
901
+ const custom = customConfig(env);
902
+ if (custom) try {
903
+ return {
904
+ path: custom,
905
+ text: await readFile(custom, "utf8")
906
+ };
907
+ } catch (err) {
908
+ if (err.code !== "ENOENT") throw err;
909
+ return {
910
+ path: custom,
911
+ text: null
912
+ };
913
+ }
914
+ const dir = configDir(env);
915
+ for (const name of ["opencode.jsonc", "opencode.json"]) {
916
+ const path = join(dir, name);
917
+ try {
918
+ return {
919
+ path,
920
+ text: await readFile(path, "utf8")
921
+ };
922
+ } catch (err) {
923
+ if (err.code !== "ENOENT") throw err;
924
+ }
925
+ }
926
+ return {
927
+ path: join(dir, "opencode.json"),
928
+ text: null
929
+ };
930
+ }
931
+ function parseConfig(file) {
932
+ if (file.text === null || file.text.trim() === "") return {};
933
+ const errors = [];
934
+ const value = parse(file.text, errors, { allowTrailingComma: true });
935
+ const first = errors[0];
936
+ 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.`);
937
+ 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.`);
938
+ return value;
939
+ }
940
+ function serverEntry(env, shape) {
941
+ const command = [
942
+ ...env.conveno.command,
943
+ "mcp",
944
+ "--cli",
945
+ "opencode"
946
+ ];
947
+ return shape === "v1" ? {
948
+ type: "local",
949
+ command,
950
+ enabled: true
951
+ } : {
952
+ type: "local",
953
+ command
954
+ };
955
+ }
956
+ function parseVersion(text) {
957
+ const m = /(\d+)\.(\d+)\.(\d+)/.exec(text);
958
+ return m ? [
959
+ Number(m[1]),
960
+ Number(m[2]),
961
+ Number(m[3])
962
+ ] : void 0;
963
+ }
964
+ function atLeast(v, min) {
965
+ for (let i = 0; i < 3; i++) if (v[i] !== min[i]) return v[i] > min[i];
966
+ return true;
967
+ }
968
+ function isV2OrLater(v) {
969
+ return atLeast(v, V2_MIN);
970
+ }
971
+ /** One line for `conveno doctor` when this OpenCode is a 2.x release older than the supported one. */
972
+ async function opencodeDoctorNotes(env) {
973
+ const v = await installedVersion(env);
974
+ if (!v || !isV2OrLater(v) || atLeast(v, V2_SUPPORTED)) return [];
975
+ return [`OpenCode ${v.join(".")} is older than 2.4, the oldest 2.x Conveno supports. Update OpenCode so waking works.`];
976
+ }
977
+ async function installedVersion(env) {
978
+ try {
979
+ const res = await env.exec("opencode", ["--version"]);
980
+ return res.code === 0 ? parseVersion(res.stdout) : void 0;
981
+ } catch {
982
+ return;
983
+ }
984
+ }
985
+ async function chooseShape(config, version) {
986
+ if (version) return isV2OrLater(version) ? "v2" : "v1";
987
+ return servers(config) !== void 0 ? "v2" : "v1";
988
+ }
989
+ function v1Entry(config) {
990
+ const mcp = config.mcp;
991
+ if (mcp === null || typeof mcp !== "object" || Array.isArray(mcp)) return void 0;
992
+ return mcp[SERVER_NAME];
993
+ }
994
+ function pathFor(shape) {
995
+ return shape === "v1" ? ["mcp", SERVER_NAME] : [
996
+ "mcp",
997
+ "servers",
998
+ SERVER_NAME
999
+ ];
1000
+ }
1001
+ function sameEntry(found, want) {
1002
+ if (found === null || typeof found !== "object") return false;
1003
+ const f = found;
1004
+ 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]);
1005
+ }
1006
+ function servers(config) {
1007
+ const mcp = config.mcp;
1008
+ if (mcp === null || typeof mcp !== "object" || Array.isArray(mcp)) return void 0;
1009
+ const s = mcp.servers;
1010
+ if (s === null || typeof s !== "object" || Array.isArray(s)) return void 0;
1011
+ return s;
1012
+ }
1013
+ async function detect(env) {
1014
+ const custom = customConfig(env);
1015
+ const configPaths = custom ? [custom] : [join(configDir(env), "opencode.jsonc"), join(configDir(env), "opencode.json")];
1016
+ try {
1017
+ const res = await env.exec("opencode", ["--version"]);
1018
+ if (res.code !== 0) return {
1019
+ installed: false,
1020
+ configPaths
1021
+ };
1022
+ const version = parseCliVersion(res.stdout);
1023
+ return {
1024
+ installed: true,
1025
+ binary: "opencode",
1026
+ configPaths,
1027
+ ...version ? { version } : {}
1028
+ };
1029
+ } catch {
1030
+ return {
1031
+ installed: false,
1032
+ configPaths
1033
+ };
1034
+ }
1035
+ }
1036
+ /** `<config dir>/plugins/conveno.js`, the global plugin folder OpenCode 1.x and 2.x load. */
1037
+ const pluginPath = (env) => join(configDir(env), "plugins", "conveno.js");
1038
+ async function readText(path) {
1039
+ try {
1040
+ return await readFile(path, "utf8");
1041
+ } catch (err) {
1042
+ if (err.code === "ENOENT") return null;
1043
+ throw err;
1044
+ }
1045
+ }
1046
+ /**
1047
+ * The plugin API differs between the lines (https://opencode.ai/docs/build/plugins/migrate-v1/), so
1048
+ * each gets its own source at the same path. An unknown version gets nothing rather than a file
1049
+ * that might not load.
1050
+ */
1051
+ const pluginFor = (env, version) => {
1052
+ if (version === void 0) return void 0;
1053
+ return isV2OrLater(version) ? pluginSourceV2(env.conveno.command) : pluginSource(env.conveno.command);
1054
+ };
1055
+ async function planPlugin(env, version) {
1056
+ const want = pluginFor(env, version);
1057
+ if (want === void 0) return [];
1058
+ const path = pluginPath(env);
1059
+ const before = await readText(path);
1060
+ if (before === want) return [];
1061
+ 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.`);
1062
+ return [{
1063
+ component: "hooks",
1064
+ kind: before === null ? "add" : "update",
1065
+ parts: [{
1066
+ name: "plugin file",
1067
+ kind: before === null ? "add" : "update"
1068
+ }],
1069
+ path,
1070
+ before,
1071
+ after: want,
1072
+ description: `${before === null ? "Add" : "Update"} the Conveno plugin for OpenCode ${version && isV2OrLater(version) ? "2.x" : "1.x"}. It hands waiting messages to a session when its turn ends or while it is idle.`
1073
+ }];
1074
+ }
1075
+ async function uninstallPlugin(env) {
1076
+ const path = pluginPath(env);
1077
+ const before = await readText(path);
1078
+ if (before === null || !before.startsWith("// conveno-plugin:")) return [];
1079
+ return [{
1080
+ component: "hooks",
1081
+ kind: "remove",
1082
+ path,
1083
+ before,
1084
+ after: "",
1085
+ deleteFile: true,
1086
+ description: "Remove the Conveno plugin for OpenCode."
1087
+ }];
1088
+ }
1089
+ async function plan(env) {
1090
+ const version = await installedVersion(env);
1091
+ return [...await planMcp(env, version), ...await planPlugin(env, version)];
1092
+ }
1093
+ async function uninstallPlan(env) {
1094
+ return [...await uninstallMcp(env), ...await uninstallPlugin(env)];
1095
+ }
1096
+ async function planMcp(env, version) {
1097
+ const file = await locateConfig(env);
1098
+ const config = parseConfig(file);
1099
+ const shape = await chooseShape(config, version);
1100
+ const want = serverEntry(env, shape);
1101
+ const current = shape === "v1" ? v1Entry(config) : servers(config)?.[SERVER_NAME];
1102
+ if (sameEntry(current, want)) return [];
1103
+ let text = file.text === null || file.text.trim() === "" ? "{}\n" : file.text;
1104
+ const otherShape = shape === "v1" ? "v2" : "v1";
1105
+ const other = otherShape === "v1" ? v1Entry(config) : servers(config)?.[SERVER_NAME];
1106
+ if (other !== void 0) text = applyEdits(text, modify(text, pathFor(otherShape), void 0, { formattingOptions: FORMAT }));
1107
+ let after = applyEdits(text, modify(text, pathFor(shape), want, { formattingOptions: FORMAT }));
1108
+ if (!after.endsWith("\n")) after += "\n";
1109
+ const where = shape === "v1" ? `mcp.${SERVER_NAME}` : `mcp.servers.${SERVER_NAME}`;
1110
+ return [{
1111
+ component: "mcp",
1112
+ kind: current !== void 0 || other !== void 0 ? "update" : "add",
1113
+ parts: [{
1114
+ name: "MCP server",
1115
+ kind: current !== void 0 || other !== void 0 ? "update" : "add"
1116
+ }],
1117
+ path: file.path,
1118
+ before: file.text,
1119
+ after,
1120
+ description: `Add the conveno MCP server (${where}) to the OpenCode global config`
1121
+ }];
1122
+ }
1123
+ async function uninstallMcp(env) {
1124
+ const file = await locateConfig(env);
1125
+ if (file.text === null) return [];
1126
+ const config = parseConfig(file);
1127
+ let text = file.text;
1128
+ const removed = [];
1129
+ if (servers(config)?.[SERVER_NAME] !== void 0) {
1130
+ text = applyEdits(text, modify(text, pathFor("v2"), void 0, { formattingOptions: FORMAT }));
1131
+ removed.push(`mcp.servers.${SERVER_NAME}`);
1132
+ }
1133
+ if (v1Entry(config) !== void 0) {
1134
+ text = applyEdits(text, modify(text, pathFor("v1"), void 0, { formattingOptions: FORMAT }));
1135
+ removed.push(`mcp.${SERVER_NAME}`);
1136
+ }
1137
+ if (removed.length === 0) return [];
1138
+ return [{
1139
+ component: "mcp",
1140
+ kind: "remove",
1141
+ path: file.path,
1142
+ before: file.text,
1143
+ after: text,
1144
+ description: `Remove the conveno MCP server (${removed.join(", ")}) from the OpenCode global config`
1145
+ }];
1146
+ }
1147
+ const EMPTY = {
1148
+ stdout: "",
1149
+ exitCode: 0
1150
+ };
1151
+ /**
1152
+ * Run by the plugin, never by OpenCode itself. Each prints the prompt to send as plain text, which
1153
+ * the plugin sends to the session (1.x `client.session.promptAsync`, 2.x `ctx.session.prompt`).
1154
+ * - Idle: the session's turn ended. With messages waiting, the prompt to continue with.
1155
+ * - Stopped: the turn failed or the user interrupted it. Records the end and never continues.
1156
+ * - Listen: the background listener. Waits for work while the session is idle.
1157
+ * - Requeue: the plugin could not send the prompt; puts the messages (`ids` in the input) back to queued.
1158
+ * - Deleted: the OpenCode session was deleted; unregisters its Conveno session.
1159
+ * - Title: prints the session's Conveno name, which the plugin sets as the OpenCode session title.
1160
+ */
1161
+ async function hook(event, input, ctx) {
1162
+ const dir = typeof input === "object" && input !== null ? input.directory : void 0;
1163
+ if (typeof dir === "string" && dir !== "") ctx = {
1164
+ ...ctx,
1165
+ cwd: dir
1166
+ };
1167
+ const native = typeof input === "object" && input !== null ? input.sessionID : void 0;
1168
+ if (typeof native === "string" && native !== "") ctx = {
1169
+ ...ctx,
1170
+ nativeId: native
1171
+ };
1172
+ if (event === "Deleted") {
1173
+ await release(ctx, input);
1174
+ return EMPTY;
1175
+ }
1176
+ if (event === "Requeue") {
1177
+ await requeue(ctx, input);
1178
+ return EMPTY;
1179
+ }
1180
+ const ids = [];
1181
+ if (ctx.client) ctx = {
1182
+ ...ctx,
1183
+ client: recordIds(ctx.client, ids)
1184
+ };
1185
+ let text = null;
1186
+ if (event === "Idle") text = await endTurnContinuation(ctx);
1187
+ else if (event === "Stopped") await endTurnContinuation(ctx, { allowContinue: false });
1188
+ else if (event === "Listen") text = await waitForWork(ctx);
1189
+ else if (event === "Title") text = await sessionName(ctx);
1190
+ if (text === null) return EMPTY;
1191
+ return {
1192
+ stdout: ids.length > 0 ? `#conveno-ids ${ids.join(",")}\n${text}` : text,
1193
+ exitCode: 0
1194
+ };
1195
+ }
1196
+ /** The client, with the ids of every message `turn.end` and `turn.wake` return copied into `ids`. */
1197
+ function recordIds(client, ids) {
1198
+ return new Proxy(client, { get(target, prop, receiver) {
1199
+ const value = Reflect.get(target, prop, receiver);
1200
+ if (prop !== "turn.end" && prop !== "turn.wake" || typeof value !== "function") return value;
1201
+ return async (...args) => {
1202
+ const r = await value.apply(target, args);
1203
+ for (const m of r?.messages ?? []) ids.push(m.id);
1204
+ return r;
1205
+ };
1206
+ } });
1207
+ }
1208
+ /** `Deleted`: the OpenCode session is gone, so its Conveno session goes offline now. */
1209
+ async function release(ctx, input) {
1210
+ try {
1211
+ const id = input?.sessionID;
1212
+ if (typeof id !== "string" || id === "") return;
1213
+ const session = await ownSession(ctx);
1214
+ if (!session) return;
1215
+ await ctx.client["session.unregister"]({ sessionId: session.id });
1216
+ } catch {}
1217
+ }
1218
+ /** `Requeue`: sending the prompt failed, so the messages go back to queued for the next turn. */
1219
+ async function requeue(ctx, input) {
1220
+ try {
1221
+ const ids = input?.ids;
1222
+ if (!Array.isArray(ids) || ids.length === 0) return;
1223
+ const session = await ownSession(ctx);
1224
+ if (!session) return;
1225
+ await ctx.client["message.requeue"]({
1226
+ sessionId: session.id,
1227
+ ids
1228
+ });
1229
+ } catch {}
1230
+ }
1231
+ async function sessionName(ctx) {
1232
+ try {
1233
+ const session = await ownSession(ctx);
1234
+ return session?.name ? session.name : null;
1235
+ } catch {
1236
+ return null;
1237
+ }
1238
+ }
1239
+ /**
1240
+ * Only the plugin delivers, on 1.x and 2.4+ alike; it adds nothing to a prompt the user types.
1241
+ * 2.0 to 2.3 are not supported (`opencodeDoctorNotes`), so doctor claims no waking for them.
1242
+ */
1243
+ function delivery(detection) {
1244
+ const v = detection.version === void 0 ? void 0 : parseVersion(detection.version);
1245
+ const supported = v !== void 0 && (!isV2OrLater(v) || atLeast(v, V2_SUPPORTED));
1246
+ return {
1247
+ nextTurn: false,
1248
+ endOfTurn: supported,
1249
+ idleWake: supported
1250
+ };
1251
+ }
1252
+ const opencodeAdapter = {
1253
+ doctorNotes: opencodeDoctorNotes,
1254
+ cli: "opencode",
1255
+ displayName: "OpenCode",
1256
+ deliveryTier: "inbox",
1257
+ detect,
1258
+ plan,
1259
+ uninstallPlan,
1260
+ hook,
1261
+ listenEvents: ["Listen"],
1262
+ delivery
1263
+ };
1264
+ // src/hook-entry.ts
1265
+ function readAllStdin() {
1266
+ if (process.stdin.isTTY) return Promise.resolve("");
1267
+ return new Promise((resolve, reject) => {
1268
+ let data = "";
1269
+ process.stdin.setEncoding("utf8");
1270
+ process.stdin.on("data", (c) => {
1271
+ data += c;
1272
+ });
1273
+ process.stdin.on("end", () => resolve(data));
1274
+ process.stdin.on("error", reject);
1275
+ });
1276
+ }
1277
+ /** `kill(pid, 0)` liveness: EPERM means the process exists but belongs to someone else. */
1278
+ function isProcessAlive(pid) {
1279
+ try {
1280
+ process.kill(pid, 0);
1281
+ return true;
1282
+ } catch (e) {
1283
+ return e.code === "EPERM";
1284
+ }
1285
+ }
1286
+ function createHookCtx() {
1287
+ const launcherPaths = process.argv[1] ? [process.argv[1]] : [];
1288
+ return {
1289
+ dataDir: dataDir(process.platform, process.env, homedir()),
1290
+ adapters: [
1291
+ claudeAdapter,
1292
+ codexAdapter,
1293
+ opencodeAdapter,
1294
+ antigravityAdapter,
1295
+ grokAdapter
1296
+ ],
1297
+ out: (s) => void process.stdout.write(s),
1298
+ err: (s) => void process.stderr.write(s),
1299
+ readStdin: readAllStdin,
1300
+ connect,
1301
+ ancestry: (timeoutMs) => readAncestry({
1302
+ timeoutMs,
1303
+ launcherPaths
1304
+ }),
1305
+ hostLookup: {
1306
+ ppid: process.ppid,
1307
+ launcherPaths
1308
+ },
1309
+ isAlive: isProcessAlive,
1310
+ hookTimeoutMs: 2e3,
1311
+ ...process.env.CONVENO_HOOK_TIMING_LOG ? {
1312
+ timingLog: process.env.CONVENO_HOOK_TIMING_LOG,
1313
+ uptimeMs: () => process.uptime() * 1e3
1314
+ } : {}
1315
+ };
1316
+ }
1317
+ function runHookEntry(argv) {
1318
+ return runHook(createHookCtx(), argv);
1319
+ }
1320
+ export { opencodeAdapter as a, runHookEntry as i, isProcessAlive as n, claudeAdapter as o, readAllStdin as r, createHookCtx as t };