@conveno/cli 0.1.1 → 0.2.0-rc.10
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.
- package/README.md +34 -16
- package/dist/acp-TSjX4JP9.js +82 -0
- package/dist/agy-relay-D-OWo85B.js +137 -0
- package/dist/args-B3Cj2Ie4.js +361 -0
- package/dist/bin.js +24 -4383
- package/dist/ctx-tYftvhz_.js +17 -0
- package/dist/daemon.js +2239 -144
- package/dist/daemonError-C05GqdhQ.js +66 -0
- package/dist/dist-BLfduOoT.js +624 -0
- package/dist/dist-BRjg9CLd.js +731 -0
- package/dist/dist-CVdpCNJo.js +793 -0
- package/dist/dist-D_O_JLLq.js +473 -0
- package/dist/dist-DaIpdMke.js +667 -0
- package/dist/dist-MK-cK1JY.js +969 -0
- package/dist/dist-STNJjbNH.js +10084 -0
- package/dist/dist-VOS92iqO.js +645 -0
- package/dist/fmt-C2SsP5Y0.js +96 -0
- package/dist/hook-CDF1A8AY.js +114 -0
- package/dist/hook-entry-C0bPssOy.js +1 -0
- package/dist/hook-entry-CQQU-e_t.js +2500 -0
- package/dist/main-BhKTG0AI.js +650 -0
- package/dist/pick-DLp6w_-z.js +9 -0
- package/dist/run-eCXO1SyO.js +5609 -0
- package/dist/runtime-BGPlr8CI.js +772 -0
- package/dist/toml-patch-DGzVRdd1.js +6756 -0
- package/dist/uninstall-DQlzpv5R.js +2034 -0
- package/dist/watch-D0KIPowJ.js +185 -0
- package/package.json +27 -11
- package/dist/dist-WPVVRVUh.js +0 -1507
|
@@ -0,0 +1,2500 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { n as antigravityAdapter } from "./dist-VOS92iqO.js";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
import { B as editJson$1, Et as readAncestry, Ft as requeueMessages, H as endTurnContinuation, Ht as sameJson$1, It as requeueOwnMessages, Kt as startTurnContext, P as dataDir, W as existedBefore, _t as pendingHookContext, dt as ownSession, et as isObject$1, nn as waitForWork, ot as loadJson$1, pt as parseCliVersion, rn as waitForWorkBatch, wt as putInList, z as dropFromList } from "./dist-STNJjbNH.js";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
|
|
7
|
+
import { t as codexAdapter } from "./dist-MK-cK1JY.js";
|
|
8
|
+
import { t as grokAdapter } from "./dist-DaIpdMke.js";
|
|
9
|
+
import { n as connect } from "./dist-D_O_JLLq.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$3 = "conveno";
|
|
65
|
+
/** Claude Code events Conveno installs hooks for. */
|
|
66
|
+
const HOOK_EVENTS$2 = [
|
|
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$1 = "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$1 = 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$1 = 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$1],
|
|
130
|
+
UserPromptSubmit: ["UserPromptSubmit"],
|
|
131
|
+
PostToolUse: ["PostToolUse"],
|
|
132
|
+
Stop: ["Stop", LISTEN_EVENT$1]
|
|
133
|
+
};
|
|
134
|
+
const EMPTY$3 = {
|
|
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$2(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$2 = (env) => [
|
|
191
|
+
...env.conveno.command,
|
|
192
|
+
"mcp",
|
|
193
|
+
"--cli",
|
|
194
|
+
"claude"
|
|
195
|
+
];
|
|
196
|
+
const desiredServer$2 = (env) => {
|
|
197
|
+
const [command = "conveno", ...args] = mcpArgs$2(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$2(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$2(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$2(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$2(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$3(env) {
|
|
262
|
+
const p = paths$2(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$3(env) {
|
|
287
|
+
const p = paths$2(env);
|
|
288
|
+
const changes = [];
|
|
289
|
+
const mcpFile = await loadJson(p.mcp);
|
|
290
|
+
const servers = mcpObject$2(mcpFile.value, p.mcp);
|
|
291
|
+
const want = desiredServer$2(env);
|
|
292
|
+
if (!sameJson(servers["conveno"], want)) {
|
|
293
|
+
const after = editJson(mcpFile, [{
|
|
294
|
+
path: ["mcpServers", SERVER_NAME$3],
|
|
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$3}" MCP server at user scope (conveno mcp --cli claude).`,
|
|
308
|
+
viaCommand: [
|
|
309
|
+
"claude",
|
|
310
|
+
"mcp",
|
|
311
|
+
"add",
|
|
312
|
+
"--scope",
|
|
313
|
+
"user",
|
|
314
|
+
SERVER_NAME$3,
|
|
315
|
+
"--",
|
|
316
|
+
...mcpArgs$2(env)
|
|
317
|
+
]
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
const setFile = await loadJson(p.settings);
|
|
321
|
+
const hooks = hooksObject$2(setFile.value, p.settings);
|
|
322
|
+
const missing = HOOK_EVENTS$2.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$2, ...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$3(env) {
|
|
346
|
+
const p = paths$2(env);
|
|
347
|
+
const changes = [];
|
|
348
|
+
const mcpFile = await loadJson(p.mcp);
|
|
349
|
+
if ("conveno" in mcpObject$2(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$3],
|
|
356
|
+
value: void 0
|
|
357
|
+
}]),
|
|
358
|
+
description: `Remove the "${SERVER_NAME$3}" MCP server from user scope.`,
|
|
359
|
+
viaCommand: [
|
|
360
|
+
"claude",
|
|
361
|
+
"mcp",
|
|
362
|
+
"remove",
|
|
363
|
+
"--scope",
|
|
364
|
+
"user",
|
|
365
|
+
SERVER_NAME$3
|
|
366
|
+
]
|
|
367
|
+
});
|
|
368
|
+
const setFile = await loadJson(p.settings);
|
|
369
|
+
const hooks = hooksObject$2(setFile.value, p.settings);
|
|
370
|
+
const next = { ...hooks };
|
|
371
|
+
const edits = [];
|
|
372
|
+
for (const e of [...HOOK_EVENTS$2, ...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$3 : {
|
|
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$3(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$3;
|
|
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$1: {
|
|
492
|
+
const entry = process.env.CLAUDE_CODE_ENTRYPOINT;
|
|
493
|
+
if (entry !== void 0 && NON_INTERACTIVE_ENTRYPOINTS.has(entry)) return EMPTY$3;
|
|
494
|
+
const own = await withSessionId(ctx, input);
|
|
495
|
+
const r = await waitForWorkBatch(own, {
|
|
496
|
+
maxMs: LISTEN_MAX_MS$1,
|
|
497
|
+
registerWaitMs: LISTEN_REGISTER_WAIT_MS$1,
|
|
498
|
+
reconnectMs: LISTEN_RECONNECT_MS,
|
|
499
|
+
maxChars: WAKE_MAX_CHARS
|
|
500
|
+
});
|
|
501
|
+
if (r === null) return EMPTY$3;
|
|
502
|
+
if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) {
|
|
503
|
+
await requeueMessages(ctx.client, r.sessionId, r.batch.messages);
|
|
504
|
+
return EMPTY$3;
|
|
505
|
+
}
|
|
506
|
+
return {
|
|
507
|
+
stdout: "",
|
|
508
|
+
stderr: `${WAKE_LEAD}\n\n${r.batch.text}`,
|
|
509
|
+
exitCode: 2
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
default: return EMPTY$3;
|
|
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$3,
|
|
525
|
+
plan: plan$3,
|
|
526
|
+
uninstallPlan: uninstallPlan$3,
|
|
527
|
+
hook: hook$3,
|
|
528
|
+
listenEvents: [LISTEN_EVENT$1],
|
|
529
|
+
delivery: delivery$1
|
|
530
|
+
};
|
|
531
|
+
// ../adapters/copilot/dist/index.js
|
|
532
|
+
/**
|
|
533
|
+
* The Copilot CLI extension Conveno installs as `<copilot home>/extensions/conveno/extension.mjs`.
|
|
534
|
+
* Copilot starts every extension in that folder as its own Node process next to an interactive
|
|
535
|
+
* session, once experimental mode is on (https://docs.github.com/en/copilot/tutorials/create-an-extension).
|
|
536
|
+
* The extension joins the session with `joinSession()` from `@github/copilot-sdk/extension`, which
|
|
537
|
+
* the CLI itself provides, so the file has no imports to install.
|
|
538
|
+
*
|
|
539
|
+
* It does no Conveno work itself. While the session is idle it runs `conveno hook copilot Listen`,
|
|
540
|
+
* the shared listener (it waits for the daemon to hand the session messages, like Claude's), and
|
|
541
|
+
* sends what that prints with `session.send({ prompt, mode: "enqueue" })`, which starts a turn
|
|
542
|
+
* with no keypress. Any turn starting stops the listener; `session.idle` starts it again.
|
|
543
|
+
*
|
|
544
|
+
* Listen's output starts with a line `#conveno-ids <id>,<id>`. The extension cuts that line off, so
|
|
545
|
+
* it never reaches the model, and if `session.send` fails it runs `hook copilot Requeue` with the
|
|
546
|
+
* ids so the messages are queued again. On SIGTERM it does the same for a listener it stops.
|
|
547
|
+
*
|
|
548
|
+
* Listen and Requeue run under this process, not under Copilot, so they name the session by
|
|
549
|
+
* Copilot's `sessionId`, and Listen also passes `process.ppid`: Copilot forks every extension
|
|
550
|
+
* (copilot-sdk docs/extensions.md), so that is the CLI that hosts the session.
|
|
551
|
+
*/
|
|
552
|
+
/** Start of the first line of the extension file. Uninstall and re-install recognise it by this. */
|
|
553
|
+
const EXTENSION_MARKER_PREFIX = "// conveno-extension:";
|
|
554
|
+
const EXTENSION_MARKER = `${EXTENSION_MARKER_PREFIX} 1`;
|
|
555
|
+
/** Plain JavaScript source with the conveno command baked in. No imports beyond Node built-ins and the SDK. */
|
|
556
|
+
function extensionSource(command) {
|
|
557
|
+
return `${EXTENSION_MARKER}
|
|
558
|
+
// Conveno extension for GitHub Copilot CLI. Written by \`conveno init\`; \`conveno uninstall\` removes it.
|
|
559
|
+
// It wakes an idle session when a Conveno message arrives. See https://conveno.dev.
|
|
560
|
+
import { spawn } from "node:child_process";
|
|
561
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
562
|
+
import { dirname, join } from "node:path";
|
|
563
|
+
import { joinSession } from "@github/copilot-sdk/extension";
|
|
564
|
+
|
|
565
|
+
const COMMAND = ${JSON.stringify(command)};
|
|
566
|
+
// A listener that ends without a message (daemon not up yet, superseded) is retried, first soon,
|
|
567
|
+
// then less often, up to this long.
|
|
568
|
+
const RETRY_MIN_MS = 1000;
|
|
569
|
+
const RETRY_MAX_MS = 30000;
|
|
570
|
+
// On SIGTERM, wait at most this long for messages a listener already took to go back to the queue.
|
|
571
|
+
const QUIT_MS = 3000;
|
|
572
|
+
|
|
573
|
+
// The first PATH entry that holds this file.
|
|
574
|
+
const onPath = (name) => {
|
|
575
|
+
for (const dir of (process.env.PATH ?? "").split(";")) {
|
|
576
|
+
if (dir && existsSync(join(dir, name))) return join(dir, name);
|
|
577
|
+
}
|
|
578
|
+
return undefined;
|
|
579
|
+
};
|
|
580
|
+
|
|
581
|
+
// A bare \`conveno\` on Windows is an npm .cmd shim. Run its node entry directly, so no shell is involved
|
|
582
|
+
// and killing the child kills the listener. The node is the one the shim itself would run: node.exe
|
|
583
|
+
// next to the shim, else node.exe on PATH (npm cmd-shim). Not process.execPath: in a native Copilot
|
|
584
|
+
// build that is copilot.exe. Only if neither can be found is a shell used.
|
|
585
|
+
const resolveCommand = () => {
|
|
586
|
+
const [file, ...args] = COMMAND;
|
|
587
|
+
if (process.platform !== "win32" || /\\.exe$/i.test(file)) return { file, args, shell: false };
|
|
588
|
+
try {
|
|
589
|
+
const dirs = /[\\\\/]/.test(file) ? [""] : (process.env.PATH ?? "").split(";");
|
|
590
|
+
for (const dir of dirs) {
|
|
591
|
+
const shim = join(dir, /\\.cmd$/i.test(file) ? file : file + ".cmd");
|
|
592
|
+
if (!existsSync(shim)) continue;
|
|
593
|
+
const m = /"%(?:~dp0|dp0%)\\\\?([^"%]*\\.[cm]?js)"/i.exec(readFileSync(shim, "utf8"));
|
|
594
|
+
if (!m) continue;
|
|
595
|
+
const local = join(dirname(shim), "node.exe");
|
|
596
|
+
const node = existsSync(local) ? local : onPath("node.exe");
|
|
597
|
+
if (node) return { file: node, args: [join(dirname(shim), m[1]), ...args], shell: false };
|
|
598
|
+
}
|
|
599
|
+
} catch {}
|
|
600
|
+
return { file, args, shell: true };
|
|
601
|
+
};
|
|
602
|
+
const RESOLVED = resolveCommand();
|
|
603
|
+
|
|
604
|
+
const run = (extra, stdio) =>
|
|
605
|
+
spawn(RESOLVED.file, [...RESOLVED.args, ...extra], { stdio, shell: RESOLVED.shell, windowsHide: true });
|
|
606
|
+
|
|
607
|
+
// With a shell on Windows, child.kill() only ends cmd.exe and orphans the listener: kill the whole tree.
|
|
608
|
+
const kill = (child) => {
|
|
609
|
+
if (process.platform === "win32" && RESOLVED.shell && child.pid) {
|
|
610
|
+
const t = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
611
|
+
t.once("error", () => child.kill());
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
child.kill();
|
|
615
|
+
};
|
|
616
|
+
|
|
617
|
+
const session = await joinSession({});
|
|
618
|
+
|
|
619
|
+
// Listen's output: "#conveno-ids <id>,<id>" on the first line, then the prompt.
|
|
620
|
+
const split = (out) => {
|
|
621
|
+
const m = /^#conveno-ids ([^\\n]*)\\n/.exec(out);
|
|
622
|
+
if (!m) return { ids: [], text: out.trim() };
|
|
623
|
+
return { ids: m[1].split(",").filter(Boolean), text: out.slice(m[0].length).trim() };
|
|
624
|
+
};
|
|
625
|
+
|
|
626
|
+
const requeue = (ids) =>
|
|
627
|
+
new Promise((resolve) => {
|
|
628
|
+
if (ids.length === 0) return resolve();
|
|
629
|
+
const child = run(["hook", "copilot", "Requeue"], ["pipe", "ignore", "ignore"]);
|
|
630
|
+
child.once("error", () => resolve());
|
|
631
|
+
child.once("close", () => resolve());
|
|
632
|
+
child.stdin.on("error", () => {});
|
|
633
|
+
child.stdin.end(JSON.stringify({ hook_event_name: "Requeue", sessionId: session.sessionId, ids }));
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
let busy = false;
|
|
637
|
+
let quitting = false;
|
|
638
|
+
let listener;
|
|
639
|
+
let retry;
|
|
640
|
+
let retryMs = RETRY_MIN_MS;
|
|
641
|
+
// Listeners that have not finished putting back what they took. SIGTERM waits for them.
|
|
642
|
+
const endings = new Set();
|
|
643
|
+
|
|
644
|
+
const stop = () => {
|
|
645
|
+
clearTimeout(retry);
|
|
646
|
+
retry = undefined;
|
|
647
|
+
if (!listener) return;
|
|
648
|
+
const child = listener;
|
|
649
|
+
listener = undefined;
|
|
650
|
+
kill(child);
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
const later = () => {
|
|
654
|
+
if (quitting) return;
|
|
655
|
+
retry = setTimeout(arm, retryMs);
|
|
656
|
+
retryMs = Math.min(retryMs * 2, RETRY_MAX_MS);
|
|
657
|
+
};
|
|
658
|
+
|
|
659
|
+
const send = async (text) => {
|
|
660
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
661
|
+
try {
|
|
662
|
+
await session.send({ prompt: text, mode: "enqueue" });
|
|
663
|
+
return true;
|
|
664
|
+
} catch {
|
|
665
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
return false;
|
|
669
|
+
};
|
|
670
|
+
|
|
671
|
+
const arm = () => {
|
|
672
|
+
if (busy || listener || quitting) return;
|
|
673
|
+
const child = run(["hook", "copilot", "Listen"], ["pipe", "pipe", "ignore"]);
|
|
674
|
+
listener = child;
|
|
675
|
+
let out = "";
|
|
676
|
+
let ended = false;
|
|
677
|
+
child.stdout.setEncoding("utf8");
|
|
678
|
+
child.stdout.on("data", (chunk) => {
|
|
679
|
+
out += chunk;
|
|
680
|
+
});
|
|
681
|
+
child.stdin.on("error", () => {});
|
|
682
|
+
// copilotPid: Copilot forks every extension, so the parent is the CLI that hosts the session.
|
|
683
|
+
child.stdin.end(
|
|
684
|
+
JSON.stringify({ hook_event_name: "Listen", sessionId: session.sessionId, copilotPid: process.ppid }),
|
|
685
|
+
);
|
|
686
|
+
const finish = async (code) => {
|
|
687
|
+
if (ended) return;
|
|
688
|
+
ended = true;
|
|
689
|
+
const current = listener === child;
|
|
690
|
+
if (current) listener = undefined;
|
|
691
|
+
const { ids, text } = split(out);
|
|
692
|
+
// Whenever the output is not sent (stopped by a user turn, failed exit, busy, quitting), the
|
|
693
|
+
// daemon has already handed these messages over, so put them back.
|
|
694
|
+
if (!current || code !== 0 || !text || busy || quitting) {
|
|
695
|
+
await requeue(ids);
|
|
696
|
+
if (current && !busy && !listener) later();
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
busy = true;
|
|
700
|
+
if (await send(text)) {
|
|
701
|
+
retryMs = RETRY_MIN_MS;
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
await requeue(ids);
|
|
705
|
+
busy = false;
|
|
706
|
+
later();
|
|
707
|
+
};
|
|
708
|
+
let done;
|
|
709
|
+
const ending = new Promise((resolve) => {
|
|
710
|
+
done = resolve;
|
|
711
|
+
});
|
|
712
|
+
endings.add(ending);
|
|
713
|
+
void ending.then(() => endings.delete(ending));
|
|
714
|
+
child.once("error", () => done(finish(1)));
|
|
715
|
+
child.once("close", (code) => done(finish(code)));
|
|
716
|
+
};
|
|
717
|
+
|
|
718
|
+
session.on("user.message", () => {
|
|
719
|
+
busy = true;
|
|
720
|
+
stop();
|
|
721
|
+
});
|
|
722
|
+
session.on("assistant.turn_start", () => {
|
|
723
|
+
busy = true;
|
|
724
|
+
stop();
|
|
725
|
+
});
|
|
726
|
+
session.on("session.idle", () => {
|
|
727
|
+
busy = false;
|
|
728
|
+
arm();
|
|
729
|
+
});
|
|
730
|
+
|
|
731
|
+
// Stop the listener and let it put back what it took before exiting, within QUIT_MS.
|
|
732
|
+
const quit = async () => {
|
|
733
|
+
if (quitting) return;
|
|
734
|
+
quitting = true;
|
|
735
|
+
stop();
|
|
736
|
+
await Promise.race([
|
|
737
|
+
Promise.all([...endings]),
|
|
738
|
+
new Promise((resolve) => setTimeout(resolve, QUIT_MS)),
|
|
739
|
+
]);
|
|
740
|
+
process.exit(0);
|
|
741
|
+
};
|
|
742
|
+
process.once("SIGTERM", quit);
|
|
743
|
+
process.once("SIGINT", quit);
|
|
744
|
+
process.once("disconnect", quit);
|
|
745
|
+
|
|
746
|
+
arm();
|
|
747
|
+
`;
|
|
748
|
+
}
|
|
749
|
+
const SERVER_NAME$2 = "conveno";
|
|
750
|
+
/**
|
|
751
|
+
* `sessionStart` adds context for the model; `userPromptSubmitted` marks the turn started (Copilot
|
|
752
|
+
* drops its output); `permissionRequest` allows Conveno's own MCP tools without a prompt;
|
|
753
|
+
* `postToolUse` adds waiting messages in the middle of a turn; `agentStop` ends a turn and
|
|
754
|
+
* continues with waiting messages.
|
|
755
|
+
*/
|
|
756
|
+
const HOOK_EVENTS$1 = [
|
|
757
|
+
"sessionStart",
|
|
758
|
+
"userPromptSubmitted",
|
|
759
|
+
"permissionRequest",
|
|
760
|
+
"postToolUse",
|
|
761
|
+
"agentStop"
|
|
762
|
+
];
|
|
763
|
+
/** Events an older Conveno wrote and this one removes: `preToolUse` failed closed for every tool. */
|
|
764
|
+
const LEGACY_EVENTS = ["preToolUse"];
|
|
765
|
+
/** The extension's listener: `conveno hook copilot Listen`. Not a Copilot hook event, so not in the hook file. */
|
|
766
|
+
const LISTEN_EVENT = "Listen";
|
|
767
|
+
/** First line of Listen's output: the ids of the handed-over messages. The extension strips it. */
|
|
768
|
+
const IDS_LEAD = "#conveno-ids";
|
|
769
|
+
/** The listener gives up on its own after this long; the extension starts a new one at the next idle. */
|
|
770
|
+
const LISTEN_MAX_MS = 216e5;
|
|
771
|
+
/** How long Listen looks for its session: the extension can start before the MCP server registers it. */
|
|
772
|
+
const LISTEN_REGISTER_WAIT_MS = 6e4;
|
|
773
|
+
const LISTEN_REGISTER_POLL_MS = 1e3;
|
|
774
|
+
/** Asked by `conveno init` before the extension and `experimental` are set up. Default no. */
|
|
775
|
+
const IDLE_WAKE_OPTION = "copilot-idle-wake";
|
|
776
|
+
const IDLE_WAKE_QUESTION = "Copilot idle wake needs Copilot's experimental mode, which also turns on its other experimental features. Turn it on?";
|
|
777
|
+
/** Our own hook file inside `~/.copilot/hooks/`, which Copilot reads as every `*.json` there. */
|
|
778
|
+
const HOOK_FILE = "conveno.json";
|
|
779
|
+
const EMPTY$2 = {
|
|
780
|
+
stdout: "",
|
|
781
|
+
exitCode: 0
|
|
782
|
+
};
|
|
783
|
+
/** `COPILOT_HOME` moves every Copilot CLI file; it defaults to `~/.copilot`. */
|
|
784
|
+
function paths$1(env) {
|
|
785
|
+
const dir = env.env.COPILOT_HOME || join(env.home, ".copilot");
|
|
786
|
+
const extDir = join(dir, "extensions", "conveno");
|
|
787
|
+
return {
|
|
788
|
+
mcp: join(dir, "mcp-config.json"),
|
|
789
|
+
hooks: join(dir, "hooks", HOOK_FILE),
|
|
790
|
+
settings: join(dir, "settings.json"),
|
|
791
|
+
extension: join(extDir, "extension.mjs"),
|
|
792
|
+
marker: join(extDir, EXPERIMENTAL_MARKER_FILE)
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* Written next to the extension when Conveno turned `experimental` on, so uninstall turns it off
|
|
797
|
+
* again only then. A user who had it on already keeps it.
|
|
798
|
+
*/
|
|
799
|
+
const EXPERIMENTAL_MARKER_FILE = "set-experimental";
|
|
800
|
+
const MARKER_TEXT = "Conveno turned on the experimental setting of Copilot CLI so the Conveno extension loads. `conveno uninstall` turns it off again and removes this file.\n";
|
|
801
|
+
const SAFE_WORD = /^[A-Za-z0-9_@%+=:,./-]+$/;
|
|
802
|
+
/**
|
|
803
|
+
* Quote one word for the hook's `bash` field: POSIX single quotes. Windows paths use forward
|
|
804
|
+
* slashes, which every shell and Windows API accepts.
|
|
805
|
+
*/
|
|
806
|
+
function bashWord(arg) {
|
|
807
|
+
const word = arg.replace(/\\/g, "/");
|
|
808
|
+
return SAFE_WORD.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
|
|
809
|
+
}
|
|
810
|
+
/** Quote one word for the hook's `powershell` field: single quotes, doubled inside. */
|
|
811
|
+
function powershellWord(arg) {
|
|
812
|
+
const word = arg.replace(/\\/g, "/");
|
|
813
|
+
return SAFE_WORD.test(word) ? word : `'${word.replace(/'/g, "''")}'`;
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* The hook entry. Copilot runs `bash` on macOS and Linux and `powershell` on Windows, and takes
|
|
817
|
+
* the command as one string, so both are written whatever the platform of this install: the file
|
|
818
|
+
* then stays right if the home directory is shared with a Windows machine through WSL.
|
|
819
|
+
* `permissionRequest` carries a matcher, so it runs only for Conveno's own tools.
|
|
820
|
+
*/
|
|
821
|
+
function hookEntry$1(env, event) {
|
|
822
|
+
const words = [
|
|
823
|
+
...env.conveno.command,
|
|
824
|
+
"hook",
|
|
825
|
+
"copilot",
|
|
826
|
+
event
|
|
827
|
+
];
|
|
828
|
+
const ps = words.map(powershellWord);
|
|
829
|
+
const call = /^'/.test(ps[0] ?? "") ? "& " : "";
|
|
830
|
+
return {
|
|
831
|
+
type: "command",
|
|
832
|
+
bash: words.map(bashWord).join(" "),
|
|
833
|
+
powershell: call + ps.join(" "),
|
|
834
|
+
...event === "permissionRequest" ? { matcher: OWN_TOOL_MATCHER } : {},
|
|
835
|
+
timeoutSec: 5
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
const mcpArgs$1 = (env) => [
|
|
839
|
+
...env.conveno.command,
|
|
840
|
+
"mcp",
|
|
841
|
+
"--cli",
|
|
842
|
+
"copilot"
|
|
843
|
+
];
|
|
844
|
+
/** The same shape `copilot mcp add` writes. */
|
|
845
|
+
const desiredServer$1 = (env) => {
|
|
846
|
+
const [command = "conveno", ...args] = mcpArgs$1(env);
|
|
847
|
+
return {
|
|
848
|
+
tools: ["*"],
|
|
849
|
+
type: "local",
|
|
850
|
+
command,
|
|
851
|
+
args
|
|
852
|
+
};
|
|
853
|
+
};
|
|
854
|
+
/** Recognizes our hook command even if the conveno path changed since install. */
|
|
855
|
+
const isOurCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook copilot (sessionStart|userPromptSubmitted|permissionRequest|preToolUse|postToolUse|agentStop)$/.test(cmd.trim());
|
|
856
|
+
const isOurEntry$1 = (e) => isObject$1(e) && [
|
|
857
|
+
e.bash,
|
|
858
|
+
e.powershell,
|
|
859
|
+
e.command
|
|
860
|
+
].some(isOurCommand);
|
|
861
|
+
function entriesOf$1(hooks, event) {
|
|
862
|
+
const g = hooks[event];
|
|
863
|
+
return Array.isArray(g) ? g : [];
|
|
864
|
+
}
|
|
865
|
+
function hasExactHook$1(hooks, event, want) {
|
|
866
|
+
return entriesOf$1(hooks, event).some((e) => isObject$1(e) && e.bash === want.bash && e.powershell === want.powershell && e.matcher === want.matcher);
|
|
867
|
+
}
|
|
868
|
+
function hooksObject$1(file, path) {
|
|
869
|
+
const h = file.hooks;
|
|
870
|
+
if (h === void 0) return {};
|
|
871
|
+
if (!isObject$1(h)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
|
|
872
|
+
return h;
|
|
873
|
+
}
|
|
874
|
+
function mcpObject$1(config, path) {
|
|
875
|
+
const s = config.mcpServers;
|
|
876
|
+
if (s === void 0) return {};
|
|
877
|
+
if (!isObject$1(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
|
|
878
|
+
return s;
|
|
879
|
+
}
|
|
880
|
+
/** `copilot --version` prints "GitHub Copilot CLI 1.0.117." with a full stop after the number. */
|
|
881
|
+
const versionOf = (stdout) => parseCliVersion(stdout)?.replace(/\.+$/, "");
|
|
882
|
+
async function detect$2(env) {
|
|
883
|
+
const p = paths$1(env);
|
|
884
|
+
const configPaths = [
|
|
885
|
+
p.mcp,
|
|
886
|
+
p.hooks,
|
|
887
|
+
p.settings,
|
|
888
|
+
p.extension
|
|
889
|
+
];
|
|
890
|
+
try {
|
|
891
|
+
const r = await env.exec("copilot", ["--version"]);
|
|
892
|
+
if (r.code !== 0) return {
|
|
893
|
+
installed: false,
|
|
894
|
+
configPaths
|
|
895
|
+
};
|
|
896
|
+
const version = versionOf(r.stdout);
|
|
897
|
+
return {
|
|
898
|
+
installed: true,
|
|
899
|
+
binary: "copilot",
|
|
900
|
+
...version ? { version } : {},
|
|
901
|
+
configPaths
|
|
902
|
+
};
|
|
903
|
+
} catch {
|
|
904
|
+
return {
|
|
905
|
+
installed: false,
|
|
906
|
+
configPaths
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
async function readText$1(path) {
|
|
911
|
+
try {
|
|
912
|
+
return await readFile(path, "utf8");
|
|
913
|
+
} catch (err) {
|
|
914
|
+
if (err.code === "ENOENT") return null;
|
|
915
|
+
throw err;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
/** The extension file, and `experimental` with the marker that says Conveno set it. */
|
|
919
|
+
async function planExtension(env) {
|
|
920
|
+
const p = paths$1(env);
|
|
921
|
+
const changes = [];
|
|
922
|
+
const want = extensionSource(env.conveno.command);
|
|
923
|
+
const before = await readText$1(p.extension);
|
|
924
|
+
if (before !== want) {
|
|
925
|
+
if (before !== null && !before.startsWith("// conveno-extension:")) throw new Error(`${p.extension} exists and was not written by Conveno. Move or rename it, then run conveno again. The file was not changed.`);
|
|
926
|
+
changes.push({
|
|
927
|
+
component: "hooks",
|
|
928
|
+
kind: before === null ? "add" : "update",
|
|
929
|
+
parts: [{
|
|
930
|
+
name: "extension file",
|
|
931
|
+
kind: before === null ? "add" : "update"
|
|
932
|
+
}],
|
|
933
|
+
path: p.extension,
|
|
934
|
+
before,
|
|
935
|
+
after: want,
|
|
936
|
+
pruneEmptyDir: true,
|
|
937
|
+
description: `${before === null ? "Add" : "Update"} the Conveno extension for Copilot CLI. It wakes an idle session when a message arrives.`
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
const settings = await loadJson$1(p.settings);
|
|
941
|
+
if (settings.value.experimental !== true) {
|
|
942
|
+
changes.push({
|
|
943
|
+
component: "hooks",
|
|
944
|
+
kind: "update",
|
|
945
|
+
parts: [{
|
|
946
|
+
name: "experimental setting",
|
|
947
|
+
kind: "update"
|
|
948
|
+
}],
|
|
949
|
+
path: p.settings,
|
|
950
|
+
before: settings.raw,
|
|
951
|
+
after: editJson$1(settings, [{
|
|
952
|
+
path: ["experimental"],
|
|
953
|
+
value: true
|
|
954
|
+
}]),
|
|
955
|
+
description: "Turn on Copilot CLI's experimental mode (\"experimental\": true). Copilot loads extensions only in that mode. It also enables Copilot's other experimental features. `conveno uninstall` turns it off again."
|
|
956
|
+
});
|
|
957
|
+
if (await readText$1(p.marker) === null) changes.push({
|
|
958
|
+
component: "hooks",
|
|
959
|
+
kind: "add",
|
|
960
|
+
parts: [{
|
|
961
|
+
name: "experimental marker",
|
|
962
|
+
kind: "add"
|
|
963
|
+
}],
|
|
964
|
+
path: p.marker,
|
|
965
|
+
before: null,
|
|
966
|
+
after: MARKER_TEXT,
|
|
967
|
+
pruneEmptyDir: true,
|
|
968
|
+
description: "Note that Conveno turned on experimental mode, so uninstall turns it off again."
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
return changes;
|
|
972
|
+
}
|
|
973
|
+
async function uninstallExtension(env, baseline) {
|
|
974
|
+
const p = paths$1(env);
|
|
975
|
+
const changes = [];
|
|
976
|
+
const ext = await readText$1(p.extension);
|
|
977
|
+
if (ext?.startsWith("// conveno-extension:")) changes.push({
|
|
978
|
+
component: "hooks",
|
|
979
|
+
kind: "remove",
|
|
980
|
+
path: p.extension,
|
|
981
|
+
before: ext,
|
|
982
|
+
after: "",
|
|
983
|
+
deleteFile: true,
|
|
984
|
+
pruneEmptyDir: true,
|
|
985
|
+
description: "Remove the Conveno extension for Copilot CLI."
|
|
986
|
+
});
|
|
987
|
+
const marker = await readText$1(p.marker);
|
|
988
|
+
if (marker !== null) {
|
|
989
|
+
const settings = await loadJson$1(p.settings);
|
|
990
|
+
const userHadIt = existedBefore(baseline?.get(p.settings), ["experimental"]);
|
|
991
|
+
if (settings.value.experimental === true && !userHadIt) {
|
|
992
|
+
const rest = { ...settings.value };
|
|
993
|
+
delete rest.experimental;
|
|
994
|
+
const wasAbsent = baseline?.get(p.settings) === null;
|
|
995
|
+
const emptied = Object.keys(rest).length === 0 && wasAbsent;
|
|
996
|
+
changes.push({
|
|
997
|
+
component: "hooks",
|
|
998
|
+
kind: "remove",
|
|
999
|
+
path: p.settings,
|
|
1000
|
+
before: settings.raw,
|
|
1001
|
+
after: emptied ? "" : editJson$1(settings, [{
|
|
1002
|
+
path: ["experimental"],
|
|
1003
|
+
value: void 0
|
|
1004
|
+
}]),
|
|
1005
|
+
...emptied ? { deleteFile: true } : {},
|
|
1006
|
+
description: "Turn off Copilot CLI's experimental mode, which Conveno turned on (\"experimental\": false by removing the key)."
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
1009
|
+
changes.push({
|
|
1010
|
+
component: "hooks",
|
|
1011
|
+
kind: "remove",
|
|
1012
|
+
path: p.marker,
|
|
1013
|
+
before: marker,
|
|
1014
|
+
after: "",
|
|
1015
|
+
deleteFile: true,
|
|
1016
|
+
pruneEmptyDir: true,
|
|
1017
|
+
description: "Remove the note that Conveno turned on experimental mode."
|
|
1018
|
+
});
|
|
1019
|
+
}
|
|
1020
|
+
return changes;
|
|
1021
|
+
}
|
|
1022
|
+
/**
|
|
1023
|
+
* Is the idle-wake extension set up? Then `plan` keeps it up to date and `conveno init` does not
|
|
1024
|
+
* ask again.
|
|
1025
|
+
*/
|
|
1026
|
+
async function idleWakeEnabled(env) {
|
|
1027
|
+
return (await readText$1(paths$1(env).extension))?.startsWith(EXTENSION_MARKER_PREFIX) === true;
|
|
1028
|
+
}
|
|
1029
|
+
/**
|
|
1030
|
+
* `accept` lists the optional parts the user said yes to (`IDLE_WAKE_OPTION`). Without it the
|
|
1031
|
+
* extension and `experimental` are left out, unless the extension is already there.
|
|
1032
|
+
*/
|
|
1033
|
+
async function plan$2(env, opts = {}) {
|
|
1034
|
+
const p = paths$1(env);
|
|
1035
|
+
const changes = [];
|
|
1036
|
+
const mcpFile = await loadJson$1(p.mcp);
|
|
1037
|
+
const servers = mcpObject$1(mcpFile.value, p.mcp);
|
|
1038
|
+
const want = desiredServer$1(env);
|
|
1039
|
+
if (!sameJson$1(servers["conveno"], want)) changes.push({
|
|
1040
|
+
component: "mcp",
|
|
1041
|
+
kind: servers["conveno"] === void 0 ? "add" : "update",
|
|
1042
|
+
parts: [{
|
|
1043
|
+
name: "MCP server",
|
|
1044
|
+
kind: servers["conveno"] === void 0 ? "add" : "update"
|
|
1045
|
+
}],
|
|
1046
|
+
path: p.mcp,
|
|
1047
|
+
before: mcpFile.raw,
|
|
1048
|
+
after: editJson$1(mcpFile, [{
|
|
1049
|
+
path: ["mcpServers", SERVER_NAME$2],
|
|
1050
|
+
value: want
|
|
1051
|
+
}]),
|
|
1052
|
+
description: `Register the "${SERVER_NAME$2}" MCP server for Copilot CLI (conveno mcp --cli copilot).`,
|
|
1053
|
+
viaCommand: [
|
|
1054
|
+
"copilot",
|
|
1055
|
+
"mcp",
|
|
1056
|
+
"add",
|
|
1057
|
+
SERVER_NAME$2,
|
|
1058
|
+
"--",
|
|
1059
|
+
...mcpArgs$1(env)
|
|
1060
|
+
]
|
|
1061
|
+
});
|
|
1062
|
+
const hookFile = await loadJson$1(p.hooks);
|
|
1063
|
+
const hooks = hooksObject$1(hookFile.value, p.hooks);
|
|
1064
|
+
const missing = HOOK_EVENTS$1.filter((e) => !hasExactHook$1(hooks, e, hookEntry$1(env, e)));
|
|
1065
|
+
const legacy = LEGACY_EVENTS.filter((e) => entriesOf$1(hooks, e).some(isOurEntry$1));
|
|
1066
|
+
if (missing.length > 0 || legacy.length > 0) {
|
|
1067
|
+
const edits = [];
|
|
1068
|
+
if (hookFile.value.version === void 0) edits.push({
|
|
1069
|
+
path: ["version"],
|
|
1070
|
+
value: 1
|
|
1071
|
+
});
|
|
1072
|
+
for (const e of missing) edits.push(...putInList(hooks[e], ["hooks", e], hookEntry$1(env, e), isOurEntry$1));
|
|
1073
|
+
for (const e of legacy) edits.push(...dropFromList(hooks[e], ["hooks", e], isOurEntry$1));
|
|
1074
|
+
const installed = [...HOOK_EVENTS$1, ...LEGACY_EVENTS].some((e) => entriesOf$1(hooks, e).some(isOurEntry$1));
|
|
1075
|
+
changes.push({
|
|
1076
|
+
component: "hooks",
|
|
1077
|
+
kind: installed ? "update" : "add",
|
|
1078
|
+
parts: [...missing, ...legacy].map((e) => ({
|
|
1079
|
+
name: `${e} hook`,
|
|
1080
|
+
kind: installed ? "update" : "add"
|
|
1081
|
+
})),
|
|
1082
|
+
path: p.hooks,
|
|
1083
|
+
before: hookFile.raw,
|
|
1084
|
+
after: editJson$1(hookFile, edits),
|
|
1085
|
+
description: missing.length > 0 ? `Add ${missing.join(", ")} hooks that deliver Conveno messages to Copilot CLI on the next turn and at the end of a turn.` : `Remove the old ${legacy.join(", ")} hook, which blocked every tool when conveno could not run.`
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
const extension = opts.accept?.includes("copilot-idle-wake") === true || await idleWakeEnabled(env);
|
|
1089
|
+
return [...changes, ...extension ? await planExtension(env) : []];
|
|
1090
|
+
}
|
|
1091
|
+
async function uninstallPlan$2(env, baseline) {
|
|
1092
|
+
const p = paths$1(env);
|
|
1093
|
+
const changes = [];
|
|
1094
|
+
const mcpFile = await loadJson$1(p.mcp);
|
|
1095
|
+
if ("conveno" in mcpObject$1(mcpFile.value, p.mcp)) changes.push({
|
|
1096
|
+
component: "mcp",
|
|
1097
|
+
kind: "remove",
|
|
1098
|
+
path: p.mcp,
|
|
1099
|
+
before: mcpFile.raw,
|
|
1100
|
+
after: editJson$1(mcpFile, [{
|
|
1101
|
+
path: ["mcpServers", SERVER_NAME$2],
|
|
1102
|
+
value: void 0
|
|
1103
|
+
}]),
|
|
1104
|
+
description: `Remove the "${SERVER_NAME$2}" MCP server.`,
|
|
1105
|
+
viaCommand: [
|
|
1106
|
+
"copilot",
|
|
1107
|
+
"mcp",
|
|
1108
|
+
"remove",
|
|
1109
|
+
SERVER_NAME$2
|
|
1110
|
+
]
|
|
1111
|
+
});
|
|
1112
|
+
const hookFile = await loadJson$1(p.hooks);
|
|
1113
|
+
const hooks = hooksObject$1(hookFile.value, p.hooks);
|
|
1114
|
+
const next = { ...hooks };
|
|
1115
|
+
const edits = [];
|
|
1116
|
+
for (const e of [...HOOK_EVENTS$1, ...LEGACY_EVENTS]) {
|
|
1117
|
+
const drops = dropFromList(hooks[e], ["hooks", e], isOurEntry$1, { keepEmpty: existedBefore(baseline?.get(p.hooks), ["hooks", e]) });
|
|
1118
|
+
if (drops.length === 0) continue;
|
|
1119
|
+
if (drops.length === 1 && drops[0]?.path.length === 2) delete next[e];
|
|
1120
|
+
edits.push(...drops);
|
|
1121
|
+
}
|
|
1122
|
+
if (edits.length > 0) {
|
|
1123
|
+
if (Object.keys(next).length === 0 && !existedBefore(baseline?.get(p.hooks), ["hooks"])) edits.push({
|
|
1124
|
+
path: ["hooks"],
|
|
1125
|
+
value: void 0
|
|
1126
|
+
});
|
|
1127
|
+
changes.push({
|
|
1128
|
+
component: "hooks",
|
|
1129
|
+
kind: "remove",
|
|
1130
|
+
path: p.hooks,
|
|
1131
|
+
before: hookFile.raw,
|
|
1132
|
+
after: editJson$1(hookFile, edits),
|
|
1133
|
+
description: "Remove the Conveno sessionStart, userPromptSubmitted, permissionRequest, postToolUse and agentStop hooks."
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
return [...changes, ...await uninstallExtension(env, baseline)];
|
|
1137
|
+
}
|
|
1138
|
+
const isHookEvent$1 = (e) => HOOK_EVENTS$1.includes(e);
|
|
1139
|
+
/**
|
|
1140
|
+
* The `permissionRequest` matcher: Conveno's own MCP tools. Copilot names an MCP tool there
|
|
1141
|
+
* `<server>/<tool>` and anchors the matcher as `^(?:...)$`, so another server whose name starts
|
|
1142
|
+
* with "conveno" never matches (docs hooks-reference "permissionRequest decision control";
|
|
1143
|
+
* the 1.0.63 bundle builds the name as `${t.serverName}/${toolName}` for `kind: "mcp"`).
|
|
1144
|
+
*/
|
|
1145
|
+
const OWN_TOOL_MATCHER = `${SERVER_NAME$2}/(${[
|
|
1146
|
+
"whoami",
|
|
1147
|
+
"list_sessions",
|
|
1148
|
+
"send",
|
|
1149
|
+
"inbox",
|
|
1150
|
+
"ack",
|
|
1151
|
+
"rename",
|
|
1152
|
+
"set_status",
|
|
1153
|
+
"become_lead",
|
|
1154
|
+
"orchestrate",
|
|
1155
|
+
"handoff",
|
|
1156
|
+
"spawn_session"
|
|
1157
|
+
].join("|")})`;
|
|
1158
|
+
const OWN_TOOL_RE = new RegExp(`^(?:${OWN_TOOL_MATCHER})$`);
|
|
1159
|
+
const isOwnTool = (name) => typeof name === "string" && OWN_TOOL_RE.test(name);
|
|
1160
|
+
/**
|
|
1161
|
+
* If Copilot sets `COPILOT_HOOK_DEPTH` on a run started from inside another hook or extension, that
|
|
1162
|
+
* run's hooks deliver nothing: those messages belong to the outer session. Depth 1 is the session
|
|
1163
|
+
* itself. Not found in the Copilot 1.0.63 bundle, so this guard may never fire.
|
|
1164
|
+
*/
|
|
1165
|
+
const nested = () => Number(process.env.COPILOT_HOOK_DEPTH ?? 0) > 1;
|
|
1166
|
+
const field = (input, ...keys) => isObject$1(input) ? keys.map((k) => input[k]).find((v) => v !== void 0) : void 0;
|
|
1167
|
+
/** Copilot's own id for the session: `sessionId` in every hook input and in the extension's. */
|
|
1168
|
+
const copilotSessionId = (input) => {
|
|
1169
|
+
const id = field(input, "sessionId", "session_id");
|
|
1170
|
+
return typeof id === "string" && id !== "" ? id : void 0;
|
|
1171
|
+
};
|
|
1172
|
+
/**
|
|
1173
|
+
* A hook runs under the Copilot process that hosts the session, so its pid finds the session. Record
|
|
1174
|
+
* Copilot's session id on it, so the extension's Listen and Requeue, which run under the extension's
|
|
1175
|
+
* own process, find it by that id. Best effort.
|
|
1176
|
+
*/
|
|
1177
|
+
async function recordSessionId(ctx, id) {
|
|
1178
|
+
if (id === void 0) return;
|
|
1179
|
+
try {
|
|
1180
|
+
const session = await ownSession(ctx);
|
|
1181
|
+
if (session && session.nativeId !== id) await ctx.client["session.setNative"]({
|
|
1182
|
+
sessionId: session.id,
|
|
1183
|
+
nativeId: id
|
|
1184
|
+
});
|
|
1185
|
+
} catch {}
|
|
1186
|
+
}
|
|
1187
|
+
/**
|
|
1188
|
+
* Listen's session: the one that holds Copilot's session id. Until a hook has recorded that id, the
|
|
1189
|
+
* session is found by `copilotPid`, the CLI the extension was forked from, and the id is recorded
|
|
1190
|
+
* then. Looks again until the MCP server has registered the session or `LISTEN_REGISTER_WAIT_MS`
|
|
1191
|
+
* passes. False when there is none.
|
|
1192
|
+
*/
|
|
1193
|
+
async function claimSession(ctx, id, copilotPid) {
|
|
1194
|
+
const until = Date.now() + LISTEN_REGISTER_WAIT_MS;
|
|
1195
|
+
for (;;) {
|
|
1196
|
+
try {
|
|
1197
|
+
if (await ownSession({
|
|
1198
|
+
...ctx,
|
|
1199
|
+
nativeId: id
|
|
1200
|
+
})) return true;
|
|
1201
|
+
if (typeof copilotPid === "number" && Number.isInteger(copilotPid) && copilotPid > 0) {
|
|
1202
|
+
const { nativeId: _, ...byPid } = ctx;
|
|
1203
|
+
const session = await ownSession({
|
|
1204
|
+
...byPid,
|
|
1205
|
+
hostPid: copilotPid
|
|
1206
|
+
});
|
|
1207
|
+
if (session) {
|
|
1208
|
+
await ctx.client["session.setNative"]({
|
|
1209
|
+
sessionId: session.id,
|
|
1210
|
+
nativeId: id
|
|
1211
|
+
});
|
|
1212
|
+
return true;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
} catch {
|
|
1216
|
+
return false;
|
|
1217
|
+
}
|
|
1218
|
+
if (Date.now() + LISTEN_REGISTER_POLL_MS > until) return false;
|
|
1219
|
+
if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) return false;
|
|
1220
|
+
await new Promise((r) => setTimeout(r, LISTEN_REGISTER_POLL_MS));
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* - sessionStart: waiting messages as `{ "additionalContext": "<text>" }`, added as a first message
|
|
1225
|
+
* of the session.
|
|
1226
|
+
* - userPromptSubmitted: marks the turn started. Nothing is delivered: Copilot drops the output of
|
|
1227
|
+
* command `userPromptSubmitted` hooks (docs hooks-reference, `userPromptSubmitted` note), so a
|
|
1228
|
+
* message taken there would be lost.
|
|
1229
|
+
* - permissionRequest: `{ "behavior": "allow" }` for Conveno's own MCP tools, so a session never
|
|
1230
|
+
* waits on a prompt to read or send a message. Its matcher keeps it to those tools, and a failing
|
|
1231
|
+
* `permissionRequest` hook falls through to the normal prompt (only exit 2 denies).
|
|
1232
|
+
* - postToolUse: waiting messages as `additionalContext`, which Copilot appends to the tool result
|
|
1233
|
+
* so the model sees them on the same turn (10 KB cap).
|
|
1234
|
+
* - agentStop: records the turn end. With messages waiting, `decision: "block"` with
|
|
1235
|
+
* the framed messages as `reason`, which Copilot runs as another turn. Like Codex, Copilot has no
|
|
1236
|
+
* idle wake, so this also happens when `stop_hook_active` is set; Copilot ends the chain after 8
|
|
1237
|
+
* blocks in a row, and Conveno's auto-mode limit bounds it before that.
|
|
1238
|
+
* - Listen: the extension's idle-wake listener. Waits for work and prints `#conveno-ids <id>,<id>`
|
|
1239
|
+
* and then the framed messages (plain text, exit 0); the extension strips the first line and sends
|
|
1240
|
+
* the rest with `session.send`. Nothing when it stops for any other reason.
|
|
1241
|
+
* - Requeue: the extension's `session.send` failed; puts the messages (`ids` in the input) back to queued.
|
|
1242
|
+
* The hooks record Copilot's `sessionId` on the session; Listen and Requeue run under the
|
|
1243
|
+
* extension's process, not Copilot's, so they find the session by that id.
|
|
1244
|
+
* Never throws and never writes to stderr: any failure means "deliver nothing this time".
|
|
1245
|
+
*/
|
|
1246
|
+
/**
|
|
1247
|
+
* Copilot caps a hook's `additionalContext` at 10 KB (docs hooks-reference, `postToolUse`). The
|
|
1248
|
+
* budget counts characters, so 4,500 keeps text of up to two UTF-8 bytes a character under it.
|
|
1249
|
+
* Messages past it stay queued for the next tool call or turn end.
|
|
1250
|
+
*/
|
|
1251
|
+
const CONTEXT_MAX_CHARS = 4500;
|
|
1252
|
+
async function hook$2(event, input, ctx) {
|
|
1253
|
+
if (nested()) return EMPTY$2;
|
|
1254
|
+
const id = copilotSessionId(input);
|
|
1255
|
+
if (event === "Listen") {
|
|
1256
|
+
if (id === void 0) return EMPTY$2;
|
|
1257
|
+
if (!await claimSession(ctx, id, field(input, "copilotPid"))) return EMPTY$2;
|
|
1258
|
+
const r = await waitForWorkBatch({
|
|
1259
|
+
...ctx,
|
|
1260
|
+
nativeId: id
|
|
1261
|
+
}, { maxMs: LISTEN_MAX_MS });
|
|
1262
|
+
if (r === null) return EMPTY$2;
|
|
1263
|
+
const ids = r.batch.messages.map((m) => m.id);
|
|
1264
|
+
return {
|
|
1265
|
+
stdout: (ids.length > 0 ? `${IDS_LEAD} ${ids.join(",")}\n` : "") + r.batch.text,
|
|
1266
|
+
exitCode: 0
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
if (event === "Requeue") {
|
|
1270
|
+
if (id !== void 0) await requeue$1({
|
|
1271
|
+
...ctx,
|
|
1272
|
+
nativeId: id
|
|
1273
|
+
}, input);
|
|
1274
|
+
return EMPTY$2;
|
|
1275
|
+
}
|
|
1276
|
+
if (!isHookEvent$1(event)) return EMPTY$2;
|
|
1277
|
+
if (event === "permissionRequest") {
|
|
1278
|
+
if (!isOwnTool(field(input, "toolName", "tool_name"))) return EMPTY$2;
|
|
1279
|
+
return {
|
|
1280
|
+
stdout: JSON.stringify({ behavior: "allow" }),
|
|
1281
|
+
exitCode: 0
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
await recordSessionId(ctx, id);
|
|
1285
|
+
if (event === "userPromptSubmitted") {
|
|
1286
|
+
await startTurn(ctx);
|
|
1287
|
+
return EMPTY$2;
|
|
1288
|
+
}
|
|
1289
|
+
if (event === "agentStop") {
|
|
1290
|
+
const reason = await endTurnContinuation(ctx);
|
|
1291
|
+
if (reason === null) return EMPTY$2;
|
|
1292
|
+
return {
|
|
1293
|
+
stdout: JSON.stringify({
|
|
1294
|
+
decision: "block",
|
|
1295
|
+
reason
|
|
1296
|
+
}),
|
|
1297
|
+
exitCode: 0
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
const additionalContext = await pendingHookContext(ctx, { maxChars: CONTEXT_MAX_CHARS });
|
|
1301
|
+
if (additionalContext === null) return EMPTY$2;
|
|
1302
|
+
return {
|
|
1303
|
+
stdout: JSON.stringify({ additionalContext }),
|
|
1304
|
+
exitCode: 0
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
/** A typed prompt starts a turn: the session is busy, and what it sends starts a new chain. */
|
|
1308
|
+
async function startTurn(ctx) {
|
|
1309
|
+
try {
|
|
1310
|
+
const session = await ownSession(ctx);
|
|
1311
|
+
if (session) await ctx.client["turn.start"]({ sessionId: session.id });
|
|
1312
|
+
} catch {}
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* `Requeue`: sending failed, so the messages go back to queued for the next turn. Copilot may be
|
|
1316
|
+
* exiting and have unregistered the session already, so a session that just went offline counts.
|
|
1317
|
+
*/
|
|
1318
|
+
async function requeue$1(ctx, input) {
|
|
1319
|
+
const ids = field(input, "ids");
|
|
1320
|
+
if (!Array.isArray(ids) || !ids.every((i) => typeof i === "string")) return;
|
|
1321
|
+
await requeueOwnMessages(ctx, ids);
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Things `conveno doctor` should tell the user about the idle-wake extension: Copilot asks once
|
|
1325
|
+
* before it starts an extension (docs cli-command-reference, extensions: "Each extension requires
|
|
1326
|
+
* approval before it launches"), and with `extensions.enabled` false in settings.json (docs
|
|
1327
|
+
* cli-config-dir-reference, `extensions/`) it never starts. Empty without the extension.
|
|
1328
|
+
*/
|
|
1329
|
+
async function doctorNotes(env) {
|
|
1330
|
+
if (!await idleWakeEnabled(env)) return [];
|
|
1331
|
+
const notes = ["Copilot asks once to approve the Conveno extension. Approve it, or idle sessions do not wake."];
|
|
1332
|
+
try {
|
|
1333
|
+
const ext = (await loadJson$1(paths$1(env).settings)).value.extensions;
|
|
1334
|
+
if (isObject$1(ext) && ext.enabled === false) notes.push("Copilot extensions are off (\"extensions\": { \"enabled\": false } in settings.json), so idle sessions do not wake. Turn them on with /extensions in Copilot.");
|
|
1335
|
+
} catch {}
|
|
1336
|
+
return notes;
|
|
1337
|
+
}
|
|
1338
|
+
const copilotAdapter = {
|
|
1339
|
+
cli: "copilot",
|
|
1340
|
+
displayName: "GitHub Copilot CLI",
|
|
1341
|
+
deliveryTier: "next_turn",
|
|
1342
|
+
delivery: () => ({
|
|
1343
|
+
nextTurn: true,
|
|
1344
|
+
endOfTurn: true,
|
|
1345
|
+
idleWake: true
|
|
1346
|
+
}),
|
|
1347
|
+
detect: detect$2,
|
|
1348
|
+
plan: plan$2,
|
|
1349
|
+
uninstallPlan: uninstallPlan$2,
|
|
1350
|
+
hook: hook$2,
|
|
1351
|
+
listenEvents: [LISTEN_EVENT],
|
|
1352
|
+
optional: [{
|
|
1353
|
+
id: IDLE_WAKE_OPTION,
|
|
1354
|
+
question: IDLE_WAKE_QUESTION,
|
|
1355
|
+
enabled: idleWakeEnabled
|
|
1356
|
+
}],
|
|
1357
|
+
doctorNotes
|
|
1358
|
+
};
|
|
1359
|
+
// ../adapters/cursor/dist/index.js
|
|
1360
|
+
const SERVER_NAME$1 = "conveno";
|
|
1361
|
+
/**
|
|
1362
|
+
* Hooks that can add context to the conversation: `sessionStart` for a new chat and `postToolUse`
|
|
1363
|
+
* after each tool call. `beforeSubmitPrompt` is not here because it can only allow or block a
|
|
1364
|
+
* prompt, never add to it. `stop` ends a turn and, continues with waiting messages.
|
|
1365
|
+
*/
|
|
1366
|
+
const HOOK_EVENTS = [
|
|
1367
|
+
"sessionStart",
|
|
1368
|
+
"postToolUse",
|
|
1369
|
+
"stop"
|
|
1370
|
+
];
|
|
1371
|
+
/** The `permissions.allow` token that lets the agent call every tool of the conveno server. */
|
|
1372
|
+
const MCP_PERMISSION = `Mcp(${SERVER_NAME$1}:*)`;
|
|
1373
|
+
const EMPTY$1 = {
|
|
1374
|
+
stdout: "",
|
|
1375
|
+
exitCode: 0
|
|
1376
|
+
};
|
|
1377
|
+
/**
|
|
1378
|
+
* `mcp.json` and `hooks.json` are always read from `~/.cursor`. The CLI's own settings file moves
|
|
1379
|
+
* with `CURSOR_CONFIG_DIR`, or with `XDG_CONFIG_HOME` on Linux and BSD, and `CURSOR_CONFIG_DIR` wins.
|
|
1380
|
+
*/
|
|
1381
|
+
function paths(env) {
|
|
1382
|
+
const dir = join(env.home, ".cursor");
|
|
1383
|
+
const custom = env.env.CURSOR_CONFIG_DIR;
|
|
1384
|
+
const xdg = env.env.XDG_CONFIG_HOME;
|
|
1385
|
+
const xdgApplies = env.platform !== "win32" && env.platform !== "darwin";
|
|
1386
|
+
const cliConfig = custom ? join(custom, "cli-config.json") : xdg && xdgApplies ? join(xdg, "cursor", "cli-config.json") : join(dir, "cli-config.json");
|
|
1387
|
+
return {
|
|
1388
|
+
mcp: join(dir, "mcp.json"),
|
|
1389
|
+
hooks: join(dir, "hooks.json"),
|
|
1390
|
+
cliConfig
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Quote one word of a hook command. Cursor runs every hook command through a POSIX shell, on
|
|
1395
|
+
* Windows too (Git Bash): the bundle's `hookCommandsArePowerShell()` is `false` and the payload is
|
|
1396
|
+
* appended as `<command> <<'CURSOR_HOOK_EOF' ...` (cursor-agent 2026.11.22 4721.index.js,
|
|
1397
|
+
* `executeCommandScript`). So words get POSIX single quotes everywhere. On Windows, `\` becomes
|
|
1398
|
+
* `/` first: bash would read a backslash as an escape, and Windows accepts `/` in paths.
|
|
1399
|
+
*/
|
|
1400
|
+
function quoteWord(arg, platform) {
|
|
1401
|
+
const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
|
|
1402
|
+
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
|
|
1403
|
+
}
|
|
1404
|
+
function hookCommand(env, event) {
|
|
1405
|
+
return [
|
|
1406
|
+
...env.conveno.command,
|
|
1407
|
+
"hook",
|
|
1408
|
+
"cursor",
|
|
1409
|
+
event
|
|
1410
|
+
].map((w) => quoteWord(w, env.platform)).join(" ");
|
|
1411
|
+
}
|
|
1412
|
+
/**
|
|
1413
|
+
* `stop` sets `loop_limit: null`: Cursor's own cap (5 follow-ups by default) would end the loop
|
|
1414
|
+
* for the conversation, and Conveno's own auto-mode limit already bounds it.
|
|
1415
|
+
*/
|
|
1416
|
+
const hookEntry = (env, event) => ({
|
|
1417
|
+
command: hookCommand(env, event),
|
|
1418
|
+
timeout: 5,
|
|
1419
|
+
...event === "stop" ? { loop_limit: null } : {}
|
|
1420
|
+
});
|
|
1421
|
+
const mcpArgs = (env) => [
|
|
1422
|
+
...env.conveno.command,
|
|
1423
|
+
"mcp",
|
|
1424
|
+
"--cli",
|
|
1425
|
+
"cursor"
|
|
1426
|
+
];
|
|
1427
|
+
const desiredServer = (env) => {
|
|
1428
|
+
const [command = "conveno", ...args] = mcpArgs(env);
|
|
1429
|
+
return {
|
|
1430
|
+
type: "stdio",
|
|
1431
|
+
command,
|
|
1432
|
+
args
|
|
1433
|
+
};
|
|
1434
|
+
};
|
|
1435
|
+
/** Recognizes our hook command even if the conveno path changed since install. */
|
|
1436
|
+
const isOurHookCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook cursor (sessionStart|postToolUse|stop)$/.test(cmd.trim());
|
|
1437
|
+
const isOurEntry = (e) => isObject$1(e) && isOurHookCommand(e.command);
|
|
1438
|
+
function entriesOf(hooks, event) {
|
|
1439
|
+
const g = hooks[event];
|
|
1440
|
+
return Array.isArray(g) ? g : [];
|
|
1441
|
+
}
|
|
1442
|
+
const hasExactHook = (hooks, event, want) => entriesOf(hooks, event).some((e) => sameJson$1(e, want));
|
|
1443
|
+
function hooksObject(file, path) {
|
|
1444
|
+
const h = file.hooks;
|
|
1445
|
+
if (h === void 0) return {};
|
|
1446
|
+
if (!isObject$1(h)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
|
|
1447
|
+
return h;
|
|
1448
|
+
}
|
|
1449
|
+
function mcpObject(config, path) {
|
|
1450
|
+
const s = config.mcpServers;
|
|
1451
|
+
if (s === void 0) return {};
|
|
1452
|
+
if (!isObject$1(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
|
|
1453
|
+
return s;
|
|
1454
|
+
}
|
|
1455
|
+
/** The `permissions.allow` list of cli-config.json, or undefined when it is not there. */
|
|
1456
|
+
function allowList(config, path) {
|
|
1457
|
+
const p = config.permissions;
|
|
1458
|
+
if (p === void 0) return void 0;
|
|
1459
|
+
if (!isObject$1(p)) throw new Error(`"permissions" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
|
|
1460
|
+
const a = p.allow;
|
|
1461
|
+
if (a === void 0) return void 0;
|
|
1462
|
+
if (!Array.isArray(a)) throw new Error(`"permissions.allow" in ${path} must be an array. Fix the file, then run the install again. Nothing was changed.`);
|
|
1463
|
+
return a;
|
|
1464
|
+
}
|
|
1465
|
+
async function detect$1(env) {
|
|
1466
|
+
const p = paths(env);
|
|
1467
|
+
const configPaths = [
|
|
1468
|
+
p.mcp,
|
|
1469
|
+
p.hooks,
|
|
1470
|
+
p.cliConfig
|
|
1471
|
+
];
|
|
1472
|
+
for (const binary of ["cursor-agent", "agent"]) try {
|
|
1473
|
+
const r = await env.exec(binary, ["--version"]);
|
|
1474
|
+
if (r.code !== 0) continue;
|
|
1475
|
+
if (binary === "agent" && !/^\d{4}\.\d{1,2}\.\d{1,2}/.test(r.stdout.trim())) continue;
|
|
1476
|
+
const version = parseCliVersion(r.stdout);
|
|
1477
|
+
return {
|
|
1478
|
+
installed: true,
|
|
1479
|
+
binary,
|
|
1480
|
+
...version ? { version } : {},
|
|
1481
|
+
configPaths
|
|
1482
|
+
};
|
|
1483
|
+
} catch {}
|
|
1484
|
+
return {
|
|
1485
|
+
installed: false,
|
|
1486
|
+
configPaths
|
|
1487
|
+
};
|
|
1488
|
+
}
|
|
1489
|
+
async function plan$1(env) {
|
|
1490
|
+
const p = paths(env);
|
|
1491
|
+
const changes = [];
|
|
1492
|
+
const mcpFile = await loadJson$1(p.mcp);
|
|
1493
|
+
const servers = mcpObject(mcpFile.value, p.mcp);
|
|
1494
|
+
const want = desiredServer(env);
|
|
1495
|
+
if (!sameJson$1(servers["conveno"], want)) changes.push({
|
|
1496
|
+
component: "mcp",
|
|
1497
|
+
kind: servers["conveno"] === void 0 ? "add" : "update",
|
|
1498
|
+
parts: [{
|
|
1499
|
+
name: "MCP server",
|
|
1500
|
+
kind: servers["conveno"] === void 0 ? "add" : "update"
|
|
1501
|
+
}],
|
|
1502
|
+
path: p.mcp,
|
|
1503
|
+
before: mcpFile.raw,
|
|
1504
|
+
after: editJson$1(mcpFile, [{
|
|
1505
|
+
path: ["mcpServers", SERVER_NAME$1],
|
|
1506
|
+
value: want
|
|
1507
|
+
}]),
|
|
1508
|
+
description: `Register the "${SERVER_NAME$1}" MCP server for the Cursor CLI (conveno mcp --cli cursor).`
|
|
1509
|
+
});
|
|
1510
|
+
const cfgFile = await loadJson$1(p.cliConfig);
|
|
1511
|
+
const allow = allowList(cfgFile.value, p.cliConfig);
|
|
1512
|
+
if (!allow?.includes("Mcp(conveno:*)")) {
|
|
1513
|
+
const edits = [];
|
|
1514
|
+
if (cfgFile.raw === null || cfgFile.raw.trim() === "") edits.push({
|
|
1515
|
+
path: ["version"],
|
|
1516
|
+
value: 1
|
|
1517
|
+
}, {
|
|
1518
|
+
path: ["editor"],
|
|
1519
|
+
value: { vimMode: false }
|
|
1520
|
+
}, {
|
|
1521
|
+
path: ["permissions"],
|
|
1522
|
+
value: {
|
|
1523
|
+
allow: [MCP_PERMISSION],
|
|
1524
|
+
deny: []
|
|
1525
|
+
}
|
|
1526
|
+
});
|
|
1527
|
+
else if (cfgFile.value.permissions === void 0) edits.push({
|
|
1528
|
+
path: ["permissions"],
|
|
1529
|
+
value: {
|
|
1530
|
+
allow: [MCP_PERMISSION],
|
|
1531
|
+
deny: []
|
|
1532
|
+
}
|
|
1533
|
+
});
|
|
1534
|
+
else if (allow === void 0) edits.push({
|
|
1535
|
+
path: ["permissions", "allow"],
|
|
1536
|
+
value: [MCP_PERMISSION]
|
|
1537
|
+
});
|
|
1538
|
+
else edits.push({
|
|
1539
|
+
path: [
|
|
1540
|
+
"permissions",
|
|
1541
|
+
"allow",
|
|
1542
|
+
allow.length
|
|
1543
|
+
],
|
|
1544
|
+
value: MCP_PERMISSION,
|
|
1545
|
+
insert: true
|
|
1546
|
+
});
|
|
1547
|
+
changes.push({
|
|
1548
|
+
component: "mcp",
|
|
1549
|
+
kind: "add",
|
|
1550
|
+
parts: [{
|
|
1551
|
+
name: "tools permission",
|
|
1552
|
+
kind: "add"
|
|
1553
|
+
}],
|
|
1554
|
+
path: p.cliConfig,
|
|
1555
|
+
before: cfgFile.raw,
|
|
1556
|
+
after: editJson$1(cfgFile, edits),
|
|
1557
|
+
description: `Allow the agent to call the "${SERVER_NAME$1}" server's tools without asking (${MCP_PERMISSION}). They only exchange messages between your own sessions.`
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
const hookFile = await loadJson$1(p.hooks);
|
|
1561
|
+
const hooks = hooksObject(hookFile.value, p.hooks);
|
|
1562
|
+
const missing = HOOK_EVENTS.filter((e) => !hasExactHook(hooks, e, hookEntry(env, e)));
|
|
1563
|
+
if (missing.length > 0) {
|
|
1564
|
+
const edits = [];
|
|
1565
|
+
if (hookFile.value.version === void 0) edits.push({
|
|
1566
|
+
path: ["version"],
|
|
1567
|
+
value: 1
|
|
1568
|
+
});
|
|
1569
|
+
for (const e of missing) edits.push(...putInList(hooks[e], ["hooks", e], hookEntry(env, e), isOurEntry));
|
|
1570
|
+
const installed = HOOK_EVENTS.some((e) => entriesOf(hooks, e).some(isOurEntry));
|
|
1571
|
+
changes.push({
|
|
1572
|
+
component: "hooks",
|
|
1573
|
+
kind: installed ? "update" : "add",
|
|
1574
|
+
parts: missing.map((e) => ({
|
|
1575
|
+
name: `${e} hook`,
|
|
1576
|
+
kind: entriesOf(hooks, e).some(isOurEntry) ? "update" : "add"
|
|
1577
|
+
})),
|
|
1578
|
+
path: p.hooks,
|
|
1579
|
+
before: hookFile.raw,
|
|
1580
|
+
after: editJson$1(hookFile, edits),
|
|
1581
|
+
description: `Add ${missing.join(", ")} hooks that deliver Conveno messages to the Cursor CLI on the next turn and at the end of a turn.`
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
return changes;
|
|
1585
|
+
}
|
|
1586
|
+
async function uninstallPlan$1(env, baseline) {
|
|
1587
|
+
const p = paths(env);
|
|
1588
|
+
const changes = [];
|
|
1589
|
+
const mcpFile = await loadJson$1(p.mcp);
|
|
1590
|
+
if ("conveno" in mcpObject(mcpFile.value, p.mcp)) changes.push({
|
|
1591
|
+
component: "mcp",
|
|
1592
|
+
kind: "remove",
|
|
1593
|
+
path: p.mcp,
|
|
1594
|
+
before: mcpFile.raw,
|
|
1595
|
+
after: editJson$1(mcpFile, [{
|
|
1596
|
+
path: ["mcpServers", SERVER_NAME$1],
|
|
1597
|
+
value: void 0
|
|
1598
|
+
}]),
|
|
1599
|
+
description: `Remove the "${SERVER_NAME$1}" MCP server.`
|
|
1600
|
+
});
|
|
1601
|
+
const cfgFile = await loadJson$1(p.cliConfig);
|
|
1602
|
+
const at = (allowList(cfgFile.value, p.cliConfig) ?? []).flatMap((x, i) => x === "Mcp(conveno:*)" ? [i] : []);
|
|
1603
|
+
if (at.length > 0) changes.push({
|
|
1604
|
+
component: "mcp",
|
|
1605
|
+
kind: "remove",
|
|
1606
|
+
path: p.cliConfig,
|
|
1607
|
+
before: cfgFile.raw,
|
|
1608
|
+
after: editJson$1(cfgFile, at.reverse().map((i) => ({
|
|
1609
|
+
path: [
|
|
1610
|
+
"permissions",
|
|
1611
|
+
"allow",
|
|
1612
|
+
i
|
|
1613
|
+
],
|
|
1614
|
+
value: void 0
|
|
1615
|
+
}))),
|
|
1616
|
+
description: `Remove ${MCP_PERMISSION} from the allowed permissions.`
|
|
1617
|
+
});
|
|
1618
|
+
const hookFile = await loadJson$1(p.hooks);
|
|
1619
|
+
const hooks = hooksObject(hookFile.value, p.hooks);
|
|
1620
|
+
const next = { ...hooks };
|
|
1621
|
+
const edits = [];
|
|
1622
|
+
for (const e of HOOK_EVENTS) {
|
|
1623
|
+
const drops = dropFromList(hooks[e], ["hooks", e], isOurEntry, { keepEmpty: existedBefore(baseline?.get(p.hooks), ["hooks", e]) });
|
|
1624
|
+
if (drops.length === 0) continue;
|
|
1625
|
+
if (drops.length === 1 && drops[0]?.path.length === 2) delete next[e];
|
|
1626
|
+
edits.push(...drops);
|
|
1627
|
+
}
|
|
1628
|
+
if (edits.length > 0) {
|
|
1629
|
+
if (Object.keys(next).length === 0 && !existedBefore(baseline?.get(p.hooks), ["hooks"])) edits.push({
|
|
1630
|
+
path: ["hooks"],
|
|
1631
|
+
value: void 0
|
|
1632
|
+
});
|
|
1633
|
+
changes.push({
|
|
1634
|
+
component: "hooks",
|
|
1635
|
+
kind: "remove",
|
|
1636
|
+
path: p.hooks,
|
|
1637
|
+
before: hookFile.raw,
|
|
1638
|
+
after: editJson$1(hookFile, edits),
|
|
1639
|
+
description: "Remove the Conveno sessionStart, postToolUse and stop hooks."
|
|
1640
|
+
});
|
|
1641
|
+
}
|
|
1642
|
+
return changes;
|
|
1643
|
+
}
|
|
1644
|
+
const isHookEvent = (e) => HOOK_EVENTS.includes(e);
|
|
1645
|
+
/**
|
|
1646
|
+
* - sessionStart, postToolUse: `{ "additional_context": "<text>" }`, added to the chat's initial
|
|
1647
|
+
* context or to the conversation after the tool result.
|
|
1648
|
+
* - stop: records the turn end. With messages waiting, after a turn that `completed`,
|
|
1649
|
+
* `{ "followup_message": "<text>" }`, which Cursor submits as the next user message. An aborted
|
|
1650
|
+
* or failed turn never continues. Like Codex, Cursor has no idle wake, so this also runs on a
|
|
1651
|
+
* turn that was itself a follow-up; Conveno's auto-mode limit bounds the chain.
|
|
1652
|
+
* cursor-agent 2026.11.22 sends `completed` even after Esc and then does not submit the follow-up
|
|
1653
|
+
* (7000.index.js), so `status` cannot catch every abort; see the README.
|
|
1654
|
+
* Never throws and never writes to stderr: any failure means "deliver nothing this time".
|
|
1655
|
+
*/
|
|
1656
|
+
async function hook$1(event, input, ctx) {
|
|
1657
|
+
if (!isHookEvent(event)) return EMPTY$1;
|
|
1658
|
+
await recordConversationId(input, ctx);
|
|
1659
|
+
if (event === "stop") {
|
|
1660
|
+
const status = isObject$1(input) ? input.status : void 0;
|
|
1661
|
+
const followup = await endTurnContinuation(ctx, { allowContinue: status === void 0 || status === "completed" });
|
|
1662
|
+
if (followup === null) return EMPTY$1;
|
|
1663
|
+
return {
|
|
1664
|
+
stdout: JSON.stringify({ followup_message: followup }),
|
|
1665
|
+
exitCode: 0
|
|
1666
|
+
};
|
|
1667
|
+
}
|
|
1668
|
+
const additionalContext = await pendingHookContext(ctx);
|
|
1669
|
+
if (additionalContext === null) return EMPTY$1;
|
|
1670
|
+
return {
|
|
1671
|
+
stdout: JSON.stringify({ additional_context: additionalContext }),
|
|
1672
|
+
exitCode: 0
|
|
1673
|
+
};
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Every hook input carries `conversation_id`, stable across a chat's turns
|
|
1677
|
+
* (https://cursor.com/docs/hooks.md, "Input (all hooks)"). Tell the daemon, so it knows the CLI's
|
|
1678
|
+
* own id for the session. The lookup itself stays by process: the first hook of a new chat (`/new`
|
|
1679
|
+
* in the same process) holds an id the daemon has not seen, and a lookup by that id would miss.
|
|
1680
|
+
* Best effort; an older daemon without `session.setNative` keeps the pid lookup.
|
|
1681
|
+
*/
|
|
1682
|
+
async function recordConversationId(input, ctx) {
|
|
1683
|
+
const id = isObject$1(input) ? input.conversation_id : void 0;
|
|
1684
|
+
if (typeof id !== "string" || id === "") return;
|
|
1685
|
+
try {
|
|
1686
|
+
const session = await ownSession(ctx);
|
|
1687
|
+
if (!session || session.nativeId === id) return;
|
|
1688
|
+
const call = ctx.client["session.setNative"];
|
|
1689
|
+
if (typeof call === "function") await call({
|
|
1690
|
+
sessionId: session.id,
|
|
1691
|
+
nativeId: id
|
|
1692
|
+
});
|
|
1693
|
+
} catch {}
|
|
1694
|
+
}
|
|
1695
|
+
const cursorAdapter = {
|
|
1696
|
+
cli: "cursor",
|
|
1697
|
+
displayName: "Cursor CLI",
|
|
1698
|
+
deliveryTier: "next_turn",
|
|
1699
|
+
delivery: () => ({
|
|
1700
|
+
nextTurn: true,
|
|
1701
|
+
endOfTurn: true,
|
|
1702
|
+
idleWake: false
|
|
1703
|
+
}),
|
|
1704
|
+
detect: detect$1,
|
|
1705
|
+
plan: plan$1,
|
|
1706
|
+
uninstallPlan: uninstallPlan$1,
|
|
1707
|
+
hook: hook$1
|
|
1708
|
+
};
|
|
1709
|
+
// ../adapters/opencode/dist/index.js
|
|
1710
|
+
/**
|
|
1711
|
+
* The OpenCode 1.x plugin Conveno installs as `<config dir>/plugins/conveno.js`. OpenCode 1.x loads
|
|
1712
|
+
* every `.js` file in the global `plugins/` folder at startup (https://opencode.ai/docs/plugins/,
|
|
1713
|
+
* "From local files") and calls each exported function with a context that holds an SDK `client`.
|
|
1714
|
+
*
|
|
1715
|
+
* The plugin does no Conveno work itself; it runs `conveno hook opencode <event>`, which finds the
|
|
1716
|
+
* session by its host process (this OpenCode process) like every other hook:
|
|
1717
|
+
*
|
|
1718
|
+
* - On `session.idle` of a top-level session it runs `Idle`. With messages waiting,
|
|
1719
|
+
* that prints the continuation prompt, and the plugin sends it with `client.session.promptAsync`.
|
|
1720
|
+
* - Otherwise it starts `Listen`, which waits in the background and prints a prompt when work
|
|
1721
|
+
* arrives while the session is idle; the plugin sends that the same way.
|
|
1722
|
+
* - `promptAsync` always answers 204, so a prompt that cannot run shows up later as a `session.error`
|
|
1723
|
+
* event. The plugin remembers the ids it just sent and hands them back with `Requeue` if that
|
|
1724
|
+
* event arrives before the session turns busy. (The event shape is `{ sessionID?, error }`,
|
|
1725
|
+
* `packages/schema/src/v1/session.ts` at v2.4.3; that it comes before `busy` is UNVERIFIED.)
|
|
1726
|
+
* - When the session turns busy, the plugin is disposed, or a newer listener starts, the listener
|
|
1727
|
+
* is stopped. It also stops by itself when OpenCode exits.
|
|
1728
|
+
*/
|
|
1729
|
+
/** Start of the first line of every Conveno plugin file, whatever the OpenCode line it is for. */
|
|
1730
|
+
const PLUGIN_MARKER_PREFIX = "// conveno-plugin:";
|
|
1731
|
+
/** First line of the 1.x plugin. Uninstall and re-install recognise a plugin by the marker prefix. */
|
|
1732
|
+
const PLUGIN_MARKER = `${PLUGIN_MARKER_PREFIX} 1`;
|
|
1733
|
+
/**
|
|
1734
|
+
* The part both plugins share: the import, the baked-in command, and `run`, which starts
|
|
1735
|
+
* `conveno hook opencode <event>` and resolves with what it prints. Plain JavaScript source text.
|
|
1736
|
+
*/
|
|
1737
|
+
function runHelper(command) {
|
|
1738
|
+
return `import { spawn } from "node:child_process";
|
|
1739
|
+
|
|
1740
|
+
const COMMAND = ${JSON.stringify(command)};
|
|
1741
|
+
// A bare \`conveno\` on Windows is a .cmd shim, which only a shell can start. Every argument is a plain word.
|
|
1742
|
+
const SHELL = process.platform === "win32" && !/\\.exe$/i.test(COMMAND[0]);
|
|
1743
|
+
|
|
1744
|
+
// A hook that hands messages over starts its output with "#conveno-ids <id>,<id>" and the prompt
|
|
1745
|
+
// follows. If sending the prompt fails, the plugin hands those ids back with \`Requeue\`.
|
|
1746
|
+
function split(out) {
|
|
1747
|
+
const m = /^#conveno-ids ([^\\n]*)\\n/.exec(out);
|
|
1748
|
+
if (!m) return { ids: [], text: out };
|
|
1749
|
+
return { ids: m[1].split(",").filter(Boolean), text: out.slice(m[0].length).trim() };
|
|
1750
|
+
}
|
|
1751
|
+
|
|
1752
|
+
function run(event, sessionID, directory, extra) {
|
|
1753
|
+
const [file, ...args] = COMMAND;
|
|
1754
|
+
const child = spawn(file, [...args, "hook", "opencode", event], {
|
|
1755
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
1756
|
+
shell: SHELL,
|
|
1757
|
+
windowsHide: true,
|
|
1758
|
+
});
|
|
1759
|
+
let out = "";
|
|
1760
|
+
child.stdout.setEncoding("utf8");
|
|
1761
|
+
child.stdout.on("data", (chunk) => {
|
|
1762
|
+
out += chunk;
|
|
1763
|
+
});
|
|
1764
|
+
const done = new Promise((resolve) => {
|
|
1765
|
+
child.once("error", () => resolve(""));
|
|
1766
|
+
child.once("close", (code) => resolve(code === 0 ? out.trim() : ""));
|
|
1767
|
+
});
|
|
1768
|
+
child.stdin.on("error", () => {});
|
|
1769
|
+
child.stdin.end(JSON.stringify({ hook_event_name: event, sessionID, directory, ...extra }));
|
|
1770
|
+
return { child, done };
|
|
1771
|
+
}`;
|
|
1772
|
+
}
|
|
1773
|
+
/** The plugin source with the conveno command baked in. Plain JavaScript, no imports beyond Node built-ins. */
|
|
1774
|
+
function pluginSource(command) {
|
|
1775
|
+
return `${PLUGIN_MARKER}
|
|
1776
|
+
// Conveno plugin for OpenCode. Written by \`conveno init\`; \`conveno uninstall\` removes it.
|
|
1777
|
+
// It hands Conveno messages to an idle session. See https://conveno.dev.
|
|
1778
|
+
${runHelper(command)}
|
|
1779
|
+
|
|
1780
|
+
export const ConvenoPlugin = async ({ client }) => {
|
|
1781
|
+
let listener;
|
|
1782
|
+
|
|
1783
|
+
const stop = () => {
|
|
1784
|
+
if (!listener) return;
|
|
1785
|
+
listener.child.kill();
|
|
1786
|
+
listener = undefined;
|
|
1787
|
+
};
|
|
1788
|
+
|
|
1789
|
+
// Ids of the batch just sent to a session, until it turns busy, the next prompt replaces it, or
|
|
1790
|
+
// SENT_TTL_MS pass. A session.error before that means the prompt did not run. An idle event does
|
|
1791
|
+
// not clear it: a cancel with no runner can publish one before the error. The TTL stops a much
|
|
1792
|
+
// later error (of a turn that did run) from requeueing messages that were delivered.
|
|
1793
|
+
const SENT_TTL_MS = 30000;
|
|
1794
|
+
const sent = new Map();
|
|
1795
|
+
const requeue = (sessionID, ids) =>
|
|
1796
|
+
ids.length > 0 ? run("Requeue", sessionID, undefined, { ids }).done : undefined;
|
|
1797
|
+
|
|
1798
|
+
const prompt = async (sessionID, out) => {
|
|
1799
|
+
const { ids, text } = split(out);
|
|
1800
|
+
try {
|
|
1801
|
+
sent.delete(sessionID);
|
|
1802
|
+
if (ids.length > 0) sent.set(sessionID, { ids, at: Date.now() });
|
|
1803
|
+
const res = await client.session.promptAsync({
|
|
1804
|
+
path: { id: sessionID },
|
|
1805
|
+
body: { parts: [{ type: "text", text }] },
|
|
1806
|
+
});
|
|
1807
|
+
if (res?.error) throw new Error("prompt failed");
|
|
1808
|
+
} catch {
|
|
1809
|
+
// The session is gone or busy again: hand the messages back so the next turn gets them.
|
|
1810
|
+
sent.delete(sessionID);
|
|
1811
|
+
await requeue(sessionID, ids);
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
|
|
1815
|
+
const titles = new Map();
|
|
1816
|
+
const retitle = async (sessionID) => {
|
|
1817
|
+
try {
|
|
1818
|
+
const name = await run("Title", sessionID).done;
|
|
1819
|
+
if (!name || titles.get(sessionID) === name) return;
|
|
1820
|
+
await client.session.update({ path: { id: sessionID }, body: { title: name } });
|
|
1821
|
+
titles.set(sessionID, name);
|
|
1822
|
+
} catch {
|
|
1823
|
+
// The title is cosmetic.
|
|
1824
|
+
}
|
|
1825
|
+
};
|
|
1826
|
+
|
|
1827
|
+
const topLevel = async (sessionID) => {
|
|
1828
|
+
try {
|
|
1829
|
+
const res = await client.session.get({ path: { id: sessionID } });
|
|
1830
|
+
return !res?.data?.parentID;
|
|
1831
|
+
} catch {
|
|
1832
|
+
return false;
|
|
1833
|
+
}
|
|
1834
|
+
};
|
|
1835
|
+
|
|
1836
|
+
const onIdle = async (sessionID) => {
|
|
1837
|
+
if (!(await topLevel(sessionID))) return;
|
|
1838
|
+
stop();
|
|
1839
|
+
void retitle(sessionID);
|
|
1840
|
+
const now = await run("Idle", sessionID).done;
|
|
1841
|
+
if (now) return prompt(sessionID, now);
|
|
1842
|
+
const current = { ...run("Listen", sessionID), sessionID };
|
|
1843
|
+
listener = current;
|
|
1844
|
+
const text = await current.done;
|
|
1845
|
+
if (listener === current) listener = undefined;
|
|
1846
|
+
if (text) await prompt(sessionID, text);
|
|
1847
|
+
};
|
|
1848
|
+
|
|
1849
|
+
return {
|
|
1850
|
+
event: async ({ event }) => {
|
|
1851
|
+
if (event.type === "session.idle") void onIdle(event.properties.sessionID);
|
|
1852
|
+
else if (event.type === "session.error") {
|
|
1853
|
+
const id = event.properties?.sessionID;
|
|
1854
|
+
const entry = id && sent.get(id);
|
|
1855
|
+
if (entry) {
|
|
1856
|
+
sent.delete(id);
|
|
1857
|
+
if (Date.now() - entry.at <= SENT_TTL_MS) await requeue(id, entry.ids);
|
|
1858
|
+
}
|
|
1859
|
+
} else if (event.type === "session.status" && event.properties.status?.type === "busy") {
|
|
1860
|
+
sent.delete(event.properties.sessionID);
|
|
1861
|
+
if (event.properties.sessionID === listener?.sessionID) stop();
|
|
1862
|
+
}
|
|
1863
|
+
},
|
|
1864
|
+
dispose: async () => stop(),
|
|
1865
|
+
};
|
|
1866
|
+
};
|
|
1867
|
+
`;
|
|
1868
|
+
}
|
|
1869
|
+
/**
|
|
1870
|
+
* The OpenCode 2.x plugin Conveno installs as `<config dir>/plugins/conveno.js`, the same path as
|
|
1871
|
+
* the 1.x one. OpenCode 2.x loads every `.js` and `.ts` file in the global `plugins/` folder
|
|
1872
|
+
* (https://opencode.ai/docs/plugins/, "Discover"; `packages/core/src/plugin/module.ts` at tag
|
|
1873
|
+
* v2.4.3 accepts a standalone file whose default export is `{ id, setup }`, the object
|
|
1874
|
+
* `Plugin.define` returns, so the file needs no import of `@opencode/plugin`).
|
|
1875
|
+
*
|
|
1876
|
+
* The plugin runs inside the OpenCode server process, which is also the parent of the MCP server
|
|
1877
|
+
* it starts, so `conveno hook opencode <event>` finds the session by host process like every other
|
|
1878
|
+
* hook. It does no Conveno work itself:
|
|
1879
|
+
*
|
|
1880
|
+
* - Just before a session goes idle (`experimental.idle`, `packages/plugin/src/promise/session.ts`
|
|
1881
|
+
* at v2.4.3) it runs `Idle` and admits waiting messages into the same execution. Every prompt
|
|
1882
|
+
* uses `delivery: "queue"`, so it never cuts into a running turn.
|
|
1883
|
+
* - The session title follows the Conveno name (`ctx.session.update`).
|
|
1884
|
+
* - When an execution of a top-level session in this plugin's directory ends
|
|
1885
|
+
* (`session.execution.succeeded`) it runs `Idle`. With messages waiting, that prints
|
|
1886
|
+
* the continuation prompt, and the plugin sends it with `ctx.session.prompt`
|
|
1887
|
+
* (`POST /api/session/{id}/prompt`).
|
|
1888
|
+
* - After a failed or interrupted execution it runs `Stopped`, which records the end without
|
|
1889
|
+
* continuing. An execution that a newer one superseded, or that a shutdown cut off, does nothing.
|
|
1890
|
+
* - Then it starts `Listen`, which waits in the background and prints a prompt when work arrives
|
|
1891
|
+
* while the session is idle; the plugin sends that the same way.
|
|
1892
|
+
* - `session.execution.started`, a newer listener, or unloading the plugin stops the listener.
|
|
1893
|
+
*
|
|
1894
|
+
* - When a session is deleted (`session.deleted`) it runs `Deleted`, which releases the Conveno
|
|
1895
|
+
* session so it goes offline at once instead of waiting for the MCP server to lapse it.
|
|
1896
|
+
*
|
|
1897
|
+
* A prompt sent while the session is busy (between `session.execution.started` and the end event)
|
|
1898
|
+
* uses `delivery: "steer"`, which reaches the agent before its next model call
|
|
1899
|
+
* (`packages/schema/src/session-inbox.ts` at v2.4.3); an idle session gets `"queue"`.
|
|
1900
|
+
*
|
|
1901
|
+
* `session.idle` (deprecated) and `session.status` are not used: 2.4.3 does not deliver them to
|
|
1902
|
+
* plugins (README, "Events"); the durable `session.execution.*` events replace them. Of the APIs
|
|
1903
|
+
* used here, `experimental.idle`, `delivery` and the execution events are feature-detected at run
|
|
1904
|
+
* time; the first 2.x release that has all three is UNVERIFIED.
|
|
1905
|
+
*/
|
|
1906
|
+
/** First line of the 2.x plugin. */
|
|
1907
|
+
const PLUGIN_MARKER_V2 = `${PLUGIN_MARKER_PREFIX} 2`;
|
|
1908
|
+
/** The plugin source with the conveno command baked in. Plain JavaScript, no imports beyond Node built-ins. */
|
|
1909
|
+
function pluginSourceV2(command) {
|
|
1910
|
+
return `${PLUGIN_MARKER_V2}
|
|
1911
|
+
// Conveno plugin for OpenCode 2.x. Written by \`conveno init\`; \`conveno uninstall\` removes it.
|
|
1912
|
+
// It hands Conveno messages to an idle session. See https://conveno.dev.
|
|
1913
|
+
${runHelper(command)}
|
|
1914
|
+
|
|
1915
|
+
export default {
|
|
1916
|
+
id: "conveno",
|
|
1917
|
+
setup(ctx) {
|
|
1918
|
+
const controller = new AbortController();
|
|
1919
|
+
let listener;
|
|
1920
|
+
// Sessions with a running execution, from the execution events.
|
|
1921
|
+
const busy = new Set();
|
|
1922
|
+
|
|
1923
|
+
const stop = () => {
|
|
1924
|
+
if (!listener) return;
|
|
1925
|
+
listener.child.kill();
|
|
1926
|
+
listener = undefined;
|
|
1927
|
+
};
|
|
1928
|
+
|
|
1929
|
+
const prompt = async (sessionID, out, forceQueue) => {
|
|
1930
|
+
const { ids, text } = split(out);
|
|
1931
|
+
// "steer" reaches a busy agent before its next model call; "queue" waits for it to finish.
|
|
1932
|
+
// The idle hook runs while the execution is still open but about to end, so it queues.
|
|
1933
|
+
const delivery = !forceQueue && busy.has(sessionID) ? "steer" : "queue";
|
|
1934
|
+
try {
|
|
1935
|
+
try {
|
|
1936
|
+
await ctx.session.prompt({ sessionID, text, delivery });
|
|
1937
|
+
} catch (err) {
|
|
1938
|
+
// A server that does not know \`delivery\` rejects it; send without it (the server's default).
|
|
1939
|
+
if (!/delivery/i.test(String(err?.message ?? err))) throw err;
|
|
1940
|
+
await ctx.session.prompt({ sessionID, text });
|
|
1941
|
+
}
|
|
1942
|
+
} catch {
|
|
1943
|
+
// The session is gone or busy again: hand the messages back so the next turn gets them.
|
|
1944
|
+
if (ids.length > 0) await run("Requeue", sessionID, ctx.location.directory, { ids }).done;
|
|
1945
|
+
}
|
|
1946
|
+
};
|
|
1947
|
+
|
|
1948
|
+
// The server sends every plugin the events of every location it serves. Only top-level
|
|
1949
|
+
// sessions of this plugin's own directory are ours.
|
|
1950
|
+
const ours = async (sessionID) => {
|
|
1951
|
+
try {
|
|
1952
|
+
const info = await ctx.session.get({ sessionID });
|
|
1953
|
+
return !info.parentID && info.location.directory === ctx.location.directory;
|
|
1954
|
+
} catch {
|
|
1955
|
+
return false;
|
|
1956
|
+
}
|
|
1957
|
+
};
|
|
1958
|
+
|
|
1959
|
+
// The session title follows the Conveno name; it is cosmetic, so failures are ignored.
|
|
1960
|
+
const titles = new Map();
|
|
1961
|
+
const retitle = async (sessionID) => {
|
|
1962
|
+
try {
|
|
1963
|
+
const name = await run("Title", sessionID, ctx.location.directory).done;
|
|
1964
|
+
if (!name || titles.get(sessionID) === name) return;
|
|
1965
|
+
await ctx.session.update({ sessionID, title: name });
|
|
1966
|
+
titles.set(sessionID, name);
|
|
1967
|
+
} catch {
|
|
1968
|
+
// Ignored.
|
|
1969
|
+
}
|
|
1970
|
+
};
|
|
1971
|
+
|
|
1972
|
+
// Runs just before the session goes idle. Messages that arrived during the turn are admitted
|
|
1973
|
+
// here, so the same execution carries on instead of the session going idle first.
|
|
1974
|
+
if (typeof ctx.session.hook === "function") {
|
|
1975
|
+
void ctx.session
|
|
1976
|
+
.hook("experimental.idle", async ({ sessionID }) => {
|
|
1977
|
+
if (!(await ours(sessionID))) return;
|
|
1978
|
+
const now = await run("Idle", sessionID, ctx.location.directory).done;
|
|
1979
|
+
if (now) await prompt(sessionID, now, true);
|
|
1980
|
+
})
|
|
1981
|
+
.catch(() => {});
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
const onEnd = async (sessionID, event) => {
|
|
1985
|
+
if (!(await ours(sessionID))) return;
|
|
1986
|
+
stop();
|
|
1987
|
+
void retitle(sessionID);
|
|
1988
|
+
const now = await run(event, sessionID, ctx.location.directory).done;
|
|
1989
|
+
if (now) return prompt(sessionID, now);
|
|
1990
|
+
const current = { ...run("Listen", sessionID, ctx.location.directory), sessionID };
|
|
1991
|
+
listener = current;
|
|
1992
|
+
const text = await current.done;
|
|
1993
|
+
if (listener === current) listener = undefined;
|
|
1994
|
+
if (text) await prompt(sessionID, text);
|
|
1995
|
+
};
|
|
1996
|
+
|
|
1997
|
+
void (async () => {
|
|
1998
|
+
try {
|
|
1999
|
+
if (typeof ctx.event?.subscribe !== "function") return;
|
|
2000
|
+
for await (const event of ctx.event.subscribe({
|
|
2001
|
+
types: [
|
|
2002
|
+
"session.execution.started",
|
|
2003
|
+
"session.execution.succeeded",
|
|
2004
|
+
"session.execution.failed",
|
|
2005
|
+
"session.execution.interrupted",
|
|
2006
|
+
"session.deleted",
|
|
2007
|
+
],
|
|
2008
|
+
signal: controller.signal,
|
|
2009
|
+
})) {
|
|
2010
|
+
const { sessionID } = event.data;
|
|
2011
|
+
if (event.type === "session.execution.started") busy.add(sessionID);
|
|
2012
|
+
else busy.delete(sessionID);
|
|
2013
|
+
if (event.type === "session.deleted") {
|
|
2014
|
+
// The session is gone: release its Conveno session so it goes offline now.
|
|
2015
|
+
if (sessionID === listener?.sessionID) stop();
|
|
2016
|
+
void run("Deleted", sessionID, ctx.location.directory).done;
|
|
2017
|
+
} else if (event.type === "session.execution.started") {
|
|
2018
|
+
if (sessionID === listener?.sessionID) stop();
|
|
2019
|
+
} else if (event.type === "session.execution.succeeded") {
|
|
2020
|
+
void onEnd(sessionID, "Idle");
|
|
2021
|
+
} else if (
|
|
2022
|
+
event.type === "session.execution.failed" ||
|
|
2023
|
+
(event.type === "session.execution.interrupted" &&
|
|
2024
|
+
(event.data.reason === "user" || event.data.reason === "inactivity"))
|
|
2025
|
+
) {
|
|
2026
|
+
void onEnd(sessionID, "Stopped");
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
} catch {
|
|
2030
|
+
// The subscription ended with the plugin.
|
|
2031
|
+
}
|
|
2032
|
+
})();
|
|
2033
|
+
|
|
2034
|
+
return () => {
|
|
2035
|
+
controller.abort();
|
|
2036
|
+
stop();
|
|
2037
|
+
};
|
|
2038
|
+
},
|
|
2039
|
+
};
|
|
2040
|
+
`;
|
|
2041
|
+
}
|
|
2042
|
+
const SERVER_NAME = "conveno";
|
|
2043
|
+
const FORMAT = {
|
|
2044
|
+
insertSpaces: true,
|
|
2045
|
+
tabSize: 2,
|
|
2046
|
+
eol: "\n"
|
|
2047
|
+
};
|
|
2048
|
+
/**
|
|
2049
|
+
* First OpenCode release that reads `mcp.servers` and gets the 2.x plugin. There were no 2.0.x or
|
|
2050
|
+
* 2.1.x releases.
|
|
2051
|
+
*/
|
|
2052
|
+
const V2_MIN = [
|
|
2053
|
+
2,
|
|
2054
|
+
2,
|
|
2055
|
+
0
|
|
2056
|
+
];
|
|
2057
|
+
/**
|
|
2058
|
+
* The 2.x release Conveno is checked against (the 2.4.3 source). Older 2.x still gets the right
|
|
2059
|
+
* config, but waking is only supported from here; doctor says so.
|
|
2060
|
+
*/
|
|
2061
|
+
const V2_SUPPORTED = [
|
|
2062
|
+
2,
|
|
2063
|
+
4,
|
|
2064
|
+
0
|
|
2065
|
+
];
|
|
2066
|
+
/** `$XDG_CONFIG_HOME/opencode` when XDG_CONFIG_HOME is an absolute path, else `~/.config/opencode`. */
|
|
2067
|
+
function configDir(env) {
|
|
2068
|
+
const xdg = env.env.XDG_CONFIG_HOME;
|
|
2069
|
+
const base = xdg && isAbsolute(xdg) ? xdg : join(env.home, ".config");
|
|
2070
|
+
return join(base, "opencode");
|
|
2071
|
+
}
|
|
2072
|
+
/** `OPENCODE_CONFIG` names one config file; when set it is the only file we touch. */
|
|
2073
|
+
const customConfig = (env) => env.env.OPENCODE_CONFIG || void 0;
|
|
2074
|
+
/**
|
|
2075
|
+
* `OPENCODE_CONFIG` when set. Otherwise an existing opencode.jsonc, then opencode.json, else a
|
|
2076
|
+
* new opencode.json in the config directory.
|
|
2077
|
+
*/
|
|
2078
|
+
async function locateConfig(env) {
|
|
2079
|
+
const custom = customConfig(env);
|
|
2080
|
+
if (custom) try {
|
|
2081
|
+
return {
|
|
2082
|
+
path: custom,
|
|
2083
|
+
text: await readFile(custom, "utf8")
|
|
2084
|
+
};
|
|
2085
|
+
} catch (err) {
|
|
2086
|
+
if (err.code !== "ENOENT") throw err;
|
|
2087
|
+
return {
|
|
2088
|
+
path: custom,
|
|
2089
|
+
text: null
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
const dir = configDir(env);
|
|
2093
|
+
for (const name of ["opencode.jsonc", "opencode.json"]) {
|
|
2094
|
+
const path = join(dir, name);
|
|
2095
|
+
try {
|
|
2096
|
+
return {
|
|
2097
|
+
path,
|
|
2098
|
+
text: await readFile(path, "utf8")
|
|
2099
|
+
};
|
|
2100
|
+
} catch (err) {
|
|
2101
|
+
if (err.code !== "ENOENT") throw err;
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
return {
|
|
2105
|
+
path: join(dir, "opencode.json"),
|
|
2106
|
+
text: null
|
|
2107
|
+
};
|
|
2108
|
+
}
|
|
2109
|
+
function parseConfig(file) {
|
|
2110
|
+
if (file.text === null || file.text.trim() === "") return {};
|
|
2111
|
+
const errors = [];
|
|
2112
|
+
const value = parse(file.text, errors, { allowTrailingComma: true });
|
|
2113
|
+
const first = errors[0];
|
|
2114
|
+
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.`);
|
|
2115
|
+
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.`);
|
|
2116
|
+
return value;
|
|
2117
|
+
}
|
|
2118
|
+
function serverEntry(env, shape) {
|
|
2119
|
+
const command = [
|
|
2120
|
+
...env.conveno.command,
|
|
2121
|
+
"mcp",
|
|
2122
|
+
"--cli",
|
|
2123
|
+
"opencode"
|
|
2124
|
+
];
|
|
2125
|
+
return shape === "v1" ? {
|
|
2126
|
+
type: "local",
|
|
2127
|
+
command,
|
|
2128
|
+
enabled: true
|
|
2129
|
+
} : {
|
|
2130
|
+
type: "local",
|
|
2131
|
+
command
|
|
2132
|
+
};
|
|
2133
|
+
}
|
|
2134
|
+
function parseVersion(text) {
|
|
2135
|
+
const m = /(\d+)\.(\d+)\.(\d+)/.exec(text);
|
|
2136
|
+
return m ? [
|
|
2137
|
+
Number(m[1]),
|
|
2138
|
+
Number(m[2]),
|
|
2139
|
+
Number(m[3])
|
|
2140
|
+
] : void 0;
|
|
2141
|
+
}
|
|
2142
|
+
function atLeast(v, min) {
|
|
2143
|
+
for (let i = 0; i < 3; i++) if (v[i] !== min[i]) return v[i] > min[i];
|
|
2144
|
+
return true;
|
|
2145
|
+
}
|
|
2146
|
+
function isV2OrLater(v) {
|
|
2147
|
+
return atLeast(v, V2_MIN);
|
|
2148
|
+
}
|
|
2149
|
+
/** One line for `conveno doctor` when this OpenCode is a 2.x release older than the supported one. */
|
|
2150
|
+
async function opencodeDoctorNotes(env) {
|
|
2151
|
+
const v = await installedVersion(env);
|
|
2152
|
+
if (!v || !isV2OrLater(v) || atLeast(v, V2_SUPPORTED)) return [];
|
|
2153
|
+
return [`OpenCode ${v.join(".")} is older than 2.4, the oldest 2.x Conveno supports. Update OpenCode so waking works.`];
|
|
2154
|
+
}
|
|
2155
|
+
async function installedVersion(env) {
|
|
2156
|
+
try {
|
|
2157
|
+
const res = await env.exec("opencode", ["--version"]);
|
|
2158
|
+
return res.code === 0 ? parseVersion(res.stdout) : void 0;
|
|
2159
|
+
} catch {
|
|
2160
|
+
return;
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
async function chooseShape(config, version) {
|
|
2164
|
+
if (version) return isV2OrLater(version) ? "v2" : "v1";
|
|
2165
|
+
return servers(config) !== void 0 ? "v2" : "v1";
|
|
2166
|
+
}
|
|
2167
|
+
function v1Entry(config) {
|
|
2168
|
+
const mcp = config.mcp;
|
|
2169
|
+
if (mcp === null || typeof mcp !== "object" || Array.isArray(mcp)) return void 0;
|
|
2170
|
+
return mcp[SERVER_NAME];
|
|
2171
|
+
}
|
|
2172
|
+
function pathFor(shape) {
|
|
2173
|
+
return shape === "v1" ? ["mcp", SERVER_NAME] : [
|
|
2174
|
+
"mcp",
|
|
2175
|
+
"servers",
|
|
2176
|
+
SERVER_NAME
|
|
2177
|
+
];
|
|
2178
|
+
}
|
|
2179
|
+
function sameEntry(found, want) {
|
|
2180
|
+
if (found === null || typeof found !== "object") return false;
|
|
2181
|
+
const f = found;
|
|
2182
|
+
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]);
|
|
2183
|
+
}
|
|
2184
|
+
function servers(config) {
|
|
2185
|
+
const mcp = config.mcp;
|
|
2186
|
+
if (mcp === null || typeof mcp !== "object" || Array.isArray(mcp)) return void 0;
|
|
2187
|
+
const s = mcp.servers;
|
|
2188
|
+
if (s === null || typeof s !== "object" || Array.isArray(s)) return void 0;
|
|
2189
|
+
return s;
|
|
2190
|
+
}
|
|
2191
|
+
async function detect(env) {
|
|
2192
|
+
const custom = customConfig(env);
|
|
2193
|
+
const configPaths = custom ? [custom] : [join(configDir(env), "opencode.jsonc"), join(configDir(env), "opencode.json")];
|
|
2194
|
+
try {
|
|
2195
|
+
const res = await env.exec("opencode", ["--version"]);
|
|
2196
|
+
if (res.code !== 0) return {
|
|
2197
|
+
installed: false,
|
|
2198
|
+
configPaths
|
|
2199
|
+
};
|
|
2200
|
+
const version = parseCliVersion(res.stdout);
|
|
2201
|
+
return {
|
|
2202
|
+
installed: true,
|
|
2203
|
+
binary: "opencode",
|
|
2204
|
+
configPaths,
|
|
2205
|
+
...version ? { version } : {}
|
|
2206
|
+
};
|
|
2207
|
+
} catch {
|
|
2208
|
+
return {
|
|
2209
|
+
installed: false,
|
|
2210
|
+
configPaths
|
|
2211
|
+
};
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
/** `<config dir>/plugins/conveno.js`, the global plugin folder OpenCode 1.x and 2.x load. */
|
|
2215
|
+
const pluginPath = (env) => join(configDir(env), "plugins", "conveno.js");
|
|
2216
|
+
async function readText(path) {
|
|
2217
|
+
try {
|
|
2218
|
+
return await readFile(path, "utf8");
|
|
2219
|
+
} catch (err) {
|
|
2220
|
+
if (err.code === "ENOENT") return null;
|
|
2221
|
+
throw err;
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
/**
|
|
2225
|
+
* The plugin API differs between the lines (https://opencode.ai/docs/build/plugins/migrate-v1/), so
|
|
2226
|
+
* each gets its own source at the same path. An unknown version gets nothing rather than a file
|
|
2227
|
+
* that might not load.
|
|
2228
|
+
*/
|
|
2229
|
+
const pluginFor = (env, version) => {
|
|
2230
|
+
if (version === void 0) return void 0;
|
|
2231
|
+
return isV2OrLater(version) ? pluginSourceV2(env.conveno.command) : pluginSource(env.conveno.command);
|
|
2232
|
+
};
|
|
2233
|
+
async function planPlugin(env, version) {
|
|
2234
|
+
const want = pluginFor(env, version);
|
|
2235
|
+
if (want === void 0) return [];
|
|
2236
|
+
const path = pluginPath(env);
|
|
2237
|
+
const before = await readText(path);
|
|
2238
|
+
if (before === want) return [];
|
|
2239
|
+
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.`);
|
|
2240
|
+
return [{
|
|
2241
|
+
component: "hooks",
|
|
2242
|
+
kind: before === null ? "add" : "update",
|
|
2243
|
+
parts: [{
|
|
2244
|
+
name: "plugin file",
|
|
2245
|
+
kind: before === null ? "add" : "update"
|
|
2246
|
+
}],
|
|
2247
|
+
path,
|
|
2248
|
+
before,
|
|
2249
|
+
after: want,
|
|
2250
|
+
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.`
|
|
2251
|
+
}];
|
|
2252
|
+
}
|
|
2253
|
+
async function uninstallPlugin(env) {
|
|
2254
|
+
const path = pluginPath(env);
|
|
2255
|
+
const before = await readText(path);
|
|
2256
|
+
if (before === null || !before.startsWith("// conveno-plugin:")) return [];
|
|
2257
|
+
return [{
|
|
2258
|
+
component: "hooks",
|
|
2259
|
+
kind: "remove",
|
|
2260
|
+
path,
|
|
2261
|
+
before,
|
|
2262
|
+
after: "",
|
|
2263
|
+
deleteFile: true,
|
|
2264
|
+
description: "Remove the Conveno plugin for OpenCode."
|
|
2265
|
+
}];
|
|
2266
|
+
}
|
|
2267
|
+
async function plan(env) {
|
|
2268
|
+
const version = await installedVersion(env);
|
|
2269
|
+
return [...await planMcp(env, version), ...await planPlugin(env, version)];
|
|
2270
|
+
}
|
|
2271
|
+
async function uninstallPlan(env) {
|
|
2272
|
+
return [...await uninstallMcp(env), ...await uninstallPlugin(env)];
|
|
2273
|
+
}
|
|
2274
|
+
async function planMcp(env, version) {
|
|
2275
|
+
const file = await locateConfig(env);
|
|
2276
|
+
const config = parseConfig(file);
|
|
2277
|
+
const shape = await chooseShape(config, version);
|
|
2278
|
+
const want = serverEntry(env, shape);
|
|
2279
|
+
const current = shape === "v1" ? v1Entry(config) : servers(config)?.[SERVER_NAME];
|
|
2280
|
+
if (sameEntry(current, want)) return [];
|
|
2281
|
+
let text = file.text === null || file.text.trim() === "" ? "{}\n" : file.text;
|
|
2282
|
+
const otherShape = shape === "v1" ? "v2" : "v1";
|
|
2283
|
+
const other = otherShape === "v1" ? v1Entry(config) : servers(config)?.[SERVER_NAME];
|
|
2284
|
+
if (other !== void 0) text = applyEdits(text, modify(text, pathFor(otherShape), void 0, { formattingOptions: FORMAT }));
|
|
2285
|
+
let after = applyEdits(text, modify(text, pathFor(shape), want, { formattingOptions: FORMAT }));
|
|
2286
|
+
if (!after.endsWith("\n")) after += "\n";
|
|
2287
|
+
const where = shape === "v1" ? `mcp.${SERVER_NAME}` : `mcp.servers.${SERVER_NAME}`;
|
|
2288
|
+
return [{
|
|
2289
|
+
component: "mcp",
|
|
2290
|
+
kind: current !== void 0 || other !== void 0 ? "update" : "add",
|
|
2291
|
+
parts: [{
|
|
2292
|
+
name: "MCP server",
|
|
2293
|
+
kind: current !== void 0 || other !== void 0 ? "update" : "add"
|
|
2294
|
+
}],
|
|
2295
|
+
path: file.path,
|
|
2296
|
+
before: file.text,
|
|
2297
|
+
after,
|
|
2298
|
+
description: `Add the conveno MCP server (${where}) to the OpenCode global config`
|
|
2299
|
+
}];
|
|
2300
|
+
}
|
|
2301
|
+
async function uninstallMcp(env) {
|
|
2302
|
+
const file = await locateConfig(env);
|
|
2303
|
+
if (file.text === null) return [];
|
|
2304
|
+
const config = parseConfig(file);
|
|
2305
|
+
let text = file.text;
|
|
2306
|
+
const removed = [];
|
|
2307
|
+
if (servers(config)?.[SERVER_NAME] !== void 0) {
|
|
2308
|
+
text = applyEdits(text, modify(text, pathFor("v2"), void 0, { formattingOptions: FORMAT }));
|
|
2309
|
+
removed.push(`mcp.servers.${SERVER_NAME}`);
|
|
2310
|
+
}
|
|
2311
|
+
if (v1Entry(config) !== void 0) {
|
|
2312
|
+
text = applyEdits(text, modify(text, pathFor("v1"), void 0, { formattingOptions: FORMAT }));
|
|
2313
|
+
removed.push(`mcp.${SERVER_NAME}`);
|
|
2314
|
+
}
|
|
2315
|
+
if (removed.length === 0) return [];
|
|
2316
|
+
return [{
|
|
2317
|
+
component: "mcp",
|
|
2318
|
+
kind: "remove",
|
|
2319
|
+
path: file.path,
|
|
2320
|
+
before: file.text,
|
|
2321
|
+
after: text,
|
|
2322
|
+
description: `Remove the conveno MCP server (${removed.join(", ")}) from the OpenCode global config`
|
|
2323
|
+
}];
|
|
2324
|
+
}
|
|
2325
|
+
const EMPTY = {
|
|
2326
|
+
stdout: "",
|
|
2327
|
+
exitCode: 0
|
|
2328
|
+
};
|
|
2329
|
+
/**
|
|
2330
|
+
* Run by the plugin, never by OpenCode itself. Each prints the prompt to send as plain text, which
|
|
2331
|
+
* the plugin sends to the session (1.x `client.session.promptAsync`, 2.x `ctx.session.prompt`).
|
|
2332
|
+
* - Idle: the session's turn ended. With messages waiting, the prompt to continue with.
|
|
2333
|
+
* - Stopped: the turn failed or the user interrupted it. Records the end and never continues.
|
|
2334
|
+
* - Listen: the background listener. Waits for work while the session is idle.
|
|
2335
|
+
* - Requeue: the plugin could not send the prompt; puts the messages (`ids` in the input) back to queued.
|
|
2336
|
+
* - Deleted: the OpenCode session was deleted; unregisters its Conveno session.
|
|
2337
|
+
* - Title: prints the session's Conveno name, which the plugin sets as the OpenCode session title.
|
|
2338
|
+
*/
|
|
2339
|
+
async function hook(event, input, ctx) {
|
|
2340
|
+
const dir = typeof input === "object" && input !== null ? input.directory : void 0;
|
|
2341
|
+
if (typeof dir === "string" && dir !== "") ctx = {
|
|
2342
|
+
...ctx,
|
|
2343
|
+
cwd: dir
|
|
2344
|
+
};
|
|
2345
|
+
const native = typeof input === "object" && input !== null ? input.sessionID : void 0;
|
|
2346
|
+
if (typeof native === "string" && native !== "") ctx = {
|
|
2347
|
+
...ctx,
|
|
2348
|
+
nativeId: native
|
|
2349
|
+
};
|
|
2350
|
+
if (event === "Deleted") {
|
|
2351
|
+
await release(ctx, input);
|
|
2352
|
+
return EMPTY;
|
|
2353
|
+
}
|
|
2354
|
+
if (event === "Requeue") {
|
|
2355
|
+
await requeue(ctx, input);
|
|
2356
|
+
return EMPTY;
|
|
2357
|
+
}
|
|
2358
|
+
const ids = [];
|
|
2359
|
+
if (ctx.client) ctx = {
|
|
2360
|
+
...ctx,
|
|
2361
|
+
client: recordIds(ctx.client, ids)
|
|
2362
|
+
};
|
|
2363
|
+
let text = null;
|
|
2364
|
+
if (event === "Idle") text = await endTurnContinuation(ctx);
|
|
2365
|
+
else if (event === "Stopped") await endTurnContinuation(ctx, { allowContinue: false });
|
|
2366
|
+
else if (event === "Listen") text = await waitForWork(ctx);
|
|
2367
|
+
else if (event === "Title") text = await sessionName(ctx);
|
|
2368
|
+
if (text === null) return EMPTY;
|
|
2369
|
+
return {
|
|
2370
|
+
stdout: ids.length > 0 ? `#conveno-ids ${ids.join(",")}\n${text}` : text,
|
|
2371
|
+
exitCode: 0
|
|
2372
|
+
};
|
|
2373
|
+
}
|
|
2374
|
+
/** The client, with the ids of every message `turn.end` and `turn.wake` return copied into `ids`. */
|
|
2375
|
+
function recordIds(client, ids) {
|
|
2376
|
+
return new Proxy(client, { get(target, prop, receiver) {
|
|
2377
|
+
const value = Reflect.get(target, prop, receiver);
|
|
2378
|
+
if (prop !== "turn.end" && prop !== "turn.wake" || typeof value !== "function") return value;
|
|
2379
|
+
return async (...args) => {
|
|
2380
|
+
const r = await value.apply(target, args);
|
|
2381
|
+
for (const m of r?.messages ?? []) ids.push(m.id);
|
|
2382
|
+
return r;
|
|
2383
|
+
};
|
|
2384
|
+
} });
|
|
2385
|
+
}
|
|
2386
|
+
/** `Deleted`: the OpenCode session is gone, so its Conveno session goes offline now. */
|
|
2387
|
+
async function release(ctx, input) {
|
|
2388
|
+
try {
|
|
2389
|
+
const id = input?.sessionID;
|
|
2390
|
+
if (typeof id !== "string" || id === "") return;
|
|
2391
|
+
const session = await ownSession(ctx);
|
|
2392
|
+
if (!session) return;
|
|
2393
|
+
await ctx.client["session.unregister"]({ sessionId: session.id });
|
|
2394
|
+
} catch {}
|
|
2395
|
+
}
|
|
2396
|
+
/** `Requeue`: sending the prompt failed, so the messages go back to queued for the next turn. */
|
|
2397
|
+
async function requeue(ctx, input) {
|
|
2398
|
+
try {
|
|
2399
|
+
const ids = input?.ids;
|
|
2400
|
+
if (!Array.isArray(ids) || ids.length === 0) return;
|
|
2401
|
+
const session = await ownSession(ctx);
|
|
2402
|
+
if (!session) return;
|
|
2403
|
+
await ctx.client["message.requeue"]({
|
|
2404
|
+
sessionId: session.id,
|
|
2405
|
+
ids
|
|
2406
|
+
});
|
|
2407
|
+
} catch {}
|
|
2408
|
+
}
|
|
2409
|
+
async function sessionName(ctx) {
|
|
2410
|
+
try {
|
|
2411
|
+
const session = await ownSession(ctx);
|
|
2412
|
+
return session?.name ? session.name : null;
|
|
2413
|
+
} catch {
|
|
2414
|
+
return null;
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
/**
|
|
2418
|
+
* Only the plugin delivers, on 1.x and 2.4+ alike; it adds nothing to a prompt the user types.
|
|
2419
|
+
* 2.0 to 2.3 are not supported (`opencodeDoctorNotes`), so doctor claims no waking for them.
|
|
2420
|
+
*/
|
|
2421
|
+
function delivery(detection) {
|
|
2422
|
+
const v = detection.version === void 0 ? void 0 : parseVersion(detection.version);
|
|
2423
|
+
const supported = v !== void 0 && (!isV2OrLater(v) || atLeast(v, V2_SUPPORTED));
|
|
2424
|
+
return {
|
|
2425
|
+
nextTurn: false,
|
|
2426
|
+
endOfTurn: supported,
|
|
2427
|
+
idleWake: supported
|
|
2428
|
+
};
|
|
2429
|
+
}
|
|
2430
|
+
const opencodeAdapter = {
|
|
2431
|
+
doctorNotes: opencodeDoctorNotes,
|
|
2432
|
+
cli: "opencode",
|
|
2433
|
+
displayName: "OpenCode",
|
|
2434
|
+
deliveryTier: "inbox",
|
|
2435
|
+
detect,
|
|
2436
|
+
plan,
|
|
2437
|
+
uninstallPlan,
|
|
2438
|
+
hook,
|
|
2439
|
+
listenEvents: ["Listen"],
|
|
2440
|
+
delivery
|
|
2441
|
+
};
|
|
2442
|
+
// src/hook-entry.ts
|
|
2443
|
+
function readAllStdin() {
|
|
2444
|
+
if (process.stdin.isTTY) return Promise.resolve("");
|
|
2445
|
+
return new Promise((resolve, reject) => {
|
|
2446
|
+
let data = "";
|
|
2447
|
+
process.stdin.setEncoding("utf8");
|
|
2448
|
+
process.stdin.on("data", (c) => {
|
|
2449
|
+
data += c;
|
|
2450
|
+
});
|
|
2451
|
+
process.stdin.on("end", () => resolve(data));
|
|
2452
|
+
process.stdin.on("error", reject);
|
|
2453
|
+
});
|
|
2454
|
+
}
|
|
2455
|
+
/** `kill(pid, 0)` liveness: EPERM means the process exists but belongs to someone else. */
|
|
2456
|
+
function isProcessAlive(pid) {
|
|
2457
|
+
try {
|
|
2458
|
+
process.kill(pid, 0);
|
|
2459
|
+
return true;
|
|
2460
|
+
} catch (e) {
|
|
2461
|
+
return e.code === "EPERM";
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
function createHookCtx() {
|
|
2465
|
+
const launcherPaths = process.argv[1] ? [process.argv[1]] : [];
|
|
2466
|
+
return {
|
|
2467
|
+
dataDir: dataDir(process.platform, process.env, homedir()),
|
|
2468
|
+
adapters: [
|
|
2469
|
+
claudeAdapter,
|
|
2470
|
+
codexAdapter,
|
|
2471
|
+
opencodeAdapter,
|
|
2472
|
+
cursorAdapter,
|
|
2473
|
+
copilotAdapter,
|
|
2474
|
+
antigravityAdapter,
|
|
2475
|
+
grokAdapter
|
|
2476
|
+
],
|
|
2477
|
+
out: (s) => void process.stdout.write(s),
|
|
2478
|
+
err: (s) => void process.stderr.write(s),
|
|
2479
|
+
readStdin: readAllStdin,
|
|
2480
|
+
connect,
|
|
2481
|
+
ancestry: (timeoutMs) => readAncestry({
|
|
2482
|
+
timeoutMs,
|
|
2483
|
+
launcherPaths
|
|
2484
|
+
}),
|
|
2485
|
+
hostLookup: {
|
|
2486
|
+
ppid: process.ppid,
|
|
2487
|
+
launcherPaths
|
|
2488
|
+
},
|
|
2489
|
+
isAlive: isProcessAlive,
|
|
2490
|
+
hookTimeoutMs: 2e3,
|
|
2491
|
+
...process.env.CONVENO_HOOK_TIMING_LOG ? {
|
|
2492
|
+
timingLog: process.env.CONVENO_HOOK_TIMING_LOG,
|
|
2493
|
+
uptimeMs: () => process.uptime() * 1e3
|
|
2494
|
+
} : {}
|
|
2495
|
+
};
|
|
2496
|
+
}
|
|
2497
|
+
function runHookEntry(argv) {
|
|
2498
|
+
return runHook(createHookCtx(), argv);
|
|
2499
|
+
}
|
|
2500
|
+
export { opencodeAdapter as a, claudeAdapter as c, runHookEntry as i, isProcessAlive as n, cursorAdapter as o, readAllStdin as r, copilotAdapter as s, createHookCtx as t };
|