@conveno/cli 0.1.1 → 0.2.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ // src/fmt.ts
2
+ /** Shorten the home directory to `~`. */
3
+ function tilde(path, home) {
4
+ if (path === home) return "~";
5
+ for (const sep of ["/", "\\"]) if (path.startsWith(home + sep)) return `~${sep}${path.slice(home.length + 1)}`;
6
+ return path;
7
+ }
8
+ /** Length of a string without ANSI escapes. */
9
+ const visibleLength = (s) => s.replace(/\u001b\[[0-9;]*m/g, "").length;
10
+ const padEnd = (s, width) => s + " ".repeat(Math.max(0, width - visibleLength(s)));
11
+ /** Pad every column to its widest cell. The last column is left unpadded. */
12
+ function columns(rows, gap = 2) {
13
+ const widths = [];
14
+ for (const row of rows) row.forEach((cell, i) => {
15
+ widths[i] = Math.max(widths[i] ?? 0, visibleLength(cell));
16
+ });
17
+ return rows.map((row) => row.map((cell, i) => i === row.length - 1 ? cell : padEnd(cell, (widths[i] ?? 0) + gap)).join("").trimEnd());
18
+ }
19
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
20
+ const pad2 = (n) => String(n).padStart(2, "0");
21
+ /** `2026-11-27 14:02:11` in the machine's local time. */
22
+ function localStamp(iso) {
23
+ const d = new Date(iso);
24
+ if (Number.isNaN(d.getTime())) return iso;
25
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
26
+ }
27
+ /** `1.2s` between two times. */
28
+ const seconds = (from, to) => `${(Math.max(0, to.getTime() - from.getTime()) / 1e3).toFixed(1)}s`;
29
+ function levenshtein(a, b) {
30
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
31
+ for (let i = 1; i <= a.length; i++) {
32
+ const row = [i];
33
+ for (let j = 1; j <= b.length; j++) row[j] = Math.min(row[j - 1] + 1, prev[j] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
34
+ prev = row;
35
+ }
36
+ return prev[b.length];
37
+ }
38
+ /** The closest candidate within two edits, or undefined. */
39
+ function closest(word, candidates) {
40
+ let best;
41
+ let bestDistance = 3;
42
+ for (const c of candidates) {
43
+ const d = levenshtein(word.toLowerCase(), c.toLowerCase());
44
+ if (d < bestDistance) {
45
+ best = c;
46
+ bestDistance = d;
47
+ }
48
+ }
49
+ return best;
50
+ }
51
+ /** Error block: what happened, detail, fix, then `exit N · ref e_code`. Goes to stderr. */
52
+ function errorBlock(theme, f) {
53
+ const lines = [`${theme.status("error")} ${f.what}`];
54
+ for (const d of f.detail ?? []) lines.push(` ${d}`);
55
+ if (f.fix) lines.push(` ${theme.paint("quiet", "fix")} ${f.fix}`);
56
+ if (f.didYouMean) lines.push(` ${f.didYouMean}`);
57
+ lines.push("", theme.paint("quiet", `exit ${f.exit} ${theme.glyph("bullet")} ref ${f.ref}`));
58
+ return `${lines.join("\n")}\n`;
59
+ }
60
+ /** Print an error block on stderr and return its exit code. */
61
+ function fail(ctx, f) {
62
+ ctx.err(errorBlock(ctx.theme, f));
63
+ return f.exit;
64
+ }
65
+ /**
66
+ * A message safe to show a user. Errors raised by Node get a plain sentence; errors we wrote
67
+ * pass through. Never a stack trace or a bare `EACCES: ...`.
68
+ */
69
+ function plainError(e) {
70
+ if (!(e instanceof Error)) return "Something unexpected stopped the command.";
71
+ const code = e.code;
72
+ const path = e.path;
73
+ const named = path ?? "a file it needs";
74
+ switch (code) {
75
+ case "EACCES":
76
+ case "EPERM": return `Conveno has no permission to use ${named}.`;
77
+ case "ENOENT": return `${path ?? "A file or folder"} does not exist.`;
78
+ case "ENOSPC": return "The disk is full.";
79
+ case "EROFS": return `${path ?? "The location"} is read-only.`;
80
+ case "EISDIR":
81
+ case "ENOTDIR": return `${path ?? "A path"} is not the kind of entry Conveno expected.`;
82
+ case "EMFILE": return "Too many files are open.";
83
+ }
84
+ if (typeof code === "string" && /^E[A-Z0-9]+$/.test(code)) return `The system refused an operation (${code}).`;
85
+ if (e instanceof TypeError || e instanceof RangeError || e instanceof ReferenceError) return "Conveno hit an internal error.";
86
+ return e.message.replace(/,? or enable autoStart\.?/i, ".").replace(/No session holds the orchestrator role/, "No session is the lead yet").replace(/Run orchestrate in the session you want to use/, "Run conveno lead <session>").replace(/ Run list_sessions to see who is available\./, "").replace(/^No Conveno daemon is listening at /, "Conveno's background service is not listening at ").replace(/\.\.$/, ".");
87
+ }
88
+ function warnBlock(theme, what, fix, why) {
89
+ const lines = [`${theme.status("warn")} ${what}`];
90
+ if (why) lines.push(` ${theme.paint("quiet", "why")} ${why}`);
91
+ lines.push(` ${theme.paint("quiet", "fix")} ${fix}`);
92
+ return `${lines.join("\n")}\n`;
93
+ }
94
+ /** A command to run, in bold ink. */
95
+ const cmd = (theme, text) => theme.bold(text);
96
+ export { fail as a, plural as c, warnBlock as d, errorBlock as i, seconds as l, cmd as n, localStamp as o, columns as r, plainError as s, closest as t, tilde as u };
@@ -0,0 +1,114 @@
1
+ import { appendFileSync } from "node:fs";
2
+ import { n as connectOpts } from "./ctx-tYftvhz_.js";
3
+ // src/hook.ts
4
+ /**
5
+ * Time allowed for the hook's own process-table query. Only the fallback runs it: the usual way to
6
+ * find the host CLI is to ask the daemon (`session.hostOf`). When the query fails or runs out, the
7
+ * hook falls back to its direct parent as the host.
8
+ */
9
+ const HOOK_ANCESTRY_TIMEOUT_MS = 1200;
10
+ const NOTHING = {
11
+ stdout: "",
12
+ exitCode: 0
13
+ };
14
+ /**
15
+ * The pid of the CLI that runs this hook, or undefined when there is nothing to deliver to.
16
+ * The daemon walks the process chain (it keeps a warm query helper on Windows) and answers at once
17
+ * when no session of this CLI is online, so the hook reads no process table in either case. When
18
+ * the daemon cannot answer (an older daemon, a table it may not read), the hook reads the table
19
+ * itself, as it always did, and `complete: false` keeps the direct-parent fallback.
20
+ */
21
+ async function findHostPid(ctx, client, cli, local) {
22
+ if (ctx.hostLookup) {
23
+ const { ppid, launcherPaths } = ctx.hostLookup;
24
+ const r = await client["session.hostOf"]({
25
+ cli,
26
+ ppid,
27
+ launcherPaths
28
+ }).catch(() => void 0);
29
+ if (r && !r.online) return void 0;
30
+ if (r?.complete) return r.hostPid;
31
+ }
32
+ return (await local()).hostPid;
33
+ }
34
+ /**
35
+ * One line of the timing log: `<iso time> cli=<cli> event=<event> ms=<n> proc_ms=<n> timeout=<yes|no>`.
36
+ * `ms` is the time inside `runHook`; `proc_ms` also counts process start-up (what the CLI's own
37
+ * hook limit sees). `timeout=yes` means the hook ran past its limit and was cut off.
38
+ */
39
+ function timingLine(cli, event, ms, procMs, timedOut) {
40
+ return `${(/* @__PURE__ */ new Date()).toISOString()} cli=${cli} event=${event} ms=${ms}${procMs === void 0 ? "" : ` proc_ms=${procMs}`} timeout=${timedOut ? "yes" : "no"}\n`;
41
+ }
42
+ /** After a timeout, the hook gets this many more timeouts' worth of time to finish recording. */
43
+ const FINISH_GRACE_FACTOR = 2;
44
+ /** How long before the hook's timeout its messages count as too late to print. */
45
+ const DEADLINE_MARGIN_MS = 300;
46
+ /**
47
+ * `conveno hook <cli> <event>`: reads the CLI's hook JSON on stdin and prints what the adapter
48
+ * returns. Never starts a daemon. A hook that fails or stalls must not hold the CLI up, so an
49
+ * ordinary hook gives up after the context's timeout (2 s), never writes to stderr and exits 0.
50
+ *
51
+ * Listener events (the adapter's `listenEvents`) are the exception: they run in the background,
52
+ * wait without the 2 s budget until a message arrives or their CLI goes away, and may exit 2 with
53
+ * the message on stderr (Claude Code's `asyncRewake`). They stop on their own when the host CLI
54
+ * exits, the session goes offline, or a newer listener replaces them.
55
+ */
56
+ async function runHook(ctx, argv) {
57
+ const [cli, event] = argv;
58
+ const adapter = ctx.adapters.find((a) => a.cli === cli);
59
+ if (!adapter || !event) return 0;
60
+ const listener = adapter.listenEvents?.includes(event) === true;
61
+ const deadline = listener ? void 0 : Date.now() + ctx.hookTimeoutMs - DEADLINE_MARGIN_MS;
62
+ const t0 = ctx.timingLog && !listener ? Date.now() : void 0;
63
+ let timedOut = false;
64
+ let client;
65
+ let timer;
66
+ const early = ctx.hostLookup ? void 0 : ctx.ancestry(HOOK_ANCESTRY_TIMEOUT_MS);
67
+ const work = (async () => {
68
+ const readInput = async () => {
69
+ try {
70
+ const raw = await ctx.readStdin();
71
+ return raw.trim() === "" ? {} : JSON.parse(raw);
72
+ } catch {
73
+ return {};
74
+ }
75
+ };
76
+ const [input, connected] = await Promise.all([readInput(), ctx.connect(connectOpts(ctx, false))]);
77
+ client = connected;
78
+ const hostPid = await findHostPid(ctx, connected, adapter.cli, () => early ?? ctx.ancestry(1200));
79
+ if (hostPid === void 0) return NOTHING;
80
+ return adapter.hook(event, input, {
81
+ client,
82
+ hostPid,
83
+ cli: adapter.cli,
84
+ isAlive: ctx.isAlive,
85
+ ...deadline === void 0 ? {} : { deadline }
86
+ });
87
+ })();
88
+ const timeout = listener ? new Promise(() => void 0) : new Promise((resolve) => {
89
+ timer = setTimeout(() => {
90
+ timedOut = true;
91
+ resolve(NOTHING);
92
+ }, ctx.hookTimeoutMs);
93
+ });
94
+ let code = 0;
95
+ try {
96
+ const out = await Promise.race([work, timeout]);
97
+ if (out === NOTHING && !listener) await Promise.race([work.catch(() => void 0), new Promise((r) => setTimeout(r, ctx.hookTimeoutMs * FINISH_GRACE_FACTOR))]);
98
+ if (out.stdout) ctx.out(out.stdout.endsWith("\n") ? out.stdout : `${out.stdout}\n`);
99
+ if (listener && out.stderr) ctx.err(out.stderr.endsWith("\n") ? out.stderr : `${out.stderr}\n`);
100
+ if (listener) code = out.exitCode;
101
+ } catch {} finally {
102
+ if (t0 !== void 0 && ctx.timingLog) {
103
+ const up = ctx.uptimeMs?.();
104
+ try {
105
+ appendFileSync(ctx.timingLog, timingLine(adapter.cli, event, Date.now() - t0, up === void 0 ? void 0 : Math.round(up), timedOut));
106
+ } catch {}
107
+ }
108
+ if (timer) clearTimeout(timer);
109
+ work.catch(() => void 0);
110
+ await Promise.race([client?.close().catch(() => void 0), new Promise((r) => setTimeout(r, 100))]);
111
+ }
112
+ return code;
113
+ }
114
+ export { runHook as t };
@@ -0,0 +1 @@
1
+ export { i as runHookEntry } from "./hook-entry-CQQU-e_t.js";