@conveno/cli 0.2.0-rc.4 → 0.2.0-rc.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -29
- package/dist/acp-3xehqLdo.js +82 -0
- package/dist/args-D9T-6TDw.js +315 -0
- package/dist/bin.js +2 -2
- package/dist/{ctx-CDLE-2f2.js → ctx-tYftvhz_.js} +2 -3
- package/dist/daemon.js +361 -1203
- package/dist/daemonError-CdLataBW.js +66 -0
- package/dist/{dist-CuStS_nO.js → dist-BAlMjYqQ.js} +39 -148
- package/dist/{dist-DUqXHTRg.js → dist-BTLBO1Rp.js} +373 -1130
- package/dist/{dist-CiE50AoI.js → dist-BYVibI3a.js} +4 -17
- package/dist/{dist-CfwMkSGH.js → dist-CNyzLyZh.js} +161 -1554
- package/dist/{dist-BmpWfYuM.js → dist-DIAtMDWW.js} +1 -1
- package/dist/dist-LkcRvVjE.js +449 -0
- package/dist/{doctor-Bckon1ju.js → doctor-DjwXJvKw.js} +26 -94
- package/dist/fmt-C2SsP5Y0.js +96 -0
- package/dist/{hook-DUMp43Xn.js → hook-BGJc4PHG.js} +2 -4
- package/dist/hook-entry-BWWJS7n3.js +2622 -0
- package/dist/hook-entry-rDISaMgP.js +1 -0
- package/dist/main-CRw-fISR.js +971 -0
- package/dist/pick-B-18E4Mx.js +9 -0
- package/dist/{run-BEhIahUS.js → run-Yi48fiJN.js} +286 -1667
- package/dist/{runtime-BS-SUGVR.js → runtime-DyknkzAS.js} +136 -209
- package/dist/sidecar-CTKxOMie.js +98 -0
- package/dist/watch-CfYanJvt.js +109 -0
- package/package.json +15 -15
- package/dist/acp-Bs2yS0Qg.js +0 -142
- package/dist/args-DEYV4Ran.js +0 -517
- package/dist/dist-DcmKjrmu.js +0 -271
- package/dist/hook-entry-C-HTnddc.js +0 -1289
- package/dist/hook-entry-DP6eq6qr.js +0 -1
- package/dist/main-ByyF0srt.js +0 -1448
|
@@ -0,0 +1,2622 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { t as antigravityAdapter } from "./dist-LkcRvVjE.js";
|
|
3
|
+
import { isAbsolute, join } from "node:path";
|
|
4
|
+
import { $ as loadJson$1, Et as requeueMessages, Gt as waitForWorkBatch, I as dropFromList, It as startTurnContext, L as editJson$1, Mt as sameJson$1, V as existedBefore, Wt as waitForWork, X as isObject$1, _t as readAncestry, a as FROM_USER_NOTICE, at as parseCliVersion, c as ORCHESTRATOR_TASK_NOTICE, ht as putInList, j as dataDir, lt as pendingHookContext, rt as ownSession, s as NOT_FROM_USER_NOTICE, z as endTurnContinuation } from "./dist-BTLBO1Rp.js";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { applyEdits, modify, parse, printParseErrorCode } from "jsonc-parser";
|
|
7
|
+
import { n as Za, r as cs, t as codexAdapter } from "./dist-CNyzLyZh.js";
|
|
8
|
+
import { n as connect } from "./dist-BYVibI3a.js";
|
|
9
|
+
import { t as runHook } from "./hook-BGJc4PHG.js";
|
|
10
|
+
// ../adapters/claude/dist/index.js
|
|
11
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
12
|
+
/** Read a JSON object file. Missing or blank files give `{}`; anything else that is not a JSON object throws. */
|
|
13
|
+
async function loadJson(path) {
|
|
14
|
+
let raw;
|
|
15
|
+
try {
|
|
16
|
+
raw = await readFile(path, "utf8");
|
|
17
|
+
} catch (err) {
|
|
18
|
+
if (err.code === "ENOENT") raw = null;
|
|
19
|
+
else throw new Error(`Cannot read ${path}: ${err.message}. Check its permissions.`);
|
|
20
|
+
}
|
|
21
|
+
if (raw === null || raw.trim() === "") return {
|
|
22
|
+
raw,
|
|
23
|
+
value: {},
|
|
24
|
+
indent: 2,
|
|
25
|
+
trailingNewline: true
|
|
26
|
+
};
|
|
27
|
+
let value;
|
|
28
|
+
try {
|
|
29
|
+
value = JSON.parse(raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw);
|
|
30
|
+
} catch (err) {
|
|
31
|
+
throw new Error(`${path} is not valid JSON (${err.message}). Fix or remove the file, then run the install again. Nothing was changed.`);
|
|
32
|
+
}
|
|
33
|
+
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.`);
|
|
34
|
+
return {
|
|
35
|
+
raw,
|
|
36
|
+
value,
|
|
37
|
+
indent: detectIndent(raw),
|
|
38
|
+
trailingNewline: raw.endsWith("\n")
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function detectIndent(raw) {
|
|
42
|
+
const m = /^([ \t]+)\S/m.exec(raw);
|
|
43
|
+
if (!m?.[1]) return 2;
|
|
44
|
+
return m[1].startsWith(" ") ? " " : m[1].length;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Apply edits to the file's own text. Only the touched keys change: other keys, duplicate keys,
|
|
48
|
+
* escapes, key order and line endings stay as they were, byte for byte.
|
|
49
|
+
*/
|
|
50
|
+
function editJson(file, edits) {
|
|
51
|
+
const bom = file.raw?.charCodeAt(0) === 65279;
|
|
52
|
+
let text = file.raw === null || file.raw.trim() === "" ? "{}\n" : file.raw;
|
|
53
|
+
if (bom) text = text.slice(1);
|
|
54
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
55
|
+
const formattingOptions = {
|
|
56
|
+
insertSpaces: file.indent !== " ",
|
|
57
|
+
tabSize: typeof file.indent === "number" ? file.indent : 2,
|
|
58
|
+
eol
|
|
59
|
+
};
|
|
60
|
+
for (const e of edits) text = applyEdits(text, modify(text, e.path, e.value, { formattingOptions }));
|
|
61
|
+
return (bom ? "" : "") + text;
|
|
62
|
+
}
|
|
63
|
+
const SERVER_NAME$4 = "conveno";
|
|
64
|
+
/** Claude Code events Conveno installs hooks for. */
|
|
65
|
+
const HOOK_EVENTS$3 = [
|
|
66
|
+
"SessionStart",
|
|
67
|
+
"UserPromptSubmit",
|
|
68
|
+
"Stop"
|
|
69
|
+
];
|
|
70
|
+
/** Older versions also installed a PermissionRequest hook; uninstall still removes it. */
|
|
71
|
+
const LEGACY_HOOK_EVENTS = ["PermissionRequest"];
|
|
72
|
+
/** The background listener's `conveno hook claude <arg>`. It is armed on SessionStart and Stop. */
|
|
73
|
+
const LISTEN_EVENT$1 = "Listen";
|
|
74
|
+
/**
|
|
75
|
+
* Seconds. Claude Code kills a hook at its `timeout` (SIGTERM, exit 143, which wakes nothing) and
|
|
76
|
+
* does not cap the value for a local command hook (checked in Claude Code 2.1.332: the schema is
|
|
77
|
+
* `timeout: positive().optional()` and the runner arms `setTimeout(timeout * 1000)`). An idle
|
|
78
|
+
* session must stay wakeable for as long as it is open, so one armed listener waits 20 days. That
|
|
79
|
+
* stays under the largest timer delay (2^31 - 1 ms, about 24.8 days); a longer one fires at once.
|
|
80
|
+
* Every SessionStart and Stop arms a fresh listener, which replaces the old.
|
|
81
|
+
*/
|
|
82
|
+
const LISTEN_TIMEOUT_SECONDS = 1728e3;
|
|
83
|
+
/** The listener gives up on its own a few minutes before Claude Code's timeout, so it exits 0 instead of being killed. */
|
|
84
|
+
const LISTEN_MAX_MS$1 = 17277e5;
|
|
85
|
+
/**
|
|
86
|
+
* A listener armed on SessionStart can start before Claude Code's MCP server registered the
|
|
87
|
+
* session. It looks for its session this long before it gives up.
|
|
88
|
+
*/
|
|
89
|
+
const LISTEN_REGISTER_WAIT_MS = 12e4;
|
|
90
|
+
/**
|
|
91
|
+
* Claude Code shows the stderr of a waking hook after its own "Stop hook blocking error from
|
|
92
|
+
* command" prefix. This first line tells the model what the text is.
|
|
93
|
+
*/
|
|
94
|
+
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.";
|
|
95
|
+
/** The handlers Conveno wants on each event, in order: the hook itself, then a listener where one is armed. */
|
|
96
|
+
const HANDLERS = {
|
|
97
|
+
SessionStart: ["SessionStart", LISTEN_EVENT$1],
|
|
98
|
+
UserPromptSubmit: ["UserPromptSubmit"],
|
|
99
|
+
Stop: ["Stop", LISTEN_EVENT$1]
|
|
100
|
+
};
|
|
101
|
+
const EMPTY$4 = {
|
|
102
|
+
stdout: "",
|
|
103
|
+
exitCode: 0
|
|
104
|
+
};
|
|
105
|
+
/** `~/.claude.json` holds user-scope MCP servers; settings.json holds hooks. Both honor CLAUDE_CONFIG_DIR. */
|
|
106
|
+
function paths$2(env) {
|
|
107
|
+
const dir = env.env.CLAUDE_CONFIG_DIR;
|
|
108
|
+
if (dir) return {
|
|
109
|
+
mcp: join(dir, ".claude.json"),
|
|
110
|
+
settings: join(dir, "settings.json")
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
mcp: join(env.home, ".claude.json"),
|
|
114
|
+
settings: join(env.home, ".claude", "settings.json")
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Quote one word of a hook command for the shell Claude Code runs it in. On Windows that is Git
|
|
119
|
+
* Bash (PowerShell only when Git Bash is not installed), so the word is written for bash. Windows
|
|
120
|
+
* paths use forward slashes there: bash would read `\P` inside double quotes as an escape, and
|
|
121
|
+
* Windows accepts `/` in every API Node and Git Bash use, so `C:/Program Files/nodejs/node.exe`
|
|
122
|
+
* means the same file and needs no escaping.
|
|
123
|
+
*/
|
|
124
|
+
function quoteHookWord$1(arg, platform) {
|
|
125
|
+
const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
|
|
126
|
+
return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
|
|
127
|
+
}
|
|
128
|
+
const hookCommand$2 = (env, event) => [
|
|
129
|
+
...env.conveno.command,
|
|
130
|
+
"hook",
|
|
131
|
+
"claude",
|
|
132
|
+
event
|
|
133
|
+
].map((w) => quoteHookWord$1(w, env.platform)).join(" ");
|
|
134
|
+
/** One hook handler as written to settings.json. The listener runs in the background (`asyncRewake`). */
|
|
135
|
+
function handlerFor(env, arg) {
|
|
136
|
+
const command = hookCommand$2(env, arg);
|
|
137
|
+
return arg === "Listen" ? {
|
|
138
|
+
type: "command",
|
|
139
|
+
command,
|
|
140
|
+
asyncRewake: true,
|
|
141
|
+
timeout: LISTEN_TIMEOUT_SECONDS
|
|
142
|
+
} : {
|
|
143
|
+
type: "command",
|
|
144
|
+
command,
|
|
145
|
+
timeout: 5
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
const mcpArgs$2 = (env) => [
|
|
149
|
+
...env.conveno.command,
|
|
150
|
+
"mcp",
|
|
151
|
+
"--cli",
|
|
152
|
+
"claude"
|
|
153
|
+
];
|
|
154
|
+
const desiredServer$2 = (env) => {
|
|
155
|
+
const [command = "conveno", ...args] = mcpArgs$2(env);
|
|
156
|
+
return {
|
|
157
|
+
type: "stdio",
|
|
158
|
+
command,
|
|
159
|
+
args,
|
|
160
|
+
env: {}
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
/** Recognizes our hook command even if the conveno path changed since install. */
|
|
164
|
+
const isOurHookCommand$2 = (cmd) => typeof cmd === "string" && /(^|\s)hook claude (SessionStart|UserPromptSubmit|Stop|Listen|PermissionRequest)$/.test(cmd.trim());
|
|
165
|
+
const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
166
|
+
function groupsOf(hooks, event) {
|
|
167
|
+
const g = hooks[event];
|
|
168
|
+
return Array.isArray(g) ? g : [];
|
|
169
|
+
}
|
|
170
|
+
function hasExactHook$2(hooks, event, handler) {
|
|
171
|
+
return groupsOf(hooks, event).some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => sameJson(h, handler)));
|
|
172
|
+
}
|
|
173
|
+
/** Every handler Conveno wants on `event` is there, exactly. */
|
|
174
|
+
const eventComplete = (env, hooks, event) => HANDLERS[event].every((arg) => hasExactHook$2(hooks, event, handlerFor(env, arg)));
|
|
175
|
+
/** The name `conveno doctor --verbose` shows for one event. Start and Stop also arm the listener. */
|
|
176
|
+
const hookPartName = (e) => HANDLERS[e].includes("Listen") ? `${e} hook and listener` : `${e} hook`;
|
|
177
|
+
const hasOurHandler = (g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject(h) && isOurHookCommand$2(h.command));
|
|
178
|
+
/** Drop our hook handlers (and groups left empty by that). */
|
|
179
|
+
function stripOurHooks(groups) {
|
|
180
|
+
const out = [];
|
|
181
|
+
for (const g of groups) {
|
|
182
|
+
if (!isObject(g) || !Array.isArray(g.hooks)) {
|
|
183
|
+
out.push(g);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const kept = g.hooks.filter((h) => !(isObject(h) && isOurHookCommand$2(h.command)));
|
|
187
|
+
if (kept.length === g.hooks.length) out.push(g);
|
|
188
|
+
else if (kept.length > 0) out.push({
|
|
189
|
+
...g,
|
|
190
|
+
hooks: kept
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
function hooksObject$2(settings, path) {
|
|
196
|
+
const h = settings.hooks;
|
|
197
|
+
if (h === void 0) return {};
|
|
198
|
+
if (!isObject(h)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
|
|
199
|
+
return h;
|
|
200
|
+
}
|
|
201
|
+
function mcpObject$2(config, path) {
|
|
202
|
+
const s = config.mcpServers;
|
|
203
|
+
if (s === void 0) return {};
|
|
204
|
+
if (!isObject(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
|
|
205
|
+
return s;
|
|
206
|
+
}
|
|
207
|
+
async function detect$4(env) {
|
|
208
|
+
const p = paths$2(env);
|
|
209
|
+
const configPaths = [p.mcp, p.settings];
|
|
210
|
+
try {
|
|
211
|
+
const r = await env.exec("claude", ["--version"]);
|
|
212
|
+
if (r.code !== 0) return {
|
|
213
|
+
installed: false,
|
|
214
|
+
configPaths
|
|
215
|
+
};
|
|
216
|
+
const version = parseCliVersion(r.stdout);
|
|
217
|
+
return {
|
|
218
|
+
installed: true,
|
|
219
|
+
binary: "claude",
|
|
220
|
+
...version ? { version } : {},
|
|
221
|
+
configPaths
|
|
222
|
+
};
|
|
223
|
+
} catch {
|
|
224
|
+
return {
|
|
225
|
+
installed: false,
|
|
226
|
+
configPaths
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/** `A`, `A and B`, `A, B and C`. */
|
|
231
|
+
const listed = (words) => words.length < 2 ? words[0] ?? "" : `${words.slice(0, -1).join(", ")} and ${words.at(-1)}`;
|
|
232
|
+
async function plan$4(env) {
|
|
233
|
+
const p = paths$2(env);
|
|
234
|
+
const changes = [];
|
|
235
|
+
const mcpFile = await loadJson(p.mcp);
|
|
236
|
+
const servers = mcpObject$2(mcpFile.value, p.mcp);
|
|
237
|
+
const want = desiredServer$2(env);
|
|
238
|
+
if (!sameJson(servers["conveno"], want)) {
|
|
239
|
+
const after = editJson(mcpFile, [{
|
|
240
|
+
path: ["mcpServers", SERVER_NAME$4],
|
|
241
|
+
value: want
|
|
242
|
+
}]);
|
|
243
|
+
changes.push({
|
|
244
|
+
component: "mcp",
|
|
245
|
+
kind: servers["conveno"] === void 0 ? "add" : "update",
|
|
246
|
+
path: p.mcp,
|
|
247
|
+
before: mcpFile.raw,
|
|
248
|
+
after,
|
|
249
|
+
parts: [{
|
|
250
|
+
name: "MCP server",
|
|
251
|
+
kind: servers["conveno"] === void 0 ? "add" : "update"
|
|
252
|
+
}],
|
|
253
|
+
description: `Register the "${SERVER_NAME$4}" MCP server at user scope (conveno mcp --cli claude).`,
|
|
254
|
+
viaCommand: [
|
|
255
|
+
"claude",
|
|
256
|
+
"mcp",
|
|
257
|
+
"add",
|
|
258
|
+
"--scope",
|
|
259
|
+
"user",
|
|
260
|
+
SERVER_NAME$4,
|
|
261
|
+
"--",
|
|
262
|
+
...mcpArgs$2(env)
|
|
263
|
+
]
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
const setFile = await loadJson(p.settings);
|
|
267
|
+
const hooks = hooksObject$2(setFile.value, p.settings);
|
|
268
|
+
const missing = HOOK_EVENTS$3.filter((e) => !eventComplete(env, hooks, e));
|
|
269
|
+
if (missing.length > 0) {
|
|
270
|
+
const next = { ...hooks };
|
|
271
|
+
for (const e of missing) next[e] = [...stripOurHooks(groupsOf(hooks, e)), ...HANDLERS[e].map((arg) => ({ hooks: [handlerFor(env, arg)] }))];
|
|
272
|
+
const installed = [...HOOK_EVENTS$3, ...LEGACY_HOOK_EVENTS].some((e) => groupsOf(hooks, e).some((g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject(h) && isOurHookCommand$2(h.command))));
|
|
273
|
+
changes.push({
|
|
274
|
+
component: "hooks",
|
|
275
|
+
kind: installed ? "update" : "add",
|
|
276
|
+
parts: missing.map((e) => ({
|
|
277
|
+
name: hookPartName(e),
|
|
278
|
+
kind: groupsOf(hooks, e).some(hasOurHandler) ? "update" : "add"
|
|
279
|
+
})),
|
|
280
|
+
path: p.settings,
|
|
281
|
+
before: setFile.raw,
|
|
282
|
+
after: editJson(setFile, missing.map((e) => ({
|
|
283
|
+
path: ["hooks", e],
|
|
284
|
+
value: next[e]
|
|
285
|
+
}))),
|
|
286
|
+
description: `Add Conveno's ${listed(missing)} hooks to Claude Code. They deliver messages at the next prompt and, at the end of a turn or by waking an idle session through a background listener.`
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
return changes;
|
|
290
|
+
}
|
|
291
|
+
async function uninstallPlan$4(env) {
|
|
292
|
+
const p = paths$2(env);
|
|
293
|
+
const changes = [];
|
|
294
|
+
const mcpFile = await loadJson(p.mcp);
|
|
295
|
+
if ("conveno" in mcpObject$2(mcpFile.value, p.mcp)) changes.push({
|
|
296
|
+
component: "mcp",
|
|
297
|
+
kind: "remove",
|
|
298
|
+
path: p.mcp,
|
|
299
|
+
before: mcpFile.raw,
|
|
300
|
+
after: editJson(mcpFile, [{
|
|
301
|
+
path: ["mcpServers", SERVER_NAME$4],
|
|
302
|
+
value: void 0
|
|
303
|
+
}]),
|
|
304
|
+
description: `Remove the "${SERVER_NAME$4}" MCP server from user scope.`,
|
|
305
|
+
viaCommand: [
|
|
306
|
+
"claude",
|
|
307
|
+
"mcp",
|
|
308
|
+
"remove",
|
|
309
|
+
"--scope",
|
|
310
|
+
"user",
|
|
311
|
+
SERVER_NAME$4
|
|
312
|
+
]
|
|
313
|
+
});
|
|
314
|
+
const setFile = await loadJson(p.settings);
|
|
315
|
+
const hooks = hooksObject$2(setFile.value, p.settings);
|
|
316
|
+
const next = { ...hooks };
|
|
317
|
+
const edits = [];
|
|
318
|
+
for (const e of [...HOOK_EVENTS$3, ...LEGACY_HOOK_EVENTS]) {
|
|
319
|
+
const groups = groupsOf(hooks, e);
|
|
320
|
+
const stripped = stripOurHooks(groups);
|
|
321
|
+
if (sameJson(groups, stripped)) continue;
|
|
322
|
+
if (stripped.length > 0) next[e] = stripped;
|
|
323
|
+
else delete next[e];
|
|
324
|
+
edits.push({
|
|
325
|
+
path: ["hooks", e],
|
|
326
|
+
value: stripped.length > 0 ? stripped : void 0
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
if (edits.length > 0) {
|
|
330
|
+
if (Object.keys(next).length === 0) edits.push({
|
|
331
|
+
path: ["hooks"],
|
|
332
|
+
value: void 0
|
|
333
|
+
});
|
|
334
|
+
changes.push({
|
|
335
|
+
component: "hooks",
|
|
336
|
+
kind: "remove",
|
|
337
|
+
path: p.settings,
|
|
338
|
+
before: setFile.raw,
|
|
339
|
+
after: editJson(setFile, edits),
|
|
340
|
+
description: "Remove the Conveno SessionStart, UserPromptSubmit, and Stop hooks and the listener."
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
return changes;
|
|
344
|
+
}
|
|
345
|
+
/** `stop_hook_active` from the Stop input: Claude Code is already continuing because of a Stop hook. */
|
|
346
|
+
const stopHookActive = (input) => isObject(input) && input.stop_hook_active === true;
|
|
347
|
+
/**
|
|
348
|
+
* Never throws: any failure means "deliver nothing this time".
|
|
349
|
+
*
|
|
350
|
+
* - SessionStart: waiting messages as `additionalContext`.
|
|
351
|
+
* - UserPromptSubmit: the turn starts (the session is busy), waiting messages as `additionalContext`.
|
|
352
|
+
* - Stop: with messages waiting, `decision: "block"` with the framed messages as
|
|
353
|
+
* `reason`, so Claude continues with them. When `stop_hook_active` is set (Claude is already
|
|
354
|
+
* continuing because of a Stop hook) it never blocks; it only records that the turn ended, and the
|
|
355
|
+
* listener armed on this Stop wakes the session with what waits, as a new turn.
|
|
356
|
+
* - Listen: the background listener (`asyncRewake`). Waits for its session to register, then for
|
|
357
|
+
* work, and exits 2 with the framed messages on stderr (after `WAKE_LEAD`), which wakes Claude
|
|
358
|
+
* even when the session is idle. Exit 0, silent, when it stops for any other reason, and at once
|
|
359
|
+
* in `claude -p` (`CLAUDE_CODE_ENTRYPOINT=sdk-cli`). A batch taken just as Claude Code exited is
|
|
360
|
+
* requeued.
|
|
361
|
+
*/
|
|
362
|
+
async function hook$4(event, input, ctx) {
|
|
363
|
+
switch (event) {
|
|
364
|
+
case "SessionStart":
|
|
365
|
+
case "UserPromptSubmit": {
|
|
366
|
+
const additionalContext = await (event === "SessionStart" ? pendingHookContext(ctx) : startTurnContext(ctx));
|
|
367
|
+
if (additionalContext === null) return EMPTY$4;
|
|
368
|
+
return {
|
|
369
|
+
stdout: JSON.stringify({ hookSpecificOutput: {
|
|
370
|
+
hookEventName: event,
|
|
371
|
+
additionalContext
|
|
372
|
+
} }),
|
|
373
|
+
exitCode: 0
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
case "Stop": {
|
|
377
|
+
const reason = await endTurnContinuation(ctx, { allowContinue: !stopHookActive(input) });
|
|
378
|
+
if (reason === null) return EMPTY$4;
|
|
379
|
+
return {
|
|
380
|
+
stdout: JSON.stringify({
|
|
381
|
+
decision: "block",
|
|
382
|
+
reason
|
|
383
|
+
}),
|
|
384
|
+
exitCode: 0
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
case LISTEN_EVENT$1: {
|
|
388
|
+
if (process.env.CLAUDE_CODE_ENTRYPOINT === "sdk-cli") return EMPTY$4;
|
|
389
|
+
const r = await waitForWorkBatch(ctx, {
|
|
390
|
+
maxMs: LISTEN_MAX_MS$1,
|
|
391
|
+
registerWaitMs: LISTEN_REGISTER_WAIT_MS
|
|
392
|
+
});
|
|
393
|
+
if (r === null) return EMPTY$4;
|
|
394
|
+
if (ctx.isAlive && !ctx.isAlive(ctx.hostPid)) {
|
|
395
|
+
await requeueMessages(ctx.client, r.sessionId, r.batch.messages);
|
|
396
|
+
return EMPTY$4;
|
|
397
|
+
}
|
|
398
|
+
return {
|
|
399
|
+
stdout: "",
|
|
400
|
+
stderr: `${WAKE_LEAD}\n\n${r.batch.text}`,
|
|
401
|
+
exitCode: 2
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
default: return EMPTY$4;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const delivery$1 = () => ({
|
|
408
|
+
nextTurn: true,
|
|
409
|
+
endOfTurn: true,
|
|
410
|
+
idleWake: true
|
|
411
|
+
});
|
|
412
|
+
const claudeAdapter = {
|
|
413
|
+
cli: "claude",
|
|
414
|
+
displayName: "Claude Code",
|
|
415
|
+
deliveryTier: "next_turn",
|
|
416
|
+
detect: detect$4,
|
|
417
|
+
plan: plan$4,
|
|
418
|
+
uninstallPlan: uninstallPlan$4,
|
|
419
|
+
hook: hook$4,
|
|
420
|
+
listenEvents: [LISTEN_EVENT$1],
|
|
421
|
+
delivery: delivery$1
|
|
422
|
+
};
|
|
423
|
+
// ../adapters/copilot/dist/index.js
|
|
424
|
+
const EXTENSION_MARKER = `// conveno-extension: 1`;
|
|
425
|
+
/** Plain JavaScript source with the conveno command baked in. No imports beyond Node built-ins and the SDK. */
|
|
426
|
+
function extensionSource(command) {
|
|
427
|
+
return `${EXTENSION_MARKER}
|
|
428
|
+
// Conveno extension for GitHub Copilot CLI. Written by \`conveno init\`; \`conveno uninstall\` removes it.
|
|
429
|
+
// It wakes an idle session when a Conveno message arrives. See https://conveno.dev.
|
|
430
|
+
import { spawn } from "node:child_process";
|
|
431
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
432
|
+
import { dirname, join } from "node:path";
|
|
433
|
+
import { joinSession } from "@github/copilot-sdk/extension";
|
|
434
|
+
|
|
435
|
+
const COMMAND = ${JSON.stringify(command)};
|
|
436
|
+
// A listener that ends without a message (daemon not up yet, superseded) is retried after this long.
|
|
437
|
+
const RETRY_MS = 30000;
|
|
438
|
+
|
|
439
|
+
// A bare \`conveno\` on Windows is an npm .cmd shim. Run its node entry directly, so no shell is involved
|
|
440
|
+
// and killing the child kills the listener. Only if the shim cannot be read is a shell used.
|
|
441
|
+
const resolveCommand = () => {
|
|
442
|
+
const [file, ...args] = COMMAND;
|
|
443
|
+
if (process.platform !== "win32" || /\\.exe$/i.test(file)) return { file, args, shell: false };
|
|
444
|
+
try {
|
|
445
|
+
const dirs = /[\\/]/.test(file) ? [""] : (process.env.PATH ?? "").split(";");
|
|
446
|
+
for (const dir of dirs) {
|
|
447
|
+
const shim = join(dir, /\\.cmd$/i.test(file) ? file : file + ".cmd");
|
|
448
|
+
if (!existsSync(shim)) continue;
|
|
449
|
+
const m = /"%(?:~dp0|dp0%)\\?([^"%]*\\.[cm]?js)"/i.exec(readFileSync(shim, "utf8"));
|
|
450
|
+
if (m) return { file: process.execPath, args: [join(dirname(shim), m[1]), ...args], shell: false };
|
|
451
|
+
}
|
|
452
|
+
} catch {}
|
|
453
|
+
return { file, args, shell: true };
|
|
454
|
+
};
|
|
455
|
+
const RESOLVED = resolveCommand();
|
|
456
|
+
|
|
457
|
+
const run = (extra, stdio) =>
|
|
458
|
+
spawn(RESOLVED.file, [...RESOLVED.args, ...extra], { stdio, shell: RESOLVED.shell, windowsHide: true });
|
|
459
|
+
|
|
460
|
+
// With a shell on Windows, child.kill() only ends cmd.exe and orphans the listener: kill the whole tree.
|
|
461
|
+
const kill = (child) => {
|
|
462
|
+
if (process.platform === "win32" && RESOLVED.shell && child.pid) {
|
|
463
|
+
const t = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
464
|
+
t.once("error", () => child.kill());
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
child.kill();
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
const session = await joinSession({});
|
|
471
|
+
|
|
472
|
+
// Listen's output: "#conveno-ids <id>,<id>" on the first line, then the prompt.
|
|
473
|
+
const split = (out) => {
|
|
474
|
+
const m = /^#conveno-ids ([^\\n]*)\\n/.exec(out);
|
|
475
|
+
if (!m) return { ids: [], text: out.trim() };
|
|
476
|
+
return { ids: m[1].split(",").filter(Boolean), text: out.slice(m[0].length).trim() };
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
const requeue = (ids) =>
|
|
480
|
+
new Promise((resolve) => {
|
|
481
|
+
if (ids.length === 0) return resolve();
|
|
482
|
+
const child = run(["hook", "copilot", "Requeue"], ["pipe", "ignore", "ignore"]);
|
|
483
|
+
child.once("error", () => resolve());
|
|
484
|
+
child.once("close", () => resolve());
|
|
485
|
+
child.stdin.on("error", () => {});
|
|
486
|
+
child.stdin.end(JSON.stringify({ hook_event_name: "Requeue", sessionId: session.sessionId, ids }));
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
let busy = false;
|
|
490
|
+
let listener;
|
|
491
|
+
let retry;
|
|
492
|
+
|
|
493
|
+
const stop = () => {
|
|
494
|
+
clearTimeout(retry);
|
|
495
|
+
retry = undefined;
|
|
496
|
+
if (!listener) return;
|
|
497
|
+
const child = listener;
|
|
498
|
+
listener = undefined;
|
|
499
|
+
kill(child);
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
const send = async (text) => {
|
|
503
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
504
|
+
try {
|
|
505
|
+
await session.send({ prompt: text, mode: "enqueue" });
|
|
506
|
+
return true;
|
|
507
|
+
} catch {
|
|
508
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
return false;
|
|
512
|
+
};
|
|
513
|
+
|
|
514
|
+
const arm = () => {
|
|
515
|
+
if (busy || listener) return;
|
|
516
|
+
const child = run(["hook", "copilot", "Listen"], ["pipe", "pipe", "ignore"]);
|
|
517
|
+
listener = child;
|
|
518
|
+
let out = "";
|
|
519
|
+
let ended = false;
|
|
520
|
+
child.stdout.setEncoding("utf8");
|
|
521
|
+
child.stdout.on("data", (chunk) => {
|
|
522
|
+
out += chunk;
|
|
523
|
+
});
|
|
524
|
+
child.stdin.on("error", () => {});
|
|
525
|
+
child.stdin.end(JSON.stringify({ hook_event_name: "Listen", sessionId: session.sessionId }));
|
|
526
|
+
const finish = async (code) => {
|
|
527
|
+
if (ended) return;
|
|
528
|
+
ended = true;
|
|
529
|
+
const current = listener === child;
|
|
530
|
+
if (current) listener = undefined;
|
|
531
|
+
const { ids, text } = split(out);
|
|
532
|
+
// Whenever the output is not sent (stopped by a user turn, failed exit, busy), the daemon has
|
|
533
|
+
// already handed these messages over, so put them back.
|
|
534
|
+
if (!current || code !== 0 || !text || busy) {
|
|
535
|
+
await requeue(ids);
|
|
536
|
+
if (current && !busy && !listener) retry = setTimeout(arm, RETRY_MS);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
busy = true;
|
|
540
|
+
if (!(await send(text))) {
|
|
541
|
+
await requeue(ids);
|
|
542
|
+
busy = false;
|
|
543
|
+
retry = setTimeout(arm, RETRY_MS);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
child.once("error", () => void finish(1));
|
|
547
|
+
child.once("close", (code) => void finish(code));
|
|
548
|
+
};
|
|
549
|
+
|
|
550
|
+
session.on("user.message", () => {
|
|
551
|
+
busy = true;
|
|
552
|
+
stop();
|
|
553
|
+
});
|
|
554
|
+
session.on("assistant.turn_start", () => {
|
|
555
|
+
busy = true;
|
|
556
|
+
stop();
|
|
557
|
+
});
|
|
558
|
+
session.on("session.idle", () => {
|
|
559
|
+
busy = false;
|
|
560
|
+
arm();
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
const quit = () => {
|
|
564
|
+
stop();
|
|
565
|
+
process.exit(0);
|
|
566
|
+
};
|
|
567
|
+
process.once("SIGTERM", quit);
|
|
568
|
+
process.once("SIGINT", quit);
|
|
569
|
+
process.once("disconnect", quit);
|
|
570
|
+
|
|
571
|
+
arm();
|
|
572
|
+
`;
|
|
573
|
+
}
|
|
574
|
+
const SERVER_NAME$3 = "conveno";
|
|
575
|
+
/**
|
|
576
|
+
* `sessionStart` and `userPromptSubmitted` add context for the model; `postToolUse` adds waiting
|
|
577
|
+
* messages in the middle of a turn; `preToolUse` allows Conveno's own MCP tools without a prompt;
|
|
578
|
+
* `agentStop` ends a turn and continues with waiting messages.
|
|
579
|
+
*/
|
|
580
|
+
const HOOK_EVENTS$2 = [
|
|
581
|
+
"sessionStart",
|
|
582
|
+
"userPromptSubmitted",
|
|
583
|
+
"preToolUse",
|
|
584
|
+
"postToolUse",
|
|
585
|
+
"agentStop"
|
|
586
|
+
];
|
|
587
|
+
/** The extension's listener: `conveno hook copilot Listen`. Not a Copilot hook event, so not in the hook file. */
|
|
588
|
+
const LISTEN_EVENT = "Listen";
|
|
589
|
+
/** First line of Listen's output: the ids of the handed-over messages. The extension strips it. */
|
|
590
|
+
const IDS_LEAD = "#conveno-ids";
|
|
591
|
+
/** The listener gives up on its own after this long; the extension starts a new one at the next idle. */
|
|
592
|
+
const LISTEN_MAX_MS = 216e5;
|
|
593
|
+
/** Our own hook file inside `~/.copilot/hooks/`, which Copilot reads as every `*.json` there. */
|
|
594
|
+
const HOOK_FILE = "conveno.json";
|
|
595
|
+
const EMPTY$3 = {
|
|
596
|
+
stdout: "",
|
|
597
|
+
exitCode: 0
|
|
598
|
+
};
|
|
599
|
+
/** `COPILOT_HOME` moves every Copilot CLI file; it defaults to `~/.copilot`. */
|
|
600
|
+
function paths$1(env) {
|
|
601
|
+
const dir = env.env.COPILOT_HOME || join(env.home, ".copilot");
|
|
602
|
+
const extDir = join(dir, "extensions", "conveno");
|
|
603
|
+
return {
|
|
604
|
+
mcp: join(dir, "mcp-config.json"),
|
|
605
|
+
hooks: join(dir, "hooks", HOOK_FILE),
|
|
606
|
+
settings: join(dir, "settings.json"),
|
|
607
|
+
extension: join(extDir, "extension.mjs"),
|
|
608
|
+
marker: join(extDir, EXPERIMENTAL_MARKER_FILE)
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Written next to the extension when Conveno turned `experimental` on, so uninstall turns it off
|
|
613
|
+
* again only then. A user who had it on already keeps it.
|
|
614
|
+
*/
|
|
615
|
+
const EXPERIMENTAL_MARKER_FILE = "set-experimental";
|
|
616
|
+
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";
|
|
617
|
+
const SAFE_WORD = /^[A-Za-z0-9_@%+=:,./-]+$/;
|
|
618
|
+
/**
|
|
619
|
+
* Quote one word for the hook's `bash` field: POSIX single quotes. Windows paths use forward
|
|
620
|
+
* slashes, which every shell and Windows API accepts.
|
|
621
|
+
*/
|
|
622
|
+
function bashWord(arg) {
|
|
623
|
+
const word = arg.replace(/\\/g, "/");
|
|
624
|
+
return SAFE_WORD.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
|
|
625
|
+
}
|
|
626
|
+
/** Quote one word for the hook's `powershell` field: single quotes, doubled inside. */
|
|
627
|
+
function powershellWord(arg) {
|
|
628
|
+
const word = arg.replace(/\\/g, "/");
|
|
629
|
+
return SAFE_WORD.test(word) ? word : `'${word.replace(/'/g, "''")}'`;
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* The hook entry. Copilot runs `bash` on macOS and Linux and `powershell` on Windows, and takes
|
|
633
|
+
* the command as one string, so both are written whatever the platform of this install: the file
|
|
634
|
+
* then stays right if the home directory is shared with a Windows machine through WSL.
|
|
635
|
+
*/
|
|
636
|
+
function hookEntry$1(env, event) {
|
|
637
|
+
const words = [
|
|
638
|
+
...env.conveno.command,
|
|
639
|
+
"hook",
|
|
640
|
+
"copilot",
|
|
641
|
+
event
|
|
642
|
+
];
|
|
643
|
+
const ps = words.map(powershellWord);
|
|
644
|
+
const call = /^'/.test(ps[0] ?? "") ? "& " : "";
|
|
645
|
+
return {
|
|
646
|
+
type: "command",
|
|
647
|
+
bash: words.map(bashWord).join(" "),
|
|
648
|
+
powershell: call + ps.join(" "),
|
|
649
|
+
timeoutSec: 5
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
const mcpArgs$1 = (env) => [
|
|
653
|
+
...env.conveno.command,
|
|
654
|
+
"mcp",
|
|
655
|
+
"--cli",
|
|
656
|
+
"copilot"
|
|
657
|
+
];
|
|
658
|
+
/** The same shape `copilot mcp add` writes. */
|
|
659
|
+
const desiredServer$1 = (env) => {
|
|
660
|
+
const [command = "conveno", ...args] = mcpArgs$1(env);
|
|
661
|
+
return {
|
|
662
|
+
tools: ["*"],
|
|
663
|
+
type: "local",
|
|
664
|
+
command,
|
|
665
|
+
args
|
|
666
|
+
};
|
|
667
|
+
};
|
|
668
|
+
/** Recognizes our hook command even if the conveno path changed since install. */
|
|
669
|
+
const isOurCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook copilot (sessionStart|userPromptSubmitted|preToolUse|postToolUse|agentStop)$/.test(cmd.trim());
|
|
670
|
+
const isOurEntry$1 = (e) => isObject$1(e) && [
|
|
671
|
+
e.bash,
|
|
672
|
+
e.powershell,
|
|
673
|
+
e.command
|
|
674
|
+
].some(isOurCommand);
|
|
675
|
+
function entriesOf$1(hooks, event) {
|
|
676
|
+
const g = hooks[event];
|
|
677
|
+
return Array.isArray(g) ? g : [];
|
|
678
|
+
}
|
|
679
|
+
function hasExactHook$1(hooks, event, want) {
|
|
680
|
+
return entriesOf$1(hooks, event).some((e) => isObject$1(e) && e.bash === want.bash && e.powershell === want.powershell);
|
|
681
|
+
}
|
|
682
|
+
function hooksObject$1(file, path) {
|
|
683
|
+
const h = file.hooks;
|
|
684
|
+
if (h === void 0) return {};
|
|
685
|
+
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.`);
|
|
686
|
+
return h;
|
|
687
|
+
}
|
|
688
|
+
function mcpObject$1(config, path) {
|
|
689
|
+
const s = config.mcpServers;
|
|
690
|
+
if (s === void 0) return {};
|
|
691
|
+
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.`);
|
|
692
|
+
return s;
|
|
693
|
+
}
|
|
694
|
+
/** `copilot --version` prints "GitHub Copilot CLI 1.0.117." with a full stop after the number. */
|
|
695
|
+
const versionOf = (stdout) => parseCliVersion(stdout)?.replace(/\.+$/, "");
|
|
696
|
+
async function detect$3(env) {
|
|
697
|
+
const p = paths$1(env);
|
|
698
|
+
const configPaths = [
|
|
699
|
+
p.mcp,
|
|
700
|
+
p.hooks,
|
|
701
|
+
p.settings,
|
|
702
|
+
p.extension
|
|
703
|
+
];
|
|
704
|
+
try {
|
|
705
|
+
const r = await env.exec("copilot", ["--version"]);
|
|
706
|
+
if (r.code !== 0) return {
|
|
707
|
+
installed: false,
|
|
708
|
+
configPaths
|
|
709
|
+
};
|
|
710
|
+
const version = versionOf(r.stdout);
|
|
711
|
+
return {
|
|
712
|
+
installed: true,
|
|
713
|
+
binary: "copilot",
|
|
714
|
+
...version ? { version } : {},
|
|
715
|
+
configPaths
|
|
716
|
+
};
|
|
717
|
+
} catch {
|
|
718
|
+
return {
|
|
719
|
+
installed: false,
|
|
720
|
+
configPaths
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
async function readText$1(path) {
|
|
725
|
+
try {
|
|
726
|
+
return await readFile(path, "utf8");
|
|
727
|
+
} catch (err) {
|
|
728
|
+
if (err.code === "ENOENT") return null;
|
|
729
|
+
throw err;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
/** The extension file, and `experimental` with the marker that says Conveno set it. */
|
|
733
|
+
async function planExtension(env) {
|
|
734
|
+
const p = paths$1(env);
|
|
735
|
+
const changes = [];
|
|
736
|
+
const want = extensionSource(env.conveno.command);
|
|
737
|
+
const before = await readText$1(p.extension);
|
|
738
|
+
if (before !== want) {
|
|
739
|
+
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.`);
|
|
740
|
+
changes.push({
|
|
741
|
+
component: "hooks",
|
|
742
|
+
kind: before === null ? "add" : "update",
|
|
743
|
+
parts: [{
|
|
744
|
+
name: "extension file",
|
|
745
|
+
kind: before === null ? "add" : "update"
|
|
746
|
+
}],
|
|
747
|
+
path: p.extension,
|
|
748
|
+
before,
|
|
749
|
+
after: want,
|
|
750
|
+
description: `${before === null ? "Add" : "Update"} the Conveno extension for Copilot CLI. It wakes an idle session when a message arrives.`
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
const settings = await loadJson$1(p.settings);
|
|
754
|
+
if (settings.value.experimental !== true) {
|
|
755
|
+
changes.push({
|
|
756
|
+
component: "hooks",
|
|
757
|
+
kind: "update",
|
|
758
|
+
parts: [{
|
|
759
|
+
name: "experimental setting",
|
|
760
|
+
kind: "update"
|
|
761
|
+
}],
|
|
762
|
+
path: p.settings,
|
|
763
|
+
before: settings.raw,
|
|
764
|
+
after: editJson$1(settings, [{
|
|
765
|
+
path: ["experimental"],
|
|
766
|
+
value: true
|
|
767
|
+
}]),
|
|
768
|
+
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."
|
|
769
|
+
});
|
|
770
|
+
if (await readText$1(p.marker) === null) changes.push({
|
|
771
|
+
component: "hooks",
|
|
772
|
+
kind: "add",
|
|
773
|
+
parts: [{
|
|
774
|
+
name: "experimental marker",
|
|
775
|
+
kind: "add"
|
|
776
|
+
}],
|
|
777
|
+
path: p.marker,
|
|
778
|
+
before: null,
|
|
779
|
+
after: MARKER_TEXT,
|
|
780
|
+
description: "Note that Conveno turned on experimental mode, so uninstall turns it off again."
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
return changes;
|
|
784
|
+
}
|
|
785
|
+
async function uninstallExtension(env, baseline) {
|
|
786
|
+
const p = paths$1(env);
|
|
787
|
+
const changes = [];
|
|
788
|
+
const ext = await readText$1(p.extension);
|
|
789
|
+
if (ext?.startsWith("// conveno-extension:")) changes.push({
|
|
790
|
+
component: "hooks",
|
|
791
|
+
kind: "remove",
|
|
792
|
+
path: p.extension,
|
|
793
|
+
before: ext,
|
|
794
|
+
after: "",
|
|
795
|
+
deleteFile: true,
|
|
796
|
+
pruneEmptyDir: true,
|
|
797
|
+
description: "Remove the Conveno extension for Copilot CLI."
|
|
798
|
+
});
|
|
799
|
+
const marker = await readText$1(p.marker);
|
|
800
|
+
if (marker !== null) {
|
|
801
|
+
const settings = await loadJson$1(p.settings);
|
|
802
|
+
const userHadIt = existedBefore(baseline?.get(p.settings), ["experimental"]);
|
|
803
|
+
if (settings.value.experimental === true && !userHadIt) {
|
|
804
|
+
const rest = { ...settings.value };
|
|
805
|
+
delete rest.experimental;
|
|
806
|
+
const wasAbsent = baseline?.get(p.settings) === null;
|
|
807
|
+
const emptied = Object.keys(rest).length === 0 && wasAbsent;
|
|
808
|
+
changes.push({
|
|
809
|
+
component: "hooks",
|
|
810
|
+
kind: "remove",
|
|
811
|
+
path: p.settings,
|
|
812
|
+
before: settings.raw,
|
|
813
|
+
after: emptied ? "" : editJson$1(settings, [{
|
|
814
|
+
path: ["experimental"],
|
|
815
|
+
value: void 0
|
|
816
|
+
}]),
|
|
817
|
+
...emptied ? { deleteFile: true } : {},
|
|
818
|
+
description: "Turn off Copilot CLI's experimental mode, which Conveno turned on (\"experimental\": false by removing the key)."
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
changes.push({
|
|
822
|
+
component: "hooks",
|
|
823
|
+
kind: "remove",
|
|
824
|
+
path: p.marker,
|
|
825
|
+
before: marker,
|
|
826
|
+
after: "",
|
|
827
|
+
deleteFile: true,
|
|
828
|
+
pruneEmptyDir: true,
|
|
829
|
+
description: "Remove the note that Conveno turned on experimental mode."
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
return changes;
|
|
833
|
+
}
|
|
834
|
+
async function plan$3(env) {
|
|
835
|
+
const p = paths$1(env);
|
|
836
|
+
const changes = [];
|
|
837
|
+
const mcpFile = await loadJson$1(p.mcp);
|
|
838
|
+
const servers = mcpObject$1(mcpFile.value, p.mcp);
|
|
839
|
+
const want = desiredServer$1(env);
|
|
840
|
+
if (!sameJson$1(servers["conveno"], want)) changes.push({
|
|
841
|
+
component: "mcp",
|
|
842
|
+
kind: servers["conveno"] === void 0 ? "add" : "update",
|
|
843
|
+
parts: [{
|
|
844
|
+
name: "MCP server",
|
|
845
|
+
kind: servers["conveno"] === void 0 ? "add" : "update"
|
|
846
|
+
}],
|
|
847
|
+
path: p.mcp,
|
|
848
|
+
before: mcpFile.raw,
|
|
849
|
+
after: editJson$1(mcpFile, [{
|
|
850
|
+
path: ["mcpServers", SERVER_NAME$3],
|
|
851
|
+
value: want
|
|
852
|
+
}]),
|
|
853
|
+
description: `Register the "${SERVER_NAME$3}" MCP server for Copilot CLI (conveno mcp --cli copilot).`,
|
|
854
|
+
viaCommand: [
|
|
855
|
+
"copilot",
|
|
856
|
+
"mcp",
|
|
857
|
+
"add",
|
|
858
|
+
SERVER_NAME$3,
|
|
859
|
+
"--",
|
|
860
|
+
...mcpArgs$1(env)
|
|
861
|
+
]
|
|
862
|
+
});
|
|
863
|
+
const hookFile = await loadJson$1(p.hooks);
|
|
864
|
+
const hooks = hooksObject$1(hookFile.value, p.hooks);
|
|
865
|
+
const missing = HOOK_EVENTS$2.filter((e) => !hasExactHook$1(hooks, e, hookEntry$1(env, e)));
|
|
866
|
+
if (missing.length > 0) {
|
|
867
|
+
const edits = [];
|
|
868
|
+
if (hookFile.value.version === void 0) edits.push({
|
|
869
|
+
path: ["version"],
|
|
870
|
+
value: 1
|
|
871
|
+
});
|
|
872
|
+
for (const e of missing) edits.push(...putInList(hooks[e], ["hooks", e], hookEntry$1(env, e), isOurEntry$1));
|
|
873
|
+
const installed = HOOK_EVENTS$2.some((e) => entriesOf$1(hooks, e).some(isOurEntry$1));
|
|
874
|
+
changes.push({
|
|
875
|
+
component: "hooks",
|
|
876
|
+
kind: installed ? "update" : "add",
|
|
877
|
+
parts: missing.map((e) => ({
|
|
878
|
+
name: `${e} hook`,
|
|
879
|
+
kind: entriesOf$1(hooks, e).some(isOurEntry$1) ? "update" : "add"
|
|
880
|
+
})),
|
|
881
|
+
path: p.hooks,
|
|
882
|
+
before: hookFile.raw,
|
|
883
|
+
after: editJson$1(hookFile, edits),
|
|
884
|
+
description: `Add ${missing.join(", ")} hooks that deliver Conveno messages to Copilot CLI on the next turn and at the end of a turn.`
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
return [...changes, ...await planExtension(env)];
|
|
888
|
+
}
|
|
889
|
+
async function uninstallPlan$3(env, baseline) {
|
|
890
|
+
const p = paths$1(env);
|
|
891
|
+
const changes = [];
|
|
892
|
+
const mcpFile = await loadJson$1(p.mcp);
|
|
893
|
+
if ("conveno" in mcpObject$1(mcpFile.value, p.mcp)) changes.push({
|
|
894
|
+
component: "mcp",
|
|
895
|
+
kind: "remove",
|
|
896
|
+
path: p.mcp,
|
|
897
|
+
before: mcpFile.raw,
|
|
898
|
+
after: editJson$1(mcpFile, [{
|
|
899
|
+
path: ["mcpServers", SERVER_NAME$3],
|
|
900
|
+
value: void 0
|
|
901
|
+
}]),
|
|
902
|
+
description: `Remove the "${SERVER_NAME$3}" MCP server.`,
|
|
903
|
+
viaCommand: [
|
|
904
|
+
"copilot",
|
|
905
|
+
"mcp",
|
|
906
|
+
"remove",
|
|
907
|
+
SERVER_NAME$3
|
|
908
|
+
]
|
|
909
|
+
});
|
|
910
|
+
const hookFile = await loadJson$1(p.hooks);
|
|
911
|
+
const hooks = hooksObject$1(hookFile.value, p.hooks);
|
|
912
|
+
const next = { ...hooks };
|
|
913
|
+
const edits = [];
|
|
914
|
+
for (const e of HOOK_EVENTS$2) {
|
|
915
|
+
const drops = dropFromList(hooks[e], ["hooks", e], isOurEntry$1, { keepEmpty: existedBefore(baseline?.get(p.hooks), ["hooks", e]) });
|
|
916
|
+
if (drops.length === 0) continue;
|
|
917
|
+
if (drops.length === 1 && drops[0]?.path.length === 2) delete next[e];
|
|
918
|
+
edits.push(...drops);
|
|
919
|
+
}
|
|
920
|
+
if (edits.length > 0) {
|
|
921
|
+
if (Object.keys(next).length === 0 && !existedBefore(baseline?.get(p.hooks), ["hooks"])) edits.push({
|
|
922
|
+
path: ["hooks"],
|
|
923
|
+
value: void 0
|
|
924
|
+
});
|
|
925
|
+
changes.push({
|
|
926
|
+
component: "hooks",
|
|
927
|
+
kind: "remove",
|
|
928
|
+
path: p.hooks,
|
|
929
|
+
before: hookFile.raw,
|
|
930
|
+
after: editJson$1(hookFile, edits),
|
|
931
|
+
description: "Remove the Conveno sessionStart, userPromptSubmitted, preToolUse, postToolUse and agentStop hooks."
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
return [...changes, ...await uninstallExtension(env, baseline)];
|
|
935
|
+
}
|
|
936
|
+
const isHookEvent$1 = (e) => HOOK_EVENTS$2.includes(e);
|
|
937
|
+
/** The tools Conveno's MCP server offers (packages/mcp). */
|
|
938
|
+
const OWN_TOOLS = /* @__PURE__ */ new Set([
|
|
939
|
+
"whoami",
|
|
940
|
+
"list_sessions",
|
|
941
|
+
"send",
|
|
942
|
+
"inbox",
|
|
943
|
+
"ack",
|
|
944
|
+
"rename",
|
|
945
|
+
"set_status",
|
|
946
|
+
"become_lead",
|
|
947
|
+
"orchestrate",
|
|
948
|
+
"handoff",
|
|
949
|
+
"spawn_session"
|
|
950
|
+
]);
|
|
951
|
+
/**
|
|
952
|
+
* Conveno's own MCP tools as Copilot names them: `conveno-send` for the model, `conveno/send`
|
|
953
|
+
* inside Copilot (1.0.63 bundle). Only exact names match, so another server whose name starts
|
|
954
|
+
* with "conveno" is never pre-approved.
|
|
955
|
+
*/
|
|
956
|
+
const isOwnTool = (name) => {
|
|
957
|
+
if (typeof name !== "string") return false;
|
|
958
|
+
const m = /^conveno[-/]([a-z_]+)$/.exec(name);
|
|
959
|
+
return m !== null && OWN_TOOLS.has(m[1] ?? "");
|
|
960
|
+
};
|
|
961
|
+
/**
|
|
962
|
+
* If Copilot sets `COPILOT_HOOK_DEPTH` on a run started from inside another hook or extension, that
|
|
963
|
+
* run's hooks deliver nothing: those messages belong to the outer session. Depth 1 is the session
|
|
964
|
+
* itself. Not found in the Copilot 1.0.63 bundle, so this guard may never fire.
|
|
965
|
+
*/
|
|
966
|
+
const nested = () => Number(process.env.COPILOT_HOOK_DEPTH ?? 0) > 1;
|
|
967
|
+
const field = (input, ...keys) => isObject$1(input) ? keys.map((k) => input[k]).find((v) => v !== void 0) : void 0;
|
|
968
|
+
/**
|
|
969
|
+
* - sessionStart, userPromptSubmitted: `{ "additionalContext": "<text>" }`. `sessionStart` adds it
|
|
970
|
+
* as a first message of the session; `userPromptSubmitted` adds it to the prompt being submitted
|
|
971
|
+
* and marks the turn started.
|
|
972
|
+
* - preToolUse: `{ "permissionDecision": "allow" }` for Conveno's own MCP tools, so a session never
|
|
973
|
+
* waits on a prompt to read or send a message. Nothing for any other tool.
|
|
974
|
+
* - postToolUse: waiting messages as `additionalContext`, which Copilot appends to the tool result
|
|
975
|
+
* so the model sees them on the same turn (10 KB cap).
|
|
976
|
+
* - agentStop: records the turn end. With messages waiting, `decision: "block"` with
|
|
977
|
+
* the framed messages as `reason`, which Copilot runs as another turn. Like Codex, Copilot has no
|
|
978
|
+
* idle wake, so this also happens when `stop_hook_active` is set; Copilot ends the chain after 8
|
|
979
|
+
* blocks in a row, and Conveno's auto-mode limit bounds it before that.
|
|
980
|
+
* - Listen: the extension's idle-wake listener. Waits for work and prints `#conveno-ids <id>,<id>`
|
|
981
|
+
* and then the framed messages (plain text, exit 0); the extension strips the first line and sends
|
|
982
|
+
* the rest with `session.send`. Nothing when it stops for any other reason.
|
|
983
|
+
* - Requeue: the extension's `session.send` failed; puts the messages (`ids` in the input) back to queued.
|
|
984
|
+
* Never throws and never writes to stderr: any failure means "deliver nothing this time".
|
|
985
|
+
*/
|
|
986
|
+
async function hook$3(event, input, ctx) {
|
|
987
|
+
if (nested()) return EMPTY$3;
|
|
988
|
+
if (event === "Listen") {
|
|
989
|
+
const r = await waitForWorkBatch(ctx, { maxMs: LISTEN_MAX_MS });
|
|
990
|
+
if (r === null) return EMPTY$3;
|
|
991
|
+
const ids = r.batch.messages.map((m) => m.id);
|
|
992
|
+
return {
|
|
993
|
+
stdout: (ids.length > 0 ? `${IDS_LEAD} ${ids.join(",")}\n` : "") + r.batch.text,
|
|
994
|
+
exitCode: 0
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
if (event === "Requeue") {
|
|
998
|
+
await requeue$1(ctx, input);
|
|
999
|
+
return EMPTY$3;
|
|
1000
|
+
}
|
|
1001
|
+
if (!isHookEvent$1(event)) return EMPTY$3;
|
|
1002
|
+
if (event === "preToolUse") {
|
|
1003
|
+
if (!isOwnTool(field(input, "toolName", "tool_name"))) return EMPTY$3;
|
|
1004
|
+
return {
|
|
1005
|
+
stdout: JSON.stringify({ permissionDecision: "allow" }),
|
|
1006
|
+
exitCode: 0
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
if (event === "agentStop") {
|
|
1010
|
+
const reason = await endTurnContinuation(ctx);
|
|
1011
|
+
if (reason === null) return EMPTY$3;
|
|
1012
|
+
return {
|
|
1013
|
+
stdout: JSON.stringify({
|
|
1014
|
+
decision: "block",
|
|
1015
|
+
reason
|
|
1016
|
+
}),
|
|
1017
|
+
exitCode: 0
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
const additionalContext = event === "userPromptSubmitted" ? await startTurnContext(ctx) : await pendingHookContext(ctx);
|
|
1021
|
+
if (additionalContext === null) return EMPTY$3;
|
|
1022
|
+
return {
|
|
1023
|
+
stdout: JSON.stringify({ additionalContext }),
|
|
1024
|
+
exitCode: 0
|
|
1025
|
+
};
|
|
1026
|
+
}
|
|
1027
|
+
/** `Requeue`: sending failed, so the messages go back to queued for the next turn. */
|
|
1028
|
+
async function requeue$1(ctx, input) {
|
|
1029
|
+
try {
|
|
1030
|
+
const ids = field(input, "ids");
|
|
1031
|
+
if (!Array.isArray(ids) || ids.length === 0) return;
|
|
1032
|
+
const session = await ownSession(ctx);
|
|
1033
|
+
if (!session) return;
|
|
1034
|
+
await ctx.client["message.requeue"]({
|
|
1035
|
+
sessionId: session.id,
|
|
1036
|
+
ids
|
|
1037
|
+
});
|
|
1038
|
+
} catch {}
|
|
1039
|
+
}
|
|
1040
|
+
const copilotAdapter = {
|
|
1041
|
+
cli: "copilot",
|
|
1042
|
+
displayName: "GitHub Copilot CLI",
|
|
1043
|
+
deliveryTier: "next_turn",
|
|
1044
|
+
delivery: () => ({
|
|
1045
|
+
nextTurn: true,
|
|
1046
|
+
endOfTurn: true,
|
|
1047
|
+
idleWake: true
|
|
1048
|
+
}),
|
|
1049
|
+
detect: detect$3,
|
|
1050
|
+
plan: plan$3,
|
|
1051
|
+
uninstallPlan: uninstallPlan$3,
|
|
1052
|
+
hook: hook$3,
|
|
1053
|
+
listenEvents: [LISTEN_EVENT]
|
|
1054
|
+
};
|
|
1055
|
+
// ../adapters/cursor/dist/index.js
|
|
1056
|
+
const SERVER_NAME$2 = "conveno";
|
|
1057
|
+
/**
|
|
1058
|
+
* Hooks that can add context to the conversation: `sessionStart` for a new chat and `postToolUse`
|
|
1059
|
+
* after each tool call. `beforeSubmitPrompt` is not here because it can only allow or block a
|
|
1060
|
+
* prompt, never add to it. `stop` ends a turn and, continues with waiting messages.
|
|
1061
|
+
*/
|
|
1062
|
+
const HOOK_EVENTS$1 = [
|
|
1063
|
+
"sessionStart",
|
|
1064
|
+
"postToolUse",
|
|
1065
|
+
"stop"
|
|
1066
|
+
];
|
|
1067
|
+
/** The `permissions.allow` token that lets the agent call every tool of the conveno server. */
|
|
1068
|
+
const MCP_PERMISSION = `Mcp(${SERVER_NAME$2}:*)`;
|
|
1069
|
+
const EMPTY$2 = {
|
|
1070
|
+
stdout: "",
|
|
1071
|
+
exitCode: 0
|
|
1072
|
+
};
|
|
1073
|
+
/**
|
|
1074
|
+
* `mcp.json` and `hooks.json` are always read from `~/.cursor`. The CLI's own settings file moves
|
|
1075
|
+
* with `CURSOR_CONFIG_DIR`, or with `XDG_CONFIG_HOME` on Linux and BSD, and `CURSOR_CONFIG_DIR` wins.
|
|
1076
|
+
*/
|
|
1077
|
+
function paths(env) {
|
|
1078
|
+
const dir = join(env.home, ".cursor");
|
|
1079
|
+
const custom = env.env.CURSOR_CONFIG_DIR;
|
|
1080
|
+
const xdg = env.env.XDG_CONFIG_HOME;
|
|
1081
|
+
const xdgApplies = env.platform !== "win32" && env.platform !== "darwin";
|
|
1082
|
+
const cliConfig = custom ? join(custom, "cli-config.json") : xdg && xdgApplies ? join(xdg, "cursor", "cli-config.json") : join(dir, "cli-config.json");
|
|
1083
|
+
return {
|
|
1084
|
+
mcp: join(dir, "mcp.json"),
|
|
1085
|
+
hooks: join(dir, "hooks.json"),
|
|
1086
|
+
cliConfig
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Quote one word of a hook command. On Windows the desktop app runs hook commands through
|
|
1091
|
+
* PowerShell, so words are written for PowerShell: single quotes, and forward slashes in paths
|
|
1092
|
+
* (Windows accepts `/` everywhere, and it keeps `\` away from every quoting rule). Elsewhere the
|
|
1093
|
+
* command runs in a POSIX shell.
|
|
1094
|
+
*/
|
|
1095
|
+
function quoteWord(arg, platform) {
|
|
1096
|
+
if (platform === "win32") {
|
|
1097
|
+
const word = arg.replace(/\\/g, "/");
|
|
1098
|
+
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, "''")}'`;
|
|
1099
|
+
}
|
|
1100
|
+
return /^[A-Za-z0-9_@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
|
|
1101
|
+
}
|
|
1102
|
+
function hookCommand$1(env, event) {
|
|
1103
|
+
const words = [
|
|
1104
|
+
...env.conveno.command,
|
|
1105
|
+
"hook",
|
|
1106
|
+
"cursor",
|
|
1107
|
+
event
|
|
1108
|
+
].map((w) => quoteWord(w, env.platform));
|
|
1109
|
+
return (env.platform === "win32" && /^'/.test(words[0] ?? "") ? "& " : "") + words.join(" ");
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* `stop` sets `loop_limit: null`: Cursor's own cap (5 follow-ups by default) would end the loop
|
|
1113
|
+
* for the conversation, and Conveno's own auto-mode limit already bounds it.
|
|
1114
|
+
*/
|
|
1115
|
+
const hookEntry = (env, event) => ({
|
|
1116
|
+
command: hookCommand$1(env, event),
|
|
1117
|
+
timeout: 5,
|
|
1118
|
+
...event === "stop" ? { loop_limit: null } : {}
|
|
1119
|
+
});
|
|
1120
|
+
const mcpArgs = (env) => [
|
|
1121
|
+
...env.conveno.command,
|
|
1122
|
+
"mcp",
|
|
1123
|
+
"--cli",
|
|
1124
|
+
"cursor"
|
|
1125
|
+
];
|
|
1126
|
+
const desiredServer = (env) => {
|
|
1127
|
+
const [command = "conveno", ...args] = mcpArgs(env);
|
|
1128
|
+
return {
|
|
1129
|
+
type: "stdio",
|
|
1130
|
+
command,
|
|
1131
|
+
args
|
|
1132
|
+
};
|
|
1133
|
+
};
|
|
1134
|
+
/** Recognizes our hook command even if the conveno path changed since install. */
|
|
1135
|
+
const isOurHookCommand$1 = (cmd) => typeof cmd === "string" && /(^|\s)hook cursor (sessionStart|postToolUse|stop)$/.test(cmd.trim());
|
|
1136
|
+
const isOurEntry = (e) => isObject$1(e) && isOurHookCommand$1(e.command);
|
|
1137
|
+
function entriesOf(hooks, event) {
|
|
1138
|
+
const g = hooks[event];
|
|
1139
|
+
return Array.isArray(g) ? g : [];
|
|
1140
|
+
}
|
|
1141
|
+
const hasExactHook = (hooks, event, want) => entriesOf(hooks, event).some((e) => sameJson$1(e, want));
|
|
1142
|
+
function hooksObject(file, path) {
|
|
1143
|
+
const h = file.hooks;
|
|
1144
|
+
if (h === void 0) return {};
|
|
1145
|
+
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.`);
|
|
1146
|
+
return h;
|
|
1147
|
+
}
|
|
1148
|
+
function mcpObject(config, path) {
|
|
1149
|
+
const s = config.mcpServers;
|
|
1150
|
+
if (s === void 0) return {};
|
|
1151
|
+
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.`);
|
|
1152
|
+
return s;
|
|
1153
|
+
}
|
|
1154
|
+
/** The `permissions.allow` list of cli-config.json, or undefined when it is not there. */
|
|
1155
|
+
function allowList(config, path) {
|
|
1156
|
+
const p = config.permissions;
|
|
1157
|
+
if (p === void 0) return void 0;
|
|
1158
|
+
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.`);
|
|
1159
|
+
const a = p.allow;
|
|
1160
|
+
if (a === void 0) return void 0;
|
|
1161
|
+
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.`);
|
|
1162
|
+
return a;
|
|
1163
|
+
}
|
|
1164
|
+
async function detect$2(env) {
|
|
1165
|
+
const p = paths(env);
|
|
1166
|
+
const configPaths = [
|
|
1167
|
+
p.mcp,
|
|
1168
|
+
p.hooks,
|
|
1169
|
+
p.cliConfig
|
|
1170
|
+
];
|
|
1171
|
+
for (const binary of ["cursor-agent", "agent"]) try {
|
|
1172
|
+
const r = await env.exec(binary, ["--version"]);
|
|
1173
|
+
if (r.code !== 0) continue;
|
|
1174
|
+
if (binary === "agent" && !/^\d{4}\.\d{1,2}\.\d{1,2}/.test(r.stdout.trim())) continue;
|
|
1175
|
+
const version = parseCliVersion(r.stdout);
|
|
1176
|
+
return {
|
|
1177
|
+
installed: true,
|
|
1178
|
+
binary,
|
|
1179
|
+
...version ? { version } : {},
|
|
1180
|
+
configPaths
|
|
1181
|
+
};
|
|
1182
|
+
} catch {}
|
|
1183
|
+
return {
|
|
1184
|
+
installed: false,
|
|
1185
|
+
configPaths
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
async function plan$2(env) {
|
|
1189
|
+
const p = paths(env);
|
|
1190
|
+
const changes = [];
|
|
1191
|
+
const mcpFile = await loadJson$1(p.mcp);
|
|
1192
|
+
const servers = mcpObject(mcpFile.value, p.mcp);
|
|
1193
|
+
const want = desiredServer(env);
|
|
1194
|
+
if (!sameJson$1(servers["conveno"], want)) changes.push({
|
|
1195
|
+
component: "mcp",
|
|
1196
|
+
kind: servers["conveno"] === void 0 ? "add" : "update",
|
|
1197
|
+
parts: [{
|
|
1198
|
+
name: "MCP server",
|
|
1199
|
+
kind: servers["conveno"] === void 0 ? "add" : "update"
|
|
1200
|
+
}],
|
|
1201
|
+
path: p.mcp,
|
|
1202
|
+
before: mcpFile.raw,
|
|
1203
|
+
after: editJson$1(mcpFile, [{
|
|
1204
|
+
path: ["mcpServers", SERVER_NAME$2],
|
|
1205
|
+
value: want
|
|
1206
|
+
}]),
|
|
1207
|
+
description: `Register the "${SERVER_NAME$2}" MCP server for the Cursor CLI (conveno mcp --cli cursor).`
|
|
1208
|
+
});
|
|
1209
|
+
const cfgFile = await loadJson$1(p.cliConfig);
|
|
1210
|
+
const allow = allowList(cfgFile.value, p.cliConfig);
|
|
1211
|
+
if (!allow?.includes("Mcp(conveno:*)")) {
|
|
1212
|
+
const edits = [];
|
|
1213
|
+
if (cfgFile.raw === null || cfgFile.raw.trim() === "") edits.push({
|
|
1214
|
+
path: ["version"],
|
|
1215
|
+
value: 1
|
|
1216
|
+
}, {
|
|
1217
|
+
path: ["editor"],
|
|
1218
|
+
value: { vimMode: false }
|
|
1219
|
+
}, {
|
|
1220
|
+
path: ["permissions"],
|
|
1221
|
+
value: {
|
|
1222
|
+
allow: [MCP_PERMISSION],
|
|
1223
|
+
deny: []
|
|
1224
|
+
}
|
|
1225
|
+
});
|
|
1226
|
+
else if (cfgFile.value.permissions === void 0) edits.push({
|
|
1227
|
+
path: ["permissions"],
|
|
1228
|
+
value: {
|
|
1229
|
+
allow: [MCP_PERMISSION],
|
|
1230
|
+
deny: []
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
else if (allow === void 0) edits.push({
|
|
1234
|
+
path: ["permissions", "allow"],
|
|
1235
|
+
value: [MCP_PERMISSION]
|
|
1236
|
+
});
|
|
1237
|
+
else edits.push({
|
|
1238
|
+
path: [
|
|
1239
|
+
"permissions",
|
|
1240
|
+
"allow",
|
|
1241
|
+
allow.length
|
|
1242
|
+
],
|
|
1243
|
+
value: MCP_PERMISSION,
|
|
1244
|
+
insert: true
|
|
1245
|
+
});
|
|
1246
|
+
changes.push({
|
|
1247
|
+
component: "mcp",
|
|
1248
|
+
kind: "add",
|
|
1249
|
+
parts: [{
|
|
1250
|
+
name: "tools permission",
|
|
1251
|
+
kind: "add"
|
|
1252
|
+
}],
|
|
1253
|
+
path: p.cliConfig,
|
|
1254
|
+
before: cfgFile.raw,
|
|
1255
|
+
after: editJson$1(cfgFile, edits),
|
|
1256
|
+
description: `Allow the agent to call the "${SERVER_NAME$2}" server's tools without asking (${MCP_PERMISSION}). They only exchange messages between your own sessions.`
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
const hookFile = await loadJson$1(p.hooks);
|
|
1260
|
+
const hooks = hooksObject(hookFile.value, p.hooks);
|
|
1261
|
+
const missing = HOOK_EVENTS$1.filter((e) => !hasExactHook(hooks, e, hookEntry(env, e)));
|
|
1262
|
+
if (missing.length > 0) {
|
|
1263
|
+
const edits = [];
|
|
1264
|
+
if (hookFile.value.version === void 0) edits.push({
|
|
1265
|
+
path: ["version"],
|
|
1266
|
+
value: 1
|
|
1267
|
+
});
|
|
1268
|
+
for (const e of missing) edits.push(...putInList(hooks[e], ["hooks", e], hookEntry(env, e), isOurEntry));
|
|
1269
|
+
const installed = HOOK_EVENTS$1.some((e) => entriesOf(hooks, e).some(isOurEntry));
|
|
1270
|
+
changes.push({
|
|
1271
|
+
component: "hooks",
|
|
1272
|
+
kind: installed ? "update" : "add",
|
|
1273
|
+
parts: missing.map((e) => ({
|
|
1274
|
+
name: `${e} hook`,
|
|
1275
|
+
kind: entriesOf(hooks, e).some(isOurEntry) ? "update" : "add"
|
|
1276
|
+
})),
|
|
1277
|
+
path: p.hooks,
|
|
1278
|
+
before: hookFile.raw,
|
|
1279
|
+
after: editJson$1(hookFile, edits),
|
|
1280
|
+
description: `Add ${missing.join(", ")} hooks that deliver Conveno messages to the Cursor CLI on the next turn and at the end of a turn.`
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
return changes;
|
|
1284
|
+
}
|
|
1285
|
+
async function uninstallPlan$2(env, baseline) {
|
|
1286
|
+
const p = paths(env);
|
|
1287
|
+
const changes = [];
|
|
1288
|
+
const mcpFile = await loadJson$1(p.mcp);
|
|
1289
|
+
if ("conveno" in mcpObject(mcpFile.value, p.mcp)) changes.push({
|
|
1290
|
+
component: "mcp",
|
|
1291
|
+
kind: "remove",
|
|
1292
|
+
path: p.mcp,
|
|
1293
|
+
before: mcpFile.raw,
|
|
1294
|
+
after: editJson$1(mcpFile, [{
|
|
1295
|
+
path: ["mcpServers", SERVER_NAME$2],
|
|
1296
|
+
value: void 0
|
|
1297
|
+
}]),
|
|
1298
|
+
description: `Remove the "${SERVER_NAME$2}" MCP server.`
|
|
1299
|
+
});
|
|
1300
|
+
const cfgFile = await loadJson$1(p.cliConfig);
|
|
1301
|
+
const at = (allowList(cfgFile.value, p.cliConfig) ?? []).flatMap((x, i) => x === "Mcp(conveno:*)" ? [i] : []);
|
|
1302
|
+
if (at.length > 0) changes.push({
|
|
1303
|
+
component: "mcp",
|
|
1304
|
+
kind: "remove",
|
|
1305
|
+
path: p.cliConfig,
|
|
1306
|
+
before: cfgFile.raw,
|
|
1307
|
+
after: editJson$1(cfgFile, at.reverse().map((i) => ({
|
|
1308
|
+
path: [
|
|
1309
|
+
"permissions",
|
|
1310
|
+
"allow",
|
|
1311
|
+
i
|
|
1312
|
+
],
|
|
1313
|
+
value: void 0
|
|
1314
|
+
}))),
|
|
1315
|
+
description: `Remove ${MCP_PERMISSION} from the allowed permissions.`
|
|
1316
|
+
});
|
|
1317
|
+
const hookFile = await loadJson$1(p.hooks);
|
|
1318
|
+
const hooks = hooksObject(hookFile.value, p.hooks);
|
|
1319
|
+
const next = { ...hooks };
|
|
1320
|
+
const edits = [];
|
|
1321
|
+
for (const e of HOOK_EVENTS$1) {
|
|
1322
|
+
const drops = dropFromList(hooks[e], ["hooks", e], isOurEntry, { keepEmpty: existedBefore(baseline?.get(p.hooks), ["hooks", e]) });
|
|
1323
|
+
if (drops.length === 0) continue;
|
|
1324
|
+
if (drops.length === 1 && drops[0]?.path.length === 2) delete next[e];
|
|
1325
|
+
edits.push(...drops);
|
|
1326
|
+
}
|
|
1327
|
+
if (edits.length > 0) {
|
|
1328
|
+
if (Object.keys(next).length === 0 && !existedBefore(baseline?.get(p.hooks), ["hooks"])) edits.push({
|
|
1329
|
+
path: ["hooks"],
|
|
1330
|
+
value: void 0
|
|
1331
|
+
});
|
|
1332
|
+
changes.push({
|
|
1333
|
+
component: "hooks",
|
|
1334
|
+
kind: "remove",
|
|
1335
|
+
path: p.hooks,
|
|
1336
|
+
before: hookFile.raw,
|
|
1337
|
+
after: editJson$1(hookFile, edits),
|
|
1338
|
+
description: "Remove the Conveno sessionStart, postToolUse and stop hooks."
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
return changes;
|
|
1342
|
+
}
|
|
1343
|
+
const isHookEvent = (e) => HOOK_EVENTS$1.includes(e);
|
|
1344
|
+
/**
|
|
1345
|
+
* - sessionStart, postToolUse: `{ "additional_context": "<text>" }`, added to the chat's initial
|
|
1346
|
+
* context or to the conversation after the tool result.
|
|
1347
|
+
* - stop: records the turn end. With messages waiting, after a turn that `completed`,
|
|
1348
|
+
* `{ "followup_message": "<text>" }`, which Cursor submits as the next user message. An aborted
|
|
1349
|
+
* or failed turn never continues. Like Codex, Cursor has no idle wake, so this also runs on a
|
|
1350
|
+
* turn that was itself a follow-up; Conveno's auto-mode limit bounds the chain.
|
|
1351
|
+
* Never throws and never writes to stderr: any failure means "deliver nothing this time".
|
|
1352
|
+
*/
|
|
1353
|
+
async function hook$2(event, input, ctx) {
|
|
1354
|
+
if (!isHookEvent(event)) return EMPTY$2;
|
|
1355
|
+
if (event === "stop") {
|
|
1356
|
+
const status = isObject$1(input) ? input.status : void 0;
|
|
1357
|
+
const followup = await endTurnContinuation(ctx, { allowContinue: status === void 0 || status === "completed" });
|
|
1358
|
+
if (followup === null) return EMPTY$2;
|
|
1359
|
+
return {
|
|
1360
|
+
stdout: JSON.stringify({ followup_message: followup }),
|
|
1361
|
+
exitCode: 0
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
const additionalContext = await pendingHookContext(ctx);
|
|
1365
|
+
if (additionalContext === null) return EMPTY$2;
|
|
1366
|
+
return {
|
|
1367
|
+
stdout: JSON.stringify({ additional_context: additionalContext }),
|
|
1368
|
+
exitCode: 0
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
const cursorAdapter = {
|
|
1372
|
+
cli: "cursor",
|
|
1373
|
+
displayName: "Cursor CLI",
|
|
1374
|
+
deliveryTier: "next_turn",
|
|
1375
|
+
delivery: () => ({
|
|
1376
|
+
nextTurn: true,
|
|
1377
|
+
endOfTurn: true,
|
|
1378
|
+
idleWake: false
|
|
1379
|
+
}),
|
|
1380
|
+
detect: detect$2,
|
|
1381
|
+
plan: plan$2,
|
|
1382
|
+
uninstallPlan: uninstallPlan$2,
|
|
1383
|
+
hook: hook$2
|
|
1384
|
+
};
|
|
1385
|
+
// ../adapters/grok/dist/index.js
|
|
1386
|
+
const SERVER_NAME$1 = "conveno";
|
|
1387
|
+
/** The pattern of the allow rule: every tool of our server, in Grok's `server__tool` spelling. */
|
|
1388
|
+
const RULE_PATTERN = `${SERVER_NAME$1}__*`;
|
|
1389
|
+
var ConfigParseError = class extends Error {};
|
|
1390
|
+
function parseToml(path, text) {
|
|
1391
|
+
try {
|
|
1392
|
+
return cs(text);
|
|
1393
|
+
} catch (err) {
|
|
1394
|
+
throw new ConfigParseError(`Cannot parse ${path} as TOML (${err instanceof Error ? err.message : String(err)}). Fix or move the file, then run conveno again. Conveno did not change it.`);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
const isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1398
|
+
function serverOf(doc) {
|
|
1399
|
+
const ours = isTable(doc.mcp_servers) ? doc.mcp_servers[SERVER_NAME$1] : void 0;
|
|
1400
|
+
return isTable(ours) ? ours : void 0;
|
|
1401
|
+
}
|
|
1402
|
+
const matchesSpec = (server, spec) => server !== void 0 && server.command === spec.command && JSON.stringify(server.args) === JSON.stringify(spec.args);
|
|
1403
|
+
/** True for the MCP allow rule Conveno writes. Extra keys on the rule make it someone else's. */
|
|
1404
|
+
const isMcpRule = (r) => isTable(r) && r.action === "allow" && r.tool === "mcp" && r.pattern === "conveno__*" && Object.keys(r).length === 3;
|
|
1405
|
+
/** Tail of the watch rule Conveno writes: one session name starting with a letter or digit. */
|
|
1406
|
+
const WATCH_TAIL = " watch [a-z0-9]*";
|
|
1407
|
+
/**
|
|
1408
|
+
* True for an allow rule that lets Conveno's `watch` command run without a prompt: a bash rule
|
|
1409
|
+
* whose pattern is `<conveno command> watch [a-z0-9]*` (or, with `pattern`, any exact
|
|
1410
|
+
* string, such as the older `... watch *`). Without `pattern`, any conveno path, which only install
|
|
1411
|
+
* uses to replace a stale rule after a move; uninstall always passes exact patterns (`isOurRule`).
|
|
1412
|
+
*/
|
|
1413
|
+
const isWatchRule = (r, pattern) => isTable(r) && r.action === "allow" && r.tool === "bash" && typeof r.pattern === "string" && Object.keys(r).length === 3 && (pattern === void 0 ? r.pattern.endsWith(" watch [a-z0-9]*") : r.pattern === pattern);
|
|
1414
|
+
/** Either of the allow rules Conveno wrote, the watch one only if its pattern is one of `watchPatterns`. */
|
|
1415
|
+
const isOurRule = (r, watchPatterns) => isMcpRule(r) || watchPatterns.some((p) => isWatchRule(r, p));
|
|
1416
|
+
function rulesOf(doc) {
|
|
1417
|
+
const rules = isTable(doc.permission) ? doc.permission.rules : void 0;
|
|
1418
|
+
return Array.isArray(rules) ? rules : void 0;
|
|
1419
|
+
}
|
|
1420
|
+
/** True when the MCP rule and the exact watch rule are both there. */
|
|
1421
|
+
const hasRules = (doc, watchPattern) => {
|
|
1422
|
+
const rules = rulesOf(doc) ?? [];
|
|
1423
|
+
return rules.some(isMcpRule) && rules.some((r) => isWatchRule(r, watchPattern));
|
|
1424
|
+
};
|
|
1425
|
+
/** True when any rule of ours is there (the watch rule only with one of `watchPatterns`). */
|
|
1426
|
+
const hasAnyRule = (doc, watchPatterns) => rulesOf(doc)?.some((r) => isOurRule(r, watchPatterns)) ?? false;
|
|
1427
|
+
const eolOf = (text) => text.includes("\r\n") ? "\r\n" : "\n";
|
|
1428
|
+
/** TOML basic strings use the same escapes as JSON for everything we write. */
|
|
1429
|
+
const q = (s) => JSON.stringify(s);
|
|
1430
|
+
function serverText(spec, eol) {
|
|
1431
|
+
return [
|
|
1432
|
+
`[mcp_servers.${SERVER_NAME$1}]`,
|
|
1433
|
+
`command = ${q(spec.command)}`,
|
|
1434
|
+
`args = [${spec.args.map(q).join(", ")}]`,
|
|
1435
|
+
""
|
|
1436
|
+
].join(eol);
|
|
1437
|
+
}
|
|
1438
|
+
function ruleText(eol, tool, pattern) {
|
|
1439
|
+
return [
|
|
1440
|
+
"[[permission.rules]]",
|
|
1441
|
+
"action = \"allow\"",
|
|
1442
|
+
`tool = ${q(tool)}`,
|
|
1443
|
+
`pattern = ${q(pattern)}`,
|
|
1444
|
+
""
|
|
1445
|
+
].join(eol);
|
|
1446
|
+
}
|
|
1447
|
+
const EMPTYABLE = /* @__PURE__ */ new Set([
|
|
1448
|
+
"mcp_servers",
|
|
1449
|
+
"permission",
|
|
1450
|
+
"rules"
|
|
1451
|
+
]);
|
|
1452
|
+
/** A copy of `v` in which an emptied `mcp_servers`, `permission` or `rules` is gone, children first. */
|
|
1453
|
+
function prune(v) {
|
|
1454
|
+
if (Array.isArray(v)) return v.map(prune);
|
|
1455
|
+
if (!isTable(v)) return v;
|
|
1456
|
+
const out = {};
|
|
1457
|
+
for (const [k, child] of Object.entries(v)) {
|
|
1458
|
+
const p = prune(child);
|
|
1459
|
+
if (!((Array.isArray(p) && p.length === 0 || isTable(p) && Object.keys(p).length === 0) && EMPTYABLE.has(k))) out[k] = p;
|
|
1460
|
+
}
|
|
1461
|
+
return out;
|
|
1462
|
+
}
|
|
1463
|
+
/** Compare parsed data, treating an emptied `mcp_servers`, `permission` or `rules` as missing. */
|
|
1464
|
+
const sameData = (a, b) => JSON.stringify(prune(a)) === JSON.stringify(prune(b));
|
|
1465
|
+
/** `text` with a header line as the start of each section. The first one has no header. */
|
|
1466
|
+
function sections(text) {
|
|
1467
|
+
const out = [{
|
|
1468
|
+
key: null,
|
|
1469
|
+
text: ""
|
|
1470
|
+
}];
|
|
1471
|
+
for (const line of text.split(/(?<=\n)/)) {
|
|
1472
|
+
const m = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/.exec(line.replace(/\r?\n$/, ""));
|
|
1473
|
+
if (m) out.push({
|
|
1474
|
+
key: m[1].replace(/["'\s]/g, ""),
|
|
1475
|
+
text: line
|
|
1476
|
+
});
|
|
1477
|
+
else out.at(-1).text += line;
|
|
1478
|
+
}
|
|
1479
|
+
return out;
|
|
1480
|
+
}
|
|
1481
|
+
/**
|
|
1482
|
+
* Drop the sections whose header is `key` (or a subtable of it) and for which `drop` returns true.
|
|
1483
|
+
* The blank line that separated a dropped last section from the rest goes with it.
|
|
1484
|
+
*/
|
|
1485
|
+
function dropSections(text, keys, drop) {
|
|
1486
|
+
const all = sections(text);
|
|
1487
|
+
let lastDropped = false;
|
|
1488
|
+
let out = all.filter((s, i) => {
|
|
1489
|
+
const hit = s.key !== null && keys.some((k) => s.key === k || s.key?.startsWith(`${k}.`)) && drop(s.text);
|
|
1490
|
+
if (i === all.length - 1) lastDropped = hit;
|
|
1491
|
+
return !hit;
|
|
1492
|
+
}).map((s) => s.text).join("");
|
|
1493
|
+
if (lastDropped) out = out.replace(/(\r?\n)+$/, "") + (out.trim() === "" ? "" : eolOf(text));
|
|
1494
|
+
return out;
|
|
1495
|
+
}
|
|
1496
|
+
const parsesTo = (text, expected) => {
|
|
1497
|
+
try {
|
|
1498
|
+
return sameData(cs(text), expected);
|
|
1499
|
+
} catch {
|
|
1500
|
+
return false;
|
|
1501
|
+
}
|
|
1502
|
+
};
|
|
1503
|
+
/** Drop the `[[permission.rules]]` sections that hold one of our watch rules, other than `keep`. */
|
|
1504
|
+
function dropStaleWatchRules(text, keep) {
|
|
1505
|
+
return dropSections(text, ["permission.rules"], (section) => {
|
|
1506
|
+
try {
|
|
1507
|
+
const rule = cs(section).permission?.rules;
|
|
1508
|
+
return rule?.length === 1 && isWatchRule(rule[0]) && !isWatchRule(rule[0], keep);
|
|
1509
|
+
} catch {
|
|
1510
|
+
return false;
|
|
1511
|
+
}
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* Add our server table and our two allow rules (the MCP tools, and the `watch` command at
|
|
1516
|
+
* `watchPattern`) where they are missing, by appending text to the file. A watch rule for another
|
|
1517
|
+
* conveno path is replaced. If the result does not parse to the expected data (for example the user
|
|
1518
|
+
* already defines the rules as an inline `rules = [...]`), fall back to a comment-preserving patch.
|
|
1519
|
+
*/
|
|
1520
|
+
function addConfig(path, before, spec, watchPattern) {
|
|
1521
|
+
const doc = parseToml(path, before);
|
|
1522
|
+
const expected = structuredClone(doc);
|
|
1523
|
+
const servers = isTable(expected.mcp_servers) ? expected.mcp_servers : {};
|
|
1524
|
+
servers[SERVER_NAME$1] = {
|
|
1525
|
+
command: spec.command,
|
|
1526
|
+
args: spec.args
|
|
1527
|
+
};
|
|
1528
|
+
expected.mcp_servers = servers;
|
|
1529
|
+
const permission = isTable(expected.permission) ? expected.permission : {};
|
|
1530
|
+
const rules = (Array.isArray(permission.rules) ? permission.rules : []).filter((r) => !isWatchRule(r) || isWatchRule(r, watchPattern));
|
|
1531
|
+
if (!rules.some(isMcpRule)) rules.push({
|
|
1532
|
+
action: "allow",
|
|
1533
|
+
tool: "mcp",
|
|
1534
|
+
pattern: RULE_PATTERN
|
|
1535
|
+
});
|
|
1536
|
+
if (!rules.some((r) => isWatchRule(r, watchPattern))) rules.push({
|
|
1537
|
+
action: "allow",
|
|
1538
|
+
tool: "bash",
|
|
1539
|
+
pattern: watchPattern
|
|
1540
|
+
});
|
|
1541
|
+
permission.rules = rules;
|
|
1542
|
+
expected.permission = permission;
|
|
1543
|
+
const eol = eolOf(before);
|
|
1544
|
+
const needServer = !matchesSpec(serverOf(doc), spec);
|
|
1545
|
+
let text = needServer && serverOf(doc) ? removeServerText(before) : before;
|
|
1546
|
+
text = dropStaleWatchRules(text, watchPattern);
|
|
1547
|
+
const rulesBefore = rulesOf(doc) ?? [];
|
|
1548
|
+
const append = (block) => {
|
|
1549
|
+
const sep = text === "" ? "" : text.endsWith("\n") ? eol : eol + eol;
|
|
1550
|
+
text = text + sep + block;
|
|
1551
|
+
};
|
|
1552
|
+
if (needServer) append(serverText(spec, eol));
|
|
1553
|
+
if (!rulesBefore.some(isMcpRule)) append(ruleText(eol, "mcp", RULE_PATTERN));
|
|
1554
|
+
if (!rulesBefore.some((r) => isWatchRule(r, watchPattern))) append(ruleText(eol, "bash", watchPattern));
|
|
1555
|
+
if (parsesTo(text, expected)) return text;
|
|
1556
|
+
return Za(before, expected);
|
|
1557
|
+
}
|
|
1558
|
+
function removeServerText(text) {
|
|
1559
|
+
return dropSections(text, [`mcp_servers.${SERVER_NAME$1}`], () => true);
|
|
1560
|
+
}
|
|
1561
|
+
/** Remove our server table (and its subtables) and the allow rules Conveno wrote, matched exactly. Everything else stays byte for byte. */
|
|
1562
|
+
function removeConfig(path, before, watchPatterns) {
|
|
1563
|
+
const doc = parseToml(path, before);
|
|
1564
|
+
const expected = structuredClone(doc);
|
|
1565
|
+
if (isTable(expected.mcp_servers)) delete expected.mcp_servers[SERVER_NAME$1];
|
|
1566
|
+
const rules = rulesOf(expected);
|
|
1567
|
+
if (rules && isTable(expected.permission)) expected.permission.rules = rules.filter((r) => !isOurRule(r, watchPatterns));
|
|
1568
|
+
const text = dropSections(removeServerText(before), ["permission.rules"], (section) => {
|
|
1569
|
+
try {
|
|
1570
|
+
const rule = cs(section).permission?.rules;
|
|
1571
|
+
return rule?.length === 1 && isOurRule(rule[0], watchPatterns);
|
|
1572
|
+
} catch {
|
|
1573
|
+
return false;
|
|
1574
|
+
}
|
|
1575
|
+
});
|
|
1576
|
+
if (parsesTo(text, expected)) return text;
|
|
1577
|
+
return Za(before, expected);
|
|
1578
|
+
}
|
|
1579
|
+
/** `$GROK_HOME`, else `~/.grok` (`%USERPROFILE%\.grok` on Windows). */
|
|
1580
|
+
const grokDir = (env) => env.env.GROK_HOME || join(env.home, ".grok");
|
|
1581
|
+
const configPath = (env) => join(grokDir(env), "config.toml");
|
|
1582
|
+
/**
|
|
1583
|
+
* Grok loads every `*.json` file in `$GROK_HOME/hooks`, always trusted. Conveno's hook gets a file
|
|
1584
|
+
* of its own: `config.toml` carries the MCP change, and one file cannot take two changes.
|
|
1585
|
+
*/
|
|
1586
|
+
const hooksPath = (env) => join(grokDir(env), "hooks", "conveno.json");
|
|
1587
|
+
/**
|
|
1588
|
+
* Home rules: Grok reads every `*.md` in `$GROK_HOME/rules` for every project, whatever the folder
|
|
1589
|
+
* trust (user guide 12-project-rules.md). Conveno's wake instructions get a file of their own.
|
|
1590
|
+
*/
|
|
1591
|
+
const rulesPath = (env) => join(grokDir(env), "rules", "conveno.md");
|
|
1592
|
+
/** The agent is about to end its turn. */
|
|
1593
|
+
const HOOK_EVENT = "Stop";
|
|
1594
|
+
/** A tool finished: the one point inside a turn where a hook can hand the model text. */
|
|
1595
|
+
const MID_TURN_EVENT = "PostToolUse";
|
|
1596
|
+
/** Every hook event Conveno installs. */
|
|
1597
|
+
const HOOK_EVENTS = [HOOK_EVENT, MID_TURN_EVENT];
|
|
1598
|
+
const EMPTY$1 = {
|
|
1599
|
+
stdout: "",
|
|
1600
|
+
exitCode: 0
|
|
1601
|
+
};
|
|
1602
|
+
/**
|
|
1603
|
+
* Quote one word of a hook command. Grok runs the command in a POSIX shell, and on Windows in
|
|
1604
|
+
* Git Bash, PowerShell or cmd.exe, whichever it finds, so the word is written to mean the same in
|
|
1605
|
+
* all of them: double quotes only when it needs them, and on Windows forward slashes.
|
|
1606
|
+
*/
|
|
1607
|
+
function quoteHookWord(arg, platform) {
|
|
1608
|
+
const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
|
|
1609
|
+
return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
|
|
1610
|
+
}
|
|
1611
|
+
const hookCommand = (env, event) => [
|
|
1612
|
+
...env.conveno.command,
|
|
1613
|
+
"hook",
|
|
1614
|
+
"grok",
|
|
1615
|
+
event
|
|
1616
|
+
].map((w) => quoteHookWord(w, env.platform)).join(" ");
|
|
1617
|
+
/** The matcher group in the hook file. Neither event is filtered, so there is no matcher. */
|
|
1618
|
+
const desiredGroup = (env, event) => ({ hooks: [{
|
|
1619
|
+
type: "command",
|
|
1620
|
+
command: hookCommand(env, event),
|
|
1621
|
+
timeout: 5
|
|
1622
|
+
}] });
|
|
1623
|
+
/** Recognizes our hook command for `event` even if the conveno path changed since install. */
|
|
1624
|
+
const isOurHookCommand = (cmd, event) => typeof cmd === "string" && cmd.trim().endsWith(` hook grok ${event}`);
|
|
1625
|
+
const isOurGroup = (event) => (g) => isObject$1(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject$1(h) && isOurHookCommand(h.command, event));
|
|
1626
|
+
const isOurAnyGroup = (g) => HOOK_EVENTS.some((e) => isOurGroup(e)(g));
|
|
1627
|
+
/** The `hooks` object of the hook file, and the list of each of our events when there is one. */
|
|
1628
|
+
function eventsOf(file, path) {
|
|
1629
|
+
const hooks = file.hooks;
|
|
1630
|
+
if (hooks !== void 0 && !isObject$1(hooks)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
|
|
1631
|
+
const lists = /* @__PURE__ */ new Map();
|
|
1632
|
+
for (const event of HOOK_EVENTS) {
|
|
1633
|
+
const list = hooks?.[event];
|
|
1634
|
+
if (list !== void 0 && !Array.isArray(list)) throw new Error(`"hooks.${event}" in ${path} must be a list. Fix the file, then run the install again. Nothing was changed.`);
|
|
1635
|
+
lists.set(event, list);
|
|
1636
|
+
}
|
|
1637
|
+
return {
|
|
1638
|
+
hooks,
|
|
1639
|
+
lists
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
async function readIfExists(path) {
|
|
1643
|
+
try {
|
|
1644
|
+
return await readFile(path, "utf8");
|
|
1645
|
+
} catch (err) {
|
|
1646
|
+
if (err.code === "ENOENT") return null;
|
|
1647
|
+
throw err;
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
const specOf = (env) => {
|
|
1651
|
+
const [command = "conveno", ...args] = [
|
|
1652
|
+
...env.conveno.command,
|
|
1653
|
+
"mcp",
|
|
1654
|
+
"--cli",
|
|
1655
|
+
"grok"
|
|
1656
|
+
];
|
|
1657
|
+
return {
|
|
1658
|
+
command,
|
|
1659
|
+
args
|
|
1660
|
+
};
|
|
1661
|
+
};
|
|
1662
|
+
async function detect$1(env) {
|
|
1663
|
+
const configPaths = [configPath(env)];
|
|
1664
|
+
try {
|
|
1665
|
+
const r = await env.exec("grok", ["--version"]);
|
|
1666
|
+
if (r.code !== 0) return {
|
|
1667
|
+
installed: false,
|
|
1668
|
+
configPaths
|
|
1669
|
+
};
|
|
1670
|
+
const version = parseCliVersion(r.stdout);
|
|
1671
|
+
return {
|
|
1672
|
+
installed: true,
|
|
1673
|
+
binary: "grok",
|
|
1674
|
+
...version ? { version } : {},
|
|
1675
|
+
configPaths
|
|
1676
|
+
};
|
|
1677
|
+
} catch {
|
|
1678
|
+
return {
|
|
1679
|
+
installed: false,
|
|
1680
|
+
configPaths
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
/** First line of the rules file: how Conveno tells the file is its own. */
|
|
1685
|
+
const RULES_MARKER = "<!-- Written by Conveno. `conveno uninstall` removes this file. -->";
|
|
1686
|
+
/** How the agent starts the watcher: the conveno command words, quoted, then `watch`. */
|
|
1687
|
+
const watchCommand = (env) => [...env.conveno.command, "watch"].map((w) => quoteHookWord(w, env.platform)).join(" ");
|
|
1688
|
+
const watchBase = (env) => [...env.conveno.command.map((w) => env.platform === "win32" ? w.replace(/\\/g, "/") : w)].join(" ");
|
|
1689
|
+
/**
|
|
1690
|
+
* The allow rule's pattern: `watch` of this conveno with one session name. Grok matches parsed words
|
|
1691
|
+
* joined by single spaces, without quotes (user guide 22-permissions-and-safety.md, Rule Matching
|
|
1692
|
+
* Reference). Allow is checked per command: the script is split on ; && || | and every part must
|
|
1693
|
+
* match a rule (xai-grok-permission-rules policy/bash_commands.rs:58-104), and a script with `$(...)`
|
|
1694
|
+
* or backticks is not eligible for an allow (bash_permission_script.rs:58-64). So the `*` only spans
|
|
1695
|
+
* the rest of one command, and `[a-z0-9]` keeps the name from starting with `-`, `$` or a quote.
|
|
1696
|
+
* Monitor is checked as a Bash command (xai-grok-tools permission_access.rs:55).
|
|
1697
|
+
*/
|
|
1698
|
+
const watchPattern = (env) => `${watchBase(env)}${WATCH_TAIL}`;
|
|
1699
|
+
/** What older Conveno wrote for this conveno: `watch *`. Uninstall still removes exactly that. */
|
|
1700
|
+
const legacyWatchPattern = (env) => `${watchBase(env)} watch *`;
|
|
1701
|
+
const ownPatterns = (env) => [watchPattern(env), legacyWatchPattern(env)];
|
|
1702
|
+
/**
|
|
1703
|
+
* What the Grok agent is told once, in a rules file Grok loads for every project. Idle wake needs
|
|
1704
|
+
* the agent's own help: Grok has no way to push text into an idle session, but it wakes on every
|
|
1705
|
+
* line a monitor prints, so the agent starts `conveno watch` in one persistent monitor.
|
|
1706
|
+
*/
|
|
1707
|
+
function rulesText(env) {
|
|
1708
|
+
return `${[
|
|
1709
|
+
RULES_MARKER,
|
|
1710
|
+
"# Conveno",
|
|
1711
|
+
"",
|
|
1712
|
+
"Conveno connects this session to your other AI coding sessions. Do this once so their messages wake you while you are idle:",
|
|
1713
|
+
"",
|
|
1714
|
+
"1. Call the conveno `whoami` tool and note your session name.",
|
|
1715
|
+
`2. Call the \`monitor\` tool once with \`persistent: true\`, the description "Conveno messages" and the command \`${watchCommand(env)} <your session name>\`. Do not start a second one while it runs. If it ended, start it again.`,
|
|
1716
|
+
"",
|
|
1717
|
+
"Every line the monitor prints starts with `[conveno]` and is one message:",
|
|
1718
|
+
`- "The user sent a message through Conveno": ${FROM_USER_NOTICE}`,
|
|
1719
|
+
`- "Task from the lead": ${ORCHESTRATOR_TASK_NOTICE}`,
|
|
1720
|
+
`- "sent a message (not from the user)": ${NOT_FROM_USER_NOTICE}`,
|
|
1721
|
+
"",
|
|
1722
|
+
"A line holds at most a short piece of the message. Call the `inbox` tool with `unread_only` false for the full text. While you work, Conveno also adds new messages to your tool results."
|
|
1723
|
+
].join("\n")}\n`;
|
|
1724
|
+
}
|
|
1725
|
+
async function plan$1(env) {
|
|
1726
|
+
const changes = [];
|
|
1727
|
+
const path = configPath(env);
|
|
1728
|
+
const before = await readIfExists(path);
|
|
1729
|
+
const doc = parseToml(path, before ?? "");
|
|
1730
|
+
const spec = specOf(env);
|
|
1731
|
+
const pattern = watchPattern(env);
|
|
1732
|
+
const server = serverOf(doc);
|
|
1733
|
+
if (!matchesSpec(server, spec) || !hasRules(doc, pattern)) changes.push({
|
|
1734
|
+
component: "mcp",
|
|
1735
|
+
kind: server ? "update" : "add",
|
|
1736
|
+
parts: [{
|
|
1737
|
+
name: "MCP server",
|
|
1738
|
+
kind: server ? "update" : "add"
|
|
1739
|
+
}],
|
|
1740
|
+
path,
|
|
1741
|
+
before,
|
|
1742
|
+
after: addConfig(path, before ?? "", spec, pattern),
|
|
1743
|
+
description: `Register the "${SERVER_NAME$1}" MCP server (conveno mcp --cli grok) and allow its tools (permission rule MCPTool(${RULE_PATTERN})) and the idle-wake watcher (permission rule Bash(${pattern})).`
|
|
1744
|
+
});
|
|
1745
|
+
const hp = hooksPath(env);
|
|
1746
|
+
const hookFile = await loadJson$1(hp);
|
|
1747
|
+
const { hooks, lists } = eventsOf(hookFile.value, hp);
|
|
1748
|
+
const edits = [];
|
|
1749
|
+
const parts = [];
|
|
1750
|
+
let anyOurs = false;
|
|
1751
|
+
for (const event of HOOK_EVENTS) {
|
|
1752
|
+
const list = lists.get(event);
|
|
1753
|
+
const want = desiredGroup(env, event);
|
|
1754
|
+
if (list?.some((g) => sameJson$1(g, want))) continue;
|
|
1755
|
+
const has = list?.some(isOurGroup(event)) ?? false;
|
|
1756
|
+
anyOurs ||= has;
|
|
1757
|
+
parts.push({
|
|
1758
|
+
name: `${event} hook`,
|
|
1759
|
+
kind: has ? "update" : "add"
|
|
1760
|
+
});
|
|
1761
|
+
edits.push(...hooks === void 0 && edits.length === 0 ? [{
|
|
1762
|
+
path: ["hooks"],
|
|
1763
|
+
value: { [event]: [want] }
|
|
1764
|
+
}] : list === void 0 ? [{
|
|
1765
|
+
path: ["hooks", event],
|
|
1766
|
+
value: [want]
|
|
1767
|
+
}] : putInList(list, ["hooks", event], want, isOurGroup(event)));
|
|
1768
|
+
}
|
|
1769
|
+
if (edits.length > 0) changes.push({
|
|
1770
|
+
component: "hooks",
|
|
1771
|
+
kind: anyOurs ? "update" : "add",
|
|
1772
|
+
parts,
|
|
1773
|
+
path: hp,
|
|
1774
|
+
before: hookFile.raw,
|
|
1775
|
+
after: editJson$1(hookFile, edits),
|
|
1776
|
+
description: `Add a ${HOOK_EVENT} hook that continues the agent with waiting Conveno messages at the end of a turn, and a ${MID_TURN_EVENT} hook that adds them to a tool result while it works.`
|
|
1777
|
+
});
|
|
1778
|
+
const rp = rulesPath(env);
|
|
1779
|
+
const rulesBefore = await readIfExists(rp);
|
|
1780
|
+
const rulesAfter = rulesText(env);
|
|
1781
|
+
if (rulesBefore !== rulesAfter) changes.push({
|
|
1782
|
+
component: "hooks",
|
|
1783
|
+
kind: rulesBefore === null ? "add" : "update",
|
|
1784
|
+
parts: [{
|
|
1785
|
+
name: "Wake instructions",
|
|
1786
|
+
kind: rulesBefore === null ? "add" : "update"
|
|
1787
|
+
}],
|
|
1788
|
+
path: rp,
|
|
1789
|
+
before: rulesBefore,
|
|
1790
|
+
after: rulesAfter,
|
|
1791
|
+
description: "Tell Grok to start `conveno watch` in a persistent monitor, so messages wake it while idle."
|
|
1792
|
+
});
|
|
1793
|
+
return changes;
|
|
1794
|
+
}
|
|
1795
|
+
async function uninstallPlan$1(env, baseline) {
|
|
1796
|
+
const changes = [];
|
|
1797
|
+
const path = configPath(env);
|
|
1798
|
+
const before = await readIfExists(path);
|
|
1799
|
+
if (before !== null) {
|
|
1800
|
+
const doc = parseToml(path, before);
|
|
1801
|
+
if (serverOf(doc) || hasAnyRule(doc, ownPatterns(env))) changes.push({
|
|
1802
|
+
component: "mcp",
|
|
1803
|
+
kind: "remove",
|
|
1804
|
+
path,
|
|
1805
|
+
before,
|
|
1806
|
+
after: removeConfig(path, before, ownPatterns(env)),
|
|
1807
|
+
description: `Remove the "${SERVER_NAME$1}" MCP server and its permission rules.`
|
|
1808
|
+
});
|
|
1809
|
+
}
|
|
1810
|
+
const hp = hooksPath(env);
|
|
1811
|
+
const hookFile = await loadJson$1(hp);
|
|
1812
|
+
const { hooks, lists } = eventsOf(hookFile.value, hp);
|
|
1813
|
+
if (hookFile.raw !== null && [...lists.values()].some((l) => l?.some(isOurAnyGroup))) {
|
|
1814
|
+
const base = baseline?.get(hp);
|
|
1815
|
+
const onlyOurs = [...lists.values()].every((l) => l === void 0 || l.every(isOurAnyGroup)) && Object.keys(hooks ?? {}).every((k) => HOOK_EVENTS.includes(k)) && Object.keys(hookFile.value).length === 1;
|
|
1816
|
+
const description = "Remove the Conveno hooks.";
|
|
1817
|
+
if (onlyOurs && typeof base !== "string") changes.push({
|
|
1818
|
+
component: "hooks",
|
|
1819
|
+
kind: "remove",
|
|
1820
|
+
path: hp,
|
|
1821
|
+
before: hookFile.raw,
|
|
1822
|
+
after: "",
|
|
1823
|
+
description,
|
|
1824
|
+
deleteFile: true
|
|
1825
|
+
});
|
|
1826
|
+
else {
|
|
1827
|
+
const edits = [];
|
|
1828
|
+
for (const event of HOOK_EVENTS) {
|
|
1829
|
+
const list = lists.get(event);
|
|
1830
|
+
if (!list?.some(isOurGroup(event))) continue;
|
|
1831
|
+
edits.push(...dropFromList(list, ["hooks", event], isOurGroup(event), { keepEmpty: existedBefore(base, ["hooks", event]) }));
|
|
1832
|
+
}
|
|
1833
|
+
changes.push({
|
|
1834
|
+
component: "hooks",
|
|
1835
|
+
kind: "remove",
|
|
1836
|
+
path: hp,
|
|
1837
|
+
before: hookFile.raw,
|
|
1838
|
+
after: editJson$1(hookFile, edits),
|
|
1839
|
+
description
|
|
1840
|
+
});
|
|
1841
|
+
}
|
|
1842
|
+
}
|
|
1843
|
+
const rp = rulesPath(env);
|
|
1844
|
+
const rulesBefore = await readIfExists(rp);
|
|
1845
|
+
if (rulesBefore?.startsWith(RULES_MARKER)) changes.push({
|
|
1846
|
+
component: "hooks",
|
|
1847
|
+
kind: "remove",
|
|
1848
|
+
path: rp,
|
|
1849
|
+
before: rulesBefore,
|
|
1850
|
+
after: "",
|
|
1851
|
+
description: "Remove the Conveno wake instructions.",
|
|
1852
|
+
deleteFile: true
|
|
1853
|
+
});
|
|
1854
|
+
return changes;
|
|
1855
|
+
}
|
|
1856
|
+
/**
|
|
1857
|
+
* Hooks. A hook can hand text to the model in two places:
|
|
1858
|
+
* - PostToolUse: `hookSpecificOutput.additionalContext` lands next to the tool result, inside the
|
|
1859
|
+
* turn (user guide 10-hooks.md, PostToolUse Output). Messages that arrive while Grok works
|
|
1860
|
+
* reach it after its next tool call.
|
|
1861
|
+
* - Stop: records the turn end. With messages waiting, after a genuine turn end (`reason`
|
|
1862
|
+
* `end_turn`), `hookSpecificOutput.additionalContext` keeps the agent working and is shown as
|
|
1863
|
+
* hook feedback, not as a hook error (10-hooks.md, Stop Decision Control). The session-end
|
|
1864
|
+
* fire (`channel_closed`, `shutdown`) only records. Grok overrides the gate after 8
|
|
1865
|
+
* continuations in a turn, and Conveno's auto-mode limit bounds the chain before that.
|
|
1866
|
+
* `UserPromptSubmit` and `SessionStart` output cannot add text, so a message that arrives while
|
|
1867
|
+
* the session is idle reaches it through `conveno watch` in a monitor, not through a hook.
|
|
1868
|
+
* Never throws and never writes to stderr: any failure means "deliver nothing this time".
|
|
1869
|
+
*/
|
|
1870
|
+
async function hook$1(event, input, ctx) {
|
|
1871
|
+
if (event === "PostToolUse") {
|
|
1872
|
+
const text = await pendingHookContext(ctx);
|
|
1873
|
+
return text === null ? EMPTY$1 : context(MID_TURN_EVENT, text);
|
|
1874
|
+
}
|
|
1875
|
+
if (event !== "Stop") return EMPTY$1;
|
|
1876
|
+
const reason = isObject$1(input) ? input.reason : void 0;
|
|
1877
|
+
const text = await endTurnContinuation(ctx, { allowContinue: reason === void 0 || reason === "end_turn" });
|
|
1878
|
+
return text === null ? EMPTY$1 : context(HOOK_EVENT, text);
|
|
1879
|
+
}
|
|
1880
|
+
const context = (hookEventName, additionalContext) => ({
|
|
1881
|
+
stdout: JSON.stringify({ hookSpecificOutput: {
|
|
1882
|
+
hookEventName,
|
|
1883
|
+
additionalContext
|
|
1884
|
+
} }),
|
|
1885
|
+
exitCode: 0
|
|
1886
|
+
});
|
|
1887
|
+
const grokAdapter = {
|
|
1888
|
+
cli: "grok",
|
|
1889
|
+
displayName: "Grok",
|
|
1890
|
+
deliveryTier: "inbox",
|
|
1891
|
+
delivery: () => ({
|
|
1892
|
+
nextTurn: false,
|
|
1893
|
+
endOfTurn: true,
|
|
1894
|
+
idleWake: true
|
|
1895
|
+
}),
|
|
1896
|
+
detect: detect$1,
|
|
1897
|
+
plan: plan$1,
|
|
1898
|
+
uninstallPlan: uninstallPlan$1,
|
|
1899
|
+
hook: hook$1
|
|
1900
|
+
};
|
|
1901
|
+
// ../adapters/opencode/dist/index.js
|
|
1902
|
+
/**
|
|
1903
|
+
* The OpenCode 1.x plugin Conveno installs as `<config dir>/plugins/conveno.js`. OpenCode 1.x loads
|
|
1904
|
+
* every `.js` file in the global `plugins/` folder at startup (https://opencode.ai/docs/plugins/,
|
|
1905
|
+
* "From local files") and calls each exported function with a context that holds an SDK `client`.
|
|
1906
|
+
*
|
|
1907
|
+
* The plugin does no Conveno work itself; it runs `conveno hook opencode <event>`, which finds the
|
|
1908
|
+
* session by its host process (this OpenCode process) like every other hook:
|
|
1909
|
+
*
|
|
1910
|
+
* - On `session.idle` of a top-level session it runs `Idle`. With messages waiting,
|
|
1911
|
+
* that prints the continuation prompt, and the plugin sends it with `client.session.promptAsync`.
|
|
1912
|
+
* - Otherwise it starts `Listen`, which waits in the background and prints a prompt when work
|
|
1913
|
+
* arrives while the session is idle; the plugin sends that the same way.
|
|
1914
|
+
* - When the session turns busy, the plugin is disposed, or a newer listener starts, the listener
|
|
1915
|
+
* is stopped. It also stops by itself when OpenCode exits.
|
|
1916
|
+
*/
|
|
1917
|
+
/** Start of the first line of every Conveno plugin file, whatever the OpenCode line it is for. */
|
|
1918
|
+
const PLUGIN_MARKER_PREFIX = "// conveno-plugin:";
|
|
1919
|
+
/** First line of the 1.x plugin. Uninstall and re-install recognise a plugin by the marker prefix. */
|
|
1920
|
+
const PLUGIN_MARKER = `${PLUGIN_MARKER_PREFIX} 1`;
|
|
1921
|
+
/**
|
|
1922
|
+
* The part both plugins share: the import, the baked-in command, and `run`, which starts
|
|
1923
|
+
* `conveno hook opencode <event>` and resolves with what it prints. Plain JavaScript source text.
|
|
1924
|
+
*/
|
|
1925
|
+
function runHelper(command) {
|
|
1926
|
+
return `import { spawn } from "node:child_process";
|
|
1927
|
+
|
|
1928
|
+
const COMMAND = ${JSON.stringify(command)};
|
|
1929
|
+
// A bare \`conveno\` on Windows is a .cmd shim, which only a shell can start. Every argument is a plain word.
|
|
1930
|
+
const SHELL = process.platform === "win32" && !/\\.exe$/i.test(COMMAND[0]);
|
|
1931
|
+
|
|
1932
|
+
// A hook that hands messages over starts its output with "#conveno-ids <id>,<id>" and the prompt
|
|
1933
|
+
// follows. If sending the prompt fails, the plugin hands those ids back with \`Requeue\`.
|
|
1934
|
+
function split(out) {
|
|
1935
|
+
const m = /^#conveno-ids ([^\\n]*)\\n/.exec(out);
|
|
1936
|
+
if (!m) return { ids: [], text: out };
|
|
1937
|
+
return { ids: m[1].split(",").filter(Boolean), text: out.slice(m[0].length).trim() };
|
|
1938
|
+
}
|
|
1939
|
+
|
|
1940
|
+
function run(event, sessionID, directory, extra) {
|
|
1941
|
+
const [file, ...args] = COMMAND;
|
|
1942
|
+
const child = spawn(file, [...args, "hook", "opencode", event], {
|
|
1943
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
1944
|
+
shell: SHELL,
|
|
1945
|
+
windowsHide: true,
|
|
1946
|
+
});
|
|
1947
|
+
let out = "";
|
|
1948
|
+
child.stdout.setEncoding("utf8");
|
|
1949
|
+
child.stdout.on("data", (chunk) => {
|
|
1950
|
+
out += chunk;
|
|
1951
|
+
});
|
|
1952
|
+
const done = new Promise((resolve) => {
|
|
1953
|
+
child.once("error", () => resolve(""));
|
|
1954
|
+
child.once("close", (code) => resolve(code === 0 ? out.trim() : ""));
|
|
1955
|
+
});
|
|
1956
|
+
child.stdin.on("error", () => {});
|
|
1957
|
+
child.stdin.end(JSON.stringify({ hook_event_name: event, sessionID, directory, ...extra }));
|
|
1958
|
+
return { child, done };
|
|
1959
|
+
}`;
|
|
1960
|
+
}
|
|
1961
|
+
/** The plugin source with the conveno command baked in. Plain JavaScript, no imports beyond Node built-ins. */
|
|
1962
|
+
function pluginSource(command) {
|
|
1963
|
+
return `${PLUGIN_MARKER}
|
|
1964
|
+
// Conveno plugin for OpenCode. Written by \`conveno init\`; \`conveno uninstall\` removes it.
|
|
1965
|
+
// It hands Conveno messages to an idle session. See https://conveno.dev.
|
|
1966
|
+
${runHelper(command)}
|
|
1967
|
+
|
|
1968
|
+
export const ConvenoPlugin = async ({ client }) => {
|
|
1969
|
+
let listener;
|
|
1970
|
+
|
|
1971
|
+
const stop = () => {
|
|
1972
|
+
if (!listener) return;
|
|
1973
|
+
listener.child.kill();
|
|
1974
|
+
listener = undefined;
|
|
1975
|
+
};
|
|
1976
|
+
|
|
1977
|
+
const prompt = async (sessionID, out) => {
|
|
1978
|
+
const { ids, text } = split(out);
|
|
1979
|
+
try {
|
|
1980
|
+
const res = await client.session.promptAsync({
|
|
1981
|
+
path: { id: sessionID },
|
|
1982
|
+
body: { parts: [{ type: "text", text }] },
|
|
1983
|
+
});
|
|
1984
|
+
if (res?.error) throw new Error("prompt failed");
|
|
1985
|
+
} catch {
|
|
1986
|
+
// The session is gone or busy again: hand the messages back so the next turn gets them.
|
|
1987
|
+
if (ids.length > 0) await run("Requeue", sessionID, undefined, { ids }).done;
|
|
1988
|
+
}
|
|
1989
|
+
};
|
|
1990
|
+
|
|
1991
|
+
const titles = new Map();
|
|
1992
|
+
const retitle = async (sessionID) => {
|
|
1993
|
+
try {
|
|
1994
|
+
const name = await run("Title", sessionID).done;
|
|
1995
|
+
if (!name || titles.get(sessionID) === name) return;
|
|
1996
|
+
await client.session.update({ path: { id: sessionID }, body: { title: name } });
|
|
1997
|
+
titles.set(sessionID, name);
|
|
1998
|
+
} catch {
|
|
1999
|
+
// The title is cosmetic.
|
|
2000
|
+
}
|
|
2001
|
+
};
|
|
2002
|
+
|
|
2003
|
+
const topLevel = async (sessionID) => {
|
|
2004
|
+
try {
|
|
2005
|
+
const res = await client.session.get({ path: { id: sessionID } });
|
|
2006
|
+
return !res?.data?.parentID;
|
|
2007
|
+
} catch {
|
|
2008
|
+
return false;
|
|
2009
|
+
}
|
|
2010
|
+
};
|
|
2011
|
+
|
|
2012
|
+
const onIdle = async (sessionID) => {
|
|
2013
|
+
if (!(await topLevel(sessionID))) return;
|
|
2014
|
+
stop();
|
|
2015
|
+
void retitle(sessionID);
|
|
2016
|
+
const now = await run("Idle", sessionID).done;
|
|
2017
|
+
if (now) return prompt(sessionID, now);
|
|
2018
|
+
const current = { ...run("Listen", sessionID), sessionID };
|
|
2019
|
+
listener = current;
|
|
2020
|
+
const text = await current.done;
|
|
2021
|
+
if (listener === current) listener = undefined;
|
|
2022
|
+
if (text) await prompt(sessionID, text);
|
|
2023
|
+
};
|
|
2024
|
+
|
|
2025
|
+
return {
|
|
2026
|
+
event: async ({ event }) => {
|
|
2027
|
+
if (event.type === "session.idle") void onIdle(event.properties.sessionID);
|
|
2028
|
+
else if (
|
|
2029
|
+
event.type === "session.status" &&
|
|
2030
|
+
event.properties.status?.type === "busy" &&
|
|
2031
|
+
event.properties.sessionID === listener?.sessionID
|
|
2032
|
+
) {
|
|
2033
|
+
stop();
|
|
2034
|
+
}
|
|
2035
|
+
},
|
|
2036
|
+
dispose: async () => stop(),
|
|
2037
|
+
};
|
|
2038
|
+
};
|
|
2039
|
+
`;
|
|
2040
|
+
}
|
|
2041
|
+
/**
|
|
2042
|
+
* The OpenCode 2.x plugin Conveno installs as `<config dir>/plugins/conveno.js`, the same path as
|
|
2043
|
+
* the 1.x one. OpenCode 2.x loads every `.js` and `.ts` file in the global `plugins/` folder
|
|
2044
|
+
* (https://opencode.ai/docs/plugins/, "Discover"; `packages/core/src/plugin/module.ts` at tag
|
|
2045
|
+
* v2.4.3 accepts a standalone file whose default export is `{ id, setup }`, the object
|
|
2046
|
+
* `Plugin.define` returns, so the file needs no import of `@opencode/plugin`).
|
|
2047
|
+
*
|
|
2048
|
+
* The plugin runs inside the OpenCode server process, which is also the parent of the MCP server
|
|
2049
|
+
* it starts, so `conveno hook opencode <event>` finds the session by host process like every other
|
|
2050
|
+
* hook. It does no Conveno work itself:
|
|
2051
|
+
*
|
|
2052
|
+
* - Just before a session goes idle (`experimental.idle`, `packages/plugin/src/promise/session.ts`
|
|
2053
|
+
* at v2.4.3) it runs `Idle` and admits waiting messages into the same execution. Every prompt
|
|
2054
|
+
* uses `delivery: "queue"`, so it never cuts into a running turn.
|
|
2055
|
+
* - The session title follows the Conveno name (`ctx.session.update`).
|
|
2056
|
+
* - When an execution of a top-level session in this plugin's directory ends
|
|
2057
|
+
* (`session.execution.succeeded`) it runs `Idle`. With messages waiting, that prints
|
|
2058
|
+
* the continuation prompt, and the plugin sends it with `ctx.session.prompt`
|
|
2059
|
+
* (`POST /api/session/{id}/prompt`).
|
|
2060
|
+
* - After a failed or interrupted execution it runs `Stopped`, which records the end without
|
|
2061
|
+
* continuing. An execution that a newer one superseded, or that a shutdown cut off, does nothing.
|
|
2062
|
+
* - Then it starts `Listen`, which waits in the background and prints a prompt when work arrives
|
|
2063
|
+
* while the session is idle; the plugin sends that the same way.
|
|
2064
|
+
* - `session.execution.started`, a newer listener, or unloading the plugin stops the listener.
|
|
2065
|
+
*
|
|
2066
|
+
* - When a session is deleted (`session.deleted`) it runs `Deleted`, which releases the Conveno
|
|
2067
|
+
* session so it goes offline at once instead of waiting for the MCP server to lapse it.
|
|
2068
|
+
*
|
|
2069
|
+
* `session.status` and `session.idle` are not used: 2.4.3 does not deliver them to plugins.
|
|
2070
|
+
*/
|
|
2071
|
+
/** First line of the 2.x plugin. */
|
|
2072
|
+
const PLUGIN_MARKER_V2 = `${PLUGIN_MARKER_PREFIX} 2`;
|
|
2073
|
+
/** The plugin source with the conveno command baked in. Plain JavaScript, no imports beyond Node built-ins. */
|
|
2074
|
+
function pluginSourceV2(command) {
|
|
2075
|
+
return `${PLUGIN_MARKER_V2}
|
|
2076
|
+
// Conveno plugin for OpenCode 2.x. Written by \`conveno init\`; \`conveno uninstall\` removes it.
|
|
2077
|
+
// It hands Conveno messages to an idle session. See https://conveno.dev.
|
|
2078
|
+
${runHelper(command)}
|
|
2079
|
+
|
|
2080
|
+
export default {
|
|
2081
|
+
id: "conveno",
|
|
2082
|
+
setup(ctx) {
|
|
2083
|
+
const controller = new AbortController();
|
|
2084
|
+
let listener;
|
|
2085
|
+
|
|
2086
|
+
const stop = () => {
|
|
2087
|
+
if (!listener) return;
|
|
2088
|
+
listener.child.kill();
|
|
2089
|
+
listener = undefined;
|
|
2090
|
+
};
|
|
2091
|
+
|
|
2092
|
+
const prompt = async (sessionID, out) => {
|
|
2093
|
+
const { ids, text } = split(out);
|
|
2094
|
+
try {
|
|
2095
|
+
// "queue" waits for the agent's current work and never cuts into a running turn.
|
|
2096
|
+
await ctx.session.prompt({ sessionID, text, delivery: "queue" });
|
|
2097
|
+
} catch {
|
|
2098
|
+
// The session is gone or busy again: hand the messages back so the next turn gets them.
|
|
2099
|
+
if (ids.length > 0) await run("Requeue", sessionID, ctx.location.directory, { ids }).done;
|
|
2100
|
+
}
|
|
2101
|
+
};
|
|
2102
|
+
|
|
2103
|
+
// The server sends every plugin the events of every location it serves. Only top-level
|
|
2104
|
+
// sessions of this plugin's own directory are ours.
|
|
2105
|
+
const ours = async (sessionID) => {
|
|
2106
|
+
try {
|
|
2107
|
+
const info = await ctx.session.get({ sessionID });
|
|
2108
|
+
return !info.parentID && info.location.directory === ctx.location.directory;
|
|
2109
|
+
} catch {
|
|
2110
|
+
return false;
|
|
2111
|
+
}
|
|
2112
|
+
};
|
|
2113
|
+
|
|
2114
|
+
// The session title follows the Conveno name; it is cosmetic, so failures are ignored.
|
|
2115
|
+
const titles = new Map();
|
|
2116
|
+
const retitle = async (sessionID) => {
|
|
2117
|
+
try {
|
|
2118
|
+
const name = await run("Title", sessionID, ctx.location.directory).done;
|
|
2119
|
+
if (!name || titles.get(sessionID) === name) return;
|
|
2120
|
+
await ctx.session.update({ sessionID, title: name });
|
|
2121
|
+
titles.set(sessionID, name);
|
|
2122
|
+
} catch {
|
|
2123
|
+
// Ignored.
|
|
2124
|
+
}
|
|
2125
|
+
};
|
|
2126
|
+
|
|
2127
|
+
// Runs just before the session goes idle. Messages that arrived during the turn are admitted
|
|
2128
|
+
// here, so the same execution carries on instead of the session going idle first.
|
|
2129
|
+
if (typeof ctx.session.hook === "function") {
|
|
2130
|
+
void ctx.session
|
|
2131
|
+
.hook("experimental.idle", async ({ sessionID }) => {
|
|
2132
|
+
if (!(await ours(sessionID))) return;
|
|
2133
|
+
const now = await run("Idle", sessionID, ctx.location.directory).done;
|
|
2134
|
+
if (now) await prompt(sessionID, now);
|
|
2135
|
+
})
|
|
2136
|
+
.catch(() => {});
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
const onEnd = async (sessionID, event) => {
|
|
2140
|
+
if (!(await ours(sessionID))) return;
|
|
2141
|
+
stop();
|
|
2142
|
+
void retitle(sessionID);
|
|
2143
|
+
const now = await run(event, sessionID, ctx.location.directory).done;
|
|
2144
|
+
if (now) return prompt(sessionID, now);
|
|
2145
|
+
const current = { ...run("Listen", sessionID, ctx.location.directory), sessionID };
|
|
2146
|
+
listener = current;
|
|
2147
|
+
const text = await current.done;
|
|
2148
|
+
if (listener === current) listener = undefined;
|
|
2149
|
+
if (text) await prompt(sessionID, text);
|
|
2150
|
+
};
|
|
2151
|
+
|
|
2152
|
+
void (async () => {
|
|
2153
|
+
try {
|
|
2154
|
+
for await (const event of ctx.event.subscribe({
|
|
2155
|
+
types: [
|
|
2156
|
+
"session.execution.started",
|
|
2157
|
+
"session.execution.succeeded",
|
|
2158
|
+
"session.execution.failed",
|
|
2159
|
+
"session.execution.interrupted",
|
|
2160
|
+
"session.deleted",
|
|
2161
|
+
],
|
|
2162
|
+
signal: controller.signal,
|
|
2163
|
+
})) {
|
|
2164
|
+
const { sessionID } = event.data;
|
|
2165
|
+
if (event.type === "session.deleted") {
|
|
2166
|
+
// The session is gone: release its Conveno session so it goes offline now.
|
|
2167
|
+
if (sessionID === listener?.sessionID) stop();
|
|
2168
|
+
void run("Deleted", sessionID, ctx.location.directory).done;
|
|
2169
|
+
} else if (event.type === "session.execution.started") {
|
|
2170
|
+
if (sessionID === listener?.sessionID) stop();
|
|
2171
|
+
} else if (event.type === "session.execution.succeeded") {
|
|
2172
|
+
void onEnd(sessionID, "Idle");
|
|
2173
|
+
} else if (
|
|
2174
|
+
event.type === "session.execution.failed" ||
|
|
2175
|
+
(event.type === "session.execution.interrupted" &&
|
|
2176
|
+
(event.data.reason === "user" || event.data.reason === "inactivity"))
|
|
2177
|
+
) {
|
|
2178
|
+
void onEnd(sessionID, "Stopped");
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
} catch {
|
|
2182
|
+
// The subscription ended with the plugin.
|
|
2183
|
+
}
|
|
2184
|
+
})();
|
|
2185
|
+
|
|
2186
|
+
return () => {
|
|
2187
|
+
controller.abort();
|
|
2188
|
+
stop();
|
|
2189
|
+
};
|
|
2190
|
+
},
|
|
2191
|
+
};
|
|
2192
|
+
`;
|
|
2193
|
+
}
|
|
2194
|
+
const SERVER_NAME = "conveno";
|
|
2195
|
+
const FORMAT = {
|
|
2196
|
+
insertSpaces: true,
|
|
2197
|
+
tabSize: 2,
|
|
2198
|
+
eol: "\n"
|
|
2199
|
+
};
|
|
2200
|
+
/** First OpenCode release that reads `mcp.servers`. There were no 2.0.x or 2.1.x releases. */
|
|
2201
|
+
const V2_MIN = [
|
|
2202
|
+
2,
|
|
2203
|
+
2,
|
|
2204
|
+
0
|
|
2205
|
+
];
|
|
2206
|
+
/** `$XDG_CONFIG_HOME/opencode` when XDG_CONFIG_HOME is an absolute path, else `~/.config/opencode`. */
|
|
2207
|
+
function configDir(env) {
|
|
2208
|
+
const xdg = env.env.XDG_CONFIG_HOME;
|
|
2209
|
+
const base = xdg && isAbsolute(xdg) ? xdg : join(env.home, ".config");
|
|
2210
|
+
return join(base, "opencode");
|
|
2211
|
+
}
|
|
2212
|
+
/** `OPENCODE_CONFIG` names one config file; when set it is the only file we touch. */
|
|
2213
|
+
const customConfig = (env) => env.env.OPENCODE_CONFIG || void 0;
|
|
2214
|
+
/**
|
|
2215
|
+
* `OPENCODE_CONFIG` when set. Otherwise an existing opencode.jsonc, then opencode.json, else a
|
|
2216
|
+
* new opencode.json in the config directory.
|
|
2217
|
+
*/
|
|
2218
|
+
async function locateConfig(env) {
|
|
2219
|
+
const custom = customConfig(env);
|
|
2220
|
+
if (custom) try {
|
|
2221
|
+
return {
|
|
2222
|
+
path: custom,
|
|
2223
|
+
text: await readFile(custom, "utf8")
|
|
2224
|
+
};
|
|
2225
|
+
} catch (err) {
|
|
2226
|
+
if (err.code !== "ENOENT") throw err;
|
|
2227
|
+
return {
|
|
2228
|
+
path: custom,
|
|
2229
|
+
text: null
|
|
2230
|
+
};
|
|
2231
|
+
}
|
|
2232
|
+
const dir = configDir(env);
|
|
2233
|
+
for (const name of ["opencode.jsonc", "opencode.json"]) {
|
|
2234
|
+
const path = join(dir, name);
|
|
2235
|
+
try {
|
|
2236
|
+
return {
|
|
2237
|
+
path,
|
|
2238
|
+
text: await readFile(path, "utf8")
|
|
2239
|
+
};
|
|
2240
|
+
} catch (err) {
|
|
2241
|
+
if (err.code !== "ENOENT") throw err;
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
return {
|
|
2245
|
+
path: join(dir, "opencode.json"),
|
|
2246
|
+
text: null
|
|
2247
|
+
};
|
|
2248
|
+
}
|
|
2249
|
+
function parseConfig(file) {
|
|
2250
|
+
if (file.text === null || file.text.trim() === "") return {};
|
|
2251
|
+
const errors = [];
|
|
2252
|
+
const value = parse(file.text, errors, { allowTrailingComma: true });
|
|
2253
|
+
const first = errors[0];
|
|
2254
|
+
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.`);
|
|
2255
|
+
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.`);
|
|
2256
|
+
return value;
|
|
2257
|
+
}
|
|
2258
|
+
function serverEntry(env, shape) {
|
|
2259
|
+
const command = [
|
|
2260
|
+
...env.conveno.command,
|
|
2261
|
+
"mcp",
|
|
2262
|
+
"--cli",
|
|
2263
|
+
"opencode"
|
|
2264
|
+
];
|
|
2265
|
+
return shape === "v1" ? {
|
|
2266
|
+
type: "local",
|
|
2267
|
+
command,
|
|
2268
|
+
enabled: true
|
|
2269
|
+
} : {
|
|
2270
|
+
type: "local",
|
|
2271
|
+
command
|
|
2272
|
+
};
|
|
2273
|
+
}
|
|
2274
|
+
function parseVersion(text) {
|
|
2275
|
+
const m = /(\d+)\.(\d+)\.(\d+)/.exec(text);
|
|
2276
|
+
return m ? [
|
|
2277
|
+
Number(m[1]),
|
|
2278
|
+
Number(m[2]),
|
|
2279
|
+
Number(m[3])
|
|
2280
|
+
] : void 0;
|
|
2281
|
+
}
|
|
2282
|
+
function isV2OrLater(v) {
|
|
2283
|
+
for (let i = 0; i < 3; i++) if (v[i] !== V2_MIN[i]) return v[i] > V2_MIN[i];
|
|
2284
|
+
return true;
|
|
2285
|
+
}
|
|
2286
|
+
async function installedVersion(env) {
|
|
2287
|
+
try {
|
|
2288
|
+
const res = await env.exec("opencode", ["--version"]);
|
|
2289
|
+
return res.code === 0 ? parseVersion(res.stdout) : void 0;
|
|
2290
|
+
} catch {
|
|
2291
|
+
return;
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
async function chooseShape(config, version) {
|
|
2295
|
+
if (version) return isV2OrLater(version) ? "v2" : "v1";
|
|
2296
|
+
return servers(config) !== void 0 ? "v2" : "v1";
|
|
2297
|
+
}
|
|
2298
|
+
function v1Entry(config) {
|
|
2299
|
+
const mcp = config.mcp;
|
|
2300
|
+
if (mcp === null || typeof mcp !== "object" || Array.isArray(mcp)) return void 0;
|
|
2301
|
+
return mcp[SERVER_NAME];
|
|
2302
|
+
}
|
|
2303
|
+
function pathFor(shape) {
|
|
2304
|
+
return shape === "v1" ? ["mcp", SERVER_NAME] : [
|
|
2305
|
+
"mcp",
|
|
2306
|
+
"servers",
|
|
2307
|
+
SERVER_NAME
|
|
2308
|
+
];
|
|
2309
|
+
}
|
|
2310
|
+
function sameEntry(found, want) {
|
|
2311
|
+
if (found === null || typeof found !== "object") return false;
|
|
2312
|
+
const f = found;
|
|
2313
|
+
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]);
|
|
2314
|
+
}
|
|
2315
|
+
function servers(config) {
|
|
2316
|
+
const mcp = config.mcp;
|
|
2317
|
+
if (mcp === null || typeof mcp !== "object" || Array.isArray(mcp)) return void 0;
|
|
2318
|
+
const s = mcp.servers;
|
|
2319
|
+
if (s === null || typeof s !== "object" || Array.isArray(s)) return void 0;
|
|
2320
|
+
return s;
|
|
2321
|
+
}
|
|
2322
|
+
async function detect(env) {
|
|
2323
|
+
const custom = customConfig(env);
|
|
2324
|
+
const configPaths = custom ? [custom] : [join(configDir(env), "opencode.jsonc"), join(configDir(env), "opencode.json")];
|
|
2325
|
+
try {
|
|
2326
|
+
const res = await env.exec("opencode", ["--version"]);
|
|
2327
|
+
if (res.code !== 0) return {
|
|
2328
|
+
installed: false,
|
|
2329
|
+
configPaths
|
|
2330
|
+
};
|
|
2331
|
+
const version = parseCliVersion(res.stdout);
|
|
2332
|
+
return {
|
|
2333
|
+
installed: true,
|
|
2334
|
+
binary: "opencode",
|
|
2335
|
+
configPaths,
|
|
2336
|
+
...version ? { version } : {}
|
|
2337
|
+
};
|
|
2338
|
+
} catch {
|
|
2339
|
+
return {
|
|
2340
|
+
installed: false,
|
|
2341
|
+
configPaths
|
|
2342
|
+
};
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
/** `<config dir>/plugins/conveno.js`, the global plugin folder OpenCode 1.x and 2.x load. */
|
|
2346
|
+
const pluginPath = (env) => join(configDir(env), "plugins", "conveno.js");
|
|
2347
|
+
async function readText(path) {
|
|
2348
|
+
try {
|
|
2349
|
+
return await readFile(path, "utf8");
|
|
2350
|
+
} catch (err) {
|
|
2351
|
+
if (err.code === "ENOENT") return null;
|
|
2352
|
+
throw err;
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
/**
|
|
2356
|
+
* The plugin API differs between the lines (https://opencode.ai/docs/build/plugins/migrate-v1/), so
|
|
2357
|
+
* each gets its own source at the same path. An unknown version gets nothing rather than a file
|
|
2358
|
+
* that might not load.
|
|
2359
|
+
*/
|
|
2360
|
+
const pluginFor = (env, version) => {
|
|
2361
|
+
if (version === void 0) return void 0;
|
|
2362
|
+
return isV2OrLater(version) ? pluginSourceV2(env.conveno.command) : pluginSource(env.conveno.command);
|
|
2363
|
+
};
|
|
2364
|
+
async function planPlugin(env, version) {
|
|
2365
|
+
const want = pluginFor(env, version);
|
|
2366
|
+
if (want === void 0) return [];
|
|
2367
|
+
const path = pluginPath(env);
|
|
2368
|
+
const before = await readText(path);
|
|
2369
|
+
if (before === want) return [];
|
|
2370
|
+
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.`);
|
|
2371
|
+
return [{
|
|
2372
|
+
component: "hooks",
|
|
2373
|
+
kind: before === null ? "add" : "update",
|
|
2374
|
+
parts: [{
|
|
2375
|
+
name: "plugin file",
|
|
2376
|
+
kind: before === null ? "add" : "update"
|
|
2377
|
+
}],
|
|
2378
|
+
path,
|
|
2379
|
+
before,
|
|
2380
|
+
after: want,
|
|
2381
|
+
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.`
|
|
2382
|
+
}];
|
|
2383
|
+
}
|
|
2384
|
+
async function uninstallPlugin(env) {
|
|
2385
|
+
const path = pluginPath(env);
|
|
2386
|
+
const before = await readText(path);
|
|
2387
|
+
if (before === null || !before.startsWith("// conveno-plugin:")) return [];
|
|
2388
|
+
return [{
|
|
2389
|
+
component: "hooks",
|
|
2390
|
+
kind: "remove",
|
|
2391
|
+
path,
|
|
2392
|
+
before,
|
|
2393
|
+
after: "",
|
|
2394
|
+
deleteFile: true,
|
|
2395
|
+
description: "Remove the Conveno plugin for OpenCode."
|
|
2396
|
+
}];
|
|
2397
|
+
}
|
|
2398
|
+
async function plan(env) {
|
|
2399
|
+
const version = await installedVersion(env);
|
|
2400
|
+
return [...await planMcp(env, version), ...await planPlugin(env, version)];
|
|
2401
|
+
}
|
|
2402
|
+
async function uninstallPlan(env) {
|
|
2403
|
+
return [...await uninstallMcp(env), ...await uninstallPlugin(env)];
|
|
2404
|
+
}
|
|
2405
|
+
async function planMcp(env, version) {
|
|
2406
|
+
const file = await locateConfig(env);
|
|
2407
|
+
const config = parseConfig(file);
|
|
2408
|
+
const shape = await chooseShape(config, version);
|
|
2409
|
+
const want = serverEntry(env, shape);
|
|
2410
|
+
const current = shape === "v1" ? v1Entry(config) : servers(config)?.[SERVER_NAME];
|
|
2411
|
+
if (sameEntry(current, want)) return [];
|
|
2412
|
+
let text = file.text === null || file.text.trim() === "" ? "{}\n" : file.text;
|
|
2413
|
+
const otherShape = shape === "v1" ? "v2" : "v1";
|
|
2414
|
+
const other = otherShape === "v1" ? v1Entry(config) : servers(config)?.[SERVER_NAME];
|
|
2415
|
+
if (other !== void 0) text = applyEdits(text, modify(text, pathFor(otherShape), void 0, { formattingOptions: FORMAT }));
|
|
2416
|
+
let after = applyEdits(text, modify(text, pathFor(shape), want, { formattingOptions: FORMAT }));
|
|
2417
|
+
if (!after.endsWith("\n")) after += "\n";
|
|
2418
|
+
const where = shape === "v1" ? `mcp.${SERVER_NAME}` : `mcp.servers.${SERVER_NAME}`;
|
|
2419
|
+
return [{
|
|
2420
|
+
component: "mcp",
|
|
2421
|
+
kind: current !== void 0 || other !== void 0 ? "update" : "add",
|
|
2422
|
+
parts: [{
|
|
2423
|
+
name: "MCP server",
|
|
2424
|
+
kind: current !== void 0 || other !== void 0 ? "update" : "add"
|
|
2425
|
+
}],
|
|
2426
|
+
path: file.path,
|
|
2427
|
+
before: file.text,
|
|
2428
|
+
after,
|
|
2429
|
+
description: `Add the conveno MCP server (${where}) to the OpenCode global config`
|
|
2430
|
+
}];
|
|
2431
|
+
}
|
|
2432
|
+
async function uninstallMcp(env) {
|
|
2433
|
+
const file = await locateConfig(env);
|
|
2434
|
+
if (file.text === null) return [];
|
|
2435
|
+
const config = parseConfig(file);
|
|
2436
|
+
let text = file.text;
|
|
2437
|
+
const removed = [];
|
|
2438
|
+
if (servers(config)?.[SERVER_NAME] !== void 0) {
|
|
2439
|
+
text = applyEdits(text, modify(text, pathFor("v2"), void 0, { formattingOptions: FORMAT }));
|
|
2440
|
+
removed.push(`mcp.servers.${SERVER_NAME}`);
|
|
2441
|
+
}
|
|
2442
|
+
if (v1Entry(config) !== void 0) {
|
|
2443
|
+
text = applyEdits(text, modify(text, pathFor("v1"), void 0, { formattingOptions: FORMAT }));
|
|
2444
|
+
removed.push(`mcp.${SERVER_NAME}`);
|
|
2445
|
+
}
|
|
2446
|
+
if (removed.length === 0) return [];
|
|
2447
|
+
return [{
|
|
2448
|
+
component: "mcp",
|
|
2449
|
+
kind: "remove",
|
|
2450
|
+
path: file.path,
|
|
2451
|
+
before: file.text,
|
|
2452
|
+
after: text,
|
|
2453
|
+
description: `Remove the conveno MCP server (${removed.join(", ")}) from the OpenCode global config`
|
|
2454
|
+
}];
|
|
2455
|
+
}
|
|
2456
|
+
const EMPTY = {
|
|
2457
|
+
stdout: "",
|
|
2458
|
+
exitCode: 0
|
|
2459
|
+
};
|
|
2460
|
+
/**
|
|
2461
|
+
* Run by the plugin, never by OpenCode itself. Each prints the prompt to send as plain text, which
|
|
2462
|
+
* the plugin sends to the session (1.x `client.session.promptAsync`, 2.x `ctx.session.prompt`).
|
|
2463
|
+
* - Idle: the session's turn ended. With messages waiting, the prompt to continue with.
|
|
2464
|
+
* - Stopped: the turn failed or the user interrupted it. Records the end and never continues.
|
|
2465
|
+
* - Listen: the background listener. Waits for work while the session is idle.
|
|
2466
|
+
* - Requeue: the plugin could not send the prompt; puts the messages (`ids` in the input) back to queued.
|
|
2467
|
+
* - Deleted: the OpenCode session was deleted; unregisters its Conveno session.
|
|
2468
|
+
* - Title: prints the session's Conveno name, which the plugin sets as the OpenCode session title.
|
|
2469
|
+
*/
|
|
2470
|
+
async function hook(event, input, ctx) {
|
|
2471
|
+
const dir = typeof input === "object" && input !== null ? input.directory : void 0;
|
|
2472
|
+
if (typeof dir === "string" && dir !== "") ctx = {
|
|
2473
|
+
...ctx,
|
|
2474
|
+
cwd: dir
|
|
2475
|
+
};
|
|
2476
|
+
const native = typeof input === "object" && input !== null ? input.sessionID : void 0;
|
|
2477
|
+
if (typeof native === "string" && native !== "") ctx = {
|
|
2478
|
+
...ctx,
|
|
2479
|
+
nativeId: native
|
|
2480
|
+
};
|
|
2481
|
+
if (event === "Deleted") {
|
|
2482
|
+
await release(ctx, input);
|
|
2483
|
+
return EMPTY;
|
|
2484
|
+
}
|
|
2485
|
+
if (event === "Requeue") {
|
|
2486
|
+
await requeue(ctx, input);
|
|
2487
|
+
return EMPTY;
|
|
2488
|
+
}
|
|
2489
|
+
const ids = [];
|
|
2490
|
+
if (ctx.client) ctx = {
|
|
2491
|
+
...ctx,
|
|
2492
|
+
client: recordIds(ctx.client, ids)
|
|
2493
|
+
};
|
|
2494
|
+
let text = null;
|
|
2495
|
+
if (event === "Idle") text = await endTurnContinuation(ctx);
|
|
2496
|
+
else if (event === "Stopped") await endTurnContinuation(ctx, { allowContinue: false });
|
|
2497
|
+
else if (event === "Listen") text = await waitForWork(ctx);
|
|
2498
|
+
else if (event === "Title") text = await sessionName(ctx);
|
|
2499
|
+
if (text === null) return EMPTY;
|
|
2500
|
+
return {
|
|
2501
|
+
stdout: ids.length > 0 ? `#conveno-ids ${ids.join(",")}\n${text}` : text,
|
|
2502
|
+
exitCode: 0
|
|
2503
|
+
};
|
|
2504
|
+
}
|
|
2505
|
+
/** The client, with the ids of every message `turn.end` and `turn.wake` return copied into `ids`. */
|
|
2506
|
+
function recordIds(client, ids) {
|
|
2507
|
+
return new Proxy(client, { get(target, prop, receiver) {
|
|
2508
|
+
const value = Reflect.get(target, prop, receiver);
|
|
2509
|
+
if (prop !== "turn.end" && prop !== "turn.wake" || typeof value !== "function") return value;
|
|
2510
|
+
return async (...args) => {
|
|
2511
|
+
const r = await value.apply(target, args);
|
|
2512
|
+
for (const m of r?.messages ?? []) ids.push(m.id);
|
|
2513
|
+
return r;
|
|
2514
|
+
};
|
|
2515
|
+
} });
|
|
2516
|
+
}
|
|
2517
|
+
/** `Deleted`: the OpenCode session is gone, so its Conveno session goes offline now. */
|
|
2518
|
+
async function release(ctx, input) {
|
|
2519
|
+
try {
|
|
2520
|
+
const id = input?.sessionID;
|
|
2521
|
+
if (typeof id !== "string" || id === "") return;
|
|
2522
|
+
const session = await ownSession(ctx);
|
|
2523
|
+
if (!session) return;
|
|
2524
|
+
await ctx.client["session.unregister"]({ sessionId: session.id });
|
|
2525
|
+
} catch {}
|
|
2526
|
+
}
|
|
2527
|
+
/** `Requeue`: sending the prompt failed, so the messages go back to queued for the next turn. */
|
|
2528
|
+
async function requeue(ctx, input) {
|
|
2529
|
+
try {
|
|
2530
|
+
const ids = input?.ids;
|
|
2531
|
+
if (!Array.isArray(ids) || ids.length === 0) return;
|
|
2532
|
+
const session = await ownSession(ctx);
|
|
2533
|
+
if (!session) return;
|
|
2534
|
+
await ctx.client["message.requeue"]({
|
|
2535
|
+
sessionId: session.id,
|
|
2536
|
+
ids
|
|
2537
|
+
});
|
|
2538
|
+
} catch {}
|
|
2539
|
+
}
|
|
2540
|
+
async function sessionName(ctx) {
|
|
2541
|
+
try {
|
|
2542
|
+
const session = await ownSession(ctx);
|
|
2543
|
+
return session?.name ? session.name : null;
|
|
2544
|
+
} catch {
|
|
2545
|
+
return null;
|
|
2546
|
+
}
|
|
2547
|
+
}
|
|
2548
|
+
/** Only the plugin delivers, on 1.x and 2.x alike; it adds nothing to a prompt the user types. */
|
|
2549
|
+
function delivery(detection) {
|
|
2550
|
+
const supported = detection.version !== void 0 && parseVersion(detection.version) !== void 0;
|
|
2551
|
+
return {
|
|
2552
|
+
nextTurn: false,
|
|
2553
|
+
endOfTurn: supported,
|
|
2554
|
+
idleWake: supported
|
|
2555
|
+
};
|
|
2556
|
+
}
|
|
2557
|
+
const opencodeAdapter = {
|
|
2558
|
+
cli: "opencode",
|
|
2559
|
+
displayName: "OpenCode",
|
|
2560
|
+
deliveryTier: "inbox",
|
|
2561
|
+
detect,
|
|
2562
|
+
plan,
|
|
2563
|
+
uninstallPlan,
|
|
2564
|
+
hook,
|
|
2565
|
+
listenEvents: ["Listen"],
|
|
2566
|
+
delivery
|
|
2567
|
+
};
|
|
2568
|
+
// src/hook-entry.ts
|
|
2569
|
+
function readAllStdin() {
|
|
2570
|
+
if (process.stdin.isTTY) return Promise.resolve("");
|
|
2571
|
+
return new Promise((resolve, reject) => {
|
|
2572
|
+
let data = "";
|
|
2573
|
+
process.stdin.setEncoding("utf8");
|
|
2574
|
+
process.stdin.on("data", (c) => {
|
|
2575
|
+
data += c;
|
|
2576
|
+
});
|
|
2577
|
+
process.stdin.on("end", () => resolve(data));
|
|
2578
|
+
process.stdin.on("error", reject);
|
|
2579
|
+
});
|
|
2580
|
+
}
|
|
2581
|
+
/** `kill(pid, 0)` liveness: EPERM means the process exists but belongs to someone else. */
|
|
2582
|
+
function isProcessAlive(pid) {
|
|
2583
|
+
try {
|
|
2584
|
+
process.kill(pid, 0);
|
|
2585
|
+
return true;
|
|
2586
|
+
} catch (e) {
|
|
2587
|
+
return e.code === "EPERM";
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
function createHookCtx() {
|
|
2591
|
+
const launcherPaths = process.argv[1] ? [process.argv[1]] : [];
|
|
2592
|
+
return {
|
|
2593
|
+
dataDir: dataDir(process.platform, process.env, homedir()),
|
|
2594
|
+
adapters: [
|
|
2595
|
+
claudeAdapter,
|
|
2596
|
+
codexAdapter,
|
|
2597
|
+
opencodeAdapter,
|
|
2598
|
+
cursorAdapter,
|
|
2599
|
+
copilotAdapter,
|
|
2600
|
+
antigravityAdapter,
|
|
2601
|
+
grokAdapter
|
|
2602
|
+
],
|
|
2603
|
+
out: (s) => void process.stdout.write(s),
|
|
2604
|
+
err: (s) => void process.stderr.write(s),
|
|
2605
|
+
readStdin: readAllStdin,
|
|
2606
|
+
connect,
|
|
2607
|
+
ancestry: (timeoutMs) => readAncestry({
|
|
2608
|
+
timeoutMs,
|
|
2609
|
+
launcherPaths
|
|
2610
|
+
}),
|
|
2611
|
+
hostLookup: {
|
|
2612
|
+
ppid: process.ppid,
|
|
2613
|
+
launcherPaths
|
|
2614
|
+
},
|
|
2615
|
+
isAlive: isProcessAlive,
|
|
2616
|
+
hookTimeoutMs: 2e3
|
|
2617
|
+
};
|
|
2618
|
+
}
|
|
2619
|
+
function runHookEntry(argv) {
|
|
2620
|
+
return runHook(createHookCtx(), argv);
|
|
2621
|
+
}
|
|
2622
|
+
export { opencodeAdapter as a, copilotAdapter as c, runHookEntry as i, claudeAdapter as l, isProcessAlive as n, grokAdapter as o, readAllStdin as r, cursorAdapter as s, createHookCtx as t };
|