@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.
@@ -1,12 +1,12 @@
1
- import { At as readSettings, Bt as runLaunchFile, Cn as SessionNameInput, D as compatStatus, Dn as TicketId, G as fetchAccountStatus, It as requestDeviceCode, K as findOnPath, Lt as resolveAcpProgram, N as dataPaths, Nt as realSpawnDeps, O as completeLogin, Sn as SessionName, St as pollDeviceCode, Tt as readAccountTokens, Un as sanitizeLine, Wt as spawnSession, an as AUTO_LIMIT_MAX, bt as pinnedAdapter, c as SPAWN_CLIS, f as acpOverrideVar, g as adapterNpxCommand, gt as pauseLabel, h as adapterInstallCommand, in as writeSettings, l as SPAWN_TABLE, n as AccountError, on as CLI_KINDS, r as ConvenoError, st as logoutAccount, u as SpawnError, wn as SessionNamePattern, xn as SessionId, yn as RpcErrorCode } from "./dist-_qrCNXUP.js";
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";
2
7
  import { spawn } from "node:child_process";
3
- import { a as closest, c as errorBlock, d as plainError, f as plural, h as warnBlock, i as parseFlags, l as fail, m as tilde, n as COMMAND_NAMES, o as cmd, p as seconds, r as commandHelp, s as columns, t as COMMANDS, u as localStamp } from "./args-DHkLY6_f.js";
4
- import { n as adapterEnv, r as connectOpts, t as runHook } from "./hook-bfp9_AVT.js";
5
- import { t as ClientError } from "./dist-DsRTUePN.js";
6
- import { access, chmod, mkdir, open, readFile, readdir, realpath, rename as rename$1, rm, stat, writeFile } from "node:fs/promises";
7
- import { basename, dirname, join, resolve } from "node:path";
8
+ import { access, chmod, mkdir, open, readFile, readdir, realpath, rename as rename$1, rm, rmdir, stat, writeFile } from "node:fs/promises";
8
9
  import { createHash, randomBytes } from "node:crypto";
9
- import { readFileSync } from "node:fs";
10
10
  // src/account.ts
