klui-code 0.0.0-stage → 0.1.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.
@@ -0,0 +1,301 @@
1
+ // Spots where Pi shows itself that the extension API can't reach. Each patch reaches into one of
2
+ // Pi's own modules (the same instance Pi runs, resolved from its package) and is skipped quietly
3
+ // if a Pi update moves things around.
4
+ import { Spacer, TruncatedText, TuiAltScreen } from "@earendil-works/pi-tui";
5
+ import { chipFor, isClipboardImageFile } from "./images.js";
6
+ import { scrollFrame } from "./scroll.js";
7
+ export const piModule = async (path) => (await import(new URL(path, import.meta.resolve("@earendil-works/pi-coding-agent")).href));
8
+ export async function patchPi(config) {
9
+ brandOutput();
10
+ scrollWithTerminal();
11
+ clearAfterCopy();
12
+ for (const patch of [hidePiFooter, hoverJumpToLatest, queuedMessages, trimSlashMenu, slashAliases, simpleThinkingMenu, thinkingAfterModel, () => tidyModelPicker(), () => quietPiHints(config), pasteImageChips])
13
+ await patch().catch(() => { });
14
+ }
15
+ /** Klui puts its own footer in place once it loads; Pi's would show until then, and again on /new. */
16
+ async function hidePiFooter() {
17
+ const { FooterComponent } = await piModule("./modes/interactive/components/footer.js");
18
+ if (typeof FooterComponent.prototype.render === "function")
19
+ FooterComponent.prototype.render = () => [];
20
+ }
21
+ /**
22
+ * The terminal title ("π - project"), the line printed on exit ("To resume this session:
23
+ * pi --session …") and a few of Pi's warnings are written straight to stdout.
24
+ */
25
+ function brandOutput() {
26
+ const write = process.stdout.write.bind(process.stdout);
27
+ process.stdout.write = ((chunk, ...rest) => {
28
+ if (typeof chunk === "string" && /π - |\bpi\b|Pi works/.test(chunk))
29
+ chunk = rebrand(chunk);
30
+ return write(chunk, ...rest);
31
+ });
32
+ }
33
+ /** Fullscreen scroll steps move the rows on screen instead of repainting them all (see scroll.ts). */
34
+ function scrollWithTerminal() {
35
+ const proto = TuiAltScreen.prototype;
36
+ const render = proto.doRender;
37
+ if (typeof render !== "function")
38
+ return;
39
+ proto.doRender = function () {
40
+ const before = this.previousScreen;
41
+ const terminal = this.terminal;
42
+ const write = terminal.write;
43
+ let frame;
44
+ terminal.write = (data) => {
45
+ frame = (frame ?? "") + data;
46
+ };
47
+ try {
48
+ render.call(this);
49
+ }
50
+ finally {
51
+ terminal.write = write;
52
+ }
53
+ if (frame !== undefined)
54
+ write.call(terminal, scrollFrame(before, this.previousScreen, frame) ?? frame);
55
+ };
56
+ }
57
+ /** Selecting text copies it (Pi does that), and then the highlight goes away. */
58
+ function clearAfterCopy() {
59
+ const proto = TuiAltScreen.prototype;
60
+ const copy = proto.copySelectionToClipboard;
61
+ if (typeof copy !== "function")
62
+ return;
63
+ proto.copySelectionToClipboard = async function () {
64
+ const copied = copy.call(this);
65
+ this.clearTextSelection();
66
+ this.requestRender();
67
+ return copied;
68
+ };
69
+ }
70
+ /** The "↓ Jump to latest message" bar lights up while the pointer is over it. */
71
+ async function hoverJumpToLatest() {
72
+ const { theme } = await piModule("./modes/interactive/theme/theme.js");
73
+ const proto = TuiAltScreen.prototype;
74
+ const handle = proto.handleMouseEvent;
75
+ const composite = proto.compositeScrollToEndIndicator;
76
+ if (typeof handle !== "function" || typeof composite !== "function")
77
+ return;
78
+ proto.handleMouseEvent = function (raw) {
79
+ const rect = this.scrollToEndIndicatorRect;
80
+ const over = !!rect && raw.y === rect.row && raw.x >= rect.column && raw.x < rect.column + rect.width;
81
+ if (over !== !!this.kluiJumpHover) {
82
+ this.kluiJumpHover = over;
83
+ this.requestRender();
84
+ }
85
+ return handle.call(this, raw);
86
+ };
87
+ proto.compositeScrollToEndIndicator = function (...args) {
88
+ const label = this.scrollToEndIndicator;
89
+ if (this.kluiJumpHover && label) {
90
+ this.scrollToEndIndicator = () => theme.inverse(theme.fg("accent", theme.bold(label().replace(/\x1b\[[\d;]*m/g, ""))));
91
+ }
92
+ try {
93
+ return composite.apply(this, args);
94
+ }
95
+ finally {
96
+ this.scrollToEndIndicator = label;
97
+ // Gone (jumped to the end): it comes back unlit wherever the pointer is.
98
+ if (!this.scrollToEndIndicatorRect)
99
+ this.kluiJumpHover = false;
100
+ }
101
+ };
102
+ }
103
+ /**
104
+ * Messages sent while Klui works wait under the chat as "Queued" and go in once the current step
105
+ * is done. Pi labels them "Steering" and "Follow-up", after how they're delivered.
106
+ */
107
+ async function queuedMessages() {
108
+ const [{ InteractiveMode }, { theme }] = await Promise.all([
109
+ piModule("./modes/interactive/interactive-mode.js"),
110
+ piModule("./modes/interactive/theme/theme.js"),
111
+ ]);
112
+ if (typeof InteractiveMode.prototype.updatePendingMessagesDisplay !== "function")
113
+ return;
114
+ InteractiveMode.prototype.updatePendingMessagesDisplay = function () {
115
+ const { steering, followUp } = this.getAllQueuedMessages();
116
+ const queued = [...steering, ...followUp];
117
+ this.pendingMessagesContainer.clear();
118
+ if (queued.length === 0)
119
+ return;
120
+ this.pendingMessagesContainer.addChild(new Spacer(1));
121
+ for (const text of queued)
122
+ this.pendingMessagesContainer.addChild(new TruncatedText(`${theme.fg("accent", "⏵ Queued")} ${theme.fg("muted", text)}`, 1, 0));
123
+ this.pendingMessagesContainer.addChild(new TruncatedText(theme.fg("dim", ` ${this.getAppKeyDisplay("app.message.dequeue")} to edit`), 1, 0));
124
+ };
125
+ }
126
+ /** Pi's own lines that can reach the screen, renamed. */
127
+ function rebrand(text) {
128
+ return text
129
+ .replaceAll("\x1b]0;π - ", "\x1b]0;klui · ")
130
+ .replace(/(To resume this session:\S*\s+)pi(?= )/, "$1klui")
131
+ .replaceAll("`pi -r`", "`klui -r`")
132
+ .replaceAll("start pi and", "start klui and")
133
+ .replaceAll("restart pi.", "restart klui.")
134
+ .replaceAll("Pi works best", "Klui works best");
135
+ }
136
+ /**
137
+ * Klui's slash menu: /resume and /exit (see slashAliases) open /sessions and quit. Pi's /session,
138
+ * its bug reporter (it files issues with the Pi developers), its changelog and /scoped-models stay
139
+ * out of the list; they still work when typed.
140
+ */
141
+ async function trimSlashMenu() {
142
+ const { BUILTIN_SLASH_COMMANDS: commands } = await piModule("./core/slash-commands.js");
143
+ const hidden = new Set(["session", "bug", "changelog", "scoped-models"]);
144
+ for (let i = commands.length - 1; i >= 0; i--)
145
+ if (hidden.has(commands[i].name))
146
+ commands.splice(i, 1);
147
+ const resume = commands.find((c) => c.name === "resume");
148
+ if (resume)
149
+ resume.description = "Pick up one of your earlier chats";
150
+ const quit = commands.findIndex((c) => c.name === "quit");
151
+ if (quit !== -1)
152
+ commands.splice(quit, 1, { name: "quit", description: "Quit Klui Code" }, { name: "exit", description: "Quit Klui Code" });
153
+ }
154
+ let interactive;
155
+ /** Opens the reasoning menu, as /thinking does. Nothing happens outside the interactive UI. */
156
+ export function showThinkingMenu() {
157
+ if (interactive?.session.supportsThinking())
158
+ interactive.showThinkingSelector();
159
+ }
160
+ /** /resume opens Klui's /sessions picker, and /exit quits like /quit. */
161
+ async function slashAliases() {
162
+ const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
163
+ const proto = InteractiveMode.prototype;
164
+ const setup = proto.setupEditorSubmitHandler;
165
+ if (typeof setup !== "function")
166
+ return;
167
+ proto.setupEditorSubmitHandler = function () {
168
+ setup.call(this);
169
+ interactive = this;
170
+ const submit = this.defaultEditor.onSubmit;
171
+ if (!submit)
172
+ return;
173
+ const aliases = { "/resume": "/sessions", "/exit": "/quit" };
174
+ this.defaultEditor.onSubmit = (text) => submit(aliases[text.trim()] ?? text);
175
+ };
176
+ }
177
+ /**
178
+ * The reasoning menu lists just the levels. Pi's adds a title, a key hint, a search box, a line
179
+ * about each level and a key legend. Typing still filters, and ctrl+s still sets the default.
180
+ */
181
+ async function simpleThinkingMenu() {
182
+ const { ThinkingSelectorComponent } = await piModule("./modes/interactive/components/thinking-selector.js");
183
+ const proto = ThinkingSelectorComponent.prototype;
184
+ const render = proto.render;
185
+ if (typeof render !== "function" || typeof proto.buildSelectList !== "function")
186
+ return;
187
+ proto.render = function (width) {
188
+ if (!this.kluiTidy) {
189
+ this.kluiTidy = true;
190
+ const first = this.children[0];
191
+ const last = this.children[this.children.length - 1];
192
+ const current = this.selectList.getSelectedItem()?.value;
193
+ this.allItems = this.allItems.map((item) => ({ value: item.value, label: item.value }));
194
+ this.selectList = this.buildSelectList(this.allItems, current);
195
+ this.children = [first, this.selectList, last];
196
+ this.selectListChildIndex = 1;
197
+ }
198
+ return render.call(this, width);
199
+ };
200
+ }
201
+ /** Picking a model in Pi's model picker opens the reasoning menu next. */
202
+ async function thinkingAfterModel() {
203
+ const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
204
+ const proto = InteractiveMode.prototype;
205
+ const show = proto.showModelSelector;
206
+ if (typeof show !== "function")
207
+ return;
208
+ proto.showModelSelector = function (search) {
209
+ show.call(this, search);
210
+ const picker = this.editorContainer.children.at(-1);
211
+ for (const key of ["onSelectCallback", "onSelectAsDefaultCallback"]) {
212
+ const pick = picker?.[key];
213
+ if (typeof pick !== "function")
214
+ continue;
215
+ picker[key] = async (model) => {
216
+ await pick(model);
217
+ // Only once the switch went through.
218
+ if (this.session.model?.provider === model.provider && this.session.model.id === model.id)
219
+ showThinkingMenu();
220
+ };
221
+ }
222
+ };
223
+ }
224
+ /**
225
+ * The model picker as a plain list of model names under the search box. Pi's version adds the
226
+ * scope switch, raw gateway ids (peer hashes included), provider badges and a key legend.
227
+ */
228
+ async function tidyModelPicker() {
229
+ const [{ ModelSelectorComponent }, { theme }, { Text }] = await Promise.all([
230
+ piModule("./modes/interactive/components/model-selector.js"),
231
+ piModule("./modes/interactive/theme/theme.js"),
232
+ import("@earendil-works/pi-tui"),
233
+ ]);
234
+ const proto = ModelSelectorComponent.prototype;
235
+ const load = proto.loadModelsFromSnapshot;
236
+ // Runs once the constructor has added everything: keep the borders, search box and list.
237
+ proto.loadModelsFromSnapshot = function () {
238
+ const first = this.children[0];
239
+ const last = this.children[this.children.length - 1];
240
+ if (first && last && this.children.includes(this.searchInput)) {
241
+ this.children = [first, this.searchInput, new Spacer(1), this.listContainer, last];
242
+ }
243
+ load.call(this);
244
+ };
245
+ proto.updateList = function () {
246
+ this.listContainer.clear();
247
+ const visible = 10;
248
+ const start = Math.max(0, Math.min(this.selectedIndex - Math.floor(visible / 2), this.filteredModels.length - visible));
249
+ const end = Math.min(start + visible, this.filteredModels.length);
250
+ for (let i = start; i < end; i++) {
251
+ const item = this.filteredModels[i];
252
+ const name = item.model.name || item.id;
253
+ const line = i === this.selectedIndex ? theme.fg("accent", `→ ${name}`) : ` ${name}`;
254
+ this.listContainer.addChild(new Text(line, 0, 0));
255
+ }
256
+ if (this.errorMessage)
257
+ this.listContainer.addChild(new Text(theme.fg("error", this.errorMessage), 0, 0));
258
+ else if (this.filteredModels.length === 0)
259
+ this.listContainer.addChild(new Text(theme.fg("muted", " No matching models"), 0, 0));
260
+ };
261
+ }
262
+ /**
263
+ * Pi suggests "/bug sends a report to the developers" after an error, and confirms a model switch
264
+ * with its gateway id ("Model: 73b4…@mimo-v2.6-flash"). Klui shows the model's name instead.
265
+ */
266
+ async function quietPiHints(config) {
267
+ const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
268
+ const proto = InteractiveMode.prototype;
269
+ proto.suggestBugReport = () => { };
270
+ const showStatus = proto.showStatus;
271
+ proto.showStatus = function (message) {
272
+ const match = /^(Default model|Model): (?:klui\/)?(.+)$/.exec(message);
273
+ const name = match && config.models.find((m) => m.id === match[2])?.name;
274
+ showStatus.call(this, name ? `${match[1] === "Model" ? "Using" : "Default is now"} ${name}` : message);
275
+ };
276
+ }
277
+ /** ctrl+v with an image on the clipboard puts an "[Image #1]" chip in the composer, not a temp path. */
278
+ async function pasteImageChips() {
279
+ const { InteractiveMode } = await piModule("./modes/interactive/interactive-mode.js");
280
+ const proto = InteractiveMode.prototype;
281
+ const paste = proto.handleClipboardPaste;
282
+ if (typeof paste !== "function")
283
+ return;
284
+ proto.handleClipboardPaste = async function () {
285
+ const editor = this.editor;
286
+ const insert = editor.insertTextAtCursor;
287
+ if (typeof insert !== "function")
288
+ return paste.call(this);
289
+ const own = Object.hasOwn(editor, "insertTextAtCursor");
290
+ editor.insertTextAtCursor = (text) => insert.call(editor, isClipboardImageFile(text) ? `${chipFor(text)} ` : text);
291
+ try {
292
+ await paste.call(this);
293
+ }
294
+ finally {
295
+ if (own)
296
+ editor.insertTextAtCursor = insert;
297
+ else
298
+ delete editor.insertTextAtCursor;
299
+ }
300
+ };
301
+ }
package/dist/pixels.js ADDED
@@ -0,0 +1,107 @@
1
+ // Pixel art for the terminal. Every pixel is one column wide and half a row tall, which is close
2
+ // to square in most terminal fonts, so two stacked pixels share one cell through "▀" / "▄". A cell
3
+ // whose two pixels match is drawn as a colored space rather than "█": terminals fill a cell's
4
+ // background edge to edge, but draw "█" from the font, which leaves seams between cells. For the
5
+ // same reason a cell with two colors puts the surrounding color in the background: a half block
6
+ // rarely covers exactly half, and the sliver it leaves then blends in.
7
+ import { backgroundAnsi, foregroundAnsi, parseColor } from "@earendil-works/pi-tui";
8
+ const RESET_FG = "\x1b[39m";
9
+ const RESET_BG = "\x1b[49m";
10
+ const ansiCache = new Map();
11
+ function ansi(hex, mode, layer) {
12
+ const key = `${layer}:${mode}:${hex}`;
13
+ let value = ansiCache.get(key);
14
+ if (value === undefined) {
15
+ const color = parseColor(hex);
16
+ value = layer === "fg" ? foregroundAnsi(color, mode) : backgroundAnsi(color, mode);
17
+ ansiCache.set(key, value);
18
+ }
19
+ return value;
20
+ }
21
+ /** Turn pixels into terminal lines, two pixel rows per line. Every line is exactly `width` columns. */
22
+ export function renderPixels(pixels, mode) {
23
+ const width = Math.max(0, ...pixels.map((row) => row.length));
24
+ const lines = [];
25
+ for (let y = 0; y < pixels.length; y += 2) {
26
+ const top = pixels[y] ?? [];
27
+ const bottom = pixels[y + 1] ?? [];
28
+ let line = "";
29
+ let fg = null;
30
+ let bg = null;
31
+ const setFg = (hex) => {
32
+ if (hex === fg)
33
+ return;
34
+ line += hex ? ansi(hex, mode, "fg") : RESET_FG;
35
+ fg = hex;
36
+ };
37
+ const setBg = (hex) => {
38
+ if (hex === bg)
39
+ return;
40
+ line += hex ? ansi(hex, mode, "bg") : RESET_BG;
41
+ bg = hex;
42
+ };
43
+ for (let x = 0; x < width; x++) {
44
+ const t = top[x] ?? null;
45
+ const b = bottom[x] ?? null;
46
+ if (!t && !b) {
47
+ setBg(null);
48
+ line += " ";
49
+ }
50
+ else if (t && b && t === b) {
51
+ setBg(t);
52
+ line += " ";
53
+ }
54
+ else if (t && !b) {
55
+ setBg(null);
56
+ setFg(t);
57
+ line += "▀";
58
+ }
59
+ else if (!t && b) {
60
+ setBg(null);
61
+ setFg(b);
62
+ line += "▄";
63
+ }
64
+ else {
65
+ const solid = (i) => (top[i] && top[i] === bottom[i] ? top[i] : undefined);
66
+ const around = solid(x - 1) ?? solid(x + 1);
67
+ const flip = around === t;
68
+ setFg(flip ? b : t);
69
+ setBg(flip ? t : b);
70
+ line += flip ? "▄" : "▀";
71
+ }
72
+ }
73
+ if (fg)
74
+ line += RESET_FG;
75
+ if (bg)
76
+ line += RESET_BG;
77
+ lines.push(line);
78
+ }
79
+ return lines;
80
+ }
81
+ /** A blank canvas that sprites draw rectangles onto. */
82
+ export function canvas(width, height) {
83
+ return Array.from({ length: height }, () => Array(width).fill(null));
84
+ }
85
+ export function fillRect(pixels, x, y, w, h, color) {
86
+ for (let row = Math.max(0, y); row < Math.min(pixels.length, y + h); row++) {
87
+ const line = pixels[row];
88
+ for (let col = Math.max(0, x); col < Math.min(line.length, x + w); col++)
89
+ line[col] = color;
90
+ }
91
+ }
92
+ /** Draw ASCII art: each character maps to a color through `palette`; unknown characters are transparent. */
93
+ export function fromArt(art, palette) {
94
+ const width = Math.max(...art.map((row) => row.length));
95
+ return art.map((row) => Array.from({ length: width }, (_, x) => palette[row[x] ?? "."] ?? null));
96
+ }
97
+ /** Mix two hex colors; `t` = 0 gives `a`, 1 gives `b`. */
98
+ export function mixHex(a, b, t) {
99
+ const pa = parseInt(a.slice(1), 16);
100
+ const pb = parseInt(b.slice(1), 16);
101
+ const channel = (shift) => {
102
+ const ca = (pa >> shift) & 0xff;
103
+ const cb = (pb >> shift) & 0xff;
104
+ return Math.round(ca + (cb - ca) * t);
105
+ };
106
+ return `#${((channel(16) << 16) | (channel(8) << 8) | channel(0)).toString(16).padStart(6, "0")}`;
107
+ }
package/dist/scroll.js ADDED
@@ -0,0 +1,77 @@
1
+ // Pi's fullscreen mode repaints every row that changed. A scroll step changes every row of the chat,
2
+ // so each wheel tick rewrote the whole screen, which Terminal.app draws as a visible stagger. This
3
+ // turns such a frame into what vim and less send: one hardware scroll of the rows that moved, then
4
+ // only the rows that are actually new.
5
+ const BEGIN = "\x1b[?2026h";
6
+ const END = "\x1b[?2026l";
7
+ /** Pi's frame ends by placing (or hiding) the cursor. */
8
+ const TAIL = /(?:\x1b\[\d+;\d+H)?\x1b\[\?25[hl]\x1b\[\?2026l$/;
9
+ /** Images and full clears are left to Pi. */
10
+ const UNSAFE = /\x1b\[2J|\x1b_G|\x1b\]1337;/;
11
+ /** Below this many moved rows a plain repaint is just as cheap. */
12
+ const MIN_MOVED = 4;
13
+ /**
14
+ * The frame Pi wrote to go from `before` to `after`, rewritten to scroll the terminal when most of
15
+ * the screen just moved. Returns `undefined` to keep Pi's frame.
16
+ */
17
+ export function scrollFrame(before, after, frame) {
18
+ const height = after.length;
19
+ if (height === 0 || before.length !== height || !frame.startsWith(BEGIN) || UNSAFE.test(frame))
20
+ return undefined;
21
+ const tail = TAIL.exec(frame);
22
+ if (!tail)
23
+ return undefined;
24
+ const shift = bestShift(before, after);
25
+ if (!shift)
26
+ return undefined;
27
+ const { by, top, bottom } = shift;
28
+ const screen = [...before];
29
+ const k = Math.abs(by);
30
+ let out = `${BEGIN}\x1b[0m\x1b[${top + 1};${bottom + 1}r`;
31
+ if (by > 0) {
32
+ out += `\x1b[${bottom + 1};1H${"\n".repeat(k)}`;
33
+ screen.splice(top, k);
34
+ screen.splice(bottom - k + 1, 0, ...new Array(k).fill(""));
35
+ }
36
+ else {
37
+ out += `\x1b[${top + 1};1H${"\x1bM".repeat(k)}`;
38
+ screen.splice(bottom - k + 1, k);
39
+ screen.splice(top, 0, ...new Array(k).fill(""));
40
+ }
41
+ out += "\x1b[r";
42
+ for (let row = 0; row < height; row++) {
43
+ if (screen[row] !== after[row])
44
+ out += `\x1b[${row + 1};1H\x1b[2K${after[row]}`;
45
+ }
46
+ out += tail[0];
47
+ return out.length < frame.length ? out : undefined;
48
+ }
49
+ /**
50
+ * The scroll that leaves the most rows already in place. Rows that stay put inside the moved span
51
+ * (Pi's scrollbar thumb edges, the "Jump to latest" bar) are repainted after the scroll instead of
52
+ * splitting it. Blank rows don't count as moved.
53
+ */
54
+ function bestShift(before, after) {
55
+ const height = after.length;
56
+ let best;
57
+ for (let k = 1; k < height - 1; k++) {
58
+ for (const by of [k, -k]) {
59
+ let first = -1;
60
+ let last = -1;
61
+ let moved = 0;
62
+ for (let row = Math.max(0, -by); row < Math.min(height, height - by); row++) {
63
+ if (after[row] !== before[row + by])
64
+ continue;
65
+ if (first < 0)
66
+ first = row;
67
+ last = row;
68
+ if (after[row] !== "")
69
+ moved++;
70
+ }
71
+ if (moved < MIN_MOVED || moved <= (best?.moved ?? 0))
72
+ continue;
73
+ best = by > 0 ? { by, top: first, bottom: last + by, moved } : { by, top: first + by, bottom: last, moved };
74
+ }
75
+ }
76
+ return best;
77
+ }
package/dist/update.js ADDED
@@ -0,0 +1,133 @@
1
+ // Updating klui in place, like `opencode upgrade`: `klui update` in the shell or /update in the
2
+ // app installs the latest release over the current one, the same way it was installed (the
3
+ // curl installer's folder or a global npm install). The next launch runs the new version.
4
+ import { spawn } from "node:child_process";
5
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { KLUI_HOME, PACKAGE_DIR, VERSION } from "./paths.js";
8
+ const PACKAGE = "klui-code";
9
+ const CHECK_FILE = join(KLUI_HOME, "update-check.json");
10
+ const CHECK_EVERY_MS = 24 * 60 * 60 * 1000;
11
+ export function installKind(dir = PACKAGE_DIR) {
12
+ if (basename(dirname(dir)) !== "node_modules")
13
+ return { kind: "source" };
14
+ const root = dirname(dirname(dir));
15
+ // `npm install --prefix` (what install.sh does) leaves a package.json naming klui; a global
16
+ // npm folder has none.
17
+ try {
18
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
19
+ if (pkg?.dependencies?.[PACKAGE])
20
+ return { kind: "prefix", root };
21
+ }
22
+ catch { }
23
+ return { kind: "global" };
24
+ }
25
+ /** Whether version `a` is newer than `b` (semver, prereleases before their release). */
26
+ export function newer(a, b) {
27
+ const parse = (v) => {
28
+ const [core = "", pre] = v.trim().replace(/^v/, "").split("-", 2);
29
+ return { core: core.split(".").map((n) => Number(n) || 0), pre };
30
+ };
31
+ const x = parse(a);
32
+ const y = parse(b);
33
+ for (let i = 0; i < 3; i++)
34
+ if ((x.core[i] ?? 0) !== (y.core[i] ?? 0))
35
+ return (x.core[i] ?? 0) > (y.core[i] ?? 0);
36
+ if (!x.pre || !y.pre)
37
+ return !x.pre && !!y.pre;
38
+ return x.pre.localeCompare(y.pre, "en", { numeric: true }) > 0;
39
+ }
40
+ /** The latest published version, or undefined when the registry can't be reached. */
41
+ export async function latestVersion(timeoutMs = 5000) {
42
+ const registry = (process.env.NPM_CONFIG_REGISTRY || process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
43
+ try {
44
+ const res = await fetch(`${registry}/${PACKAGE}/latest`, { signal: AbortSignal.timeout(timeoutMs) });
45
+ if (!res.ok)
46
+ return undefined;
47
+ const version = (await res.json()).version;
48
+ return typeof version === "string" ? version : undefined;
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ }
54
+ /** Installs the latest release over this one. `onStart` hears the version before npm runs. */
55
+ export async function update(onStart = () => { }) {
56
+ const install = installKind();
57
+ if (install.kind === "source")
58
+ return { status: "failed", message: "This klui runs from a source checkout. Update it with git pull && npm install." };
59
+ const latest = await latestVersion(10_000);
60
+ if (!latest)
61
+ return { status: "failed", message: "Couldn't reach the npm registry. Check your connection and try again." };
62
+ if (!newer(latest, VERSION))
63
+ return { status: "current", version: VERSION };
64
+ onStart(latest);
65
+ const where = install.kind === "prefix" ? ["--prefix", install.root] : ["-g"];
66
+ const { ok, output } = await npm(["install", ...where, "--no-fund", "--no-audit", "--loglevel=error", `${PACKAGE}@${latest}`]);
67
+ if (!ok) {
68
+ const last = output.trim().split("\n").filter(Boolean).pop() ?? "npm failed";
69
+ const hint = /EACCES|permission denied/i.test(output) ? " npm can't write to its global folder; rerun the install script or fix npm's permissions." : "";
70
+ return { status: "failed", message: `The update didn't install: ${last}${hint}` };
71
+ }
72
+ remember(latest);
73
+ return { status: "updated", from: VERSION, to: installedVersion() ?? latest };
74
+ }
75
+ /**
76
+ * A newer release than this one, from a check made at most once a day (the answer is kept in
77
+ * ~/.klui). Undefined when up to date, offline, or running from source.
78
+ */
79
+ export async function availableUpdate() {
80
+ if (installKind().kind === "source")
81
+ return undefined;
82
+ let latest;
83
+ try {
84
+ const saved = JSON.parse(readFileSync(CHECK_FILE, "utf8"));
85
+ if (typeof saved.checkedAt === "number" && Date.now() - saved.checkedAt < CHECK_EVERY_MS)
86
+ latest = saved.latest;
87
+ }
88
+ catch { }
89
+ if (!latest) {
90
+ latest = await latestVersion();
91
+ if (latest)
92
+ remember(latest);
93
+ }
94
+ return latest && newer(latest, VERSION) ? latest : undefined;
95
+ }
96
+ function remember(latest) {
97
+ try {
98
+ writeFileSync(CHECK_FILE, `${JSON.stringify({ checkedAt: Date.now(), latest })}\n`);
99
+ }
100
+ catch { }
101
+ }
102
+ /** The version now on disk, which is what the next launch runs. */
103
+ function installedVersion() {
104
+ try {
105
+ return JSON.parse(readFileSync(join(PACKAGE_DIR, "package.json"), "utf8")).version;
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ }
111
+ /** npm next to the Node running klui (the installer's own copy), else the one on PATH. */
112
+ function npm(args) {
113
+ const win = process.platform === "win32";
114
+ // npm's own script, run by this Node, so no shell has to parse a path like C:\Program Files.
115
+ const node = dirname(process.execPath);
116
+ const cli = [join(node, "node_modules", "npm", "bin", "npm-cli.js"), join(node, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js")].find((path) => existsSync(path));
117
+ return new Promise((done) => {
118
+ const child = spawn(cli ? process.execPath : win ? "npm.cmd" : "npm", cli ? [cli, ...args] : args, {
119
+ env: { ...process.env, NPM_CONFIG_UPDATE_NOTIFIER: "false", PATH: `${node}${win ? ";" : ":"}${process.env.PATH ?? ""}` },
120
+ stdio: ["ignore", "pipe", "pipe"],
121
+ shell: win && !cli,
122
+ windowsHide: true,
123
+ });
124
+ let output = "";
125
+ const keep = (chunk) => {
126
+ output = (output + chunk.toString()).slice(-4000);
127
+ };
128
+ child.stdout.on("data", keep);
129
+ child.stderr.on("data", keep);
130
+ child.on("error", (error) => done({ ok: false, output: error.message }));
131
+ child.on("close", (code) => done({ ok: code === 0, output }));
132
+ });
133
+ }