@conveno/cli 0.1.1 → 0.2.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2034 @@
1
+ import { A as completeLogin, F as dataPaths, G as fetchAccountStatus, K as findOnPath, Lt as resolveAcpProgram, Nt as requestDeviceCode, St as pollDeviceCode, Tt as readAccountTokens, an as CLI_KINDS, d as SPAWN_TABLE, g as adapterNpxCommand, h as adapterInstallCommand, in as writeSettings, k as compatStatus, kt as readSettings, m as acpOverrideVar, n as AccountError, st as logoutAccount, vt as pinnedAdapter } from "./dist-STNJjbNH.js";
2
+ import { a as fail, c as plural, d as warnBlock, i as errorBlock, l as seconds, n as cmd, o as localStamp, r as columns, s as plainError, t as closest, u as tilde } from "./fmt-C2SsP5Y0.js";
3
+ import { a as parseFlags, n as COMMANDS } from "./args-B3Cj2Ie4.js";
4
+ import { n as connectOpts, t as adapterEnv } from "./ctx-tYftvhz_.js";
5
+ import { t as daemonProblem } from "./daemonError-C05GqdhQ.js";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { spawn } from "node:child_process";
8
+ import { access, chmod, mkdir, open, readFile, readdir, realpath, rename as rename$1, rm, rmdir, stat, writeFile } from "node:fs/promises";
9
+ import { createHash, randomBytes } from "node:crypto";
10
+ // src/account.ts
11
+ const accountIo = (ctx, io) => ({
12
+ apiBase: ctx.env.CONVENO_API_URL || "https://api.conveno.dev",
13
+ now: () => ctx.now().getTime(),
14
+ ...io.fetch ? { fetch: io.fetch } : {}
15
+ });
16
+ const tokenFile = (ctx) => dataPaths(ctx.platform, ctx.dataDir).account;
17
+ /** Show the code as ABCD-1234, the way the page asks for it. */
18
+ const showCode = (code) => /^[A-Za-z0-9]{8}$/.test(code) ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
19
+ /** Open a page with the system's own opener. No shell is involved, so the URL is one argument. */
20
+ function openInBrowser(platform, url) {
21
+ if (!/^https?:\/\//.test(url)) return;
22
+ const [file, args] = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
23
+ try {
24
+ const child = spawn(file, args, {
25
+ stdio: "ignore",
26
+ detached: true,
27
+ windowsHide: true
28
+ });
29
+ child.on("error", () => {});
30
+ child.unref();
31
+ } catch {}
32
+ }
33
+ function accountFailure(ctx, e, what) {
34
+ const t = ctx.theme;
35
+ if (e instanceof AccountError) {
36
+ const fixes = {
37
+ session_expired: `Run ${cmd(t, "conveno login")} to sign in again.`,
38
+ not_logged_in: `Run ${cmd(t, "conveno login")}.`,
39
+ denied: `Run ${cmd(t, "conveno login")} again and approve the code in the browser.`,
40
+ expired: `Run ${cmd(t, "conveno login")} again. The code lasts 15 minutes.`,
41
+ network: "Check your connection and try again.",
42
+ server: "Try again in a few minutes."
43
+ };
44
+ return fail(ctx, {
45
+ what,
46
+ detail: [e.message],
47
+ ...fixes[e.code] ? { fix: fixes[e.code] } : {},
48
+ exit: 1,
49
+ ref: `e_account_${e.code}`
50
+ });
51
+ }
52
+ throw e;
53
+ }
54
+ function planLine(ctx, s) {
55
+ const t = ctx.theme;
56
+ if (s.plan !== "pro") return "Free";
57
+ if (s.status === "trialing") return `${t.paint("ok", "Pro")} (trial)`;
58
+ return t.paint("ok", "Pro");
59
+ }
60
+ const day = (seconds) => (/* @__PURE__ */ new Date(seconds * 1e3)).toISOString().slice(0, 10);
61
+ /** `conveno login`: the device authorization grant, RFC 8628. */
62
+ async function runLogin(ctx, argv, io = {}) {
63
+ const spec = COMMANDS.find((c) => c.name === "login");
64
+ if (!spec) return 2;
65
+ const parsed = parseFlags(ctx, spec, argv);
66
+ if (typeof parsed === "number") return parsed;
67
+ const t = ctx.theme;
68
+ const aio = accountIo(ctx, io);
69
+ try {
70
+ const code = await requestDeviceCode(aio);
71
+ ctx.err([
72
+ "Sign in to Conveno in your browser:",
73
+ ` ${code.verificationUriComplete}`,
74
+ "",
75
+ `It should show the code ${t.bold(showCode(code.userCode))}. Approve only if it matches.`,
76
+ t.paint("quiet", "Waiting for approval. Press Ctrl+C to cancel."),
77
+ ""
78
+ ].join("\n"));
79
+ if (ctx.interactive && parsed.values["no-browser"] !== true) (io.open ?? ((u) => openInBrowser(ctx.platform, u)))(code.verificationUriComplete);
80
+ const session = await pollDeviceCode(code, {
81
+ ...aio,
82
+ ...io.sleep ? { sleep: io.sleep } : {}
83
+ });
84
+ await completeLogin(tokenFile(ctx), session, aio);
85
+ let plan = "";
86
+ try {
87
+ plan = ` Plan: ${planLine(ctx, await fetchAccountStatus(session, aio))}.`;
88
+ } catch {}
89
+ ctx.out(`${t.status("ok")} Signed in.${plan}\n`);
90
+ return 0;
91
+ } catch (e) {
92
+ return accountFailure(ctx, e, "Could not sign in");
93
+ }
94
+ }
95
+ /** `conveno logout`: end the login on the server and delete the local tokens. */
96
+ async function runLogout(ctx, argv, io = {}) {
97
+ const spec = COMMANDS.find((c) => c.name === "logout");
98
+ if (!spec) return 2;
99
+ const parsed = parseFlags(ctx, spec, argv);
100
+ if (typeof parsed === "number") return parsed;
101
+ const r = await logoutAccount(tokenFile(ctx), accountIo(ctx, io));
102
+ if (!r.hadLogin) {
103
+ ctx.out("You were not signed in.\n");
104
+ return 0;
105
+ }
106
+ ctx.out(`${ctx.theme.status("ok")} Signed out.\n`);
107
+ if (!r.revoked) ctx.err(`${ctx.theme.status("warn")} The account server could not be reached, so the login was only removed from this machine. Sign out everywhere at https://api.conveno.dev/account.\n`);
108
+ return 0;
109
+ }
110
+ /** `conveno account`: plan and trial. */
111
+ async function runAccount(ctx, argv, io = {}) {
112
+ const spec = COMMANDS.find((c) => c.name === "account");
113
+ if (!spec) return 2;
114
+ const parsed = parseFlags(ctx, spec, argv);
115
+ if (typeof parsed === "number") return parsed;
116
+ const t = ctx.theme;
117
+ const tokens = await readAccountTokens(tokenFile(ctx));
118
+ if (!tokens) return fail(ctx, {
119
+ what: "You are not signed in",
120
+ detail: ["Conveno works without an account. Pro adds the encrypted relay."],
121
+ fix: `Run ${cmd(t, "conveno login")}.`,
122
+ exit: 1,
123
+ ref: "e_account_not_logged_in"
124
+ });
125
+ try {
126
+ const s = await fetchAccountStatus(tokens.refreshToken, accountIo(ctx, io));
127
+ const rows = [["Account", s.user.name], ["Plan", planLine(ctx, s)]];
128
+ if (s.status === "trialing" && s.trialEnd !== null) {
129
+ const left = s.trialDaysLeft ?? 0;
130
+ rows.push(["Trial", `${left} ${left === 1 ? "day" : "days"} left, until ${day(s.trialEnd)}`]);
131
+ } else if (s.plan === "pro" && s.currentPeriodEnd !== null) rows.push([s.cancelAtPeriodEnd ? "Ends" : "Renews", day(s.currentPeriodEnd)]);
132
+ if (s.paymentFailed) rows.push(["Billing", t.paint("warn", "last payment failed")]);
133
+ const width = Math.max(...rows.map(([k]) => k.length)) + 2;
134
+ const lines = rows.map(([k, v]) => `${t.paint("quiet", k.padEnd(width))}${v}`);
135
+ if (s.plan === "free") lines.push("", `Upgrade or start the 14-day trial at ${t.bold("https://api.conveno.dev/account")}.`);
136
+ else if (s.status === "trialing") lines.push("", "No card is on file. Add one at https://api.conveno.dev/account to keep Pro.");
137
+ ctx.out(`${lines.join("\n")}\n`);
138
+ return 0;
139
+ } catch (e) {
140
+ return accountFailure(ctx, e, "Could not read your account");
141
+ }
142
+ }
143
+ // src/daemon.ts
144
+ async function lockPid(ctx) {
145
+ try {
146
+ const raw = await readFile(dataPaths(ctx.platform, ctx.dataDir).lock, "utf8");
147
+ const pid = JSON.parse(raw).pid;
148
+ return typeof pid === "number" && Number.isInteger(pid) && pid > 0 ? pid : null;
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+ const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
154
+ /** Does something on the socket answer the Conveno handshake? */
155
+ async function reachable(ctx) {
156
+ try {
157
+ await (await ctx.connect(connectOpts(ctx, false))).close().catch(() => void 0);
158
+ return true;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+ const lockExists = (ctx) => access(dataPaths(ctx.platform, ctx.dataDir).lock).then(() => true, () => false);
164
+ /** Poll until `done()` holds or `ms` pass. Returns whether it held. */
165
+ async function waitFor(done, ms) {
166
+ const deadline = Date.now() + ms;
167
+ for (;;) {
168
+ if (await done()) return true;
169
+ if (Date.now() >= deadline) return false;
170
+ await sleep$1(50);
171
+ }
172
+ }
173
+ const norm = (text) => text.replaceAll("\\", "/").toLowerCase();
174
+ /**
175
+ * Does this command line belong to the Conveno daemon? It must run the daemon's entry script: the
176
+ * one this install resolved, any installed `@conveno/cli`'s `daemon.js`, or the `bin.js` of the
177
+ * `@conveno/daemon` package that releases before 0.1.1 started.
178
+ */
179
+ function isConvenoDaemonCommand(commandLine, daemonEntry) {
180
+ const line = norm(commandLine);
181
+ if (daemonEntry !== void 0 && line.includes(norm(daemonEntry))) return true;
182
+ return /@conveno\/cli\/(?:[^ ]+\/)?daemon\.js|@conveno\/daemon\/(?:[^ ]+\/)?bin\.js/.test(line);
183
+ }
184
+ const STOP_FIX = (t) => `then run ${cmd(t, "conveno daemon status")}`;
185
+ /**
186
+ * `conveno daemon stop`. The normal path asks the daemon to shut itself down over the control
187
+ * channel (`daemon.shutdown`), the way Docker and pm2 do. That needs no signal and no external
188
+ * tool, so it works for a normal user in a Windows SSH session. Only when the daemon does not answer,
189
+ * and its lock pid is verified to be the daemon, is the process ended directly.
190
+ */
191
+ async function stopDaemon(ctx, plain = false) {
192
+ const t = ctx.theme;
193
+ const lock = dataPaths(ctx.platform, ctx.dataDir).lock;
194
+ const pid = await lockPid(ctx);
195
+ const named = pid === null ? "" : ` (pid ${pid})`;
196
+ let client;
197
+ try {
198
+ client = await ctx.connect(connectOpts(ctx, false));
199
+ } catch {
200
+ client = void 0;
201
+ }
202
+ if (client) {
203
+ try {
204
+ await client["daemon.shutdown"]({});
205
+ } catch (e) {
206
+ await client.close().catch(() => void 0);
207
+ return fail(ctx, {
208
+ what: `The background service${named} did not accept the stop request`,
209
+ detail: [plainError(e)],
210
+ fix: `${pid === null ? "Stop the process that owns the daemon socket yourself" : `Stop pid ${pid} yourself`}, ${STOP_FIX(t)}.`,
211
+ exit: 1,
212
+ ref: "e_daemon_stop"
213
+ });
214
+ }
215
+ await client.close().catch(() => void 0);
216
+ if (!await waitFor(async () => !await reachable(ctx) && !await lockExists(ctx) && (pid === null || !ctx.isAlive(pid)), ctx.stopTimeoutMs)) return fail(ctx, {
217
+ what: `The background service${named} is still running after ${Math.round(ctx.stopTimeoutMs / 1e3)}s`,
218
+ detail: ["It accepted the stop request, but its process, socket or lock file is still there."],
219
+ fix: `${pid === null ? "Stop the process that owns the daemon socket yourself" : `Stop pid ${pid} yourself`}, ${STOP_FIX(t)}.`,
220
+ exit: 1,
221
+ ref: "e_daemon_stop"
222
+ });
223
+ ctx.out(`${t.status("ok")} Stopped ${plain ? "Conveno's background service" : "the daemon"}${named}.\n`);
224
+ return 0;
225
+ }
226
+ if (pid === null) {
227
+ ctx.out(`${t.status("info")} Conveno's background service is not running. Nothing to stop.\n`);
228
+ return 0;
229
+ }
230
+ const stale = async () => {
231
+ await rm(lock, { force: true }).catch(() => void 0);
232
+ ctx.out(`${t.status("info")} Nothing answered as the Conveno daemon, so no process was stopped. Removed the stale lock file (it named pid ${pid}).\n`);
233
+ return 0;
234
+ };
235
+ if (!ctx.isAlive(pid)) return stale();
236
+ const commandLine = await ctx.commandLineOf(pid);
237
+ if (commandLine === null) return fail(ctx, {
238
+ what: `The background service did not answer, and pid ${pid} could not be checked`,
239
+ detail: ["Conveno could not read that process's command line, so it cannot tell whether it is the daemon. It stopped nothing."],
240
+ fix: `If pid ${pid} is the Conveno daemon, end it yourself (Task Manager on Windows, \`kill ${pid}\` elsewhere), ${STOP_FIX(t)}.`,
241
+ exit: 1,
242
+ ref: "e_daemon_lock"
243
+ });
244
+ if (!isConvenoDaemonCommand(commandLine, ctx.daemonEntry)) return stale();
245
+ try {
246
+ ctx.kill(pid);
247
+ } catch (e) {
248
+ return fail(ctx, {
249
+ what: `Could not stop the daemon (pid ${pid})`,
250
+ detail: [plainError(e)],
251
+ fix: `Stop that process yourself, ${STOP_FIX(t)}.`,
252
+ exit: 1,
253
+ ref: "e_daemon_stop"
254
+ });
255
+ }
256
+ if (!await waitFor(() => !ctx.isAlive(pid), ctx.stopTimeoutMs)) return fail(ctx, {
257
+ what: `The background service (pid ${pid}) is still running after ${Math.round(ctx.stopTimeoutMs / 1e3)}s`,
258
+ detail: ["It did not answer, was ended, and has not exited."],
259
+ fix: `Stop that process yourself, ${STOP_FIX(t)}.`,
260
+ exit: 1,
261
+ ref: "e_daemon_stop"
262
+ });
263
+ await rm(lock, { force: true }).catch(() => void 0);
264
+ ctx.out(`${t.status("ok")} Stopped ${plain ? "Conveno's background service" : "the daemon"} (pid ${pid}). It was not answering, so it was ended directly.\n`);
265
+ return 0;
266
+ }
267
+ /**
268
+ * Stop the daemon if one is running, and say nothing when none is. Used before `conveno uninstall`
269
+ * changes any file, because a running daemon keeps files open (on Windows that blocks removing them).
270
+ * Returns 0 when nothing is left running, else the exit code of the failed stop.
271
+ */
272
+ async function stopDaemonIfRunning(ctx) {
273
+ if (!await reachable(ctx)) {
274
+ const pid = await lockPid(ctx);
275
+ if (pid === null || !ctx.isAlive(pid)) return 0;
276
+ }
277
+ return stopDaemon(ctx, true);
278
+ }
279
+ const SUBCOMMANDS = [
280
+ "start",
281
+ "stop",
282
+ "status"
283
+ ];
284
+ async function runDaemon(ctx, argv) {
285
+ const t = ctx.theme;
286
+ const sub = argv[0];
287
+ if (sub === "start") {
288
+ try {
289
+ await (await ctx.connect(connectOpts(ctx, true))).close().catch(() => void 0);
290
+ } catch (e) {
291
+ const problem = daemonProblem(t, e);
292
+ return fail(ctx, {
293
+ what: "The Conveno daemon did not start",
294
+ detail: [problem.why],
295
+ fix: problem.notRunning ? `Run ${cmd(t, "conveno doctor")} to check the install, then try again.` : problem.fix,
296
+ exit: 1,
297
+ ref: "e_daemon_start"
298
+ });
299
+ }
300
+ const pid = await lockPid(ctx);
301
+ ctx.out(`${t.status("ok")} Daemon running${pid ? `, pid ${pid}` : ""}.\n`);
302
+ return 0;
303
+ }
304
+ if (sub === "status") {
305
+ const pid = await lockPid(ctx);
306
+ try {
307
+ await (await ctx.connect(connectOpts(ctx, false))).close().catch(() => void 0);
308
+ ctx.out(`${t.status("ok")} daemon running${pid ? `, pid ${pid}` : ""}\n`);
309
+ return 0;
310
+ } catch (e) {
311
+ const problem = daemonProblem(t, e);
312
+ if (problem.notRunning) ctx.out(`${t.glyph("offline")} daemon not running\n`);
313
+ else {
314
+ ctx.out(`${t.status("error")} daemon cannot be reached\n`);
315
+ ctx.err(warnBlock(t, "Conveno's background service cannot be reached.", problem.fix, problem.why));
316
+ }
317
+ return 1;
318
+ }
319
+ }
320
+ if (sub === "stop") return stopDaemon(ctx);
321
+ const suggestion = sub ? closest(sub, SUBCOMMANDS) : void 0;
322
+ return fail(ctx, {
323
+ what: sub ? `Unknown daemon command "${sub}"` : "conveno daemon needs a command",
324
+ fix: `Run ${cmd(t, "conveno daemon start")}, ${cmd(t, "conveno daemon stop")} or ${cmd(t, "conveno daemon status")}.`,
325
+ ...suggestion ? { didYouMean: `Did you mean ${suggestion}?` } : {},
326
+ exit: 2,
327
+ ref: "e_usage"
328
+ });
329
+ }
330
+ const PAIR_TIMEOUT_MS = 3e5;
331
+ /**
332
+ * Run `run` with a daemon client. Commands that change something start the daemon when needed;
333
+ * the read-only ones (`devices`, `relay status`) do not, like `conveno status`.
334
+ */
335
+ async function withClient(ctx, autoStart, run) {
336
+ const t = ctx.theme;
337
+ let client;
338
+ try {
339
+ client = await ctx.connect(connectOpts(ctx, autoStart));
340
+ } catch (e) {
341
+ const problem = daemonProblem(t, e);
342
+ return fail(ctx, {
343
+ what: "Conveno's background service cannot be reached",
344
+ detail: [problem.why],
345
+ fix: problem.fix,
346
+ exit: 1,
347
+ ref: "e_daemon"
348
+ });
349
+ }
350
+ try {
351
+ return await run(client);
352
+ } catch (e) {
353
+ return fail(ctx, {
354
+ what: "The background service refused the request",
355
+ detail: [plainError(e)],
356
+ fix: `Run ${cmd(t, "conveno relay status")} to see the relay and login state.`,
357
+ exit: 1,
358
+ ref: "e_relay"
359
+ });
360
+ } finally {
361
+ await client.close().catch(() => void 0);
362
+ }
363
+ }
364
+ /** The device list's head and length. The full head is what `devices accept` takes. */
365
+ function listLine(ctx, list) {
366
+ if (!list) return "";
367
+ return ` ${ctx.theme.paint("quiet", "device list:")} ${list.head} ${ctx.theme.paint("quiet", `(${plural(list.length, "entry", "entries")})`)}\n`;
368
+ }
369
+ /** A loud warning while the device list has an unresolved conflict. */
370
+ function conflictBlock(ctx, c) {
371
+ if (!c) return "";
372
+ const t = ctx.theme;
373
+ const head = (l) => l ? `${l.head.slice(0, 16)} ${t.paint("quiet", `(${plural(l.length, "entry", "entries")})`)}` : "none";
374
+ const why = c.kind === "split_view" ? [` ${c.peer?.name ?? "Another device"} signed a message with a device list this device does not hold.`, " The relay may be showing your devices different lists, for example to hide a revocation."] : [" The relay holds a device list that this device's list is not part of.", " Someone changed the list in a way this device cannot follow, or the relay is lying."];
375
+ return `${[
376
+ "",
377
+ `${t.status("error")} ${t.bold("Your device list has a conflict.")} Nothing is sent to or accepted from other devices.`,
378
+ ...why,
379
+ ` ${c.detail}`,
380
+ "",
381
+ ` This device: ${head(c.local)}`,
382
+ ` The relay: ${head(c.relay)}`,
383
+ ...c.peer ? [` ${c.peer.name}: ${head(c.peer)}`] : [],
384
+ "",
385
+ ` To recover, run ${cmd(t, "conveno devices")} on a device you trust that is not in conflict.`,
386
+ " If it lists only devices you recognize, type the head it shows (the full 64 characters) here:",
387
+ ` ${cmd(t, "conveno devices accept <head>")}. Then revoke any device you do not recognize.`,
388
+ " If no device you trust is left, or you did not reset the devices yourself, reset them at",
389
+ ` https://api.conveno.dev/account. After a reset, run ${cmd(t, "conveno devices reset")} here and pair again.`,
390
+ ""
391
+ ].join("\n")}\n`;
392
+ }
393
+ function deviceTable(ctx, list) {
394
+ const t = ctx.theme;
395
+ const q = (w) => t.paint("quiet", w);
396
+ const head = [
397
+ ` ${q("DEVICE")}`,
398
+ q("STATE"),
399
+ q("SESSIONS"),
400
+ q("FINGERPRINT"),
401
+ q("ADDED")
402
+ ];
403
+ const rows = list.devices.map((d) => [
404
+ `${d.online ? t.status("idle") : t.status("offline")} ${t.bold(d.name)}${d.self ? q(" (this device)") : ""}`,
405
+ d.online ? "online" : "offline",
406
+ d.self ? "" : String(d.sessions),
407
+ q(d.fingerprint),
408
+ d.addedAt ? q(localStamp(d.addedAt)) : ""
409
+ ]);
410
+ const lines = columns([head, ...rows]).map((l) => ` ${l}`);
411
+ if (list.revoked.length > 0) {
412
+ lines.push("", ` ${q("Revoked:")}`);
413
+ for (const r of list.revoked) lines.push(` ${r.name} ${q(`${r.deviceId}, ${localStamp(r.revokedAt)}`)}`);
414
+ }
415
+ return lines.join("\n");
416
+ }
417
+ async function list(ctx) {
418
+ return withClient(ctx, false, async (c) => {
419
+ const devices = await c["devices.list"]({});
420
+ ctx.out(`${deviceTable(ctx, devices)}\n\n${listLine(ctx, devices.list)}`);
421
+ if (devices.conflict) {
422
+ ctx.err(conflictBlock(ctx, devices.conflict));
423
+ return 1;
424
+ }
425
+ if (devices.devices.length === 1) ctx.out(`Only this device. Run ${cmd(ctx.theme, "conveno devices pair")} here and ${cmd(ctx.theme, "conveno devices join")} on the other device.\n`);
426
+ return 0;
427
+ });
428
+ }
429
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
430
+ /**
431
+ * Pair this device with another one. Each device shows its own 8-digit code, and the owner types
432
+ * the code from the other screen. There is deliberately no flag to skip that, since the check is
433
+ * what stops a relay from slipping in its own key, and no yes/no question to answer by habit.
434
+ */
435
+ async function pair(ctx, role) {
436
+ const t = ctx.theme;
437
+ if (!ctx.interactive) return fail(ctx, {
438
+ what: "Pairing needs a terminal",
439
+ detail: ["You compare a code on both devices and confirm it here, so it cannot run unattended."],
440
+ fix: `Run ${cmd(t, role === "invite" ? "conveno devices pair" : "conveno devices join")} in a terminal.`,
441
+ exit: 2,
442
+ ref: "e_no_tty"
443
+ });
444
+ return withClient(ctx, true, async (c) => {
445
+ let s = await c["devices.pair"]({ role });
446
+ ctx.out(role === "invite" ? `Waiting for the new device. Run ${cmd(t, "conveno devices join")} on it now.\n` : `Looking for one of your devices. Run ${cmd(t, "conveno devices pair")} on it now.\n`);
447
+ const end = Date.now() + PAIR_TIMEOUT_MS;
448
+ let asked = false;
449
+ while (s.state !== "done" && s.state !== "failed" && Date.now() < end) {
450
+ if (s.state === "confirm" && !asked && s.sas && s.peer) {
451
+ asked = true;
452
+ ctx.out([
453
+ "",
454
+ ` ${role === "invite" ? "New device" : "Your device"}: ${t.bold(s.peer.name)} ${t.paint("quiet", `(${s.peer.fingerprint})`)}`,
455
+ "",
456
+ " Type this code on the other device:",
457
+ "",
458
+ ` ${t.bold(s.sas)}`,
459
+ "",
460
+ ""
461
+ ].join("\n"));
462
+ for (;;) {
463
+ const code = await ctx.prompt("Code shown on the other device (leave empty to stop):");
464
+ s = await c["devices.pairConfirm"]({
465
+ pairingId: s.pairingId,
466
+ accept: code !== "",
467
+ ...code !== "" ? { code } : {}
468
+ });
469
+ if (s.state !== "confirm") break;
470
+ ctx.err(`${t.status("error")} ${s.error ?? "That code does not match."}\n`);
471
+ }
472
+ if (s.state === "failed") break;
473
+ if (s.state === "waiting_peer") ctx.out("Waiting for the other device.\n");
474
+ continue;
475
+ }
476
+ await sleep(400);
477
+ s = await c["devices.pairStatus"]({ pairingId: s.pairingId });
478
+ }
479
+ if (s.state === "done") {
480
+ ctx.out(`${t.status("ok")} ${t.bold("Paired.")} ${s.peer ? `${s.peer.name} and this device` : "The devices"} now see each other's sessions.\n`);
481
+ return 0;
482
+ }
483
+ return fail(ctx, {
484
+ what: "Pairing did not finish",
485
+ detail: [s.error ?? (s.state === "failed" ? "The pairing failed." : "It timed out.")],
486
+ fix: "Start it again on both devices. If a code did not match although you typed it carefully, someone may be in between.",
487
+ exit: 1,
488
+ ref: "e_pair"
489
+ });
490
+ });
491
+ }
492
+ async function revoke(ctx, device, yes) {
493
+ const t = ctx.theme;
494
+ if (!device) return fail(ctx, {
495
+ what: "conveno devices revoke needs a device",
496
+ detail: ["Give its name or id, as conveno devices lists them."],
497
+ fix: `For example ${cmd(t, "conveno devices revoke desktop")}.`,
498
+ exit: 2,
499
+ ref: "e_usage"
500
+ });
501
+ if (!yes) {
502
+ if (!ctx.interactive) return fail(ctx, {
503
+ what: "Needs a terminal to confirm",
504
+ detail: ["Nothing was revoked."],
505
+ fix: `Run ${cmd(t, `conveno devices revoke ${device} --yes`)}.`,
506
+ exit: 2,
507
+ ref: "e_no_tty"
508
+ });
509
+ if (!await ctx.confirm(`Revoke ${device}? It can no longer read or send messages for your sessions.`, false)) {
510
+ ctx.out(`${t.status("info")} Nothing was changed.\n`);
511
+ return 0;
512
+ }
513
+ }
514
+ return withClient(ctx, true, async (c) => {
515
+ const r = await c["devices.revoke"]({ device });
516
+ ctx.out(`${t.status("ok")} Revoked ${t.bold(r.revoked.name)} ${t.paint("quiet", r.revoked.deviceId)}. The relay refuses it from now on and ends its login.\n`);
517
+ return 0;
518
+ });
519
+ }
520
+ async function rename(ctx, name) {
521
+ if (!name) return fail(ctx, {
522
+ what: "conveno devices rename needs a name",
523
+ fix: `For example ${cmd(ctx.theme, "conveno devices rename laptop")}.`,
524
+ exit: 2,
525
+ ref: "e_usage"
526
+ });
527
+ return withClient(ctx, true, async (c) => {
528
+ const r = await c["devices.rename"]({ name });
529
+ ctx.out(`${ctx.theme.status("ok")} This device is now called ${ctx.theme.bold(r.name)}.\n`);
530
+ return 0;
531
+ });
532
+ }
533
+ /** Clear a conflict by taking the relay's list, if its head is the one the owner typed. */
534
+ async function accept(ctx, head, yes) {
535
+ const t = ctx.theme;
536
+ if (!head || !/^[0-9a-f]{64}$/.test(head)) return fail(ctx, {
537
+ what: "conveno devices accept needs the full head of the device list",
538
+ detail: ["Run conveno devices on a device you trust and copy the 64-character head it shows."],
539
+ fix: `For example ${cmd(t, "conveno devices accept 3f1c…")} with all 64 characters.`,
540
+ exit: 2,
541
+ ref: "e_usage"
542
+ });
543
+ if (!yes) {
544
+ if (!ctx.interactive) return fail(ctx, {
545
+ what: "Needs a terminal to confirm",
546
+ detail: ["Nothing was changed."],
547
+ fix: `Run it again with ${cmd(t, "--yes")}.`,
548
+ exit: 2,
549
+ ref: "e_no_tty"
550
+ });
551
+ if (!await ctx.confirm(`Take the relay's device list with head ${head.slice(0, 16)}? Only do this if a device you trust shows the same head.`, false)) {
552
+ ctx.out(`${t.status("info")} Nothing was changed.\n`);
553
+ return 0;
554
+ }
555
+ }
556
+ return withClient(ctx, true, async (c) => {
557
+ const r = await c["devices.accept"]({ head });
558
+ ctx.out(`${t.status("ok")} ${t.bold("Accepted.")} The device list now has head ${r.list.head.slice(0, 16)}.\n`);
559
+ if (!r.member) ctx.out(` This device is not in that list, so it stays off the relay. Pair it again with ${cmd(t, "conveno devices join")}.\n`);
560
+ else ctx.out(` Run ${cmd(t, "conveno devices")} and revoke any device you do not recognize.\n`);
561
+ return 0;
562
+ });
563
+ }
564
+ /** Forget this device's copy of the list after a reset or when the relay's list left it out. */
565
+ async function reset(ctx, yes) {
566
+ const t = ctx.theme;
567
+ if (!yes) {
568
+ if (!ctx.interactive) return fail(ctx, {
569
+ what: "Needs a terminal to confirm",
570
+ detail: ["Nothing was changed."],
571
+ fix: `Run it again with ${cmd(t, "--yes")}.`,
572
+ exit: 2,
573
+ ref: "e_no_tty"
574
+ });
575
+ if (!await ctx.confirm("Forget this device's device list? It is then unpaired and has to be paired again.", false)) {
576
+ ctx.out(`${t.status("info")} Nothing was changed.\n`);
577
+ return 0;
578
+ }
579
+ }
580
+ return withClient(ctx, true, async (c) => {
581
+ await c["devices.reset"]({});
582
+ ctx.out(`${t.status("ok")} This device forgot its device list. Pair it with ${cmd(t, "conveno devices pair")} on a device you trust and ${cmd(t, "conveno devices join")} here.\n`);
583
+ return 0;
584
+ });
585
+ }
586
+ async function runDevices(ctx, argv) {
587
+ const spec = COMMANDS.find((c) => c.name === "devices");
588
+ if (!spec) return 2;
589
+ const parsed = parseFlags(ctx, spec, argv);
590
+ if (typeof parsed === "number") return parsed;
591
+ const [sub = "list", arg] = parsed.positionals;
592
+ switch (sub) {
593
+ case "list": return list(ctx);
594
+ case "pair": return pair(ctx, "invite");
595
+ case "join": return pair(ctx, "join");
596
+ case "revoke": return revoke(ctx, arg, parsed.values.yes === true);
597
+ case "rename": return rename(ctx, arg);
598
+ case "accept": return accept(ctx, arg, parsed.values.yes === true);
599
+ case "reset": return reset(ctx, parsed.values.yes === true);
600
+ default: return fail(ctx, {
601
+ what: `Unknown devices command "${sub}"`,
602
+ detail: ["Known: list, pair, join, revoke, rename, accept, reset."],
603
+ fix: `Run ${cmd(ctx.theme, "conveno devices --help")}.`,
604
+ exit: 2,
605
+ ref: "e_usage"
606
+ });
607
+ }
608
+ }
609
+ const STATE_TEXT = {
610
+ logged_out: "off, not logged in",
611
+ not_pro: "off, the account is not on Pro",
612
+ unpaired: "off, no paired devices",
613
+ connecting: "connecting",
614
+ connected: "connected",
615
+ disconnected: "disconnected, retrying",
616
+ revoked: "off, this device was revoked"
617
+ };
618
+ async function runRelay(ctx, argv) {
619
+ const t = ctx.theme;
620
+ const spec = COMMANDS.find((c) => c.name === "relay");
621
+ if (!spec) return 2;
622
+ const parsed = parseFlags(ctx, spec, argv);
623
+ if (typeof parsed === "number") return parsed;
624
+ const [sub = "status"] = parsed.positionals;
625
+ if (sub !== "status") return fail(ctx, {
626
+ what: `Unknown relay command "${sub}"`,
627
+ fix: `Run ${cmd(t, "conveno relay status")}.`,
628
+ exit: 2,
629
+ ref: "e_usage"
630
+ });
631
+ return withClient(ctx, false, async (c) => {
632
+ const r = await c["relay.status"]({});
633
+ const q = (w) => t.paint("quiet", w);
634
+ const glyph = r.state === "connected" ? t.status("ok") : t.status("info");
635
+ ctx.out(`${glyph} relay: ${t.bold(STATE_TEXT[r.state])} ${q(r.relayUrl)}\n`);
636
+ if (r.detail) ctx.out(` ${r.detail}\n`);
637
+ ctx.out(` this device: ${t.bold(r.device.name)} ${q(r.device.fingerprint)}\n`);
638
+ ctx.out(listLine(ctx, r.list));
639
+ if (r.peers.length > 0) {
640
+ ctx.out(` ${plural(r.peers.length, "other device")}:\n`);
641
+ for (const p of r.peers) ctx.out(` ${p.online ? t.status("idle") : t.status("offline")} ${p.name} ${q(p.online ? `online, ${plural(p.sessions, "session")}` : "offline")}\n`);
642
+ }
643
+ if (r.conflict) {
644
+ ctx.err(conflictBlock(ctx, r.conflict));
645
+ return 1;
646
+ }
647
+ return 0;
648
+ });
649
+ }
650
+ // src/acp-doctor.ts
651
+ /** ACP readiness of the given CLIs, in order. CLIs with no ACP entry are left out. */
652
+ function acpReadiness(ctx, clis) {
653
+ const npxConsent = readSettings(dataPaths(ctx.platform, ctx.dataDir).settings).acpAdapterNpx === true;
654
+ const out = [];
655
+ for (const cli of clis) {
656
+ const acp = SPAWN_TABLE[cli]?.acp;
657
+ if (!acp) continue;
658
+ const res = resolveAcpProgram(cli, acp, {
659
+ env: ctx.env,
660
+ which: (name) => findOnPath(name, ctx.env, ctx.platform),
661
+ npxConsent
662
+ });
663
+ if (res.ok) {
664
+ const { source, args } = res.run;
665
+ const command = source.startsWith("path:") ? [source.slice(5), ...acp.args].join(" ") : source.startsWith("npx:") ? [
666
+ "npx",
667
+ ...args,
668
+ ...acp.args
669
+ ].join(" ") : source.slice(9);
670
+ out.push({
671
+ cli,
672
+ command,
673
+ adapter: source,
674
+ ...source.startsWith("npx:") ? { onDemand: true } : {}
675
+ });
676
+ continue;
677
+ }
678
+ out.push({
679
+ cli,
680
+ ...acp.adapterPackage ? { install: adapterInstallCommand(acp.adapterPackage) } : {},
681
+ ...res.reason === "no-npx" ? { noNpx: true } : {}
682
+ });
683
+ }
684
+ return out;
685
+ }
686
+ /** The lines doctor prints. Informational: a missing ACP server is not a warning. */
687
+ function acpDoctorLines(ctx, clis) {
688
+ const rows = acpReadiness(ctx, clis);
689
+ if (rows.length === 0) return [];
690
+ const t = ctx.theme;
691
+ const q = (w) => t.paint("quiet", w);
692
+ const table = rows.map((r) => [` ${r.command ? t.status("ok") : t.glyph("offline")} ${r.cli}`, r.command ? r.onDemand ? `ready: ${r.command} (on demand; the first start downloads the package, which can take minutes)` : r.adapter?.startsWith("override:") ? `ready: ${r.command} (${acpOverrideVar(r.cli)})` : `ready: ${r.command}` : r.noNpx ? `npx was not found on PATH. Install Node.js, or install the ACP adapter: ${r.install}` : r.install ? `to enable, install the ACP adapter: ${r.install} (or run conveno init to fetch it with npx)` : q("its ACP server was not found on PATH")]);
693
+ return [
694
+ "",
695
+ `ACP workers ${q("(conveno spawn <cli>)")}`,
696
+ ...columns(table),
697
+ ...rows.some((r) => r.install || r.onDemand) ? [q("Adapters are third-party npm packages, fetched by npx on first use. They use the CLI's own sign-in.")] : []
698
+ ];
699
+ }
700
+ // src/acp-offer.ts
701
+ /** The adapter packages an installed CLI needs and that are not on PATH (nor overridden). */
702
+ function missingAdapters(ctx, installed) {
703
+ const out = [];
704
+ for (const { cli, displayName } of installed) {
705
+ const acp = SPAWN_TABLE[cli]?.acp;
706
+ if (!acp?.adapterPackage) continue;
707
+ if (!resolveAcpProgram(cli, acp, {
708
+ env: ctx.env,
709
+ which: (n) => findOnPath(n, ctx.env, ctx.platform),
710
+ npxConsent: false
711
+ }).ok) out.push({
712
+ pkg: acp.adapterPackage,
713
+ cli: displayName
714
+ });
715
+ }
716
+ return out;
717
+ }
718
+ function printManual(ctx, missing) {
719
+ const q = (w) => ctx.theme.paint("quiet", w);
720
+ for (const { pkg } of missing) {
721
+ ctx.out(` ${adapterInstallCommand(pkg)}\n`);
722
+ ctx.out(` ${q(`or run it on demand: ${adapterNpxCommand(pkg)}`)}\n`);
723
+ }
724
+ }
725
+ /**
726
+ * Ask once whether ACP workers may fetch the adapters with npx. `--acp-adapters` and
727
+ * `--no-acp-adapters` answer without asking and replace an earlier answer. Without a terminal, or
728
+ * with `--yes`, nothing is asked and nothing is saved.
729
+ */
730
+ async function offerAcpAdapters(ctx, opts) {
731
+ const t = ctx.theme;
732
+ const path = dataPaths(ctx.platform, ctx.dataDir).settings;
733
+ const missing = missingAdapters(ctx, opts.installed);
734
+ if (opts.flag !== void 0) {
735
+ writeSettings(path, { acpAdapterNpx: opts.flag });
736
+ if (opts.flag) ctx.out(`${t.status("ok")} ACP workers may fetch adapters with npx (pinned versions).\n`);
737
+ else {
738
+ ctx.out(`${t.status("info")} ACP workers will not fetch adapters with npx.\n`);
739
+ if (missing.length > 0) {
740
+ ctx.out(" To use ACP workers, install the adapters yourself:\n");
741
+ printManual(ctx, missing);
742
+ }
743
+ }
744
+ return;
745
+ }
746
+ if (missing.length === 0) return;
747
+ if (readSettings(path).acpAdapterNpx !== void 0) return;
748
+ const who = missing.map((m) => m.cli).join(" and ");
749
+ ctx.out(`\n${t.bold("ACP workers")} let conveno spawn <cli> drive a worker over the Agent Client Protocol.\n ${who} ${missing.length > 1 ? "need" : "needs"} a separate adapter for that. Adapters are third-party npm packages\n (Apache-2.0). Conveno does not bundle them; npx would download these on first use:
750
+ ${missing.map((m) => ` ${pinnedAdapter(m.pkg) ?? m.pkg}\n`).join("")}`);
751
+ if (!ctx.interactive || opts.yes) {
752
+ ctx.out(`${t.status("info")} Not asked. Run ${cmd(t, "conveno init --acp-adapters")} to allow npx, or install by hand:\n`);
753
+ printManual(ctx, missing);
754
+ return;
755
+ }
756
+ if (await ctx.confirm("Let ACP workers fetch these adapters with npx?", false)) {
757
+ writeSettings(path, { acpAdapterNpx: true });
758
+ ctx.out(`${t.status("ok")} Allowed. The first ACP worker for each takes a moment to start.\n`);
759
+ } else {
760
+ writeSettings(path, { acpAdapterNpx: false });
761
+ ctx.out(`${t.status("info")} Not allowed. To use ACP workers, install the adapters yourself:\n`);
762
+ printManual(ctx, missing);
763
+ }
764
+ }
765
+ // src/diff.ts
766
+ const splitLines = (s) => {
767
+ if (s === "") return [];
768
+ const lines = s.split("\n");
769
+ if (lines.at(-1) === "") lines.pop();
770
+ return lines;
771
+ };
772
+ /** Line diff through the longest common subsequence. Fine for config files. */
773
+ function diffOps(a, b) {
774
+ let start = 0;
775
+ while (start < a.length && start < b.length && a[start] === b[start]) start++;
776
+ let endA = a.length;
777
+ let endB = b.length;
778
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
779
+ endA--;
780
+ endB--;
781
+ }
782
+ const mid = [];
783
+ const x = a.slice(start, endA);
784
+ const y = b.slice(start, endB);
785
+ if (x.length * y.length > 4e6) {
786
+ for (const line of x) mid.push({
787
+ t: "-",
788
+ line
789
+ });
790
+ for (const line of y) mid.push({
791
+ t: "+",
792
+ line
793
+ });
794
+ } else {
795
+ const w = y.length + 1;
796
+ const lcs = new Uint32Array((x.length + 1) * w);
797
+ for (let i = x.length - 1; i >= 0; i--) for (let j = y.length - 1; j >= 0; j--) lcs[i * w + j] = x[i] === y[j] ? lcs[(i + 1) * w + j + 1] + 1 : Math.max(lcs[(i + 1) * w + j], lcs[i * w + j + 1]);
798
+ let i = 0;
799
+ let j = 0;
800
+ while (i < x.length && j < y.length) if (x[i] === y[j]) {
801
+ mid.push({
802
+ t: " ",
803
+ line: x[i]
804
+ });
805
+ i++;
806
+ j++;
807
+ } else if (lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) mid.push({
808
+ t: "-",
809
+ line: x[i++]
810
+ });
811
+ else mid.push({
812
+ t: "+",
813
+ line: y[j++]
814
+ });
815
+ while (i < x.length) mid.push({
816
+ t: "-",
817
+ line: x[i++]
818
+ });
819
+ while (j < y.length) mid.push({
820
+ t: "+",
821
+ line: y[j++]
822
+ });
823
+ }
824
+ return [
825
+ ...a.slice(0, start).map((line) => ({
826
+ t: " ",
827
+ line
828
+ })),
829
+ ...mid,
830
+ ...a.slice(endA).map((line) => ({
831
+ t: " ",
832
+ line
833
+ }))
834
+ ];
835
+ }
836
+ /** Unified diff body (hunks only) between two texts, `before` null meaning a new file. */
837
+ function unifiedDiff(before, after, context = 2) {
838
+ const ops = diffOps(splitLines(before ?? ""), splitLines(after));
839
+ const changed = ops.flatMap((o, i) => o.t === " " ? [] : [i]);
840
+ if (changed.length === 0) return [];
841
+ const ranges = [];
842
+ for (const i of changed) {
843
+ const lo = Math.max(0, i - context);
844
+ const hi = Math.min(ops.length, i + context + 1);
845
+ const last = ranges.at(-1);
846
+ if (last && lo <= last[1]) last[1] = hi;
847
+ else ranges.push([lo, hi]);
848
+ }
849
+ const out = [];
850
+ for (const [lo, hi] of ranges) {
851
+ let oldStart = 1;
852
+ let newStart = 1;
853
+ for (const o of ops.slice(0, lo)) {
854
+ if (o.t !== "+") oldStart++;
855
+ if (o.t !== "-") newStart++;
856
+ }
857
+ const slice = ops.slice(lo, hi);
858
+ const oldCount = slice.filter((o) => o.t !== "+").length;
859
+ const newCount = slice.filter((o) => o.t !== "-").length;
860
+ const oldFrom = oldCount === 0 ? oldStart - 1 : oldStart;
861
+ out.push(`@@ -${oldFrom},${oldCount} +${newStart},${newCount} @@`);
862
+ for (const o of slice) out.push(`${o.t}${o.line}`);
863
+ }
864
+ return out;
865
+ }
866
+ /** Colour diff lines with brand roles: added `ok`, removed `error`, hunk headers `quiet`. */
867
+ function paintDiff(theme, lines, indent = " ") {
868
+ return lines.map((l) => {
869
+ const role = l.startsWith("@@") ? "quiet" : l.startsWith("+") ? "ok" : l.startsWith("-") ? "error" : null;
870
+ return indent + (role ? theme.paint(role, l) : l);
871
+ });
872
+ }
873
+ // src/apply.ts
874
+ const MANIFEST_NAME = "manifest.json";
875
+ const isPosix = (ctx) => ctx.platform !== "win32";
876
+ const sha256 = (data) => createHash("sha256").update(data).digest("hex");
877
+ /** A file changed between planning and writing. */
878
+ var StaleError = class extends Error {
879
+ path;
880
+ /** True unless files written earlier in the same run could not be put back. */
881
+ rolledBack = true;
882
+ constructor(path) {
883
+ super(`${path} changed while Conveno was working. Nothing in it was overwritten.`);
884
+ this.path = path;
885
+ this.name = "StaleError";
886
+ }
887
+ };
888
+ /** Will this change be made by the CLI's own command? Yes when the CLI is installed and the plan has one. */
889
+ const usesCommand = (item) => Boolean(item.change.viaCommand) && item.installed;
890
+ /** Print one block per file: path, what changes, the command that will run, the unified diff. */
891
+ function presentChanges(ctx, items) {
892
+ const t = ctx.theme;
893
+ for (const item of items) {
894
+ const { change } = item;
895
+ ctx.out(` ${t.bold(tilde(change.path, ctx.home))}${change.before === null ? t.paint("quiet", " (new file)") : change.deleteFile ? t.paint("quiet", " (deleted)") : ""}\n`);
896
+ ctx.out(` ${change.description}\n`);
897
+ if (usesCommand(item) && change.viaCommand !== void 0 && change.viaCommand) {
898
+ ctx.out(` ${t.paint("quiet", "will run")} ${t.bold(change.viaCommand.join(" "))}\n`);
899
+ ctx.out(` ${t.paint("quiet", "expected result (the command may format the file differently)")}\n`);
900
+ }
901
+ const body = paintDiff(t, unifiedDiff(change.before, change.after));
902
+ if (body.length > 0) ctx.out(`${body.join("\n")}\n`);
903
+ ctx.out("\n");
904
+ }
905
+ }
906
+ /** `<backups>/files/<path without drive or leading separator>`. */
907
+ const mirrored = (path) => join("files", path.replace(/^[A-Za-z]:/, "").replace(/^[\\/]+/, ""));
908
+ async function uniqueDir(base, stamp) {
909
+ const existing = new Set(await readdir(base).catch(() => []));
910
+ let name = stamp;
911
+ for (let n = 2; existing.has(name); n++) name = `${stamp}-${n}`;
912
+ return name;
913
+ }
914
+ async function readBytes(path) {
915
+ try {
916
+ return await readFile(path);
917
+ } catch (e) {
918
+ if (e.code === "ENOENT") return null;
919
+ throw e;
920
+ }
921
+ }
922
+ /** Create a directory only the user can use, and tighten one that already exists. */
923
+ async function privateDir(ctx, dir) {
924
+ await mkdir(dir, {
925
+ recursive: true,
926
+ mode: 448
927
+ });
928
+ if (isPosix(ctx)) await chmod(dir, 448).catch(() => void 0);
929
+ }
930
+ const realIo = {
931
+ realpath: (p) => realpath(p),
932
+ mkdir: async (p) => void await mkdir(p, { recursive: true }),
933
+ mode: (p) => stat(p).then((s) => s.mode & 511, () => void 0),
934
+ writeFile: (p, data, mode) => writeFile(p, data, { mode }),
935
+ chmod: (p, mode) => chmod(p, mode),
936
+ rename: (a, b) => rename$1(a, b),
937
+ overwrite: async (p, data) => {
938
+ const fh = await open(p, "w");
939
+ try {
940
+ await fh.writeFile(data);
941
+ await fh.sync();
942
+ } finally {
943
+ await fh.close();
944
+ }
945
+ },
946
+ rm: (p) => rm(p, { force: true }),
947
+ platform: process.platform
948
+ };
949
+ /**
950
+ * Replace the contents of `path` with `data`, keeping its mode and writing through a symlink.
951
+ *
952
+ * POSIX: write a temp file in the same directory, then rename it over the target, so a reader
953
+ * never sees half a file.
954
+ *
955
+ * Windows: write the target in place (open truncated, write, fsync). Reason, confirmed in the
956
+ * libuv source Node uses: `fs.rename` is `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`, which needs
957
+ * DELETE access to the existing target. That fails with ERROR_ACCESS_DENIED (reported as EPERM,
958
+ * with `err.path` set to the temp file, the source) whenever any other process holds the target
959
+ * open without FILE_SHARE_DELETE. Node itself shares READ, WRITE and DELETE on every handle, but
960
+ * C runtime, Python and .NET defaults share only READ and WRITE, and so may a running CLI or a
961
+ * virus scanner. Truncating in place needs only FILE_SHARE_WRITE from the other handles, so it
962
+ * succeeds in the cases where an atomic replace cannot. The cost is that a reader can see a
963
+ * half-written file for a moment. That is acceptable here because callers re-read the target and
964
+ * compare it with the plan just before writing, and `applyChanges` restores every file from its
965
+ * backup if any write fails. No temp file exists on this path, so none can be left behind.
966
+ */
967
+ async function writeAtomic(path, data, io = realIo, wantMode) {
968
+ const target = await io.realpath(path).catch(() => path);
969
+ await io.mkdir(dirname(target));
970
+ if (io.platform === "win32") {
971
+ await io.overwrite(target, data);
972
+ return;
973
+ }
974
+ const mode = wantMode ?? await io.mode(target);
975
+ const tmp = join(dirname(target), `.${basename(target)}.conveno-${randomBytes(6).toString("hex")}.tmp`);
976
+ try {
977
+ await io.writeFile(tmp, data, mode ?? 420);
978
+ if (mode !== void 0) await io.chmod(tmp, mode);
979
+ await io.rename(tmp, target);
980
+ } catch (e) {
981
+ if (e instanceof Error && e.path === tmp) e.path = target;
982
+ throw e;
983
+ } finally {
984
+ await io.rm(tmp).catch(() => void 0);
985
+ }
986
+ }
987
+ /** A write failed. `rolledBack` says whether every file written before it was put back. */
988
+ var ApplyError = class extends Error {
989
+ rolledBack;
990
+ notRestored;
991
+ backupDir;
992
+ constructor(message, rolledBack, notRestored, backupDir, options) {
993
+ super(message, options);
994
+ this.rolledBack = rolledBack;
995
+ this.notRestored = notRestored;
996
+ this.backupDir = backupDir;
997
+ this.name = "ApplyError";
998
+ }
999
+ };
1000
+ /** Re-read the file and refuse to go on when it is no longer what the plan was made from. */
1001
+ async function currentIfUnchanged(change) {
1002
+ const bytes = await readBytes(change.path);
1003
+ if (!(change.before === null ? bytes === null : bytes !== null && bytes.toString("utf8") === change.before)) throw new StaleError(change.path);
1004
+ return bytes;
1005
+ }
1006
+ /**
1007
+ * Back up every file we will touch, write the manifest, then apply. Each file is re-read first,
1008
+ * so a change made after the plan was shown is never overwritten.
1009
+ */
1010
+ async function applyChanges(ctx, items, opts = {}) {
1011
+ const paths = dataPaths(ctx.platform, ctx.dataDir);
1012
+ const unique = items.filter((it, i) => items.findIndex((o) => o.change.path === it.change.path) === i);
1013
+ const originals = /* @__PURE__ */ new Map();
1014
+ for (const { change } of unique) originals.set(change.path, await currentIfUnchanged(change));
1015
+ await privateDir(ctx, ctx.dataDir);
1016
+ await privateDir(ctx, paths.backups);
1017
+ const stamp = ctx.now().toISOString().slice(0, 19).replace(/:/g, "-");
1018
+ const backupDir = join(paths.backups, await uniqueDir(paths.backups, stamp));
1019
+ await privateDir(ctx, backupDir);
1020
+ const entries = [];
1021
+ for (const { cli, change } of unique) {
1022
+ const original = originals.get(change.path) ?? null;
1023
+ let backup = null;
1024
+ if (original !== null) {
1025
+ backup = mirrored(change.path);
1026
+ const dest = join(backupDir, backup);
1027
+ await mkdir(dirname(dest), {
1028
+ recursive: true,
1029
+ mode: 448
1030
+ });
1031
+ await writeFile(dest, original, { mode: 384 });
1032
+ }
1033
+ entries.push({
1034
+ cli,
1035
+ path: change.path,
1036
+ backup,
1037
+ description: change.description,
1038
+ ...change.deleteFile ? {} : { afterSha256: sha256(change.after) },
1039
+ ...change.pruneEmptyDir === void 0 ? {} : { pruneEmptyDir: change.pruneEmptyDir }
1040
+ });
1041
+ }
1042
+ const manifest = {
1043
+ version: 1,
1044
+ createdAt: ctx.now().toISOString(),
1045
+ entries,
1046
+ ...opts.markRestored ? { restoredAt: ctx.now().toISOString() } : {}
1047
+ };
1048
+ const writeManifest = () => writeFile(join(backupDir, MANIFEST_NAME), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 384 });
1049
+ await writeManifest();
1050
+ const io = opts.io ?? realIo;
1051
+ const how = [];
1052
+ const touched = [];
1053
+ try {
1054
+ for (const item of unique) {
1055
+ const { cli, change } = item;
1056
+ let done = false;
1057
+ touched.push(change.path);
1058
+ if (usesCommand(item) && change.viaCommand) {
1059
+ const [bin, ...args] = change.viaCommand;
1060
+ try {
1061
+ const r = await ctx.exec(bin, args);
1062
+ const now = await readBytes(change.path);
1063
+ done = r.code === 0 && now !== null && now.toString("utf8") !== change.before;
1064
+ } catch {
1065
+ done = false;
1066
+ }
1067
+ }
1068
+ if (!done) {
1069
+ await currentIfUnchanged(change);
1070
+ if (change.deleteFile) {
1071
+ await io.rm(change.path);
1072
+ if (change.pruneEmptyDir !== void 0) await pruneEmptyDirs(change.path, change.pruneEmptyDir);
1073
+ } else await writeAtomic(change.path, change.after, io, change.mode);
1074
+ }
1075
+ how.push({
1076
+ cli,
1077
+ path: change.path,
1078
+ via: done ? "command" : "file"
1079
+ });
1080
+ }
1081
+ } catch (e) {
1082
+ const notRestored = [];
1083
+ for (const path of touched.reverse()) {
1084
+ const original = originals.get(path) ?? null;
1085
+ try {
1086
+ const now = await readBytes(path);
1087
+ if (original === null ? now === null : now?.equals(original) === true) continue;
1088
+ if (original === null) await io.rm(path);
1089
+ else await writeAtomic(path, original, io);
1090
+ } catch {
1091
+ notRestored.push(path);
1092
+ }
1093
+ }
1094
+ const rolledBack = notRestored.length === 0;
1095
+ if (rolledBack) await rm(backupDir, {
1096
+ recursive: true,
1097
+ force: true
1098
+ }).catch(() => void 0);
1099
+ if (e instanceof StaleError) {
1100
+ e.rolledBack = rolledBack;
1101
+ throw e;
1102
+ }
1103
+ throw new ApplyError(e instanceof Error ? e.message : String(e), rolledBack, notRestored, backupDir, { cause: e });
1104
+ }
1105
+ let rewrite = false;
1106
+ for (const e of entries) {
1107
+ const now = await readBytes(e.path);
1108
+ if (now !== null && sha256(now) !== e.afterSha256) {
1109
+ e.afterSha256 = sha256(now);
1110
+ rewrite = true;
1111
+ }
1112
+ }
1113
+ if (rewrite) await writeManifest();
1114
+ return {
1115
+ backupDir,
1116
+ how
1117
+ };
1118
+ }
1119
+ /** Every manifest that has not been restored yet, newest first. */
1120
+ async function listManifests(ctx) {
1121
+ const { backups } = dataPaths(ctx.platform, ctx.dataDir);
1122
+ const names = (await readdir(backups).catch(() => [])).sort().reverse();
1123
+ const out = [];
1124
+ for (const name of names) try {
1125
+ const manifest = JSON.parse(await readFile(join(backups, name, MANIFEST_NAME), "utf8"));
1126
+ if (manifest.version === 1 && !manifest.restoredAt) out.push({
1127
+ dir: join(backups, name),
1128
+ manifest
1129
+ });
1130
+ } catch {}
1131
+ return out;
1132
+ }
1133
+ /**
1134
+ * What uninstall does with one file. `current` is the hash of the file now (null when missing).
1135
+ * The backup is restored only when the file is exactly what init left; any other content means
1136
+ * someone changed it since, so only Conveno's own entries come out.
1137
+ */
1138
+ function actionFor(entry, current) {
1139
+ if (current === null) return "gone";
1140
+ if (entry.afterSha256 !== void 0 && current === entry.afterSha256) return entry.backup === null ? "remove" : "restore";
1141
+ return "edit";
1142
+ }
1143
+ /**
1144
+ * Predict the actions for all manifests, newest to oldest, following how each restore changes the
1145
+ * file the next (older) manifest sees.
1146
+ */
1147
+ async function previewRestore(manifests) {
1148
+ const state = /* @__PURE__ */ new Map();
1149
+ const rows = [];
1150
+ for (const { dir, manifest } of manifests) for (const entry of manifest.entries) {
1151
+ if (!state.has(entry.path)) {
1152
+ const bytes = await readBytes(entry.path);
1153
+ state.set(entry.path, bytes === null ? null : sha256(bytes));
1154
+ }
1155
+ const action = actionFor(entry, state.get(entry.path) ?? null);
1156
+ rows.push({
1157
+ entry,
1158
+ action
1159
+ });
1160
+ if (action === "restore" && entry.backup !== null) state.set(entry.path, sha256(await readFile(join(dir, entry.backup))));
1161
+ else if (action === "remove") state.set(entry.path, null);
1162
+ else if (action === "edit") state.set(entry.path, "unknown");
1163
+ }
1164
+ return rows;
1165
+ }
1166
+ /** Remove up to `levels` empty folders above `file`, stopping at the first one with anything in it. */
1167
+ async function pruneEmptyDirs(file, levels) {
1168
+ let dir = dirname(file);
1169
+ for (let n = levels === true ? 1 : levels; n > 0; n--) {
1170
+ if (!await rmdir(dir).then(() => true, () => false)) break;
1171
+ dir = dirname(dir);
1172
+ }
1173
+ }
1174
+ /** Restore one file as init found it, when it still matches. Returns the action taken. */
1175
+ async function restoreEntry(dir, entry) {
1176
+ const bytes = await readBytes(entry.path);
1177
+ const action = actionFor(entry, bytes === null ? null : sha256(bytes));
1178
+ if (action === "remove") {
1179
+ await rm(entry.path, { force: true });
1180
+ if (entry.pruneEmptyDir !== void 0) await pruneEmptyDirs(entry.path, entry.pruneEmptyDir);
1181
+ } else if (action === "restore" && entry.backup !== null) await writeAtomic(entry.path, await readFile(join(dir, entry.backup)));
1182
+ return action;
1183
+ }
1184
+ async function markRestored(ctx, found) {
1185
+ const done = {
1186
+ ...found.manifest,
1187
+ restoredAt: ctx.now().toISOString()
1188
+ };
1189
+ await writeFile(join(found.dir, MANIFEST_NAME), `${JSON.stringify(done, null, 2)}\n`, { mode: 384 });
1190
+ }
1191
+ // src/init.ts
1192
+ const CODEX_NOTE = "Codex asks you to approve Conveno once: run /hooks inside Codex.";
1193
+ const CURSOR_NOTE = "Cursor can ask you to approve Conveno when you start it in your home folder. Approve it once there with: cursor-agent mcp enable conveno";
1194
+ /** Detect every adapter. A detection that throws counts as not installed. */
1195
+ async function detectAll(ctx, adapters = ctx.adapters) {
1196
+ const env = adapterEnv(ctx);
1197
+ return Promise.all(adapters.map(async (adapter) => {
1198
+ try {
1199
+ return {
1200
+ adapter,
1201
+ detection: await adapter.detect(env)
1202
+ };
1203
+ } catch {
1204
+ return {
1205
+ adapter,
1206
+ detection: {
1207
+ installed: false,
1208
+ configPaths: []
1209
+ }
1210
+ };
1211
+ }
1212
+ }));
1213
+ }
1214
+ /** The `--cli` example in error fixes: every CLI this version supports. */
1215
+ const cliListExample = (ctx) => `--cli ${ctx.adapters.map((a) => a.cli).join(",")}`;
1216
+ function parseCliList(raw, ctx) {
1217
+ if (raw === void 0) return ctx.adapters;
1218
+ const names = raw.split(/[\s,]+/).filter(Boolean);
1219
+ const out = [];
1220
+ for (const n of names) {
1221
+ if (!CLI_KINDS.includes(n)) {
1222
+ const suggestion = closest(n, ctx.adapters.map((a) => a.cli));
1223
+ return {
1224
+ message: `Unknown CLI "${n}". Known CLIs: ${ctx.adapters.map((a) => a.cli).join(", ")}.`,
1225
+ ...suggestion ? { suggestion: `Did you mean ${suggestion}?` } : {}
1226
+ };
1227
+ }
1228
+ const a = ctx.adapters.find((x) => x.cli === n);
1229
+ if (!a) return { message: `"${n}" is not supported in this version. Supported: ${ctx.adapters.map((x) => x.cli).join(", ")}.` };
1230
+ out.push(a);
1231
+ }
1232
+ return out;
1233
+ }
1234
+ function printDetections(ctx, found) {
1235
+ const t = ctx.theme;
1236
+ ctx.out(`${t.bold("Looking for AI tools on this machine")}\n`);
1237
+ const rows = found.map(({ adapter, detection }) => detection.installed ? [
1238
+ ` ${t.status("ok")} ${adapter.cli}`,
1239
+ adapter.displayName,
1240
+ detection.version ?? "",
1241
+ t.paint("quiet", tilde(detection.configPaths[0] ?? "", ctx.home))
1242
+ ] : [` ${t.glyph("offline")} ${adapter.cli}`, t.paint("quiet", "not found")]);
1243
+ ctx.out(`${columns(rows).join("\n")}\n\n`);
1244
+ }
1245
+ /** Collect plans from installed adapters. Returns failures instead of throwing. */
1246
+ async function collectPlans(ctx, found, which, baseline, accept = []) {
1247
+ const env = adapterEnv(ctx);
1248
+ const items = [];
1249
+ const failures = [];
1250
+ for (const { adapter, detection } of found) try {
1251
+ for (const change of await (which === "plan" ? adapter.plan(env, { accept }) : adapter.uninstallPlan(env, baseline))) {
1252
+ if (items.some((i) => i.change.path === change.path && i.change.after === change.after)) continue;
1253
+ items.push({
1254
+ cli: adapter.cli,
1255
+ installed: detection.installed,
1256
+ change
1257
+ });
1258
+ }
1259
+ } catch (e) {
1260
+ failures.push({
1261
+ cli: adapter.cli,
1262
+ message: plainError(e)
1263
+ });
1264
+ }
1265
+ return {
1266
+ items,
1267
+ failures
1268
+ };
1269
+ }
1270
+ function reportFailures(ctx, failures, retry) {
1271
+ for (const f of failures) fail(ctx, {
1272
+ what: `Could not plan changes for ${f.cli}`,
1273
+ detail: [f.message],
1274
+ fix: `Fix the problem above, or run ${cmd(ctx.theme, retry)} to leave ${f.cli} out.`,
1275
+ exit: 1,
1276
+ ref: "e_plan"
1277
+ });
1278
+ }
1279
+ const staleFailure = (ctx, e, rerun) => fail(ctx, {
1280
+ what: `${tilde(e.path, ctx.home)} changed while Conveno was waiting`,
1281
+ detail: [e.rolledBack ? "Conveno did not overwrite it. Nothing was left changed." : "Conveno did not overwrite it. Some other files may already be changed."],
1282
+ fix: `Run ${cmd(ctx.theme, rerun)} again to plan from the file as it is now.`,
1283
+ exit: 1,
1284
+ ref: "e_stale"
1285
+ });
1286
+ /** Show the plan, confirm, back up, apply. Shared by init and the plan-based uninstall. */
1287
+ async function confirmAndApply(ctx, items, opts) {
1288
+ const t = ctx.theme;
1289
+ const files = new Set(items.map((i) => i.change.path)).size;
1290
+ const notes = opts.notes ?? [];
1291
+ ctx.out(`${t.bold(`Conveno will change ${plural(files, "file")}.`)}${notes.length > 0 ? "" : " Nothing else is touched."}\n\n`);
1292
+ presentChanges(ctx, items);
1293
+ for (const n of notes) ctx.out(` ${n}\n\n`);
1294
+ const paths = dataPaths(ctx.platform, ctx.dataDir);
1295
+ ctx.out(` ${t.paint("quiet", `Backups go to ${tilde(paths.backups, ctx.home)}/<timestamp>/`)}\n`);
1296
+ ctx.out(` ${t.paint("quiet", "Undo any time with:")} ${cmd(t, "conveno uninstall")}\n\n`);
1297
+ if (!opts.yes) {
1298
+ if (!ctx.interactive) return { exit: fail(ctx, {
1299
+ what: "Needs a terminal to confirm",
1300
+ detail: ["No changes were made."],
1301
+ fix: `Run ${cmd(t, `${opts.rerun} --yes`)} to apply the changes shown above.`,
1302
+ exit: 2,
1303
+ ref: "e_no_tty"
1304
+ }) };
1305
+ if (!await ctx.confirm(`${opts.verb} these changes?`, true)) {
1306
+ ctx.out(`${t.status("info")} Nothing was changed.\n`);
1307
+ return { exit: 0 };
1308
+ }
1309
+ }
1310
+ if (opts.beforeApply) {
1311
+ const code = await opts.beforeApply();
1312
+ if (code !== 0) return { exit: code };
1313
+ }
1314
+ try {
1315
+ return { applied: await applyChanges(ctx, [...items, ...opts.backups ?? []], opts.markRestored ? { markRestored: true } : {}) };
1316
+ } catch (e) {
1317
+ if (e instanceof StaleError) return { exit: staleFailure(ctx, e, opts.rerun) };
1318
+ if (e instanceof ApplyError && !e.rolledBack) return { exit: fail(ctx, {
1319
+ what: "Could not write the changes",
1320
+ detail: [plainError(e.cause ?? e), `These files could not be put back and may be changed: ${e.notRestored.map((p) => tilde(p, ctx.home)).join(", ")}.`],
1321
+ fix: `The originals are in ${tilde(e.backupDir, ctx.home)}. Copy them back, then fix the problem and run again.`,
1322
+ exit: 1,
1323
+ ref: "e_write"
1324
+ }) };
1325
+ return { exit: fail(ctx, {
1326
+ what: "Could not write the changes",
1327
+ detail: [plainError(e instanceof ApplyError ? e.cause ?? e : e), "Files already written in this run were restored. Nothing was left changed."],
1328
+ fix: "Close the program that has the file open (a running Claude Code, an editor), then run again.",
1329
+ exit: 1,
1330
+ ref: "e_write"
1331
+ }) };
1332
+ }
1333
+ }
1334
+ /**
1335
+ * Every optional question for these CLIs that is not yet turned on. `enabled` throwing counts as
1336
+ * on: nothing to offer. So does an option the tool cannot take (`available` false).
1337
+ */
1338
+ async function pendingOptions(ctx, adapters) {
1339
+ const env = adapterEnv(ctx);
1340
+ const out = [];
1341
+ for (const a of adapters) for (const o of a.optional ?? []) {
1342
+ if (o.available && !await o.available(env).catch(() => false)) continue;
1343
+ if (await o.enabled(env).catch(() => true)) continue;
1344
+ out.push({
1345
+ cli: a.cli,
1346
+ id: o.id,
1347
+ question: o.question,
1348
+ defaultYes: o.defaultYes === true
1349
+ });
1350
+ }
1351
+ return out;
1352
+ }
1353
+ /**
1354
+ * Run the follow-up step of the options answered yes, for options that are not file edits (they
1355
+ * have `apply`). Each failure comes back as one friendly line and never stops the setup.
1356
+ */
1357
+ async function applyOptions(ctx, adapters, accepted) {
1358
+ const env = adapterEnv(ctx);
1359
+ const yes = new Set(accepted);
1360
+ const done = [];
1361
+ const problems = [];
1362
+ for (const a of adapters) for (const o of a.optional ?? []) {
1363
+ if (!yes.has(o.id) || !o.apply) continue;
1364
+ try {
1365
+ const r = await o.apply(env);
1366
+ if (r.ok) done.push({
1367
+ cli: a.cli,
1368
+ id: o.id
1369
+ });
1370
+ else problems.push(r.message);
1371
+ } catch {
1372
+ problems.push(`Couldn't finish setting up ${a.displayName}.`);
1373
+ }
1374
+ }
1375
+ return {
1376
+ done,
1377
+ problems
1378
+ };
1379
+ }
1380
+ /**
1381
+ * Whether setup has taken care of a tool's first-run approvals: true when every approval option it
1382
+ * has is in place. Undefined when the tool has none, so its note is unchanged.
1383
+ */
1384
+ async function approvedBySetup(ctx, adapter) {
1385
+ const env = adapterEnv(ctx);
1386
+ const approvals = (adapter.optional ?? []).filter((o) => o.approval === true);
1387
+ if (approvals.length === 0) return void 0;
1388
+ for (const o of approvals) if (!await o.enabled(env).catch(() => false)) return false;
1389
+ return true;
1390
+ }
1391
+ /**
1392
+ * Approval options that are already on for a tool this run changes. Codex calls a hook it has
1393
+ * trusted "modified" once its command changes (a moved `conveno`), so the approval is given again.
1394
+ */
1395
+ async function renewedApprovals(ctx, adapters, items) {
1396
+ const env = adapterEnv(ctx);
1397
+ const ids = [];
1398
+ for (const a of adapters) {
1399
+ if (!items.some((i) => i.cli === a.cli)) continue;
1400
+ for (const o of a.optional ?? []) {
1401
+ if (o.approval !== true || !o.apply) continue;
1402
+ if (o.available && !await o.available(env).catch(() => false)) continue;
1403
+ if (await o.enabled(env).catch(() => false)) ids.push(o.id);
1404
+ }
1405
+ }
1406
+ return ids;
1407
+ }
1408
+ /**
1409
+ * What the options answered yes write outside the plan: a line for each, and the files as
1410
+ * no-change entries so they are backed up with the rest (a file the plan already changes is not
1411
+ * listed twice, and a file that does not exist has nothing to back up).
1412
+ */
1413
+ async function approvalWrites(ctx, adapters, ids, items) {
1414
+ const env = adapterEnv(ctx);
1415
+ const notes = [];
1416
+ const backups = [];
1417
+ for (const a of adapters) for (const o of a.optional ?? []) {
1418
+ if (!ids.has(o.id) || !o.applyWrites) continue;
1419
+ const w = o.applyWrites(env);
1420
+ notes.push(w.note);
1421
+ for (const path of w.paths) {
1422
+ if ([...items, ...backups].some((i) => i.change.path === path)) continue;
1423
+ const text = await readFile(path, "utf8").catch(() => null);
1424
+ if (text === null) continue;
1425
+ backups.push({
1426
+ cli: a.cli,
1427
+ installed: true,
1428
+ change: {
1429
+ component: "hooks",
1430
+ kind: "update",
1431
+ path,
1432
+ before: text,
1433
+ after: text,
1434
+ description: `${a.displayName} approval of Conveno's hooks, written by ${a.displayName}.`
1435
+ }
1436
+ });
1437
+ }
1438
+ }
1439
+ return {
1440
+ notes,
1441
+ backups
1442
+ };
1443
+ }
1444
+ /**
1445
+ * After a tool wrote its own approval into a backed-up file, record the file as it is now, so
1446
+ * `conveno uninstall` still sees it as the one setup left and can restore the backup.
1447
+ */
1448
+ async function refreshManifest(backupDir, paths) {
1449
+ const file = join(backupDir, "manifest.json");
1450
+ try {
1451
+ const manifest = JSON.parse(await readFile(file, "utf8"));
1452
+ let changed = false;
1453
+ for (const e of manifest.entries) {
1454
+ if (!paths.includes(e.path)) continue;
1455
+ const now = await readFile(e.path).catch(() => null);
1456
+ if (now === null) continue;
1457
+ e.afterSha256 = sha256(now);
1458
+ changed = true;
1459
+ }
1460
+ if (changed) await writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, { mode: 384 });
1461
+ } catch {}
1462
+ }
1463
+ /** The changes `with` has that `base` does not: a different file, or the same file with other text. */
1464
+ function extraChanges(base, withOpt) {
1465
+ const had = new Set(base.map((i) => `${i.change.path}\0${i.change.after}\0${i.change.kind}`));
1466
+ return withOpt.filter((i) => !had.has(`${i.change.path}\0${i.change.after}\0${i.change.kind}`));
1467
+ }
1468
+ /** `conveno setup` and its older name `conveno init`. Both end here. */
1469
+ async function runInit(ctx, argv, name = "init") {
1470
+ const first = COMMANDS.find((c) => c.name === name);
1471
+ const early = first ? parseFlags(ctx, first, argv) : void 0;
1472
+ if (typeof early === "number") return early;
1473
+ const lead = early?.values.lead;
1474
+ if (typeof lead === "string" && !CLI_KINDS.includes(lead)) {
1475
+ const suggestion = closest(lead, [...CLI_KINDS]);
1476
+ return fail(ctx, {
1477
+ what: `Unknown AI tool "${lead}" for --lead`,
1478
+ detail: [`Known AI tools: ${CLI_KINDS.join(", ")}.`],
1479
+ fix: `Pass ${cmd(ctx.theme, `--lead ${CLI_KINDS[0]}`)} or leave it out.`,
1480
+ ...suggestion ? { didYouMean: `Did you mean ${suggestion}?` } : {},
1481
+ exit: 2,
1482
+ ref: "e_usage"
1483
+ });
1484
+ }
1485
+ const outcome = {};
1486
+ const code = await initSetup(ctx, argv, outcome, name);
1487
+ if (code !== 0) return code;
1488
+ if (typeof lead === "string" && early?.values["dry-run"] !== true) {
1489
+ writeSettings(dataPaths(ctx.platform, ctx.dataDir).settings, { leadCli: lead });
1490
+ const shown = ctx.adapters.find((a) => a.cli === lead)?.displayName ?? lead;
1491
+ ctx.out(`${ctx.theme.status("ok")} ${shown} will lead when it starts and nobody else leads.\n`);
1492
+ }
1493
+ if (!outcome.offer) return code;
1494
+ const spec = COMMANDS.find((c) => c.name === name);
1495
+ const parsed = spec ? parseFlags(ctx, spec, argv) : void 0;
1496
+ const values = typeof parsed === "object" ? parsed.values : {};
1497
+ await offerAcpAdapters(ctx, {
1498
+ installed: outcome.offer,
1499
+ flag: values["acp-adapters"] === true ? true : values["no-acp-adapters"] === true ? false : void 0,
1500
+ yes: values.yes === true
1501
+ });
1502
+ return 0;
1503
+ }
1504
+ async function initSetup(ctx, argv, outcome, name) {
1505
+ const t = ctx.theme;
1506
+ const started = ctx.now();
1507
+ const spec = COMMANDS.find((c) => c.name === name);
1508
+ if (!spec) return 2;
1509
+ const parsed = parseFlags(ctx, spec, argv);
1510
+ if (typeof parsed === "number") return parsed;
1511
+ const values = parsed.values;
1512
+ if (values["acp-adapters"] === true && values["no-acp-adapters"] === true) return fail(ctx, {
1513
+ what: "Use --acp-adapters or --no-acp-adapters, not both",
1514
+ fix: `Run ${cmd(t, `conveno ${name} --help`)} to see the options.`,
1515
+ exit: 2,
1516
+ ref: "e_usage"
1517
+ });
1518
+ const chosen = parseCliList(typeof values.cli === "string" ? values.cli : void 0, ctx);
1519
+ if (!Array.isArray(chosen)) return fail(ctx, {
1520
+ what: chosen.message,
1521
+ fix: `Pass ${cmd(t, cliListExample(ctx))} or leave it out.`,
1522
+ ...chosen.suggestion ? { didYouMean: chosen.suggestion } : {},
1523
+ exit: 2,
1524
+ ref: "e_usage"
1525
+ });
1526
+ const found = await detectAll(ctx, chosen);
1527
+ printDetections(ctx, found);
1528
+ const installed = found.filter((f) => f.detection.installed);
1529
+ if (installed.length === 0) return fail(ctx, {
1530
+ what: "No supported AI tool was found",
1531
+ detail: [`Looked for ${chosen.map((a) => a.displayName).join(", ")} on PATH.`],
1532
+ fix: `Install one of them, then run conveno ${name} again.`,
1533
+ exit: 1,
1534
+ ref: "e_no_cli"
1535
+ });
1536
+ const accepted = /* @__PURE__ */ new Set();
1537
+ const acceptRaw = typeof values.accept === "string" ? values.accept : void 0;
1538
+ if (acceptRaw !== void 0) {
1539
+ const known = new Set(ctx.adapters.flatMap((a) => (a.optional ?? []).map((o) => o.id)));
1540
+ for (const id of acceptRaw.split(/[\s,]+/).filter(Boolean)) {
1541
+ if (!known.has(id)) return fail(ctx, {
1542
+ what: `Unknown option "${id}" for --accept`,
1543
+ detail: [known.size > 0 ? `Known: ${[...known].join(", ")}.` : "There are none."],
1544
+ fix: `Run ${cmd(t, `conveno ${name} --help`)} to see the options.`,
1545
+ exit: 2,
1546
+ ref: "e_usage"
1547
+ });
1548
+ accepted.add(id);
1549
+ }
1550
+ }
1551
+ const pending = await pendingOptions(ctx, installed.map((f) => f.adapter));
1552
+ const dryRun = Boolean(values["dry-run"]);
1553
+ for (const o of pending) {
1554
+ if (accepted.has(o.id)) continue;
1555
+ if (dryRun || values.yes === true || !ctx.interactive) {
1556
+ if (acceptRaw === void 0 && o.defaultYes) accepted.add(o.id);
1557
+ continue;
1558
+ }
1559
+ if (await ctx.confirm(o.question, o.defaultYes)) accepted.add(o.id);
1560
+ }
1561
+ const { items, failures } = await collectPlans(ctx, installed, "plan", void 0, [...accepted]);
1562
+ if (failures.length > 0) {
1563
+ reportFailures(ctx, failures, `conveno ${name} --cli <others>`);
1564
+ return 1;
1565
+ }
1566
+ const adapters = installed.map((f) => f.adapter);
1567
+ const applying = /* @__PURE__ */ new Set([...accepted, ...dryRun ? [] : await renewedApprovals(ctx, adapters, items)]);
1568
+ const extras = [];
1569
+ if (dryRun) for (const o of pending) {
1570
+ if (accepted.has(o.id)) continue;
1571
+ const more = extraChanges(items, (await collectPlans(ctx, installed, "plan", void 0, [...accepted, o.id])).items);
1572
+ if (more.length > 0) extras.push({
1573
+ option: o,
1574
+ items: more
1575
+ });
1576
+ }
1577
+ if (items.length === 0 && extras.length === 0) {
1578
+ ctx.out(`${t.status("ok")} Conveno is already set up for ${installed.map((f) => f.adapter.cli).join(", ")}. Nothing to change.\n`);
1579
+ if (!dryRun) await approveTools(ctx, installed, accepted, /* @__PURE__ */ new Set());
1580
+ outcome.offer = installed.map((f) => f.adapter);
1581
+ return 0;
1582
+ }
1583
+ if (dryRun) {
1584
+ const files = new Set(items.map((i) => i.change.path)).size;
1585
+ const { notes } = await approvalWrites(ctx, installed.map((f) => f.adapter), applying, items);
1586
+ ctx.out(`${t.bold(`Conveno would change ${plural(files, "file")}.`)}${notes.length > 0 ? "" : " Nothing else is touched."}\n\n`);
1587
+ presentChanges(ctx, items);
1588
+ for (const n of notes) ctx.out(` ${n}\n\n`);
1589
+ for (const x of extras) {
1590
+ ctx.out(`${t.bold(x.option.question)}\n ${t.paint("quiet", `Not turned on. With --accept ${x.option.id} Conveno would also change:`)}\n\n`);
1591
+ presentChanges(ctx, x.items);
1592
+ }
1593
+ ctx.out(`${t.status("info")} Dry run: nothing was written. Run ${cmd(t, `conveno ${name}`)} to apply.\n`);
1594
+ return 0;
1595
+ }
1596
+ const writes = await approvalWrites(ctx, adapters, applying, items);
1597
+ const result = await confirmAndApply(ctx, items, {
1598
+ yes: values.yes === true,
1599
+ verb: "Apply",
1600
+ rerun: `conveno ${name}`,
1601
+ notes: writes.notes,
1602
+ backups: writes.backups
1603
+ });
1604
+ if ("exit" in result) return result.exit;
1605
+ const byCli = /* @__PURE__ */ new Map();
1606
+ for (const h of result.applied.how) byCli.set(h.cli, [...byCli.get(h.cli) ?? [], h.via]);
1607
+ const rows = [...byCli].map(([cli, vias]) => [` ${t.status("ok")} ${cli}`, vias.every((v) => v === "command") ? "set up with its own command" : "configured"]);
1608
+ ctx.out(`${columns(rows).join("\n")}\n\n`);
1609
+ ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
1610
+ ctx.out(` Backups are in ${tilde(result.applied.backupDir, ctx.home)}.\n`);
1611
+ ctx.out(" Restart open sessions so they pick up Conveno.\n");
1612
+ const approved = await approveTools(ctx, installed, applying, new Set(byCli.keys()), result.applied.backupDir);
1613
+ if (byCli.has("codex") && !approved.has("codex")) ctx.out(`${t.status("info")} ${CODEX_NOTE}\n`);
1614
+ if (byCli.has("cursor")) ctx.out(`${t.status("info")} ${CURSOR_NOTE}\n`);
1615
+ ctx.out(` Next: ${cmd(t, "conveno status")} lists your sessions.\n`);
1616
+ outcome.offer = installed.map((f) => f.adapter);
1617
+ return 0;
1618
+ }
1619
+ /**
1620
+ * Runs the follow-up of the options answered yes and says what it did. Returns the tools whose
1621
+ * first-run approvals are now in place among `touched`, so their note is left out.
1622
+ */
1623
+ async function approveTools(ctx, installed, accepted, touched, backupDir) {
1624
+ const t = ctx.theme;
1625
+ const adapters = installed.map((f) => f.adapter);
1626
+ const { done, problems } = await applyOptions(ctx, adapters, accepted);
1627
+ if (backupDir && done.length > 0) {
1628
+ const env = adapterEnv(ctx);
1629
+ const ids = new Set(done.map((d) => d.id));
1630
+ await refreshManifest(backupDir, adapters.flatMap((a) => (a.optional ?? []).flatMap((o) => ids.has(o.id) && o.applyWrites ? o.applyWrites(env).paths : [])));
1631
+ }
1632
+ for (const d of done) {
1633
+ const name = adapters.find((a) => a.cli === d.cli)?.displayName ?? d.cli;
1634
+ ctx.out(`${t.status("ok")} Approved Conveno in ${name}.\n`);
1635
+ }
1636
+ for (const p of problems) ctx.out(`${t.status("info")} ${p}\n`);
1637
+ const approved = /* @__PURE__ */ new Set();
1638
+ for (const a of adapters) {
1639
+ if (!touched.has(a.cli)) continue;
1640
+ if (await approvedBySetup(ctx, a) === true) approved.add(a.cli);
1641
+ }
1642
+ return approved;
1643
+ }
1644
+ /**
1645
+ * `conveno setup`. In a terminal with no --yes it opens the onboarding in the app. Anywhere else
1646
+ * it does what `conveno init` does, and also saves --lead.
1647
+ */
1648
+ async function runSetup(ctx, argv) {
1649
+ const spec = COMMANDS.find((c) => c.name === "setup");
1650
+ if (!spec) return 2;
1651
+ const parsed = parseFlags(ctx, spec, argv);
1652
+ if (typeof parsed === "number") return parsed;
1653
+ const v = parsed.values;
1654
+ if (ctx.interactive && v.yes !== true && v["dry-run"] !== true) return (await import("./run-eCXO1SyO.js")).runTui(ctx, { start: "setup" });
1655
+ return runInit(ctx, argv, "setup");
1656
+ }
1657
+ // src/doctor.ts
1658
+ /** What the plan says about one part: nothing to do, an addition, or an update to what is there. */
1659
+ function partState(changes, component) {
1660
+ const mine = changes.filter((c) => c.component === component);
1661
+ if (mine.length === 0) return "ok";
1662
+ return mine.some((c) => c.kind === "add") ? "missing" : "outdated";
1663
+ }
1664
+ /** Time allowed for the one process-table query. */
1665
+ const ANCESTRY_TIMEOUT_MS = 5e3;
1666
+ const tierWord = (t) => t === "next_turn" ? "next turn" : t;
1667
+ const hasAny = (c) => c !== void 0 && (c.nextTurn || c.endOfTurn || c.idleWake);
1668
+ /**
1669
+ * The delivery tiers that work right now for one CLI: what the adapter can do for this version,
1670
+ * once its hooks (or plugin) are in place. Without them only the inbox tool is left.
1671
+ */
1672
+ function activeTiers(row) {
1673
+ const base = row.adapter.delivery?.(row.detection);
1674
+ const caps = base && row.idleWake !== void 0 ? {
1675
+ ...base,
1676
+ idleWake: base.idleWake && row.idleWake
1677
+ } : base;
1678
+ if (!caps) return row.adapter.deliveryTier === "inbox" || row.hooks === "ok" ? [tierWord(row.adapter.deliveryTier)] : ["inbox"];
1679
+ if (!hasAny(caps) || row.hooks !== "ok") return ["inbox"];
1680
+ return [
1681
+ ...caps.nextTurn ? ["next turn"] : [],
1682
+ ...caps.endOfTurn ? ["end of turn"] : [],
1683
+ ...caps.idleWake ? ["idle wake"] : []
1684
+ ];
1685
+ }
1686
+ async function inspect(ctx, adapter) {
1687
+ const env = adapterEnv(ctx);
1688
+ let detection;
1689
+ try {
1690
+ detection = await adapter.detect(env);
1691
+ } catch {
1692
+ detection = {
1693
+ installed: false,
1694
+ configPaths: []
1695
+ };
1696
+ }
1697
+ if (!detection.installed) return {
1698
+ adapter,
1699
+ detection,
1700
+ mcp: null,
1701
+ hooks: null
1702
+ };
1703
+ const hasHooks = adapter.deliveryTier !== "inbox" || hasAny(adapter.delivery?.(detection));
1704
+ let idleWake;
1705
+ const wakeOptions = (adapter.optional ?? []).filter((o) => o.approval !== true);
1706
+ if (wakeOptions.length > 0) {
1707
+ idleWake = true;
1708
+ for (const o of wakeOptions) if (!await o.enabled(env).catch(() => false)) idleWake = false;
1709
+ }
1710
+ const adapterNotes = await adapter.doctorNotes?.(env).catch(() => []);
1711
+ try {
1712
+ const changes = await adapter.plan(env);
1713
+ return {
1714
+ adapter,
1715
+ detection,
1716
+ mcp: partState(changes, "mcp"),
1717
+ hooks: hasHooks ? partState(changes, "hooks") : null,
1718
+ changes,
1719
+ ...idleWake === void 0 ? {} : { idleWake },
1720
+ ...adapterNotes?.length ? { adapterNotes } : {}
1721
+ };
1722
+ } catch (e) {
1723
+ return {
1724
+ adapter,
1725
+ detection,
1726
+ mcp: "missing",
1727
+ hooks: hasHooks ? "missing" : null,
1728
+ planError: plainError(e),
1729
+ ...idleWake === void 0 ? {} : { idleWake },
1730
+ ...adapterNotes?.length ? { adapterNotes } : {}
1731
+ };
1732
+ }
1733
+ }
1734
+ /**
1735
+ * A note for a CLI outside the tested range. Older than the minimum is a problem. Past the tested
1736
+ * major or minor version is a warning. A patch release ahead gets only the short table note: CLIs
1737
+ * like Claude Code ship patches almost daily, and they rarely change config or hook formats.
1738
+ */
1739
+ function versionBlock(t, adapter, version, status) {
1740
+ const name = adapter.displayName;
1741
+ if (status.kind === "older") return {
1742
+ problem: true,
1743
+ text: errorBlock(t, {
1744
+ what: `${name} ${version} is older than Conveno supports`,
1745
+ detail: [`Conveno needs ${name} ${status.minimum} or newer.`],
1746
+ fix: `Upgrade ${name}, then run ${cmd(t, "conveno doctor")} again.`,
1747
+ exit: 1,
1748
+ ref: "e_cli_old"
1749
+ })
1750
+ };
1751
+ if (status.kind === "newer" && status.minor) return {
1752
+ problem: false,
1753
+ text: warnBlock(t, `${name} ${version} is newer than the ${status.verified} Conveno was tested with.`, "Nothing to do unless messages stop arriving. Please report it at https://github.com/0xPixelNinja/conveno/issues if something breaks.", "CLI vendors change config and hook formats often. A nightly check tests the newest releases and raises the tested version when they pass.")
1754
+ };
1755
+ }
1756
+ async function runDoctor(ctx, argv = []) {
1757
+ const t = ctx.theme;
1758
+ const spec = COMMANDS.find((c) => c.name === "doctor");
1759
+ let adapters = ctx.adapters;
1760
+ if (spec) {
1761
+ const parsed = parseFlags(ctx, spec, argv);
1762
+ if (typeof parsed === "number") return parsed;
1763
+ const chosen = parseCliList(typeof parsed.values.cli === "string" ? parsed.values.cli : void 0, ctx);
1764
+ if (!Array.isArray(chosen)) return fail(ctx, {
1765
+ what: chosen.message,
1766
+ fix: `Pass ${cmd(t, cliListExample(ctx))} or leave it out.`,
1767
+ ...chosen.suggestion ? { didYouMean: chosen.suggestion } : {},
1768
+ exit: 2,
1769
+ ref: "e_usage"
1770
+ });
1771
+ adapters = chosen;
1772
+ }
1773
+ let ok = 0;
1774
+ let warnings = 0;
1775
+ let problems = 0;
1776
+ const notes = [];
1777
+ let daemonLine;
1778
+ try {
1779
+ const client = await ctx.connect(connectOpts(ctx, false));
1780
+ try {
1781
+ const { sessions } = await client["session.list"]({});
1782
+ daemonLine = [` ${t.status("ok")} daemon`, `running, ${plural(sessions.length, "session")}`];
1783
+ ok++;
1784
+ } finally {
1785
+ await client.close().catch(() => void 0);
1786
+ }
1787
+ } catch (e) {
1788
+ const problem = daemonProblem(t, e);
1789
+ if (problem.notRunning) {
1790
+ daemonLine = [` ${t.status("warn")} daemon`, "not running"];
1791
+ warnings++;
1792
+ notes.push(warnBlock(t, "Conveno's background service is not running.", problem.fix, problem.why));
1793
+ } else {
1794
+ daemonLine = [` ${t.status("error")} daemon`, "cannot be reached"];
1795
+ problems++;
1796
+ notes.push(errorBlock(t, {
1797
+ what: "Conveno's background service cannot be reached",
1798
+ detail: [problem.why],
1799
+ fix: problem.fix,
1800
+ exit: 1,
1801
+ ref: "e_daemon"
1802
+ }));
1803
+ }
1804
+ }
1805
+ ctx.out(`${columns([daemonLine]).join("\n")}\n\n`);
1806
+ if (!(await ctx.ancestry(ANCESTRY_TIMEOUT_MS)).complete) {
1807
+ warnings++;
1808
+ notes.push(warnBlock(t, "Process ancestry is unavailable.", `Run ${cmd(t, "conveno doctor")} from a normal desktop session, or allow this user to read the process list. Messages still reach the inbox tool either way.`, ctx.platform === "win32" ? "Windows refused the process list (WMI denies it to non-admin remote logons such as SSH). A hook can then only match a session whose CLI is its direct parent, so next-turn delivery can miss sessions started through a launcher such as conveno.cmd." : "The process list could not be read. A hook can then only match a session whose CLI is its direct parent, so next-turn delivery can miss sessions started through a launcher or a shell."));
1809
+ }
1810
+ const rows = await Promise.all(adapters.map((a) => inspect(ctx, a)));
1811
+ const q = (w) => t.paint("quiet", w);
1812
+ const table = [[
1813
+ ` ${q("CLI")}`,
1814
+ q("NAME"),
1815
+ q("VERSION"),
1816
+ q("MCP"),
1817
+ q("HOOKS"),
1818
+ q("DELIVERY"),
1819
+ q("NOTE")
1820
+ ]];
1821
+ const yesNo = (v) => v === null ? q("n/a") : v === "ok" ? "yes" : t.paint("warn", v === "missing" ? "not configured" : "needs update");
1822
+ for (const r of rows) {
1823
+ const { adapter, detection } = r;
1824
+ if (!detection.installed) {
1825
+ table.push([
1826
+ ` ${t.glyph("offline")} ${adapter.cli}`,
1827
+ adapter.displayName,
1828
+ "",
1829
+ "",
1830
+ "",
1831
+ "",
1832
+ q("not found on PATH")
1833
+ ]);
1834
+ continue;
1835
+ }
1836
+ const good = r.mcp === "ok" && (r.hooks === null || r.hooks === "ok") && !r.planError;
1837
+ const compat = compatStatus(adapter.cli, detection.version, ctx.compat);
1838
+ const tiers = activeTiers(r);
1839
+ let note = tiers.includes("idle wake") ? "wakes idle sessions" : tiers.includes("end of turn") ? "wakes at the end of a turn, no idle wake" : tiers.includes("next turn") ? "delivered at the next prompt" : "read through the inbox tool";
1840
+ if (!good) note = r.planError ? "config could not be read" : r.mcp === "outdated" || r.hooks === "outdated" ? "needs an update" : "not fully configured";
1841
+ if (compat.kind === "older") note = `older than the minimum ${compat.minimum}`;
1842
+ else if (compat.kind === "newer" && good) note = `newer than tested (${compat.verified})`;
1843
+ const glyph = compat.kind === "older" ? t.status("error") : good && !(compat.kind === "newer" && compat.minor) ? t.status("ok") : t.status("warn");
1844
+ table.push([
1845
+ ` ${glyph} ${adapter.cli}`,
1846
+ adapter.displayName,
1847
+ detection.version ?? "",
1848
+ yesNo(r.mcp),
1849
+ yesNo(r.hooks),
1850
+ tiers.join(", "),
1851
+ q(note)
1852
+ ]);
1853
+ for (const line of r.adapterNotes ?? []) notes.push(`${q(`${adapter.displayName}:`)} ${line}`);
1854
+ if (r.planError) {
1855
+ problems++;
1856
+ notes.push(errorBlock(t, {
1857
+ what: `${adapter.displayName} config could not be read`,
1858
+ detail: [r.planError],
1859
+ fix: "Repair the file named above, then run conveno doctor again.",
1860
+ exit: 1,
1861
+ ref: "e_config"
1862
+ }));
1863
+ } else if (good) {
1864
+ if (compat.kind !== "older" && !(compat.kind === "newer" && compat.minor)) ok++;
1865
+ } else {
1866
+ warnings++;
1867
+ const named = [["the MCP server", r.mcp], ["the hooks", r.hooks]];
1868
+ const list = (state) => named.filter(([, s]) => s === state).map(([n]) => n).join(" and ");
1869
+ const missing = list("missing");
1870
+ const outdated = list("outdated");
1871
+ const fix = `Run ${cmd(t, "conveno init")}, then restart open ${adapter.displayName} sessions.`;
1872
+ notes.push(missing && outdated ? warnBlock(t, `${adapter.displayName} is missing ${missing} and needs an update to ${outdated}.`, fix) : missing ? warnBlock(t, `${adapter.displayName} is missing ${missing}.`, fix) : warnBlock(t, `${adapter.displayName} needs an update.`, fix, `Conveno's setup for ${outdated} is from an older version. ${cmd(t, "conveno init")} shows exactly which lines change.`));
1873
+ }
1874
+ const versionNote = versionBlock(t, adapter, detection.version, compat);
1875
+ if (versionNote) {
1876
+ notes.push(versionNote.text);
1877
+ if (versionNote.problem) problems++;
1878
+ else warnings++;
1879
+ }
1880
+ }
1881
+ ctx.out(`${columns(table).join("\n")}\n`);
1882
+ const acpLines = acpDoctorLines(ctx, rows.filter((r) => r.detection.installed).map((r) => r.adapter.cli));
1883
+ if (acpLines.length > 0) ctx.out(`${acpLines.join("\n")}\n`);
1884
+ if (!rows.some((r) => r.detection.installed)) {
1885
+ notes.push(warnBlock(t, "No supported AI coding CLI was found on PATH.", "Install Claude Code, Codex CLI or OpenCode, then run conveno init."));
1886
+ warnings++;
1887
+ }
1888
+ for (const n of notes) ctx.err(`\n${n.trimEnd()}\n`);
1889
+ ctx.out(`\n${ok} ok, ${plural(warnings, "warning")}, ${plural(problems, "problem")}\n`);
1890
+ return problems > 0 ? 1 : 0;
1891
+ }
1892
+ // src/uninstall.ts
1893
+ const NOTE = {
1894
+ restore: "restored byte for byte",
1895
+ remove: "removed, it did not exist before",
1896
+ edit: "edited since setup, so only Conveno's entries are removed",
1897
+ gone: "already gone, left as it is"
1898
+ };
1899
+ /** The "asked once" markers the Grok and Antigravity Stop hooks keep in the data folder. */
1900
+ async function removeAskedMarkers(ctx) {
1901
+ for (const folder of ["grok-watch-asked", "agy-relay-asked"]) await rm(join(ctx.dataDir, folder), {
1902
+ recursive: true,
1903
+ force: true
1904
+ }).catch(() => void 0);
1905
+ }
1906
+ /**
1907
+ * The files as init found them, from the backups: their text, or null when they did not exist. A
1908
+ * backup that cannot be read leaves its file out, and the adapter then treats what it finds as
1909
+ * Conveno's own.
1910
+ */
1911
+ async function baselineOf(dir, entries) {
1912
+ const out = /* @__PURE__ */ new Map();
1913
+ for (const e of entries) if (e.backup === null) out.set(e.path, null);
1914
+ else try {
1915
+ out.set(e.path, await readFile(join(dir, e.backup), "utf8"));
1916
+ } catch {}
1917
+ return out;
1918
+ }
1919
+ /** Remove Conveno's own entries from files that changed since init, through each adapter. */
1920
+ async function removeOwnEntries(ctx, dir, entries) {
1921
+ if (entries.length === 0) return {
1922
+ edited: [],
1923
+ failures: []
1924
+ };
1925
+ const clis = new Set(entries.map((e) => e.cli));
1926
+ const { items, failures } = await collectPlans(ctx, (await detectAll(ctx)).filter((f) => clis.has(f.adapter.cli)), "uninstallPlan", await baselineOf(dir, entries));
1927
+ const wanted = new Set(entries.map((e) => e.path));
1928
+ const mine = items.filter((i) => wanted.has(i.change.path));
1929
+ if (mine.length > 0) await applyChanges(ctx, mine, { markRestored: true });
1930
+ return {
1931
+ edited: mine.map((i) => i.change.path),
1932
+ failures
1933
+ };
1934
+ }
1935
+ async function restoreAll(ctx, manifests) {
1936
+ const restored = [];
1937
+ const edited = [];
1938
+ const untouched = [];
1939
+ for (const found of manifests) {
1940
+ const needEdit = [];
1941
+ for (const entry of found.manifest.entries) {
1942
+ const action = await restoreEntry(found.dir, entry);
1943
+ if (action === "edit") needEdit.push(entry);
1944
+ else if (action === "gone") untouched.push(entry.path);
1945
+ else restored.push(entry.path);
1946
+ }
1947
+ const r = await removeOwnEntries(ctx, found.dir, needEdit);
1948
+ if (r.failures.length > 0) {
1949
+ reportFailures(ctx, r.failures, "conveno uninstall");
1950
+ throw new Error("A config file could not be read, so it was left as it is.");
1951
+ }
1952
+ edited.push(...r.edited);
1953
+ for (const e of needEdit) if (!r.edited.includes(e.path)) untouched.push(e.path);
1954
+ await markRestored(ctx, found);
1955
+ }
1956
+ return {
1957
+ restored,
1958
+ edited,
1959
+ untouched
1960
+ };
1961
+ }
1962
+ async function runUninstall(ctx, argv) {
1963
+ const t = ctx.theme;
1964
+ const started = ctx.now();
1965
+ const spec = COMMANDS.find((c) => c.name === "uninstall");
1966
+ if (!spec) return 2;
1967
+ const parsed = parseFlags(ctx, spec, argv);
1968
+ if (typeof parsed === "number") return parsed;
1969
+ const yes = parsed.values.yes === true;
1970
+ const manifests = await listManifests(ctx).catch(() => []);
1971
+ if (manifests.length > 0) {
1972
+ const rows = await previewRestore(manifests);
1973
+ const made = manifests.map((m) => localStamp(m.manifest.createdAt));
1974
+ ctx.out(`${t.bold(`Conveno will undo ${plural(manifests.length, "install")}`)}, made ${made.join(", ")} (local time).\n\n`);
1975
+ ctx.out(`${columns(rows.map((r) => [` ${tilde(r.entry.path, ctx.home)}`, t.paint("quiet", NOTE[r.action])])).join("\n")}\n\n`);
1976
+ if (!yes) {
1977
+ if (!ctx.interactive) return fail(ctx, {
1978
+ what: "Needs a terminal to confirm",
1979
+ detail: ["No files were changed."],
1980
+ fix: `Run ${cmd(t, "conveno uninstall --yes")} to undo the changes listed above.`,
1981
+ exit: 2,
1982
+ ref: "e_no_tty"
1983
+ });
1984
+ if (!await ctx.confirm("Undo these changes?", false)) {
1985
+ ctx.out(`${t.status("info")} Nothing was changed.\n`);
1986
+ return 0;
1987
+ }
1988
+ }
1989
+ const stopped = await stopDaemonIfRunning(ctx);
1990
+ if (stopped !== 0) return stopped;
1991
+ let result;
1992
+ try {
1993
+ result = await restoreAll(ctx, manifests);
1994
+ } catch (e) {
1995
+ if (e instanceof StaleError) return staleFailure(ctx, e, "conveno uninstall");
1996
+ return fail(ctx, {
1997
+ what: "Could not restore a file",
1998
+ detail: [plainError(e), `The backups are still in ${tilde(manifests[0]?.dir ?? ctx.dataDir, ctx.home)} and the other backup folders next to it.`],
1999
+ fix: "Fix the problem above, then run conveno uninstall again.",
2000
+ exit: 1,
2001
+ ref: "e_restore"
2002
+ });
2003
+ }
2004
+ await removeAskedMarkers(ctx);
2005
+ ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
2006
+ ctx.out(` Restored ${plural(result.restored.length, "file")} to how they were before setup.\n`);
2007
+ if (result.edited.length > 0) ctx.out(` Edited, not restored, because they changed since setup: ${result.edited.map((p) => tilde(p, ctx.home)).join(", ")}. Only Conveno's entries were removed.\n`);
2008
+ ctx.out(" Restart open sessions to drop Conveno.\n");
2009
+ return 0;
2010
+ }
2011
+ const { items, failures } = await collectPlans(ctx, await detectAll(ctx), "uninstallPlan");
2012
+ if (failures.length > 0) {
2013
+ reportFailures(ctx, failures, "conveno uninstall");
2014
+ return 1;
2015
+ }
2016
+ if (items.length === 0) {
2017
+ ctx.out(`${t.status("ok")} Nothing to remove. No Conveno entries were found in any supported CLI.\n`);
2018
+ return 0;
2019
+ }
2020
+ ctx.out(`${t.status("info")} No install backup found, so Conveno will remove only its own entries.\n\n`);
2021
+ const result = await confirmAndApply(ctx, items, {
2022
+ yes,
2023
+ verb: "Remove",
2024
+ rerun: "conveno uninstall",
2025
+ markRestored: true,
2026
+ beforeApply: () => stopDaemonIfRunning(ctx)
2027
+ });
2028
+ if ("exit" in result) return result.exit;
2029
+ await removeAskedMarkers(ctx);
2030
+ ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
2031
+ ctx.out(" Removed the Conveno entries. Restart open sessions to drop Conveno.\n");
2032
+ return 0;
2033
+ }
2034
+ export { openInBrowser as C, showCode as D, runLogout as E, stopDaemonIfRunning as S, runLogin as T, unifiedDiff as _, applyOptions as a, runRelay as b, collectPlans as c, refreshManifest as d, renewedApprovals as f, applyChanges as g, StaleError as h, runDoctor as i, detectAll as l, runSetup as m, inspect as n, approvalWrites as o, runInit as p, partState as r, approvedBySetup as s, runUninstall as t, pendingOptions as u, PAIR_TIMEOUT_MS as v, runAccount as w, runDaemon as x, runDevices as y };