@conveno/cli 0.2.0-rc.10 → 0.2.0-rc.12

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