11
11
  const accountIo = (ctx, io) => ({
12
12
  apiBase: ctx.env.CONVENO_API_URL || "https://api.conveno.dev",
@@ -140,340 +140,6 @@ async function runAccount(ctx, argv, io = {}) {
140
140
  return accountFailure(ctx, e, "Could not read your account");
141
141
  }
142
142
  }
143
- // src/daemonError.ts
144
- /**
145
- * Explain a failed connection to the daemon, with a fix that fits the cause. `start` is the command
146
- * that fixes a daemon that is merely not running.
147
- */
148
- function daemonProblem(t, e) {
149
- const why = plainError(e);
150
- const kind = e instanceof ClientError ? e.kind : void 0;
151
- const start = cmd(t, "conveno daemon start");
152
- const status = cmd(t, "conveno daemon status");
153
- switch (kind) {
154
- case "socket_path_too_long": return {
155
- why,
156
- fix: `Set ${cmd(t, "XDG_RUNTIME_DIR")} to a shorter directory, then run ${start}. Use the same value everywhere you run Conveno and your AI CLIs.`,
157
- notRunning: false
158
- };
159
- case "permission": return {
160
- why,
161
- fix: `Check who owns the socket named above. If it is not yours, remove it, then run ${start}.`,
162
- notRunning: false
163
- };
164
- case "not_daemon": return {
165
- why,
166
- fix: `Stop the process that owns the socket, or remove the socket, then run ${start}.`,
167
- notRunning: false
168
- };
169
- case "token_empty": return {
170
- why,
171
- fix: `Run ${cmd(t, "conveno daemon stop")}, then ${start}.`,
172
- notRunning: false
173
- };
174
- case "daemon_missing": return {
175
- why,
176
- fix: `Reinstall Conveno (${cmd(t, "npm install -g @conveno/cli")}), then run ${start}.`,
177
- notRunning: false
178
- };
179
- case "start_timeout": return {
180
- why,
181
- fix: `Run ${status} to see whether it came up, or ${cmd(t, "conveno doctor")} to check the install.`,
182
- notRunning: false
183
- };
184
- case "start_exited": return {
185
- why,
186
- fix: `Fix what its output above shows, then run ${start}. If it is unclear, report it with that output.`,
187
- notRunning: false
188
- };
189
- case "connection": return {
190
- why,
191
- fix: `Run ${status}, then try again.`,
192
- notRunning: false
193
- };
194
- case "no_daemon": return {
195
- why,
196
- fix: `Run ${start}. It also starts when a CLI opens the Conveno MCP server.`,
197
- notRunning: true
198
- };
199
- default: return {
200
- why,
201
- fix: `Run ${cmd(t, "conveno doctor")} to check the install, then try again.`,
202
- notRunning: false
203
- };
204
- }
205
- }
206
- // src/status.ts
207
- const CLI_SHORT = {
208
- claude: "cl",
209
- codex: "cx",
210
- opencode: "oc",
211
- antigravity: "ag",
212
- cursor: "cu",
213
- copilot: "cp",
214
- grok: "gk"
215
- };
216
- const pad2 = (n) => String(n).padStart(2, "0");
217
- /** Local `HH:MM:SS`, with the date in front when it is not today. */
218
- function stamp(iso, now) {
219
- const d = new Date(iso);
220
- const time = `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
221
- const day = `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
222
- return day === `${now.getFullYear()}-${pad2(now.getMonth() + 1)}-${pad2(now.getDate())}` ? time : `${day} ${time}`;
223
- }
224
- function tierText(theme, tier) {
225
- switch (tier) {
226
- case "live": return theme.paint("entry", "live");
227
- case "next_turn": return "next turn";
228
- case "acp": return "ACP";
229
- case "inbox": return theme.paint("quiet", "inbox");
230
- }
231
- }
232
- function stateCell(theme, s) {
233
- if (s.status === "offline") return {
234
- glyph: theme.status("offline"),
235
- word: "offline"
236
- };
237
- if (s.status === "waiting_on_question") return {
238
- glyph: theme.status("waiting"),
239
- word: "waiting"
240
- };
241
- if (s.isOrchestrator) return {
242
- glyph: theme.status("orchestrator"),
243
- word: s.status
244
- };
245
- if (s.status === "busy") return {
246
- glyph: theme.glyph("busy"),
247
- word: "busy"
248
- };
249
- return {
250
- glyph: theme.status("idle"),
251
- word: "idle"
252
- };
253
- }
254
- /** `on`, `off` or `paused by limit`. */
255
- function autoText(theme, s) {
256
- if (s.auto === true && s.autoPausedBy !== void 0) return theme.paint("warn", pauseLabel(s.autoPausedBy));
257
- return s.auto === true ? "on" : theme.paint("quiet", "off");
258
- }
259
- /** Sessions grouped by repository, the way brand/components/terminal.md lays them out. */
260
- function renderSessions(ctx, sessions) {
261
- const t = ctx.theme;
262
- const now = ctx.now();
263
- const groups = /* @__PURE__ */ new Map();
264
- const keyOf = (s) => s.remote ? `${s.repo?.root ?? s.cwd}\u0000${s.deviceName ?? ""}` : s.repo?.root ?? s.cwd;
265
- for (const s of sessions) {
266
- const key = keyOf(s);
267
- groups.set(key, [...groups.get(key) ?? [], s]);
268
- }
269
- const blocks = [];
270
- for (const key of [...groups.keys()].sort()) {
271
- const list = (groups.get(key) ?? []).sort((a, b) => a.name.localeCompare(b.name));
272
- const q = (w) => t.paint("quiet", w);
273
- const head = [
274
- ` ${q("SESSION")}`,
275
- q("CLI"),
276
- q("TIER"),
277
- q("STATE"),
278
- q("AUTO"),
279
- q("UNREAD"),
280
- q("LAST SEEN")
281
- ];
282
- const rows = list.map((s) => {
283
- const st = stateCell(t, s);
284
- return [
285
- `${st.glyph} ${t.bold(s.name)}`,
286
- CLI_SHORT[s.cli] ?? s.cli,
287
- tierText(t, s.deliveryTier),
288
- st.word,
289
- autoText(t, s),
290
- s.unreadCount ? String(s.unreadCount) : q("0"),
291
- t.paint("quiet", stamp(s.lastSeenAt, now)),
292
- ...s.isOrchestrator ? [t.paint("entry", "orchestrator")] : [],
293
- ...s.spawned || s.spawnedBy ? [t.paint("quiet", "spawned")] : []
294
- ];
295
- });
296
- const [headLine, ...rowLines] = columns([head, ...rows]);
297
- const [path, device] = key.split("\0");
298
- const title = device === void 0 ? t.bold(tilde(key, ctx.home)) : `${t.bold(path ?? "")} ${t.paint("quiet", `on ${device || "another device"}`)}`;
299
- blocks.push([
300
- ` ${title}`,
301
- ` ${headLine}`,
302
- ...rowLines.map((l) => ` ${l}`)
303
- ].join("\n"));
304
- }
305
- return blocks.join("\n\n");
306
- }
307
- /** The relay part of the status header line. */
308
- function relaySummary(r) {
309
- if (!r) return "off (local only)";
310
- switch (r.state) {
311
- case "connected": {
312
- const online = r.peers.filter((p) => p.online).length;
313
- return `connected (${plural(online, "other device")} online)`;
314
- }
315
- case "connecting": return "connecting";
316
- case "disconnected": return "disconnected, retrying";
317
- case "revoked": return "off (this device was revoked)";
318
- case "unpaired": return "off (no paired devices)";
319
- default: return "off (local only)";
320
- }
321
- }
322
- async function runStatus(ctx, argv = []) {
323
- const t = ctx.theme;
324
- const spec = COMMANDS.find((c) => c.name === "status");
325
- let all = false;
326
- if (spec) {
327
- const parsed = parseFlags(ctx, spec, argv);
328
- if (typeof parsed === "number") return parsed;
329
- all = parsed.values.all === true;
330
- }
331
- let client;
332
- try {
333
- client = await ctx.connect(connectOpts(ctx, false));
334
- } catch (e) {
335
- const problem = daemonProblem(t, e);
336
- ctx.err(problem.notRunning ? warnBlock(t, "The Conveno daemon is not running.", `Run ${cmd(t, "conveno daemon start")}, or open a supported CLI after ${cmd(t, "conveno init")}.`, "Sessions are listed by the daemon, and nothing is listening on its socket.") : warnBlock(t, "The Conveno daemon cannot be reached.", problem.fix, problem.why));
337
- return 0;
338
- }
339
- try {
340
- const everyone = (await client["session.list"]({ includeOffline: true })).sessions;
341
- const sessions = all ? everyone : everyone.filter((s) => s.status !== "offline");
342
- const hidden = everyone.length - sessions.length;
343
- const repos = new Set(sessions.map((s) => s.repo?.root ?? s.cwd)).size;
344
- const hint = hidden > 0 ? `${hidden} offline hidden, ${cmd(t, "conveno status --all")} shows them` : "";
345
- const relay = await (async () => client["relay.status"]({}))().catch(() => void 0);
346
- ctx.out(`daemon up ${t.status("bullet")} relay: ${relaySummary(relay)} ${t.status("bullet")} ${plural(sessions.length, "session")}\n`);
347
- if (sessions.length === 0) {
348
- ctx.out(hidden > 0 ? `\nNo sessions online. ${hint}.\n` : `\nNo sessions yet. Open a supported CLI after ${cmd(t, "conveno init")} and it appears here.\n`);
349
- return 0;
350
- }
351
- ctx.out(`\n${renderSessions(ctx, sessions)}\n\n`);
352
- ctx.out(`${plural(sessions.length, "session")} in ${plural(repos, "repo")}${hint ? ` ${t.status("bullet")} ${hint}` : ""}\n`);
353
- const paused = sessions.filter((s) => s.auto === true && s.autoPausedBy !== void 0);
354
- for (const s of paused) ctx.err(warnBlock(t, `Auto mode for ${s.name} is paused by limit.`, `Run ${cmd(t, `conveno auto resume ${s.name}`)}, or let the orchestrator resume it (once per hour).`, "It took as many automatic turns as its limit allows in the window, or a message reached it after that many automatic turns with no person in between (sessions answering each other). Its messages still arrive at the next prompt."));
355
- const open = await client["ticket.list"]({
356
- status: "open",
357
- limit: 1
358
- }).catch(() => void 0);
359
- if (open && open.openCount > 0) ctx.out(`${t.paint("entry", plural(open.openCount, "open ticket"))} waiting for an answer ${t.status("bullet")} ${cmd(t, "conveno tickets --open")}\n`);
360
- return 0;
361
- } finally {
362
- await client.close().catch(() => void 0);
363
- }
364
- }
365
- // src/auto.ts
366
- /** Time allowed for the process-table query that finds the session this command runs in. */
367
- const ANCESTRY_TIMEOUT_MS$1 = 5e3;
368
- /**
369
- * The session this command runs inside, when it is typed in a CLI's own shell (for example
370
- * `! conveno auto on` in Claude Code): the nearest ancestor that hosts exactly one session. A
371
- * command the user types may look past its first ancestor, because the user asked for it and is
372
- * told which session changed; hooks never do this.
373
- */
374
- async function enclosingSession(ctx, client) {
375
- const { pids } = await ctx.ancestry(ANCESTRY_TIMEOUT_MS$1);
376
- for (const pid of pids) {
377
- const { session } = await client["session.byHost"]({ pid });
378
- if (session) return session;
379
- }
380
- return null;
381
- }
382
- const isTarget = (s) => SessionName.safeParse(s).success || SessionId.safeParse(s).success;
383
- /** `conveno auto [on|off|resume|limit <n|default>] [<session>]`. */
384
- async function runAuto(ctx, argv) {
385
- const t = ctx.theme;
386
- const spec = COMMANDS.find((c) => c.name === "auto");
387
- if (!spec) return 2;
388
- const parsed = parseFlags(ctx, spec, argv);
389
- if (typeof parsed === "number") return parsed;
390
- const [mode, ...rest] = parsed.positionals;
391
- const usage = `Run ${cmd(t, "conveno auto --help")} to see the usage.`;
392
- const usageError = (what) => fail(ctx, {
393
- what,
394
- fix: usage,
395
- exit: 2,
396
- ref: "e_usage"
397
- });
398
- let change;
399
- let args = rest;
400
- switch (mode) {
401
- case void 0: break;
402
- case "on":
403
- case "off":
404
- change = { auto: mode === "on" };
405
- break;
406
- case "resume":
407
- change = { resume: true };
408
- break;
409
- case "limit": {
410
- const [value, ...after] = rest;
411
- if (value === void 0) return usageError("conveno auto limit needs a number or default");
412
- if (value === "default") change = { limit: null };
413
- else if (/^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 1e3) change = { limit: Number(value) };
414
- else return usageError(`"${value}" is not a limit from 1 to ${AUTO_LIMIT_MAX}, or default`);
415
- args = after;
416
- break;
417
- }
418
- default: return usageError(`Unexpected argument "${mode}" for conveno auto`);
419
- }
420
- const [target, ...extra] = args;
421
- if (extra.length > 0) return usageError(`Unexpected argument "${extra[0]}" for conveno auto`);
422
- if (target !== void 0 && !isTarget(target)) return fail(ctx, {
423
- what: `"${target}" is not a session name or id`,
424
- fix: `Run ${cmd(t, "conveno status")} to see the names.`,
425
- exit: 2,
426
- ref: "e_usage"
427
- });
428
- let client;
429
- try {
430
- client = await ctx.connect(connectOpts(ctx, false));
431
- } catch (e) {
432
- const problem = daemonProblem(t, e);
433
- return fail(ctx, {
434
- what: "The Conveno daemon cannot be reached",
435
- detail: [problem.why],
436
- fix: problem.fix,
437
- exit: 1,
438
- ref: "e_daemon"
439
- });
440
- }
441
- try {
442
- if (change === void 0) {
443
- const { sessions } = await client["session.list"]({});
444
- ctx.out(sessions.length === 0 ? "No sessions online.\n" : `${renderSessions(ctx, sessions)}\n`);
445
- return 0;
446
- }
447
- const session = target ?? (await enclosingSession(ctx, client))?.id;
448
- if (session === void 0) return fail(ctx, {
449
- what: "conveno auto needs a session",
450
- detail: ["This command does not run inside a session Conveno knows."],
451
- fix: `Name one, such as ${cmd(t, "conveno auto on api-worker")}. ${cmd(t, "conveno status")} lists the names.`,
452
- exit: 2,
453
- ref: "e_usage"
454
- });
455
- const s = (await client["session.setAuto"]({
456
- session,
457
- ...change
458
- })).session;
459
- ctx.out(`Auto mode for ${t.bold(s.name)} is ${autoText(t, s)}.\n`);
460
- if (change.limit !== void 0) ctx.out(s.autoLimit !== void 0 ? `It may take ${s.autoLimit} automatic turns per window.\n` : "It uses the daemon's limit again.\n");
461
- else if (s.auto) ctx.out("Waiting messages become its next prompt when a turn ends, or right away while it is idle where its CLI allows.\n");
462
- else ctx.out("Messages still reach it at the next prompt and through the inbox tool.\n");
463
- return 0;
464
- } catch (e) {
465
- const problem = daemonProblem(t, e);
466
- return fail(ctx, {
467
- what: "Auto mode was not changed",
468
- detail: [problem.why],
469
- fix: `Run ${cmd(t, "conveno status")} to see the sessions.`,
470
- exit: 1,
471
- ref: "e_auto"
472
- });
473
- } finally {
474
- await client.close().catch(() => void 0);
475
- }
476
- }
477
143
  // src/daemon.ts
478
144
  async function lockPid(ctx) {
479
145
  try {
@@ -522,7 +188,7 @@ const STOP_FIX = (t) => `then run ${cmd(t, "conveno daemon status")}`;
522
188
  * tool, so it works for a normal user in a Windows SSH session. Only when the daemon does not answer,
523
189
  * and its lock pid is verified to be the daemon, is the process ended directly.
524
190
  */
525
- async function stopDaemon(ctx) {
191
+ async function stopDaemon(ctx, plain = false) {
526
192
  const t = ctx.theme;
527
193
  const lock = dataPaths(ctx.platform, ctx.dataDir).lock;
528
194
  const pid = await lockPid(ctx);
@@ -539,7 +205,7 @@ async function stopDaemon(ctx) {
539
205
  } catch (e) {
540
206
  await client.close().catch(() => void 0);
541
207
  return fail(ctx, {
542
- what: `The daemon${named} did not accept the stop request`,
208
+ what: `The background service${named} did not accept the stop request`,
543
209
  detail: [plainError(e)],
544
210
  fix: `${pid === null ? "Stop the process that owns the daemon socket yourself" : `Stop pid ${pid} yourself`}, ${STOP_FIX(t)}.`,
545
211
  exit: 1,
@@ -548,17 +214,17 @@ async function stopDaemon(ctx) {
548
214
  }
549
215
  await client.close().catch(() => void 0);
550
216
  if (!await waitFor(async () => !await reachable(ctx) && !await lockExists(ctx) && (pid === null || !ctx.isAlive(pid)), ctx.stopTimeoutMs)) return fail(ctx, {
551
- what: `The daemon${named} is still running after ${Math.round(ctx.stopTimeoutMs / 1e3)}s`,
217
+ what: `The background service${named} is still running after ${Math.round(ctx.stopTimeoutMs / 1e3)}s`,
552
218
  detail: ["It accepted the stop request, but its process, socket or lock file is still there."],
553
219
  fix: `${pid === null ? "Stop the process that owns the daemon socket yourself" : `Stop pid ${pid} yourself`}, ${STOP_FIX(t)}.`,
554
220
  exit: 1,
555
221
  ref: "e_daemon_stop"
556
222
  });
557
- ctx.out(`${t.status("ok")} Stopped the daemon${named}.\n`);
223
+ ctx.out(`${t.status("ok")} Stopped ${plain ? "Conveno's background service" : "the daemon"}${named}.\n`);
558
224
  return 0;
559
225
  }
560
226
  if (pid === null) {
561
- ctx.out(`${t.status("info")} The daemon is not running. Nothing to stop.\n`);
227
+ ctx.out(`${t.status("info")} Conveno's background service is not running. Nothing to stop.\n`);
562
228
  return 0;
563
229
  }
564
230
  const stale = async () => {
@@ -569,7 +235,7 @@ async function stopDaemon(ctx) {
569
235
  if (!ctx.isAlive(pid)) return stale();
570
236
  const commandLine = await ctx.commandLineOf(pid);
571
237
  if (commandLine === null) return fail(ctx, {
572
- what: `The daemon did not answer, and pid ${pid} could not be checked`,
238
+ what: `The background service did not answer, and pid ${pid} could not be checked`,
573
239
  detail: ["Conveno could not read that process's command line, so it cannot tell whether it is the daemon. It stopped nothing."],
574
240
  fix: `If pid ${pid} is the Conveno daemon, end it yourself (Task Manager on Windows, \`kill ${pid}\` elsewhere), ${STOP_FIX(t)}.`,
575
241
  exit: 1,
@@ -588,16 +254,28 @@ async function stopDaemon(ctx) {
588
254
  });
589
255
  }
590
256
  if (!await waitFor(() => !ctx.isAlive(pid), ctx.stopTimeoutMs)) return fail(ctx, {
591
- what: `The daemon (pid ${pid}) is still running after ${Math.round(ctx.stopTimeoutMs / 1e3)}s`,
257
+ what: `The background service (pid ${pid}) is still running after ${Math.round(ctx.stopTimeoutMs / 1e3)}s`,
592
258
  detail: ["It did not answer, was ended, and has not exited."],
593
259
  fix: `Stop that process yourself, ${STOP_FIX(t)}.`,
594
260
  exit: 1,
595
261
  ref: "e_daemon_stop"
596
262
  });
597
263
  await rm(lock, { force: true }).catch(() => void 0);
598
- ctx.out(`${t.status("ok")} Stopped the daemon (pid ${pid}). It was not answering, so it was ended directly.\n`);
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`);
599
265
  return 0;
600
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
+ }
601
279
  const SUBCOMMANDS = [
602
280
  "start",
603
281
  "stop",
@@ -634,7 +312,7 @@ async function runDaemon(ctx, argv) {
634
312
  if (problem.notRunning) ctx.out(`${t.glyph("offline")} daemon not running\n`);
635
313
  else {
636
314
  ctx.out(`${t.status("error")} daemon cannot be reached\n`);
637
- ctx.err(warnBlock(t, "The Conveno daemon cannot be reached.", problem.fix, problem.why));
315
+ ctx.err(warnBlock(t, "Conveno's background service cannot be reached.", problem.fix, problem.why));
638
316
  }
639
317
  return 1;
640
318
  }
@@ -662,7 +340,7 @@ async function withClient(ctx, autoStart, run) {
662
340
  } catch (e) {
663
341
  const problem = daemonProblem(t, e);
664
342
  return fail(ctx, {
665
- what: "The Conveno daemon cannot be reached",
343
+ what: "Conveno's background service cannot be reached",
666
344
  detail: [problem.why],
667
345
  fix: problem.fix,
668
346
  exit: 1,
@@ -673,7 +351,7 @@ async function withClient(ctx, autoStart, run) {
673
351
  return await run(client);
674
352
  } catch (e) {
675
353
  return fail(ctx, {
676
- what: "The daemon refused the request",
354
+ what: "The background service refused the request",
677
355
  detail: [plainError(e)],
678
356
  fix: `Run ${cmd(t, "conveno relay status")} to see the relay and login state.`,
679
357
  exit: 1,
@@ -1014,465 +692,92 @@ function acpDoctorLines(ctx, clis) {
1014
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")]);
1015
693
  return [
1016
694
  "",
1017
- `ACP workers ${q("(conveno spawn <cli> --acp)")}`,
695
+ `ACP workers ${q("(conveno spawn <cli>)")}`,
1018
696
  ...columns(table),
1019
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.")] : []
1020
698
  ];
1021
699
  }
1022
- // src/doctor.ts
1023
- /** What the plan says about one part: nothing to do, an addition, or an update to what is there. */
1024
- function partState(changes, component) {
1025
- const mine = changes.filter((c) => c.component === component);
1026
- if (mine.length === 0) return "ok";
1027
- return mine.some((c) => c.kind === "add") ? "missing" : "outdated";
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
+ }
1028
724
  }
1029
- /** Time allowed for the one process-table query. */
1030
- const ANCESTRY_TIMEOUT_MS = 5e3;
1031
- const tierWord = (t) => t === "next_turn" ? "next turn" : t;
1032
- const hasAny = (c) => c !== void 0 && (c.nextTurn || c.endOfTurn || c.idleWake);
1033
725
  /**
1034
- * The delivery tiers that work right now for one CLI: what the adapter can do for this version,
1035
- * once its hooks (or plugin) are in place. Without them only the inbox tool is left.
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.
1036
729
  */
1037
- function activeTiers(row) {
1038
- const caps = row.adapter.delivery?.(row.detection);
1039
- if (!caps) return row.adapter.deliveryTier === "inbox" || row.hooks === "ok" ? [tierWord(row.adapter.deliveryTier)] : ["inbox"];
1040
- if (!hasAny(caps) || row.hooks !== "ok") return ["inbox"];
1041
- return [
1042
- ...caps.nextTurn ? ["next turn"] : [],
1043
- ...caps.endOfTurn ? ["end of turn"] : [],
1044
- ...caps.idleWake ? ["idle wake"] : []
1045
- ];
1046
- }
1047
- async function inspect(ctx, adapter) {
1048
- const env = adapterEnv(ctx);
1049
- let detection;
1050
- try {
1051
- detection = await adapter.detect(env);
1052
- } catch {
1053
- detection = {
1054
- installed: false,
1055
- configPaths: []
1056
- };
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;
1057
745
  }
1058
- if (!detection.installed) return {
1059
- adapter,
1060
- detection,
1061
- mcp: null,
1062
- hooks: null
1063
- };
1064
- const hasHooks = adapter.deliveryTier !== "inbox" || hasAny(adapter.delivery?.(detection));
1065
- try {
1066
- const changes = await adapter.plan(env);
1067
- return {
1068
- adapter,
1069
- detection,
1070
- mcp: partState(changes, "mcp"),
1071
- hooks: hasHooks ? partState(changes, "hooks") : null
1072
- };
1073
- } catch (e) {
1074
- return {
1075
- adapter,
1076
- detection,
1077
- mcp: "missing",
1078
- hooks: hasHooks ? "missing" : null,
1079
- planError: plainError(e)
1080
- };
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);
1081
763
  }
1082
764
  }
1083
- /** A note for a CLI outside the tested range. Newer is a warning, older than the minimum a problem. */
1084
- function versionBlock(t, adapter, version, status) {
1085
- const name = adapter.displayName;
1086
- if (status.kind === "older") return {
1087
- problem: true,
1088
- text: errorBlock(t, {
1089
- what: `${name} ${version} is older than Conveno supports`,
1090
- detail: [`Conveno needs ${name} ${status.minimum} or newer.`],
1091
- fix: `Upgrade ${name}, then run ${cmd(t, "conveno doctor")} again.`,
1092
- exit: 1,
1093
- ref: "e_cli_old"
1094
- })
1095
- };
1096
- if (status.kind === "newer") return {
1097
- problem: false,
1098
- 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.")
1099
- };
1100
- }
1101
- async function runDoctor(ctx, argv = []) {
1102
- const t = ctx.theme;
1103
- const spec = COMMANDS.find((c) => c.name === "doctor");
1104
- if (spec) {
1105
- const parsed = parseFlags(ctx, spec, argv);
1106
- if (typeof parsed === "number") return parsed;
1107
- }
1108
- let ok = 0;
1109
- let warnings = 0;
1110
- let problems = 0;
1111
- const notes = [];
1112
- let daemonLine;
1113
- try {
1114
- const client = await ctx.connect(connectOpts(ctx, false));
1115
- try {
1116
- const { sessions } = await client["session.list"]({ includeOffline: true });
1117
- daemonLine = [` ${t.status("ok")} daemon`, `running, ${plural(sessions.length, "session")}`];
1118
- ok++;
1119
- } finally {
1120
- await client.close().catch(() => void 0);
1121
- }
1122
- } catch (e) {
1123
- const problem = daemonProblem(t, e);
1124
- if (problem.notRunning) {
1125
- daemonLine = [` ${t.status("warn")} daemon`, "not running"];
1126
- warnings++;
1127
- notes.push(warnBlock(t, "The Conveno daemon is not running.", problem.fix, problem.why));
1128
- } else {
1129
- daemonLine = [` ${t.status("error")} daemon`, "cannot be reached"];
1130
- problems++;
1131
- notes.push(errorBlock(t, {
1132
- what: "The Conveno daemon cannot be reached",
1133
- detail: [problem.why],
1134
- fix: problem.fix,
1135
- exit: 1,
1136
- ref: "e_daemon"
1137
- }));
1138
- }
1139
- }
1140
- ctx.out(`${columns([daemonLine]).join("\n")}\n\n`);
1141
- if (!(await ctx.ancestry(ANCESTRY_TIMEOUT_MS)).complete) {
1142
- warnings++;
1143
- 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."));
1144
- }
1145
- const rows = await Promise.all(ctx.adapters.map((a) => inspect(ctx, a)));
1146
- const q = (w) => t.paint("quiet", w);
1147
- const table = [[
1148
- ` ${q("CLI")}`,
1149
- q("NAME"),
1150
- q("VERSION"),
1151
- q("MCP"),
1152
- q("HOOKS"),
1153
- q("DELIVERY"),
1154
- q("NOTE")
1155
- ]];
1156
- const yesNo = (v) => v === null ? q("n/a") : v === "ok" ? "yes" : t.paint("warn", v === "missing" ? "not configured" : "needs update");
1157
- for (const r of rows) {
1158
- const { adapter, detection } = r;
1159
- if (!detection.installed) {
1160
- table.push([
1161
- ` ${t.glyph("offline")} ${adapter.cli}`,
1162
- adapter.displayName,
1163
- "",
1164
- "",
1165
- "",
1166
- "",
1167
- q("not found on PATH")
1168
- ]);
1169
- continue;
1170
- }
1171
- const good = r.mcp === "ok" && (r.hooks === null || r.hooks === "ok") && !r.planError;
1172
- const compat = compatStatus(adapter.cli, detection.version, ctx.compat);
1173
- const tiers = activeTiers(r);
1174
- let note = tiers.includes("idle wake") ? "auto mode wakes idle sessions" : tiers.includes("end of turn") ? "auto mode: at the end of a turn, no idle wake" : tiers.includes("next turn") ? "delivered at the next prompt" : "read through the inbox tool";
1175
- if (!good) note = r.planError ? "config could not be read" : r.mcp === "outdated" || r.hooks === "outdated" ? "needs an update" : "not fully configured";
1176
- if (compat.kind === "older") note = `older than the minimum ${compat.minimum}`;
1177
- else if (compat.kind === "newer" && good) note = `newer than tested (${compat.verified})`;
1178
- const glyph = compat.kind === "older" ? t.status("error") : good && compat.kind !== "newer" ? t.status("ok") : t.status("warn");
1179
- table.push([
1180
- ` ${glyph} ${adapter.cli}`,
1181
- adapter.displayName,
1182
- detection.version ?? "",
1183
- yesNo(r.mcp),
1184
- yesNo(r.hooks),
1185
- tiers.join(", "),
1186
- q(note)
1187
- ]);
1188
- if (r.planError) {
1189
- problems++;
1190
- notes.push(errorBlock(t, {
1191
- what: `${adapter.displayName} config could not be read`,
1192
- detail: [r.planError],
1193
- fix: "Repair the file named above, then run conveno doctor again.",
1194
- exit: 1,
1195
- ref: "e_config"
1196
- }));
1197
- } else if (good) {
1198
- if (compat.kind === "ok" || compat.kind === "unknown") ok++;
1199
- } else {
1200
- warnings++;
1201
- const named = [["the MCP server", r.mcp], ["the hooks", r.hooks]];
1202
- const list = (state) => named.filter(([, s]) => s === state).map(([n]) => n).join(" and ");
1203
- const missing = list("missing");
1204
- const outdated = list("outdated");
1205
- const fix = `Run ${cmd(t, "conveno init")}, then restart open ${adapter.displayName} sessions.`;
1206
- 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.`));
1207
- }
1208
- const versionNote = versionBlock(t, adapter, detection.version, compat);
1209
- if (versionNote) {
1210
- notes.push(versionNote.text);
1211
- if (versionNote.problem) problems++;
1212
- else warnings++;
1213
- }
1214
- }
1215
- ctx.out(`${columns(table).join("\n")}\n`);
1216
- if (rows.some((r) => r.detection.installed && activeTiers(r).some((t) => t !== "next turn" && t !== "inbox"))) ctx.out(`${q("End of turn and idle wake apply to sessions in auto mode; see conveno auto.")}\n`);
1217
- const acpLines = acpDoctorLines(ctx, rows.filter((r) => r.detection.installed).map((r) => r.adapter.cli));
1218
- if (acpLines.length > 0) ctx.out(`${acpLines.join("\n")}\n`);
1219
- const relayRows = [];
1220
- for (const r of rows) {
1221
- if (!r.detection.installed || !r.adapter.permissionHookInstalled || r.planError) continue;
1222
- const installed = await r.adapter.permissionHookInstalled(adapterEnv(ctx)).catch(() => false);
1223
- relayRows.push([` ${r.adapter.cli}`, q(installed ? "permission relay: hook installed (off until turned on per session)" : "permission relay: not installed (optional)")]);
1224
- }
1225
- if (relayRows.length > 0) ctx.out(`\n${columns(relayRows).join("\n")}\n`);
1226
- if (!rows.some((r) => r.detection.installed)) {
1227
- notes.push(warnBlock(t, "No supported AI coding CLI was found on PATH.", "Install Claude Code, Codex CLI or OpenCode, then run conveno init."));
1228
- warnings++;
1229
- }
1230
- for (const n of notes) ctx.err(`\n${n.trimEnd()}\n`);
1231
- ctx.out(`\n${ok} ok, ${plural(warnings, "warning")}, ${plural(problems, "problem")}\n`);
1232
- return problems > 0 ? 1 : 0;
1233
- }
1234
- // src/version.ts
1235
- const VERSION = "0.2.0-rc.1";
1236
- // src/errorLog.ts
1237
- /** The message of an unexpected error, as it is. Not the softened text `plainError` gives. */
1238
- function rawMessage(e) {
1239
- if (e instanceof Error) return `${e.name}: ${e.message}`;
1240
- return String(e);
1241
- }
1242
- /**
1243
- * Write the full stack of an unexpected error to `<data dir>/logs/<timestamp>-error.log`, readable
1244
- * by the user only. Returns the path, or undefined when the log could not be written (the error is
1245
- * still reported, just without a log).
1246
- */
1247
- async function writeErrorLog(ctx, argv, e) {
1248
- try {
1249
- const dir = dataPaths(ctx.platform, ctx.dataDir).logs;
1250
- await mkdir(dir, {
1251
- recursive: true,
1252
- mode: 448
1253
- });
1254
- const stamp = ctx.now().toISOString().replace(/[:.]/g, "-");
1255
- const file = join(dir, `${stamp}-error.log`);
1256
- const command = argv.slice(0, 2).join(" ");
1257
- const text = [
1258
- `conveno ${VERSION} ${command}`,
1259
- "ref e_internal",
1260
- `time ${ctx.now().toISOString()}`,
1261
- `platform ${ctx.platform}, node ${process.version}`,
1262
- "",
1263
- e instanceof Error ? e.stack ?? rawMessage(e) : rawMessage(e),
1264
- e instanceof Error && e.cause !== void 0 ? `\nCaused by: ${e.cause instanceof Error ? e.cause.stack ?? rawMessage(e.cause) : String(e.cause)}` : "",
1265
- ""
1266
- ].join("\n");
1267
- await writeFile(file, text, { mode: 384 });
1268
- await chmod(file, 384).catch(() => void 0);
1269
- return file;
1270
- } catch {
1271
- return;
1272
- }
1273
- }
1274
- // src/forget.ts
1275
- const UNIT_MS = {
1276
- m: 6e4,
1277
- h: 36e5,
1278
- d: 864e5
1279
- };
1280
- /** `30m`, `24h` or `7d` as milliseconds, or undefined when the text is anything else. */
1281
- function parseDuration(text) {
1282
- const m = /^(\d{1,6})([mhd])$/.exec(text);
1283
- if (!m) return void 0;
1284
- const ms = Number(m[1]) * UNIT_MS[m[2]];
1285
- return ms > 0 ? ms : void 0;
1286
- }
1287
- /** Rebuild the command line the user typed, for the "run it again with --yes" hint. */
1288
- function rerunLine(names, flags) {
1289
- return [
1290
- "conveno forget",
1291
- ...names.map((n) => n.includes("*") ? `'${n}'` : n),
1292
- ...flags.offline ? ["--offline"] : [],
1293
- ...flags.olderThan ? ["--older-than", flags.olderThan] : []
1294
- ].join(" ");
1295
- }
1296
- async function runForget(ctx, argv) {
1297
- const t = ctx.theme;
1298
- const spec = COMMANDS.find((c) => c.name === "forget");
1299
- if (!spec) return 2;
1300
- const parsed = parseFlags(ctx, spec, argv);
1301
- if (typeof parsed === "number") return parsed;
1302
- const names = parsed.positionals;
1303
- const offline = parsed.values.offline === true;
1304
- const olderThan = typeof parsed.values["older-than"] === "string" ? parsed.values["older-than"] : void 0;
1305
- const dryRun = parsed.values["dry-run"] === true;
1306
- const yes = parsed.values.yes === true;
1307
- const help = `Run ${cmd(t, "conveno forget --help")} to see the options.`;
1308
- for (const n of names) if (!SessionNamePattern.safeParse(n).success) return fail(ctx, {
1309
- what: `"${n}" is not a session name or pattern`,
1310
- detail: ["Names use lowercase letters, digits and \".\", \"_\", \"@\" or \"-\". A \"*\" matches any run of characters."],
1311
- fix: `Run ${cmd(t, "conveno status --all")} to see the names.`,
1312
- exit: 2,
1313
- ref: "e_usage"
1314
- });
1315
- let olderThanMs;
1316
- if (olderThan !== void 0) {
1317
- olderThanMs = parseDuration(olderThan);
1318
- if (olderThanMs === void 0) return fail(ctx, {
1319
- what: `"${olderThan}" is not a duration`,
1320
- detail: ["Use a whole number and a unit: 30m for minutes, 24h for hours, 7d for days."],
1321
- fix: help,
1322
- exit: 2,
1323
- ref: "e_usage"
1324
- });
1325
- }
1326
- if (names.length === 0 && !offline && olderThanMs === void 0) return fail(ctx, {
1327
- what: "conveno forget needs to know which sessions to forget",
1328
- detail: ["Name them, or pass --offline for every offline session."],
1329
- fix: `For example ${cmd(t, "conveno forget 'conveno-real-*'")} or ${cmd(t, "conveno forget --offline --older-than 7d")}.`,
1330
- exit: 2,
1331
- ref: "e_usage"
1332
- });
1333
- let client;
1334
- try {
1335
- client = await ctx.connect(connectOpts(ctx, false));
1336
- } catch (e) {
1337
- const problem = daemonProblem(t, e);
1338
- return fail(ctx, {
1339
- what: problem.notRunning ? "The Conveno daemon is not running" : "The Conveno daemon cannot be reached",
1340
- detail: [problem.notRunning ? "Sessions live in the daemon, so there is nothing to forget until it runs." : problem.why],
1341
- fix: problem.notRunning ? `Run ${cmd(t, "conveno daemon start")}.` : problem.fix,
1342
- exit: 1,
1343
- ref: "e_daemon"
1344
- });
1345
- }
1346
- try {
1347
- const selector = {
1348
- ...names.length > 0 ? { names } : {},
1349
- ...names.length === 0 || olderThanMs !== void 0 ? { olderThanMs: olderThanMs ?? 0 } : {}
1350
- };
1351
- const preview = await client["session.forget"]({
1352
- ...selector,
1353
- dryRun: true
1354
- });
1355
- const ids = new Set(preview.forgotten.map((s) => s.id));
1356
- const picked = (await client["session.list"]({ includeOffline: true })).sessions.filter((s) => ids.has(s.id));
1357
- if (preview.skippedOnline.length > 0) {
1358
- ctx.out(`${t.status("warn")} ${t.bold(`Skipped ${plural(preview.skippedOnline.length, "online session")}`)}\n`);
1359
- ctx.out(`${columns(preview.skippedOnline.map((s) => [` ${t.status("idle")} ${t.bold(s.name)}`, t.paint("quiet", "online, a running session is never forgotten")])).join("\n")}\n\n`);
1360
- }
1361
- if (picked.length === 0) {
1362
- ctx.out(`${t.status("info")} Nothing to forget. ${t.paint("quiet", `${cmd(t, "conveno status --all")} lists the offline sessions.`)}\n`);
1363
- return 0;
1364
- }
1365
- ctx.out(`${t.bold(dryRun ? `Would forget ${plural(picked.length, "session")}` : `Will forget ${plural(picked.length, "session")}`)}\n\n`);
1366
- ctx.out(`${renderSessions(ctx, picked)}\n\n`);
1367
- ctx.out(` ${t.paint("quiet", "Their queued messages are deleted too. Messages they sent stay with the receivers.")}\n\n`);
1368
- if (dryRun) {
1369
- ctx.out(`${t.status("info")} Dry run. Nothing was changed.\n`);
1370
- return 0;
1371
- }
1372
- if (!yes) {
1373
- if (!ctx.interactive) return fail(ctx, {
1374
- what: "Needs a terminal to confirm",
1375
- detail: ["No sessions were forgotten."],
1376
- fix: `Run ${cmd(t, `${rerunLine(names, {
1377
- offline,
1378
- ...olderThan ? { olderThan } : {}
1379
- })} --yes`)} to forget the sessions listed above.`,
1380
- exit: 2,
1381
- ref: "e_no_tty"
1382
- });
1383
- if (!await ctx.confirm(`Forget ${plural(picked.length, "session")}?`, false)) {
1384
- ctx.out(`${t.status("info")} Nothing was changed.\n`);
1385
- return 0;
1386
- }
1387
- }
1388
- const done = await client["session.forget"]({ ids: [...ids] });
1389
- ctx.out(`${t.status("ok")} ${t.bold("Done.")} Forgot ${plural(done.forgotten.length, "session")}.\n`);
1390
- return 0;
1391
- } finally {
1392
- await client.close().catch(() => void 0);
1393
- }
1394
- }
1395
- // src/acp-offer.ts
1396
- /** The adapter packages an installed CLI needs and that are not on PATH (nor overridden). */
1397
- function missingAdapters(ctx, installed) {
1398
- const out = [];
1399
- for (const { cli, displayName } of installed) {
1400
- const acp = SPAWN_TABLE[cli]?.acp;
1401
- if (!acp?.adapterPackage) continue;
1402
- if (!resolveAcpProgram(cli, acp, {
1403
- env: ctx.env,
1404
- which: (n) => findOnPath(n, ctx.env, ctx.platform),
1405
- npxConsent: false
1406
- }).ok) out.push({
1407
- pkg: acp.adapterPackage,
1408
- cli: displayName
1409
- });
1410
- }
1411
- return out;
1412
- }
1413
- function printManual(ctx, missing) {
1414
- const q = (w) => ctx.theme.paint("quiet", w);
1415
- for (const { pkg } of missing) {
1416
- ctx.out(` ${adapterInstallCommand(pkg)}\n`);
1417
- ctx.out(` ${q(`or run it on demand: ${adapterNpxCommand(pkg)}`)}\n`);
1418
- }
1419
- }
1420
- /**
1421
- * Ask once whether ACP workers may fetch the adapters with npx. `--acp-adapters` and
1422
- * `--no-acp-adapters` answer without asking and replace an earlier answer. Without a terminal, or
1423
- * with `--yes`, nothing is asked and nothing is saved.
1424
- */
1425
- async function offerAcpAdapters(ctx, opts) {
1426
- const t = ctx.theme;
1427
- const path = dataPaths(ctx.platform, ctx.dataDir).settings;
1428
- const missing = missingAdapters(ctx, opts.installed);
1429
- if (opts.flag !== void 0) {
1430
- writeSettings(path, { acpAdapterNpx: opts.flag });
1431
- if (opts.flag) ctx.out(`${t.status("ok")} ACP workers may fetch adapters with npx (pinned versions).\n`);
1432
- else {
1433
- ctx.out(`${t.status("info")} ACP workers will not fetch adapters with npx.\n`);
1434
- if (missing.length > 0) {
1435
- ctx.out(" To use ACP workers, install the adapters yourself:\n");
1436
- printManual(ctx, missing);
1437
- }
1438
- }
1439
- return;
1440
- }
1441
- if (missing.length === 0) return;
1442
- if (readSettings(path).acpAdapterNpx !== void 0) return;
1443
- const who = missing.map((m) => m.cli).join(" and ");
1444
- ctx.out(`\n${t.bold("ACP workers")} let conveno spawn <cli> --acp 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:
1445
- ${missing.map((m) => ` ${pinnedAdapter(m.pkg) ?? m.pkg}\n`).join("")}`);
1446
- if (!ctx.interactive || opts.yes) {
1447
- ctx.out(`${t.status("info")} Not asked. Run ${cmd(t, "conveno init --acp-adapters")} to allow npx, or install by hand:\n`);
1448
- printManual(ctx, missing);
1449
- return;
1450
- }
1451
- if (await ctx.confirm("Let ACP workers fetch these adapters with npx?", false)) {
1452
- writeSettings(path, { acpAdapterNpx: true });
1453
- ctx.out(`${t.status("ok")} Allowed. The first ACP worker for each takes a moment to start.\n`);
1454
- } else {
1455
- writeSettings(path, { acpAdapterNpx: false });
1456
- ctx.out(`${t.status("info")} Not allowed. To use ACP workers, install the adapters yourself:\n`);
1457
- printManual(ctx, missing);
1458
- }
1459
- }
1460
- // src/diff.ts
1461
- const splitLines = (s) => {
1462
- if (s === "") return [];
1463
- const lines = s.split("\n");
1464
- if (lines.at(-1) === "") lines.pop();
1465
- return lines;
1466
- };
1467
- /** Line diff through the longest common subsequence. Fine for config files. */
1468
- function diffOps(a, b) {
1469
- let start = 0;
1470
- while (start < a.length && start < b.length && a[start] === b[start]) start++;
1471
- let endA = a.length;
1472
- let endB = b.length;
1473
- while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
1474
- endA--;
1475
- endB--;
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--;
1476
781
  }
1477
782
  const mid = [];
1478
783
  const x = a.slice(start, endA);
@@ -1659,14 +964,14 @@ const realIo = {
1659
964
  * compare it with the plan just before writing, and `applyChanges` restores every file from its
1660
965
  * backup if any write fails. No temp file exists on this path, so none can be left behind.
1661
966
  */
1662
- async function writeAtomic(path, data, io = realIo) {
967
+ async function writeAtomic(path, data, io = realIo, wantMode) {
1663
968
  const target = await io.realpath(path).catch(() => path);
1664
969
  await io.mkdir(dirname(target));
1665
970
  if (io.platform === "win32") {
1666
971
  await io.overwrite(target, data);
1667
972
  return;
1668
973
  }
1669
- const mode = await io.mode(target);
974
+ const mode = wantMode ?? await io.mode(target);
1670
975
  const tmp = join(dirname(target), `.${basename(target)}.conveno-${randomBytes(6).toString("hex")}.tmp`);
1671
976
  try {
1672
977
  await io.writeFile(tmp, data, mode ?? 420);
@@ -1730,7 +1035,8 @@ async function applyChanges(ctx, items, opts = {}) {
1730
1035
  path: change.path,
1731
1036
  backup,
1732
1037
  description: change.description,
1733
- ...change.deleteFile ? {} : { afterSha256: sha256(change.after) }
1038
+ ...change.deleteFile ? {} : { afterSha256: sha256(change.after) },
1039
+ ...change.pruneEmptyDir === void 0 ? {} : { pruneEmptyDir: change.pruneEmptyDir }
1734
1040
  });
1735
1041
  }
1736
1042
  const manifest = {
@@ -1761,8 +1067,10 @@ async function applyChanges(ctx, items, opts = {}) {
1761
1067
  }
1762
1068
  if (!done) {
1763
1069
  await currentIfUnchanged(change);
1764
- if (change.deleteFile) await io.rm(change.path);
1765
- else await writeAtomic(change.path, change.after, io);
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);
1766
1074
  }
1767
1075
  how.push({
1768
1076
  cli,
@@ -1855,12 +1163,22 @@ async function previewRestore(manifests) {
1855
1163
  }
1856
1164
  return rows;
1857
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
+ }
1858
1174
  /** Restore one file as init found it, when it still matches. Returns the action taken. */
1859
1175
  async function restoreEntry(dir, entry) {
1860
1176
  const bytes = await readBytes(entry.path);
1861
1177
  const action = actionFor(entry, bytes === null ? null : sha256(bytes));
1862
- if (action === "remove") await rm(entry.path, { force: true });
1863
- else if (action === "restore" && entry.backup !== null) await writeAtomic(entry.path, await readFile(join(dir, entry.backup)));
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)));
1864
1182
  return action;
1865
1183
  }
1866
1184
  async function markRestored(ctx, found) {
@@ -1871,8 +1189,8 @@ async function markRestored(ctx, found) {
1871
1189
  await writeFile(join(found.dir, MANIFEST_NAME), `${JSON.stringify(done, null, 2)}\n`, { mode: 384 });
1872
1190
  }
1873
1191
  // src/init.ts
1874
- const CODEX_NOTE = "Codex asks you to trust new hooks once: run /hooks inside Codex.";
1875
- const CURSOR_NOTE = "Cursor CLI can ask to approve the Conveno MCP server when you start it in your home folder. Approve it once there with: cursor-agent mcp enable conveno";
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";
1876
1194
  /** Detect every adapter. A detection that throws counts as not installed. */
1877
1195
  async function detectAll(ctx, adapters = ctx.adapters) {
1878
1196
  const env = adapterEnv(ctx);
@@ -1893,9 +1211,11 @@ async function detectAll(ctx, adapters = ctx.adapters) {
1893
1211
  }
1894
1212
  }));
1895
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(",")}`;
1896
1216
  function parseCliList(raw, ctx) {
1897
1217
  if (raw === void 0) return ctx.adapters;
1898
- const names = raw.split(",").map((s) => s.trim()).filter(Boolean);
1218
+ const names = raw.split(/[\s,]+/).filter(Boolean);
1899
1219
  const out = [];
1900
1220
  for (const n of names) {
1901
1221
  if (!CLI_KINDS.includes(n)) {
@@ -1913,7 +1233,7 @@ function parseCliList(raw, ctx) {
1913
1233
  }
1914
1234
  function printDetections(ctx, found) {
1915
1235
  const t = ctx.theme;
1916
- ctx.out(`${t.bold("Looking for AI coding CLIs on this machine")}\n`);
1236
+ ctx.out(`${t.bold("Looking for AI tools on this machine")}\n`);
1917
1237
  const rows = found.map(({ adapter, detection }) => detection.installed ? [
1918
1238
  ` ${t.status("ok")} ${adapter.cli}`,
1919
1239
  adapter.displayName,
@@ -1923,16 +1243,19 @@ function printDetections(ctx, found) {
1923
1243
  ctx.out(`${columns(rows).join("\n")}\n\n`);
1924
1244
  }
1925
1245
  /** Collect plans from installed adapters. Returns failures instead of throwing. */
1926
- async function collectPlans(ctx, found, which, baseline, opts = {}) {
1927
- const env = adapterEnv(ctx, opts);
1246
+ async function collectPlans(ctx, found, which, baseline, accept = []) {
1247
+ const env = adapterEnv(ctx);
1928
1248
  const items = [];
1929
1249
  const failures = [];
1930
1250
  for (const { adapter, detection } of found) try {
1931
- for (const change of await (which === "plan" ? adapter.plan(env) : adapter.uninstallPlan(env, baseline))) items.push({
1932
- cli: adapter.cli,
1933
- installed: detection.installed,
1934
- change
1935
- });
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
+ }
1936
1259
  } catch (e) {
1937
1260
  failures.push({
1938
1261
  cli: adapter.cli,
@@ -1964,8 +1287,10 @@ const staleFailure = (ctx, e, rerun) => fail(ctx, {
1964
1287
  async function confirmAndApply(ctx, items, opts) {
1965
1288
  const t = ctx.theme;
1966
1289
  const files = new Set(items.map((i) => i.change.path)).size;
1967
- ctx.out(`${t.bold(`Conveno will change ${plural(files, "file")}.`)} Nothing else is touched.\n\n`);
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`);
1968
1292
  presentChanges(ctx, items);
1293
+ for (const n of notes) ctx.out(` ${n}\n\n`);
1969
1294
  const paths = dataPaths(ctx.platform, ctx.dataDir);
1970
1295
  ctx.out(` ${t.paint("quiet", `Backups go to ${tilde(paths.backups, ctx.home)}/<timestamp>/`)}\n`);
1971
1296
  ctx.out(` ${t.paint("quiet", "Undo any time with:")} ${cmd(t, "conveno uninstall")}\n\n`);
@@ -1982,8 +1307,12 @@ async function confirmAndApply(ctx, items, opts) {
1982
1307
  return { exit: 0 };
1983
1308
  }
1984
1309
  }
