@conveno/cli 0.1.1 → 0.2.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1289 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { Et as readAncestry, Gt as startTurnContext, M as dataDir, R as dropFromList, V as endTurnContinuation, Vt as sameJson, W as existedBefore, et as isObject, ot as loadJson, pt as parseCliVersion, vt as pendingHookContext, wt as putInList, z as editJson } from "./dist-_sq6DmrE.js";
4
+ import { a as Za, n as opencodeAdapter, o as cs, r as codexAdapter, s as claudeAdapter } from "./dist-BVE5ihb8.js";
5
+ import { readFile } from "node:fs/promises";
6
+ import { n as connect } from "./dist-BEZPNGU5.js";
7
+ import { t as runHook } from "./hook-DlTGn8Do.js";
8
+ // ../adapters/antigravity/dist/index.js
9
+ const SERVER_NAME$3 = "conveno";
10
+ /** The name of our entry in hooks.json. Antigravity keys hooks by an arbitrary name. */
11
+ const HOOK_NAME = "conveno";
12
+ /**
13
+ * SessionStart fires when a conversation starts; PreInvocation before every model call; Stop when
14
+ * the agent loop is about to stop, where in auto mode a waiting message continues it.
15
+ */
16
+ const HOOK_EVENTS$2 = [
17
+ "SessionStart",
18
+ "PreInvocation",
19
+ "Stop"
20
+ ];
21
+ /** The permission rule that lets the agent call our tools without asking. */
22
+ const PERMISSION_RULE = `mcp(${SERVER_NAME$3}/*)`;
23
+ const EMPTY$3 = {
24
+ stdout: "",
25
+ exitCode: 0
26
+ };
27
+ /** Everything Antigravity CLI keeps for the user lives under `~/.gemini`. */
28
+ function paths$2(env) {
29
+ const root = join(env.home, ".gemini");
30
+ return {
31
+ mcp: join(root, "config", "mcp_config.json"),
32
+ settings: join(root, "antigravity-cli", "settings.json"),
33
+ hooks: join(root, "config", "hooks.json")
34
+ };
35
+ }
36
+ /**
37
+ * Quote one word of a hook command. Antigravity's docs do not say which shell runs a hook, so the
38
+ * word is written to mean the same in bash, cmd.exe and POSIX sh: double quotes only when the word
39
+ * needs them, and on Windows forward slashes, which every Windows API Node uses accepts, so no
40
+ * backslash has to be escaped.
41
+ */
42
+ function quoteHookWord$1(arg, platform) {
43
+ const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
44
+ return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
45
+ }
46
+ const hookCommand$2 = (env, event) => [
47
+ ...env.conveno.command,
48
+ "hook",
49
+ "antigravity",
50
+ event
51
+ ].map((w) => quoteHookWord$1(w, env.platform)).join(" ");
52
+ const mcpArgs$2 = (env) => [
53
+ ...env.conveno.command,
54
+ "mcp",
55
+ "--cli",
56
+ "antigravity"
57
+ ];
58
+ const desiredServer$2 = (env) => {
59
+ const [command = "conveno", ...args] = mcpArgs$2(env);
60
+ return {
61
+ command,
62
+ args
63
+ };
64
+ };
65
+ const desiredHandlers = (env, event) => [{
66
+ type: "command",
67
+ command: hookCommand$2(env, event),
68
+ timeout: 5
69
+ }];
70
+ /** Recognizes our hook command even if the conveno path changed since install. */
71
+ const isOurHookCommand$2 = (cmd) => typeof cmd === "string" && /(^|\s)hook antigravity (SessionStart|PreInvocation|Stop)$/.test(cmd.trim());
72
+ const listOf = (names) => `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
73
+ const handlersOf = (entry, event) => {
74
+ const h = entry[event];
75
+ return Array.isArray(h) ? h : [];
76
+ };
77
+ const hasOurHandler = (entry) => HOOK_EVENTS$2.some((e) => handlersOf(entry, e).some((h) => isObject(h) && isOurHookCommand$2(h.command)));
78
+ function mcpServers(config, path) {
79
+ const s = config.mcpServers;
80
+ if (s === void 0) return {};
81
+ if (!isObject(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
82
+ return s;
83
+ }
84
+ /** The `permissions.allow` list, or undefined when there is none. */
85
+ function allowList$1(settings, path) {
86
+ const p = settings.permissions;
87
+ if (p === void 0) return void 0;
88
+ if (!isObject(p)) throw new Error(`"permissions" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
89
+ const a = p.allow;
90
+ if (a === void 0) return void 0;
91
+ if (!Array.isArray(a)) throw new Error(`"permissions.allow" in ${path} must be a list. Fix the file, then run the install again. Nothing was changed.`);
92
+ return a;
93
+ }
94
+ /** Our entry in hooks.json, or undefined. A hook of that name that is not ours is the user's: refuse. */
95
+ function ourHookEntry(hooksFile, path) {
96
+ const e = hooksFile[HOOK_NAME];
97
+ if (e === void 0) return void 0;
98
+ if (!isObject(e) || !hasOurHandler(e)) throw new Error(`${path} already has a hook named "${HOOK_NAME}" that is not Conveno's. Rename it, then run the install again. Nothing was changed.`);
99
+ return e;
100
+ }
101
+ async function detect$3(env) {
102
+ const p = paths$2(env);
103
+ const configPaths = [
104
+ p.mcp,
105
+ p.settings,
106
+ p.hooks
107
+ ];
108
+ try {
109
+ const r = await env.exec("agy", ["--version"]);
110
+ if (r.code !== 0) return {
111
+ installed: false,
112
+ configPaths
113
+ };
114
+ const version = parseCliVersion(r.stdout);
115
+ return {
116
+ installed: true,
117
+ binary: "agy",
118
+ ...version ? { version } : {},
119
+ configPaths
120
+ };
121
+ } catch {
122
+ return {
123
+ installed: false,
124
+ configPaths
125
+ };
126
+ }
127
+ }
128
+ async function plan$3(env) {
129
+ const p = paths$2(env);
130
+ const changes = [];
131
+ const mcpFile = await loadJson(p.mcp);
132
+ const servers = mcpServers(mcpFile.value, p.mcp);
133
+ const wantServer = desiredServer$2(env);
134
+ if (!sameJson(servers["conveno"], wantServer)) changes.push({
135
+ component: "mcp",
136
+ kind: servers["conveno"] === void 0 ? "add" : "update",
137
+ path: p.mcp,
138
+ before: mcpFile.raw,
139
+ after: editJson(mcpFile, [{
140
+ path: ["mcpServers", SERVER_NAME$3],
141
+ value: wantServer
142
+ }]),
143
+ description: `Register the "${SERVER_NAME$3}" MCP server (conveno mcp --cli antigravity).`
144
+ });
145
+ const setFile = await loadJson(p.settings);
146
+ const allow = allowList$1(setFile.value, p.settings);
147
+ if (!allow?.includes("mcp(conveno/*)")) {
148
+ const edit = setFile.value.permissions === void 0 ? {
149
+ path: ["permissions"],
150
+ value: { allow: [PERMISSION_RULE] }
151
+ } : allow === void 0 ? {
152
+ path: ["permissions", "allow"],
153
+ value: [PERMISSION_RULE]
154
+ } : {
155
+ path: [
156
+ "permissions",
157
+ "allow",
158
+ allow.length
159
+ ],
160
+ value: PERMISSION_RULE,
161
+ insert: true
162
+ };
163
+ changes.push({
164
+ component: "mcp",
165
+ kind: "add",
166
+ path: p.settings,
167
+ before: setFile.raw,
168
+ after: editJson(setFile, [edit]),
169
+ description: `Allow the agent to call Conveno's tools without asking (${PERMISSION_RULE}). They only exchange messages between your own sessions.`
170
+ });
171
+ }
172
+ const hooksFile = await loadJson(p.hooks);
173
+ const entry = ourHookEntry(hooksFile.value, p.hooks);
174
+ const edits = [];
175
+ for (const e of HOOK_EVENTS$2) {
176
+ const want = desiredHandlers(env, e);
177
+ if (!sameJson(entry ? handlersOf(entry, e) : void 0, want)) edits.push({
178
+ path: [HOOK_NAME, e],
179
+ value: want
180
+ });
181
+ }
182
+ if (edits.length > 0) changes.push({
183
+ component: "hooks",
184
+ kind: entry ? "update" : "add",
185
+ path: p.hooks,
186
+ before: hooksFile.raw,
187
+ after: editJson(hooksFile, edits),
188
+ description: `Add ${listOf(HOOK_EVENTS$2)} hooks that deliver Conveno messages to Antigravity on the next prompt and, in auto mode, at the end of a turn.`
189
+ });
190
+ return changes;
191
+ }
192
+ async function uninstallPlan$3(env, baseline) {
193
+ const p = paths$2(env);
194
+ const changes = [];
195
+ const mcpFile = await loadJson(p.mcp);
196
+ if ("conveno" in mcpServers(mcpFile.value, p.mcp)) changes.push({
197
+ component: "mcp",
198
+ kind: "remove",
199
+ path: p.mcp,
200
+ before: mcpFile.raw,
201
+ after: editJson(mcpFile, [{
202
+ path: ["mcpServers", SERVER_NAME$3],
203
+ value: void 0
204
+ }]),
205
+ description: `Remove the "${SERVER_NAME$3}" MCP server.`
206
+ });
207
+ const setFile = await loadJson(p.settings);
208
+ const drops = dropFromList(allowList$1(setFile.value, p.settings), ["permissions", "allow"], (r) => r === PERMISSION_RULE, { keepEmpty: existedBefore(baseline?.get(p.settings), ["permissions", "allow"]) });
209
+ if (drops.length > 0) {
210
+ const alone = drops.length === 1 && drops[0]?.path.length === 2;
211
+ const only = Object.keys(setFile.value.permissions).length === 1 && !existedBefore(baseline?.get(p.settings), ["permissions"]);
212
+ changes.push({
213
+ component: "mcp",
214
+ kind: "remove",
215
+ path: p.settings,
216
+ before: setFile.raw,
217
+ after: editJson(setFile, alone && only ? [{
218
+ path: ["permissions"],
219
+ value: void 0
220
+ }] : drops),
221
+ description: `Remove the ${PERMISSION_RULE} permission.`
222
+ });
223
+ }
224
+ const hooksFile = await loadJson(p.hooks);
225
+ if (ourHookEntry(hooksFile.value, p.hooks)) changes.push({
226
+ component: "hooks",
227
+ kind: "remove",
228
+ path: p.hooks,
229
+ before: hooksFile.raw,
230
+ after: editJson(hooksFile, [{
231
+ path: [HOOK_NAME],
232
+ value: void 0
233
+ }]),
234
+ description: `Remove the Conveno ${listOf(HOOK_EVENTS$2)} hooks.`
235
+ });
236
+ return changes;
237
+ }
238
+ const isHookEvent$2 = (e) => HOOK_EVENTS$2.includes(e);
239
+ /**
240
+ * - SessionStart, PreInvocation: both accept `injectSteps`. An injected system message stays in the
241
+ * conversation, so a step is added only when a message is waiting.
242
+ * - Stop: records the turn end. In auto mode with messages waiting, after a turn that ended on its
243
+ * own (`terminationReason` `model_stop`, no `error`), `{"decision":"continue","reason":"<text>"}`
244
+ * re-enters the loop and `reason` becomes a system message. The input has no loop-guard flag and
245
+ * Antigravity has no idle wake, so a message that arrives during a continued turn is delivered
246
+ * at its end; Conveno's auto-mode limit bounds the chain. While background tasks still run
247
+ * (`fullyIdle` false) the agent is not done, so nothing is recorded or delivered yet: another
248
+ * Stop follows when they finish.
249
+ * Never throws and never writes to stderr: any failure means "deliver nothing this time".
250
+ */
251
+ async function hook$3(event, input, ctx) {
252
+ if (!isHookEvent$2(event)) return EMPTY$3;
253
+ if (event === "Stop") {
254
+ const stop = isObject(input) ? input : {};
255
+ if (stop.fullyIdle === false) return EMPTY$3;
256
+ const completed = (stop.terminationReason === void 0 || stop.terminationReason === "model_stop") && (stop.error === void 0 || stop.error === "");
257
+ const reason = await endTurnContinuation(ctx, { allowContinue: completed });
258
+ if (reason === null) return EMPTY$3;
259
+ return {
260
+ stdout: JSON.stringify({
261
+ decision: "continue",
262
+ reason
263
+ }),
264
+ exitCode: 0
265
+ };
266
+ }
267
+ const text = await pendingHookContext(ctx);
268
+ if (text === null) return EMPTY$3;
269
+ return {
270
+ stdout: JSON.stringify({ injectSteps: [{ systemMessage: { systemMessage: text } }] }),
271
+ exitCode: 0
272
+ };
273
+ }
274
+ const antigravityAdapter = {
275
+ cli: "antigravity",
276
+ displayName: "Antigravity CLI",
277
+ deliveryTier: "next_turn",
278
+ delivery: () => ({
279
+ nextTurn: true,
280
+ endOfTurn: true,
281
+ idleWake: false
282
+ }),
283
+ detect: detect$3,
284
+ plan: plan$3,
285
+ uninstallPlan: uninstallPlan$3,
286
+ hook: hook$3
287
+ };
288
+ // ../adapters/copilot/dist/index.js
289
+ const SERVER_NAME$2 = "conveno";
290
+ /**
291
+ * `sessionStart` and `userPromptSubmitted` add context for the model; `agentStop` ends a turn and,
292
+ * in auto mode, continues with waiting messages.
293
+ */
294
+ const HOOK_EVENTS$1 = [
295
+ "sessionStart",
296
+ "userPromptSubmitted",
297
+ "agentStop"
298
+ ];
299
+ /** Our own hook file inside `~/.copilot/hooks/`, which Copilot reads as every `*.json` there. */
300
+ const HOOK_FILE = "conveno.json";
301
+ const EMPTY$2 = {
302
+ stdout: "",
303
+ exitCode: 0
304
+ };
305
+ /** `COPILOT_HOME` moves every Copilot CLI file; it defaults to `~/.copilot`. */
306
+ function paths$1(env) {
307
+ const dir = env.env.COPILOT_HOME || join(env.home, ".copilot");
308
+ return {
309
+ mcp: join(dir, "mcp-config.json"),
310
+ hooks: join(dir, "hooks", HOOK_FILE)
311
+ };
312
+ }
313
+ const SAFE_WORD = /^[A-Za-z0-9_@%+=:,./-]+$/;
314
+ /**
315
+ * Quote one word for the hook's `bash` field: POSIX single quotes. Windows paths use forward
316
+ * slashes, which every shell and Windows API accepts.
317
+ */
318
+ function bashWord(arg) {
319
+ const word = arg.replace(/\\/g, "/");
320
+ return SAFE_WORD.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
321
+ }
322
+ /** Quote one word for the hook's `powershell` field: single quotes, doubled inside. */
323
+ function powershellWord(arg) {
324
+ const word = arg.replace(/\\/g, "/");
325
+ return SAFE_WORD.test(word) ? word : `'${word.replace(/'/g, "''")}'`;
326
+ }
327
+ /**
328
+ * The hook entry. Copilot runs `bash` on macOS and Linux and `powershell` on Windows, and takes
329
+ * the command as one string, so both are written whatever the platform of this install: the file
330
+ * then stays right if the home directory is shared with a Windows machine through WSL.
331
+ */
332
+ function hookEntry$1(env, event) {
333
+ const words = [
334
+ ...env.conveno.command,
335
+ "hook",
336
+ "copilot",
337
+ event
338
+ ];
339
+ const ps = words.map(powershellWord);
340
+ const call = /^'/.test(ps[0] ?? "") ? "& " : "";
341
+ return {
342
+ type: "command",
343
+ bash: words.map(bashWord).join(" "),
344
+ powershell: call + ps.join(" "),
345
+ timeoutSec: 5
346
+ };
347
+ }
348
+ const mcpArgs$1 = (env) => [
349
+ ...env.conveno.command,
350
+ "mcp",
351
+ "--cli",
352
+ "copilot"
353
+ ];
354
+ /** The same shape `copilot mcp add` writes. */
355
+ const desiredServer$1 = (env) => {
356
+ const [command = "conveno", ...args] = mcpArgs$1(env);
357
+ return {
358
+ tools: ["*"],
359
+ type: "local",
360
+ command,
361
+ args
362
+ };
363
+ };
364
+ /** Recognizes our hook command even if the conveno path changed since install. */
365
+ const isOurCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook copilot (sessionStart|userPromptSubmitted|agentStop)$/.test(cmd.trim());
366
+ const isOurEntry$1 = (e) => isObject(e) && [
367
+ e.bash,
368
+ e.powershell,
369
+ e.command
370
+ ].some(isOurCommand);
371
+ function entriesOf$1(hooks, event) {
372
+ const g = hooks[event];
373
+ return Array.isArray(g) ? g : [];
374
+ }
375
+ function hasExactHook$1(hooks, event, want) {
376
+ return entriesOf$1(hooks, event).some((e) => isObject(e) && e.bash === want.bash && e.powershell === want.powershell);
377
+ }
378
+ function hooksObject$1(file, path) {
379
+ const h = file.hooks;
380
+ if (h === void 0) return {};
381
+ if (!isObject(h)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
382
+ return h;
383
+ }
384
+ function mcpObject$1(config, path) {
385
+ const s = config.mcpServers;
386
+ if (s === void 0) return {};
387
+ if (!isObject(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
388
+ return s;
389
+ }
390
+ /** `copilot --version` prints "GitHub Copilot CLI 1.0.117." with a full stop after the number. */
391
+ const versionOf = (stdout) => parseCliVersion(stdout)?.replace(/\.+$/, "");
392
+ async function detect$2(env) {
393
+ const p = paths$1(env);
394
+ const configPaths = [p.mcp, p.hooks];
395
+ try {
396
+ const r = await env.exec("copilot", ["--version"]);
397
+ if (r.code !== 0) return {
398
+ installed: false,
399
+ configPaths
400
+ };
401
+ const version = versionOf(r.stdout);
402
+ return {
403
+ installed: true,
404
+ binary: "copilot",
405
+ ...version ? { version } : {},
406
+ configPaths
407
+ };
408
+ } catch {
409
+ return {
410
+ installed: false,
411
+ configPaths
412
+ };
413
+ }
414
+ }
415
+ async function plan$2(env) {
416
+ const p = paths$1(env);
417
+ const changes = [];
418
+ const mcpFile = await loadJson(p.mcp);
419
+ const servers = mcpObject$1(mcpFile.value, p.mcp);
420
+ const want = desiredServer$1(env);
421
+ if (!sameJson(servers["conveno"], want)) changes.push({
422
+ component: "mcp",
423
+ kind: servers["conveno"] === void 0 ? "add" : "update",
424
+ path: p.mcp,
425
+ before: mcpFile.raw,
426
+ after: editJson(mcpFile, [{
427
+ path: ["mcpServers", SERVER_NAME$2],
428
+ value: want
429
+ }]),
430
+ description: `Register the "${SERVER_NAME$2}" MCP server for Copilot CLI (conveno mcp --cli copilot).`,
431
+ viaCommand: [
432
+ "copilot",
433
+ "mcp",
434
+ "add",
435
+ SERVER_NAME$2,
436
+ "--",
437
+ ...mcpArgs$1(env)
438
+ ]
439
+ });
440
+ const hookFile = await loadJson(p.hooks);
441
+ const hooks = hooksObject$1(hookFile.value, p.hooks);
442
+ const missing = HOOK_EVENTS$1.filter((e) => !hasExactHook$1(hooks, e, hookEntry$1(env, e)));
443
+ if (missing.length > 0) {
444
+ const edits = [];
445
+ if (hookFile.value.version === void 0) edits.push({
446
+ path: ["version"],
447
+ value: 1
448
+ });
449
+ for (const e of missing) edits.push(...putInList(hooks[e], ["hooks", e], hookEntry$1(env, e), isOurEntry$1));
450
+ const installed = HOOK_EVENTS$1.some((e) => entriesOf$1(hooks, e).some(isOurEntry$1));
451
+ changes.push({
452
+ component: "hooks",
453
+ kind: installed ? "update" : "add",
454
+ path: p.hooks,
455
+ before: hookFile.raw,
456
+ after: editJson(hookFile, edits),
457
+ description: `Add ${missing.join(", ")} hooks that deliver Conveno messages to Copilot CLI on the next turn and, in auto mode, at the end of a turn.`
458
+ });
459
+ }
460
+ return changes;
461
+ }
462
+ async function uninstallPlan$2(env, baseline) {
463
+ const p = paths$1(env);
464
+ const changes = [];
465
+ const mcpFile = await loadJson(p.mcp);
466
+ if ("conveno" in mcpObject$1(mcpFile.value, p.mcp)) changes.push({
467
+ component: "mcp",
468
+ kind: "remove",
469
+ path: p.mcp,
470
+ before: mcpFile.raw,
471
+ after: editJson(mcpFile, [{
472
+ path: ["mcpServers", SERVER_NAME$2],
473
+ value: void 0
474
+ }]),
475
+ description: `Remove the "${SERVER_NAME$2}" MCP server.`,
476
+ viaCommand: [
477
+ "copilot",
478
+ "mcp",
479
+ "remove",
480
+ SERVER_NAME$2
481
+ ]
482
+ });
483
+ const hookFile = await loadJson(p.hooks);
484
+ const hooks = hooksObject$1(hookFile.value, p.hooks);
485
+ const next = { ...hooks };
486
+ const edits = [];
487
+ for (const e of HOOK_EVENTS$1) {
488
+ const drops = dropFromList(hooks[e], ["hooks", e], isOurEntry$1, { keepEmpty: existedBefore(baseline?.get(p.hooks), ["hooks", e]) });
489
+ if (drops.length === 0) continue;
490
+ if (drops.length === 1 && drops[0]?.path.length === 2) delete next[e];
491
+ edits.push(...drops);
492
+ }
493
+ if (edits.length > 0) {
494
+ if (Object.keys(next).length === 0 && !existedBefore(baseline?.get(p.hooks), ["hooks"])) edits.push({
495
+ path: ["hooks"],
496
+ value: void 0
497
+ });
498
+ changes.push({
499
+ component: "hooks",
500
+ kind: "remove",
501
+ path: p.hooks,
502
+ before: hookFile.raw,
503
+ after: editJson(hookFile, edits),
504
+ description: "Remove the Conveno sessionStart, userPromptSubmitted and agentStop hooks."
505
+ });
506
+ }
507
+ return changes;
508
+ }
509
+ const isHookEvent$1 = (e) => HOOK_EVENTS$1.includes(e);
510
+ /**
511
+ * - sessionStart, userPromptSubmitted: `{ "additionalContext": "<text>" }`. `sessionStart` adds it
512
+ * as a first message of the session; `userPromptSubmitted` adds it to the prompt being submitted
513
+ * and marks the turn started.
514
+ * - agentStop: records the turn end. In auto mode with messages waiting, `decision: "block"` with
515
+ * the framed messages as `reason`, which Copilot runs as another turn. Like Codex, Copilot has no
516
+ * idle wake, so this also happens when `stop_hook_active` is set; Copilot ends the chain after 8
517
+ * blocks in a row, and Conveno's auto-mode limit bounds it before that.
518
+ * Never throws and never writes to stderr: any failure means "deliver nothing this time".
519
+ */
520
+ async function hook$2(event, _input, ctx) {
521
+ if (!isHookEvent$1(event)) return EMPTY$2;
522
+ if (event === "agentStop") {
523
+ const reason = await endTurnContinuation(ctx);
524
+ if (reason === null) return EMPTY$2;
525
+ return {
526
+ stdout: JSON.stringify({
527
+ decision: "block",
528
+ reason
529
+ }),
530
+ exitCode: 0
531
+ };
532
+ }
533
+ const additionalContext = event === "sessionStart" ? await pendingHookContext(ctx) : await startTurnContext(ctx);
534
+ if (additionalContext === null) return EMPTY$2;
535
+ return {
536
+ stdout: JSON.stringify({ additionalContext }),
537
+ exitCode: 0
538
+ };
539
+ }
540
+ const copilotAdapter = {
541
+ cli: "copilot",
542
+ displayName: "GitHub Copilot CLI",
543
+ deliveryTier: "next_turn",
544
+ delivery: () => ({
545
+ nextTurn: true,
546
+ endOfTurn: true,
547
+ idleWake: false
548
+ }),
549
+ detect: detect$2,
550
+ plan: plan$2,
551
+ uninstallPlan: uninstallPlan$2,
552
+ hook: hook$2
553
+ };
554
+ // ../adapters/cursor/dist/index.js
555
+ const SERVER_NAME$1 = "conveno";
556
+ /**
557
+ * Hooks that can add context to the conversation: `sessionStart` for a new chat and `postToolUse`
558
+ * after each tool call. `beforeSubmitPrompt` is not here because it can only allow or block a
559
+ * prompt, never add to it. `stop` ends a turn and, in auto mode, continues with waiting messages.
560
+ */
561
+ const HOOK_EVENTS = [
562
+ "sessionStart",
563
+ "postToolUse",
564
+ "stop"
565
+ ];
566
+ /** The `permissions.allow` token that lets the agent call every tool of the conveno server. */
567
+ const MCP_PERMISSION = `Mcp(${SERVER_NAME$1}:*)`;
568
+ const EMPTY$1 = {
569
+ stdout: "",
570
+ exitCode: 0
571
+ };
572
+ /**
573
+ * `mcp.json` and `hooks.json` are always read from `~/.cursor`. The CLI's own settings file moves
574
+ * with `CURSOR_CONFIG_DIR`, or with `XDG_CONFIG_HOME` on Linux and BSD, and `CURSOR_CONFIG_DIR` wins.
575
+ */
576
+ function paths(env) {
577
+ const dir = join(env.home, ".cursor");
578
+ const custom = env.env.CURSOR_CONFIG_DIR;
579
+ const xdg = env.env.XDG_CONFIG_HOME;
580
+ const xdgApplies = env.platform !== "win32" && env.platform !== "darwin";
581
+ const cliConfig = custom ? join(custom, "cli-config.json") : xdg && xdgApplies ? join(xdg, "cursor", "cli-config.json") : join(dir, "cli-config.json");
582
+ return {
583
+ mcp: join(dir, "mcp.json"),
584
+ hooks: join(dir, "hooks.json"),
585
+ cliConfig
586
+ };
587
+ }
588
+ /**
589
+ * Quote one word of a hook command. On Windows the desktop app runs hook commands through
590
+ * PowerShell, so words are written for PowerShell: single quotes, and forward slashes in paths
591
+ * (Windows accepts `/` everywhere, and it keeps `\` away from every quoting rule). Elsewhere the
592
+ * command runs in a POSIX shell.
593
+ */
594
+ function quoteWord(arg, platform) {
595
+ if (platform === "win32") {
596
+ const word = arg.replace(/\\/g, "/");
597
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(word) ? word : `'${word.replace(/'/g, "''")}'`;
598
+ }
599
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, `'\\''`)}'`;
600
+ }
601
+ function hookCommand$1(env, event) {
602
+ const words = [
603
+ ...env.conveno.command,
604
+ "hook",
605
+ "cursor",
606
+ event
607
+ ].map((w) => quoteWord(w, env.platform));
608
+ return (env.platform === "win32" && /^'/.test(words[0] ?? "") ? "& " : "") + words.join(" ");
609
+ }
610
+ /**
611
+ * `stop` sets `loop_limit: null`: Cursor's own cap (5 follow-ups by default) would end auto mode
612
+ * for the conversation, and Conveno's own auto-mode limit already bounds it.
613
+ */
614
+ const hookEntry = (env, event) => ({
615
+ command: hookCommand$1(env, event),
616
+ timeout: 5,
617
+ ...event === "stop" ? { loop_limit: null } : {}
618
+ });
619
+ const mcpArgs = (env) => [
620
+ ...env.conveno.command,
621
+ "mcp",
622
+ "--cli",
623
+ "cursor"
624
+ ];
625
+ const desiredServer = (env) => {
626
+ const [command = "conveno", ...args] = mcpArgs(env);
627
+ return {
628
+ type: "stdio",
629
+ command,
630
+ args
631
+ };
632
+ };
633
+ /** Recognizes our hook command even if the conveno path changed since install. */
634
+ const isOurHookCommand$1 = (cmd) => typeof cmd === "string" && /(^|\s)hook cursor (sessionStart|postToolUse|stop)$/.test(cmd.trim());
635
+ const isOurEntry = (e) => isObject(e) && isOurHookCommand$1(e.command);
636
+ function entriesOf(hooks, event) {
637
+ const g = hooks[event];
638
+ return Array.isArray(g) ? g : [];
639
+ }
640
+ const hasExactHook = (hooks, event, want) => entriesOf(hooks, event).some((e) => sameJson(e, want));
641
+ function hooksObject(file, path) {
642
+ const h = file.hooks;
643
+ if (h === void 0) return {};
644
+ if (!isObject(h)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
645
+ return h;
646
+ }
647
+ function mcpObject(config, path) {
648
+ const s = config.mcpServers;
649
+ if (s === void 0) return {};
650
+ if (!isObject(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
651
+ return s;
652
+ }
653
+ /** The `permissions.allow` list of cli-config.json, or undefined when it is not there. */
654
+ function allowList(config, path) {
655
+ const p = config.permissions;
656
+ if (p === void 0) return void 0;
657
+ if (!isObject(p)) throw new Error(`"permissions" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
658
+ const a = p.allow;
659
+ if (a === void 0) return void 0;
660
+ 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.`);
661
+ return a;
662
+ }
663
+ async function detect$1(env) {
664
+ const p = paths(env);
665
+ const configPaths = [
666
+ p.mcp,
667
+ p.hooks,
668
+ p.cliConfig
669
+ ];
670
+ for (const binary of ["cursor-agent", "agent"]) try {
671
+ const r = await env.exec(binary, ["--version"]);
672
+ if (r.code !== 0) continue;
673
+ if (binary === "agent" && !/^\d{4}\.\d{1,2}\.\d{1,2}/.test(r.stdout.trim())) continue;
674
+ const version = parseCliVersion(r.stdout);
675
+ return {
676
+ installed: true,
677
+ binary,
678
+ ...version ? { version } : {},
679
+ configPaths
680
+ };
681
+ } catch {}
682
+ return {
683
+ installed: false,
684
+ configPaths
685
+ };
686
+ }
687
+ async function plan$1(env) {
688
+ const p = paths(env);
689
+ const changes = [];
690
+ const mcpFile = await loadJson(p.mcp);
691
+ const servers = mcpObject(mcpFile.value, p.mcp);
692
+ const want = desiredServer(env);
693
+ if (!sameJson(servers["conveno"], want)) changes.push({
694
+ component: "mcp",
695
+ kind: servers["conveno"] === void 0 ? "add" : "update",
696
+ path: p.mcp,
697
+ before: mcpFile.raw,
698
+ after: editJson(mcpFile, [{
699
+ path: ["mcpServers", SERVER_NAME$1],
700
+ value: want
701
+ }]),
702
+ description: `Register the "${SERVER_NAME$1}" MCP server for the Cursor CLI (conveno mcp --cli cursor).`
703
+ });
704
+ const cfgFile = await loadJson(p.cliConfig);
705
+ const allow = allowList(cfgFile.value, p.cliConfig);
706
+ if (!allow?.includes("Mcp(conveno:*)")) {
707
+ const edits = [];
708
+ if (cfgFile.raw === null || cfgFile.raw.trim() === "") edits.push({
709
+ path: ["version"],
710
+ value: 1
711
+ }, {
712
+ path: ["editor"],
713
+ value: { vimMode: false }
714
+ }, {
715
+ path: ["permissions"],
716
+ value: {
717
+ allow: [MCP_PERMISSION],
718
+ deny: []
719
+ }
720
+ });
721
+ else if (cfgFile.value.permissions === void 0) edits.push({
722
+ path: ["permissions"],
723
+ value: {
724
+ allow: [MCP_PERMISSION],
725
+ deny: []
726
+ }
727
+ });
728
+ else if (allow === void 0) edits.push({
729
+ path: ["permissions", "allow"],
730
+ value: [MCP_PERMISSION]
731
+ });
732
+ else edits.push({
733
+ path: [
734
+ "permissions",
735
+ "allow",
736
+ allow.length
737
+ ],
738
+ value: MCP_PERMISSION,
739
+ insert: true
740
+ });
741
+ changes.push({
742
+ component: "mcp",
743
+ kind: "add",
744
+ path: p.cliConfig,
745
+ before: cfgFile.raw,
746
+ after: editJson(cfgFile, edits),
747
+ description: `Allow the agent to call the "${SERVER_NAME$1}" server's tools without asking (${MCP_PERMISSION}). They only exchange messages between your own sessions.`
748
+ });
749
+ }
750
+ const hookFile = await loadJson(p.hooks);
751
+ const hooks = hooksObject(hookFile.value, p.hooks);
752
+ const missing = HOOK_EVENTS.filter((e) => !hasExactHook(hooks, e, hookEntry(env, e)));
753
+ if (missing.length > 0) {
754
+ const edits = [];
755
+ if (hookFile.value.version === void 0) edits.push({
756
+ path: ["version"],
757
+ value: 1
758
+ });
759
+ for (const e of missing) edits.push(...putInList(hooks[e], ["hooks", e], hookEntry(env, e), isOurEntry));
760
+ const installed = HOOK_EVENTS.some((e) => entriesOf(hooks, e).some(isOurEntry));
761
+ changes.push({
762
+ component: "hooks",
763
+ kind: installed ? "update" : "add",
764
+ path: p.hooks,
765
+ before: hookFile.raw,
766
+ after: editJson(hookFile, edits),
767
+ description: `Add ${missing.join(", ")} hooks that deliver Conveno messages to the Cursor CLI on the next turn and, in auto mode, at the end of a turn.`
768
+ });
769
+ }
770
+ return changes;
771
+ }
772
+ async function uninstallPlan$1(env, baseline) {
773
+ const p = paths(env);
774
+ const changes = [];
775
+ const mcpFile = await loadJson(p.mcp);
776
+ if ("conveno" in mcpObject(mcpFile.value, p.mcp)) changes.push({
777
+ component: "mcp",
778
+ kind: "remove",
779
+ path: p.mcp,
780
+ before: mcpFile.raw,
781
+ after: editJson(mcpFile, [{
782
+ path: ["mcpServers", SERVER_NAME$1],
783
+ value: void 0
784
+ }]),
785
+ description: `Remove the "${SERVER_NAME$1}" MCP server.`
786
+ });
787
+ const cfgFile = await loadJson(p.cliConfig);
788
+ const at = (allowList(cfgFile.value, p.cliConfig) ?? []).flatMap((x, i) => x === "Mcp(conveno:*)" ? [i] : []);
789
+ if (at.length > 0) changes.push({
790
+ component: "mcp",
791
+ kind: "remove",
792
+ path: p.cliConfig,
793
+ before: cfgFile.raw,
794
+ after: editJson(cfgFile, at.reverse().map((i) => ({
795
+ path: [
796
+ "permissions",
797
+ "allow",
798
+ i
799
+ ],
800
+ value: void 0
801
+ }))),
802
+ description: `Remove ${MCP_PERMISSION} from the allowed permissions.`
803
+ });
804
+ const hookFile = await loadJson(p.hooks);
805
+ const hooks = hooksObject(hookFile.value, p.hooks);
806
+ const next = { ...hooks };
807
+ const edits = [];
808
+ for (const e of HOOK_EVENTS) {
809
+ const drops = dropFromList(hooks[e], ["hooks", e], isOurEntry, { keepEmpty: existedBefore(baseline?.get(p.hooks), ["hooks", e]) });
810
+ if (drops.length === 0) continue;
811
+ if (drops.length === 1 && drops[0]?.path.length === 2) delete next[e];
812
+ edits.push(...drops);
813
+ }
814
+ if (edits.length > 0) {
815
+ if (Object.keys(next).length === 0 && !existedBefore(baseline?.get(p.hooks), ["hooks"])) edits.push({
816
+ path: ["hooks"],
817
+ value: void 0
818
+ });
819
+ changes.push({
820
+ component: "hooks",
821
+ kind: "remove",
822
+ path: p.hooks,
823
+ before: hookFile.raw,
824
+ after: editJson(hookFile, edits),
825
+ description: "Remove the Conveno sessionStart, postToolUse and stop hooks."
826
+ });
827
+ }
828
+ return changes;
829
+ }
830
+ const isHookEvent = (e) => HOOK_EVENTS.includes(e);
831
+ /**
832
+ * - sessionStart, postToolUse: `{ "additional_context": "<text>" }`, added to the chat's initial
833
+ * context or to the conversation after the tool result.
834
+ * - stop: records the turn end. In auto mode with messages waiting, after a turn that `completed`,
835
+ * `{ "followup_message": "<text>" }`, which Cursor submits as the next user message. An aborted
836
+ * or failed turn never continues. Like Codex, Cursor has no idle wake, so this also runs on a
837
+ * turn that was itself a follow-up; Conveno's auto-mode limit bounds the chain.
838
+ * Never throws and never writes to stderr: any failure means "deliver nothing this time".
839
+ */
840
+ async function hook$1(event, input, ctx) {
841
+ if (!isHookEvent(event)) return EMPTY$1;
842
+ if (event === "stop") {
843
+ const status = isObject(input) ? input.status : void 0;
844
+ const followup = await endTurnContinuation(ctx, { allowContinue: status === void 0 || status === "completed" });
845
+ if (followup === null) return EMPTY$1;
846
+ return {
847
+ stdout: JSON.stringify({ followup_message: followup }),
848
+ exitCode: 0
849
+ };
850
+ }
851
+ const additionalContext = await pendingHookContext(ctx);
852
+ if (additionalContext === null) return EMPTY$1;
853
+ return {
854
+ stdout: JSON.stringify({ additional_context: additionalContext }),
855
+ exitCode: 0
856
+ };
857
+ }
858
+ const cursorAdapter = {
859
+ cli: "cursor",
860
+ displayName: "Cursor CLI",
861
+ deliveryTier: "next_turn",
862
+ delivery: () => ({
863
+ nextTurn: true,
864
+ endOfTurn: true,
865
+ idleWake: false
866
+ }),
867
+ detect: detect$1,
868
+ plan: plan$1,
869
+ uninstallPlan: uninstallPlan$1,
870
+ hook: hook$1
871
+ };
872
+ // ../adapters/grok/dist/index.js
873
+ const SERVER_NAME = "conveno";
874
+ /** The pattern of the allow rule: every tool of our server, in Grok's `server__tool` spelling. */
875
+ const RULE_PATTERN = `${SERVER_NAME}__*`;
876
+ var ConfigParseError = class extends Error {};
877
+ function parseToml(path, text) {
878
+ try {
879
+ return cs(text);
880
+ } catch (err) {
881
+ 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.`);
882
+ }
883
+ }
884
+ const isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
885
+ function serverOf(doc) {
886
+ const ours = isTable(doc.mcp_servers) ? doc.mcp_servers[SERVER_NAME] : void 0;
887
+ return isTable(ours) ? ours : void 0;
888
+ }
889
+ const matchesSpec = (server, spec) => server !== void 0 && server.command === spec.command && JSON.stringify(server.args) === JSON.stringify(spec.args);
890
+ /** True for the allow rule Conveno writes. Extra keys on the rule make it someone else's. */
891
+ const isOurRule = (r) => isTable(r) && r.action === "allow" && r.tool === "mcp" && r.pattern === "conveno__*" && Object.keys(r).length === 3;
892
+ function rulesOf(doc) {
893
+ const rules = isTable(doc.permission) ? doc.permission.rules : void 0;
894
+ return Array.isArray(rules) ? rules : void 0;
895
+ }
896
+ const hasRule = (doc) => rulesOf(doc)?.some(isOurRule) ?? false;
897
+ const eolOf = (text) => text.includes("\r\n") ? "\r\n" : "\n";
898
+ /** TOML basic strings use the same escapes as JSON for everything we write. */
899
+ const q = (s) => JSON.stringify(s);
900
+ function serverText(spec, eol) {
901
+ return [
902
+ `[mcp_servers.${SERVER_NAME}]`,
903
+ `command = ${q(spec.command)}`,
904
+ `args = [${spec.args.map(q).join(", ")}]`,
905
+ ""
906
+ ].join(eol);
907
+ }
908
+ function ruleText(eol) {
909
+ return [
910
+ "[[permission.rules]]",
911
+ "action = \"allow\"",
912
+ "tool = \"mcp\"",
913
+ `pattern = ${q(RULE_PATTERN)}`,
914
+ ""
915
+ ].join(eol);
916
+ }
917
+ const EMPTYABLE = /* @__PURE__ */ new Set([
918
+ "mcp_servers",
919
+ "permission",
920
+ "rules"
921
+ ]);
922
+ /** A copy of `v` in which an emptied `mcp_servers`, `permission` or `rules` is gone, children first. */
923
+ function prune(v) {
924
+ if (Array.isArray(v)) return v.map(prune);
925
+ if (!isTable(v)) return v;
926
+ const out = {};
927
+ for (const [k, child] of Object.entries(v)) {
928
+ const p = prune(child);
929
+ if (!((Array.isArray(p) && p.length === 0 || isTable(p) && Object.keys(p).length === 0) && EMPTYABLE.has(k))) out[k] = p;
930
+ }
931
+ return out;
932
+ }
933
+ /** Compare parsed data, treating an emptied `mcp_servers`, `permission` or `rules` as missing. */
934
+ const sameData = (a, b) => JSON.stringify(prune(a)) === JSON.stringify(prune(b));
935
+ /** `text` with a header line as the start of each section. The first one has no header. */
936
+ function sections(text) {
937
+ const out = [{
938
+ key: null,
939
+ text: ""
940
+ }];
941
+ for (const line of text.split(/(?<=\n)/)) {
942
+ const m = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/.exec(line.replace(/\r?\n$/, ""));
943
+ if (m) out.push({
944
+ key: m[1].replace(/["'\s]/g, ""),
945
+ text: line
946
+ });
947
+ else out.at(-1).text += line;
948
+ }
949
+ return out;
950
+ }
951
+ /**
952
+ * Drop the sections whose header is `key` (or a subtable of it) and for which `drop` returns true.
953
+ * The blank line that separated a dropped last section from the rest goes with it.
954
+ */
955
+ function dropSections(text, keys, drop) {
956
+ const all = sections(text);
957
+ let lastDropped = false;
958
+ let out = all.filter((s, i) => {
959
+ const hit = s.key !== null && keys.some((k) => s.key === k || s.key?.startsWith(`${k}.`)) && drop(s.text);
960
+ if (i === all.length - 1) lastDropped = hit;
961
+ return !hit;
962
+ }).map((s) => s.text).join("");
963
+ if (lastDropped) out = out.replace(/(\r?\n)+$/, "") + (out.trim() === "" ? "" : eolOf(text));
964
+ return out;
965
+ }
966
+ const parsesTo = (text, expected) => {
967
+ try {
968
+ return sameData(cs(text), expected);
969
+ } catch {
970
+ return false;
971
+ }
972
+ };
973
+ /**
974
+ * Add our server table and our allow rule where they are missing, by appending text to the file. If
975
+ * the result does not parse to the expected data (for example the user already defines the rules as
976
+ * an inline `rules = [...]`), fall back to a comment-preserving patch.
977
+ */
978
+ function addConfig(path, before, spec) {
979
+ const doc = parseToml(path, before);
980
+ const expected = structuredClone(doc);
981
+ const servers = isTable(expected.mcp_servers) ? expected.mcp_servers : {};
982
+ servers[SERVER_NAME] = {
983
+ command: spec.command,
984
+ args: spec.args
985
+ };
986
+ expected.mcp_servers = servers;
987
+ const permission = isTable(expected.permission) ? expected.permission : {};
988
+ const rules = Array.isArray(permission.rules) ? permission.rules : [];
989
+ if (!rules.some(isOurRule)) rules.push({
990
+ action: "allow",
991
+ tool: "mcp",
992
+ pattern: RULE_PATTERN
993
+ });
994
+ permission.rules = rules;
995
+ expected.permission = permission;
996
+ const eol = eolOf(before);
997
+ const needServer = !matchesSpec(serverOf(doc), spec);
998
+ let text = needServer && serverOf(doc) ? removeServerText(before) : before;
999
+ const append = (block) => {
1000
+ const sep = text === "" ? "" : text.endsWith("\n") ? eol : eol + eol;
1001
+ text = text + sep + block;
1002
+ };
1003
+ if (needServer) append(serverText(spec, eol));
1004
+ if (!hasRule(doc)) append(ruleText(eol));
1005
+ if (parsesTo(text, expected)) return text;
1006
+ return Za(before, expected);
1007
+ }
1008
+ function removeServerText(text) {
1009
+ return dropSections(text, [`mcp_servers.${SERVER_NAME}`], () => true);
1010
+ }
1011
+ /** Remove our server table (and its subtables) and our allow rule. Everything else stays byte for byte. */
1012
+ function removeConfig(path, before) {
1013
+ const doc = parseToml(path, before);
1014
+ const expected = structuredClone(doc);
1015
+ if (isTable(expected.mcp_servers)) delete expected.mcp_servers[SERVER_NAME];
1016
+ const rules = rulesOf(expected);
1017
+ if (rules && isTable(expected.permission)) expected.permission.rules = rules.filter((r) => !isOurRule(r));
1018
+ const text = dropSections(removeServerText(before), ["permission.rules"], (section) => {
1019
+ try {
1020
+ const rule = cs(section).permission?.rules;
1021
+ return rule?.length === 1 && isOurRule(rule[0]);
1022
+ } catch {
1023
+ return false;
1024
+ }
1025
+ });
1026
+ if (parsesTo(text, expected)) return text;
1027
+ return Za(before, expected);
1028
+ }
1029
+ /** `$GROK_HOME`, else `~/.grok` (`%USERPROFILE%\.grok` on Windows). */
1030
+ const grokDir = (env) => env.env.GROK_HOME || join(env.home, ".grok");
1031
+ const configPath = (env) => join(grokDir(env), "config.toml");
1032
+ /**
1033
+ * Grok loads every `*.json` file in `$GROK_HOME/hooks`, always trusted. Conveno's hook gets a file
1034
+ * of its own: `config.toml` carries the MCP change, and one file cannot take two changes.
1035
+ */
1036
+ const hooksPath = (env) => join(grokDir(env), "hooks", "conveno.json");
1037
+ /** The one hook event Conveno uses: the agent is about to end its turn. */
1038
+ const HOOK_EVENT = "Stop";
1039
+ const EMPTY = {
1040
+ stdout: "",
1041
+ exitCode: 0
1042
+ };
1043
+ /**
1044
+ * Quote one word of a hook command. Grok runs the command in a POSIX shell, and on Windows in
1045
+ * Git Bash, PowerShell or cmd.exe, whichever it finds, so the word is written to mean the same in
1046
+ * all of them: double quotes only when it needs them, and on Windows forward slashes.
1047
+ */
1048
+ function quoteHookWord(arg, platform) {
1049
+ const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
1050
+ return /^[A-Za-z0-9_@%+=:,./\\-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
1051
+ }
1052
+ const hookCommand = (env) => [
1053
+ ...env.conveno.command,
1054
+ "hook",
1055
+ "grok",
1056
+ HOOK_EVENT
1057
+ ].map((w) => quoteHookWord(w, env.platform)).join(" ");
1058
+ /** The matcher group in the hook file. `Stop` ignores a matcher, so there is none. */
1059
+ const desiredGroup = (env) => ({ hooks: [{
1060
+ type: "command",
1061
+ command: hookCommand(env),
1062
+ timeout: 5
1063
+ }] });
1064
+ /** Recognizes our hook command even if the conveno path changed since install. */
1065
+ const isOurHookCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook grok Stop$/.test(cmd.trim());
1066
+ const isOurGroup = (g) => isObject(g) && Array.isArray(g.hooks) && g.hooks.some((h) => isObject(h) && isOurHookCommand(h.command));
1067
+ /** The `hooks` object of the hook file, and its `Stop` list when there is one. */
1068
+ function stopOf(file, path) {
1069
+ const hooks = file.hooks;
1070
+ if (hooks !== void 0 && !isObject(hooks)) throw new Error(`"hooks" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
1071
+ const stop = hooks?.[HOOK_EVENT];
1072
+ if (stop !== void 0 && !Array.isArray(stop)) throw new Error(`"hooks.${HOOK_EVENT}" in ${path} must be a list. Fix the file, then run the install again. Nothing was changed.`);
1073
+ return {
1074
+ hooks,
1075
+ stop
1076
+ };
1077
+ }
1078
+ async function readIfExists(path) {
1079
+ try {
1080
+ return await readFile(path, "utf8");
1081
+ } catch (err) {
1082
+ if (err.code === "ENOENT") return null;
1083
+ throw err;
1084
+ }
1085
+ }
1086
+ const specOf = (env) => {
1087
+ const [command = "conveno", ...args] = [
1088
+ ...env.conveno.command,
1089
+ "mcp",
1090
+ "--cli",
1091
+ "grok"
1092
+ ];
1093
+ return {
1094
+ command,
1095
+ args
1096
+ };
1097
+ };
1098
+ async function detect(env) {
1099
+ const configPaths = [configPath(env)];
1100
+ try {
1101
+ const r = await env.exec("grok", ["--version"]);
1102
+ if (r.code !== 0) return {
1103
+ installed: false,
1104
+ configPaths
1105
+ };
1106
+ const version = parseCliVersion(r.stdout);
1107
+ return {
1108
+ installed: true,
1109
+ binary: "grok",
1110
+ ...version ? { version } : {},
1111
+ configPaths
1112
+ };
1113
+ } catch {
1114
+ return {
1115
+ installed: false,
1116
+ configPaths
1117
+ };
1118
+ }
1119
+ }
1120
+ async function plan(env) {
1121
+ const changes = [];
1122
+ const path = configPath(env);
1123
+ const before = await readIfExists(path);
1124
+ const doc = parseToml(path, before ?? "");
1125
+ const spec = specOf(env);
1126
+ const server = serverOf(doc);
1127
+ if (!matchesSpec(server, spec) || !hasRule(doc)) changes.push({
1128
+ component: "mcp",
1129
+ kind: server ? "update" : "add",
1130
+ path,
1131
+ before,
1132
+ after: addConfig(path, before ?? "", spec),
1133
+ description: `Register the "${SERVER_NAME}" MCP server (conveno mcp --cli grok) and allow its tools (permission rule MCPTool(${RULE_PATTERN})).`
1134
+ });
1135
+ const hp = hooksPath(env);
1136
+ const hookFile = await loadJson(hp);
1137
+ const { hooks, stop } = stopOf(hookFile.value, hp);
1138
+ const want = desiredGroup(env);
1139
+ if (!stop?.some((g) => sameJson(g, want))) {
1140
+ const edits = hooks === void 0 ? [{
1141
+ path: ["hooks"],
1142
+ value: { [HOOK_EVENT]: [want] }
1143
+ }] : putInList(stop, ["hooks", HOOK_EVENT], want, isOurGroup);
1144
+ changes.push({
1145
+ component: "hooks",
1146
+ kind: stop?.some(isOurGroup) ? "update" : "add",
1147
+ path: hp,
1148
+ before: hookFile.raw,
1149
+ after: editJson(hookFile, edits),
1150
+ description: `Add a ${HOOK_EVENT} hook that, in auto mode, continues the agent with waiting Conveno messages at the end of a turn.`
1151
+ });
1152
+ }
1153
+ return changes;
1154
+ }
1155
+ async function uninstallPlan(env, baseline) {
1156
+ const changes = [];
1157
+ const path = configPath(env);
1158
+ const before = await readIfExists(path);
1159
+ if (before !== null) {
1160
+ const doc = parseToml(path, before);
1161
+ if (serverOf(doc) || hasRule(doc)) changes.push({
1162
+ component: "mcp",
1163
+ kind: "remove",
1164
+ path,
1165
+ before,
1166
+ after: removeConfig(path, before),
1167
+ description: `Remove the "${SERVER_NAME}" MCP server and its permission rule.`
1168
+ });
1169
+ }
1170
+ const hp = hooksPath(env);
1171
+ const hookFile = await loadJson(hp);
1172
+ const { hooks, stop } = stopOf(hookFile.value, hp);
1173
+ if (hookFile.raw === null || !stop?.some(isOurGroup)) return changes;
1174
+ const base = baseline?.get(hp);
1175
+ const onlyOurs = stop.every(isOurGroup) && Object.keys(hooks ?? {}).length === 1 && Object.keys(hookFile.value).length === 1;
1176
+ const description = `Remove the Conveno ${HOOK_EVENT} hook.`;
1177
+ if (onlyOurs && typeof base !== "string") changes.push({
1178
+ component: "hooks",
1179
+ kind: "remove",
1180
+ path: hp,
1181
+ before: hookFile.raw,
1182
+ after: "",
1183
+ description,
1184
+ deleteFile: true
1185
+ });
1186
+ else changes.push({
1187
+ component: "hooks",
1188
+ kind: "remove",
1189
+ path: hp,
1190
+ before: hookFile.raw,
1191
+ after: editJson(hookFile, dropFromList(stop, ["hooks", HOOK_EVENT], isOurGroup, { keepEmpty: existedBefore(base, ["hooks", HOOK_EVENT]) })),
1192
+ description
1193
+ });
1194
+ return changes;
1195
+ }
1196
+ /**
1197
+ * Grok has no hook that can add text to the next prompt: `UserPromptSubmit` and `SessionStart`
1198
+ * output cannot inject context. Messages reach a Grok session through the `inbox` tool, and in
1199
+ * auto mode at the end of a turn:
1200
+ * - Stop: records the turn end. In auto mode with messages waiting, after a genuine turn end
1201
+ * (`reason` `end_turn`), `{"decision":"block","reason":"<text>"}`, which Grok feeds to the model
1202
+ * as a user message and runs another round. The session-end fire (`channel_closed`, `shutdown`)
1203
+ * only records. Grok has no idle wake, so this also runs while `stopHookActive` is set; Grok
1204
+ * overrides the hook after 8 continuations in a turn, and Conveno's auto-mode limit bounds the
1205
+ * chain before that.
1206
+ * Never throws and never writes to stderr: any failure means "deliver nothing this time".
1207
+ */
1208
+ async function hook(event, input, ctx) {
1209
+ if (event !== "Stop") return EMPTY;
1210
+ const reason = isObject(input) ? input.reason : void 0;
1211
+ const text = await endTurnContinuation(ctx, { allowContinue: reason === void 0 || reason === "end_turn" });
1212
+ if (text === null) return EMPTY;
1213
+ return {
1214
+ stdout: JSON.stringify({
1215
+ decision: "block",
1216
+ reason: text
1217
+ }),
1218
+ exitCode: 0
1219
+ };
1220
+ }
1221
+ const grokAdapter = {
1222
+ cli: "grok",
1223
+ displayName: "Grok",
1224
+ deliveryTier: "inbox",
1225
+ delivery: () => ({
1226
+ nextTurn: false,
1227
+ endOfTurn: true,
1228
+ idleWake: false
1229
+ }),
1230
+ detect,
1231
+ plan,
1232
+ uninstallPlan,
1233
+ hook
1234
+ };
1235
+ // src/hook-entry.ts
1236
+ function readAllStdin() {
1237
+ if (process.stdin.isTTY) return Promise.resolve("");
1238
+ return new Promise((resolve, reject) => {
1239
+ let data = "";
1240
+ process.stdin.setEncoding("utf8");
1241
+ process.stdin.on("data", (c) => {
1242
+ data += c;
1243
+ });
1244
+ process.stdin.on("end", () => resolve(data));
1245
+ process.stdin.on("error", reject);
1246
+ });
1247
+ }
1248
+ /** `kill(pid, 0)` liveness: EPERM means the process exists but belongs to someone else. */
1249
+ function isProcessAlive(pid) {
1250
+ try {
1251
+ process.kill(pid, 0);
1252
+ return true;
1253
+ } catch (e) {
1254
+ return e.code === "EPERM";
1255
+ }
1256
+ }
1257
+ function createHookCtx() {
1258
+ const launcherPaths = process.argv[1] ? [process.argv[1]] : [];
1259
+ return {
1260
+ dataDir: dataDir(process.platform, process.env, homedir()),
1261
+ adapters: [
1262
+ claudeAdapter,
1263
+ codexAdapter,
1264
+ opencodeAdapter,
1265
+ cursorAdapter,
1266
+ copilotAdapter,
1267
+ antigravityAdapter,
1268
+ grokAdapter
1269
+ ],
1270
+ out: (s) => void process.stdout.write(s),
1271
+ err: (s) => void process.stderr.write(s),
1272
+ readStdin: readAllStdin,
1273
+ connect,
1274
+ ancestry: (timeoutMs) => readAncestry({
1275
+ timeoutMs,
1276
+ launcherPaths
1277
+ }),
1278
+ hostLookup: {
1279
+ ppid: process.ppid,
1280
+ launcherPaths
1281
+ },
1282
+ isAlive: isProcessAlive,
1283
+ hookTimeoutMs: 2e3
1284
+ };
1285
+ }
1286
+ function runHookEntry(argv) {
1287
+ return runHook(createHookCtx(), argv);
1288
+ }
1289
+ export { grokAdapter as a, antigravityAdapter as c, runHookEntry as i, isProcessAlive as n, cursorAdapter as o, readAllStdin as r, copilotAdapter as s, createHookCtx as t };