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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
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 { 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-_sq6DmrE.js";
2
2
  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";
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-DEYV4Ran.js";
4
+ import { n as adapterEnv, r as connectOpts, t as runHook } from "./hook-DlTGn8Do.js";
5
+ import { t as ClientError } from "./dist-BEZPNGU5.js";
6
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
7
  import { createHash, randomBytes } from "node:crypto";
8
+ import { basename, dirname, join, resolve } from "node:path";
9
9
  import { readFileSync } from "node:fs";
10
10
  // src/account.ts
11
11
  const accountIo = (ctx, io) => ({
@@ -1019,1071 +1019,1081 @@ function acpDoctorLines(ctx, clis) {
1019
1019
  ...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
1020
  ];
1021
1021
  }
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";
1022
+ // src/acp-offer.ts
1023
+ /** The adapter packages an installed CLI needs and that are not on PATH (nor overridden). */
1024
+ function missingAdapters(ctx, installed) {
1025
+ const out = [];
1026
+ for (const { cli, displayName } of installed) {
1027
+ const acp = SPAWN_TABLE[cli]?.acp;
1028
+ if (!acp?.adapterPackage) continue;
1029
+ if (!resolveAcpProgram(cli, acp, {
1030
+ env: ctx.env,
1031
+ which: (n) => findOnPath(n, ctx.env, ctx.platform),
1032
+ npxConsent: false
1033
+ }).ok) out.push({
1034
+ pkg: acp.adapterPackage,
1035
+ cli: displayName
1036
+ });
1037
+ }
1038
+ return out;
1039
+ }
1040
+ function printManual(ctx, missing) {
1041
+ const q = (w) => ctx.theme.paint("quiet", w);
1042
+ for (const { pkg } of missing) {
1043
+ ctx.out(` ${adapterInstallCommand(pkg)}\n`);
1044
+ ctx.out(` ${q(`or run it on demand: ${adapterNpxCommand(pkg)}`)}\n`);
1045
+ }
1028
1046
  }
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
1047
  /**
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.
1048
+ * Ask once whether ACP workers may fetch the adapters with npx. `--acp-adapters` and
1049
+ * `--no-acp-adapters` answer without asking and replace an earlier answer. Without a terminal, or
1050
+ * with `--yes`, nothing is asked and nothing is saved.
1036
1051
  */
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"];
1052
+ async function offerAcpAdapters(ctx, opts) {
1053
+ const t = ctx.theme;
1054
+ const path = dataPaths(ctx.platform, ctx.dataDir).settings;
1055
+ const missing = missingAdapters(ctx, opts.installed);
1056
+ if (opts.flag !== void 0) {
1057
+ writeSettings(path, { acpAdapterNpx: opts.flag });
1058
+ if (opts.flag) ctx.out(`${t.status("ok")} ACP workers may fetch adapters with npx (pinned versions).\n`);
1059
+ else {
1060
+ ctx.out(`${t.status("info")} ACP workers will not fetch adapters with npx.\n`);
1061
+ if (missing.length > 0) {
1062
+ ctx.out(" To use ACP workers, install the adapters yourself:\n");
1063
+ printManual(ctx, missing);
1064
+ }
1065
+ }
1066
+ return;
1067
+ }
1068
+ if (missing.length === 0) return;
1069
+ if (readSettings(path).acpAdapterNpx !== void 0) return;
1070
+ const who = missing.map((m) => m.cli).join(" and ");
1071
+ 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:
1072
+ ${missing.map((m) => ` ${pinnedAdapter(m.pkg) ?? m.pkg}\n`).join("")}`);
1073
+ if (!ctx.interactive || opts.yes) {
1074
+ ctx.out(`${t.status("info")} Not asked. Run ${cmd(t, "conveno init --acp-adapters")} to allow npx, or install by hand:\n`);
1075
+ printManual(ctx, missing);
1076
+ return;
1077
+ }
1078
+ if (await ctx.confirm("Let ACP workers fetch these adapters with npx?", false)) {
1079
+ writeSettings(path, { acpAdapterNpx: true });
1080
+ ctx.out(`${t.status("ok")} Allowed. The first ACP worker for each takes a moment to start.\n`);
1081
+ } else {
1082
+ writeSettings(path, { acpAdapterNpx: false });
1083
+ ctx.out(`${t.status("info")} Not allowed. To use ACP workers, install the adapters yourself:\n`);
1084
+ printManual(ctx, missing);
1085
+ }
1086
+ }
1087
+ // src/diff.ts
1088
+ const splitLines = (s) => {
1089
+ if (s === "") return [];
1090
+ const lines = s.split("\n");
1091
+ if (lines.at(-1) === "") lines.pop();
1092
+ return lines;
1093
+ };
1094
+ /** Line diff through the longest common subsequence. Fine for config files. */
1095
+ function diffOps(a, b) {
1096
+ let start = 0;
1097
+ while (start < a.length && start < b.length && a[start] === b[start]) start++;
1098
+ let endA = a.length;
1099
+ let endB = b.length;
1100
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
1101
+ endA--;
1102
+ endB--;
1103
+ }
1104
+ const mid = [];
1105
+ const x = a.slice(start, endA);
1106
+ const y = b.slice(start, endB);
1107
+ if (x.length * y.length > 4e6) {
1108
+ for (const line of x) mid.push({
1109
+ t: "-",
1110
+ line
1111
+ });
1112
+ for (const line of y) mid.push({
1113
+ t: "+",
1114
+ line
1115
+ });
1116
+ } else {
1117
+ const w = y.length + 1;
1118
+ const lcs = new Uint32Array((x.length + 1) * w);
1119
+ for (let i = x.length - 1; i >= 0; i--) for (let j = y.length - 1; j >= 0; j--) lcs[i * w + j] = x[i] === y[j] ? lcs[(i + 1) * w + j + 1] + 1 : Math.max(lcs[(i + 1) * w + j], lcs[i * w + j + 1]);
1120
+ let i = 0;
1121
+ let j = 0;
1122
+ while (i < x.length && j < y.length) if (x[i] === y[j]) {
1123
+ mid.push({
1124
+ t: " ",
1125
+ line: x[i]
1126
+ });
1127
+ i++;
1128
+ j++;
1129
+ } else if (lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) mid.push({
1130
+ t: "-",
1131
+ line: x[i++]
1132
+ });
1133
+ else mid.push({
1134
+ t: "+",
1135
+ line: y[j++]
1136
+ });
1137
+ while (i < x.length) mid.push({
1138
+ t: "-",
1139
+ line: x[i++]
1140
+ });
1141
+ while (j < y.length) mid.push({
1142
+ t: "+",
1143
+ line: y[j++]
1144
+ });
1145
+ }
1041
1146
  return [
1042
- ...caps.nextTurn ? ["next turn"] : [],
1043
- ...caps.endOfTurn ? ["end of turn"] : [],
1044
- ...caps.idleWake ? ["idle wake"] : []
1147
+ ...a.slice(0, start).map((line) => ({
1148
+ t: " ",
1149
+ line
1150
+ })),
1151
+ ...mid,
1152
+ ...a.slice(endA).map((line) => ({
1153
+ t: " ",
1154
+ line
1155
+ }))
1045
1156
  ];
1046
1157
  }
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
- };
1158
+ /** Unified diff body (hunks only) between two texts, `before` null meaning a new file. */
1159
+ function unifiedDiff(before, after, context = 2) {
1160
+ const ops = diffOps(splitLines(before ?? ""), splitLines(after));
1161
+ const changed = ops.flatMap((o, i) => o.t === " " ? [] : [i]);
1162
+ if (changed.length === 0) return [];
1163
+ const ranges = [];
1164
+ for (const i of changed) {
1165
+ const lo = Math.max(0, i - context);
1166
+ const hi = Math.min(ops.length, i + context + 1);
1167
+ const last = ranges.at(-1);
1168
+ if (last && lo <= last[1]) last[1] = hi;
1169
+ else ranges.push([lo, hi]);
1057
1170
  }
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
- };
1171
+ const out = [];
1172
+ for (const [lo, hi] of ranges) {
1173
+ let oldStart = 1;
1174
+ let newStart = 1;
1175
+ for (const o of ops.slice(0, lo)) {
1176
+ if (o.t !== "+") oldStart++;
1177
+ if (o.t !== "-") newStart++;
1178
+ }
1179
+ const slice = ops.slice(lo, hi);
1180
+ const oldCount = slice.filter((o) => o.t !== "+").length;
1181
+ const newCount = slice.filter((o) => o.t !== "-").length;
1182
+ const oldFrom = oldCount === 0 ? oldStart - 1 : oldStart;
1183
+ out.push(`@@ -${oldFrom},${oldCount} +${newStart},${newCount} @@`);
1184
+ for (const o of slice) out.push(`${o.t}${o.line}`);
1081
1185
  }
1186
+ return out;
1082
1187
  }
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
- };
1188
+ /** Colour diff lines with brand roles: added `ok`, removed `error`, hunk headers `quiet`. */
1189
+ function paintDiff(theme, lines, indent = " ") {
1190
+ return lines.map((l) => {
1191
+ const role = l.startsWith("@@") ? "quiet" : l.startsWith("+") ? "ok" : l.startsWith("-") ? "error" : null;
1192
+ return indent + (role ? theme.paint(role, l) : l);
1193
+ });
1100
1194
  }
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;
1195
+ // src/apply.ts
1196
+ const MANIFEST_NAME = "manifest.json";
1197
+ const isPosix = (ctx) => ctx.platform !== "win32";
1198
+ const sha256 = (data) => createHash("sha256").update(data).digest("hex");
1199
+ /** A file changed between planning and writing. */
1200
+ var StaleError = class extends Error {
1201
+ path;
1202
+ /** True unless files written earlier in the same run could not be put back. */
1203
+ rolledBack = true;
1204
+ constructor(path) {
1205
+ super(`${path} changed while Conveno was working. Nothing in it was overwritten.`);
1206
+ this.path = path;
1207
+ this.name = "StaleError";
1107
1208
  }
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++;
1209
+ };
1210
+ /** Will this change be made by the CLI's own command? Yes when the CLI is installed and the plan has one. */
1211
+ const usesCommand = (item) => Boolean(item.change.viaCommand) && item.installed;
1212
+ /** Print one block per file: path, what changes, the command that will run, the unified diff. */
1213
+ function presentChanges(ctx, items) {
1214
+ const t = ctx.theme;
1215
+ for (const item of items) {
1216
+ const { change } = item;
1217
+ ctx.out(` ${t.bold(tilde(change.path, ctx.home))}${change.before === null ? t.paint("quiet", " (new file)") : change.deleteFile ? t.paint("quiet", " (deleted)") : ""}\n`);
1218
+ ctx.out(` ${change.description}\n`);
1219
+ if (usesCommand(item) && change.viaCommand !== void 0 && change.viaCommand) {
1220
+ ctx.out(` ${t.paint("quiet", "will run")} ${t.bold(change.viaCommand.join(" "))}\n`);
1221
+ ctx.out(` ${t.paint("quiet", "expected result (the command may format the file differently)")}\n`);
1213
1222
  }
1223
+ const body = paintDiff(t, unifiedDiff(change.before, change.after));
1224
+ if (body.length > 0) ctx.out(`${body.join("\n")}\n`);
1225
+ ctx.out("\n");
1214
1226
  }
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++;
1227
+ }
1228
+ /** `<backups>/files/<path without drive or leading separator>`. */
1229
+ const mirrored = (path) => join("files", path.replace(/^[A-Za-z]:/, "").replace(/^[\\/]+/, ""));
1230
+ async function uniqueDir(base, stamp) {
1231
+ const existing = new Set(await readdir(base).catch(() => []));
1232
+ let name = stamp;
1233
+ for (let n = 2; existing.has(name); n++) name = `${stamp}-${n}`;
1234
+ return name;
1235
+ }
1236
+ async function readBytes(path) {
1237
+ try {
1238
+ return await readFile(path);
1239
+ } catch (e) {
1240
+ if (e.code === "ENOENT") return null;
1241
+ throw e;
1229
1242
  }
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
1243
  }
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);
1244
+ /** Create a directory only the user can use, and tighten one that already exists. */
1245
+ async function privateDir(ctx, dir) {
1246
+ await mkdir(dir, {
1247
+ recursive: true,
1248
+ mode: 448
1249
+ });
1250
+ if (isPosix(ctx)) await chmod(dir, 448).catch(() => void 0);
1241
1251
  }
1252
+ const realIo = {
1253
+ realpath: (p) => realpath(p),
1254
+ mkdir: async (p) => void await mkdir(p, { recursive: true }),
1255
+ mode: (p) => stat(p).then((s) => s.mode & 511, () => void 0),
1256
+ writeFile: (p, data, mode) => writeFile(p, data, { mode }),
1257
+ chmod: (p, mode) => chmod(p, mode),
1258
+ rename: (a, b) => rename$1(a, b),
1259
+ overwrite: async (p, data) => {
1260
+ const fh = await open(p, "w");
1261
+ try {
1262
+ await fh.writeFile(data);
1263
+ await fh.sync();
1264
+ } finally {
1265
+ await fh.close();
1266
+ }
1267
+ },
1268
+ rm: (p) => rm(p, { force: true }),
1269
+ platform: process.platform
1270
+ };
1242
1271
  /**
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).
1272
+ * Replace the contents of `path` with `data`, keeping its mode and writing through a symlink.
1273
+ *
1274
+ * POSIX: write a temp file in the same directory, then rename it over the target, so a reader
1275
+ * never sees half a file.
1276
+ *
1277
+ * Windows: write the target in place (open truncated, write, fsync). Reason, confirmed in the
1278
+ * libuv source Node uses: `fs.rename` is `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`, which needs
1279
+ * DELETE access to the existing target. That fails with ERROR_ACCESS_DENIED (reported as EPERM,
1280
+ * with `err.path` set to the temp file, the source) whenever any other process holds the target
1281
+ * open without FILE_SHARE_DELETE. Node itself shares READ, WRITE and DELETE on every handle, but
1282
+ * C runtime, Python and .NET defaults share only READ and WRITE, and so may a running CLI or a
1283
+ * virus scanner. Truncating in place needs only FILE_SHARE_WRITE from the other handles, so it
1284
+ * succeeds in the cases where an atomic replace cannot. The cost is that a reader can see a
1285
+ * half-written file for a moment. That is acceptable here because callers re-read the target and
1286
+ * compare it with the plan just before writing, and `applyChanges` restores every file from its
1287
+ * backup if any write fails. No temp file exists on this path, so none can be left behind.
1246
1288
  */
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 {
1289
+ async function writeAtomic(path, data, io = realIo) {
1290
+ const target = await io.realpath(path).catch(() => path);
1291
+ await io.mkdir(dirname(target));
1292
+ if (io.platform === "win32") {
1293
+ await io.overwrite(target, data);
1271
1294
  return;
1272
1295
  }
1296
+ const mode = await io.mode(target);
1297
+ const tmp = join(dirname(target), `.${basename(target)}.conveno-${randomBytes(6).toString("hex")}.tmp`);
1298
+ try {
1299
+ await io.writeFile(tmp, data, mode ?? 420);
1300
+ if (mode !== void 0) await io.chmod(tmp, mode);
1301
+ await io.rename(tmp, target);
1302
+ } catch (e) {
1303
+ if (e instanceof Error && e.path === tmp) e.path = target;
1304
+ throw e;
1305
+ } finally {
1306
+ await io.rm(tmp).catch(() => void 0);
1307
+ }
1273
1308
  }
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
- });
1309
+ /** A write failed. `rolledBack` says whether every file written before it was put back. */
1310
+ var ApplyError = class extends Error {
1311
+ rolledBack;
1312
+ notRestored;
1313
+ backupDir;
1314
+ constructor(message, rolledBack, notRestored, backupDir, options) {
1315
+ super(message, options);
1316
+ this.rolledBack = rolledBack;
1317
+ this.notRestored = notRestored;
1318
+ this.backupDir = backupDir;
1319
+ this.name = "ApplyError";
1325
1320
  }
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"
1321
+ };
1322
+ /** Re-read the file and refuse to go on when it is no longer what the plan was made from. */
1323
+ async function currentIfUnchanged(change) {
1324
+ const bytes = await readBytes(change.path);
1325
+ if (!(change.before === null ? bytes === null : bytes !== null && bytes.toString("utf8") === change.before)) throw new StaleError(change.path);
1326
+ return bytes;
1327
+ }
1328
+ /**
1329
+ * Back up every file we will touch, write the manifest, then apply. Each file is re-read first,
1330
+ * so a change made after the plan was shown is never overwritten.
1331
+ */
1332
+ async function applyChanges(ctx, items, opts = {}) {
1333
+ const paths = dataPaths(ctx.platform, ctx.dataDir);
1334
+ const unique = items.filter((it, i) => items.findIndex((o) => o.change.path === it.change.path) === i);
1335
+ const originals = /* @__PURE__ */ new Map();
1336
+ for (const { change } of unique) originals.set(change.path, await currentIfUnchanged(change));
1337
+ await privateDir(ctx, ctx.dataDir);
1338
+ await privateDir(ctx, paths.backups);
1339
+ const stamp = ctx.now().toISOString().slice(0, 19).replace(/:/g, "-");
1340
+ const backupDir = join(paths.backups, await uniqueDir(paths.backups, stamp));
1341
+ await privateDir(ctx, backupDir);
1342
+ const entries = [];
1343
+ for (const { cli, change } of unique) {
1344
+ const original = originals.get(change.path) ?? null;
1345
+ let backup = null;
1346
+ if (original !== null) {
1347
+ backup = mirrored(change.path);
1348
+ const dest = join(backupDir, backup);
1349
+ await mkdir(dirname(dest), {
1350
+ recursive: true,
1351
+ mode: 448
1352
+ });
1353
+ await writeFile(dest, original, { mode: 384 });
1354
+ }
1355
+ entries.push({
1356
+ cli,
1357
+ path: change.path,
1358
+ backup,
1359
+ description: change.description,
1360
+ ...change.deleteFile ? {} : { afterSha256: sha256(change.after) }
1344
1361
  });
1345
1362
  }
1363
+ const manifest = {
1364
+ version: 1,
1365
+ createdAt: ctx.now().toISOString(),
1366
+ entries,
1367
+ ...opts.markRestored ? { restoredAt: ctx.now().toISOString() } : {}
1368
+ };
1369
+ const writeManifest = () => writeFile(join(backupDir, MANIFEST_NAME), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 384 });
1370
+ await writeManifest();
1371
+ const io = opts.io ?? realIo;
1372
+ const how = [];
1373
+ const touched = [];
1346
1374
  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`);
1375
+ for (const item of unique) {
1376
+ const { cli, change } = item;
1377
+ let done = false;
1378
+ touched.push(change.path);
1379
+ if (usesCommand(item) && change.viaCommand) {
1380
+ const [bin, ...args] = change.viaCommand;
1381
+ try {
1382
+ const r = await ctx.exec(bin, args);
1383
+ const now = await readBytes(change.path);
1384
+ done = r.code === 0 && now !== null && now.toString("utf8") !== change.before;
1385
+ } catch {
1386
+ done = false;
1387
+ }
1388
+ }
1389
+ if (!done) {
1390
+ await currentIfUnchanged(change);
1391
+ if (change.deleteFile) await io.rm(change.path);
1392
+ else await writeAtomic(change.path, change.after, io);
1393
+ }
1394
+ how.push({
1395
+ cli,
1396
+ path: change.path,
1397
+ via: done ? "command" : "file"
1398
+ });
1360
1399
  }
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;
1400
+ } catch (e) {
1401
+ const notRestored = [];
1402
+ for (const path of touched.reverse()) {
1403
+ const original = originals.get(path) ?? null;
1404
+ try {
1405
+ const now = await readBytes(path);
1406
+ if (original === null ? now === null : now?.equals(original) === true) continue;
1407
+ if (original === null) await io.rm(path);
1408
+ else await writeAtomic(path, original, io);
1409
+ } catch {
1410
+ notRestored.push(path);
1411
+ }
1364
1412
  }
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;
1413
+ const rolledBack = notRestored.length === 0;
1414
+ if (rolledBack) await rm(backupDir, {
1415
+ recursive: true,
1416
+ force: true
1417
+ }).catch(() => void 0);
1418
+ if (e instanceof StaleError) {
1419
+ e.rolledBack = rolledBack;
1420
+ throw e;
1371
1421
  }
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
- }
1422
+ throw new ApplyError(e instanceof Error ? e.message : String(e), rolledBack, notRestored, backupDir, { cause: e });
1423
+ }
1424
+ let rewrite = false;
1425
+ for (const e of entries) {
1426
+ const now = await readBytes(e.path);
1427
+ if (now !== null && sha256(now) !== e.afterSha256) {
1428
+ e.afterSha256 = sha256(now);
1429
+ rewrite = true;
1387
1430
  }
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
1431
  }