1310
+ if (opts.beforeApply) {
1311
+ const code = await opts.beforeApply();
1312
+ if (code !== 0) return { exit: code };
1313
+ }
1985
1314
  try {
1986
- return { applied: await applyChanges(ctx, items, opts.markRestored ? { markRestored: true } : {}) };
1315
+ return { applied: await applyChanges(ctx, [...items, ...opts.backups ?? []], opts.markRestored ? { markRestored: true } : {}) };
1987
1316
  } catch (e) {
1988
1317
  if (e instanceof StaleError) return { exit: staleFailure(ctx, e, opts.rerun) };
1989
1318
  if (e instanceof ApplyError && !e.rolledBack) return { exit: fail(ctx, {
@@ -2002,11 +1331,167 @@ async function confirmAndApply(ctx, items, opts) {
2002
1331
  }) };
2003
1332
  }
2004
1333
  }
2005
- async function runInit(ctx, argv) {
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
+ }
2006
1485
  const outcome = {};
2007
- const code = await initSetup(ctx, argv, outcome);
2008
- if (code !== 0 || !outcome.offer) return code;
2009
- const spec = COMMANDS.find((c) => c.name === "init");
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);
2010
1495
  const parsed = spec ? parseFlags(ctx, spec, argv) : void 0;
2011
1496
  const values = typeof parsed === "object" ? parsed.values : {};
