@conveno/cli 0.1.1-rc.3 → 0.2.0-rc.1
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.
- package/README.md +24 -5
- package/dist/acp-BlKK0v-B.js +871 -0
- package/dist/args-DHkLY6_f.js +513 -0
- package/dist/bin.js +24 -4383
- package/dist/daemon.js +2804 -48
- package/dist/dist-CWvQqhPj.js +793 -0
- package/dist/dist-D8gPpZKN.js +8625 -0
- package/dist/dist-DcmKjrmu.js +271 -0
- package/dist/dist-DsRTUePN.js +481 -0
- package/dist/dist-_qrCNXUP.js +10497 -0
- package/dist/hook-bfp9_AVT.js +105 -0
- package/dist/hook-entry-Daxws9EC.js +1 -0
- package/dist/hook-entry-RlH2cG3S.js +1289 -0
- package/dist/main-sIWDc4jt.js +2899 -0
- package/dist/runtime-5nEur1P5.js +1505 -0
- package/package.json +19 -10
- package/dist/dist-WPVVRVUh.js +0 -1507
|
@@ -0,0 +1,2899 @@
|
|
|
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";
|
|
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";
|
|
6
|
+
import { access, chmod, mkdir, open, readFile, readdir, realpath, rename as rename$1, rm, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
8
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
9
|
+
import { readFileSync } from "node:fs";
|
|
10
|
+
// src/account.ts
|
|
11
|
+
const accountIo = (ctx, io) => ({
|
|
12
|
+
apiBase: ctx.env.CONVENO_API_URL || "https://api.conveno.dev",
|
|
13
|
+
now: () => ctx.now().getTime(),
|
|
14
|
+
...io.fetch ? { fetch: io.fetch } : {}
|
|
15
|
+
});
|
|
16
|
+
const tokenFile = (ctx) => dataPaths(ctx.platform, ctx.dataDir).account;
|
|
17
|
+
/** Show the code as ABCD-1234, the way the page asks for it. */
|
|
18
|
+
const showCode = (code) => /^[A-Za-z0-9]{8}$/.test(code) ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
|
|
19
|
+
/** Open a page with the system's own opener. No shell is involved, so the URL is one argument. */
|
|
20
|
+
function openInBrowser(platform, url) {
|
|
21
|
+
if (!/^https?:\/\//.test(url)) return;
|
|
22
|
+
const [file, args] = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
|
|
23
|
+
try {
|
|
24
|
+
const child = spawn(file, args, {
|
|
25
|
+
stdio: "ignore",
|
|
26
|
+
detached: true,
|
|
27
|
+
windowsHide: true
|
|
28
|
+
});
|
|
29
|
+
child.on("error", () => {});
|
|
30
|
+
child.unref();
|
|
31
|
+
} catch {}
|
|
32
|
+
}
|
|
33
|
+
function accountFailure(ctx, e, what) {
|
|
34
|
+
const t = ctx.theme;
|
|
35
|
+
if (e instanceof AccountError) {
|
|
36
|
+
const fixes = {
|
|
37
|
+
session_expired: `Run ${cmd(t, "conveno login")} to sign in again.`,
|
|
38
|
+
not_logged_in: `Run ${cmd(t, "conveno login")}.`,
|
|
39
|
+
denied: `Run ${cmd(t, "conveno login")} again and approve the code in the browser.`,
|
|
40
|
+
expired: `Run ${cmd(t, "conveno login")} again. The code lasts 15 minutes.`,
|
|
41
|
+
network: "Check your connection and try again.",
|
|
42
|
+
server: "Try again in a few minutes."
|
|
43
|
+
};
|
|
44
|
+
return fail(ctx, {
|
|
45
|
+
what,
|
|
46
|
+
detail: [e.message],
|
|
47
|
+
...fixes[e.code] ? { fix: fixes[e.code] } : {},
|
|
48
|
+
exit: 1,
|
|
49
|
+
ref: `e_account_${e.code}`
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
throw e;
|
|
53
|
+
}
|
|
54
|
+
function planLine(ctx, s) {
|
|
55
|
+
const t = ctx.theme;
|
|
56
|
+
if (s.plan !== "pro") return "Free";
|
|
57
|
+
if (s.status === "trialing") return `${t.paint("ok", "Pro")} (trial)`;
|
|
58
|
+
return t.paint("ok", "Pro");
|
|
59
|
+
}
|
|
60
|
+
const day = (seconds) => (/* @__PURE__ */ new Date(seconds * 1e3)).toISOString().slice(0, 10);
|
|
61
|
+
/** `conveno login`: the device authorization grant, RFC 8628. */
|
|
62
|
+
async function runLogin(ctx, argv, io = {}) {
|
|
63
|
+
const spec = COMMANDS.find((c) => c.name === "login");
|
|
64
|
+
if (!spec) return 2;
|
|
65
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
66
|
+
if (typeof parsed === "number") return parsed;
|
|
67
|
+
const t = ctx.theme;
|
|
68
|
+
const aio = accountIo(ctx, io);
|
|
69
|
+
try {
|
|
70
|
+
const code = await requestDeviceCode(aio);
|
|
71
|
+
ctx.err([
|
|
72
|
+
"Sign in to Conveno in your browser:",
|
|
73
|
+
` ${code.verificationUriComplete}`,
|
|
74
|
+
"",
|
|
75
|
+
`It should show the code ${t.bold(showCode(code.userCode))}. Approve only if it matches.`,
|
|
76
|
+
t.paint("quiet", "Waiting for approval. Press Ctrl+C to cancel."),
|
|
77
|
+
""
|
|
78
|
+
].join("\n"));
|
|
79
|
+
if (ctx.interactive && parsed.values["no-browser"] !== true) (io.open ?? ((u) => openInBrowser(ctx.platform, u)))(code.verificationUriComplete);
|
|
80
|
+
const session = await pollDeviceCode(code, {
|
|
81
|
+
...aio,
|
|
82
|
+
...io.sleep ? { sleep: io.sleep } : {}
|
|
83
|
+
});
|
|
84
|
+
await completeLogin(tokenFile(ctx), session, aio);
|
|
85
|
+
let plan = "";
|
|
86
|
+
try {
|
|
87
|
+
plan = ` Plan: ${planLine(ctx, await fetchAccountStatus(session, aio))}.`;
|
|
88
|
+
} catch {}
|
|
89
|
+
ctx.out(`${t.status("ok")} Signed in.${plan}\n`);
|
|
90
|
+
return 0;
|
|
91
|
+
} catch (e) {
|
|
92
|
+
return accountFailure(ctx, e, "Could not sign in");
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** `conveno logout`: end the login on the server and delete the local tokens. */
|
|
96
|
+
async function runLogout(ctx, argv, io = {}) {
|
|
97
|
+
const spec = COMMANDS.find((c) => c.name === "logout");
|
|
98
|
+
if (!spec) return 2;
|
|
99
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
100
|
+
if (typeof parsed === "number") return parsed;
|
|
101
|
+
const r = await logoutAccount(tokenFile(ctx), accountIo(ctx, io));
|
|
102
|
+
if (!r.hadLogin) {
|
|
103
|
+
ctx.out("You were not signed in.\n");
|
|
104
|
+
return 0;
|
|
105
|
+
}
|
|
106
|
+
ctx.out(`${ctx.theme.status("ok")} Signed out.\n`);
|
|
107
|
+
if (!r.revoked) ctx.err(`${ctx.theme.status("warn")} The account server could not be reached, so the login was only removed from this machine. Sign out everywhere at https://api.conveno.dev/account.\n`);
|
|
108
|
+
return 0;
|
|
109
|
+
}
|
|
110
|
+
/** `conveno account`: plan and trial. */
|
|
111
|
+
async function runAccount(ctx, argv, io = {}) {
|
|
112
|
+
const spec = COMMANDS.find((c) => c.name === "account");
|
|
113
|
+
if (!spec) return 2;
|
|
114
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
115
|
+
if (typeof parsed === "number") return parsed;
|
|
116
|
+
const t = ctx.theme;
|
|
117
|
+
const tokens = await readAccountTokens(tokenFile(ctx));
|
|
118
|
+
if (!tokens) return fail(ctx, {
|
|
119
|
+
what: "You are not signed in",
|
|
120
|
+
detail: ["Conveno works without an account. Pro adds the encrypted relay."],
|
|
121
|
+
fix: `Run ${cmd(t, "conveno login")}.`,
|
|
122
|
+
exit: 1,
|
|
123
|
+
ref: "e_account_not_logged_in"
|
|
124
|
+
});
|
|
125
|
+
try {
|
|
126
|
+
const s = await fetchAccountStatus(tokens.refreshToken, accountIo(ctx, io));
|
|
127
|
+
const rows = [["Account", s.user.name], ["Plan", planLine(ctx, s)]];
|
|
128
|
+
if (s.status === "trialing" && s.trialEnd !== null) {
|
|
129
|
+
const left = s.trialDaysLeft ?? 0;
|
|
130
|
+
rows.push(["Trial", `${left} ${left === 1 ? "day" : "days"} left, until ${day(s.trialEnd)}`]);
|
|
131
|
+
} else if (s.plan === "pro" && s.currentPeriodEnd !== null) rows.push([s.cancelAtPeriodEnd ? "Ends" : "Renews", day(s.currentPeriodEnd)]);
|
|
132
|
+
if (s.paymentFailed) rows.push(["Billing", t.paint("warn", "last payment failed")]);
|
|
133
|
+
const width = Math.max(...rows.map(([k]) => k.length)) + 2;
|
|
134
|
+
const lines = rows.map(([k, v]) => `${t.paint("quiet", k.padEnd(width))}${v}`);
|
|
135
|
+
if (s.plan === "free") lines.push("", `Upgrade or start the 14-day trial at ${t.bold("https://api.conveno.dev/account")}.`);
|
|
136
|
+
else if (s.status === "trialing") lines.push("", "No card is on file. Add one at https://api.conveno.dev/account to keep Pro.");
|
|
137
|
+
ctx.out(`${lines.join("\n")}\n`);
|
|
138
|
+
return 0;
|
|
139
|
+
} catch (e) {
|
|
140
|
+
return accountFailure(ctx, e, "Could not read your account");
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// src/daemonError.ts
|
|
144
|
+
/**
|
|
145
|
+
* Explain a failed connection to the daemon, with a fix that fits the cause. `start` is the command
|
|
146
|
+
* that fixes a daemon that is merely not running.
|
|
147
|
+
*/
|
|
148
|
+
function daemonProblem(t, e) {
|
|
149
|
+
const why = plainError(e);
|
|
150
|
+
const kind = e instanceof ClientError ? e.kind : void 0;
|
|
151
|
+
const start = cmd(t, "conveno daemon start");
|
|
152
|
+
const status = cmd(t, "conveno daemon status");
|
|
153
|
+
switch (kind) {
|
|
154
|
+
case "socket_path_too_long": return {
|
|
155
|
+
why,
|
|
156
|
+
fix: `Set ${cmd(t, "XDG_RUNTIME_DIR")} to a shorter directory, then run ${start}. Use the same value everywhere you run Conveno and your AI CLIs.`,
|
|
157
|
+
notRunning: false
|
|
158
|
+
};
|
|
159
|
+
case "permission": return {
|
|
160
|
+
why,
|
|
161
|
+
fix: `Check who owns the socket named above. If it is not yours, remove it, then run ${start}.`,
|
|
162
|
+
notRunning: false
|
|
163
|
+
};
|
|
164
|
+
case "not_daemon": return {
|
|
165
|
+
why,
|
|
166
|
+
fix: `Stop the process that owns the socket, or remove the socket, then run ${start}.`,
|
|
167
|
+
notRunning: false
|
|
168
|
+
};
|
|
169
|
+
case "token_empty": return {
|
|
170
|
+
why,
|
|
171
|
+
fix: `Run ${cmd(t, "conveno daemon stop")}, then ${start}.`,
|
|
172
|
+
notRunning: false
|
|
173
|
+
};
|
|
174
|
+
case "daemon_missing": return {
|
|
175
|
+
why,
|
|
176
|
+
fix: `Reinstall Conveno (${cmd(t, "npm install -g @conveno/cli")}), then run ${start}.`,
|
|
177
|
+
notRunning: false
|
|
178
|
+
};
|
|
179
|
+
case "start_timeout": return {
|
|
180
|
+
why,
|
|
181
|
+
fix: `Run ${status} to see whether it came up, or ${cmd(t, "conveno doctor")} to check the install.`,
|
|
182
|
+
notRunning: false
|
|
183
|
+
};
|
|
184
|
+
case "start_exited": return {
|
|
185
|
+
why,
|
|
186
|
+
fix: `Fix what its output above shows, then run ${start}. If it is unclear, report it with that output.`,
|
|
187
|
+
notRunning: false
|
|
188
|
+
};
|
|
189
|
+
case "connection": return {
|
|
190
|
+
why,
|
|
191
|
+
fix: `Run ${status}, then try again.`,
|
|
192
|
+
notRunning: false
|
|
193
|
+
};
|
|
194
|
+
case "no_daemon": return {
|
|
195
|
+
why,
|
|
196
|
+
fix: `Run ${start}. It also starts when a CLI opens the Conveno MCP server.`,
|
|
197
|
+
notRunning: true
|
|
198
|
+
};
|
|
199
|
+
default: return {
|
|
200
|
+
why,
|
|
201
|
+
fix: `Run ${cmd(t, "conveno doctor")} to check the install, then try again.`,
|
|
202
|
+
notRunning: false
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
// src/status.ts
|
|
207
|
+
const CLI_SHORT = {
|
|
208
|
+
claude: "cl",
|
|
209
|
+
codex: "cx",
|
|
210
|
+
opencode: "oc",
|
|
211
|
+
antigravity: "ag",
|
|
212
|
+
cursor: "cu",
|
|
213
|
+
copilot: "cp",
|
|
214
|
+
grok: "gk"
|
|
215
|
+
};
|
|
216
|
+
const pad2 = (n) => String(n).padStart(2, "0");
|
|
217
|
+
/** Local `HH:MM:SS`, with the date in front when it is not today. */
|
|
218
|
+
function stamp(iso, now) {
|
|
219
|
+
const d = new Date(iso);
|
|
220
|
+
const time = `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
|
|
221
|
+
const day = `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
|
|
222
|
+
return day === `${now.getFullYear()}-${pad2(now.getMonth() + 1)}-${pad2(now.getDate())}` ? time : `${day} ${time}`;
|
|
223
|
+
}
|
|
224
|
+
function tierText(theme, tier) {
|
|
225
|
+
switch (tier) {
|
|
226
|
+
case "live": return theme.paint("entry", "live");
|
|
227
|
+
case "next_turn": return "next turn";
|
|
228
|
+
case "acp": return "ACP";
|
|
229
|
+
case "inbox": return theme.paint("quiet", "inbox");
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
function stateCell(theme, s) {
|
|
233
|
+
if (s.status === "offline") return {
|
|
234
|
+
glyph: theme.status("offline"),
|
|
235
|
+
word: "offline"
|
|
236
|
+
};
|
|
237
|
+
if (s.status === "waiting_on_question") return {
|
|
238
|
+
glyph: theme.status("waiting"),
|
|
239
|
+
word: "waiting"
|
|
240
|
+
};
|
|
241
|
+
if (s.isOrchestrator) return {
|
|
242
|
+
glyph: theme.status("orchestrator"),
|
|
243
|
+
word: s.status
|
|
244
|
+
};
|
|
245
|
+
if (s.status === "busy") return {
|
|
246
|
+
glyph: theme.glyph("busy"),
|
|
247
|
+
word: "busy"
|
|
248
|
+
};
|
|
249
|
+
return {
|
|
250
|
+
glyph: theme.status("idle"),
|
|
251
|
+
word: "idle"
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
/** `on`, `off` or `paused by limit`. */
|
|
255
|
+
function autoText(theme, s) {
|
|
256
|
+
if (s.auto === true && s.autoPausedBy !== void 0) return theme.paint("warn", pauseLabel(s.autoPausedBy));
|
|
257
|
+
return s.auto === true ? "on" : theme.paint("quiet", "off");
|
|
258
|
+
}
|
|
259
|
+
/** Sessions grouped by repository, the way brand/components/terminal.md lays them out. */
|
|
260
|
+
function renderSessions(ctx, sessions) {
|
|
261
|
+
const t = ctx.theme;
|
|
262
|
+
const now = ctx.now();
|
|
263
|
+
const groups = /* @__PURE__ */ new Map();
|
|
264
|
+
const keyOf = (s) => s.remote ? `${s.repo?.root ?? s.cwd}\u0000${s.deviceName ?? ""}` : s.repo?.root ?? s.cwd;
|
|
265
|
+
for (const s of sessions) {
|
|
266
|
+
const key = keyOf(s);
|
|
267
|
+
groups.set(key, [...groups.get(key) ?? [], s]);
|
|
268
|
+
}
|
|
269
|
+
const blocks = [];
|
|
270
|
+
for (const key of [...groups.keys()].sort()) {
|
|
271
|
+
const list = (groups.get(key) ?? []).sort((a, b) => a.name.localeCompare(b.name));
|
|
272
|
+
const q = (w) => t.paint("quiet", w);
|
|
273
|
+
const head = [
|
|
274
|
+
` ${q("SESSION")}`,
|
|
275
|
+
q("CLI"),
|
|
276
|
+
q("TIER"),
|
|
277
|
+
q("STATE"),
|
|
278
|
+
q("AUTO"),
|
|
279
|
+
q("UNREAD"),
|
|
280
|
+
q("LAST SEEN")
|
|
281
|
+
];
|
|
282
|
+
const rows = list.map((s) => {
|
|
283
|
+
const st = stateCell(t, s);
|
|
284
|
+
return [
|
|
285
|
+
`${st.glyph} ${t.bold(s.name)}`,
|
|
286
|
+
CLI_SHORT[s.cli] ?? s.cli,
|
|
287
|
+
tierText(t, s.deliveryTier),
|
|
288
|
+
st.word,
|
|
289
|
+
autoText(t, s),
|
|
290
|
+
s.unreadCount ? String(s.unreadCount) : q("0"),
|
|
291
|
+
t.paint("quiet", stamp(s.lastSeenAt, now)),
|
|
292
|
+
...s.isOrchestrator ? [t.paint("entry", "orchestrator")] : [],
|
|
293
|
+
...s.spawned || s.spawnedBy ? [t.paint("quiet", "spawned")] : []
|
|
294
|
+
];
|
|
295
|
+
});
|
|
296
|
+
const [headLine, ...rowLines] = columns([head, ...rows]);
|
|
297
|
+
const [path, device] = key.split("\0");
|
|
298
|
+
const title = device === void 0 ? t.bold(tilde(key, ctx.home)) : `${t.bold(path ?? "")} ${t.paint("quiet", `on ${device || "another device"}`)}`;
|
|
299
|
+
blocks.push([
|
|
300
|
+
` ${title}`,
|
|
301
|
+
` ${headLine}`,
|
|
302
|
+
...rowLines.map((l) => ` ${l}`)
|
|
303
|
+
].join("\n"));
|
|
304
|
+
}
|
|
305
|
+
return blocks.join("\n\n");
|
|
306
|
+
}
|
|
307
|
+
/** The relay part of the status header line. */
|
|
308
|
+
function relaySummary(r) {
|
|
309
|
+
if (!r) return "off (local only)";
|
|
310
|
+
switch (r.state) {
|
|
311
|
+
case "connected": {
|
|
312
|
+
const online = r.peers.filter((p) => p.online).length;
|
|
313
|
+
return `connected (${plural(online, "other device")} online)`;
|
|
314
|
+
}
|
|
315
|
+
case "connecting": return "connecting";
|
|
316
|
+
case "disconnected": return "disconnected, retrying";
|
|
317
|
+
case "revoked": return "off (this device was revoked)";
|
|
318
|
+
case "unpaired": return "off (no paired devices)";
|
|
319
|
+
default: return "off (local only)";
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
async function runStatus(ctx, argv = []) {
|
|
323
|
+
const t = ctx.theme;
|
|
324
|
+
const spec = COMMANDS.find((c) => c.name === "status");
|
|
325
|
+
let all = false;
|
|
326
|
+
if (spec) {
|
|
327
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
328
|
+
if (typeof parsed === "number") return parsed;
|
|
329
|
+
all = parsed.values.all === true;
|
|
330
|
+
}
|
|
331
|
+
let client;
|
|
332
|
+
try {
|
|
333
|
+
client = await ctx.connect(connectOpts(ctx, false));
|
|
334
|
+
} catch (e) {
|
|
335
|
+
const problem = daemonProblem(t, e);
|
|
336
|
+
ctx.err(problem.notRunning ? warnBlock(t, "The Conveno daemon is not running.", `Run ${cmd(t, "conveno daemon start")}, or open a supported CLI after ${cmd(t, "conveno init")}.`, "Sessions are listed by the daemon, and nothing is listening on its socket.") : warnBlock(t, "The Conveno daemon cannot be reached.", problem.fix, problem.why));
|
|
337
|
+
return 0;
|
|
338
|
+
}
|
|
339
|
+
try {
|
|
340
|
+
const everyone = (await client["session.list"]({ includeOffline: true })).sessions;
|
|
341
|
+
const sessions = all ? everyone : everyone.filter((s) => s.status !== "offline");
|
|
342
|
+
const hidden = everyone.length - sessions.length;
|
|
343
|
+
const repos = new Set(sessions.map((s) => s.repo?.root ?? s.cwd)).size;
|
|
344
|
+
const hint = hidden > 0 ? `${hidden} offline hidden, ${cmd(t, "conveno status --all")} shows them` : "";
|
|
345
|
+
const relay = await (async () => client["relay.status"]({}))().catch(() => void 0);
|
|
346
|
+
ctx.out(`daemon up ${t.status("bullet")} relay: ${relaySummary(relay)} ${t.status("bullet")} ${plural(sessions.length, "session")}\n`);
|
|
347
|
+
if (sessions.length === 0) {
|
|
348
|
+
ctx.out(hidden > 0 ? `\nNo sessions online. ${hint}.\n` : `\nNo sessions yet. Open a supported CLI after ${cmd(t, "conveno init")} and it appears here.\n`);
|
|
349
|
+
return 0;
|
|
350
|
+
}
|
|
351
|
+
ctx.out(`\n${renderSessions(ctx, sessions)}\n\n`);
|
|
352
|
+
ctx.out(`${plural(sessions.length, "session")} in ${plural(repos, "repo")}${hint ? ` ${t.status("bullet")} ${hint}` : ""}\n`);
|
|
353
|
+
const paused = sessions.filter((s) => s.auto === true && s.autoPausedBy !== void 0);
|
|
354
|
+
for (const s of paused) ctx.err(warnBlock(t, `Auto mode for ${s.name} is paused by limit.`, `Run ${cmd(t, `conveno auto resume ${s.name}`)}, or let the orchestrator resume it (once per hour).`, "It took as many automatic turns as its limit allows in the window, or a message reached it after that many automatic turns with no person in between (sessions answering each other). Its messages still arrive at the next prompt."));
|
|
355
|
+
const open = await client["ticket.list"]({
|
|
356
|
+
status: "open",
|
|
357
|
+
limit: 1
|
|
358
|
+
}).catch(() => void 0);
|
|
359
|
+
if (open && open.openCount > 0) ctx.out(`${t.paint("entry", plural(open.openCount, "open ticket"))} waiting for an answer ${t.status("bullet")} ${cmd(t, "conveno tickets --open")}\n`);
|
|
360
|
+
return 0;
|
|
361
|
+
} finally {
|
|
362
|
+
await client.close().catch(() => void 0);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
// src/auto.ts
|
|
366
|
+
/** Time allowed for the process-table query that finds the session this command runs in. */
|
|
367
|
+
const ANCESTRY_TIMEOUT_MS$1 = 5e3;
|
|
368
|
+
/**
|
|
369
|
+
* The session this command runs inside, when it is typed in a CLI's own shell (for example
|
|
370
|
+
* `! conveno auto on` in Claude Code): the nearest ancestor that hosts exactly one session. A
|
|
371
|
+
* command the user types may look past its first ancestor, because the user asked for it and is
|
|
372
|
+
* told which session changed; hooks never do this.
|
|
373
|
+
*/
|
|
374
|
+
async function enclosingSession(ctx, client) {
|
|
375
|
+
const { pids } = await ctx.ancestry(ANCESTRY_TIMEOUT_MS$1);
|
|
376
|
+
for (const pid of pids) {
|
|
377
|
+
const { session } = await client["session.byHost"]({ pid });
|
|
378
|
+
if (session) return session;
|
|
379
|
+
}
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
const isTarget = (s) => SessionName.safeParse(s).success || SessionId.safeParse(s).success;
|
|
383
|
+
/** `conveno auto [on|off|resume|limit <n|default>] [<session>]`. */
|
|
384
|
+
async function runAuto(ctx, argv) {
|
|
385
|
+
const t = ctx.theme;
|
|
386
|
+
const spec = COMMANDS.find((c) => c.name === "auto");
|
|
387
|
+
if (!spec) return 2;
|
|
388
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
389
|
+
if (typeof parsed === "number") return parsed;
|
|
390
|
+
const [mode, ...rest] = parsed.positionals;
|
|
391
|
+
const usage = `Run ${cmd(t, "conveno auto --help")} to see the usage.`;
|
|
392
|
+
const usageError = (what) => fail(ctx, {
|
|
393
|
+
what,
|
|
394
|
+
fix: usage,
|
|
395
|
+
exit: 2,
|
|
396
|
+
ref: "e_usage"
|
|
397
|
+
});
|
|
398
|
+
let change;
|
|
399
|
+
let args = rest;
|
|
400
|
+
switch (mode) {
|
|
401
|
+
case void 0: break;
|
|
402
|
+
case "on":
|
|
403
|
+
case "off":
|
|
404
|
+
change = { auto: mode === "on" };
|
|
405
|
+
break;
|
|
406
|
+
case "resume":
|
|
407
|
+
change = { resume: true };
|
|
408
|
+
break;
|
|
409
|
+
case "limit": {
|
|
410
|
+
const [value, ...after] = rest;
|
|
411
|
+
if (value === void 0) return usageError("conveno auto limit needs a number or default");
|
|
412
|
+
if (value === "default") change = { limit: null };
|
|
413
|
+
else if (/^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 1e3) change = { limit: Number(value) };
|
|
414
|
+
else return usageError(`"${value}" is not a limit from 1 to ${AUTO_LIMIT_MAX}, or default`);
|
|
415
|
+
args = after;
|
|
416
|
+
break;
|
|
417
|
+
}
|
|
418
|
+
default: return usageError(`Unexpected argument "${mode}" for conveno auto`);
|
|
419
|
+
}
|
|
420
|
+
const [target, ...extra] = args;
|
|
421
|
+
if (extra.length > 0) return usageError(`Unexpected argument "${extra[0]}" for conveno auto`);
|
|
422
|
+
if (target !== void 0 && !isTarget(target)) return fail(ctx, {
|
|
423
|
+
what: `"${target}" is not a session name or id`,
|
|
424
|
+
fix: `Run ${cmd(t, "conveno status")} to see the names.`,
|
|
425
|
+
exit: 2,
|
|
426
|
+
ref: "e_usage"
|
|
427
|
+
});
|
|
428
|
+
let client;
|
|
429
|
+
try {
|
|
430
|
+
client = await ctx.connect(connectOpts(ctx, false));
|
|
431
|
+
} catch (e) {
|
|
432
|
+
const problem = daemonProblem(t, e);
|
|
433
|
+
return fail(ctx, {
|
|
434
|
+
what: "The Conveno daemon cannot be reached",
|
|
435
|
+
detail: [problem.why],
|
|
436
|
+
fix: problem.fix,
|
|
437
|
+
exit: 1,
|
|
438
|
+
ref: "e_daemon"
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
try {
|
|
442
|
+
if (change === void 0) {
|
|
443
|
+
const { sessions } = await client["session.list"]({});
|
|
444
|
+
ctx.out(sessions.length === 0 ? "No sessions online.\n" : `${renderSessions(ctx, sessions)}\n`);
|
|
445
|
+
return 0;
|
|
446
|
+
}
|
|
447
|
+
const session = target ?? (await enclosingSession(ctx, client))?.id;
|
|
448
|
+
if (session === void 0) return fail(ctx, {
|
|
449
|
+
what: "conveno auto needs a session",
|
|
450
|
+
detail: ["This command does not run inside a session Conveno knows."],
|
|
451
|
+
fix: `Name one, such as ${cmd(t, "conveno auto on api-worker")}. ${cmd(t, "conveno status")} lists the names.`,
|
|
452
|
+
exit: 2,
|
|
453
|
+
ref: "e_usage"
|
|
454
|
+
});
|
|
455
|
+
const s = (await client["session.setAuto"]({
|
|
456
|
+
session,
|
|
457
|
+
...change
|
|
458
|
+
})).session;
|
|
459
|
+
ctx.out(`Auto mode for ${t.bold(s.name)} is ${autoText(t, s)}.\n`);
|
|
460
|
+
if (change.limit !== void 0) ctx.out(s.autoLimit !== void 0 ? `It may take ${s.autoLimit} automatic turns per window.\n` : "It uses the daemon's limit again.\n");
|
|
461
|
+
else if (s.auto) ctx.out("Waiting messages become its next prompt when a turn ends, or right away while it is idle where its CLI allows.\n");
|
|
462
|
+
else ctx.out("Messages still reach it at the next prompt and through the inbox tool.\n");
|
|
463
|
+
return 0;
|
|
464
|
+
} catch (e) {
|
|
465
|
+
const problem = daemonProblem(t, e);
|
|
466
|
+
return fail(ctx, {
|
|
467
|
+
what: "Auto mode was not changed",
|
|
468
|
+
detail: [problem.why],
|
|
469
|
+
fix: `Run ${cmd(t, "conveno status")} to see the sessions.`,
|
|
470
|
+
exit: 1,
|
|
471
|
+
ref: "e_auto"
|
|
472
|
+
});
|
|
473
|
+
} finally {
|
|
474
|
+
await client.close().catch(() => void 0);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
// src/daemon.ts
|
|
478
|
+
async function lockPid(ctx) {
|
|
479
|
+
try {
|
|
480
|
+
const raw = await readFile(dataPaths(ctx.platform, ctx.dataDir).lock, "utf8");
|
|
481
|
+
const pid = JSON.parse(raw).pid;
|
|
482
|
+
return typeof pid === "number" && Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
483
|
+
} catch {
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
488
|
+
/** Does something on the socket answer the Conveno handshake? */
|
|
489
|
+
async function reachable(ctx) {
|
|
490
|
+
try {
|
|
491
|
+
await (await ctx.connect(connectOpts(ctx, false))).close().catch(() => void 0);
|
|
492
|
+
return true;
|
|
493
|
+
} catch {
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
const lockExists = (ctx) => access(dataPaths(ctx.platform, ctx.dataDir).lock).then(() => true, () => false);
|
|
498
|
+
/** Poll until `done()` holds or `ms` pass. Returns whether it held. */
|
|
499
|
+
async function waitFor(done, ms) {
|
|
500
|
+
const deadline = Date.now() + ms;
|
|
501
|
+
for (;;) {
|
|
502
|
+
if (await done()) return true;
|
|
503
|
+
if (Date.now() >= deadline) return false;
|
|
504
|
+
await sleep$1(50);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
const norm = (text) => text.replaceAll("\\", "/").toLowerCase();
|
|
508
|
+
/**
|
|
509
|
+
* Does this command line belong to the Conveno daemon? It must run the daemon's entry script: the
|
|
510
|
+
* one this install resolved, any installed `@conveno/cli`'s `daemon.js`, or the `bin.js` of the
|
|
511
|
+
* `@conveno/daemon` package that releases before 0.1.1 started.
|
|
512
|
+
*/
|
|
513
|
+
function isConvenoDaemonCommand(commandLine, daemonEntry) {
|
|
514
|
+
const line = norm(commandLine);
|
|
515
|
+
if (daemonEntry !== void 0 && line.includes(norm(daemonEntry))) return true;
|
|
516
|
+
return /@conveno\/cli\/(?:[^ ]+\/)?daemon\.js|@conveno\/daemon\/(?:[^ ]+\/)?bin\.js/.test(line);
|
|
517
|
+
}
|
|
518
|
+
const STOP_FIX = (t) => `then run ${cmd(t, "conveno daemon status")}`;
|
|
519
|
+
/**
|
|
520
|
+
* `conveno daemon stop`. The normal path asks the daemon to shut itself down over the control
|
|
521
|
+
* channel (`daemon.shutdown`), the way Docker and pm2 do. That needs no signal and no external
|
|
522
|
+
* tool, so it works for a normal user in a Windows SSH session. Only when the daemon does not answer,
|
|
523
|
+
* and its lock pid is verified to be the daemon, is the process ended directly.
|
|
524
|
+
*/
|
|
525
|
+
async function stopDaemon(ctx) {
|
|
526
|
+
const t = ctx.theme;
|
|
527
|
+
const lock = dataPaths(ctx.platform, ctx.dataDir).lock;
|
|
528
|
+
const pid = await lockPid(ctx);
|
|
529
|
+
const named = pid === null ? "" : ` (pid ${pid})`;
|
|
530
|
+
let client;
|
|
531
|
+
try {
|
|
532
|
+
client = await ctx.connect(connectOpts(ctx, false));
|
|
533
|
+
} catch {
|
|
534
|
+
client = void 0;
|
|
535
|
+
}
|
|
536
|
+
if (client) {
|
|
537
|
+
try {
|
|
538
|
+
await client["daemon.shutdown"]({});
|
|
539
|
+
} catch (e) {
|
|
540
|
+
await client.close().catch(() => void 0);
|
|
541
|
+
return fail(ctx, {
|
|
542
|
+
what: `The daemon${named} did not accept the stop request`,
|
|
543
|
+
detail: [plainError(e)],
|
|
544
|
+
fix: `${pid === null ? "Stop the process that owns the daemon socket yourself" : `Stop pid ${pid} yourself`}, ${STOP_FIX(t)}.`,
|
|
545
|
+
exit: 1,
|
|
546
|
+
ref: "e_daemon_stop"
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
await client.close().catch(() => void 0);
|
|
550
|
+
if (!await waitFor(async () => !await reachable(ctx) && !await lockExists(ctx) && (pid === null || !ctx.isAlive(pid)), ctx.stopTimeoutMs)) return fail(ctx, {
|
|
551
|
+
what: `The daemon${named} is still running after ${Math.round(ctx.stopTimeoutMs / 1e3)}s`,
|
|
552
|
+
detail: ["It accepted the stop request, but its process, socket or lock file is still there."],
|
|
553
|
+
fix: `${pid === null ? "Stop the process that owns the daemon socket yourself" : `Stop pid ${pid} yourself`}, ${STOP_FIX(t)}.`,
|
|
554
|
+
exit: 1,
|
|
555
|
+
ref: "e_daemon_stop"
|
|
556
|
+
});
|
|
557
|
+
ctx.out(`${t.status("ok")} Stopped the daemon${named}.\n`);
|
|
558
|
+
return 0;
|
|
559
|
+
}
|
|
560
|
+
if (pid === null) {
|
|
561
|
+
ctx.out(`${t.status("info")} The daemon is not running. Nothing to stop.\n`);
|
|
562
|
+
return 0;
|
|
563
|
+
}
|
|
564
|
+
const stale = async () => {
|
|
565
|
+
await rm(lock, { force: true }).catch(() => void 0);
|
|
566
|
+
ctx.out(`${t.status("info")} Nothing answered as the Conveno daemon, so no process was stopped. Removed the stale lock file (it named pid ${pid}).\n`);
|
|
567
|
+
return 0;
|
|
568
|
+
};
|
|
569
|
+
if (!ctx.isAlive(pid)) return stale();
|
|
570
|
+
const commandLine = await ctx.commandLineOf(pid);
|
|
571
|
+
if (commandLine === null) return fail(ctx, {
|
|
572
|
+
what: `The daemon did not answer, and pid ${pid} could not be checked`,
|
|
573
|
+
detail: ["Conveno could not read that process's command line, so it cannot tell whether it is the daemon. It stopped nothing."],
|
|
574
|
+
fix: `If pid ${pid} is the Conveno daemon, end it yourself (Task Manager on Windows, \`kill ${pid}\` elsewhere), ${STOP_FIX(t)}.`,
|
|
575
|
+
exit: 1,
|
|
576
|
+
ref: "e_daemon_lock"
|
|
577
|
+
});
|
|
578
|
+
if (!isConvenoDaemonCommand(commandLine, ctx.daemonEntry)) return stale();
|
|
579
|
+
try {
|
|
580
|
+
ctx.kill(pid);
|
|
581
|
+
} catch (e) {
|
|
582
|
+
return fail(ctx, {
|
|
583
|
+
what: `Could not stop the daemon (pid ${pid})`,
|
|
584
|
+
detail: [plainError(e)],
|
|
585
|
+
fix: `Stop that process yourself, ${STOP_FIX(t)}.`,
|
|
586
|
+
exit: 1,
|
|
587
|
+
ref: "e_daemon_stop"
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
if (!await waitFor(() => !ctx.isAlive(pid), ctx.stopTimeoutMs)) return fail(ctx, {
|
|
591
|
+
what: `The daemon (pid ${pid}) is still running after ${Math.round(ctx.stopTimeoutMs / 1e3)}s`,
|
|
592
|
+
detail: ["It did not answer, was ended, and has not exited."],
|
|
593
|
+
fix: `Stop that process yourself, ${STOP_FIX(t)}.`,
|
|
594
|
+
exit: 1,
|
|
595
|
+
ref: "e_daemon_stop"
|
|
596
|
+
});
|
|
597
|
+
await rm(lock, { force: true }).catch(() => void 0);
|
|
598
|
+
ctx.out(`${t.status("ok")} Stopped the daemon (pid ${pid}). It was not answering, so it was ended directly.\n`);
|
|
599
|
+
return 0;
|
|
600
|
+
}
|
|
601
|
+
const SUBCOMMANDS = [
|
|
602
|
+
"start",
|
|
603
|
+
"stop",
|
|
604
|
+
"status"
|
|
605
|
+
];
|
|
606
|
+
async function runDaemon(ctx, argv) {
|
|
607
|
+
const t = ctx.theme;
|
|
608
|
+
const sub = argv[0];
|
|
609
|
+
if (sub === "start") {
|
|
610
|
+
try {
|
|
611
|
+
await (await ctx.connect(connectOpts(ctx, true))).close().catch(() => void 0);
|
|
612
|
+
} catch (e) {
|
|
613
|
+
const problem = daemonProblem(t, e);
|
|
614
|
+
return fail(ctx, {
|
|
615
|
+
what: "The Conveno daemon did not start",
|
|
616
|
+
detail: [problem.why],
|
|
617
|
+
fix: problem.notRunning ? `Run ${cmd(t, "conveno doctor")} to check the install, then try again.` : problem.fix,
|
|
618
|
+
exit: 1,
|
|
619
|
+
ref: "e_daemon_start"
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
const pid = await lockPid(ctx);
|
|
623
|
+
ctx.out(`${t.status("ok")} Daemon running${pid ? `, pid ${pid}` : ""}.\n`);
|
|
624
|
+
return 0;
|
|
625
|
+
}
|
|
626
|
+
if (sub === "status") {
|
|
627
|
+
const pid = await lockPid(ctx);
|
|
628
|
+
try {
|
|
629
|
+
await (await ctx.connect(connectOpts(ctx, false))).close().catch(() => void 0);
|
|
630
|
+
ctx.out(`${t.status("ok")} daemon running${pid ? `, pid ${pid}` : ""}\n`);
|
|
631
|
+
return 0;
|
|
632
|
+
} catch (e) {
|
|
633
|
+
const problem = daemonProblem(t, e);
|
|
634
|
+
if (problem.notRunning) ctx.out(`${t.glyph("offline")} daemon not running\n`);
|
|
635
|
+
else {
|
|
636
|
+
ctx.out(`${t.status("error")} daemon cannot be reached\n`);
|
|
637
|
+
ctx.err(warnBlock(t, "The Conveno daemon cannot be reached.", problem.fix, problem.why));
|
|
638
|
+
}
|
|
639
|
+
return 1;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
if (sub === "stop") return stopDaemon(ctx);
|
|
643
|
+
const suggestion = sub ? closest(sub, SUBCOMMANDS) : void 0;
|
|
644
|
+
return fail(ctx, {
|
|
645
|
+
what: sub ? `Unknown daemon command "${sub}"` : "conveno daemon needs a command",
|
|
646
|
+
fix: `Run ${cmd(t, "conveno daemon start")}, ${cmd(t, "conveno daemon stop")} or ${cmd(t, "conveno daemon status")}.`,
|
|
647
|
+
...suggestion ? { didYouMean: `Did you mean ${suggestion}?` } : {},
|
|
648
|
+
exit: 2,
|
|
649
|
+
ref: "e_usage"
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
const PAIR_TIMEOUT_MS = 3e5;
|
|
653
|
+
/**
|
|
654
|
+
* Run `run` with a daemon client. Commands that change something start the daemon when needed;
|
|
655
|
+
* the read-only ones (`devices`, `relay status`) do not, like `conveno status`.
|
|
656
|
+
*/
|
|
657
|
+
async function withClient(ctx, autoStart, run) {
|
|
658
|
+
const t = ctx.theme;
|
|
659
|
+
let client;
|
|
660
|
+
try {
|
|
661
|
+
client = await ctx.connect(connectOpts(ctx, autoStart));
|
|
662
|
+
} catch (e) {
|
|
663
|
+
const problem = daemonProblem(t, e);
|
|
664
|
+
return fail(ctx, {
|
|
665
|
+
what: "The Conveno daemon cannot be reached",
|
|
666
|
+
detail: [problem.why],
|
|
667
|
+
fix: problem.fix,
|
|
668
|
+
exit: 1,
|
|
669
|
+
ref: "e_daemon"
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
try {
|
|
673
|
+
return await run(client);
|
|
674
|
+
} catch (e) {
|
|
675
|
+
return fail(ctx, {
|
|
676
|
+
what: "The daemon refused the request",
|
|
677
|
+
detail: [plainError(e)],
|
|
678
|
+
fix: `Run ${cmd(t, "conveno relay status")} to see the relay and login state.`,
|
|
679
|
+
exit: 1,
|
|
680
|
+
ref: "e_relay"
|
|
681
|
+
});
|
|
682
|
+
} finally {
|
|
683
|
+
await client.close().catch(() => void 0);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
/** The device list's head and length. The full head is what `devices accept` takes. */
|
|
687
|
+
function listLine(ctx, list) {
|
|
688
|
+
if (!list) return "";
|
|
689
|
+
return ` ${ctx.theme.paint("quiet", "device list:")} ${list.head} ${ctx.theme.paint("quiet", `(${plural(list.length, "entry", "entries")})`)}\n`;
|
|
690
|
+
}
|
|
691
|
+
/** A loud warning while the device list has an unresolved conflict. */
|
|
692
|
+
function conflictBlock(ctx, c) {
|
|
693
|
+
if (!c) return "";
|
|
694
|
+
const t = ctx.theme;
|
|
695
|
+
const head = (l) => l ? `${l.head.slice(0, 16)} ${t.paint("quiet", `(${plural(l.length, "entry", "entries")})`)}` : "none";
|
|
696
|
+
const why = c.kind === "split_view" ? [` ${c.peer?.name ?? "Another device"} signed a message with a device list this device does not hold.`, " The relay may be showing your devices different lists, for example to hide a revocation."] : [" The relay holds a device list that this device's list is not part of.", " Someone changed the list in a way this device cannot follow, or the relay is lying."];
|
|
697
|
+
return `${[
|
|
698
|
+
"",
|
|
699
|
+
`${t.status("error")} ${t.bold("Your device list has a conflict.")} Nothing is sent to or accepted from other devices.`,
|
|
700
|
+
...why,
|
|
701
|
+
` ${c.detail}`,
|
|
702
|
+
"",
|
|
703
|
+
` This device: ${head(c.local)}`,
|
|
704
|
+
` The relay: ${head(c.relay)}`,
|
|
705
|
+
...c.peer ? [` ${c.peer.name}: ${head(c.peer)}`] : [],
|
|
706
|
+
"",
|
|
707
|
+
` To recover, run ${cmd(t, "conveno devices")} on a device you trust that is not in conflict.`,
|
|
708
|
+
" If it lists only devices you recognize, type the head it shows (the full 64 characters) here:",
|
|
709
|
+
` ${cmd(t, "conveno devices accept <head>")}. Then revoke any device you do not recognize.`,
|
|
710
|
+
" If no device you trust is left, or you did not reset the devices yourself, reset them at",
|
|
711
|
+
` https://api.conveno.dev/account. After a reset, run ${cmd(t, "conveno devices reset")} here and pair again.`,
|
|
712
|
+
""
|
|
713
|
+
].join("\n")}\n`;
|
|
714
|
+
}
|
|
715
|
+
function deviceTable(ctx, list) {
|
|
716
|
+
const t = ctx.theme;
|
|
717
|
+
const q = (w) => t.paint("quiet", w);
|
|
718
|
+
const head = [
|
|
719
|
+
` ${q("DEVICE")}`,
|
|
720
|
+
q("STATE"),
|
|
721
|
+
q("SESSIONS"),
|
|
722
|
+
q("FINGERPRINT"),
|
|
723
|
+
q("ADDED")
|
|
724
|
+
];
|
|
725
|
+
const rows = list.devices.map((d) => [
|
|
726
|
+
`${d.online ? t.status("idle") : t.status("offline")} ${t.bold(d.name)}${d.self ? q(" (this device)") : ""}`,
|
|
727
|
+
d.online ? "online" : "offline",
|
|
728
|
+
d.self ? "" : String(d.sessions),
|
|
729
|
+
q(d.fingerprint),
|
|
730
|
+
d.addedAt ? q(localStamp(d.addedAt)) : ""
|
|
731
|
+
]);
|
|
732
|
+
const lines = columns([head, ...rows]).map((l) => ` ${l}`);
|
|
733
|
+
if (list.revoked.length > 0) {
|
|
734
|
+
lines.push("", ` ${q("Revoked:")}`);
|
|
735
|
+
for (const r of list.revoked) lines.push(` ${r.name} ${q(`${r.deviceId}, ${localStamp(r.revokedAt)}`)}`);
|
|
736
|
+
}
|
|
737
|
+
return lines.join("\n");
|
|
738
|
+
}
|
|
739
|
+
async function list(ctx) {
|
|
740
|
+
return withClient(ctx, false, async (c) => {
|
|
741
|
+
const devices = await c["devices.list"]({});
|
|
742
|
+
ctx.out(`${deviceTable(ctx, devices)}\n\n${listLine(ctx, devices.list)}`);
|
|
743
|
+
if (devices.conflict) {
|
|
744
|
+
ctx.err(conflictBlock(ctx, devices.conflict));
|
|
745
|
+
return 1;
|
|
746
|
+
}
|
|
747
|
+
if (devices.devices.length === 1) ctx.out(`Only this device. Run ${cmd(ctx.theme, "conveno devices pair")} here and ${cmd(ctx.theme, "conveno devices join")} on the other device.\n`);
|
|
748
|
+
return 0;
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
752
|
+
/**
|
|
753
|
+
* Pair this device with another one. Each device shows its own 8-digit code, and the owner types
|
|
754
|
+
* the code from the other screen. There is deliberately no flag to skip that, since the check is
|
|
755
|
+
* what stops a relay from slipping in its own key, and no yes/no question to answer by habit.
|
|
756
|
+
*/
|
|
757
|
+
async function pair(ctx, role) {
|
|
758
|
+
const t = ctx.theme;
|
|
759
|
+
if (!ctx.interactive) return fail(ctx, {
|
|
760
|
+
what: "Pairing needs a terminal",
|
|
761
|
+
detail: ["You compare a code on both devices and confirm it here, so it cannot run unattended."],
|
|
762
|
+
fix: `Run ${cmd(t, role === "invite" ? "conveno devices pair" : "conveno devices join")} in a terminal.`,
|
|
763
|
+
exit: 2,
|
|
764
|
+
ref: "e_no_tty"
|
|
765
|
+
});
|
|
766
|
+
return withClient(ctx, true, async (c) => {
|
|
767
|
+
let s = await c["devices.pair"]({ role });
|
|
768
|
+
ctx.out(role === "invite" ? `Waiting for the new device. Run ${cmd(t, "conveno devices join")} on it now.\n` : `Looking for one of your devices. Run ${cmd(t, "conveno devices pair")} on it now.\n`);
|
|
769
|
+
const end = Date.now() + PAIR_TIMEOUT_MS;
|
|
770
|
+
let asked = false;
|
|
771
|
+
while (s.state !== "done" && s.state !== "failed" && Date.now() < end) {
|
|
772
|
+
if (s.state === "confirm" && !asked && s.sas && s.peer) {
|
|
773
|
+
asked = true;
|
|
774
|
+
ctx.out([
|
|
775
|
+
"",
|
|
776
|
+
` ${role === "invite" ? "New device" : "Your device"}: ${t.bold(s.peer.name)} ${t.paint("quiet", `(${s.peer.fingerprint})`)}`,
|
|
777
|
+
"",
|
|
778
|
+
" Type this code on the other device:",
|
|
779
|
+
"",
|
|
780
|
+
` ${t.bold(s.sas)}`,
|
|
781
|
+
"",
|
|
782
|
+
""
|
|
783
|
+
].join("\n"));
|
|
784
|
+
for (;;) {
|
|
785
|
+
const code = await ctx.prompt("Code shown on the other device (leave empty to stop):");
|
|
786
|
+
s = await c["devices.pairConfirm"]({
|
|
787
|
+
pairingId: s.pairingId,
|
|
788
|
+
accept: code !== "",
|
|
789
|
+
...code !== "" ? { code } : {}
|
|
790
|
+
});
|
|
791
|
+
if (s.state !== "confirm") break;
|
|
792
|
+
ctx.err(`${t.status("error")} ${s.error ?? "That code does not match."}\n`);
|
|
793
|
+
}
|
|
794
|
+
if (s.state === "failed") break;
|
|
795
|
+
if (s.state === "waiting_peer") ctx.out("Waiting for the other device.\n");
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
await sleep(400);
|
|
799
|
+
s = await c["devices.pairStatus"]({ pairingId: s.pairingId });
|
|
800
|
+
}
|
|
801
|
+
if (s.state === "done") {
|
|
802
|
+
ctx.out(`${t.status("ok")} ${t.bold("Paired.")} ${s.peer ? `${s.peer.name} and this device` : "The devices"} now see each other's sessions.\n`);
|
|
803
|
+
return 0;
|
|
804
|
+
}
|
|
805
|
+
return fail(ctx, {
|
|
806
|
+
what: "Pairing did not finish",
|
|
807
|
+
detail: [s.error ?? (s.state === "failed" ? "The pairing failed." : "It timed out.")],
|
|
808
|
+
fix: "Start it again on both devices. If a code did not match although you typed it carefully, someone may be in between.",
|
|
809
|
+
exit: 1,
|
|
810
|
+
ref: "e_pair"
|
|
811
|
+
});
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
async function revoke(ctx, device, yes) {
|
|
815
|
+
const t = ctx.theme;
|
|
816
|
+
if (!device) return fail(ctx, {
|
|
817
|
+
what: "conveno devices revoke needs a device",
|
|
818
|
+
detail: ["Give its name or id, as conveno devices lists them."],
|
|
819
|
+
fix: `For example ${cmd(t, "conveno devices revoke desktop")}.`,
|
|
820
|
+
exit: 2,
|
|
821
|
+
ref: "e_usage"
|
|
822
|
+
});
|
|
823
|
+
if (!yes) {
|
|
824
|
+
if (!ctx.interactive) return fail(ctx, {
|
|
825
|
+
what: "Needs a terminal to confirm",
|
|
826
|
+
detail: ["Nothing was revoked."],
|
|
827
|
+
fix: `Run ${cmd(t, `conveno devices revoke ${device} --yes`)}.`,
|
|
828
|
+
exit: 2,
|
|
829
|
+
ref: "e_no_tty"
|
|
830
|
+
});
|
|
831
|
+
if (!await ctx.confirm(`Revoke ${device}? It can no longer read or send messages for your sessions.`, false)) {
|
|
832
|
+
ctx.out(`${t.status("info")} Nothing was changed.\n`);
|
|
833
|
+
return 0;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return withClient(ctx, true, async (c) => {
|
|
837
|
+
const r = await c["devices.revoke"]({ device });
|
|
838
|
+
ctx.out(`${t.status("ok")} Revoked ${t.bold(r.revoked.name)} ${t.paint("quiet", r.revoked.deviceId)}. The relay refuses it from now on and ends its login.\n`);
|
|
839
|
+
return 0;
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
async function rename(ctx, name) {
|
|
843
|
+
if (!name) return fail(ctx, {
|
|
844
|
+
what: "conveno devices rename needs a name",
|
|
845
|
+
fix: `For example ${cmd(ctx.theme, "conveno devices rename laptop")}.`,
|
|
846
|
+
exit: 2,
|
|
847
|
+
ref: "e_usage"
|
|
848
|
+
});
|
|
849
|
+
return withClient(ctx, true, async (c) => {
|
|
850
|
+
const r = await c["devices.rename"]({ name });
|
|
851
|
+
ctx.out(`${ctx.theme.status("ok")} This device is now called ${ctx.theme.bold(r.name)}.\n`);
|
|
852
|
+
return 0;
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
/** Clear a conflict by taking the relay's list, if its head is the one the owner typed. */
|
|
856
|
+
async function accept(ctx, head, yes) {
|
|
857
|
+
const t = ctx.theme;
|
|
858
|
+
if (!head || !/^[0-9a-f]{64}$/.test(head)) return fail(ctx, {
|
|
859
|
+
what: "conveno devices accept needs the full head of the device list",
|
|
860
|
+
detail: ["Run conveno devices on a device you trust and copy the 64-character head it shows."],
|
|
861
|
+
fix: `For example ${cmd(t, "conveno devices accept 3f1c…")} with all 64 characters.`,
|
|
862
|
+
exit: 2,
|
|
863
|
+
ref: "e_usage"
|
|
864
|
+
});
|
|
865
|
+
if (!yes) {
|
|
866
|
+
if (!ctx.interactive) return fail(ctx, {
|
|
867
|
+
what: "Needs a terminal to confirm",
|
|
868
|
+
detail: ["Nothing was changed."],
|
|
869
|
+
fix: `Run it again with ${cmd(t, "--yes")}.`,
|
|
870
|
+
exit: 2,
|
|
871
|
+
ref: "e_no_tty"
|
|
872
|
+
});
|
|
873
|
+
if (!await ctx.confirm(`Take the relay's device list with head ${head.slice(0, 16)}? Only do this if a device you trust shows the same head.`, false)) {
|
|
874
|
+
ctx.out(`${t.status("info")} Nothing was changed.\n`);
|
|
875
|
+
return 0;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
return withClient(ctx, true, async (c) => {
|
|
879
|
+
const r = await c["devices.accept"]({ head });
|
|
880
|
+
ctx.out(`${t.status("ok")} ${t.bold("Accepted.")} The device list now has head ${r.list.head.slice(0, 16)}.\n`);
|
|
881
|
+
if (!r.member) ctx.out(` This device is not in that list, so it stays off the relay. Pair it again with ${cmd(t, "conveno devices join")}.\n`);
|
|
882
|
+
else ctx.out(` Run ${cmd(t, "conveno devices")} and revoke any device you do not recognize.\n`);
|
|
883
|
+
return 0;
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
/** Forget this device's copy of the list after a reset or when the relay's list left it out. */
|
|
887
|
+
async function reset(ctx, yes) {
|
|
888
|
+
const t = ctx.theme;
|
|
889
|
+
if (!yes) {
|
|
890
|
+
if (!ctx.interactive) return fail(ctx, {
|
|
891
|
+
what: "Needs a terminal to confirm",
|
|
892
|
+
detail: ["Nothing was changed."],
|
|
893
|
+
fix: `Run it again with ${cmd(t, "--yes")}.`,
|
|
894
|
+
exit: 2,
|
|
895
|
+
ref: "e_no_tty"
|
|
896
|
+
});
|
|
897
|
+
if (!await ctx.confirm("Forget this device's device list? It is then unpaired and has to be paired again.", false)) {
|
|
898
|
+
ctx.out(`${t.status("info")} Nothing was changed.\n`);
|
|
899
|
+
return 0;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
return withClient(ctx, true, async (c) => {
|
|
903
|
+
await c["devices.reset"]({});
|
|
904
|
+
ctx.out(`${t.status("ok")} This device forgot its device list. Pair it with ${cmd(t, "conveno devices pair")} on a device you trust and ${cmd(t, "conveno devices join")} here.\n`);
|
|
905
|
+
return 0;
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
async function runDevices(ctx, argv) {
|
|
909
|
+
const spec = COMMANDS.find((c) => c.name === "devices");
|
|
910
|
+
if (!spec) return 2;
|
|
911
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
912
|
+
if (typeof parsed === "number") return parsed;
|
|
913
|
+
const [sub = "list", arg] = parsed.positionals;
|
|
914
|
+
switch (sub) {
|
|
915
|
+
case "list": return list(ctx);
|
|
916
|
+
case "pair": return pair(ctx, "invite");
|
|
917
|
+
case "join": return pair(ctx, "join");
|
|
918
|
+
case "revoke": return revoke(ctx, arg, parsed.values.yes === true);
|
|
919
|
+
case "rename": return rename(ctx, arg);
|
|
920
|
+
case "accept": return accept(ctx, arg, parsed.values.yes === true);
|
|
921
|
+
case "reset": return reset(ctx, parsed.values.yes === true);
|
|
922
|
+
default: return fail(ctx, {
|
|
923
|
+
what: `Unknown devices command "${sub}"`,
|
|
924
|
+
detail: ["Known: list, pair, join, revoke, rename, accept, reset."],
|
|
925
|
+
fix: `Run ${cmd(ctx.theme, "conveno devices --help")}.`,
|
|
926
|
+
exit: 2,
|
|
927
|
+
ref: "e_usage"
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
const STATE_TEXT = {
|
|
932
|
+
logged_out: "off, not logged in",
|
|
933
|
+
not_pro: "off, the account is not on Pro",
|
|
934
|
+
unpaired: "off, no paired devices",
|
|
935
|
+
connecting: "connecting",
|
|
936
|
+
connected: "connected",
|
|
937
|
+
disconnected: "disconnected, retrying",
|
|
938
|
+
revoked: "off, this device was revoked"
|
|
939
|
+
};
|
|
940
|
+
async function runRelay(ctx, argv) {
|
|
941
|
+
const t = ctx.theme;
|
|
942
|
+
const spec = COMMANDS.find((c) => c.name === "relay");
|
|
943
|
+
if (!spec) return 2;
|
|
944
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
945
|
+
if (typeof parsed === "number") return parsed;
|
|
946
|
+
const [sub = "status"] = parsed.positionals;
|
|
947
|
+
if (sub !== "status") return fail(ctx, {
|
|
948
|
+
what: `Unknown relay command "${sub}"`,
|
|
949
|
+
fix: `Run ${cmd(t, "conveno relay status")}.`,
|
|
950
|
+
exit: 2,
|
|
951
|
+
ref: "e_usage"
|
|
952
|
+
});
|
|
953
|
+
return withClient(ctx, false, async (c) => {
|
|
954
|
+
const r = await c["relay.status"]({});
|
|
955
|
+
const q = (w) => t.paint("quiet", w);
|
|
956
|
+
const glyph = r.state === "connected" ? t.status("ok") : t.status("info");
|
|
957
|
+
ctx.out(`${glyph} relay: ${t.bold(STATE_TEXT[r.state])} ${q(r.relayUrl)}\n`);
|
|
958
|
+
if (r.detail) ctx.out(` ${r.detail}\n`);
|
|
959
|
+
ctx.out(` this device: ${t.bold(r.device.name)} ${q(r.device.fingerprint)}\n`);
|
|
960
|
+
ctx.out(listLine(ctx, r.list));
|
|
961
|
+
if (r.peers.length > 0) {
|
|
962
|
+
ctx.out(` ${plural(r.peers.length, "other device")}:\n`);
|
|
963
|
+
for (const p of r.peers) ctx.out(` ${p.online ? t.status("idle") : t.status("offline")} ${p.name} ${q(p.online ? `online, ${plural(p.sessions, "session")}` : "offline")}\n`);
|
|
964
|
+
}
|
|
965
|
+
if (r.conflict) {
|
|
966
|
+
ctx.err(conflictBlock(ctx, r.conflict));
|
|
967
|
+
return 1;
|
|
968
|
+
}
|
|
969
|
+
return 0;
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
// src/acp-doctor.ts
|
|
973
|
+
/** ACP readiness of the given CLIs, in order. CLIs with no ACP entry are left out. */
|
|
974
|
+
function acpReadiness(ctx, clis) {
|
|
975
|
+
const npxConsent = readSettings(dataPaths(ctx.platform, ctx.dataDir).settings).acpAdapterNpx === true;
|
|
976
|
+
const out = [];
|
|
977
|
+
for (const cli of clis) {
|
|
978
|
+
const acp = SPAWN_TABLE[cli]?.acp;
|
|
979
|
+
if (!acp) continue;
|
|
980
|
+
const res = resolveAcpProgram(cli, acp, {
|
|
981
|
+
env: ctx.env,
|
|
982
|
+
which: (name) => findOnPath(name, ctx.env, ctx.platform),
|
|
983
|
+
npxConsent
|
|
984
|
+
});
|
|
985
|
+
if (res.ok) {
|
|
986
|
+
const { source, args } = res.run;
|
|
987
|
+
const command = source.startsWith("path:") ? [source.slice(5), ...acp.args].join(" ") : source.startsWith("npx:") ? [
|
|
988
|
+
"npx",
|
|
989
|
+
...args,
|
|
990
|
+
...acp.args
|
|
991
|
+
].join(" ") : source.slice(9);
|
|
992
|
+
out.push({
|
|
993
|
+
cli,
|
|
994
|
+
command,
|
|
995
|
+
adapter: source,
|
|
996
|
+
...source.startsWith("npx:") ? { onDemand: true } : {}
|
|
997
|
+
});
|
|
998
|
+
continue;
|
|
999
|
+
}
|
|
1000
|
+
out.push({
|
|
1001
|
+
cli,
|
|
1002
|
+
...acp.adapterPackage ? { install: adapterInstallCommand(acp.adapterPackage) } : {},
|
|
1003
|
+
...res.reason === "no-npx" ? { noNpx: true } : {}
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
return out;
|
|
1007
|
+
}
|
|
1008
|
+
/** The lines doctor prints. Informational: a missing ACP server is not a warning. */
|
|
1009
|
+
function acpDoctorLines(ctx, clis) {
|
|
1010
|
+
const rows = acpReadiness(ctx, clis);
|
|
1011
|
+
if (rows.length === 0) return [];
|
|
1012
|
+
const t = ctx.theme;
|
|
1013
|
+
const q = (w) => t.paint("quiet", w);
|
|
1014
|
+
const table = rows.map((r) => [` ${r.command ? t.status("ok") : t.glyph("offline")} ${r.cli}`, r.command ? r.onDemand ? `ready: ${r.command} (on demand; the first start downloads the package, which can take minutes)` : r.adapter?.startsWith("override:") ? `ready: ${r.command} (${acpOverrideVar(r.cli)})` : `ready: ${r.command}` : r.noNpx ? `npx was not found on PATH. Install Node.js, or install the ACP adapter: ${r.install}` : r.install ? `to enable, install the ACP adapter: ${r.install} (or run conveno init to fetch it with npx)` : q("its ACP server was not found on PATH")]);
|
|
1015
|
+
return [
|
|
1016
|
+
"",
|
|
1017
|
+
`ACP workers ${q("(conveno spawn <cli> --acp)")}`,
|
|
1018
|
+
...columns(table),
|
|
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
|
+
];
|
|
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";
|
|
1028
|
+
}
|
|
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
|
+
/**
|
|
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.
|
|
1036
|
+
*/
|
|
1037
|
+
function activeTiers(row) {
|
|
1038
|
+
const caps = row.adapter.delivery?.(row.detection);
|
|
1039
|
+
if (!caps) return row.adapter.deliveryTier === "inbox" || row.hooks === "ok" ? [tierWord(row.adapter.deliveryTier)] : ["inbox"];
|
|
1040
|
+
if (!hasAny(caps) || row.hooks !== "ok") return ["inbox"];
|
|
1041
|
+
return [
|
|
1042
|
+
...caps.nextTurn ? ["next turn"] : [],
|
|
1043
|
+
...caps.endOfTurn ? ["end of turn"] : [],
|
|
1044
|
+
...caps.idleWake ? ["idle wake"] : []
|
|
1045
|
+
];
|
|
1046
|
+
}
|
|
1047
|
+
async function inspect(ctx, adapter) {
|
|
1048
|
+
const env = adapterEnv(ctx);
|
|
1049
|
+
let detection;
|
|
1050
|
+
try {
|
|
1051
|
+
detection = await adapter.detect(env);
|
|
1052
|
+
} catch {
|
|
1053
|
+
detection = {
|
|
1054
|
+
installed: false,
|
|
1055
|
+
configPaths: []
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
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
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
/** A note for a CLI outside the tested range. Newer is a warning, older than the minimum a problem. */
|
|
1084
|
+
function versionBlock(t, adapter, version, status) {
|
|
1085
|
+
const name = adapter.displayName;
|
|
1086
|
+
if (status.kind === "older") return {
|
|
1087
|
+
problem: true,
|
|
1088
|
+
text: errorBlock(t, {
|
|
1089
|
+
what: `${name} ${version} is older than Conveno supports`,
|
|
1090
|
+
detail: [`Conveno needs ${name} ${status.minimum} or newer.`],
|
|
1091
|
+
fix: `Upgrade ${name}, then run ${cmd(t, "conveno doctor")} again.`,
|
|
1092
|
+
exit: 1,
|
|
1093
|
+
ref: "e_cli_old"
|
|
1094
|
+
})
|
|
1095
|
+
};
|
|
1096
|
+
if (status.kind === "newer") return {
|
|
1097
|
+
problem: false,
|
|
1098
|
+
text: warnBlock(t, `${name} ${version} is newer than the ${status.verified} Conveno was tested with.`, "Nothing to do unless messages stop arriving. Please report it at https://github.com/0xPixelNinja/conveno/issues if something breaks.", "CLI vendors change config and hook formats often. A nightly check tests the newest releases and raises the tested version when they pass.")
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
async function runDoctor(ctx, argv = []) {
|
|
1102
|
+
const t = ctx.theme;
|
|
1103
|
+
const spec = COMMANDS.find((c) => c.name === "doctor");
|
|
1104
|
+
if (spec) {
|
|
1105
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
1106
|
+
if (typeof parsed === "number") return parsed;
|
|
1107
|
+
}
|
|
1108
|
+
let ok = 0;
|
|
1109
|
+
let warnings = 0;
|
|
1110
|
+
let problems = 0;
|
|
1111
|
+
const notes = [];
|
|
1112
|
+
let daemonLine;
|
|
1113
|
+
try {
|
|
1114
|
+
const client = await ctx.connect(connectOpts(ctx, false));
|
|
1115
|
+
try {
|
|
1116
|
+
const { sessions } = await client["session.list"]({ includeOffline: true });
|
|
1117
|
+
daemonLine = [` ${t.status("ok")} daemon`, `running, ${plural(sessions.length, "session")}`];
|
|
1118
|
+
ok++;
|
|
1119
|
+
} finally {
|
|
1120
|
+
await client.close().catch(() => void 0);
|
|
1121
|
+
}
|
|
1122
|
+
} catch (e) {
|
|
1123
|
+
const problem = daemonProblem(t, e);
|
|
1124
|
+
if (problem.notRunning) {
|
|
1125
|
+
daemonLine = [` ${t.status("warn")} daemon`, "not running"];
|
|
1126
|
+
warnings++;
|
|
1127
|
+
notes.push(warnBlock(t, "The Conveno daemon is not running.", problem.fix, problem.why));
|
|
1128
|
+
} else {
|
|
1129
|
+
daemonLine = [` ${t.status("error")} daemon`, "cannot be reached"];
|
|
1130
|
+
problems++;
|
|
1131
|
+
notes.push(errorBlock(t, {
|
|
1132
|
+
what: "The Conveno daemon cannot be reached",
|
|
1133
|
+
detail: [problem.why],
|
|
1134
|
+
fix: problem.fix,
|
|
1135
|
+
exit: 1,
|
|
1136
|
+
ref: "e_daemon"
|
|
1137
|
+
}));
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
ctx.out(`${columns([daemonLine]).join("\n")}\n\n`);
|
|
1141
|
+
if (!(await ctx.ancestry(ANCESTRY_TIMEOUT_MS)).complete) {
|
|
1142
|
+
warnings++;
|
|
1143
|
+
notes.push(warnBlock(t, "Process ancestry is unavailable.", `Run ${cmd(t, "conveno doctor")} from a normal desktop session, or allow this user to read the process list. Messages still reach the inbox tool either way.`, ctx.platform === "win32" ? "Windows refused the process list (WMI denies it to non-admin remote logons such as SSH). A hook can then only match a session whose CLI is its direct parent, so next-turn delivery can miss sessions started through a launcher such as conveno.cmd." : "The process list could not be read. A hook can then only match a session whose CLI is its direct parent, so next-turn delivery can miss sessions started through a launcher or a shell."));
|
|
1144
|
+
}
|
|
1145
|
+
const rows = await Promise.all(ctx.adapters.map((a) => inspect(ctx, a)));
|
|
1146
|
+
const q = (w) => t.paint("quiet", w);
|
|
1147
|
+
const table = [[
|
|
1148
|
+
` ${q("CLI")}`,
|
|
1149
|
+
q("NAME"),
|
|
1150
|
+
q("VERSION"),
|
|
1151
|
+
q("MCP"),
|
|
1152
|
+
q("HOOKS"),
|
|
1153
|
+
q("DELIVERY"),
|
|
1154
|
+
q("NOTE")
|
|
1155
|
+
]];
|
|
1156
|
+
const yesNo = (v) => v === null ? q("n/a") : v === "ok" ? "yes" : t.paint("warn", v === "missing" ? "not configured" : "needs update");
|
|
1157
|
+
for (const r of rows) {
|
|
1158
|
+
const { adapter, detection } = r;
|
|
1159
|
+
if (!detection.installed) {
|
|
1160
|
+
table.push([
|
|
1161
|
+
` ${t.glyph("offline")} ${adapter.cli}`,
|
|
1162
|
+
adapter.displayName,
|
|
1163
|
+
"",
|
|
1164
|
+
"",
|
|
1165
|
+
"",
|
|
1166
|
+
"",
|
|
1167
|
+
q("not found on PATH")
|
|
1168
|
+
]);
|
|
1169
|
+
continue;
|
|
1170
|
+
}
|
|
1171
|
+
const good = r.mcp === "ok" && (r.hooks === null || r.hooks === "ok") && !r.planError;
|
|
1172
|
+
const compat = compatStatus(adapter.cli, detection.version, ctx.compat);
|
|
1173
|
+
const tiers = activeTiers(r);
|
|
1174
|
+
let note = tiers.includes("idle wake") ? "auto mode wakes idle sessions" : tiers.includes("end of turn") ? "auto mode: at the end of a turn, no idle wake" : tiers.includes("next turn") ? "delivered at the next prompt" : "read through the inbox tool";
|
|
1175
|
+
if (!good) note = r.planError ? "config could not be read" : r.mcp === "outdated" || r.hooks === "outdated" ? "needs an update" : "not fully configured";
|
|
1176
|
+
if (compat.kind === "older") note = `older than the minimum ${compat.minimum}`;
|
|
1177
|
+
else if (compat.kind === "newer" && good) note = `newer than tested (${compat.verified})`;
|
|
1178
|
+
const glyph = compat.kind === "older" ? t.status("error") : good && compat.kind !== "newer" ? t.status("ok") : t.status("warn");
|
|
1179
|
+
table.push([
|
|
1180
|
+
` ${glyph} ${adapter.cli}`,
|
|
1181
|
+
adapter.displayName,
|
|
1182
|
+
detection.version ?? "",
|
|
1183
|
+
yesNo(r.mcp),
|
|
1184
|
+
yesNo(r.hooks),
|
|
1185
|
+
tiers.join(", "),
|
|
1186
|
+
q(note)
|
|
1187
|
+
]);
|
|
1188
|
+
if (r.planError) {
|
|
1189
|
+
problems++;
|
|
1190
|
+
notes.push(errorBlock(t, {
|
|
1191
|
+
what: `${adapter.displayName} config could not be read`,
|
|
1192
|
+
detail: [r.planError],
|
|
1193
|
+
fix: "Repair the file named above, then run conveno doctor again.",
|
|
1194
|
+
exit: 1,
|
|
1195
|
+
ref: "e_config"
|
|
1196
|
+
}));
|
|
1197
|
+
} else if (good) {
|
|
1198
|
+
if (compat.kind === "ok" || compat.kind === "unknown") ok++;
|
|
1199
|
+
} else {
|
|
1200
|
+
warnings++;
|
|
1201
|
+
const named = [["the MCP server", r.mcp], ["the hooks", r.hooks]];
|
|
1202
|
+
const list = (state) => named.filter(([, s]) => s === state).map(([n]) => n).join(" and ");
|
|
1203
|
+
const missing = list("missing");
|
|
1204
|
+
const outdated = list("outdated");
|
|
1205
|
+
const fix = `Run ${cmd(t, "conveno init")}, then restart open ${adapter.displayName} sessions.`;
|
|
1206
|
+
notes.push(missing && outdated ? warnBlock(t, `${adapter.displayName} is missing ${missing} and needs an update to ${outdated}.`, fix) : missing ? warnBlock(t, `${adapter.displayName} is missing ${missing}.`, fix) : warnBlock(t, `${adapter.displayName} needs an update.`, fix, `Conveno's setup for ${outdated} is from an older version. ${cmd(t, "conveno init")} shows exactly which lines change.`));
|
|
1207
|
+
}
|
|
1208
|
+
const versionNote = versionBlock(t, adapter, detection.version, compat);
|
|
1209
|
+
if (versionNote) {
|
|
1210
|
+
notes.push(versionNote.text);
|
|
1211
|
+
if (versionNote.problem) problems++;
|
|
1212
|
+
else warnings++;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
ctx.out(`${columns(table).join("\n")}\n`);
|
|
1216
|
+
if (rows.some((r) => r.detection.installed && activeTiers(r).some((t) => t !== "next turn" && t !== "inbox"))) ctx.out(`${q("End of turn and idle wake apply to sessions in auto mode; see conveno auto.")}\n`);
|
|
1217
|
+
const acpLines = acpDoctorLines(ctx, rows.filter((r) => r.detection.installed).map((r) => r.adapter.cli));
|
|
1218
|
+
if (acpLines.length > 0) ctx.out(`${acpLines.join("\n")}\n`);
|
|
1219
|
+
const relayRows = [];
|
|
1220
|
+
for (const r of rows) {
|
|
1221
|
+
if (!r.detection.installed || !r.adapter.permissionHookInstalled || r.planError) continue;
|
|
1222
|
+
const installed = await r.adapter.permissionHookInstalled(adapterEnv(ctx)).catch(() => false);
|
|
1223
|
+
relayRows.push([` ${r.adapter.cli}`, q(installed ? "permission relay: hook installed (off until turned on per session)" : "permission relay: not installed (optional)")]);
|
|
1224
|
+
}
|
|
1225
|
+
if (relayRows.length > 0) ctx.out(`\n${columns(relayRows).join("\n")}\n`);
|
|
1226
|
+
if (!rows.some((r) => r.detection.installed)) {
|
|
1227
|
+
notes.push(warnBlock(t, "No supported AI coding CLI was found on PATH.", "Install Claude Code, Codex CLI or OpenCode, then run conveno init."));
|
|
1228
|
+
warnings++;
|
|
1229
|
+
}
|
|
1230
|
+
for (const n of notes) ctx.err(`\n${n.trimEnd()}\n`);
|
|
1231
|
+
ctx.out(`\n${ok} ok, ${plural(warnings, "warning")}, ${plural(problems, "problem")}\n`);
|
|
1232
|
+
return problems > 0 ? 1 : 0;
|
|
1233
|
+
}
|
|
1234
|
+
// src/version.ts
|
|
1235
|
+
const VERSION = "0.2.0-rc.1";
|
|
1236
|
+
// src/errorLog.ts
|
|
1237
|
+
/** The message of an unexpected error, as it is. Not the softened text `plainError` gives. */
|
|
1238
|
+
function rawMessage(e) {
|
|
1239
|
+
if (e instanceof Error) return `${e.name}: ${e.message}`;
|
|
1240
|
+
return String(e);
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Write the full stack of an unexpected error to `<data dir>/logs/<timestamp>-error.log`, readable
|
|
1244
|
+
* by the user only. Returns the path, or undefined when the log could not be written (the error is
|
|
1245
|
+
* still reported, just without a log).
|
|
1246
|
+
*/
|
|
1247
|
+
async function writeErrorLog(ctx, argv, e) {
|
|
1248
|
+
try {
|
|
1249
|
+
const dir = dataPaths(ctx.platform, ctx.dataDir).logs;
|
|
1250
|
+
await mkdir(dir, {
|
|
1251
|
+
recursive: true,
|
|
1252
|
+
mode: 448
|
|
1253
|
+
});
|
|
1254
|
+
const stamp = ctx.now().toISOString().replace(/[:.]/g, "-");
|
|
1255
|
+
const file = join(dir, `${stamp}-error.log`);
|
|
1256
|
+
const command = argv.slice(0, 2).join(" ");
|
|
1257
|
+
const text = [
|
|
1258
|
+
`conveno ${VERSION} ${command}`,
|
|
1259
|
+
"ref e_internal",
|
|
1260
|
+
`time ${ctx.now().toISOString()}`,
|
|
1261
|
+
`platform ${ctx.platform}, node ${process.version}`,
|
|
1262
|
+
"",
|
|
1263
|
+
e instanceof Error ? e.stack ?? rawMessage(e) : rawMessage(e),
|
|
1264
|
+
e instanceof Error && e.cause !== void 0 ? `\nCaused by: ${e.cause instanceof Error ? e.cause.stack ?? rawMessage(e.cause) : String(e.cause)}` : "",
|
|
1265
|
+
""
|
|
1266
|
+
].join("\n");
|
|
1267
|
+
await writeFile(file, text, { mode: 384 });
|
|
1268
|
+
await chmod(file, 384).catch(() => void 0);
|
|
1269
|
+
return file;
|
|
1270
|
+
} catch {
|
|
1271
|
+
return;
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
// src/forget.ts
|
|
1275
|
+
const UNIT_MS = {
|
|
1276
|
+
m: 6e4,
|
|
1277
|
+
h: 36e5,
|
|
1278
|
+
d: 864e5
|
|
1279
|
+
};
|
|
1280
|
+
/** `30m`, `24h` or `7d` as milliseconds, or undefined when the text is anything else. */
|
|
1281
|
+
function parseDuration(text) {
|
|
1282
|
+
const m = /^(\d{1,6})([mhd])$/.exec(text);
|
|
1283
|
+
if (!m) return void 0;
|
|
1284
|
+
const ms = Number(m[1]) * UNIT_MS[m[2]];
|
|
1285
|
+
return ms > 0 ? ms : void 0;
|
|
1286
|
+
}
|
|
1287
|
+
/** Rebuild the command line the user typed, for the "run it again with --yes" hint. */
|
|
1288
|
+
function rerunLine(names, flags) {
|
|
1289
|
+
return [
|
|
1290
|
+
"conveno forget",
|
|
1291
|
+
...names.map((n) => n.includes("*") ? `'${n}'` : n),
|
|
1292
|
+
...flags.offline ? ["--offline"] : [],
|
|
1293
|
+
...flags.olderThan ? ["--older-than", flags.olderThan] : []
|
|
1294
|
+
].join(" ");
|
|
1295
|
+
}
|
|
1296
|
+
async function runForget(ctx, argv) {
|
|
1297
|
+
const t = ctx.theme;
|
|
1298
|
+
const spec = COMMANDS.find((c) => c.name === "forget");
|
|
1299
|
+
if (!spec) return 2;
|
|
1300
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
1301
|
+
if (typeof parsed === "number") return parsed;
|
|
1302
|
+
const names = parsed.positionals;
|
|
1303
|
+
const offline = parsed.values.offline === true;
|
|
1304
|
+
const olderThan = typeof parsed.values["older-than"] === "string" ? parsed.values["older-than"] : void 0;
|
|
1305
|
+
const dryRun = parsed.values["dry-run"] === true;
|
|
1306
|
+
const yes = parsed.values.yes === true;
|
|
1307
|
+
const help = `Run ${cmd(t, "conveno forget --help")} to see the options.`;
|
|
1308
|
+
for (const n of names) if (!SessionNamePattern.safeParse(n).success) return fail(ctx, {
|
|
1309
|
+
what: `"${n}" is not a session name or pattern`,
|
|
1310
|
+
detail: ["Names use lowercase letters, digits and \".\", \"_\", \"@\" or \"-\". A \"*\" matches any run of characters."],
|
|
1311
|
+
fix: `Run ${cmd(t, "conveno status --all")} to see the names.`,
|
|
1312
|
+
exit: 2,
|
|
1313
|
+
ref: "e_usage"
|
|
1314
|
+
});
|
|
1315
|
+
let olderThanMs;
|
|
1316
|
+
if (olderThan !== void 0) {
|
|
1317
|
+
olderThanMs = parseDuration(olderThan);
|
|
1318
|
+
if (olderThanMs === void 0) return fail(ctx, {
|
|
1319
|
+
what: `"${olderThan}" is not a duration`,
|
|
1320
|
+
detail: ["Use a whole number and a unit: 30m for minutes, 24h for hours, 7d for days."],
|
|
1321
|
+
fix: help,
|
|
1322
|
+
exit: 2,
|
|
1323
|
+
ref: "e_usage"
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
if (names.length === 0 && !offline && olderThanMs === void 0) return fail(ctx, {
|
|
1327
|
+
what: "conveno forget needs to know which sessions to forget",
|
|
1328
|
+
detail: ["Name them, or pass --offline for every offline session."],
|
|
1329
|
+
fix: `For example ${cmd(t, "conveno forget 'conveno-real-*'")} or ${cmd(t, "conveno forget --offline --older-than 7d")}.`,
|
|
1330
|
+
exit: 2,
|
|
1331
|
+
ref: "e_usage"
|
|
1332
|
+
});
|
|
1333
|
+
let client;
|
|
1334
|
+
try {
|
|
1335
|
+
client = await ctx.connect(connectOpts(ctx, false));
|
|
1336
|
+
} catch (e) {
|
|
1337
|
+
const problem = daemonProblem(t, e);
|
|
1338
|
+
return fail(ctx, {
|
|
1339
|
+
what: problem.notRunning ? "The Conveno daemon is not running" : "The Conveno daemon cannot be reached",
|
|
1340
|
+
detail: [problem.notRunning ? "Sessions live in the daemon, so there is nothing to forget until it runs." : problem.why],
|
|
1341
|
+
fix: problem.notRunning ? `Run ${cmd(t, "conveno daemon start")}.` : problem.fix,
|
|
1342
|
+
exit: 1,
|
|
1343
|
+
ref: "e_daemon"
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
try {
|
|
1347
|
+
const selector = {
|
|
1348
|
+
...names.length > 0 ? { names } : {},
|
|
1349
|
+
...names.length === 0 || olderThanMs !== void 0 ? { olderThanMs: olderThanMs ?? 0 } : {}
|
|
1350
|
+
};
|
|
1351
|
+
const preview = await client["session.forget"]({
|
|
1352
|
+
...selector,
|
|
1353
|
+
dryRun: true
|
|
1354
|
+
});
|
|
1355
|
+
const ids = new Set(preview.forgotten.map((s) => s.id));
|
|
1356
|
+
const picked = (await client["session.list"]({ includeOffline: true })).sessions.filter((s) => ids.has(s.id));
|
|
1357
|
+
if (preview.skippedOnline.length > 0) {
|
|
1358
|
+
ctx.out(`${t.status("warn")} ${t.bold(`Skipped ${plural(preview.skippedOnline.length, "online session")}`)}\n`);
|
|
1359
|
+
ctx.out(`${columns(preview.skippedOnline.map((s) => [` ${t.status("idle")} ${t.bold(s.name)}`, t.paint("quiet", "online, a running session is never forgotten")])).join("\n")}\n\n`);
|
|
1360
|
+
}
|
|
1361
|
+
if (picked.length === 0) {
|
|
1362
|
+
ctx.out(`${t.status("info")} Nothing to forget. ${t.paint("quiet", `${cmd(t, "conveno status --all")} lists the offline sessions.`)}\n`);
|
|
1363
|
+
return 0;
|
|
1364
|
+
}
|
|
1365
|
+
ctx.out(`${t.bold(dryRun ? `Would forget ${plural(picked.length, "session")}` : `Will forget ${plural(picked.length, "session")}`)}\n\n`);
|
|
1366
|
+
ctx.out(`${renderSessions(ctx, picked)}\n\n`);
|
|
1367
|
+
ctx.out(` ${t.paint("quiet", "Their queued messages are deleted too. Messages they sent stay with the receivers.")}\n\n`);
|
|
1368
|
+
if (dryRun) {
|
|
1369
|
+
ctx.out(`${t.status("info")} Dry run. Nothing was changed.\n`);
|
|
1370
|
+
return 0;
|
|
1371
|
+
}
|
|
1372
|
+
if (!yes) {
|
|
1373
|
+
if (!ctx.interactive) return fail(ctx, {
|
|
1374
|
+
what: "Needs a terminal to confirm",
|
|
1375
|
+
detail: ["No sessions were forgotten."],
|
|
1376
|
+
fix: `Run ${cmd(t, `${rerunLine(names, {
|
|
1377
|
+
offline,
|
|
1378
|
+
...olderThan ? { olderThan } : {}
|
|
1379
|
+
})} --yes`)} to forget the sessions listed above.`,
|
|
1380
|
+
exit: 2,
|
|
1381
|
+
ref: "e_no_tty"
|
|
1382
|
+
});
|
|
1383
|
+
if (!await ctx.confirm(`Forget ${plural(picked.length, "session")}?`, false)) {
|
|
1384
|
+
ctx.out(`${t.status("info")} Nothing was changed.\n`);
|
|
1385
|
+
return 0;
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
const done = await client["session.forget"]({ ids: [...ids] });
|
|
1389
|
+
ctx.out(`${t.status("ok")} ${t.bold("Done.")} Forgot ${plural(done.forgotten.length, "session")}.\n`);
|
|
1390
|
+
return 0;
|
|
1391
|
+
} finally {
|
|
1392
|
+
await client.close().catch(() => void 0);
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
// src/acp-offer.ts
|
|
1396
|
+
/** The adapter packages an installed CLI needs and that are not on PATH (nor overridden). */
|
|
1397
|
+
function missingAdapters(ctx, installed) {
|
|
1398
|
+
const out = [];
|
|
1399
|
+
for (const { cli, displayName } of installed) {
|
|
1400
|
+
const acp = SPAWN_TABLE[cli]?.acp;
|
|
1401
|
+
if (!acp?.adapterPackage) continue;
|
|
1402
|
+
if (!resolveAcpProgram(cli, acp, {
|
|
1403
|
+
env: ctx.env,
|
|
1404
|
+
which: (n) => findOnPath(n, ctx.env, ctx.platform),
|
|
1405
|
+
npxConsent: false
|
|
1406
|
+
}).ok) out.push({
|
|
1407
|
+
pkg: acp.adapterPackage,
|
|
1408
|
+
cli: displayName
|
|
1409
|
+
});
|
|
1410
|
+
}
|
|
1411
|
+
return out;
|
|
1412
|
+
}
|
|
1413
|
+
function printManual(ctx, missing) {
|
|
1414
|
+
const q = (w) => ctx.theme.paint("quiet", w);
|
|
1415
|
+
for (const { pkg } of missing) {
|
|
1416
|
+
ctx.out(` ${adapterInstallCommand(pkg)}\n`);
|
|
1417
|
+
ctx.out(` ${q(`or run it on demand: ${adapterNpxCommand(pkg)}`)}\n`);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Ask once whether ACP workers may fetch the adapters with npx. `--acp-adapters` and
|
|
1422
|
+
* `--no-acp-adapters` answer without asking and replace an earlier answer. Without a terminal, or
|
|
1423
|
+
* with `--yes`, nothing is asked and nothing is saved.
|
|
1424
|
+
*/
|
|
1425
|
+
async function offerAcpAdapters(ctx, opts) {
|
|
1426
|
+
const t = ctx.theme;
|
|
1427
|
+
const path = dataPaths(ctx.platform, ctx.dataDir).settings;
|
|
1428
|
+
const missing = missingAdapters(ctx, opts.installed);
|
|
1429
|
+
if (opts.flag !== void 0) {
|
|
1430
|
+
writeSettings(path, { acpAdapterNpx: opts.flag });
|
|
1431
|
+
if (opts.flag) ctx.out(`${t.status("ok")} ACP workers may fetch adapters with npx (pinned versions).\n`);
|
|
1432
|
+
else {
|
|
1433
|
+
ctx.out(`${t.status("info")} ACP workers will not fetch adapters with npx.\n`);
|
|
1434
|
+
if (missing.length > 0) {
|
|
1435
|
+
ctx.out(" To use ACP workers, install the adapters yourself:\n");
|
|
1436
|
+
printManual(ctx, missing);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
if (missing.length === 0) return;
|
|
1442
|
+
if (readSettings(path).acpAdapterNpx !== void 0) return;
|
|
1443
|
+
const who = missing.map((m) => m.cli).join(" and ");
|
|
1444
|
+
ctx.out(`\n${t.bold("ACP workers")} let conveno spawn <cli> --acp drive a worker over the Agent Client Protocol.\n ${who} ${missing.length > 1 ? "need" : "needs"} a separate adapter for that. Adapters are third-party npm packages\n (Apache-2.0). Conveno does not bundle them; npx would download these on first use:
|
|
1445
|
+
${missing.map((m) => ` ${pinnedAdapter(m.pkg) ?? m.pkg}\n`).join("")}`);
|
|
1446
|
+
if (!ctx.interactive || opts.yes) {
|
|
1447
|
+
ctx.out(`${t.status("info")} Not asked. Run ${cmd(t, "conveno init --acp-adapters")} to allow npx, or install by hand:\n`);
|
|
1448
|
+
printManual(ctx, missing);
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
if (await ctx.confirm("Let ACP workers fetch these adapters with npx?", false)) {
|
|
1452
|
+
writeSettings(path, { acpAdapterNpx: true });
|
|
1453
|
+
ctx.out(`${t.status("ok")} Allowed. The first ACP worker for each takes a moment to start.\n`);
|
|
1454
|
+
} else {
|
|
1455
|
+
writeSettings(path, { acpAdapterNpx: false });
|
|
1456
|
+
ctx.out(`${t.status("info")} Not allowed. To use ACP workers, install the adapters yourself:\n`);
|
|
1457
|
+
printManual(ctx, missing);
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
// src/diff.ts
|
|
1461
|
+
const splitLines = (s) => {
|
|
1462
|
+
if (s === "") return [];
|
|
1463
|
+
const lines = s.split("\n");
|
|
1464
|
+
if (lines.at(-1) === "") lines.pop();
|
|
1465
|
+
return lines;
|
|
1466
|
+
};
|
|
1467
|
+
/** Line diff through the longest common subsequence. Fine for config files. */
|
|
1468
|
+
function diffOps(a, b) {
|
|
1469
|
+
let start = 0;
|
|
1470
|
+
while (start < a.length && start < b.length && a[start] === b[start]) start++;
|
|
1471
|
+
let endA = a.length;
|
|
1472
|
+
let endB = b.length;
|
|
1473
|
+
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
|
|
1474
|
+
endA--;
|
|
1475
|
+
endB--;
|
|
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++]
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
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
|
+
];
|
|
1530
|
+
}
|
|
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
|
+
}
|
|
1544
|
+
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++;
|
|
1551
|
+
}
|
|
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}`);
|
|
1558
|
+
}
|
|
1559
|
+
return out;
|
|
1560
|
+
}
|
|
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) {
|
|
1587
|
+
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;
|
|
1608
|
+
}
|
|
1609
|
+
async function readBytes(path) {
|
|
1610
|
+
try {
|
|
1611
|
+
return await readFile(path);
|
|
1612
|
+
} catch (e) {
|
|
1613
|
+
if (e.code === "ENOENT") return null;
|
|
1614
|
+
throw e;
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
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
|
|
1622
|
+
});
|
|
1623
|
+
if (isPosix(ctx)) await chmod(dir, 448).catch(() => void 0);
|
|
1624
|
+
}
|
|
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();
|
|
1639
|
+
}
|
|
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
|
+
}
|
|
1669
|
+
const mode = await io.mode(target);
|
|
1670
|
+
const tmp = join(dirname(target), `.${basename(target)}.conveno-${randomBytes(6).toString("hex")}.tmp`);
|
|
1671
|
+
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);
|
|
1675
|
+
} 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);
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
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";
|
|
1693
|
+
}
|
|
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;
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
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.
|
|
1704
|
+
*/
|
|
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
|
+
});
|
|
1735
|
+
}
|
|
1736
|
+
const manifest = {
|
|
1737
|
+
version: 1,
|
|
1738
|
+
createdAt: ctx.now().toISOString(),
|
|
1739
|
+
entries,
|
|
1740
|
+
...opts.markRestored ? { restoredAt: ctx.now().toISOString() } : {}
|
|
1741
|
+
};
|
|
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 = [];
|
|
1747
|
+
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
|
+
}
|
|
1773
|
+
} 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
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
if (rewrite) await writeManifest();
|
|
1806
|
+
return {
|
|
1807
|
+
backupDir,
|
|
1808
|
+
how
|
|
1809
|
+
};
|
|
1810
|
+
}
|
|
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";
|
|
1834
|
+
}
|
|
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
|
|
1851
|
+
});
|
|
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");
|
|
1855
|
+
}
|
|
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) => {
|
|
1880
|
+
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
|
+
};
|
|
1893
|
+
}
|
|
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
|
+
};
|
|
1907
|
+
}
|
|
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
|
+
}
|
|
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
|
+
});
|
|
1941
|
+
}
|
|
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 };
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
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
|
+
}) };
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
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;
|
|
2018
|
+
}
|
|
2019
|
+
async function initSetup(ctx, argv, outcome) {
|
|
2020
|
+
const t = ctx.theme;
|
|
2021
|
+
const started = ctx.now();
|
|
2022
|
+
const spec = COMMANDS.find((c) => c.name === "init");
|
|
2023
|
+
if (!spec) return 2;
|
|
2024
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
2025
|
+
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.`,
|
|
2030
|
+
exit: 2,
|
|
2031
|
+
ref: "e_usage"
|
|
2032
|
+
});
|
|
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 } : {},
|
|
2038
|
+
exit: 2,
|
|
2039
|
+
ref: "e_usage"
|
|
2040
|
+
});
|
|
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;
|
|
2061
|
+
}
|
|
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`);
|
|
2067
|
+
return 0;
|
|
2068
|
+
}
|
|
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
|
+
}
|
|
2088
|
+
// src/peek.ts
|
|
2089
|
+
async function connectOrFail(ctx) {
|
|
2090
|
+
const t = ctx.theme;
|
|
2091
|
+
try {
|
|
2092
|
+
return await ctx.connect(connectOpts(ctx, false));
|
|
2093
|
+
} catch (e) {
|
|
2094
|
+
const problem = daemonProblem(t, e);
|
|
2095
|
+
return fail(ctx, {
|
|
2096
|
+
what: problem.notRunning ? "The Conveno daemon is not running" : "The Conveno daemon cannot be reached",
|
|
2097
|
+
detail: [problem.notRunning ? "Sessions live in the daemon, so there is nothing to peek at until it runs." : problem.why],
|
|
2098
|
+
fix: problem.notRunning ? `Run ${cmd(t, "conveno daemon start")}.` : problem.fix,
|
|
2099
|
+
exit: 1,
|
|
2100
|
+
ref: "e_daemon"
|
|
2101
|
+
});
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
const isSessionRef = (s) => SessionId.safeParse(s).success || SessionNameInput.safeParse(s).success;
|
|
2105
|
+
function badSession(ctx, name) {
|
|
2106
|
+
return fail(ctx, {
|
|
2107
|
+
what: `"${name}" is not a session name`,
|
|
2108
|
+
detail: ["Names use lowercase letters, digits and \".\", \"_\", \"@\" or \"-\"."],
|
|
2109
|
+
fix: `Run ${cmd(ctx.theme, "conveno status")} to see the names.`,
|
|
2110
|
+
exit: 2,
|
|
2111
|
+
ref: "e_usage"
|
|
2112
|
+
});
|
|
2113
|
+
}
|
|
2114
|
+
/** `conveno peek on|off [session]`: the owner's switch. */
|
|
2115
|
+
async function runSwitch(ctx, peekable, session) {
|
|
2116
|
+
const t = ctx.theme;
|
|
2117
|
+
if (session !== void 0 && !isSessionRef(session)) return badSession(ctx, session);
|
|
2118
|
+
const client = await connectOrFail(ctx);
|
|
2119
|
+
if (typeof client === "number") return client;
|
|
2120
|
+
try {
|
|
2121
|
+
const res = await client["session.setPeekable"]({
|
|
2122
|
+
peekable,
|
|
2123
|
+
...session !== void 0 ? { session } : {}
|
|
2124
|
+
});
|
|
2125
|
+
if (res.sessions.length === 0) {
|
|
2126
|
+
ctx.out(`${t.status("info")} No online sessions, so nothing changed.\n`);
|
|
2127
|
+
return 0;
|
|
2128
|
+
}
|
|
2129
|
+
const names = res.sessions.map((s) => s.name).join(", ");
|
|
2130
|
+
ctx.out(`${t.status("ok")} Peek is ${t.bold(peekable ? "on" : "off")} for ${plural(res.sessions.length, "session")}: ${names}\n`);
|
|
2131
|
+
if (session === void 0) ctx.out(` ${t.paint("quiet", "Sessions that start later are peekable by default. Run it again after they start.")}\n`);
|
|
2132
|
+
return 0;
|
|
2133
|
+
} catch (e) {
|
|
2134
|
+
return daemonFailure(ctx, e);
|
|
2135
|
+
} finally {
|
|
2136
|
+
await client.close().catch(() => void 0);
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
function daemonFailure(ctx, e) {
|
|
2140
|
+
const t = ctx.theme;
|
|
2141
|
+
if (e instanceof ConvenoError) {
|
|
2142
|
+
const permission = e.code === RpcErrorCode.PermissionRequired;
|
|
2143
|
+
return fail(ctx, {
|
|
2144
|
+
what: permission ? "Peek is turned off for that session" : e.message,
|
|
2145
|
+
...permission ? { detail: [e.message] } : {},
|
|
2146
|
+
fix: e.code === RpcErrorCode.NotFound ? `Run ${cmd(t, "conveno status")} to see the sessions that are online.` : permission ? "Its owner turns peek on again with the command above." : `Run ${cmd(t, "conveno doctor")} if this keeps happening.`,
|
|
2147
|
+
exit: 1,
|
|
2148
|
+
ref: permission ? "e_peek_off" : "e_peek"
|
|
2149
|
+
});
|
|
2150
|
+
}
|
|
2151
|
+
const problem = daemonProblem(t, e);
|
|
2152
|
+
return fail(ctx, {
|
|
2153
|
+
what: "The Conveno daemon could not answer",
|
|
2154
|
+
detail: [problem.why],
|
|
2155
|
+
fix: problem.fix,
|
|
2156
|
+
exit: 1,
|
|
2157
|
+
ref: "e_daemon"
|
|
2158
|
+
});
|
|
2159
|
+
}
|
|
2160
|
+
/** `conveno peek <session> [-n N] [--raw-json]`: what another session did lately, secrets redacted. */
|
|
2161
|
+
async function runPeek(ctx, argv) {
|
|
2162
|
+
const t = ctx.theme;
|
|
2163
|
+
const spec = COMMANDS.find((c) => c.name === "peek");
|
|
2164
|
+
if (!spec) return 2;
|
|
2165
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
2166
|
+
if (typeof parsed === "number") return parsed;
|
|
2167
|
+
const [first, second] = parsed.positionals;
|
|
2168
|
+
if (first === void 0) return fail(ctx, {
|
|
2169
|
+
what: "conveno peek needs a session",
|
|
2170
|
+
detail: ["Name the session to read, or use on or off to switch peek for your sessions."],
|
|
2171
|
+
fix: `For example ${cmd(t, "conveno peek claude@api-1")} or ${cmd(t, "conveno peek off")}.`,
|
|
2172
|
+
exit: 2,
|
|
2173
|
+
ref: "e_usage"
|
|
2174
|
+
});
|
|
2175
|
+
if (first === "on" || first === "off") return runSwitch(ctx, first === "on", second);
|
|
2176
|
+
if (!isSessionRef(first)) return badSession(ctx, first);
|
|
2177
|
+
const nText = typeof parsed.values.n === "string" ? parsed.values.n : void 0;
|
|
2178
|
+
const n = nText === void 0 ? 10 : Number(nText);
|
|
2179
|
+
if (!Number.isInteger(n) || n < 1 || n > 50) return fail(ctx, {
|
|
2180
|
+
what: `"${nText}" is not a number of turns`,
|
|
2181
|
+
detail: [`Use a whole number from 1 to 50.`],
|
|
2182
|
+
fix: `For example ${cmd(t, `conveno peek ${first} -n 20`)}.`,
|
|
2183
|
+
exit: 2,
|
|
2184
|
+
ref: "e_usage"
|
|
2185
|
+
});
|
|
2186
|
+
const client = await connectOrFail(ctx);
|
|
2187
|
+
if (typeof client === "number") return client;
|
|
2188
|
+
try {
|
|
2189
|
+
const res = await client["session.peek"]({
|
|
2190
|
+
target: first,
|
|
2191
|
+
lastTurns: n
|
|
2192
|
+
});
|
|
2193
|
+
if (parsed.values["raw-json"] === true) {
|
|
2194
|
+
ctx.out(`${JSON.stringify(res, null, 2)}\n`);
|
|
2195
|
+
return 0;
|
|
2196
|
+
}
|
|
2197
|
+
ctx.out(`${t.bold(res.session.name)} ${t.paint("quiet", `${res.session.cli}, last ${plural(res.turns.length, "turn")}, secrets redacted (best effort)`)}\n`);
|
|
2198
|
+
if (res.turns.length === 0) ctx.out(`\n${t.paint("quiet", "The transcript has no turns yet.")}\n`);
|
|
2199
|
+
for (const turn of res.turns) {
|
|
2200
|
+
const stamp = turn.at ? ` ${t.paint("quiet", localStamp(turn.at))}` : "";
|
|
2201
|
+
ctx.out(`\n${t.bold(turn.role)}${stamp}\n${turn.text.replace(/\n/g, "\n ").replace(/^/, " ")}\n`);
|
|
2202
|
+
}
|
|
2203
|
+
if (res.truncated) ctx.out(`\n${t.paint("quiet", `Earlier turns, or long text, are left out. ${cmd(t, `conveno peek ${first} -n 50`)} reads more.`)}\n`);
|
|
2204
|
+
return 0;
|
|
2205
|
+
} catch (e) {
|
|
2206
|
+
return daemonFailure(ctx, e);
|
|
2207
|
+
} finally {
|
|
2208
|
+
await client.close().catch(() => void 0);
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
// src/tickets.ts
|
|
2212
|
+
/** Connect to a running daemon, or print why not. */
|
|
2213
|
+
async function connectRunning(ctx, why) {
|
|
2214
|
+
const t = ctx.theme;
|
|
2215
|
+
try {
|
|
2216
|
+
return await ctx.connect(connectOpts(ctx, false));
|
|
2217
|
+
} catch (e) {
|
|
2218
|
+
const problem = daemonProblem(t, e);
|
|
2219
|
+
return { exit: fail(ctx, {
|
|
2220
|
+
what: problem.notRunning ? "The Conveno daemon is not running" : "The Conveno daemon cannot be reached",
|
|
2221
|
+
detail: [problem.notRunning ? why : problem.why],
|
|
2222
|
+
fix: problem.notRunning ? `Run ${cmd(t, "conveno daemon start")}.` : problem.fix,
|
|
2223
|
+
exit: 1,
|
|
2224
|
+
ref: "e_daemon"
|
|
2225
|
+
}) };
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
const oneLine = (text, max) => {
|
|
2229
|
+
const flat = sanitizeLine(text);
|
|
2230
|
+
return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
|
|
2231
|
+
};
|
|
2232
|
+
/** The first line of a ticket, which for a permission request is its title line. */
|
|
2233
|
+
const headline = (t) => oneLine(t.question.split("\n")[0] ?? "", 70);
|
|
2234
|
+
async function runTickets(ctx, argv) {
|
|
2235
|
+
const t = ctx.theme;
|
|
2236
|
+
const spec = COMMANDS.find((c) => c.name === "tickets");
|
|
2237
|
+
if (!spec) return 2;
|
|
2238
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
2239
|
+
if (typeof parsed === "number") return parsed;
|
|
2240
|
+
const openOnly = parsed.values.open === true;
|
|
2241
|
+
const client = await connectRunning(ctx, "Tickets live in the daemon, so there are none to list.");
|
|
2242
|
+
if ("exit" in client) return client.exit;
|
|
2243
|
+
try {
|
|
2244
|
+
const res = await client["ticket.list"]({
|
|
2245
|
+
...openOnly ? { status: "open" } : {},
|
|
2246
|
+
limit: 200
|
|
2247
|
+
});
|
|
2248
|
+
const names = new Map((await client["session.list"]({ includeOffline: true })).sessions.map((s) => [s.id, s.name]));
|
|
2249
|
+
const who = (id) => names.get(id) ?? id.slice(-6);
|
|
2250
|
+
if (res.tickets.length === 0) {
|
|
2251
|
+
ctx.out(`${t.status("info")} ${openOnly ? "No open tickets." : "No tickets yet."} ${t.paint("quiet", "Workers raise them with the ask tool.")}\n`);
|
|
2252
|
+
return 0;
|
|
2253
|
+
}
|
|
2254
|
+
const q = (w) => t.paint("quiet", w);
|
|
2255
|
+
const rows = [[
|
|
2256
|
+
` ${q("TICKET")}`,
|
|
2257
|
+
q("STATE"),
|
|
2258
|
+
q("FROM"),
|
|
2259
|
+
q("TO"),
|
|
2260
|
+
q("WHEN"),
|
|
2261
|
+
q("QUESTION")
|
|
2262
|
+
], ...res.tickets.map((k) => [
|
|
2263
|
+
` ${t.bold(k.id)}`,
|
|
2264
|
+
k.status === "open" ? t.paint("entry", "open") : q(k.status),
|
|
2265
|
+
who(k.fromSession),
|
|
2266
|
+
who(k.toSession),
|
|
2267
|
+
q(stamp(k.createdAt, ctx.now())),
|
|
2268
|
+
`${k.kind === "permission" ? `${t.paint("warn", "permission")} ` : ""}${headline(k)}`
|
|
2269
|
+
])];
|
|
2270
|
+
ctx.out(`${columns(rows).join("\n")}\n\n`);
|
|
2271
|
+
const hint = res.openCount > 0 ? ` Answer with ${cmd(t, "conveno answer <ticket> <text>")}.` : "";
|
|
2272
|
+
ctx.out(`${plural(res.openCount, "open ticket")}.${hint}\n`);
|
|
2273
|
+
return 0;
|
|
2274
|
+
} finally {
|
|
2275
|
+
await client.close().catch(() => void 0);
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
/** A full ticket id, or the one open ticket that ends or starts with `text` (at least 6 characters). */
|
|
2279
|
+
function pickTicket(tickets, text) {
|
|
2280
|
+
if (TicketId.safeParse(text).success) return tickets.find((k) => k.id === text) ?? `No ticket ${text}.`;
|
|
2281
|
+
if (text.length < 6) return `"${text}" is too short to name a ticket. Use at least 6 characters.`;
|
|
2282
|
+
const wanted = text.toUpperCase();
|
|
2283
|
+
const hits = tickets.filter((k) => k.id.startsWith(wanted) || k.id.endsWith(wanted));
|
|
2284
|
+
if (hits.length === 1 && hits[0]) return hits[0];
|
|
2285
|
+
return hits.length === 0 ? `No ticket matches "${text}".` : `"${text}" matches ${hits.length} tickets.`;
|
|
2286
|
+
}
|
|
2287
|
+
async function runAnswer(ctx, argv) {
|
|
2288
|
+
const t = ctx.theme;
|
|
2289
|
+
const spec = COMMANDS.find((c) => c.name === "answer");
|
|
2290
|
+
if (!spec) return 2;
|
|
2291
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
2292
|
+
if (typeof parsed === "number") return parsed;
|
|
2293
|
+
const [id, ...words] = parsed.positionals;
|
|
2294
|
+
const response = words.join(" ").trim();
|
|
2295
|
+
if (!id || response === "") return fail(ctx, {
|
|
2296
|
+
what: "conveno answer needs a ticket and an answer",
|
|
2297
|
+
fix: `For example ${cmd(t, "conveno answer 01J8ABCD \"Use sqlite\"")}. ${cmd(t, "conveno tickets --open")} lists the open tickets.`,
|
|
2298
|
+
exit: 2,
|
|
2299
|
+
ref: "e_usage"
|
|
2300
|
+
});
|
|
2301
|
+
const client = await connectRunning(ctx, "Tickets live in the daemon, so there is nothing to answer.");
|
|
2302
|
+
if ("exit" in client) return client.exit;
|
|
2303
|
+
try {
|
|
2304
|
+
const { tickets } = await client["ticket.list"]({ limit: 200 });
|
|
2305
|
+
const picked = pickTicket(tickets, id);
|
|
2306
|
+
if (typeof picked === "string") return fail(ctx, {
|
|
2307
|
+
what: picked,
|
|
2308
|
+
fix: `Run ${cmd(t, "conveno tickets --open")} to see the open tickets.`,
|
|
2309
|
+
exit: 1,
|
|
2310
|
+
ref: "e_ticket"
|
|
2311
|
+
});
|
|
2312
|
+
const res = await client["ticket.answer"]({
|
|
2313
|
+
ticketId: picked.id,
|
|
2314
|
+
response
|
|
2315
|
+
});
|
|
2316
|
+
const who = res.ticket.kind === "permission" ? "The worker's CLI" : "The asker";
|
|
2317
|
+
ctx.out(`${t.status("ok")} ${t.bold("Answered")} ${res.ticket.id} ${t.paint("quiet", `(${res.ticket.answeredBy === "human" ? "by you" : "recorded"}). ${who} gets it now.`)}\n`);
|
|
2318
|
+
return 0;
|
|
2319
|
+
} catch (e) {
|
|
2320
|
+
return fail(ctx, {
|
|
2321
|
+
what: "The ticket could not be answered",
|
|
2322
|
+
detail: [e instanceof Error ? e.message : String(e)],
|
|
2323
|
+
fix: `Run ${cmd(t, "conveno tickets")} to see its state.`,
|
|
2324
|
+
exit: 1,
|
|
2325
|
+
ref: "e_ticket"
|
|
2326
|
+
});
|
|
2327
|
+
} finally {
|
|
2328
|
+
await client.close().catch(() => void 0);
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
// src/permissions.ts
|
|
2332
|
+
const RELAY_WARNING = "EXPERIMENTAL: while the relay is on, the orchestrator can allow or deny this session's tool calls. Calls outside its repo, network and credential access always stay with you. See SECURITY.md.";
|
|
2333
|
+
/**
|
|
2334
|
+
* The relay needs the CLI's PermissionRequest hook. Add it the first time, with the same diff,
|
|
2335
|
+
* backup and manifest as `conveno init` (so `conveno uninstall` removes it). Returns an exit code
|
|
2336
|
+
* to stop with, or undefined to go on.
|
|
2337
|
+
*/
|
|
2338
|
+
async function ensureHooks(ctx, targets, named, yes) {
|
|
2339
|
+
const t = ctx.theme;
|
|
2340
|
+
const items = [];
|
|
2341
|
+
const driven = targets.find((s) => !s.spawned);
|
|
2342
|
+
if (driven) return fail(ctx, {
|
|
2343
|
+
what: `The relay could not be turned on for ${driven.name}`,
|
|
2344
|
+
detail: [`${driven.name} was not started by Conveno, so a person is driving it. The relay is only for sessions started with conveno spawn or spawn_session.`],
|
|
2345
|
+
fix: `Start a worker with ${cmd(t, "conveno spawn <cli>")}.`,
|
|
2346
|
+
exit: 1,
|
|
2347
|
+
ref: "e_relay"
|
|
2348
|
+
});
|
|
2349
|
+
for (const cli of new Set(targets.map((s) => s.cli))) {
|
|
2350
|
+
const adapter = ctx.adapters.find((a) => a.cli === cli);
|
|
2351
|
+
if (!adapter?.permissionHookInstalled) return fail(ctx, {
|
|
2352
|
+
what: `The permission relay does not support ${cli}`,
|
|
2353
|
+
detail: ["It needs a hook that runs only when the CLI is about to ask for a permission. Claude Code and Codex have one; see SECURITY.md for the others."],
|
|
2354
|
+
fix: `Use the relay with a Claude Code or Codex worker.`,
|
|
2355
|
+
exit: 1,
|
|
2356
|
+
ref: "e_relay_cli"
|
|
2357
|
+
});
|
|
2358
|
+
try {
|
|
2359
|
+
if (await adapter.permissionHookInstalled(adapterEnv(ctx))) continue;
|
|
2360
|
+
const changes = await adapter.plan(adapterEnv(ctx, { permissionRelay: true }));
|
|
2361
|
+
for (const change of changes.filter((c) => c.component === "hooks")) items.push({
|
|
2362
|
+
cli: adapter.cli,
|
|
2363
|
+
installed: true,
|
|
2364
|
+
change
|
|
2365
|
+
});
|
|
2366
|
+
} catch (e) {
|
|
2367
|
+
return fail(ctx, {
|
|
2368
|
+
what: `Could not plan the ${adapter.displayName} permission hook`,
|
|
2369
|
+
detail: [plainError(e)],
|
|
2370
|
+
fix: "Fix the problem above, then run the command again.",
|
|
2371
|
+
exit: 1,
|
|
2372
|
+
ref: "e_plan"
|
|
2373
|
+
});
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
if (items.length === 0) return void 0;
|
|
2377
|
+
ctx.out(`${t.status("info")} The relay needs a ${[...new Set(items.map((i) => i.cli))].join(" and ")} PermissionRequest hook. It is not installed yet.\n\n`);
|
|
2378
|
+
const result = await confirmAndApply(ctx, items, {
|
|
2379
|
+
yes,
|
|
2380
|
+
verb: "Apply",
|
|
2381
|
+
rerun: `conveno permissions relay on${named ? ` ${named}` : ""}`
|
|
2382
|
+
});
|
|
2383
|
+
if ("exit" in result) return result.exit === 0 ? 0 : result.exit;
|
|
2384
|
+
ctx.out(`${t.status("ok")} Hook added. Restart the open ${[...new Set(items.map((i) => i.cli))].join(" and ")} sessions so they load it${items.some((i) => i.cli === "codex") ? ", and trust it in Codex with /hooks" : ""}.\n`);
|
|
2385
|
+
}
|
|
2386
|
+
async function runPermissions(ctx, argv) {
|
|
2387
|
+
const t = ctx.theme;
|
|
2388
|
+
const spec = COMMANDS.find((c) => c.name === "permissions");
|
|
2389
|
+
if (!spec) return 2;
|
|
2390
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
2391
|
+
if (typeof parsed === "number") return parsed;
|
|
2392
|
+
const [sub, state, name, ...extra] = parsed.positionals;
|
|
2393
|
+
const usage = `Run ${cmd(t, "conveno permissions relay on <session>")} or ${cmd(t, "conveno permissions relay off [session]")}.`;
|
|
2394
|
+
if (sub !== void 0 && (sub !== "relay" || state !== "on" && state !== "off" || extra.length > 0)) return fail(ctx, {
|
|
2395
|
+
what: `"${parsed.positionals.join(" ")}" is not a permissions command`,
|
|
2396
|
+
fix: usage,
|
|
2397
|
+
exit: 2,
|
|
2398
|
+
ref: "e_usage"
|
|
2399
|
+
});
|
|
2400
|
+
const client = await connectRunning(ctx, "The permission relay lives in the daemon.");
|
|
2401
|
+
if ("exit" in client) return client.exit;
|
|
2402
|
+
try {
|
|
2403
|
+
const sessions = (await client["session.list"]({ includeOffline: true })).sessions;
|
|
2404
|
+
const nameOf = (id) => sessions.find((s) => s.id === id)?.name ?? id.slice(-6);
|
|
2405
|
+
if (sub === void 0) {
|
|
2406
|
+
const { relays } = await client["permission.relay"]({});
|
|
2407
|
+
ctx.out(`${t.status("warn")} ${t.paint("quiet", "Permission relay is EXPERIMENTAL and off unless listed.")}\n`);
|
|
2408
|
+
if (relays.length === 0) ctx.out(`${t.status("info")} The relay is off for every session.\n`);
|
|
2409
|
+
else {
|
|
2410
|
+
const rows = relays.map((r) => `${nameOf(r.session)} (approved by ${nameOf(r.approver)})`);
|
|
2411
|
+
ctx.out(`${t.bold("Relay on for:")} ${rows.join(", ")}\n`);
|
|
2412
|
+
}
|
|
2413
|
+
ctx.out(` ${t.paint("quiet", `Turn it on with ${cmd(t, "conveno permissions relay on <session>")}. SECURITY.md has the threat model.`)}\n`);
|
|
2414
|
+
return 0;
|
|
2415
|
+
}
|
|
2416
|
+
const enable = state === "on";
|
|
2417
|
+
let targets;
|
|
2418
|
+
if (name !== void 0) {
|
|
2419
|
+
const found = sessions.find((s) => s.name === name && s.status !== "offline");
|
|
2420
|
+
if (!found) return fail(ctx, {
|
|
2421
|
+
what: `No online session named "${name}"`,
|
|
2422
|
+
fix: `Run ${cmd(t, "conveno status")} to see the names.`,
|
|
2423
|
+
exit: 1,
|
|
2424
|
+
ref: "e_no_session"
|
|
2425
|
+
});
|
|
2426
|
+
targets = [found];
|
|
2427
|
+
} else if (enable) {
|
|
2428
|
+
targets = sessions.filter((s) => s.spawned && s.status !== "offline");
|
|
2429
|
+
if (targets.length !== 1) return fail(ctx, {
|
|
2430
|
+
what: targets.length === 0 ? "No session started by Conveno is online" : "More than one spawned session is online",
|
|
2431
|
+
detail: ["The relay is only for sessions started with conveno spawn or spawn_session, never for one you drive yourself."],
|
|
2432
|
+
fix: `Name the session: ${cmd(t, "conveno permissions relay on <session>")}.`,
|
|
2433
|
+
exit: 2,
|
|
2434
|
+
ref: "e_usage"
|
|
2435
|
+
});
|
|
2436
|
+
} else {
|
|
2437
|
+
const { relays } = await client["permission.relay"]({});
|
|
2438
|
+
targets = sessions.filter((s) => relays.some((r) => r.session === s.id));
|
|
2439
|
+
if (targets.length === 0) {
|
|
2440
|
+
ctx.out(`${t.status("info")} The relay was already off for every session.\n`);
|
|
2441
|
+
return 0;
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
if (enable) {
|
|
2445
|
+
const code = await ensureHooks(ctx, targets, name, parsed.values.yes === true);
|
|
2446
|
+
if (code !== void 0) return code;
|
|
2447
|
+
}
|
|
2448
|
+
for (const target of targets) {
|
|
2449
|
+
let approver;
|
|
2450
|
+
try {
|
|
2451
|
+
approver = (await client["permission.relay"]({
|
|
2452
|
+
target: target.id,
|
|
2453
|
+
enabled: enable
|
|
2454
|
+
})).relays.find((r) => r.session === target.id)?.approver;
|
|
2455
|
+
} catch (e) {
|
|
2456
|
+
return fail(ctx, {
|
|
2457
|
+
what: `The relay could not be turned ${state} for ${target.name}`,
|
|
2458
|
+
detail: [e instanceof Error ? e.message : String(e)],
|
|
2459
|
+
fix: usage,
|
|
2460
|
+
exit: 1,
|
|
2461
|
+
ref: "e_relay"
|
|
2462
|
+
});
|
|
2463
|
+
}
|
|
2464
|
+
ctx.out(`${t.status(enable ? "warn" : "ok")} Permission relay ${state} for ${t.bold(target.name)}.${approver ? ` ${nameOf(approver)} approves its prompts, and no one who takes the role later.` : ""}\n`);
|
|
2465
|
+
}
|
|
2466
|
+
if (enable) ctx.out(` ${RELAY_WARNING}\n`);
|
|
2467
|
+
return 0;
|
|
2468
|
+
} finally {
|
|
2469
|
+
await client.close().catch(() => void 0);
|
|
2470
|
+
}
|
|
2471
|
+
}
|
|
2472
|
+
// src/spawn.ts
|
|
2473
|
+
/** Read the task from `--task-file`. Returns the text or the failure's exit code. */
|
|
2474
|
+
function readTaskFile(ctx, path) {
|
|
2475
|
+
try {
|
|
2476
|
+
return readFileSync(resolve(ctx.cwd, path), "utf8");
|
|
2477
|
+
} catch (e) {
|
|
2478
|
+
const code = e.code;
|
|
2479
|
+
return fail(ctx, {
|
|
2480
|
+
what: `Cannot read the task file ${path}`,
|
|
2481
|
+
detail: [code === "ENOENT" ? "The file does not exist." : `The system said ${code ?? "no"}.`],
|
|
2482
|
+
fix: "Check the path, or pass the task with --task.",
|
|
2483
|
+
exit: 2,
|
|
2484
|
+
ref: "e_usage"
|
|
2485
|
+
});
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
/**
|
|
2489
|
+
* `conveno spawn <cli> ...`: start a worker session of any CLI with a first task, and print the
|
|
2490
|
+
* name it registers under.
|
|
2491
|
+
*/
|
|
2492
|
+
async function runSpawn(ctx, argv) {
|
|
2493
|
+
const t = ctx.theme;
|
|
2494
|
+
const spec = COMMANDS.find((c) => c.name === "spawn");
|
|
2495
|
+
if (!spec) return 2;
|
|
2496
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
2497
|
+
if (typeof parsed === "number") return parsed;
|
|
2498
|
+
const help = `Run ${cmd(t, "conveno spawn --help")} to see the options.`;
|
|
2499
|
+
const [cli, ...extra] = parsed.positionals;
|
|
2500
|
+
if (!cli || extra.length > 0) return fail(ctx, {
|
|
2501
|
+
what: "conveno spawn needs exactly one CLI name",
|
|
2502
|
+
detail: [`Known: ${SPAWN_CLIS.join(", ")}.`],
|
|
2503
|
+
fix: `Run ${cmd(t, "conveno spawn claude --task 'review the open PR'")}.`,
|
|
2504
|
+
exit: 2,
|
|
2505
|
+
ref: "e_usage"
|
|
2506
|
+
});
|
|
2507
|
+
if (!Object.hasOwn(SPAWN_TABLE, cli)) return fail(ctx, {
|
|
2508
|
+
what: `"${cli}" is not a CLI Conveno can start`,
|
|
2509
|
+
detail: [`Known: ${SPAWN_CLIS.join(", ")}.`],
|
|
2510
|
+
fix: help,
|
|
2511
|
+
exit: 2,
|
|
2512
|
+
ref: "e_usage"
|
|
2513
|
+
});
|
|
2514
|
+
const str = (k) => typeof parsed.values[k] === "string" ? parsed.values[k] : void 0;
|
|
2515
|
+
if (str("task") !== void 0 && str("task-file") !== void 0) return fail(ctx, {
|
|
2516
|
+
what: "Use --task or --task-file, not both",
|
|
2517
|
+
fix: help,
|
|
2518
|
+
exit: 2,
|
|
2519
|
+
ref: "e_usage"
|
|
2520
|
+
});
|
|
2521
|
+
let task = str("task");
|
|
2522
|
+
const taskFile = str("task-file");
|
|
2523
|
+
if (taskFile !== void 0) {
|
|
2524
|
+
const text = readTaskFile(ctx, taskFile);
|
|
2525
|
+
if (typeof text === "number") return text;
|
|
2526
|
+
task = text;
|
|
2527
|
+
}
|
|
2528
|
+
const acpFlag = parsed.values.acp === true;
|
|
2529
|
+
const oneShot = parsed.values["one-shot"] === true;
|
|
2530
|
+
if (acpFlag && oneShot) return fail(ctx, {
|
|
2531
|
+
what: "Use --acp or --one-shot, not both",
|
|
2532
|
+
fix: help,
|
|
2533
|
+
exit: 2,
|
|
2534
|
+
ref: "e_usage"
|
|
2535
|
+
});
|
|
2536
|
+
const headless = parsed.values.headless === true || acpFlag || oneShot;
|
|
2537
|
+
const acp = acpFlag ? "require" : headless && !oneShot ? "prefer" : void 0;
|
|
2538
|
+
const allowFlag = str("allow");
|
|
2539
|
+
const allow = allowFlag === void 0 ? void 0 : [allowFlag];
|
|
2540
|
+
const yes = parsed.values.yes === true;
|
|
2541
|
+
const adapter = ctx.adapters.find((a) => a.cli === cli);
|
|
2542
|
+
if (adapter && !(await adapter.detect(adapterEnv(ctx))).installed) return fail(ctx, {
|
|
2543
|
+
what: `${adapter.displayName} is not installed`,
|
|
2544
|
+
detail: [`conveno could not run ${cli} --version.`],
|
|
2545
|
+
fix: "Install it, or check that its folder is on PATH.",
|
|
2546
|
+
exit: 1,
|
|
2547
|
+
ref: "e_spawn"
|
|
2548
|
+
});
|
|
2549
|
+
if (!yes) {
|
|
2550
|
+
if (!ctx.interactive) return fail(ctx, {
|
|
2551
|
+
what: "Needs a terminal to confirm",
|
|
2552
|
+
detail: ["Nothing was started."],
|
|
2553
|
+
fix: `Run the same command with ${cmd(t, "--yes")} to start the session without asking.`,
|
|
2554
|
+
exit: 2,
|
|
2555
|
+
ref: "e_no_tty"
|
|
2556
|
+
});
|
|
2557
|
+
const question = `Start ${cli} in ${tilde(resolve(ctx.cwd, str("cwd") ?? "."), ctx.home)}${headless ? " in the background" : ""}${task ? " with a first task" : ""}?`;
|
|
2558
|
+
if (!await ctx.confirm(question, true)) {
|
|
2559
|
+
ctx.out(`${t.status("info")} Nothing was started.\n`);
|
|
2560
|
+
return 0;
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
let client;
|
|
2564
|
+
try {
|
|
2565
|
+
client = await ctx.connect(connectOpts(ctx, true));
|
|
2566
|
+
} catch (e) {
|
|
2567
|
+
const problem = daemonProblem(t, e);
|
|
2568
|
+
return fail(ctx, {
|
|
2569
|
+
what: "The Conveno daemon cannot be reached",
|
|
2570
|
+
detail: [problem.why],
|
|
2571
|
+
fix: problem.fix,
|
|
2572
|
+
exit: 1,
|
|
2573
|
+
ref: "e_daemon"
|
|
2574
|
+
});
|
|
2575
|
+
}
|
|
2576
|
+
try {
|
|
2577
|
+
const { hostPid } = await ctx.ancestry(2e3);
|
|
2578
|
+
const requester = hostPid === void 0 ? void 0 : (await client["session.byHost"]({ pid: hostPid }).catch(() => void 0))?.session ?? void 0;
|
|
2579
|
+
const runner = ctx.spawnRunner ?? [process.execPath, process.argv[1] ?? "conveno"];
|
|
2580
|
+
const deps = realSpawnDeps({
|
|
2581
|
+
platform: ctx.platform,
|
|
2582
|
+
env: ctx.env,
|
|
2583
|
+
home: ctx.home,
|
|
2584
|
+
dataDir: ctx.dataDir,
|
|
2585
|
+
client,
|
|
2586
|
+
runner
|
|
2587
|
+
});
|
|
2588
|
+
const res = await spawnSession(deps, {
|
|
2589
|
+
cli,
|
|
2590
|
+
callerCwd: ctx.cwd,
|
|
2591
|
+
cwd: str("cwd"),
|
|
2592
|
+
name: str("name"),
|
|
2593
|
+
task,
|
|
2594
|
+
headless,
|
|
2595
|
+
acp,
|
|
2596
|
+
allow,
|
|
2597
|
+
requester,
|
|
2598
|
+
confineToHome: false,
|
|
2599
|
+
onProgress: (line) => ctx.err(`${t.paint("quiet", line)}\n`)
|
|
2600
|
+
});
|
|
2601
|
+
const how = res.mode === "acp" ? "over ACP, background" : res.mode === "headless" ? "background" : res.terminal ?? "terminal";
|
|
2602
|
+
ctx.out(`${t.status("ok")} ${t.bold(`Started ${res.name}`)} ${t.paint("quiet", `(${res.cli}, ${how}) in ${tilde(res.cwd, ctx.home)}`)}\n`);
|
|
2603
|
+
if (res.task === "message") ctx.out(` The first task was sent to it as a Conveno message.\n`);
|
|
2604
|
+
if (res.mode === "acp") {
|
|
2605
|
+
ctx.out(` Follow it with ${cmd(t, `conveno attach ${res.name}`)}; end it with ${cmd(t, `conveno stop ${res.name}`)}.\n`);
|
|
2606
|
+
if (res.adapter) ctx.out(` ${t.paint("quiet", `Adapter: ${res.adapter}`)}\n`);
|
|
2607
|
+
}
|
|
2608
|
+
if (res.logPath) ctx.out(` Output: ${tilde(res.logPath, ctx.home)}\n`);
|
|
2609
|
+
ctx.out(` ${t.paint("quiet", `${cmd(t, "conveno status")} lists it. Message it with send to: ${res.name}.`)}\n`);
|
|
2610
|
+
return 0;
|
|
2611
|
+
} catch (e) {
|
|
2612
|
+
if (e instanceof SpawnError) return fail(ctx, {
|
|
2613
|
+
what: "Could not start the session",
|
|
2614
|
+
detail: [e.message],
|
|
2615
|
+
...e.fix ? { fix: e.fix } : {},
|
|
2616
|
+
exit: 1,
|
|
2617
|
+
ref: "e_spawn"
|
|
2618
|
+
});
|
|
2619
|
+
throw e;
|
|
2620
|
+
} finally {
|
|
2621
|
+
await client.close().catch(() => void 0);
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
/** `conveno spawn-run <launch file>`: what a spawned terminal runs. Not for people. */
|
|
2625
|
+
async function runSpawnRun(ctx, argv) {
|
|
2626
|
+
const [file] = argv;
|
|
2627
|
+
if (!file) return fail(ctx, {
|
|
2628
|
+
what: "conveno spawn-run needs a launch file",
|
|
2629
|
+
detail: ["It is started by conveno spawn inside the new terminal."],
|
|
2630
|
+
fix: `Run ${cmd(ctx.theme, "conveno spawn <cli>")} instead.`,
|
|
2631
|
+
exit: 2,
|
|
2632
|
+
ref: "e_usage"
|
|
2633
|
+
});
|
|
2634
|
+
try {
|
|
2635
|
+
return await runLaunchFile(file);
|
|
2636
|
+
} catch (e) {
|
|
2637
|
+
return fail(ctx, {
|
|
2638
|
+
what: "Could not read the launch file",
|
|
2639
|
+
detail: [e instanceof Error ? e.message : String(e)],
|
|
2640
|
+
fix: `Run ${cmd(ctx.theme, "conveno spawn <cli>")} again.`,
|
|
2641
|
+
exit: 1,
|
|
2642
|
+
ref: "e_spawn"
|
|
2643
|
+
});
|
|
2644
|
+
}
|
|
2645
|
+
}
|
|
2646
|
+
// src/uninstall.ts
|
|
2647
|
+
const NOTE = {
|
|
2648
|
+
restore: "restored byte for byte",
|
|
2649
|
+
remove: "removed, it did not exist before",
|
|
2650
|
+
edit: "edited since init, so only Conveno's entries are removed",
|
|
2651
|
+
gone: "already gone, left as it is"
|
|
2652
|
+
};
|
|
2653
|
+
/**
|
|
2654
|
+
* The files as init found them, from the backups: their text, or null when they did not exist. A
|
|
2655
|
+
* backup that cannot be read leaves its file out, and the adapter then treats what it finds as
|
|
2656
|
+
* Conveno's own.
|
|
2657
|
+
*/
|
|
2658
|
+
async function baselineOf(dir, entries) {
|
|
2659
|
+
const out = /* @__PURE__ */ new Map();
|
|
2660
|
+
for (const e of entries) if (e.backup === null) out.set(e.path, null);
|
|
2661
|
+
else try {
|
|
2662
|
+
out.set(e.path, await readFile(join(dir, e.backup), "utf8"));
|
|
2663
|
+
} catch {}
|
|
2664
|
+
return out;
|
|
2665
|
+
}
|
|
2666
|
+
/** Remove Conveno's own entries from files that changed since init, through each adapter. */
|
|
2667
|
+
async function removeOwnEntries(ctx, dir, entries) {
|
|
2668
|
+
if (entries.length === 0) return {
|
|
2669
|
+
edited: [],
|
|
2670
|
+
failures: []
|
|
2671
|
+
};
|
|
2672
|
+
const clis = new Set(entries.map((e) => e.cli));
|
|
2673
|
+
const { items, failures } = await collectPlans(ctx, (await detectAll(ctx)).filter((f) => clis.has(f.adapter.cli)), "uninstallPlan", await baselineOf(dir, entries));
|
|
2674
|
+
const wanted = new Set(entries.map((e) => e.path));
|
|
2675
|
+
const mine = items.filter((i) => wanted.has(i.change.path));
|
|
2676
|
+
if (mine.length > 0) await applyChanges(ctx, mine, { markRestored: true });
|
|
2677
|
+
return {
|
|
2678
|
+
edited: mine.map((i) => i.change.path),
|
|
2679
|
+
failures
|
|
2680
|
+
};
|
|
2681
|
+
}
|
|
2682
|
+
async function restoreAll(ctx, manifests) {
|
|
2683
|
+
const restored = [];
|
|
2684
|
+
const edited = [];
|
|
2685
|
+
const untouched = [];
|
|
2686
|
+
for (const found of manifests) {
|
|
2687
|
+
const needEdit = [];
|
|
2688
|
+
for (const entry of found.manifest.entries) {
|
|
2689
|
+
const action = await restoreEntry(found.dir, entry);
|
|
2690
|
+
if (action === "edit") needEdit.push(entry);
|
|
2691
|
+
else if (action === "gone") untouched.push(entry.path);
|
|
2692
|
+
else restored.push(entry.path);
|
|
2693
|
+
}
|
|
2694
|
+
const r = await removeOwnEntries(ctx, found.dir, needEdit);
|
|
2695
|
+
if (r.failures.length > 0) {
|
|
2696
|
+
reportFailures(ctx, r.failures, "conveno uninstall");
|
|
2697
|
+
throw new Error("A config file could not be read, so it was left as it is.");
|
|
2698
|
+
}
|
|
2699
|
+
edited.push(...r.edited);
|
|
2700
|
+
for (const e of needEdit) if (!r.edited.includes(e.path)) untouched.push(e.path);
|
|
2701
|
+
await markRestored(ctx, found);
|
|
2702
|
+
}
|
|
2703
|
+
return {
|
|
2704
|
+
restored,
|
|
2705
|
+
edited,
|
|
2706
|
+
untouched
|
|
2707
|
+
};
|
|
2708
|
+
}
|
|
2709
|
+
async function runUninstall(ctx, argv) {
|
|
2710
|
+
const t = ctx.theme;
|
|
2711
|
+
const started = ctx.now();
|
|
2712
|
+
const spec = COMMANDS.find((c) => c.name === "uninstall");
|
|
2713
|
+
if (!spec) return 2;
|
|
2714
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
2715
|
+
if (typeof parsed === "number") return parsed;
|
|
2716
|
+
const yes = parsed.values.yes === true;
|
|
2717
|
+
const manifests = await listManifests(ctx).catch(() => []);
|
|
2718
|
+
if (manifests.length > 0) {
|
|
2719
|
+
const rows = await previewRestore(manifests);
|
|
2720
|
+
const made = manifests.map((m) => localStamp(m.manifest.createdAt));
|
|
2721
|
+
ctx.out(`${t.bold(`Conveno will undo ${plural(manifests.length, "install")}`)}, made ${made.join(", ")} (local time).\n\n`);
|
|
2722
|
+
ctx.out(`${columns(rows.map((r) => [` ${tilde(r.entry.path, ctx.home)}`, t.paint("quiet", NOTE[r.action])])).join("\n")}\n\n`);
|
|
2723
|
+
if (!yes) {
|
|
2724
|
+
if (!ctx.interactive) return fail(ctx, {
|
|
2725
|
+
what: "Needs a terminal to confirm",
|
|
2726
|
+
detail: ["No files were changed."],
|
|
2727
|
+
fix: `Run ${cmd(t, "conveno uninstall --yes")} to undo the changes listed above.`,
|
|
2728
|
+
exit: 2,
|
|
2729
|
+
ref: "e_no_tty"
|
|
2730
|
+
});
|
|
2731
|
+
if (!await ctx.confirm("Undo these changes?", false)) {
|
|
2732
|
+
ctx.out(`${t.status("info")} Nothing was changed.\n`);
|
|
2733
|
+
return 0;
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
let result;
|
|
2737
|
+
try {
|
|
2738
|
+
result = await restoreAll(ctx, manifests);
|
|
2739
|
+
} catch (e) {
|
|
2740
|
+
if (e instanceof StaleError) return staleFailure(ctx, e, "conveno uninstall");
|
|
2741
|
+
return fail(ctx, {
|
|
2742
|
+
what: "Could not restore a file",
|
|
2743
|
+
detail: [plainError(e), `The backups are still in ${tilde(manifests[0]?.dir ?? ctx.dataDir, ctx.home)} and the other backup folders next to it.`],
|
|
2744
|
+
fix: "Fix the problem above, then run conveno uninstall again.",
|
|
2745
|
+
exit: 1,
|
|
2746
|
+
ref: "e_restore"
|
|
2747
|
+
});
|
|
2748
|
+
}
|
|
2749
|
+
ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
|
|
2750
|
+
ctx.out(` Restored ${plural(result.restored.length, "file")} to how init found them.\n`);
|
|
2751
|
+
if (result.edited.length > 0) ctx.out(` Edited, not restored, because they changed since init: ${result.edited.map((p) => tilde(p, ctx.home)).join(", ")}. Only Conveno's entries were removed.\n`);
|
|
2752
|
+
ctx.out(" Restart open sessions to drop Conveno.\n");
|
|
2753
|
+
return 0;
|
|
2754
|
+
}
|
|
2755
|
+
const { items, failures } = await collectPlans(ctx, await detectAll(ctx), "uninstallPlan");
|
|
2756
|
+
if (failures.length > 0) {
|
|
2757
|
+
reportFailures(ctx, failures, "conveno uninstall");
|
|
2758
|
+
return 1;
|
|
2759
|
+
}
|
|
2760
|
+
if (items.length === 0) {
|
|
2761
|
+
ctx.out(`${t.status("ok")} Nothing to remove. No Conveno entries were found in any supported CLI.\n`);
|
|
2762
|
+
return 0;
|
|
2763
|
+
}
|
|
2764
|
+
ctx.out(`${t.status("info")} No install backup found, so Conveno will remove only its own entries.\n\n`);
|
|
2765
|
+
const result = await confirmAndApply(ctx, items, {
|
|
2766
|
+
yes,
|
|
2767
|
+
verb: "Remove",
|
|
2768
|
+
rerun: "conveno uninstall",
|
|
2769
|
+
markRestored: true
|
|
2770
|
+
});
|
|
2771
|
+
if ("exit" in result) return result.exit;
|
|
2772
|
+
ctx.out(`${t.status("ok")} ${t.bold("Done.")} ${seconds(started, ctx.now())}\n`);
|
|
2773
|
+
ctx.out(" Removed the Conveno entries. Restart open sessions to drop Conveno.\n");
|
|
2774
|
+
return 0;
|
|
2775
|
+
}
|
|
2776
|
+
// src/main.ts
|
|
2777
|
+
const DESCRIPTION = "Conveno lets AI coding sessions on one machine find each other and exchange messages.";
|
|
2778
|
+
function helpText(ctx) {
|
|
2779
|
+
const t = ctx.theme;
|
|
2780
|
+
const rows = COMMANDS.map((c) => [c.usage.replace(/^conveno /, ""), c.summary]);
|
|
2781
|
+
const width = Math.max(...rows.map(([u]) => u.length), 9) + 2;
|
|
2782
|
+
const row = (c, d) => ` ${t.bold(c.padEnd(width))}${d}`;
|
|
2783
|
+
return [
|
|
2784
|
+
DESCRIPTION,
|
|
2785
|
+
"",
|
|
2786
|
+
"Usage: conveno <command> [options]",
|
|
2787
|
+
"",
|
|
2788
|
+
...rows.map(([u, d]) => row(u, d)),
|
|
2789
|
+
row("--version", "Print the version"),
|
|
2790
|
+
"",
|
|
2791
|
+
`Run ${cmd(t, "conveno <command> --help")} for the options of one command.`,
|
|
2792
|
+
`conveno ${t.paint("info", VERSION)}`,
|
|
2793
|
+
""
|
|
2794
|
+
].join("\n");
|
|
2795
|
+
}
|
|
2796
|
+
async function runMcp(ctx, argv) {
|
|
2797
|
+
const t = ctx.theme;
|
|
2798
|
+
const spec = COMMANDS.find((c) => c.name === "mcp");
|
|
2799
|
+
if (!spec) return 2;
|
|
2800
|
+
const parsed = parseFlags(ctx, spec, argv);
|
|
2801
|
+
if (typeof parsed === "number") return parsed;
|
|
2802
|
+
const cli = typeof parsed.values.cli === "string" ? parsed.values.cli : void 0;
|
|
2803
|
+
if (!cli || !CLI_KINDS.includes(cli)) return fail(ctx, {
|
|
2804
|
+
what: "conveno mcp needs a CLI name",
|
|
2805
|
+
detail: [`Got ${cli ? `"${cli}"` : "none"}. Known: ${CLI_KINDS.join(", ")}.`],
|
|
2806
|
+
fix: `Run ${cmd(t, "conveno mcp --cli claude")}, or let ${cmd(t, "conveno init")} write the config.`,
|
|
2807
|
+
exit: 2,
|
|
2808
|
+
ref: "e_usage"
|
|
2809
|
+
});
|
|
2810
|
+
try {
|
|
2811
|
+
await ctx.runMcp({
|
|
2812
|
+
cli,
|
|
2813
|
+
...ctx.daemonEntry ? { daemonEntry: ctx.daemonEntry } : {}
|
|
2814
|
+
});
|
|
2815
|
+
return 0;
|
|
2816
|
+
} catch (e) {
|
|
2817
|
+
const problem = daemonProblem(t, e);
|
|
2818
|
+
return fail(ctx, {
|
|
2819
|
+
what: "The Conveno MCP server stopped",
|
|
2820
|
+
detail: [problem.why],
|
|
2821
|
+
fix: problem.notRunning ? `Run ${cmd(t, "conveno doctor")} to check the daemon.` : problem.fix,
|
|
2822
|
+
exit: 1,
|
|
2823
|
+
ref: "e_mcp"
|
|
2824
|
+
});
|
|
2825
|
+
}
|
|
2826
|
+
}
|
|
2827
|
+
async function dispatch(command, rest, ctx) {
|
|
2828
|
+
const spec = COMMANDS.find((c) => c.name === command);
|
|
2829
|
+
if (spec && (rest.includes("--help") || rest.includes("-h")) && command !== "hook") {
|
|
2830
|
+
ctx.out(commandHelp(ctx, spec));
|
|
2831
|
+
return 0;
|
|
2832
|
+
}
|
|
2833
|
+
switch (command) {
|
|
2834
|
+
case "init": return runInit(ctx, rest);
|
|
2835
|
+
case "uninstall": return runUninstall(ctx, rest);
|
|
2836
|
+
case "status": return runStatus(ctx, rest);
|
|
2837
|
+
case "tickets": return runTickets(ctx, rest);
|
|
2838
|
+
case "answer": return runAnswer(ctx, rest);
|
|
2839
|
+
case "permissions": return runPermissions(ctx, rest);
|
|
2840
|
+
case "forget": return runForget(ctx, rest);
|
|
2841
|
+
case "spawn": return runSpawn(ctx, rest);
|
|
2842
|
+
case "acp-host": return (await import("./acp-BlKK0v-B.js")).runAcpHostCmd(ctx, rest);
|
|
2843
|
+
case "stop": return (await import("./acp-BlKK0v-B.js")).runStop(ctx, rest);
|
|
2844
|
+
case "attach": return (await import("./acp-BlKK0v-B.js")).runAttach(ctx, rest);
|
|
2845
|
+
case "spawn-run": return runSpawnRun(ctx, rest);
|
|
2846
|
+
case "auto": return runAuto(ctx, rest);
|
|
2847
|
+
case "peek": return runPeek(ctx, rest);
|
|
2848
|
+
case "devices": return runDevices(ctx, rest);
|
|
2849
|
+
case "relay": return runRelay(ctx, rest);
|
|
2850
|
+
case "doctor": return runDoctor(ctx, rest);
|
|
2851
|
+
case "login": return runLogin(ctx, rest);
|
|
2852
|
+
case "logout": return runLogout(ctx, rest);
|
|
2853
|
+
case "account": return runAccount(ctx, rest);
|
|
2854
|
+
case "daemon": return runDaemon(ctx, rest);
|
|
2855
|
+
case "mcp": return runMcp(ctx, rest);
|
|
2856
|
+
case "hook": return runHook(ctx, rest);
|
|
2857
|
+
default: {
|
|
2858
|
+
const suggestion = closest(command, COMMAND_NAMES);
|
|
2859
|
+
return fail(ctx, {
|
|
2860
|
+
what: `Unknown command "${command}"`,
|
|
2861
|
+
detail: [`conveno ${VERSION} has: ${COMMAND_NAMES.join(", ")}.`],
|
|
2862
|
+
fix: `Run ${cmd(ctx.theme, "conveno --help")} to see usage.`,
|
|
2863
|
+
...suggestion ? { didYouMean: `Did you mean ${suggestion}?` } : {},
|
|
2864
|
+
exit: 2,
|
|
2865
|
+
ref: "e_usage"
|
|
2866
|
+
});
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
}
|
|
2870
|
+
/** Run one command line. Returns the exit code. Never throws. */
|
|
2871
|
+
async function main(argv, ctx) {
|
|
2872
|
+
const [command, ...rest] = argv;
|
|
2873
|
+
switch (command) {
|
|
2874
|
+
case void 0:
|
|
2875
|
+
case "--help":
|
|
2876
|
+
case "-h":
|
|
2877
|
+
case "help":
|
|
2878
|
+
ctx.out(helpText(ctx));
|
|
2879
|
+
return 0;
|
|
2880
|
+
case "--version":
|
|
2881
|
+
case "-v":
|
|
2882
|
+
case "version":
|
|
2883
|
+
ctx.out(`${VERSION}\n`);
|
|
2884
|
+
return 0;
|
|
2885
|
+
}
|
|
2886
|
+
try {
|
|
2887
|
+
return await dispatch(command, rest, ctx);
|
|
2888
|
+
} catch (e) {
|
|
2889
|
+
const log = await writeErrorLog(ctx, argv, e);
|
|
2890
|
+
return fail(ctx, {
|
|
2891
|
+
what: "conveno stopped before it could finish",
|
|
2892
|
+
detail: [rawMessage(e), ...log ? [`The full error is in ${tilde(log, ctx.home)}.`] : []],
|
|
2893
|
+
fix: `Run ${cmd(ctx.theme, "conveno doctor")} to check the install, then try again.`,
|
|
2894
|
+
exit: 1,
|
|
2895
|
+
ref: "e_internal"
|
|
2896
|
+
});
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
export { DESCRIPTION, helpText, main };
|