1432
+ if (rewrite) await writeManifest();
1433
+ return {
1434
+ backupDir,
1435
+ how
1436
+ };
1394
1437
  }
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) {
1438
+ /** Every manifest that has not been restored yet, newest first. */
1439
+ async function listManifests(ctx) {
1440
+ const { backups } = dataPaths(ctx.platform, ctx.dataDir);
1441
+ const names = (await readdir(backups).catch(() => [])).sort().reverse();
1398
1442
  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
1443
+ for (const name of names) try {
1444
+ const manifest = JSON.parse(await readFile(join(backups, name, MANIFEST_NAME), "utf8"));
1445
+ if (manifest.version === 1 && !manifest.restoredAt) out.push({
1446
+ dir: join(backups, name),
1447
+ manifest
1409
1448
  });
1410
- }
1449
+ } catch {}
1411
1450
  return out;
1412
1451
  }
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
1452
  /**
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.
1453
+ * What uninstall does with one file. `current` is the hash of the file now (null when missing).
1454
+ * The backup is restored only when the file is exactly what init left; any other content means
1455
+ * someone changed it since, so only Conveno's own entries come out.
1424
1456
  */
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
- }
1457
+ function actionFor(entry, current) {
1458
+ if (current === null) return "gone";
1459
+ if (entry.afterSha256 !== void 0 && current === entry.afterSha256) return entry.backup === null ? "remove" : "restore";
1460
+ return "edit";
1459
1461
  }
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--;
1476
- }
1477
- const mid = [];
1478
- const x = a.slice(start, endA);
1479
- const y = b.slice(start, endB);
1480
- if (x.length * y.length > 4e6) {
1481
- for (const line of x) mid.push({
1482
- t: "-",
1483
- line
1484
- });
1485
- for (const line of y) mid.push({
1486
- t: "+",
1487
- line
1488
- });
1489
- } else {
1490
- const w = y.length + 1;
1491
- const lcs = new Uint32Array((x.length + 1) * w);
1492
- for (let i = x.length - 1; i >= 0; i--) for (let j = y.length - 1; j >= 0; j--) lcs[i * w + j] = x[i] === y[j] ? lcs[(i + 1) * w + j + 1] + 1 : Math.max(lcs[(i + 1) * w + j], lcs[i * w + j + 1]);
1493
- let i = 0;
1494
- let j = 0;
1495
- while (i < x.length && j < y.length) if (x[i] === y[j]) {
1496
- mid.push({
1497
- t: " ",
1498
- line: x[i]
1499
- });
1500
- i++;
1501
- j++;
1502
- } else if (lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) mid.push({
1503
- t: "-",
1504
- line: x[i++]
1505
- });
1506
- else mid.push({
1507
- t: "+",
1508
- line: y[j++]
1509
- });
1510
- while (i < x.length) mid.push({
1511
- t: "-",
1512
- line: x[i++]
1513
- });
1514
- while (j < y.length) mid.push({
1515
- t: "+",
1516
- line: y[j++]
1462
+ /**
1463
+ * Predict the actions for all manifests, newest to oldest, following how each restore changes the
1464
+ * file the next (older) manifest sees.
1465
+ */
1466
+ async function previewRestore(manifests) {
1467
+ const state = /* @__PURE__ */ new Map();
1468
+ const rows = [];
1469
+ for (const { dir, manifest } of manifests) for (const entry of manifest.entries) {
1470
+ if (!state.has(entry.path)) {
1471
+ const bytes = await readBytes(entry.path);
1472
+ state.set(entry.path, bytes === null ? null : sha256(bytes));
1473
+ }
1474
+ const action = actionFor(entry, state.get(entry.path) ?? null);
1475
+ rows.push({
1476
+ entry,
1477
+ action
1517
1478
  });
1479
+ if (action === "restore" && entry.backup !== null) state.set(entry.path, sha256(await readFile(join(dir, entry.backup))));
1480
+ else if (action === "remove") state.set(entry.path, null);
1481
+ else if (action === "edit") state.set(entry.path, "unknown");
1518
1482
  }
1519
- return [
1520
- ...a.slice(0, start).map((line) => ({
1521
- t: " ",
1522
- line
1523
- })),
1524
- ...mid,
1525
- ...a.slice(endA).map((line) => ({
1526
- t: " ",
1527
- line
1528
- }))
1529
- ];
1483
+ return rows;
1530
1484
  }
1531
- /** Unified diff body (hunks only) between two texts, `before` null meaning a new file. */
1532
- function unifiedDiff(before, after, context = 2) {
1533
- const ops = diffOps(splitLines(before ?? ""), splitLines(after));
1534
- const changed = ops.flatMap((o, i) => o.t === " " ? [] : [i]);
1535
- if (changed.length === 0) return [];
1536
- const ranges = [];
1537
- for (const i of changed) {
1538
- const lo = Math.max(0, i - context);
1539
- const hi = Math.min(ops.length, i + context + 1);
1540
- const last = ranges.at(-1);
1541
- if (last && lo <= last[1]) last[1] = hi;
1542
- else ranges.push([lo, hi]);
1543
- }
1485
+ /** Restore one file as init found it, when it still matches. Returns the action taken. */
1486
+ async function restoreEntry(dir, entry) {
1487
+ const bytes = await readBytes(entry.path);
1488
+ const action = actionFor(entry, bytes === null ? null : sha256(bytes));
1489
+ if (action === "remove") await rm(entry.path, { force: true });
1490
+ else if (action === "restore" && entry.backup !== null) await writeAtomic(entry.path, await readFile(join(dir, entry.backup)));
1491
+ return action;
1492
+ }
1493
+ async function markRestored(ctx, found) {
1494
+ const done = {
1495
+ ...found.manifest,
1496
+ restoredAt: ctx.now().toISOString()
1497
+ };
1498
+ await writeFile(join(found.dir, MANIFEST_NAME), `${JSON.stringify(done, null, 2)}\n`, { mode: 384 });
1499
+ }
1500
+ // src/init.ts
1501
+ const CODEX_NOTE = "Codex asks you to trust new hooks once: run /hooks inside Codex.";
1502
+ 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";
1503
+ /** Detect every adapter. A detection that throws counts as not installed. */
1504
+ async function detectAll(ctx, adapters = ctx.adapters) {
1505
+ const env = adapterEnv(ctx);
1506
+ return Promise.all(adapters.map(async (adapter) => {
1507
+ try {
1508
+ return {
1509
+ adapter,
1510
+ detection: await adapter.detect(env)
1511
+ };
1512
+ } catch {
1513
+ return {
1514
+ adapter,
1515
+ detection: {
1516
+ installed: false,
1517
+ configPaths: []
1518
+ }
1519
+ };
1520
+ }
1521
+ }));
1522
+ }
1523
+ function parseCliList(raw, ctx) {
1524
+ if (raw === void 0) return ctx.adapters;
1525
+ const names = raw.split(",").map((s) => s.trim()).filter(Boolean);
1544
1526
  const out = [];
1545
- for (const [lo, hi] of ranges) {
1546
- let oldStart = 1;
1547
- let newStart = 1;
1548
- for (const o of ops.slice(0, lo)) {
1549
- if (o.t !== "+") oldStart++;
1550
- if (o.t !== "-") newStart++;
1527
+ for (const n of names) {
1528
+ if (!CLI_KINDS.includes(n)) {
1529
+ const suggestion = closest(n, ctx.adapters.map((a) => a.cli));
1530
+ return {
1531
+ message: `Unknown CLI "${n}". Known CLIs: ${ctx.adapters.map((a) => a.cli).join(", ")}.`,
1532
+ ...suggestion ? { suggestion: `Did you mean ${suggestion}?` } : {}
1533
+ };
1551
1534
  }
1552
- const slice = ops.slice(lo, hi);
1553
- const oldCount = slice.filter((o) => o.t !== "+").length;
1554
- const newCount = slice.filter((o) => o.t !== "-").length;
1555
- const oldFrom = oldCount === 0 ? oldStart - 1 : oldStart;
1556
- out.push(`@@ -${oldFrom},${oldCount} +${newStart},${newCount} @@`);
1557
- for (const o of slice) out.push(`${o.t}${o.line}`);
1535
+ const a = ctx.adapters.find((x) => x.cli === n);
1536
+ if (!a) return { message: `"${n}" is not supported in this version. Supported: ${ctx.adapters.map((x) => x.cli).join(", ")}.` };
1537
+ out.push(a);
1558
1538
  }
1559
1539
  return out;
1560
1540
  }
1561
- /** Colour diff lines with brand roles: added `ok`, removed `error`, hunk headers `quiet`. */
1562
- function paintDiff(theme, lines, indent = " ") {
1563
- return lines.map((l) => {
1564
- const role = l.startsWith("@@") ? "quiet" : l.startsWith("+") ? "ok" : l.startsWith("-") ? "error" : null;
1565
- return indent + (role ? theme.paint(role, l) : l);
1566
- });
1567
- }
1568
- // src/apply.ts
1569
- const MANIFEST_NAME = "manifest.json";
1570
- const isPosix = (ctx) => ctx.platform !== "win32";
1571
- const sha256 = (data) => createHash("sha256").update(data).digest("hex");
1572
- /** A file changed between planning and writing. */
1573
- var StaleError = class extends Error {
1574
- path;
1575
- /** True unless files written earlier in the same run could not be put back. */
1576
- rolledBack = true;
1577
- constructor(path) {
1578
- super(`${path} changed while Conveno was working. Nothing in it was overwritten.`);
1579
- this.path = path;
1580
- this.name = "StaleError";
1581
- }
1582
- };
1583
- /** Will this change be made by the CLI's own command? Yes when the CLI is installed and the plan has one. */
1584
- const usesCommand = (item) => Boolean(item.change.viaCommand) && item.installed;
1585
- /** Print one block per file: path, what changes, the command that will run, the unified diff. */
1586
- function presentChanges(ctx, items) {
1541
+ function printDetections(ctx, found) {
1587
1542
  const t = ctx.theme;
1588
- for (const item of items) {
1589
- const { change } = item;
1590
- ctx.out(` ${t.bold(tilde(change.path, ctx.home))}${change.before === null ? t.paint("quiet", " (new file)") : change.deleteFile ? t.paint("quiet", " (deleted)") : ""}\n`);
1591
- ctx.out(` ${change.description}\n`);
1592
- if (usesCommand(item) && change.viaCommand !== void 0 && change.viaCommand) {
1593
- ctx.out(` ${t.paint("quiet", "will run")} ${t.bold(change.viaCommand.join(" "))}\n`);
1594
- ctx.out(` ${t.paint("quiet", "expected result (the command may format the file differently)")}\n`);
1595
- }
1596
- const body = paintDiff(t, unifiedDiff(change.before, change.after));
1597
- if (body.length > 0) ctx.out(`${body.join("\n")}\n`);
1598
- ctx.out("\n");
1599
- }
1600
- }
1601
- /** `<backups>/files/<path without drive or leading separator>`. */
1602
- const mirrored = (path) => join("files", path.replace(/^[A-Za-z]:/, "").replace(/^[\\/]+/, ""));
1603
- async function uniqueDir(base, stamp) {
1604
- const existing = new Set(await readdir(base).catch(() => []));
1605
- let name = stamp;
1606
- for (let n = 2; existing.has(name); n++) name = `${stamp}-${n}`;
1607
- return name;
1543
+ ctx.out(`${t.bold("Looking for AI coding CLIs on this machine")}\n`);
1544
+ const rows = found.map(({ adapter, detection }) => detection.installed ? [
1545
+ ` ${t.status("ok")} ${adapter.cli}`,
1546
+ adapter.displayName,
1547
+ detection.version ?? "",
1548
+ t.paint("quiet", tilde(detection.configPaths[0] ?? "", ctx.home))
1549
+ ] : [` ${t.glyph("offline")} ${adapter.cli}`, t.paint("quiet", "not found")]);
1550
+ ctx.out(`${columns(rows).join("\n")}\n\n`);
1608
1551
  }
1609
- async function readBytes(path) {
1610
- try {
1611
- return await readFile(path);
1552
+ /** Collect plans from installed adapters. Returns failures instead of throwing. */
1553
+ async function collectPlans(ctx, found, which, baseline, opts = {}) {
1554
+ const env = adapterEnv(ctx, opts);
1555
+ const items = [];
1556
+ const failures = [];
1557
+ for (const { adapter, detection } of found) try {
1558
+ for (const change of await (which === "plan" ? adapter.plan(env) : adapter.uninstallPlan(env, baseline))) items.push({
1559
+ cli: adapter.cli,
1560
+ installed: detection.installed,
1561
+ change
1562
+ });
1612
1563
  } catch (e) {
1613
- if (e.code === "ENOENT") return null;
1614
- throw e;
1564
+ failures.push({
1565
+ cli: adapter.cli,
1566
+ message: plainError(e)
1567
+ });
1615
1568
  }
1569
+ return {
1570
+ items,
1571
+ failures
1572
+ };
1616
1573
  }
1617
- /** Create a directory only the user can use, and tighten one that already exists. */
1618
- async function privateDir(ctx, dir) {
1619
- await mkdir(dir, {
1620
- recursive: true,
1621
- mode: 448
1574
+ function reportFailures(ctx, failures, retry) {
1575
+ for (const f of failures) fail(ctx, {
1576
+ what: `Could not plan changes for ${f.cli}`,
1577
+ detail: [f.message],
1578
+ fix: `Fix the problem above, or run ${cmd(ctx.theme, retry)} to leave ${f.cli} out.`,
1579
+ exit: 1,
1580
+ ref: "e_plan"
1622
1581
  });
1623
- if (isPosix(ctx)) await chmod(dir, 448).catch(() => void 0);
1624
1582
  }
1625
- const realIo = {
1626
- realpath: (p) => realpath(p),
1627
- mkdir: async (p) => void await mkdir(p, { recursive: true }),
1628
- mode: (p) => stat(p).then((s) => s.mode & 511, () => void 0),
1629
- writeFile: (p, data, mode) => writeFile(p, data, { mode }),
1630
- chmod: (p, mode) => chmod(p, mode),
1631
- rename: (a, b) => rename$1(a, b),
1632
- overwrite: async (p, data) => {
1633
- const fh = await open(p, "w");
1634
- try {
1635
- await fh.writeFile(data);
1636
- await fh.sync();
1637
- } finally {
1638
- await fh.close();
1583
+ const staleFailure = (ctx, e, rerun) => fail(ctx, {
1584
+ what: `${tilde(e.path, ctx.home)} changed while Conveno was waiting`,
1585
+ detail: [e.rolledBack ? "Conveno did not overwrite it. Nothing was left changed." : "Conveno did not overwrite it. Some other files may already be changed."],
1586
+ fix: `Run ${cmd(ctx.theme, rerun)} again to plan from the file as it is now.`,
1587
+ exit: 1,
1588
+ ref: "e_stale"
1589
+ });
1590
+ /** Show the plan, confirm, back up, apply. Shared by init and the plan-based uninstall. */
1591
+ async function confirmAndApply(ctx, items, opts) {
1592
+ const t = ctx.theme;
1593
+ const files = new Set(items.map((i) => i.change.path)).size;
1594
+ ctx.out(`${t.bold(`Conveno will change ${plural(files, "file")}.`)} Nothing else is touched.\n\n`);
1595
+ presentChanges(ctx, items);
1596
+ const paths = dataPaths(ctx.platform, ctx.dataDir);
1597
+ ctx.out(` ${t.paint("quiet", `Backups go to ${tilde(paths.backups, ctx.home)}/<timestamp>/`)}\n`);
1598
+ ctx.out(` ${t.paint("quiet", "Undo any time with:")} ${cmd(t, "conveno uninstall")}\n\n`);
1599
+ if (!opts.yes) {
1600
+ if (!ctx.interactive) return { exit: fail(ctx, {
1601
+ what: "Needs a terminal to confirm",
1602
+ detail: ["No changes were made."],
1603
+ fix: `Run ${cmd(t, `${opts.rerun} --yes`)} to apply the changes shown above.`,
1604
+ exit: 2,
1605
+ ref: "e_no_tty"
1606
+ }) };
1607
+ if (!await ctx.confirm(`${opts.verb} these changes?`, true)) {
1608
+ ctx.out(`${t.status("info")} Nothing was changed.\n`);
1609
+ return { exit: 0 };
1639
1610
  }
1640
- },
1641
- rm: (p) => rm(p, { force: true }),
1642
- platform: process.platform
1643
- };
1644
- /**
1645
- * Replace the contents of `path` with `data`, keeping its mode and writing through a symlink.
1646
- *
1647
- * POSIX: write a temp file in the same directory, then rename it over the target, so a reader
1648
- * never sees half a file.
1649
- *
1650
- * Windows: write the target in place (open truncated, write, fsync). Reason, confirmed in the
1651
- * libuv source Node uses: `fs.rename` is `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`, which needs
1652
- * DELETE access to the existing target. That fails with ERROR_ACCESS_DENIED (reported as EPERM,
1653
- * with `err.path` set to the temp file, the source) whenever any other process holds the target
1654
- * open without FILE_SHARE_DELETE. Node itself shares READ, WRITE and DELETE on every handle, but
1655
- * C runtime, Python and .NET defaults share only READ and WRITE, and so may a running CLI or a
1656
- * virus scanner. Truncating in place needs only FILE_SHARE_WRITE from the other handles, so it
1657
- * succeeds in the cases where an atomic replace cannot. The cost is that a reader can see a
1658
- * half-written file for a moment. That is acceptable here because callers re-read the target and
1659
- * compare it with the plan just before writing, and `applyChanges` restores every file from its
1660
- * backup if any write fails. No temp file exists on this path, so none can be left behind.
1661
- */
1662
- async function writeAtomic(path, data, io = realIo) {
1663
- const target = await io.realpath(path).catch(() => path);
1664
- await io.mkdir(dirname(target));
1665
- if (io.platform === "win32") {
1666
- await io.overwrite(target, data);
1667
- return;
1668
1611
  }
1669
- const mode = await io.mode(target);
1670
- const tmp = join(dirname(target), `.${basename(target)}.conveno-${randomBytes(6).toString("hex")}.tmp`);
1671
1612
  try {
1672
- await io.writeFile(tmp, data, mode ?? 420);
1673
- if (mode !== void 0) await io.chmod(tmp, mode);
1674
- await io.rename(tmp, target);
1613
+ return { applied: await applyChanges(ctx, items, opts.markRestored ? { markRestored: true } : {}) };
1675
1614
  } catch (e) {
1676
- if (e instanceof Error && e.path === tmp) e.path = target;
1677
- throw e;
1678
- } finally {
1679
- await io.rm(tmp).catch(() => void 0);
1615
+ if (e instanceof StaleError) return { exit: staleFailure(ctx, e, opts.rerun) };
1616
+ if (e instanceof ApplyError && !e.rolledBack) return { exit: fail(ctx, {
1617
+ what: "Could not write the changes",
1618
+ detail: [plainError(e.cause ?? e), `These files could not be put back and may be changed: ${e.notRestored.map((p) => tilde(p, ctx.home)).join(", ")}.`],
1619
+ fix: `The originals are in ${tilde(e.backupDir, ctx.home)}. Copy them back, then fix the problem and run again.`,
1620
+ exit: 1,
1621
+ ref: "e_write"
1622
+ }) };
1623
+ return { exit: fail(ctx, {
1624
+ what: "Could not write the changes",
1625
+ detail: [plainError(e instanceof ApplyError ? e.cause ?? e : e), "Files already written in this run were restored. Nothing was left changed."],
1626
+ fix: "Close the program that has the file open (a running Claude Code, an editor), then run again.",
1627
+ exit: 1,
1628
+ ref: "e_write"
1629
+ }) };
1680
1630
  }
1681
1631
  }
1682
- /** A write failed. `rolledBack` says whether every file written before it was put back. */
1683
- var ApplyError = class extends Error {
1684
- rolledBack;
1685
- notRestored;
1686
- backupDir;
1687
- constructor(message, rolledBack, notRestored, backupDir, options) {
1688
- super(message, options);
1689
- this.rolledBack = rolledBack;
1690
- this.notRestored = notRestored;
1691
- this.backupDir = backupDir;
1692
- this.name = "ApplyError";
1632
+ async function runInit(ctx, argv) {
1633
+ const outcome = {};
1634
+ const code = await initSetup(ctx, argv, outcome);
1635
+ if (code !== 0 || !outcome.offer) return code;
1636
+ const spec = COMMANDS.find((c) => c.name === "init");
1637
+ const parsed = spec ? parseFlags(ctx, spec, argv) : void 0;
1638
+ const values = typeof parsed === "object" ? parsed.values : {};
1639
+ await offerAcpAdapters(ctx, {
1640
+ installed: outcome.offer,
1641
+ flag: values["acp-adapters"] === true ? true : values["no-acp-adapters"] === true ? false : void 0,
1642
+ yes: values.yes === true
1643
+ });
1644
+ return 0;
1645
+ }
1646
+ async function initSetup(ctx, argv, outcome) {
1647
+ const t = ctx.theme;
1648
+ const started = ctx.now();
1649
+ const spec = COMMANDS.find((c) => c.name === "init");
1650
+ if (!spec) return 2;
1651
+ const parsed = parseFlags(ctx, spec, argv);
1652
+ if (typeof parsed === "number") return parsed;
1653
+ const values = parsed.values;
1654
+ if (values["acp-adapters"] === true && values["no-acp-adapters"] === true) return fail(ctx, {
1655
+ what: "Use --acp-adapters or --no-acp-adapters, not both",
1656
+ fix: `Run ${cmd(t, "conveno init --help")} to see the options.`,
1657
+ exit: 2,
1658
+ ref: "e_usage"
1659
+ });
1660
+ const chosen = parseCliList(typeof values.cli === "string" ? values.cli : void 0, ctx);
1661
+ if (!Array.isArray(chosen)) return fail(ctx, {
1662
+ what: chosen.message,
1663
+ fix: `Pass ${cmd(t, "--cli claude,codex,opencode")} or leave it out.`,
1664
+ ...chosen.suggestion ? { didYouMean: chosen.suggestion } : {},
1665
+ exit: 2,
1666
+ ref: "e_usage"
1667
+ });
1668
+ const found = await detectAll(ctx, chosen);
1669
+ printDetections(ctx, found);
1670
+ const installed = found.filter((f) => f.detection.installed);
1671
+ if (installed.length === 0) return fail(ctx, {
1672
+ what: "No supported AI coding CLI was found",
1673
+ detail: [`Looked for ${chosen.map((a) => a.displayName).join(", ")} on PATH.`],
1674
+ fix: "Install one of them, then run conveno init again.",
1675
+ exit: 1,
1676
+ ref: "e_no_cli"
1677
+ });
1678
+ const withRelay = values["with-permission-relay"] === true;
1679
+ const { items, failures } = await collectPlans(ctx, installed, "plan", void 0, { permissionRelay: withRelay });
1680
+ if (failures.length > 0) {
1681
+ reportFailures(ctx, failures, "conveno init --cli <others>");
1682
+ return 1;
1693
1683
  }
1694
- };
1695
- /** Re-read the file and refuse to go on when it is no longer what the plan was made from. */
1696
- async function currentIfUnchanged(change) {
1697
- const bytes = await readBytes(change.path);
1698
- if (!(change.before === null ? bytes === null : bytes !== null && bytes.toString("utf8") === change.before)) throw new StaleError(change.path);
1699
- return bytes;
1684
+ if (items.length === 0) {
1685
+ ctx.out(`${t.status("ok")} Conveno is already set up for ${installed.map((f) => f.adapter.cli).join(", ")}. Nothing to change.\n`);
1686
+ outcome.offer = installed.map((f) => f.adapter);
1687
+ return 0;
1688
+ }
1689
+ if (values["dry-run"]) {
1690
+ const files = new Set(items.map((i) => i.change.path)).size;
1691
+ ctx.out(`${t.bold(`Conveno would change ${plural(files, "file")}.`)} Nothing else is touched.\n\n`);
1692
+ presentChanges(ctx, items);
1693
+ ctx.out(`${t.status("info")} Dry run: nothing was written. Run ${cmd(t, "conveno init")} to apply.\n`);
1694
+ return 0;
1695
+ }
1696
+ const result = await confirmAndApply(ctx, items, {
1697
+ yes: values.yes === true,
1698
+ verb: "Apply",
1699
+ rerun: withRelay ? "conveno init --with-permission-relay" : "conveno init"
1700
+ });
1701
+ if ("exit" in result) return result.exit;
1702
+ const byCli = /* @__PURE__ */ new Map();
1703
+ for (const h of result.applied.how) byCli.set(h.cli, [...byCli.get(h.cli) ?? [], h.via]);
1704
+ const rows = [...byCli].map(([cli, vias]) => [` ${t.status("ok")} ${cli}`, vias.every((v) => v === "command") ? "configured with the CLI's own command" : "configured"]);
1705
+ ctx.out(`${columns(rows).join("\n")}\n\n`);
1706
+ ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
1707
+ ctx.out(` Backups are in ${tilde(result.applied.backupDir, ctx.home)}.\n`);
1708
+ ctx.out(" Restart open sessions so they pick up Conveno.\n");
1709
+ if (byCli.has("codex")) ctx.out(`${t.status("info")} ${CODEX_NOTE}\n`);
1710
+ if (byCli.has("cursor")) ctx.out(`${t.status("info")} ${CURSOR_NOTE}\n`);
1711
+ ctx.out(` Next: ${cmd(t, "conveno status")} lists your sessions.\n`);
1712
+ outcome.offer = installed.map((f) => f.adapter);
1713
+ return 0;
1714
+ }
1715
+ // src/doctor.ts
1716
+ /** What the plan says about one part: nothing to do, an addition, or an update to what is there. */
1717
+ function partState(changes, component) {
1718
+ const mine = changes.filter((c) => c.component === component);
1719
+ if (mine.length === 0) return "ok";
1720
+ return mine.some((c) => c.kind === "add") ? "missing" : "outdated";
1700
1721
  }
1722
+ /** Time allowed for the one process-table query. */
1723
+ const ANCESTRY_TIMEOUT_MS = 5e3;
1724
+ const tierWord = (t) => t === "next_turn" ? "next turn" : t;
1725
+ const hasAny = (c) => c !== void 0 && (c.nextTurn || c.endOfTurn || c.idleWake);
1701
1726
  /**
1702
- * Back up every file we will touch, write the manifest, then apply. Each file is re-read first,
1703
- * so a change made after the plan was shown is never overwritten.
1727
+ * The delivery tiers that work right now for one CLI: what the adapter can do for this version,
1728
+ * once its hooks (or plugin) are in place. Without them only the inbox tool is left.
1704
1729
  */
1705
- async function applyChanges(ctx, items, opts = {}) {
1706
- const paths = dataPaths(ctx.platform, ctx.dataDir);
1707
- const unique = items.filter((it, i) => items.findIndex((o) => o.change.path === it.change.path) === i);
1708
- const originals = /* @__PURE__ */ new Map();
1709
- for (const { change } of unique) originals.set(change.path, await currentIfUnchanged(change));
1710
- await privateDir(ctx, ctx.dataDir);
1711
- await privateDir(ctx, paths.backups);
1712
- const stamp = ctx.now().toISOString().slice(0, 19).replace(/:/g, "-");
1713
- const backupDir = join(paths.backups, await uniqueDir(paths.backups, stamp));
1714
- await privateDir(ctx, backupDir);
1715
- const entries = [];
1716
- for (const { cli, change } of unique) {
1717
- const original = originals.get(change.path) ?? null;
1718
- let backup = null;
1719
- if (original !== null) {
1720
- backup = mirrored(change.path);
1721
- const dest = join(backupDir, backup);
1722
- await mkdir(dirname(dest), {
1723
- recursive: true,
1724
- mode: 448
1725
- });
1726
- await writeFile(dest, original, { mode: 384 });
1727
- }
1728
- entries.push({
1729
- cli,
1730
- path: change.path,
1731
- backup,
1732
- description: change.description,
1733
- ...change.deleteFile ? {} : { afterSha256: sha256(change.after) }
1734
- });
1730
+ function activeTiers(row) {
1731
+ const caps = row.adapter.delivery?.(row.detection);
1732
+ if (!caps) return row.adapter.deliveryTier === "inbox" || row.hooks === "ok" ? [tierWord(row.adapter.deliveryTier)] : ["inbox"];
1733
+ if (!hasAny(caps) || row.hooks !== "ok") return ["inbox"];
1734
+ return [
1735
+ ...caps.nextTurn ? ["next turn"] : [],
1736
+ ...caps.endOfTurn ? ["end of turn"] : [],
1737
+ ...caps.idleWake ? ["idle wake"] : []
1738
+ ];
1739
+ }
1740
+ async function inspect(ctx, adapter) {
1741
+ const env = adapterEnv(ctx);
1742
+ let detection;
1743
+ try {
1744
+ detection = await adapter.detect(env);
1745
+ } catch {
1746
+ detection = {
1747
+ installed: false,
1748
+ configPaths: []
1749
+ };
1735
1750
  }
1736
- const manifest = {
1737
- version: 1,
1738
- createdAt: ctx.now().toISOString(),
1739
- entries,
1740
- ...opts.markRestored ? { restoredAt: ctx.now().toISOString() } : {}
1751
+ if (!detection.installed) return {
1752
+ adapter,
1753
+ detection,
1754
+ mcp: null,
1755
+ hooks: null
1741
1756
  };
1742
- const writeManifest = () => writeFile(join(backupDir, MANIFEST_NAME), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 384 });
1743
- await writeManifest();
1744
- const io = opts.io ?? realIo;
1745
- const how = [];
1746
- const touched = [];
1757
+ const hasHooks = adapter.deliveryTier !== "inbox" || hasAny(adapter.delivery?.(detection));
1747
1758
  try {
1748
- for (const item of unique) {
1749
- const { cli, change } = item;
1750
- let done = false;
1751
- touched.push(change.path);
1752
- if (usesCommand(item) && change.viaCommand) {
1753
- const [bin, ...args] = change.viaCommand;
1754
- try {
1755
- const r = await ctx.exec(bin, args);
1756
- const now = await readBytes(change.path);
1757
- done = r.code === 0 && now !== null && now.toString("utf8") !== change.before;
1758
- } catch {
1759
- done = false;
1760
- }
1761
- }
1762
- if (!done) {
1763
- await currentIfUnchanged(change);
1764
- if (change.deleteFile) await io.rm(change.path);
1765
- else await writeAtomic(change.path, change.after, io);
1766
- }
1767
- how.push({
1768
- cli,
1769
- path: change.path,
1770
- via: done ? "command" : "file"
1771
- });
1772
- }
1759
+ const changes = await adapter.plan(env);
1760
+ return {
1761
+ adapter,
1762
+ detection,
1763
+ mcp: partState(changes, "mcp"),
1764
+ hooks: hasHooks ? partState(changes, "hooks") : null
1765
+ };
1773
1766
  } catch (e) {
1774
- const notRestored = [];
1775
- for (const path of touched.reverse()) {
1776
- const original = originals.get(path) ?? null;
1777
- try {
1778
- const now = await readBytes(path);
1779
- if (original === null ? now === null : now?.equals(original) === true) continue;
1780
- if (original === null) await io.rm(path);
1781
- else await writeAtomic(path, original, io);
1782
- } catch {
1783
- notRestored.push(path);
1784
- }
1785
- }
1786
- const rolledBack = notRestored.length === 0;
1787
- if (rolledBack) await rm(backupDir, {
1788
- recursive: true,
1789
- force: true
1790
- }).catch(() => void 0);
1791
- if (e instanceof StaleError) {
1792
- e.rolledBack = rolledBack;
1793
- throw e;
1794
- }
1795
- throw new ApplyError(e instanceof Error ? e.message : String(e), rolledBack, notRestored, backupDir, { cause: e });
1796
- }
1797
- let rewrite = false;
1798
- for (const e of entries) {
1799
- const now = await readBytes(e.path);
1800
- if (now !== null && sha256(now) !== e.afterSha256) {
1801
- e.afterSha256 = sha256(now);
1802
- rewrite = true;
1803
- }
1767
+ return {
1768
+ adapter,
1769
+ detection,
1770
+ mcp: "missing",
1771
+ hooks: hasHooks ? "missing" : null,
1772
+ planError: plainError(e)
1773
+ };
1804
1774
  }
1805
- if (rewrite) await writeManifest();
1806
- return {
1807
- backupDir,
1808
- how
1809
- };
1810
1775
  }
1811
- /** Every manifest that has not been restored yet, newest first. */
1812
- async function listManifests(ctx) {
1813
- const { backups } = dataPaths(ctx.platform, ctx.dataDir);
1814
- const names = (await readdir(backups).catch(() => [])).sort().reverse();
1815
- const out = [];
1816
- for (const name of names) try {
1817
- const manifest = JSON.parse(await readFile(join(backups, name, MANIFEST_NAME), "utf8"));
1818
- if (manifest.version === 1 && !manifest.restoredAt) out.push({
1819
- dir: join(backups, name),
1820
- manifest
1821
- });
1822
- } catch {}
1823
- return out;
1824
- }
1825
- /**
1826
- * What uninstall does with one file. `current` is the hash of the file now (null when missing).
1827
- * The backup is restored only when the file is exactly what init left; any other content means
1828
- * someone changed it since, so only Conveno's own entries come out.
1829
- */
1830
- function actionFor(entry, current) {
1831
- if (current === null) return "gone";
1832
- if (entry.afterSha256 !== void 0 && current === entry.afterSha256) return entry.backup === null ? "remove" : "restore";
1833
- return "edit";
1776
+ /** A note for a CLI outside the tested range. Newer is a warning, older than the minimum a problem. */
1777
+ function versionBlock(t, adapter, version, status) {
1778
+ const name = adapter.displayName;
1779
+ if (status.kind === "older") return {
1780
+ problem: true,
1781
+ text: errorBlock(t, {
1782
+ what: `${name} ${version} is older than Conveno supports`,
1783
+ detail: [`Conveno needs ${name} ${status.minimum} or newer.`],
1784
+ fix: `Upgrade ${name}, then run ${cmd(t, "conveno doctor")} again.`,
1785
+ exit: 1,
1786
+ ref: "e_cli_old"
1787
+ })
1788
+ };
1789
+ if (status.kind === "newer") return {
1790
+ problem: false,
1791
+ 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.")
1792
+ };
1834
1793
  }
1835
- /**
1836
- * Predict the actions for all manifests, newest to oldest, following how each restore changes the
1837
- * file the next (older) manifest sees.
1838
- */
1839
- async function previewRestore(manifests) {
1840
- const state = /* @__PURE__ */ new Map();
1841
- const rows = [];
1842
- for (const { dir, manifest } of manifests) for (const entry of manifest.entries) {
1843
- if (!state.has(entry.path)) {
1844
- const bytes = await readBytes(entry.path);
1845
- state.set(entry.path, bytes === null ? null : sha256(bytes));
1846
- }
1847
- const action = actionFor(entry, state.get(entry.path) ?? null);
1848
- rows.push({
1849
- entry,
1850
- action
1794
+ async function runDoctor(ctx, argv = []) {
1795
+ const t = ctx.theme;
1796
+ const spec = COMMANDS.find((c) => c.name === "doctor");
1797
+ let adapters = ctx.adapters;
1798
+ if (spec) {
1799
+ const parsed = parseFlags(ctx, spec, argv);
1800
+ if (typeof parsed === "number") return parsed;
1801
+ const chosen = parseCliList(typeof parsed.values.cli === "string" ? parsed.values.cli : void 0, ctx);
1802
+ if (!Array.isArray(chosen)) return fail(ctx, {
1803
+ what: chosen.message,
1804
+ fix: `Pass ${cmd(t, "--cli claude,codex,opencode")} or leave it out.`,
1805
+ ...chosen.suggestion ? { didYouMean: chosen.suggestion } : {},
1806
+ exit: 2,
1807
+ ref: "e_usage"
1851
1808
  });
1852
- if (action === "restore" && entry.backup !== null) state.set(entry.path, sha256(await readFile(join(dir, entry.backup))));
1853
- else if (action === "remove") state.set(entry.path, null);
1854
- else if (action === "edit") state.set(entry.path, "unknown");
1809
+ adapters = chosen;
1855
1810
  }
1856
- return rows;
1857
- }
1858
- /** Restore one file as init found it, when it still matches. Returns the action taken. */
1859
- async function restoreEntry(dir, entry) {
1860
- const bytes = await readBytes(entry.path);
1861
- 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)));
1864
- return action;
1865
- }
1866
- async function markRestored(ctx, found) {
1867
- const done = {
1868
- ...found.manifest,
1869
- restoredAt: ctx.now().toISOString()
1870
- };
1871
- await writeFile(join(found.dir, MANIFEST_NAME), `${JSON.stringify(done, null, 2)}\n`, { mode: 384 });
1872
- }
1873
- // 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";
1876
- /** Detect every adapter. A detection that throws counts as not installed. */
1877
- async function detectAll(ctx, adapters = ctx.adapters) {
1878
- const env = adapterEnv(ctx);
1879
- return Promise.all(adapters.map(async (adapter) => {
1811
+ let ok = 0;
1812
+ let warnings = 0;
1813
+ let problems = 0;
1814
+ const notes = [];
1815
+ let daemonLine;
1816
+ try {
1817
+ const client = await ctx.connect(connectOpts(ctx, false));
1880
1818
  try {
1881
- return {
1882
- adapter,
1883
- detection: await adapter.detect(env)
1884
- };
1885
- } catch {
1886
- return {
1887
- adapter,
1888
- detection: {
1889
- installed: false,
1890
- configPaths: []
1891
- }
1892
- };
1819
+ const { sessions } = await client["session.list"]({ includeOffline: true });
1820
+ daemonLine = [` ${t.status("ok")} daemon`, `running, ${plural(sessions.length, "session")}`];
1821
+ ok++;
1822
+ } finally {
1823
+ await client.close().catch(() => void 0);
1893
1824
  }
1894
- }));
1895
- }
1896
- function parseCliList(raw, ctx) {
1897
- if (raw === void 0) return ctx.adapters;
1898
- const names = raw.split(",").map((s) => s.trim()).filter(Boolean);
1899
- const out = [];
1900
- for (const n of names) {
1901
- if (!CLI_KINDS.includes(n)) {
1902
- const suggestion = closest(n, ctx.adapters.map((a) => a.cli));
1903
- return {
1904
- message: `Unknown CLI "${n}". Known CLIs: ${ctx.adapters.map((a) => a.cli).join(", ")}.`,
1905
- ...suggestion ? { suggestion: `Did you mean ${suggestion}?` } : {}
1906
- };
1825
+ } catch (e) {
1826
+ const problem = daemonProblem(t, e);
1827
+ if (problem.notRunning) {
1828
+ daemonLine = [` ${t.status("warn")} daemon`, "not running"];
1829
+ warnings++;
1830
+ notes.push(warnBlock(t, "The Conveno daemon is not running.", problem.fix, problem.why));
1831
+ } else {
1832
+ daemonLine = [` ${t.status("error")} daemon`, "cannot be reached"];
1833
+ problems++;
1834
+ notes.push(errorBlock(t, {
1835
+ what: "The Conveno daemon cannot be reached",
1836
+ detail: [problem.why],
1837
+ fix: problem.fix,
1838
+ exit: 1,
1839
+ ref: "e_daemon"
1840
+ }));
1907
1841
  }
1908
- const a = ctx.adapters.find((x) => x.cli === n);
1909
- if (!a) return { message: `"${n}" is not supported in this version. Supported: ${ctx.adapters.map((x) => x.cli).join(", ")}.` };
1910
- out.push(a);
1911
1842
  }
1912
- return out;
1913
- }
1914
- function printDetections(ctx, found) {
1915
- const t = ctx.theme;
1916
- ctx.out(`${t.bold("Looking for AI coding CLIs on this machine")}\n`);
1917
- const rows = found.map(({ adapter, detection }) => detection.installed ? [
1918
- ` ${t.status("ok")} ${adapter.cli}`,
1919
- adapter.displayName,
1920
- detection.version ?? "",
1921
- t.paint("quiet", tilde(detection.configPaths[0] ?? "", ctx.home))
1922
- ] : [` ${t.glyph("offline")} ${adapter.cli}`, t.paint("quiet", "not found")]);
1923
- ctx.out(`${columns(rows).join("\n")}\n\n`);
1924
- }
1925
- /** 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);
1928
- const items = [];
1929
- const failures = [];
1930
- 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
- });
1936
- } catch (e) {
1937
- failures.push({
1938
- cli: adapter.cli,
1939
- message: plainError(e)
1940
- });
1843
+ ctx.out(`${columns([daemonLine]).join("\n")}\n\n`);
1844
+ if (!(await ctx.ancestry(ANCESTRY_TIMEOUT_MS)).complete) {
1845
+ warnings++;
1846
+ 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."));
1941
1847
  }
1942
- return {
1943
- items,
1944
- failures
1945
- };
1946
- }
1947
- function reportFailures(ctx, failures, retry) {
1948
- for (const f of failures) fail(ctx, {
1949
- what: `Could not plan changes for ${f.cli}`,
1950
- detail: [f.message],
1951
- fix: `Fix the problem above, or run ${cmd(ctx.theme, retry)} to leave ${f.cli} out.`,
1952
- exit: 1,
1953
- ref: "e_plan"
1954
- });
1955
- }
1956
- const staleFailure = (ctx, e, rerun) => fail(ctx, {
1957
- what: `${tilde(e.path, ctx.home)} changed while Conveno was waiting`,
1958
- detail: [e.rolledBack ? "Conveno did not overwrite it. Nothing was left changed." : "Conveno did not overwrite it. Some other files may already be changed."],
1959
- fix: `Run ${cmd(ctx.theme, rerun)} again to plan from the file as it is now.`,
1960
- exit: 1,
1961
- ref: "e_stale"
1962
- });
1963
- /** Show the plan, confirm, back up, apply. Shared by init and the plan-based uninstall. */
1964
- async function confirmAndApply(ctx, items, opts) {
1965
- const t = ctx.theme;
1966
- 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`);
1968
- presentChanges(ctx, items);
1969
- const paths = dataPaths(ctx.platform, ctx.dataDir);
1970
- ctx.out(` ${t.paint("quiet", `Backups go to ${tilde(paths.backups, ctx.home)}/<timestamp>/`)}\n`);
1971
- ctx.out(` ${t.paint("quiet", "Undo any time with:")} ${cmd(t, "conveno uninstall")}\n\n`);
1972
- if (!opts.yes) {
1973
- if (!ctx.interactive) return { exit: fail(ctx, {
1974
- what: "Needs a terminal to confirm",
1975
- detail: ["No changes were made."],
1976
- fix: `Run ${cmd(t, `${opts.rerun} --yes`)} to apply the changes shown above.`,
1977
- exit: 2,
1978
- ref: "e_no_tty"
1979
- }) };
1980
- if (!await ctx.confirm(`${opts.verb} these changes?`, true)) {
1981
- ctx.out(`${t.status("info")} Nothing was changed.\n`);
1982
- return { exit: 0 };
1848
+ const rows = await Promise.all(adapters.map((a) => inspect(ctx, a)));
1849
+ const q = (w) => t.paint("quiet", w);
1850
+ const table = [[
1851
+ ` ${q("CLI")}`,
1852
+ q("NAME"),
1853
+ q("VERSION"),
1854
+ q("MCP"),
1855
+ q("HOOKS"),
1856
+ q("DELIVERY"),
1857
+ q("NOTE")
1858
+ ]];
1859
+ const yesNo = (v) => v === null ? q("n/a") : v === "ok" ? "yes" : t.paint("warn", v === "missing" ? "not configured" : "needs update");
1860
+ for (const r of rows) {
1861
+ const { adapter, detection } = r;
1862
+ if (!detection.installed) {
1863
+ table.push([
1864
+ ` ${t.glyph("offline")} ${adapter.cli}`,
1865
+ adapter.displayName,
1866
+ "",
1867
+ "",
1868
+ "",
1869
+ "",
1870
+ q("not found on PATH")
1871
+ ]);
1872
+ continue;
1873
+ }
1874
+ const good = r.mcp === "ok" && (r.hooks === null || r.hooks === "ok") && !r.planError;
1875
+ const compat = compatStatus(adapter.cli, detection.version, ctx.compat);
1876
+ const tiers = activeTiers(r);
1877
+ 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";
1878
+ if (!good) note = r.planError ? "config could not be read" : r.mcp === "outdated" || r.hooks === "outdated" ? "needs an update" : "not fully configured";
1879
+ if (compat.kind === "older") note = `older than the minimum ${compat.minimum}`;
1880
+ else if (compat.kind === "newer" && good) note = `newer than tested (${compat.verified})`;
1881
+ const glyph = compat.kind === "older" ? t.status("error") : good && compat.kind !== "newer" ? t.status("ok") : t.status("warn");
1882
+ table.push([
1883
+ ` ${glyph} ${adapter.cli}`,
1884
+ adapter.displayName,
1885
+ detection.version ?? "",
1886
+ yesNo(r.mcp),
1887
+ yesNo(r.hooks),
1888
+ tiers.join(", "),
1889
+ q(note)
1890
+ ]);
1891
+ if (r.planError) {
1892
+ problems++;
1893
+ notes.push(errorBlock(t, {
1894
+ what: `${adapter.displayName} config could not be read`,
1895
+ detail: [r.planError],
1896
+ fix: "Repair the file named above, then run conveno doctor again.",
1897
+ exit: 1,
1898
+ ref: "e_config"
1899
+ }));
1900
+ } else if (good) {
1901
+ if (compat.kind === "ok" || compat.kind === "unknown") ok++;
1902
+ } else {
1903
+ warnings++;
1904
+ const named = [["the MCP server", r.mcp], ["the hooks", r.hooks]];
1905
+ const list = (state) => named.filter(([, s]) => s === state).map(([n]) => n).join(" and ");
1906
+ const missing = list("missing");
1907
+ const outdated = list("outdated");
1908
+ const fix = `Run ${cmd(t, "conveno init")}, then restart open ${adapter.displayName} sessions.`;
1909
+ 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.`));
1910
+ }
1911
+ const versionNote = versionBlock(t, adapter, detection.version, compat);
1912
+ if (versionNote) {
1913
+ notes.push(versionNote.text);
1914
+ if (versionNote.problem) problems++;
1915
+ else warnings++;
1983
1916
  }
1984
1917
  }
1918
+ ctx.out(`${columns(table).join("\n")}\n`);
1919
+ 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`);
1920
+ const acpLines = acpDoctorLines(ctx, rows.filter((r) => r.detection.installed).map((r) => r.adapter.cli));
1921
+ if (acpLines.length > 0) ctx.out(`${acpLines.join("\n")}\n`);
1922
+ const relayRows = [];
1923
+ for (const r of rows) {
1924
+ if (!r.detection.installed || !r.adapter.permissionHookInstalled || r.planError) continue;
1925
+ const installed = await r.adapter.permissionHookInstalled(adapterEnv(ctx)).catch(() => false);
1926
+ relayRows.push([` ${r.adapter.cli}`, q(installed ? "permission relay: hook installed (off until turned on per session)" : "permission relay: not installed (optional)")]);
1927
+ }
1928
+ if (relayRows.length > 0) ctx.out(`\n${columns(relayRows).join("\n")}\n`);
1929
+ if (!rows.some((r) => r.detection.installed)) {
1930
+ notes.push(warnBlock(t, "No supported AI coding CLI was found on PATH.", "Install Claude Code, Codex CLI or OpenCode, then run conveno init."));
1931
+ warnings++;
1932
+ }
1933
+ for (const n of notes) ctx.err(`\n${n.trimEnd()}\n`);
1934
+ ctx.out(`\n${ok} ok, ${plural(warnings, "warning")}, ${plural(problems, "problem")}\n`);
1935
+ return problems > 0 ? 1 : 0;
1936
+ }
1937
+ // src/version.ts
1938
+ const VERSION = "0.2.0-rc.2";
1939
+ // src/errorLog.ts
1940
+ /** The message of an unexpected error, as it is. Not the softened text `plainError` gives. */
1941
+ function rawMessage(e) {
1942
+ if (e instanceof Error) return `${e.name}: ${e.message}`;
1943
+ return String(e);
1944
+ }
1945
+ /**
1946
+ * Write the full stack of an unexpected error to `<data dir>/logs/<timestamp>-error.log`, readable
1947
+ * by the user only. Returns the path, or undefined when the log could not be written (the error is
1948
+ * still reported, just without a log).
1949
+ */
1950
+ async function writeErrorLog(ctx, argv, e) {
1985
1951
  try {
1986
- return { applied: await applyChanges(ctx, items, opts.markRestored ? { markRestored: true } : {}) };
1987
- } catch (e) {
1988
- if (e instanceof StaleError) return { exit: staleFailure(ctx, e, opts.rerun) };
1989
- if (e instanceof ApplyError && !e.rolledBack) return { exit: fail(ctx, {
1990
- what: "Could not write the changes",
1991
- detail: [plainError(e.cause ?? e), `These files could not be put back and may be changed: ${e.notRestored.map((p) => tilde(p, ctx.home)).join(", ")}.`],
1992
- fix: `The originals are in ${tilde(e.backupDir, ctx.home)}. Copy them back, then fix the problem and run again.`,
1993
- exit: 1,
1994
- ref: "e_write"
1995
- }) };
1996
- return { exit: fail(ctx, {
1997
- what: "Could not write the changes",
1998
- detail: [plainError(e instanceof ApplyError ? e.cause ?? e : e), "Files already written in this run were restored. Nothing was left changed."],
1999
- fix: "Close the program that has the file open (a running Claude Code, an editor), then run again.",
2000
- exit: 1,
2001
- ref: "e_write"
2002
- }) };
1952
+ const dir = dataPaths(ctx.platform, ctx.dataDir).logs;
1953
+ await mkdir(dir, {
1954
+ recursive: true,
1955
+ mode: 448
1956
+ });
1957
+ const stamp = ctx.now().toISOString().replace(/[:.]/g, "-");
1958
+ const file = join(dir, `${stamp}-error.log`);
1959
+ const command = argv.slice(0, 2).join(" ");
1960
+ const text = [
1961
+ `conveno ${VERSION} ${command}`,
1962
+ "ref e_internal",
1963
+ `time ${ctx.now().toISOString()}`,
1964
+ `platform ${ctx.platform}, node ${process.version}`,
1965
+ "",
1966
+ e instanceof Error ? e.stack ?? rawMessage(e) : rawMessage(e),
1967
+ e instanceof Error && e.cause !== void 0 ? `\nCaused by: ${e.cause instanceof Error ? e.cause.stack ?? rawMessage(e.cause) : String(e.cause)}` : "",
1968
+ ""
1969
+ ].join("\n");
1970
+ await writeFile(file, text, { mode: 384 });
1971
+ await chmod(file, 384).catch(() => void 0);
1972
+ return file;
1973
+ } catch {
1974
+ return;
2003
1975
  }
2004
1976
  }
2005
- async function runInit(ctx, argv) {
2006
- 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");
2010
- const parsed = spec ? parseFlags(ctx, spec, argv) : void 0;
2011
- const values = typeof parsed === "object" ? parsed.values : {};
2012
- await offerAcpAdapters(ctx, {
2013
- installed: outcome.offer,
2014
- flag: values["acp-adapters"] === true ? true : values["no-acp-adapters"] === true ? false : void 0,
2015
- yes: values.yes === true
2016
- });
2017
- return 0;
1977
+ // src/forget.ts
1978
+ const UNIT_MS = {
1979
+ m: 6e4,
1980
+ h: 36e5,
1981
+ d: 864e5
1982
+ };
1983
+ /** `30m`, `24h` or `7d` as milliseconds, or undefined when the text is anything else. */
1984
+ function parseDuration(text) {
1985
+ const m = /^(\d{1,6})([mhd])$/.exec(text);
1986
+ if (!m) return void 0;
1987
+ const ms = Number(m[1]) * UNIT_MS[m[2]];
1988
+ return ms > 0 ? ms : void 0;
2018
1989
  }
2019
- async function initSetup(ctx, argv, outcome) {
1990
+ /** Rebuild the command line the user typed, for the "run it again with --yes" hint. */
1991
+ function rerunLine(names, flags) {
1992
+ return [
1993
+ "conveno forget",
1994
+ ...names.map((n) => n.includes("*") ? `'${n}'` : n),
1995
+ ...flags.offline ? ["--offline"] : [],
1996
+ ...flags.olderThan ? ["--older-than", flags.olderThan] : []
1997
+ ].join(" ");
1998
+ }
1999
+ async function runForget(ctx, argv) {
2020
2000
  const t = ctx.theme;
2021
- const started = ctx.now();
2022
- const spec = COMMANDS.find((c) => c.name === "init");
2001
+ const spec = COMMANDS.find((c) => c.name === "forget");
2023
2002
  if (!spec) return 2;
2024
2003
  const parsed = parseFlags(ctx, spec, argv);
2025
2004
  if (typeof parsed === "number") return parsed;
2026
- const values = parsed.values;
2027
- if (values["acp-adapters"] === true && values["no-acp-adapters"] === true) return fail(ctx, {
2028
- what: "Use --acp-adapters or --no-acp-adapters, not both",
2029
- fix: `Run ${cmd(t, "conveno init --help")} to see the options.`,
2005
+ const names = parsed.positionals;
2006
+ const offline = parsed.values.offline === true;
2007
+ const olderThan = typeof parsed.values["older-than"] === "string" ? parsed.values["older-than"] : void 0;
2008
+ const dryRun = parsed.values["dry-run"] === true;
2009
+ const yes = parsed.values.yes === true;
2010
+ const help = `Run ${cmd(t, "conveno forget --help")} to see the options.`;
2011
+ for (const n of names) if (!SessionNamePattern.safeParse(n).success) return fail(ctx, {
2012
+ what: `"${n}" is not a session name or pattern`,
2013
+ detail: ["Names use lowercase letters, digits and \".\", \"_\", \"@\" or \"-\". A \"*\" matches any run of characters."],
2014
+ fix: `Run ${cmd(t, "conveno status --all")} to see the names.`,
2030
2015
  exit: 2,
2031
2016
  ref: "e_usage"
2032
2017
  });
2033
- const chosen = parseCliList(typeof values.cli === "string" ? values.cli : void 0, ctx);
2034
- if (!Array.isArray(chosen)) return fail(ctx, {
2035
- what: chosen.message,
2036
- fix: `Pass ${cmd(t, "--cli claude,codex,opencode")} or leave it out.`,
2037
- ...chosen.suggestion ? { didYouMean: chosen.suggestion } : {},
2018
+ let olderThanMs;
2019
+ if (olderThan !== void 0) {
2020
+ olderThanMs = parseDuration(olderThan);
2021
+ if (olderThanMs === void 0) return fail(ctx, {
2022
+ what: `"${olderThan}" is not a duration`,
2023
+ detail: ["Use a whole number and a unit: 30m for minutes, 24h for hours, 7d for days."],
2024
+ fix: help,
2025
+ exit: 2,
2026
+ ref: "e_usage"
2027
+ });
2028
+ }
2029
+ if (names.length === 0 && !offline && olderThanMs === void 0) return fail(ctx, {
2030
+ what: "conveno forget needs to know which sessions to forget",
2031
+ detail: ["Name them, or pass --offline for every offline session."],
2032
+ fix: `For example ${cmd(t, "conveno forget 'conveno-real-*'")} or ${cmd(t, "conveno forget --offline --older-than 7d")}.`,
2038
2033
  exit: 2,
2039
2034
  ref: "e_usage"
2040
2035
  });
2041
- const found = await detectAll(ctx, chosen);
2042
- printDetections(ctx, found);
2043
- const installed = found.filter((f) => f.detection.installed);
2044
- if (installed.length === 0) return fail(ctx, {
2045
- what: "No supported AI coding CLI was found",
2046
- detail: [`Looked for ${chosen.map((a) => a.displayName).join(", ")} on PATH.`],
2047
- fix: "Install one of them, then run conveno init again.",
2048
- exit: 1,
2049
- ref: "e_no_cli"
2050
- });
2051
- const withRelay = values["with-permission-relay"] === true;
2052
- const { items, failures } = await collectPlans(ctx, installed, "plan", void 0, { permissionRelay: withRelay });
2053
- if (failures.length > 0) {
2054
- reportFailures(ctx, failures, "conveno init --cli <others>");
2055
- return 1;
2056
- }
2057
- if (items.length === 0) {
2058
- ctx.out(`${t.status("ok")} Conveno is already set up for ${installed.map((f) => f.adapter.cli).join(", ")}. Nothing to change.\n`);
2059
- outcome.offer = installed.map((f) => f.adapter);
2060
- return 0;
2036
+ let client;
2037
+ try {
2038
+ client = await ctx.connect(connectOpts(ctx, false));
2039
+ } catch (e) {
2040
+ const problem = daemonProblem(t, e);
2041
+ return fail(ctx, {
2042
+ what: problem.notRunning ? "The Conveno daemon is not running" : "The Conveno daemon cannot be reached",
2043
+ detail: [problem.notRunning ? "Sessions live in the daemon, so there is nothing to forget until it runs." : problem.why],
2044
+ fix: problem.notRunning ? `Run ${cmd(t, "conveno daemon start")}.` : problem.fix,
2045
+ exit: 1,
2046
+ ref: "e_daemon"
2047
+ });
2061
2048
  }
2062
- if (values["dry-run"]) {
2063
- 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`);
2065
- presentChanges(ctx, items);
2066
- ctx.out(`${t.status("info")} Dry run: nothing was written. Run ${cmd(t, "conveno init")} to apply.\n`);
2049
+ try {
2050
+ const selector = {
2051
+ ...names.length > 0 ? { names } : {},
2052
+ ...names.length === 0 || olderThanMs !== void 0 ? { olderThanMs: olderThanMs ?? 0 } : {}
2053
+ };
2054
+ const preview = await client["session.forget"]({
2055
+ ...selector,
2056
+ dryRun: true
2057
+ });
2058
+ const ids = new Set(preview.forgotten.map((s) => s.id));
2059
+ const picked = (await client["session.list"]({ includeOffline: true })).sessions.filter((s) => ids.has(s.id));
2060
+ if (preview.skippedOnline.length > 0) {
2061
+ ctx.out(`${t.status("warn")} ${t.bold(`Skipped ${plural(preview.skippedOnline.length, "online session")}`)}\n`);
2062
+ 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`);
2063
+ }
2064
+ if (picked.length === 0) {
2065
+ ctx.out(`${t.status("info")} Nothing to forget. ${t.paint("quiet", `${cmd(t, "conveno status --all")} lists the offline sessions.`)}\n`);
2066
+ return 0;
2067
+ }
2068
+ ctx.out(`${t.bold(dryRun ? `Would forget ${plural(picked.length, "session")}` : `Will forget ${plural(picked.length, "session")}`)}\n\n`);
2069
+ ctx.out(`${renderSessions(ctx, picked)}\n\n`);
2070
+ ctx.out(` ${t.paint("quiet", "Their queued messages are deleted too. Messages they sent stay with the receivers.")}\n\n`);
2071
+ if (dryRun) {
2072
+ ctx.out(`${t.status("info")} Dry run. Nothing was changed.\n`);
2073
+ return 0;
2074
+ }
2075
+ if (!yes) {
2076
+ if (!ctx.interactive) return fail(ctx, {
2077
+ what: "Needs a terminal to confirm",
2078
+ detail: ["No sessions were forgotten."],
2079
+ fix: `Run ${cmd(t, `${rerunLine(names, {
2080
+ offline,
2081
+ ...olderThan ? { olderThan } : {}
2082
+ })} --yes`)} to forget the sessions listed above.`,
2083
+ exit: 2,
2084
+ ref: "e_no_tty"
2085
+ });
2086
+ if (!await ctx.confirm(`Forget ${plural(picked.length, "session")}?`, false)) {
2087
+ ctx.out(`${t.status("info")} Nothing was changed.\n`);
2088
+ return 0;
2089
+ }
2090
+ }
2091
+ const done = await client["session.forget"]({ ids: [...ids] });
2092
+ ctx.out(`${t.status("ok")} ${t.bold("Done.")} Forgot ${plural(done.forgotten.length, "session")}.\n`);
2067
2093
  return 0;
2094
+ } finally {
2095
+ await client.close().catch(() => void 0);
2068
2096
  }
2069
- const result = await confirmAndApply(ctx, items, {
2070
- yes: values.yes === true,
2071
- verb: "Apply",
2072
- rerun: withRelay ? "conveno init --with-permission-relay" : "conveno init"
2073
- });
2074
- if ("exit" in result) return result.exit;
2075
- const byCli = /* @__PURE__ */ new Map();
2076
- 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"]);
2078
- ctx.out(`${columns(rows).join("\n")}\n\n`);
2079
- ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
2080
- ctx.out(` Backups are in ${tilde(result.applied.backupDir, ctx.home)}.\n`);
2081
- ctx.out(" Restart open sessions so they pick up Conveno.\n");
2082
- if (byCli.has("codex")) ctx.out(`${t.status("info")} ${CODEX_NOTE}\n`);
2083
- if (byCli.has("cursor")) ctx.out(`${t.status("info")} ${CURSOR_NOTE}\n`);
2084
- ctx.out(` Next: ${cmd(t, "conveno status")} lists your sessions.\n`);
2085
- outcome.offer = installed.map((f) => f.adapter);
2086
- return 0;
2087
2097
  }
2088
2098
  // src/peek.ts
2089
2099
  async function connectOrFail(ctx) {
@@ -2839,9 +2849,9 @@ async function dispatch(command, rest, ctx) {
2839
2849
  case "permissions": return runPermissions(ctx, rest);
2840
2850
  case "forget": return runForget(ctx, rest);
2841
2851
  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);
2852
+ case "acp-host": return (await import("./acp-B772ag5j.js")).runAcpHostCmd(ctx, rest);
2853
+ case "stop": return (await import("./acp-B772ag5j.js")).runStop(ctx, rest);
2854
+ case "attach": return (await import("./acp-B772ag5j.js")).runAttach(ctx, rest);
2845
2855
  case "spawn-run": return runSpawnRun(ctx, rest);
2846
2856
  case "auto": return runAuto(ctx, rest);
2847
2857
  case "peek": return runPeek(ctx, rest);