2012
1497
  await offerAcpAdapters(ctx, {
@@ -2016,24 +1501,24 @@ async function runInit(ctx, argv) {
2016
1501
  });
2017
1502
  return 0;
2018
1503
  }
2019
- async function initSetup(ctx, argv, outcome) {
1504
+ async function initSetup(ctx, argv, outcome, name) {
2020
1505
  const t = ctx.theme;
2021
1506
  const started = ctx.now();
2022
- const spec = COMMANDS.find((c) => c.name === "init");
1507
+ const spec = COMMANDS.find((c) => c.name === name);
2023
1508
  if (!spec) return 2;
2024
1509
  const parsed = parseFlags(ctx, spec, argv);
2025
1510
  if (typeof parsed === "number") return parsed;
2026
1511
  const values = parsed.values;
2027
1512
  if (values["acp-adapters"] === true && values["no-acp-adapters"] === true) return fail(ctx, {
2028
1513
  what: "Use --acp-adapters or --no-acp-adapters, not both",
2029
- fix: `Run ${cmd(t, "conveno init --help")} to see the options.`,
1514
+ fix: `Run ${cmd(t, `conveno ${name} --help`)} to see the options.`,
2030
1515
  exit: 2,
2031
1516
  ref: "e_usage"
2032
1517
  });
2033
1518
  const chosen = parseCliList(typeof values.cli === "string" ? values.cli : void 0, ctx);
2034
1519
  if (!Array.isArray(chosen)) return fail(ctx, {
2035
1520
  what: chosen.message,
2036
- fix: `Pass ${cmd(t, "--cli claude,codex,opencode")} or leave it out.`,
1521
+ fix: `Pass ${cmd(t, cliListExample(ctx))} or leave it out.`,
2037
1522
  ...chosen.suggestion ? { didYouMean: chosen.suggestion } : {},
2038
1523
  exit: 2,
2039
1524
  ref: "e_usage"
@@ -2042,614 +1527,382 @@ async function initSetup(ctx, argv, outcome) {
2042
1527
  printDetections(ctx, found);
2043
1528
  const installed = found.filter((f) => f.detection.installed);
2044
1529
  if (installed.length === 0) return fail(ctx, {
2045
- what: "No supported AI coding CLI was found",
1530
+ what: "No supported AI tool was found",
2046
1531
  detail: [`Looked for ${chosen.map((a) => a.displayName).join(", ")} on PATH.`],
2047
- fix: "Install one of them, then run conveno init again.",
1532
+ fix: `Install one of them, then run conveno ${name} again.`,
2048
1533
  exit: 1,
2049
1534
  ref: "e_no_cli"
2050
1535
  });
2051
- const withRelay = values["with-permission-relay"] === true;
2052
- const { items, failures } = await collectPlans(ctx, installed, "plan", void 0, { permissionRelay: withRelay });
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]);
2053
1562
  if (failures.length > 0) {
2054
- reportFailures(ctx, failures, "conveno init --cli <others>");
1563
+ reportFailures(ctx, failures, `conveno ${name} --cli <others>`);
2055
1564
  return 1;
2056
1565
  }
2057
- if (items.length === 0) {
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) {
2058
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());
2059
1580
  outcome.offer = installed.map((f) => f.adapter);
2060
1581
  return 0;
2061
1582
  }
2062
- if (values["dry-run"]) {
1583
+ if (dryRun) {
2063
1584
  const files = new Set(items.map((i) => i.change.path)).size;
2064
- ctx.out(`${t.bold(`Conveno would change ${plural(files, "file")}.`)} Nothing else is touched.\n\n`);
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`);
2065
1587
  presentChanges(ctx, items);
2066
- ctx.out(`${t.status("info")} Dry run: nothing was written. Run ${cmd(t, "conveno init")} to apply.\n`);
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`);
2067
1594
  return 0;
2068
1595
  }
1596
+ const writes = await approvalWrites(ctx, adapters, applying, items);
2069
1597
  const result = await confirmAndApply(ctx, items, {
2070
1598
  yes: values.yes === true,
2071
1599
  verb: "Apply",
2072
- rerun: withRelay ? "conveno init --with-permission-relay" : "conveno init"
1600
+ rerun: `conveno ${name}`,
1601
+ notes: writes.notes,
1602
+ backups: writes.backups
2073
1603
  });
2074
1604
  if ("exit" in result) return result.exit;
2075
1605
  const byCli = /* @__PURE__ */ new Map();
2076
1606
  for (const h of result.applied.how) byCli.set(h.cli, [...byCli.get(h.cli) ?? [], h.via]);
2077
- const rows = [...byCli].map(([cli, vias]) => [` ${t.status("ok")} ${cli}`, vias.every((v) => v === "command") ? "configured with the CLI's own command" : "configured"]);
1607
+ const rows = [...byCli].map(([cli, vias]) => [` ${t.status("ok")} ${cli}`, vias.every((v) => v === "command") ? "set up with its own command" : "configured"]);
2078
1608
  ctx.out(`${columns(rows).join("\n")}\n\n`);
2079
1609
  ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
2080
1610
  ctx.out(` Backups are in ${tilde(result.applied.backupDir, ctx.home)}.\n`);
2081
1611
  ctx.out(" Restart open sessions so they pick up Conveno.\n");
2082
- if (byCli.has("codex")) ctx.out(`${t.status("info")} ${CODEX_NOTE}\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`);
2083
1614
  if (byCli.has("cursor")) ctx.out(`${t.status("info")} ${CURSOR_NOTE}\n`);
2084
1615
  ctx.out(` Next: ${cmd(t, "conveno status")} lists your sessions.\n`);
2085
1616
  outcome.offer = installed.map((f) => f.adapter);
2086
1617
  return 0;
2087
1618
  }
2088
- // src/peek.ts
2089
- async function connectOrFail(ctx) {
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) {
2090
1624
  const t = ctx.theme;
2091
- try {
2092
- return await ctx.connect(connectOpts(ctx, false));
2093
- } catch (e) {
2094
- const problem = daemonProblem(t, e);
2095
- return fail(ctx, {
2096
- what: problem.notRunning ? "The Conveno daemon is not running" : "The Conveno daemon cannot be reached",
2097
- detail: [problem.notRunning ? "Sessions live in the daemon, so there is nothing to peek at until it runs." : problem.why],
2098
- fix: problem.notRunning ? `Run ${cmd(t, "conveno daemon start")}.` : problem.fix,
2099
- exit: 1,
2100
- ref: "e_daemon"
2101
- });
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 : [])));
2102
1631
  }
