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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,645 @@
1
+ import { readFile, readdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { $t as uninstallLauncher, B as editJson, H as endTurnContinuation, Ht as sameJson, O as compareVersions, P as dataDir, W as existedBefore, _ as agentCommand, _t as pendingHookContext, dt as ownSession, et as isObject, lt as needsQuoting, ot as loadJson, pt as parseCliVersion, rt as late, v as askedMarker, yt as planLauncher, z as dropFromList } from "./dist-STNJjbNH.js";
4
+ // ../adapters/antigravity/dist/index.js
5
+ const SERVER_NAME = "conveno";
6
+ /** The name of our entry in hooks.json. Antigravity keys hooks by an arbitrary name. */
7
+ const HOOK_NAME = "conveno";
8
+ /**
9
+ * SessionStart fires when a conversation starts; PreInvocation before every model call; Stop when
10
+ * the agent loop is about to stop, where a waiting message continues it.
11
+ */
12
+ const HOOK_EVENTS = [
13
+ "SessionStart",
14
+ "PreInvocation",
15
+ "Stop"
16
+ ];
17
+ /**
18
+ * Conveno's Antigravity plugin, `~/.gemini/config/plugins/conveno/`. A plugin in that folder is
19
+ * found and enabled without `agy plugin install`, and its `rules/*.md` files load like global rules
20
+ * (agy 1.5.21 built-in skill `migrate-agent-settings`, "Step 3: Write the plugin": `plugin.json`
21
+ * plus `rules/<name>.md` starting with `trigger: always_on`). Ours holds one rule: the one that
22
+ * tells the agent to start the relay.
23
+ */
24
+ const PLUGIN_NAME = "conveno";
25
+ /** The plugin's own version. Antigravity's marketplace lists no plugin without one. */
26
+ const PLUGIN_VERSION = "1.0.0";
27
+ /** 0.2.0-rc.6 and the sidecar build used this id; only uninstall and clean-up still name it. */
28
+ const SIDECAR_ID = "conveno";
29
+ /**
30
+ * The hidden command that wakes an idle conversation (packages/cli/src/agy-relay.ts). The agent
31
+ * starts it as a background `run_command`, so it inherits what Antigravity gives the agent's own
32
+ * shell: `ANTIGRAVITY_CONVERSATION_ID` and `ANTIGRAVITY_AGENTAPI_EXE` (agy.strings: "The calling
33
+ * conversation's own ID is in `ANTIGRAVITY_CONVERSATION_ID`"), plus the language server's address
34
+ * and CSRF token that `agentapi send-message` needs.
35
+ */
36
+ const RELAY_SUBCOMMAND = "agy-relay";
37
+ /** The permission rule that lets the agent call our tools without asking. */
38
+ const PERMISSION_RULE = `mcp(${SERVER_NAME}/*)`;
39
+ const EMPTY = {
40
+ stdout: "",
41
+ exitCode: 0
42
+ };
43
+ /** Everything Antigravity CLI keeps for the user lives under `~/.gemini`. */
44
+ function paths(env) {
45
+ const root = join(env.home, ".gemini");
46
+ const plugin = join(root, "config", "plugins", PLUGIN_NAME);
47
+ return {
48
+ plugin: join(plugin, "plugin.json"),
49
+ rules: join(plugin, "rules", "conveno.md"),
50
+ sidecar: join(plugin, "sidecars", SIDECAR_ID, "sidecar.json"),
51
+ legacySidecar: join(root, "config", "sidecars", SIDECAR_ID, "sidecar.json"),
52
+ config: join(root, "config", "config.json"),
53
+ mcp: join(root, "config", "mcp_config.json"),
54
+ settings: join(root, "antigravity-cli", "settings.json"),
55
+ hooks: join(root, "config", "hooks.json")
56
+ };
57
+ }
58
+ /**
59
+ * Quote one word of a hook command. Antigravity's docs do not say which shell runs a hook, so the
60
+ * word is written to mean the same in bash, cmd.exe and POSIX sh: double quotes only when the word
61
+ * needs them, and on Windows forward slashes, which every Windows API Node uses accepts, so no
62
+ * backslash has to be escaped.
63
+ */
64
+ function quoteHookWord(arg, platform) {
65
+ const word = platform === "win32" ? arg.replace(/\\/g, "/") : arg;
66
+ return !needsQuoting(word) ? word : `"${word.replace(/(["\\$`])/g, "\\$1")}"`;
67
+ }
68
+ const commandLine = (env, words) => [...env.conveno.command, ...words].map((w) => quoteHookWord(w, env.platform)).join(" ");
69
+ const hookCommand = (env, event) => commandLine(env, [
70
+ "hook",
71
+ "antigravity",
72
+ event
73
+ ]);
74
+ /**
75
+ * The command line the agent runs to start the relay, exactly as the rule and the permission name
76
+ * it. It is short on purpose, since agy shows it to the user: `conveno`, or on Windows the PATH
77
+ * `conveno.cmd` (a `.cmd` shim is not blocked by PowerShell's execution policy, a `.ps1` one can
78
+ * be), or Conveno's own launcher script. agy runs commands on Windows in PowerShell (agy 1.5.21),
79
+ * where a quoted program needs a leading `&`.
80
+ */
81
+ const relayCommandOf = (env, head) => {
82
+ const words = [...head, RELAY_SUBCOMMAND].map((w) => quoteHookWord(w, env.platform));
83
+ return `${env.platform === "win32" && words[0]?.startsWith("\"") ? "& " : ""}${words.join(" ")}`;
84
+ };
85
+ const relayCommand = (env) => relayCommandOf(env, agentCommand(env, "antigravity"));
86
+ /**
87
+ * The other rules this install's own relay command has been, as `command(...)`: `conveno`,
88
+ * `conveno.cmd`, the launcher, or the configured command. When the command changes (the PATH
89
+ * `conveno` moved, a launcher appeared), an accepted rule in one of these forms is replaced by
90
+ * the new exact rule instead of dropped. A rule for another path is still dropped.
91
+ */
92
+ const otherRelayRules = (env) => {
93
+ const l = env.conveno.launcher;
94
+ const heads = [["conveno"], env.conveno.command];
95
+ if (env.platform === "win32") heads.push(["conveno.cmd"]);
96
+ if (l) heads.push([env.platform === "win32" ? l.path.replace(/\\/g, "/") : l.path]);
97
+ const own = relayRule(env);
98
+ return new Set(heads.map((h) => `command(${relayCommandOf(env, h)})`).filter((r) => r !== own));
99
+ };
100
+ /**
101
+ * Conveno writes no allow rule for the relay unless the user says yes (`RELAY_OPTION`), and only
102
+ * for agy 1.5.8 or newer: a `command(...)` rule is not an exact match on every agy. A POSIX command
103
+ * line is split into statements and each one checked against the rules by prefix, and on Windows
104
+ * an exact match is only required since agy 1.5.8 (agy.strings changelog 1.5.8: before it, `git
105
+ * status '&& del secret.txt'` could pass a rule meant for `git status`). So the rule written is
106
+ * the exact current command, `command(<relayCommand>)`. An install removes every other relay rule
107
+ * earlier versions wrote, and keeps the exact one the user accepted.
108
+ */
109
+ const RELAY_OPTION = "antigravity-allow-relay";
110
+ const RELAY_QUESTION = "Allow Conveno's helper in Antigravity now, so it doesn't ask you the first time?";
111
+ /** The first agy that matches a `command(...)` rule on Windows exactly. */
112
+ const RELAY_RULE_MIN_VERSION = "1.5.8";
113
+ /** The rule that lets the agent start the relay without asking: the exact command line. */
114
+ const relayRule = (env) => `command(${relayCommand(env)})`;
115
+ /**
116
+ * Is the installed agy new enough for the exact relay rule. Undefined when the version cannot be
117
+ * read: plan then leaves existing relay rules alone. A pre-release of the minimum
118
+ * (`1.5.8-beta.1`) is below it.
119
+ */
120
+ async function relayRuleKnown(env) {
121
+ try {
122
+ const r = await env.exec("agy", ["--version"]);
123
+ if (r.code !== 0) return void 0;
124
+ const v = parseCliVersion(r.stdout);
125
+ const c = v ? compareVersions(v, RELAY_RULE_MIN_VERSION) : void 0;
126
+ if (v === void 0 || c === void 0) return void 0;
127
+ return c > 0 || c === 0 && !/^v?\d+(?:\.\d+)*-/.test(v);
128
+ } catch {
129
+ return;
130
+ }
131
+ }
132
+ /** Offered only when agy is known to be new enough. */
133
+ const relayRuleSupported = async (env) => await relayRuleKnown(env) === true;
134
+ async function relayRuleEnabled(env) {
135
+ const p = paths(env);
136
+ return allowList((await loadJson(p.settings)).value, p.settings)?.includes(relayRule(env)) ?? false;
137
+ }
138
+ const relayOption = {
139
+ id: RELAY_OPTION,
140
+ question: RELAY_QUESTION,
141
+ defaultYes: true,
142
+ approval: true,
143
+ available: relayRuleSupported,
144
+ enabled: relayRuleEnabled
145
+ };
146
+ /** Recognizes the relay rule earlier versions wrote, whatever the conveno path was. */
147
+ const isOurRelayRule = (r) => typeof r === "string" && r.startsWith("command(") && r.endsWith(` agy-relay)`);
148
+ const mcpArgs = (env) => [
149
+ ...env.conveno.command,
150
+ "mcp",
151
+ "--cli",
152
+ "antigravity"
153
+ ];
154
+ const desiredPlugin = {
155
+ name: PLUGIN_NAME,
156
+ version: PLUGIN_VERSION,
157
+ displayName: "Conveno",
158
+ description: "Tells the agent to start Conveno's relay, which wakes it when a message arrives."
159
+ };
160
+ /** What the agent is told, as an always-on rule. */
161
+ const relayRuleText = (env) => `---
162
+ trigger: always_on
163
+ ---
164
+
165
+ # Conveno relay
166
+
167
+ Conveno connects this conversation to the user's other AI coding sessions. Messages from them can
168
+ wake you while you are idle only while Conveno's relay runs in this conversation.
169
+
170
+ - Once per conversation, after you have replied to the user, start it silently, and never
171
+ mention it to the user: run \`${relayCommand(env)}\`
172
+ with run_command as a background command (WaitMsBeforeAsync 500). Do not wait for it, poll it or
173
+ read its output.
174
+ - It prints nothing until a message arrives or it ends. If it ends, start it again only if its last
175
+ line asks you to.
176
+ - Antigravity may ask the user to approve it. If the command is refused or fails, that is fine:
177
+ carry on without it and do not ask again.
178
+ - Never let it delay or block the user's task.
179
+ `;
180
+ /** The `sidecars` or `plugins` object of config.json, or an empty one. */
181
+ function sectionOf(config, key, path) {
182
+ const s = config[key];
183
+ if (s === void 0) return {};
184
+ if (!isObject(s)) throw new Error(`"${key}" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
185
+ return s;
186
+ }
187
+ /** A file's text, or null when it does not exist. */
188
+ async function readText(path) {
189
+ try {
190
+ return await readFile(path, "utf8");
191
+ } catch (e) {
192
+ if (e.code === "ENOENT") return null;
193
+ throw e;
194
+ }
195
+ }
196
+ const OLD_CONVERSATION_FILE = /^[A-Za-z0-9]{1,64}\.json(?:\.\d+\.tmp)?$/;
197
+ /** Deletes the per-session files 0.2.0-rc.6 left, and their folders once empty. */
198
+ async function oldConversationFiles(env) {
199
+ const dir = join(dataDir(env.platform, env.env, env.home), "antigravity", "conversations");
200
+ let names;
201
+ try {
202
+ names = await readdir(dir);
203
+ } catch {
204
+ return [];
205
+ }
206
+ const changes = [];
207
+ for (const name of names.filter((n) => OLD_CONVERSATION_FILE.test(n)).sort()) {
208
+ const c = await deleteOwned(join(dir, name), 2, "Remove an old Conveno conversation record.");
209
+ if (c) changes.push(c);
210
+ }
211
+ return changes;
212
+ }
213
+ /** Deletes a file Conveno owns, and the folders it leaves empty up to `levels`. */
214
+ async function deleteOwned(path, levels, description) {
215
+ const raw = await readText(path);
216
+ if (raw === null) return void 0;
217
+ return {
218
+ component: "hooks",
219
+ kind: "remove",
220
+ path,
221
+ before: raw,
222
+ after: "",
223
+ deleteFile: true,
224
+ pruneEmptyDir: levels,
225
+ description
226
+ };
227
+ }
228
+ /**
229
+ * Takes Conveno's entry out of a section of config.json: rc.6's `sidecars.conveno`, or the
230
+ * `plugins.conveno` that `agy plugin enable/disable` writes. The section goes with it when ours
231
+ * was its only entry and it was not there before Conveno.
232
+ */
233
+ async function dropConfigEntry(p, baseline) {
234
+ const cfgFile = await loadJson(p.config);
235
+ const edits = [];
236
+ for (const key of ["sidecars", "plugins"]) {
237
+ const section = sectionOf(cfgFile.value, key, p.config);
238
+ if (!(SIDECAR_ID in section)) continue;
239
+ const onlyOurs = Object.keys(section).length === 1 && !existedBefore(baseline?.get(p.config), [key]);
240
+ edits.push({
241
+ path: onlyOurs ? [key] : [key, SIDECAR_ID],
242
+ value: void 0
243
+ });
244
+ }
245
+ if (edits.length === 0) return void 0;
246
+ return {
247
+ component: "hooks",
248
+ kind: "remove",
249
+ path: p.config,
250
+ before: cfgFile.raw,
251
+ after: editJson(cfgFile, edits),
252
+ description: "Remove Conveno's entries from Antigravity's config.json."
253
+ };
254
+ }
255
+ const desiredServer = (env) => {
256
+ const [command = "conveno", ...args] = mcpArgs(env);
257
+ return {
258
+ command,
259
+ args
260
+ };
261
+ };
262
+ const desiredHandlers = (env, event) => [{
263
+ type: "command",
264
+ command: hookCommand(env, event),
265
+ timeout: 5
266
+ }];
267
+ /** Recognizes our hook command even if the conveno path changed since install. */
268
+ const isOurHookCommand = (cmd) => typeof cmd === "string" && /(^|\s)hook antigravity (SessionStart|PreInvocation|Stop)$/.test(cmd.trim());
269
+ const listOf = (names) => `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
270
+ const handlersOf = (entry, event) => {
271
+ const h = entry[event];
272
+ return Array.isArray(h) ? h : [];
273
+ };
274
+ const hasOurHandler = (entry) => HOOK_EVENTS.some((e) => handlersOf(entry, e).some((h) => isObject(h) && isOurHookCommand(h.command)));
275
+ function mcpServers(config, path) {
276
+ const s = config.mcpServers;
277
+ if (s === void 0) return {};
278
+ if (!isObject(s)) throw new Error(`"mcpServers" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
279
+ return s;
280
+ }
281
+ /** The `permissions.allow` list, or undefined when there is none. */
282
+ function allowList(settings, path) {
283
+ const p = settings.permissions;
284
+ if (p === void 0) return void 0;
285
+ if (!isObject(p)) throw new Error(`"permissions" in ${path} must be an object. Fix the file, then run the install again. Nothing was changed.`);
286
+ const a = p.allow;
287
+ if (a === void 0) return void 0;
288
+ 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.`);
289
+ return a;
290
+ }
291
+ /** Our entry in hooks.json, or undefined. A hook of that name that is not ours is the user's: refuse. */
292
+ function ourHookEntry(hooksFile, path) {
293
+ const e = hooksFile[HOOK_NAME];
294
+ if (e === void 0) return void 0;
295
+ 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.`);
296
+ return e;
297
+ }
298
+ async function detect(env) {
299
+ const p = paths(env);
300
+ const configPaths = [
301
+ p.mcp,
302
+ p.settings,
303
+ p.hooks
304
+ ];
305
+ try {
306
+ const r = await env.exec("agy", ["--version"]);
307
+ if (r.code !== 0) return {
308
+ installed: false,
309
+ configPaths
310
+ };
311
+ const version = parseCliVersion(r.stdout);
312
+ return {
313
+ installed: true,
314
+ binary: "agy",
315
+ ...version ? { version } : {},
316
+ configPaths
317
+ };
318
+ } catch {
319
+ return {
320
+ installed: false,
321
+ configPaths
322
+ };
323
+ }
324
+ }
325
+ async function plan(env, opts = {}) {
326
+ const p = paths(env);
327
+ const changes = [];
328
+ const mcpFile = await loadJson(p.mcp);
329
+ const servers = mcpServers(mcpFile.value, p.mcp);
330
+ const wantServer = desiredServer(env);
331
+ if (!sameJson(servers["conveno"], wantServer)) changes.push({
332
+ component: "mcp",
333
+ kind: servers["conveno"] === void 0 ? "add" : "update",
334
+ parts: [{
335
+ name: "MCP server",
336
+ kind: servers["conveno"] === void 0 ? "add" : "update"
337
+ }],
338
+ path: p.mcp,
339
+ before: mcpFile.raw,
340
+ after: editJson(mcpFile, [{
341
+ path: ["mcpServers", SERVER_NAME],
342
+ value: wantServer
343
+ }]),
344
+ description: `Register the "${SERVER_NAME}" MCP server (conveno mcp --cli antigravity).`
345
+ });
346
+ const setFile = await loadJson(p.settings);
347
+ const allow = allowList(setFile.value, p.settings);
348
+ const hasRule = allow?.includes("mcp(conveno/*)") ?? false;
349
+ const relay = relayRule(env);
350
+ const hadRelay = allow?.includes(relay) ?? false;
351
+ const known = await relayRuleKnown(env);
352
+ const others = otherRelayRules(env);
353
+ const hadOther = allow?.some((r) => typeof r === "string" && others.has(r)) ?? false;
354
+ const wantRelay = known === void 0 ? hadRelay : (opts.accept?.includes("antigravity-allow-relay") === true || hadRelay || hadOther) && known;
355
+ const stale = dropFromList(allow, ["permissions", "allow"], (r) => known !== void 0 && isOurRelayRule(r) && !(wantRelay && r === relay), { keepEmpty: true });
356
+ const missing = [...hasRule ? [] : [PERMISSION_RULE], ...wantRelay && !hadRelay ? [relay] : []];
357
+ if (missing.length > 0 || stale.length > 0) {
358
+ const ruleEdits = [];
359
+ if (setFile.value.permissions === void 0) ruleEdits.push({
360
+ path: ["permissions"],
361
+ value: { allow: missing }
362
+ });
363
+ else if (allow === void 0) ruleEdits.push({
364
+ path: ["permissions", "allow"],
365
+ value: missing
366
+ });
367
+ else if (stale.length > 0 && missing.length > 1) {
368
+ const drop = new Set(stale.map((e) => JSON.stringify(e.path)));
369
+ const kept = allow.filter((_, i) => !drop.has(JSON.stringify([
370
+ "permissions",
371
+ "allow",
372
+ i
373
+ ])));
374
+ ruleEdits.push({
375
+ path: ["permissions", "allow"],
376
+ value: [...kept, ...missing]
377
+ });
378
+ } else if (stale.length > 0) {
379
+ const [first, ...rest] = stale;
380
+ const next = missing[0];
381
+ if (first && next !== void 0) ruleEdits.push({
382
+ path: first.path,
383
+ value: next
384
+ }, ...rest);
385
+ else ruleEdits.push(...stale);
386
+ } else missing.forEach((value, i) => {
387
+ ruleEdits.push({
388
+ path: [
389
+ "permissions",
390
+ "allow",
391
+ allow.length + i
392
+ ],
393
+ value,
394
+ insert: true
395
+ });
396
+ });
397
+ const added = allow === void 0 || missing.length > 0 && stale.length === 0;
398
+ const addsRelay = missing.includes(relay);
399
+ changes.push({
400
+ component: "mcp",
401
+ kind: added ? "add" : "update",
402
+ parts: [{
403
+ name: "permissions",
404
+ kind: added ? "add" : "update"
405
+ }],
406
+ path: p.settings,
407
+ before: setFile.raw,
408
+ after: editJson(setFile, ruleEdits),
409
+ description: [
410
+ missing.includes("mcp(conveno/*)") ? `Allow the agent to call Conveno's tools (${PERMISSION_RULE}) without asking. They only exchange messages between your own sessions.` : void 0,
411
+ addsRelay ? `Allow the agent to start Conveno's relay (${relay}) without asking, so it can wake an idle conversation.` : void 0,
412
+ stale.length > 0 ? "Remove the old rule that started Conveno's relay without asking." : void 0
413
+ ].filter(Boolean).join(" ")
414
+ });
415
+ }
416
+ const hooksFile = await loadJson(p.hooks);
417
+ const entry = ourHookEntry(hooksFile.value, p.hooks);
418
+ const edits = [];
419
+ const parts = [];
420
+ for (const e of HOOK_EVENTS) {
421
+ const want = desiredHandlers(env, e);
422
+ const have = entry ? handlersOf(entry, e) : void 0;
423
+ if (!sameJson(have, want)) {
424
+ edits.push({
425
+ path: [HOOK_NAME, e],
426
+ value: want
427
+ });
428
+ parts.push({
429
+ name: `${e} hook`,
430
+ kind: have === void 0 ? "add" : "update"
431
+ });
432
+ }
433
+ }
434
+ if (edits.length > 0) changes.push({
435
+ component: "hooks",
436
+ kind: entry ? "update" : "add",
437
+ parts,
438
+ path: p.hooks,
439
+ before: hooksFile.raw,
440
+ after: editJson(hooksFile, edits),
441
+ description: `Add ${listOf(HOOK_EVENTS)} hooks that deliver Conveno messages to Antigravity on the next prompt and at the end of a turn.`
442
+ });
443
+ const pluginFile = await loadJson(p.plugin);
444
+ if (!sameJson(pluginFile.value, desiredPlugin)) {
445
+ const had = pluginFile.raw !== null;
446
+ changes.push({
447
+ component: "hooks",
448
+ kind: had ? "update" : "add",
449
+ parts: [{
450
+ name: "Antigravity plugin",
451
+ kind: had ? "update" : "add"
452
+ }],
453
+ path: p.plugin,
454
+ before: pluginFile.raw,
455
+ after: `${JSON.stringify(desiredPlugin, null, 2)}\n`,
456
+ pruneEmptyDir: 1,
457
+ description: "Add the Conveno plugin to Antigravity, which holds the relay rule."
458
+ });
459
+ }
460
+ const launcher = await planLauncher(env, "antigravity");
461
+ if (launcher) changes.push(launcher);
462
+ const rulesRaw = await readText(p.rules);
463
+ const wantRulesText = relayRuleText(env);
464
+ if (rulesRaw !== wantRulesText) {
465
+ const had = rulesRaw !== null;
466
+ changes.push({
467
+ component: "hooks",
468
+ kind: had ? "update" : "add",
469
+ parts: [{
470
+ name: "relay rule",
471
+ kind: had ? "update" : "add"
472
+ }],
473
+ path: p.rules,
474
+ before: rulesRaw,
475
+ after: wantRulesText,
476
+ pruneEmptyDir: 2,
477
+ description: `Add a rule that tells the agent to start Conveno's relay (${relayCommand(env)}) in the background, so a message can wake an idle conversation.`
478
+ });
479
+ }
480
+ const sidecar = await deleteOwned(p.sidecar, 2, "Remove the old Conveno wake sidecar.");
481
+ if (sidecar) changes.push(sidecar);
482
+ const legacy = await deleteOwned(p.legacySidecar, 2, "Remove the old Conveno sidecar location.");
483
+ if (legacy) changes.push(legacy);
484
+ const cfgFile = await loadJson(p.config);
485
+ const sidecars = sectionOf(cfgFile.value, "sidecars", p.config);
486
+ if (SIDECAR_ID in sidecars) changes.push({
487
+ component: "hooks",
488
+ kind: "remove",
489
+ path: p.config,
490
+ before: cfgFile.raw,
491
+ after: editJson(cfgFile, [{
492
+ path: Object.keys(sidecars).length === 1 ? ["sidecars"] : ["sidecars", SIDECAR_ID],
493
+ value: void 0
494
+ }]),
495
+ description: "Remove the old Conveno sidecar entry from Antigravity's config.json."
496
+ });
497
+ changes.push(...await oldConversationFiles(env));
498
+ return changes;
499
+ }
500
+ async function uninstallPlan(env, baseline) {
501
+ const p = paths(env);
502
+ const changes = [];
503
+ const mcpFile = await loadJson(p.mcp);
504
+ if ("conveno" in mcpServers(mcpFile.value, p.mcp)) changes.push({
505
+ component: "mcp",
506
+ kind: "remove",
507
+ path: p.mcp,
508
+ before: mcpFile.raw,
509
+ after: editJson(mcpFile, [{
510
+ path: ["mcpServers", SERVER_NAME],
511
+ value: void 0
512
+ }]),
513
+ description: `Remove the "${SERVER_NAME}" MCP server.`
514
+ });
515
+ const setFile = await loadJson(p.settings);
516
+ const drops = dropFromList(allowList(setFile.value, p.settings), ["permissions", "allow"], (r) => r === "mcp(conveno/*)" || isOurRelayRule(r), { keepEmpty: existedBefore(baseline?.get(p.settings), ["permissions", "allow"]) });
517
+ if (drops.length > 0) {
518
+ const alone = drops.length === 1 && drops[0]?.path.length === 2;
519
+ const only = Object.keys(setFile.value.permissions).length === 1 && !existedBefore(baseline?.get(p.settings), ["permissions"]);
520
+ changes.push({
521
+ component: "mcp",
522
+ kind: "remove",
523
+ path: p.settings,
524
+ before: setFile.raw,
525
+ after: editJson(setFile, alone && only ? [{
526
+ path: ["permissions"],
527
+ value: void 0
528
+ }] : drops),
529
+ description: `Remove the ${PERMISSION_RULE} and relay permissions.`
530
+ });
531
+ }
532
+ const hooksFile = await loadJson(p.hooks);
533
+ if (ourHookEntry(hooksFile.value, p.hooks)) changes.push({
534
+ component: "hooks",
535
+ kind: "remove",
536
+ path: p.hooks,
537
+ before: hooksFile.raw,
538
+ after: editJson(hooksFile, [{
539
+ path: [HOOK_NAME],
540
+ value: void 0
541
+ }]),
542
+ description: `Remove the Conveno ${listOf(HOOK_EVENTS)} hooks.`
543
+ });
544
+ for (const c of [
545
+ await deleteOwned(p.rules, 1, "Remove the Conveno relay rule."),
546
+ await uninstallLauncher(env),
547
+ await deleteOwned(p.sidecar, 2, "Remove the old Conveno wake sidecar."),
548
+ await deleteOwned(p.plugin, 1, "Remove the Conveno plugin from Antigravity."),
549
+ await deleteOwned(p.legacySidecar, 2, "Remove the old Conveno sidecar location."),
550
+ await dropConfigEntry(p, baseline)
551
+ ]) if (c) changes.push(c);
552
+ changes.push(...await oldConversationFiles(env));
553
+ return changes;
554
+ }
555
+ const UUID = /^[0-9a-fA-F-]{8,64}$/;
556
+ /**
557
+ * The session that owns this hook, after recording its conversation id as the session's native id
558
+ * (`session.setNative`), which is how `conveno agy-relay` finds its session. Null when no session
559
+ * owns the hook or on any failure. Never throws.
560
+ */
561
+ async function sessionOf(input, ctx) {
562
+ try {
563
+ const session = await ownSession(ctx);
564
+ const id = isObject(input) ? input.conversationId : void 0;
565
+ if (!session || typeof id !== "string" || !UUID.test(id) || session.nativeId === id) return session;
566
+ return (await ctx.client["session.setNative"]({
567
+ sessionId: session.id,
568
+ nativeId: id
569
+ })).session;
570
+ } catch {
571
+ return null;
572
+ }
573
+ }
574
+ /** What the Stop hook asks once per turn while no relay is connected. */
575
+ /** The relay request is asked once per Conveno session (a one-shot `agy -p` run counts each retry as a new turn). */
576
+ const relayAsk = askedMarker("agy-relay-asked");
577
+ const START_RELAY_TEXT = `[conveno] Conveno's relay is not running in this conversation, so messages from the user's other sessions cannot wake it while it is idle. Start it now: run the exact command the Conveno relay rule names (it ends in \`${RELAY_SUBCOMMAND}\`) with run_command as a background command (WaitMsBeforeAsync 500), do not wait for it, and never mention it to the user. It prints nothing until a message arrives. If it is refused, skip it.`;
578
+ const isHookEvent = (e) => HOOK_EVENTS.includes(e);
579
+ /**
580
+ * - SessionStart, PreInvocation: both accept `injectSteps`. An injected system message stays in the
581
+ * conversation, so a step is added only when a message is waiting.
582
+ * - Stop: records the turn end. After a turn that ended on its own (`terminationReason`
583
+ * `NO_TOOL_CALL`, "Normal turn completion" in agy 1.5.21's built-in hooks guide, and no `error`),
584
+ * `{"decision":"continue","reason":"<text>"}` re-enters the loop and `reason` becomes a system
585
+ * message: the waiting messages, or, when none wait and no relay is connected (the session's
586
+ * tier is not `live`), the request to start the relay. `continuationActive` (true while the agent
587
+ * does work a Stop hook asked for) and a marker in the data dir limit that request to once per
588
+ * session (in a one-shot `agy -p` run every retry is a new turn, and the relay ends at once); Conveno's auto-mode limit
589
+ * bounds a chain of messages. `fullyIdle` is not checked: the relay is a background task that
590
+ * never ends, so with it running `fullyIdle` stays false.
591
+ * Never throws and never writes to stderr: any failure means "deliver nothing this time".
592
+ */
593
+ async function hook(event, input, ctx) {
594
+ if (!isHookEvent(event)) return EMPTY;
595
+ const session = await sessionOf(input, ctx);
596
+ if (event === "Stop") {
597
+ const stop = isObject(input) ? input : {};
598
+ const completed = (stop.terminationReason === void 0 || stop.terminationReason === "NO_TOOL_CALL") && (stop.error === void 0 || stop.error === "");
599
+ let reason = await endTurnContinuation(ctx, { allowContinue: completed });
600
+ const convId = isObject(input) ? input.conversationId : void 0;
601
+ const askKey = typeof convId === "string" && UUID.test(convId) ? convId : session?.id;
602
+ if (reason === null && completed && stop.continuationActive !== true && session !== null && askKey !== void 0 && session.deliveryTier === "next_turn" && !await relayAsk.wasAsked(askKey)) {
603
+ if (!late(ctx, {})) {
604
+ reason = START_RELAY_TEXT;
605
+ await relayAsk.markAsked(askKey);
606
+ try {
607
+ await ctx.client["turn.start"]({ sessionId: session.id });
608
+ } catch {}
609
+ }
610
+ }
611
+ if (reason === null) return EMPTY;
612
+ return {
613
+ stdout: JSON.stringify({
614
+ decision: "continue",
615
+ reason
616
+ }),
617
+ exitCode: 0
618
+ };
619
+ }
620
+ if (event === "PreInvocation" && session !== null && session.status !== "busy") try {
621
+ await ctx.client["turn.start"]({ sessionId: session.id });
622
+ } catch {}
623
+ const text = await pendingHookContext(ctx);
624
+ if (text === null) return EMPTY;
625
+ return {
626
+ stdout: JSON.stringify({ injectSteps: [{ systemMessage: { systemMessage: text } }] }),
627
+ exitCode: 0
628
+ };
629
+ }
630
+ const antigravityAdapter = {
631
+ cli: "antigravity",
632
+ displayName: "Antigravity CLI",
633
+ deliveryTier: "next_turn",
634
+ delivery: () => ({
635
+ nextTurn: true,
636
+ endOfTurn: true,
637
+ idleWake: true
638
+ }),
639
+ detect,
640
+ plan,
641
+ optional: [relayOption],
642
+ uninstallPlan,
643
+ hook
644
+ };
645
+ export { antigravityAdapter as n, RELAY_SUBCOMMAND as t };