2103
- }
2104
- const isSessionRef = (s) => SessionId.safeParse(s).success || SessionNameInput.safeParse(s).success;
2105
- function badSession(ctx, name) {
2106
- return fail(ctx, {
2107
- what: `"${name}" is not a session name`,
2108
- detail: ["Names use lowercase letters, digits and \".\", \"_\", \"@\" or \"-\"."],
2109
- fix: `Run ${cmd(ctx.theme, "conveno status")} to see the names.`,
2110
- exit: 2,
2111
- ref: "e_usage"
2112
- });
2113
- }
2114
- /** `conveno peek on|off [session]`: the owner's switch. */
2115
- async function runSwitch(ctx, peekable, session) {
2116
- const t = ctx.theme;
2117
- if (session !== void 0 && !isSessionRef(session)) return badSession(ctx, session);
2118
- const client = await connectOrFail(ctx);
2119
- if (typeof client === "number") return client;
2120
- try {
2121
- const res = await client["session.setPeekable"]({
2122
- peekable,
2123
- ...session !== void 0 ? { session } : {}
2124
- });
2125
- if (res.sessions.length === 0) {
2126
- ctx.out(`${t.status("info")} No online sessions, so nothing changed.\n`);
2127
- return 0;
2128
- }
2129
- const names = res.sessions.map((s) => s.name).join(", ");
2130
- ctx.out(`${t.status("ok")} Peek is ${t.bold(peekable ? "on" : "off")} for ${plural(res.sessions.length, "session")}: ${names}\n`);
2131
- if (session === void 0) ctx.out(` ${t.paint("quiet", "Sessions that start later are peekable by default. Run it again after they start.")}\n`);
2132
- return 0;
2133
- } catch (e) {
2134
- return daemonFailure(ctx, e);
2135
- } finally {
2136
- await client.close().catch(() => void 0);
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`);
2137
1635
  }
2138
- }
2139
- function daemonFailure(ctx, e) {
2140
- const t = ctx.theme;
2141
- if (e instanceof ConvenoError) {
2142
- const permission = e.code === RpcErrorCode.PermissionRequired;
2143
- return fail(ctx, {
2144
- what: permission ? "Peek is turned off for that session" : e.message,
2145
- ...permission ? { detail: [e.message] } : {},
2146
- fix: e.code === RpcErrorCode.NotFound ? `Run ${cmd(t, "conveno status")} to see the sessions that are online.` : permission ? "Its owner turns peek on again with the command above." : `Run ${cmd(t, "conveno doctor")} if this keeps happening.`,
2147
- exit: 1,
2148
- ref: permission ? "e_peek_off" : "e_peek"
2149
- });
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);
2150
1641
  }
2151
- const problem = daemonProblem(t, e);
2152
- return fail(ctx, {
2153
- what: "The Conveno daemon could not answer",
2154
- detail: [problem.why],
2155
- fix: problem.fix,
2156
- exit: 1,
2157
- ref: "e_daemon"
2158
- });
1642
+ return approved;
2159
1643
  }
2160
- /** `conveno peek <session> [-n N] [--raw-json]`: what another session did lately, secrets redacted. */
2161
- async function runPeek(ctx, argv) {
2162
- const t = ctx.theme;
2163
- const spec = COMMANDS.find((c) => c.name === "peek");
2164
- if (!spec) return 2;
2165
- const parsed = parseFlags(ctx, spec, argv);
2166
- if (typeof parsed === "number") return parsed;
2167
- const [first, second] = parsed.positionals;
2168
- if (first === void 0) return fail(ctx, {
2169
- what: "conveno peek needs a session",
2170
- detail: ["Name the session to read, or use on or off to switch peek for your sessions."],
2171
- fix: `For example ${cmd(t, "conveno peek claude@api-1")} or ${cmd(t, "conveno peek off")}.`,
2172
- exit: 2,
2173
- ref: "e_usage"
2174
- });
2175
- if (first === "on" || first === "off") return runSwitch(ctx, first === "on", second);
2176
- if (!isSessionRef(first)) return badSession(ctx, first);
2177
- const nText = typeof parsed.values.n === "string" ? parsed.values.n : void 0;
2178
- const n = nText === void 0 ? 10 : Number(nText);
2179
- if (!Number.isInteger(n) || n < 1 || n > 50) return fail(ctx, {
2180
- what: `"${nText}" is not a number of turns`,
2181
- detail: [`Use a whole number from 1 to 50.`],
2182
- fix: `For example ${cmd(t, `conveno peek ${first} -n 20`)}.`,
2183
- exit: 2,
2184
- ref: "e_usage"
2185
- });
2186
- const client = await connectOrFail(ctx);
2187
- if (typeof client === "number") return client;
2188
- try {
2189
- const res = await client["session.peek"]({
2190
- target: first,
2191
- lastTurns: n
2192
- });
2193
- if (parsed.values["raw-json"] === true) {
2194
- ctx.out(`${JSON.stringify(res, null, 2)}\n`);
2195
- return 0;
2196
- }
2197
- ctx.out(`${t.bold(res.session.name)} ${t.paint("quiet", `${res.session.cli}, last ${plural(res.turns.length, "turn")}, secrets redacted (best effort)`)}\n`);
2198
- if (res.turns.length === 0) ctx.out(`\n${t.paint("quiet", "The transcript has no turns yet.")}\n`);
2199
- for (const turn of res.turns) {
2200
- const stamp = turn.at ? ` ${t.paint("quiet", localStamp(turn.at))}` : "";
2201
- ctx.out(`\n${t.bold(turn.role)}${stamp}\n${turn.text.replace(/\n/g, "\n ").replace(/^/, " ")}\n`);
2202
- }
2203
- if (res.truncated) ctx.out(`\n${t.paint("quiet", `Earlier turns, or long text, are left out. ${cmd(t, `conveno peek ${first} -n 50`)} reads more.`)}\n`);
2204
- return 0;
2205
- } catch (e) {
2206
- return daemonFailure(ctx, e);
2207
- } finally {
2208
- await client.close().catch(() => void 0);
2209
- }
2210
- }
2211
- // src/tickets.ts
2212
- /** Connect to a running daemon, or print why not. */
2213
- async function connectRunning(ctx, why) {
2214
- const t = ctx.theme;
2215
- try {
2216
- return await ctx.connect(connectOpts(ctx, false));
2217
- } catch (e) {
2218
- const problem = daemonProblem(t, e);
2219
- return { exit: fail(ctx, {
2220
- what: problem.notRunning ? "The Conveno daemon is not running" : "The Conveno daemon cannot be reached",
2221
- detail: [problem.notRunning ? why : problem.why],
2222
- fix: problem.notRunning ? `Run ${cmd(t, "conveno daemon start")}.` : problem.fix,
2223
- exit: 1,
2224
- ref: "e_daemon"
2225
- }) };
2226
- }
2227
- }
2228
- const oneLine = (text, max) => {
2229
- const flat = sanitizeLine(text);
2230
- return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
2231
- };
2232
- /** The first line of a ticket, which for a permission request is its title line. */
2233
- const headline = (t) => oneLine(t.question.split("\n")[0] ?? "", 70);
2234
- async function runTickets(ctx, argv) {
2235
- const t = ctx.theme;
2236
- const spec = COMMANDS.find((c) => c.name === "tickets");
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");
2237
1650
  if (!spec) return 2;
2238
1651
  const parsed = parseFlags(ctx, spec, argv);
2239
1652
  if (typeof parsed === "number") return parsed;
2240
- const openOnly = parsed.values.open === true;
2241
- const client = await connectRunning(ctx, "Tickets live in the daemon, so there are none to list.");
2242
- if ("exit" in client) return client.exit;
2243
- try {
2244
- const res = await client["ticket.list"]({
2245
- ...openOnly ? { status: "open" } : {},
2246
- limit: 200
2247
- });
2248
- const names = new Map((await client["session.list"]({ includeOffline: true })).sessions.map((s) => [s.id, s.name]));
2249
- const who = (id) => names.get(id) ?? id.slice(-6);
2250
- if (res.tickets.length === 0) {
2251
- ctx.out(`${t.status("info")} ${openOnly ? "No open tickets." : "No tickets yet."} ${t.paint("quiet", "Workers raise them with the ask tool.")}\n`);
2252
- return 0;
2253
- }
2254
- const q = (w) => t.paint("quiet", w);
2255
- const rows = [[
2256
- ` ${q("TICKET")}`,
2257
- q("STATE"),
2258
- q("FROM"),
2259
- q("TO"),
2260
- q("WHEN"),
2261
- q("QUESTION")
2262
- ], ...res.tickets.map((k) => [
2263
- ` ${t.bold(k.id)}`,
2264
- k.status === "open" ? t.paint("entry", "open") : q(k.status),
2265
- who(k.fromSession),
2266
- who(k.toSession),
2267
- q(stamp(k.createdAt, ctx.now())),
2268
- `${k.kind === "permission" ? `${t.paint("warn", "permission")} ` : ""}${headline(k)}`
2269
- ])];
2270
- ctx.out(`${columns(rows).join("\n")}\n\n`);
2271
- const hint = res.openCount > 0 ? ` Answer with ${cmd(t, "conveno answer <ticket> <text>")}.` : "";
2272
- ctx.out(`${plural(res.openCount, "open ticket")}.${hint}\n`);
2273
- return 0;
2274
- } finally {
2275
- await client.close().catch(() => void 0);
2276
- }
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");
2277
1656
  }
2278
- /** A full ticket id, or the one open ticket that ends or starts with `text` (at least 6 characters). */
2279
- function pickTicket(tickets, text) {
2280
- if (TicketId.safeParse(text).success) return tickets.find((k) => k.id === text) ?? `No ticket ${text}.`;
2281
- if (text.length < 6) return `"${text}" is too short to name a ticket. Use at least 6 characters.`;
2282
- const wanted = text.toUpperCase();
2283
- const hits = tickets.filter((k) => k.id.startsWith(wanted) || k.id.endsWith(wanted));
2284
- if (hits.length === 1 && hits[0]) return hits[0];
2285
- return hits.length === 0 ? `No ticket matches "${text}".` : `"${text}" matches ${hits.length} tickets.`;
2286
- }
2287
- async function runAnswer(ctx, argv) {
2288
- const t = ctx.theme;
2289
- const spec = COMMANDS.find((c) => c.name === "answer");
2290
- if (!spec) return 2;
2291
- const parsed = parseFlags(ctx, spec, argv);
2292
- if (typeof parsed === "number") return parsed;
2293
- const [id, ...words] = parsed.positionals;
2294
- const response = words.join(" ").trim();
2295
- if (!id || response === "") return fail(ctx, {
2296
- what: "conveno answer needs a ticket and an answer",
2297
- fix: `For example ${cmd(t, "conveno answer 01J8ABCD \"Use sqlite\"")}. ${cmd(t, "conveno tickets --open")} lists the open tickets.`,
2298
- exit: 2,
2299
- ref: "e_usage"
2300
- });
2301
- const client = await connectRunning(ctx, "Tickets live in the daemon, so there is nothing to answer.");
2302
- if ("exit" in client) return client.exit;
2303
- try {
2304
- const { tickets } = await client["ticket.list"]({ limit: 200 });
2305
- const picked = pickTicket(tickets, id);
2306
- if (typeof picked === "string") return fail(ctx, {
2307
- what: picked,
2308
- fix: `Run ${cmd(t, "conveno tickets --open")} to see the open tickets.`,
2309
- exit: 1,
2310
- ref: "e_ticket"
2311
- });
2312
- const res = await client["ticket.answer"]({
2313
- ticketId: picked.id,
2314
- response
2315
- });
2316
- const who = res.ticket.kind === "permission" ? "The worker's CLI" : "The asker";
2317
- ctx.out(`${t.status("ok")} ${t.bold("Answered")} ${res.ticket.id} ${t.paint("quiet", `(${res.ticket.answeredBy === "human" ? "by you" : "recorded"}). ${who} gets it now.`)}\n`);
2318
- return 0;
2319
- } catch (e) {
2320
- return fail(ctx, {
2321
- what: "The ticket could not be answered",
2322
- detail: [e instanceof Error ? e.message : String(e)],
2323
- fix: `Run ${cmd(t, "conveno tickets")} to see its state.`,
2324
- exit: 1,
2325
- ref: "e_ticket"
2326
- });
2327
- } finally {
2328
- await client.close().catch(() => void 0);
2329
- }
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";
2330
1663
  }
2331
- // src/permissions.ts
2332
- const RELAY_WARNING = "EXPERIMENTAL: while the relay is on, the orchestrator can allow or deny this session's tool calls. Calls outside its repo, network and credential access always stay with you. See SECURITY.md.";
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);
2333
1668
  /**
2334
- * The relay needs the CLI's PermissionRequest hook. Add it the first time, with the same diff,
2335
- * backup and manifest as `conveno init` (so `conveno uninstall` removes it). Returns an exit code
2336
- * to stop with, or undefined to go on.
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.
2337
1671
  */
2338
- async function ensureHooks(ctx, targets, named, yes) {
2339
- const t = ctx.theme;
2340
- const items = [];
2341
- const driven = targets.find((s) => !s.spawned);
2342
- if (driven) return fail(ctx, {
2343
- what: `The relay could not be turned on for ${driven.name}`,
2344
- detail: [`${driven.name} was not started by Conveno, so a person is driving it. The relay is only for sessions started with conveno spawn or spawn_session.`],
2345
- fix: `Start a worker with ${cmd(t, "conveno spawn <cli>")}.`,
2346
- exit: 1,
2347
- ref: "e_relay"
2348
- });
2349
- for (const cli of new Set(targets.map((s) => s.cli))) {
2350
- const adapter = ctx.adapters.find((a) => a.cli === cli);
2351
- if (!adapter?.permissionHookInstalled) return fail(ctx, {
2352
- what: `The permission relay does not support ${cli}`,
2353
- detail: ["It needs a hook that runs only when the CLI is about to ask for a permission. Claude Code and Codex have one; see SECURITY.md for the others."],
2354
- fix: `Use the relay with a Claude Code or Codex worker.`,
2355
- exit: 1,
2356
- ref: "e_relay_cli"
2357
- });
2358
- try {
2359
- if (await adapter.permissionHookInstalled(adapterEnv(ctx))) continue;
2360
- const changes = await adapter.plan(adapterEnv(ctx, { permissionRelay: true }));
2361
- for (const change of changes.filter((c) => c.component === "hooks")) items.push({
2362
- cli: adapter.cli,
2363
- installed: true,
2364
- change
2365
- });
2366
- } catch (e) {
2367
- return fail(ctx, {
2368
- what: `Could not plan the ${adapter.displayName} permission hook`,
2369
- detail: [plainError(e)],
2370
- fix: "Fix the problem above, then run the command again.",
2371
- exit: 1,
2372
- ref: "e_plan"
2373
- });
2374
- }
2375
- }
2376
- if (items.length === 0) return void 0;
2377
- ctx.out(`${t.status("info")} The relay needs a ${[...new Set(items.map((i) => i.cli))].join(" and ")} PermissionRequest hook. It is not installed yet.\n\n`);
2378
- const result = await confirmAndApply(ctx, items, {
2379
- yes,
2380
- verb: "Apply",
2381
- rerun: `conveno permissions relay on${named ? ` ${named}` : ""}`
2382
- });
2383
- if ("exit" in result) return result.exit === 0 ? 0 : result.exit;
2384
- ctx.out(`${t.status("ok")} Hook added. Restart the open ${[...new Set(items.map((i) => i.cli))].join(" and ")} sessions so they load it${items.some((i) => i.cli === "codex") ? ", and trust it in Codex with /hooks" : ""}.\n`);
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
+ ];
2385
1685
  }
2386
- async function runPermissions(ctx, argv) {
2387
- const t = ctx.theme;
2388
- const spec = COMMANDS.find((c) => c.name === "permissions");
2389
- if (!spec) return 2;
2390
- const parsed = parseFlags(ctx, spec, argv);
2391
- if (typeof parsed === "number") return parsed;
2392
- const [sub, state, name, ...extra] = parsed.positionals;
2393
- const usage = `Run ${cmd(t, "conveno permissions relay on <session>")} or ${cmd(t, "conveno permissions relay off [session]")}.`;
2394
- if (sub !== void 0 && (sub !== "relay" || state !== "on" && state !== "off" || extra.length > 0)) return fail(ctx, {
2395
- what: `"${parsed.positionals.join(" ")}" is not a permissions command`,
2396
- fix: usage,
2397
- exit: 2,
2398
- ref: "e_usage"
2399
- });
2400
- const client = await connectRunning(ctx, "The permission relay lives in the daemon.");
2401
- if ("exit" in client) return client.exit;
1686
+ async function inspect(ctx, adapter) {
1687
+ const env = adapterEnv(ctx);
1688
+ let detection;
2402
1689
  try {
2403
- const sessions = (await client["session.list"]({ includeOffline: true })).sessions;
2404
- const nameOf = (id) => sessions.find((s) => s.id === id)?.name ?? id.slice(-6);
2405
- if (sub === void 0) {
2406
- const { relays } = await client["permission.relay"]({});
2407
- ctx.out(`${t.status("warn")} ${t.paint("quiet", "Permission relay is EXPERIMENTAL and off unless listed.")}\n`);
2408
- if (relays.length === 0) ctx.out(`${t.status("info")} The relay is off for every session.\n`);
2409
- else {
2410
- const rows = relays.map((r) => `${nameOf(r.session)} (approved by ${nameOf(r.approver)})`);
2411
- ctx.out(`${t.bold("Relay on for:")} ${rows.join(", ")}\n`);
2412
- }
2413
- ctx.out(` ${t.paint("quiet", `Turn it on with ${cmd(t, "conveno permissions relay on <session>")}. SECURITY.md has the threat model.`)}\n`);
2414
- return 0;
2415
- }
2416
- const enable = state === "on";
2417
- let targets;
2418
- if (name !== void 0) {
2419
- const found = sessions.find((s) => s.name === name && s.status !== "offline");
2420
- if (!found) return fail(ctx, {
2421
- what: `No online session named "${name}"`,
2422
- fix: `Run ${cmd(t, "conveno status")} to see the names.`,
2423
- exit: 1,
2424
- ref: "e_no_session"
2425
- });
2426
- targets = [found];
2427
- } else if (enable) {
2428
- targets = sessions.filter((s) => s.spawned && s.status !== "offline");
2429
- if (targets.length !== 1) return fail(ctx, {
2430
- what: targets.length === 0 ? "No session started by Conveno is online" : "More than one spawned session is online",
2431
- detail: ["The relay is only for sessions started with conveno spawn or spawn_session, never for one you drive yourself."],
2432
- fix: `Name the session: ${cmd(t, "conveno permissions relay on <session>")}.`,
2433
- exit: 2,
2434
- ref: "e_usage"
2435
- });
2436
- } else {
2437
- const { relays } = await client["permission.relay"]({});
2438
- targets = sessions.filter((s) => relays.some((r) => r.session === s.id));
2439
- if (targets.length === 0) {
2440
- ctx.out(`${t.status("info")} The relay was already off for every session.\n`);
2441
- return 0;
2442
- }
2443
- }
2444
- if (enable) {
2445
- const code = await ensureHooks(ctx, targets, name, parsed.values.yes === true);
2446
- if (code !== void 0) return code;
2447
- }
2448
- for (const target of targets) {
2449
- let approver;
2450
- try {
2451
- approver = (await client["permission.relay"]({
2452
- target: target.id,
2453
- enabled: enable
2454
- })).relays.find((r) => r.session === target.id)?.approver;
2455
- } catch (e) {
2456
- return fail(ctx, {
2457
- what: `The relay could not be turned ${state} for ${target.name}`,
2458
- detail: [e instanceof Error ? e.message : String(e)],
2459
- fix: usage,
2460
- exit: 1,
2461
- ref: "e_relay"
2462
- });
2463
- }
2464
- ctx.out(`${t.status(enable ? "warn" : "ok")} Permission relay ${state} for ${t.bold(target.name)}.${approver ? ` ${nameOf(approver)} approves its prompts, and no one who takes the role later.` : ""}\n`);
2465
- }
2466
- if (enable) ctx.out(` ${RELAY_WARNING}\n`);
2467
- return 0;
2468
- } finally {
2469
- await client.close().catch(() => void 0);
1690
+ detection = await adapter.detect(env);
1691
+ } catch {
1692
+ detection = {
1693
+ installed: false,
1694
+ configPaths: []
1695
+ };
2470
1696
  }
2471
- }
2472
- // src/spawn.ts
2473
- /** Read the task from `--task-file`. Returns the text or the failure's exit code. */
2474
- function readTaskFile(ctx, path) {
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(() => []);
2475
1711
  try {
2476
- return readFileSync(resolve(ctx.cwd, path), "utf8");
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
+ };
2477
1722
  } catch (e) {
2478
- const code = e.code;
2479
- return fail(ctx, {
2480
- what: `Cannot read the task file ${path}`,
2481
- detail: [code === "ENOENT" ? "The file does not exist." : `The system said ${code ?? "no"}.`],
2482
- fix: "Check the path, or pass the task with --task.",
2483
- exit: 2,
2484
- ref: "e_usage"
2485
- });
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
+ };
2486
1732
  }
2487
1733
  }
2488
1734
  /**
2489
- * `conveno spawn <cli> ...`: start a worker session of any CLI with a first task, and print the
2490
- * name it registers under.
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.
2491
1738
  */
2492
- async function runSpawn(ctx, argv) {
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 = []) {
2493
1757
  const t = ctx.theme;
2494
- const spec = COMMANDS.find((c) => c.name === "spawn");
2495
- if (!spec) return 2;
2496
- const parsed = parseFlags(ctx, spec, argv);
2497
- if (typeof parsed === "number") return parsed;
2498
- const help = `Run ${cmd(t, "conveno spawn --help")} to see the options.`;
2499
- const [cli, ...extra] = parsed.positionals;
2500
- if (!cli || extra.length > 0) return fail(ctx, {
2501
- what: "conveno spawn needs exactly one CLI name",
2502
- detail: [`Known: ${SPAWN_CLIS.join(", ")}.`],
2503
- fix: `Run ${cmd(t, "conveno spawn claude --task 'review the open PR'")}.`,
2504
- exit: 2,
2505
- ref: "e_usage"
2506
- });
2507
- if (!Object.hasOwn(SPAWN_TABLE, cli)) return fail(ctx, {
2508
- what: `"${cli}" is not a CLI Conveno can start`,
2509
- detail: [`Known: ${SPAWN_CLIS.join(", ")}.`],
2510
- fix: help,
2511
- exit: 2,
2512
- ref: "e_usage"
2513
- });
2514
- const str = (k) => typeof parsed.values[k] === "string" ? parsed.values[k] : void 0;
2515
- if (str("task") !== void 0 && str("task-file") !== void 0) return fail(ctx, {
2516
- what: "Use --task or --task-file, not both",
2517
- fix: help,
2518
- exit: 2,
2519
- ref: "e_usage"
2520
- });
2521
- let task = str("task");
2522
- const taskFile = str("task-file");
2523
- if (taskFile !== void 0) {
2524
- const text = readTaskFile(ctx, taskFile);
2525
- if (typeof text === "number") return text;
2526
- task = text;
2527
- }
2528
- const acpFlag = parsed.values.acp === true;
2529
- const oneShot = parsed.values["one-shot"] === true;
2530
- if (acpFlag && oneShot) return fail(ctx, {
2531
- what: "Use --acp or --one-shot, not both",
2532
- fix: help,
2533
- exit: 2,
2534
- ref: "e_usage"
2535
- });
2536
- const headless = parsed.values.headless === true || acpFlag || oneShot;
2537
- const acp = acpFlag ? "require" : headless && !oneShot ? "prefer" : void 0;
2538
- const allowFlag = str("allow");
2539
- const allow = allowFlag === void 0 ? void 0 : [allowFlag];
2540
- const yes = parsed.values.yes === true;
2541
- const adapter = ctx.adapters.find((a) => a.cli === cli);
2542
- if (adapter && !(await adapter.detect(adapterEnv(ctx))).installed) return fail(ctx, {
2543
- what: `${adapter.displayName} is not installed`,
2544
- detail: [`conveno could not run ${cli} --version.`],
2545
- fix: "Install it, or check that its folder is on PATH.",
2546
- exit: 1,
2547
- ref: "e_spawn"
2548
- });
2549
- if (!yes) {
2550
- if (!ctx.interactive) return fail(ctx, {
2551
- what: "Needs a terminal to confirm",
2552
- detail: ["Nothing was started."],
2553
- fix: `Run the same command with ${cmd(t, "--yes")} to start the session without asking.`,
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 } : {},
2554
1768
  exit: 2,
2555
- ref: "e_no_tty"
1769
+ ref: "e_usage"
2556
1770
  });
2557
- const question = `Start ${cli} in ${tilde(resolve(ctx.cwd, str("cwd") ?? "."), ctx.home)}${headless ? " in the background" : ""}${task ? " with a first task" : ""}?`;
2558
- if (!await ctx.confirm(question, true)) {
2559
- ctx.out(`${t.status("info")} Nothing was started.\n`);
2560
- return 0;
2561
- }
1771
+ adapters = chosen;
2562
1772
  }
2563
- let client;
1773
+ let ok = 0;
1774
+ let warnings = 0;
1775
+ let problems = 0;
1776
+ const notes = [];
1777
+ let daemonLine;
2564
1778
  try {
2565
- client = await ctx.connect(connectOpts(ctx, true));
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
+ }
2566
1787
  } catch (e) {
2567
1788
  const problem = daemonProblem(t, e);
2568
- return fail(ctx, {
2569
- what: "The Conveno daemon cannot be reached",
2570
- detail: [problem.why],
2571
- fix: problem.fix,
2572
- exit: 1,
2573
- ref: "e_daemon"
2574
- });
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
+ }
2575
1804
  }
2576
- try {
2577
- const { hostPid } = await ctx.ancestry(2e3);
2578
- const requester = hostPid === void 0 ? void 0 : (await client["session.byHost"]({ pid: hostPid }).catch(() => void 0))?.session ?? void 0;
2579
- const runner = ctx.spawnRunner ?? [process.execPath, process.argv[1] ?? "conveno"];
2580
- const deps = realSpawnDeps({
2581
- platform: ctx.platform,
2582
- env: ctx.env,
2583
- home: ctx.home,
2584
- dataDir: ctx.dataDir,
2585
- client,
2586
- runner
2587
- });
2588
- const res = await spawnSession(deps, {
2589
- cli,
2590
- callerCwd: ctx.cwd,
2591
- cwd: str("cwd"),
2592
- name: str("name"),
2593
- task,
2594
- headless,
2595
- acp,
2596
- allow,
2597
- requester,
2598
- confineToHome: false,
2599
- onProgress: (line) => ctx.err(`${t.paint("quiet", line)}\n`)
2600
- });
2601
- const how = res.mode === "acp" ? "over ACP, background" : res.mode === "headless" ? "background" : res.terminal ?? "terminal";
2602
- ctx.out(`${t.status("ok")} ${t.bold(`Started ${res.name}`)} ${t.paint("quiet", `(${res.cli}, ${how}) in ${tilde(res.cwd, ctx.home)}`)}\n`);
2603
- if (res.task === "message") ctx.out(` The first task was sent to it as a Conveno message.\n`);
2604
- if (res.mode === "acp") {
2605
- ctx.out(` Follow it with ${cmd(t, `conveno attach ${res.name}`)}; end it with ${cmd(t, `conveno stop ${res.name}`)}.\n`);
2606
- if (res.adapter) ctx.out(` ${t.paint("quiet", `Adapter: ${res.adapter}`)}\n`);
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++;
2607
1879
  }
2608
- if (res.logPath) ctx.out(` Output: ${tilde(res.logPath, ctx.home)}\n`);
2609
- ctx.out(` ${t.paint("quiet", `${cmd(t, "conveno status")} lists it. Message it with send to: ${res.name}.`)}\n`);
2610
- return 0;
2611
- } catch (e) {
2612
- if (e instanceof SpawnError) return fail(ctx, {
2613
- what: "Could not start the session",
2614
- detail: [e.message],
2615
- ...e.fix ? { fix: e.fix } : {},
2616
- exit: 1,
2617
- ref: "e_spawn"
2618
- });
2619
- throw e;
2620
- } finally {
2621
- await client.close().catch(() => void 0);
2622
1880
  }
2623
- }
2624
- /** `conveno spawn-run <launch file>`: what a spawned terminal runs. Not for people. */
2625
- async function runSpawnRun(ctx, argv) {
2626
- const [file] = argv;
2627
- if (!file) return fail(ctx, {
2628
- what: "conveno spawn-run needs a launch file",
2629
- detail: ["It is started by conveno spawn inside the new terminal."],
2630
- fix: `Run ${cmd(ctx.theme, "conveno spawn <cli>")} instead.`,
2631
- exit: 2,
2632
- ref: "e_usage"
2633
- });
2634
- try {
2635
- return await runLaunchFile(file);
2636
- } catch (e) {
2637
- return fail(ctx, {
2638
- what: "Could not read the launch file",
2639
- detail: [e instanceof Error ? e.message : String(e)],
2640
- fix: `Run ${cmd(ctx.theme, "conveno spawn <cli>")} again.`,
2641
- exit: 1,
2642
- ref: "e_spawn"
2643
- });
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++;
2644
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;
2645
1891
  }
2646
1892
  // src/uninstall.ts
2647
1893
  const NOTE = {
2648
1894
  restore: "restored byte for byte",
2649
1895
  remove: "removed, it did not exist before",
2650
- edit: "edited since init, so only Conveno's entries are removed",
1896
+ edit: "edited since setup, so only Conveno's entries are removed",
2651
1897
  gone: "already gone, left as it is"
2652
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
+ }
2653
1906
  /**
2654
1907
  * The files as init found them, from the backups: their text, or null when they did not exist. A
2655
1908
  * backup that cannot be read leaves its file out, and the adapter then treats what it finds as
@@ -2733,6 +1986,8 @@ async function runUninstall(ctx, argv) {
2733
1986
  return 0;
2734
1987
  }
2735
1988
  }
1989
+ const stopped = await stopDaemonIfRunning(ctx);
1990
+ if (stopped !== 0) return stopped;
2736
1991
  let result;
2737
1992
  try {
2738
1993
  result = await restoreAll(ctx, manifests);
@@ -2746,9 +2001,10 @@ async function runUninstall(ctx, argv) {
2746
2001
  ref: "e_restore"
2747
2002
  });
2748
2003
  }
2004
+ await removeAskedMarkers(ctx);
2749
2005
  ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
2750
- ctx.out(` Restored ${plural(result.restored.length, "file")} to how init found them.\n`);
2751
- if (result.edited.length > 0) ctx.out(` Edited, not restored, because they changed since init: ${result.edited.map((p) => tilde(p, ctx.home)).join(", ")}. Only Conveno's entries were removed.\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`);
2752
2008
  ctx.out(" Restart open sessions to drop Conveno.\n");
2753
2009
  return 0;
2754
2010
  }
@@ -2766,134 +2022,13 @@ async function runUninstall(ctx, argv) {
2766
2022
  yes,
2767
2023
  verb: "Remove",
2768
2024
  rerun: "conveno uninstall",
2769
- markRestored: true
2025
+ markRestored: true,
2026
+ beforeApply: () => stopDaemonIfRunning(ctx)
2770
2027
  });
2771
2028
  if ("exit" in result) return result.exit;
2029
+ await removeAskedMarkers(ctx);
2772
2030
  ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
2773
2031
  ctx.out(" Removed the Conveno entries. Restart open sessions to drop Conveno.\n");
2774
2032
  return 0;
2775
2033
  }
2776
- // src/main.ts
2777
- const DESCRIPTION = "Conveno lets AI coding sessions on one machine find each other and exchange messages.";
2778
- function helpText(ctx) {
2779
- const t = ctx.theme;
2780
- const rows = COMMANDS.map((c) => [c.usage.replace(/^conveno /, ""), c.summary]);
2781
- const width = Math.max(...rows.map(([u]) => u.length), 9) + 2;
2782
- const row = (c, d) => ` ${t.bold(c.padEnd(width))}${d}`;
2783
- return [
2784
- DESCRIPTION,
2785
- "",
2786
- "Usage: conveno <command> [options]",
2787
- "",
2788
- ...rows.map(([u, d]) => row(u, d)),
2789
- row("--version", "Print the version"),
2790
- "",
2791
- `Run ${cmd(t, "conveno <command> --help")} for the options of one command.`,
2792
- `conveno ${t.paint("info", VERSION)}`,
2793
- ""
2794
- ].join("\n");
2795
- }
2796
- async function runMcp(ctx, argv) {
2797
- const t = ctx.theme;
2798
- const spec = COMMANDS.find((c) => c.name === "mcp");
2799
- if (!spec) return 2;
2800
- const parsed = parseFlags(ctx, spec, argv);
2801
- if (typeof parsed === "number") return parsed;
2802
- const cli = typeof parsed.values.cli === "string" ? parsed.values.cli : void 0;
2803
- if (!cli || !CLI_KINDS.includes(cli)) return fail(ctx, {
2804
- what: "conveno mcp needs a CLI name",
2805
- detail: [`Got ${cli ? `"${cli}"` : "none"}. Known: ${CLI_KINDS.join(", ")}.`],
2806
- fix: `Run ${cmd(t, "conveno mcp --cli claude")}, or let ${cmd(t, "conveno init")} write the config.`,
2807
- exit: 2,
2808
- ref: "e_usage"
2809
- });
2810
- try {
2811
- await ctx.runMcp({
2812
- cli,
2813
- ...ctx.daemonEntry ? { daemonEntry: ctx.daemonEntry } : {}
2814
- });
2815
- return 0;
2816
- } catch (e) {
2817
- const problem = daemonProblem(t, e);
2818
- return fail(ctx, {
2819
- what: "The Conveno MCP server stopped",
2820
- detail: [problem.why],
2821
- fix: problem.notRunning ? `Run ${cmd(t, "conveno doctor")} to check the daemon.` : problem.fix,
2822
- exit: 1,
2823
- ref: "e_mcp"
2824
- });
2825
- }
2826
- }
2827
- async function dispatch(command, rest, ctx) {
2828
- const spec = COMMANDS.find((c) => c.name === command);
2829
- if (spec && (rest.includes("--help") || rest.includes("-h")) && command !== "hook") {
2830
- ctx.out(commandHelp(ctx, spec));
2831
- return 0;
2832
- }
2833
- switch (command) {
2834
- case "init": return runInit(ctx, rest);
2835
- case "uninstall": return runUninstall(ctx, rest);
2836
- case "status": return runStatus(ctx, rest);
2837
- case "tickets": return runTickets(ctx, rest);
2838
- case "answer": return runAnswer(ctx, rest);
2839
- case "permissions": return runPermissions(ctx, rest);
2840
- case "forget": return runForget(ctx, rest);
2841
- case "spawn": return runSpawn(ctx, rest);
2842
- case "acp-host": return (await import("./acp-BlKK0v-B.js")).runAcpHostCmd(ctx, rest);
2843
- case "stop": return (await import("./acp-BlKK0v-B.js")).runStop(ctx, rest);
2844
- case "attach": return (await import("./acp-BlKK0v-B.js")).runAttach(ctx, rest);
2845
- case "spawn-run": return runSpawnRun(ctx, rest);
2846
- case "auto": return runAuto(ctx, rest);
2847
- case "peek": return runPeek(ctx, rest);
2848
- case "devices": return runDevices(ctx, rest);
2849
- case "relay": return runRelay(ctx, rest);
2850
- case "doctor": return runDoctor(ctx, rest);
2851
- case "login": return runLogin(ctx, rest);
2852
- case "logout": return runLogout(ctx, rest);
2853
- case "account": return runAccount(ctx, rest);
2854
- case "daemon": return runDaemon(ctx, rest);
2855
- case "mcp": return runMcp(ctx, rest);
2856
- case "hook": return runHook(ctx, rest);
2857
- default: {
2858
- const suggestion = closest(command, COMMAND_NAMES);
2859
- return fail(ctx, {
2860
- what: `Unknown command "${command}"`,
2861
- detail: [`conveno ${VERSION} has: ${COMMAND_NAMES.join(", ")}.`],
2862
- fix: `Run ${cmd(ctx.theme, "conveno --help")} to see usage.`,
2863
- ...suggestion ? { didYouMean: `Did you mean ${suggestion}?` } : {},
2864
- exit: 2,
2865
- ref: "e_usage"
2866
- });
2867
- }
2868
- }
2869
- }
2870
- /** Run one command line. Returns the exit code. Never throws. */
2871
- async function main(argv, ctx) {
2872
- const [command, ...rest] = argv;
2873
- switch (command) {
2874
- case void 0:
2875
- case "--help":
2876
- case "-h":
2877
- case "help":
2878
- ctx.out(helpText(ctx));
2879
- return 0;
2880
- case "--version":
2881
- case "-v":
2882
- case "version":
2883
- ctx.out(`${VERSION}\n`);
2884
- return 0;
2885
- }
2886
- try {
2887
- return await dispatch(command, rest, ctx);
2888
- } catch (e) {
2889
- const log = await writeErrorLog(ctx, argv, e);
2890
- return fail(ctx, {
2891
- what: "conveno stopped before it could finish",
2892
- detail: [rawMessage(e), ...log ? [`The full error is in ${tilde(log, ctx.home)}.`] : []],
2893
- fix: `Run ${cmd(ctx.theme, "conveno doctor")} to check the install, then try again.`,
2894
- exit: 1,
2895
- ref: "e_internal"
2896
- });
2897
- }
2898
- }
2899
- export { DESCRIPTION, helpText, main };
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 };