@bolt-cli/cli 0.0.0-stage → 0.13.0

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/lib/ui.js ADDED
@@ -0,0 +1,783 @@
1
+ "use strict";
2
+ // Terminal presentation layer. Zero deps: hand-rolled ANSI only.
3
+ //
4
+ // Scope note: this is deliberately *not* a full-screen TUI. opencode renders
5
+ // with OpenTUI + SolidJS (native binary, ~50MB of deps); bolt stays dependency
6
+ // free so `npm i -g @bolt-cli/cli` is instant. What we reproduce here is the
7
+ // vocabulary and feel -- semantic colour tokens with the same names opencode's
8
+ // TUI uses, a status-carrying prompt, a thinking indicator, an arrow-key
9
+ // command palette, and quiet de-prioritised prose.
10
+ //
11
+ // Every helper degrades to plain text when stdout is not a TTY, when NO_COLOR
12
+ // is set, or when the terminal only supports 16 colours, so piped output and CI
13
+ // logs stay clean.
14
+
15
+ const ESC = "\u001b";
16
+
17
+ const PALETTE = {
18
+ primary: "#38bdf8", // the brand/energy colour: prompt, labels, focus
19
+ accent: "#c084fc", // secondary highlight: agents, selected rows
20
+ success: "#4ade80",
21
+ warning: "#fbbf24",
22
+ error: "#fb7185",
23
+ info: "#60a5fa",
24
+ muted: "#94a3b8", // anything de-prioritised: hints, descriptions, rules
25
+ border: "#475569",
26
+ };
27
+ // NOTE: there is deliberately no `text` token. Leaving body copy at the
28
+ // terminal's own foreground means we never fight a user's light-on-dark or
29
+ // dark-on-light scheme. We only ever colour accent/semantic text.
30
+
31
+ // Pure capability probe, tested. `env` is a plain object (defaults to
32
+ // process.env), `stdio` describes the streams: { stdoutTTY, stdinTTY,
33
+ // stdoutDepth }. Terminals that report a pipe on stdout but are really an
34
+ // interactive screen (mintty/Git Bash, ConEmu, Windows Terminal inheritants)
35
+ // still get color when a human is watching (stdin is a TTY) and the terminal
36
+ // advertises capability. Pipes with no watcher stay clean, so CI logs and
37
+ // `--format json > file` never carry ANSI codes unless FORCE_COLOR says so.
38
+ function resolveDepth({ env = {}, stdoutTTY = false, stdinTTY = false, stdoutDepth = 1 } = {}) {
39
+ if (env.NO_COLOR) return 0;
40
+ if (env.FORCE_COLOR === "0") return 0;
41
+ if (env.FORCE_COLOR) {
42
+ const n = Number(env.FORCE_COLOR);
43
+ if (Number.isNaN(n)) return 1;
44
+ return n >= 3 ? 3 : n >= 2 ? 2 : 1;
45
+ }
46
+ if (env.TERM === "dumb") return 0;
47
+ if (stdoutTTY) {
48
+ const d = stdoutDepth;
49
+ return d >= 24 ? 3 : d >= 8 ? 2 : 1;
50
+ }
51
+ // No stdout TTY: only light up for a watched capable screen.
52
+ if (!stdinTTY) return 0;
53
+ const term = String(env.TERM || "");
54
+ const program = String(env.TERM_PROGRAM || "");
55
+ const termBlob = `${term} ${program} ${env.MSYSTEM || ""} ${env.ConEmuANSI || ""} ${env.ANSICON || ""}`;
56
+ const capable =
57
+ Boolean(env.WT_SESSION) ||
58
+ Boolean(env.ANSICON) ||
59
+ Boolean(env.ConEmuANSI) ||
60
+ program === "vscode" ||
61
+ /xterm|256colou?r|truecolor|24bit|screen|tmux|rxvt|alacritty|wezterm|kitty|iterm|mintty/i.test(termBlob);
62
+ if (!capable) return 0;
63
+ if (/truecolor|24bit/i.test(`${term} ${env.COLORTERM || ""}`) || Boolean(env.WT_SESSION) || /MINGW|MSYS/i.test(String(env.MSYSTEM || ""))) return 3;
64
+ if (/256colou?r/i.test(termBlob)) return 2;
65
+ return 1;
66
+ }
67
+
68
+ function depth(stream) {
69
+ const env = process.env;
70
+ return resolveDepth({
71
+ env,
72
+ stdoutTTY: Boolean(stream && stream.isTTY),
73
+ stdinTTY: Boolean(process.stdin && process.stdin.isTTY),
74
+ stdoutDepth: stream && typeof stream.getColorDepth === "function" ? stream.getColorDepth() : 1,
75
+ });
76
+ }
77
+
78
+ function parseHex(hex) {
79
+ const h = hex.replace("#", "");
80
+ return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
81
+ }
82
+
83
+ // Grayscale ramp for 256-colour terminals: keeps greys smooth instead of
84
+ // smearing them onto the colour cube, which looks muddy for borders.
85
+ function to256([r, g, b]) {
86
+ if (Math.abs(r - g) < 12 && Math.abs(g - b) < 12) {
87
+ if (r < 8) return 16;
88
+ if (r > 248) return 231;
89
+ return 232 + Math.round(((r - 8) / 247) * 24);
90
+ }
91
+ return 16 + 36 * Math.round((r / 255) * 5) + 6 * Math.round((g / 255) * 5) + Math.round((b / 255) * 5);
92
+ }
93
+
94
+ const BASE16 = [
95
+ [0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],
96
+ [0, 0, 128], [128, 0, 128], [0, 128, 128], [192, 192, 192],
97
+ [128, 128, 128], [255, 0, 0], [0, 255, 0], [255, 255, 0],
98
+ [0, 0, 255], [255, 0, 255], [0, 255, 255], [255, 255, 255],
99
+ ];
100
+
101
+ function to16([r, g, b]) {
102
+ let best = 0;
103
+ let bestDist = Infinity;
104
+ for (let i = 0; i < BASE16.length; i += 1) {
105
+ const [br, bg, bb] = BASE16[i];
106
+ const d = (r - br) ** 2 + (g - bg) ** 2 + (b - bb) ** 2;
107
+ if (d < bestDist) {
108
+ bestDist = d;
109
+ best = i;
110
+ }
111
+ }
112
+ return best;
113
+ }
114
+
115
+ function wrap(open, close) {
116
+ return (s) => (s === undefined || s === null ? "" : `${ESC}[${open}m${s}${ESC}[${close}m`);
117
+ }
118
+
119
+ function buildColors(level) {
120
+ const out = { enabled: level > 0 };
121
+ if (!level) {
122
+ for (const name of Object.keys(PALETTE)) out[name] = (s) => String(s === undefined ? "" : s);
123
+ out.bold = out.dim = out.underline = out.primary;
124
+ return out;
125
+ }
126
+ for (const [name, hex] of Object.entries(PALETTE)) {
127
+ const rgb = parseHex(hex);
128
+ if (level === 3) out[name] = wrap(`38;2;${rgb[0]};${rgb[1]};${rgb[2]}`, 39);
129
+ else if (level === 2) out[name] = wrap(`38;5;${to256(rgb)}`, 39);
130
+ else {
131
+ const n = to16(rgb);
132
+ out[name] = wrap(n < 8 ? 30 + n : 90 + (n - 8), 39);
133
+ }
134
+ }
135
+ out.bold = wrap(1, 22);
136
+ out.dim = wrap(2, 22);
137
+ out.underline = wrap(4, 24);
138
+ out.inverse = wrap(7, 27);
139
+ return out;
140
+ }
141
+
142
+ const isTTY = () => Boolean(process.stdout.isTTY);
143
+ const c = buildColors(depth(process.stdout));
144
+
145
+ // Pure glyph probe, tested. Box-drawing characters are display-only (never
146
+ // parsed), so the bar is lower than for color: any terminal that advertises
147
+ // capability gets them, including mintty/Git Bash (MSYSTEM) and classic
148
+ // Windows consoles only when they prove modern (Windows Terminal, VS Code).
149
+ // Unknown Windows consoles keep ASCII so raster fonts never show tofu.
150
+ function supportsUnicode(platform, env = {}) {
151
+ if (platform !== "win32") return true;
152
+ if (env.WT_SESSION || (env.TERM_PROGRAM || "") === "vscode") return true;
153
+ const blob = `${env.TERM || ""} ${env.MSYSTEM || ""} ${env.ConEmuANSI || ""} ${env.ANSICON || ""}`;
154
+ return /xterm|256colou?r|truecolor|24bit|screen|tmux|mintty|MINGW|MSYS|ConEmu|ANSICON/i.test(blob);
155
+ }
156
+
157
+ function unicode() {
158
+ return supportsUnicode(process.platform, process.env);
159
+ }
160
+
161
+ const U = unicode();
162
+ const GLYPH = U
163
+ ? { tl: "╭", tr: "╮", bl: "╰", br: "╯", h: "─", v: "│", caret: "›", bar: "▌", sel: "▸", tick: "✔", cross: "✖", dot: "·", arrow: "→", rule: "─" }
164
+ : { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|", caret: ">", bar: "|", sel: ">", tick: "OK", cross: "x", dot: "*", arrow: "->", rule: "-" };
165
+
166
+ function width() {
167
+ const columns = process.stdout.columns;
168
+ return typeof columns === "number" && columns > 20 ? Math.min(columns, 100) : 78;
169
+ }
170
+
171
+ // Block-letter wordmark in the opencode logo.ts spirit: heavy blocks where
172
+ // the terminal proves modern, the plain word everywhere else so raster fonts
173
+ // never show tofu. Rows pad to one width in code (no trailing whitespace in
174
+ // the literals for linters to flag); every glyph is one cell, so length math
175
+ // holds. Pure, tested.
176
+ const LOGO_RAW = [
177
+ "██████╗ ██████╗ ██╗ █████████",
178
+ "██╔══██╗ ██╔══██╗ ██║ █████████",
179
+ "██████╔╝ ██║ ██║ ██║ █",
180
+ "██╔══██╗ ██║ ██║ ██║ █",
181
+ "██████╔╝ ██║ ██║ ██║ █",
182
+ "╚═════╝ ╚════╝ ██║▄▄▄▄",
183
+ ];
184
+ const LOGO_WIDTH = Math.max(...LOGO_RAW.map((row) => row.length));
185
+ const LOGO = U ? LOGO_RAW.map((row) => row + " ".repeat(LOGO_WIDTH - row.length)) : ["bolt"];
186
+
187
+ // Relative timestamps for pickers and dashboards ("5m ago"). Pure, tested:
188
+ // `now` injects the clock, unparseable input yields "".
189
+ function relTime(iso, now = Date.now()) {
190
+ const then = Date.parse(iso);
191
+ if (Number.isNaN(then)) return "";
192
+ const s = Math.max(0, Math.floor((now - then) / 1000));
193
+ if (s < 60) return "just now";
194
+ const m = Math.floor(s / 60);
195
+ if (m < 60) return `${m}m ago`;
196
+ const h = Math.floor(m / 60);
197
+ if (h < 24) return `${h}h ago`;
198
+ const d = Math.floor(h / 24);
199
+ if (d < 30) return `${d}d ago`;
200
+ return new Date(then).toISOString().slice(0, 10);
201
+ }
202
+
203
+ // eslint-disable-next-line no-control-regex -- deliberate ANSI CSI matcher for padding maths.
204
+ const ANSI = /\u001b\[[0-9;]*m/g;
205
+
206
+ // Padding maths has to ignore escape sequences, otherwise a coloured line makes
207
+ // the right-hand border sit in the wrong column.
208
+ function visibleLength(s) {
209
+ return stripAnsi(s).length;
210
+ }
211
+
212
+ // Plain-text form of a styled line: assertions, width maths, and log files.
213
+ function stripAnsi(s) {
214
+ return String(s).replace(ANSI, "");
215
+ }
216
+
217
+ function truncateVisible(s, max) {
218
+ if (visibleLength(s) <= max) return s;
219
+ let out = "";
220
+ let n = 0;
221
+ for (let i = 0; i < s.length; i += 1) {
222
+ if (s[i] === "\u001b") {
223
+ const end = s.indexOf("m", i);
224
+ if (end === -1) break;
225
+ out += s.slice(i, end + 1);
226
+ i = end;
227
+ continue;
228
+ }
229
+ if (n >= max) break;
230
+ out += s[i];
231
+ n += 1;
232
+ }
233
+ // Reset attributes so a truncated colour never bleeds into the border.
234
+ return out.includes("\u001b[") ? `${out}\u001b[0m` : out;
235
+ }
236
+
237
+ function padVisible(s, width) {
238
+ const len = visibleLength(s);
239
+ return len >= width ? truncateVisible(s, width) : s + " ".repeat(width - len);
240
+ }
241
+
242
+ const write = (s) => process.stdout.write(s);
243
+ const errWrite = (s) => process.stderr.write(s);
244
+
245
+ // ---------------------------------------------------------------- lines
246
+
247
+ function rule(w = width()) {
248
+ return c.border(GLYPH.rule.repeat(Math.max(8, w)));
249
+ }
250
+
251
+ function box({ title = "", lines = [], w = width(), tone = "primary" }) {
252
+ const paint = c[tone] || c.primary;
253
+ const inner = w - 4;
254
+ const head = title ? ` ${c.bold(title)} ` : "";
255
+ const top = paint(GLYPH.tl + GLYPH.h) + head + paint(GLYPH.h.repeat(Math.max(0, w - 3 - visibleLength(head))) + GLYPH.tr);
256
+ // Entries may contain newlines (a pre-rendered bullet list, for instance);
257
+ // flatten first so every physical line gets its own borders.
258
+ const flat = lines.flatMap((line) => String(line).split("\n"));
259
+ const body = flat.map((line) => `${paint(GLYPH.v)} ${padVisible(line, inner)} ${paint(GLYPH.v)}`);
260
+ const bottom = paint(GLYPH.bl + GLYPH.h.repeat(w - 2) + GLYPH.br);
261
+ return [top, ...body, bottom].join("\n");
262
+ }
263
+
264
+ // Chip-style inline label, e.g. `offensive` or `tesla.com`.
265
+ function chip(text, tone = "muted") {
266
+ return (c[tone] || c.muted)(text);
267
+ }
268
+
269
+ function bullets(rows, { marker = GLYPH.dot } = {}) {
270
+ return rows.map((r) => ` ${c.muted(marker)} ${r}`).join("\n");
271
+ }
272
+
273
+ // ---------------------------------------------------------------- status
274
+
275
+ function status(text) {
276
+ errWrite(`${c.primary("bolt")} ${c.muted(GLYPH.dot)} ${text}\n`);
277
+ }
278
+
279
+ function ok(text) {
280
+ errWrite(`${c.success(GLYPH.tick)} ${text}\n`);
281
+ }
282
+
283
+ function warn(text) {
284
+ errWrite(`${c.warning("!")} ${text}\n`);
285
+ }
286
+
287
+ function err(text) {
288
+ errWrite(`${c.error(GLYPH.cross)} ${text}\n`);
289
+ }
290
+
291
+ function info(text) {
292
+ errWrite(`${c.info(GLYPH.dot)} ${text}\n`);
293
+ }
294
+
295
+ // ---------------------------------------------------------------- streaming
296
+
297
+ // The server appends a task-matched output contract made of ALL-CAPS labels
298
+ // (FINDINGS, EVIDENCE, LOCATION, NEXT, NOTES ...). Highlighting just the label
299
+ // makes a wall of prose scannable without touching the author's text. To stay
300
+ // away from prose we require either a trailing colon or a line that is *only*
301
+ // the label, so "FIRST, we tried" is left alone.
302
+ const LABEL_COLON = /^(\s*)([A-Z][A-Z0-9_]{1,23}):(.*)$/;
303
+ const LABEL_BARE = /^(\s*)([A-Z][A-Z0-9_]{1,23})$/;
304
+
305
+ function stylizeFence(line) {
306
+ const m = String(line).match(/^(\s*)(```|~~~)\s*([A-Za-z0-9+#_-]*)\s*$/);
307
+ if (!m) return c.muted(line);
308
+ const indent = m[1] || "";
309
+ const fence = m[2];
310
+ const lang = (m[3] || "").toLowerCase();
311
+ if (!lang) return `${indent}${c.muted(`${fence}`)}`;
312
+ return `${indent}${c.muted(fence)}${c.primary(c.bold(lang))}`;
313
+ }
314
+
315
+ // Inline markdown for prose: **bold** and `code`. Code spans are lifted out
316
+ // first so asterisks inside them never parse as emphasis. NUL placeholders
317
+ // are safe here: streamed prose never contains them, and every placeholder is
318
+ // restored before return.
319
+ function stylizeInline(text) {
320
+ const spans = [];
321
+ const lifted = String(text).replace(/`([^`\n]+)`/g, (m, code) => {
322
+ spans.push(code);
323
+ return `\u0000${spans.length - 1}\u0000`;
324
+ });
325
+ const bolded = lifted.replace(/\*\*([^*]+)\*\*/g, (m, b) => c.bold(b));
326
+ // eslint-disable-next-line no-control-regex -- restores the placeholders above; indices always valid.
327
+ return bolded.replace(/\u0000(\d+)\u0000/g, (m, i) => c.accent(spans[Number(i)] ?? ""));
328
+ }
329
+
330
+ function stylizeLine(line) {
331
+ if (/^\s*(```|~~~)/.test(line)) return stylizeFence(line);
332
+ const colon = line.match(LABEL_COLON);
333
+ if (colon) return `${colon[1]}${c.primary(c.bold(colon[2]))}${c.muted(":")}${stylizeInline(colon[3])}`;
334
+ const bare = line.match(LABEL_BARE);
335
+ if (bare) return `${bare[1]}${c.primary(c.bold(bare[2]))}`;
336
+ if (/^\s*[-=*_]{3,}\s*$/.test(line)) return c.border(line);
337
+ // Markdown headings render without the hashes, bold in the brand colour.
338
+ const head = line.match(/^(\s{0,3})(#{1,6})\s+(.*)$/);
339
+ if (head) return `${head[1]}${c.primary(c.bold(stylizeInline(head[3])))}`;
340
+ // Block quotes keep a muted bar; the body styles like normal prose.
341
+ const quote = line.match(/^(\s{0,3})>\s?(.*)$/);
342
+ if (quote) return `${quote[1]}${c.muted(`${GLYPH.bar} `)}${stylizeInline(quote[2])}`;
343
+ // Unordered lists normalize their marker to the muted dot.
344
+ const bullet = line.match(/^(\s*)[-*\u2022]\s+(.*)$/);
345
+ if (bullet) return `${bullet[1]}${c.muted(GLYPH.dot)} ${stylizeInline(bullet[2])}`;
346
+ // Ordered lists dim the number so the content leads.
347
+ const ordered = line.match(/^(\s*)(\d{1,3}[.)])\s+(.*)$/);
348
+ if (ordered) return `${ordered[1]}${c.muted(ordered[2])} ${stylizeInline(ordered[3])}`;
349
+ return stylizeInline(line);
350
+ }
351
+
352
+ // Line-buffered styler. SSE chunks land mid-line (and mid-word), so writing
353
+ // chunks straight through would both flicker and risk splitting an escape
354
+ // sequence across two writes. We hold back the trailing partial line and emit
355
+ // whole lines only; `end()` flushes the remainder. Fence-aware: lines inside
356
+ // ``` blocks pass through untouched so ALL-CAPS code never gets label
357
+ // highlighting and indentation is preserved.
358
+ function createStream(sink = write) {
359
+ let buffer = "";
360
+ let lines = 0;
361
+ let inCode = false;
362
+ const emit = (part) => {
363
+ if (/^\s*(```|~~~)/.test(part)) {
364
+ sink(`${stylizeFence(part)}\n`);
365
+ inCode = !inCode;
366
+ lines += 1;
367
+ return;
368
+ }
369
+ if (inCode) {
370
+ sink(`${part}\n`);
371
+ lines += 1;
372
+ return;
373
+ }
374
+ sink(`${stylizeLine(part)}\n`);
375
+ lines += 1;
376
+ };
377
+ return {
378
+ write(text) {
379
+ if (!text) return;
380
+ buffer += text;
381
+ const parts = buffer.split("\n");
382
+ buffer = parts.pop() || "";
383
+ for (const part of parts) emit(part);
384
+ },
385
+ end() {
386
+ if (buffer) {
387
+ emit(buffer);
388
+ buffer = "";
389
+ }
390
+ return lines;
391
+ },
392
+ get lines() {
393
+ return lines;
394
+ },
395
+ get inCode() {
396
+ return inCode;
397
+ },
398
+ };
399
+ }
400
+
401
+ // ---------------------------------------------------------------- spinner
402
+
403
+ const SPIN_FRAMES = U ? ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] : ["|", "/", "-", "\\"];
404
+
405
+ // Writes in place on one line. Only runs on a TTY; elsewhere it reports timing
406
+ // through its result so callers can still show a footer.
407
+ function createSpinner(text = "thinking") {
408
+ const live = isTTY() && c.enabled;
409
+ let timer = null;
410
+ let frame = 0;
411
+ let started = 0;
412
+
413
+ function paint(label) {
414
+ const spin = SPIN_FRAMES[frame % SPIN_FRAMES.length];
415
+ frame += 1;
416
+ return `\r\u001b[2K${c.primary(spin)} ${c.muted(label)} ${c.border(`${((Date.now() - started) / 1000).toFixed(1)}s`)}`;
417
+ }
418
+
419
+ return {
420
+ get live() {
421
+ return live;
422
+ },
423
+ start(msg) {
424
+ started = Date.now();
425
+ if (!live) return;
426
+ write(paint(msg || text));
427
+ timer = setInterval(() => write(paint(msg || text)), 90);
428
+ if (timer.unref) timer.unref();
429
+ },
430
+ setMessage(msg) {
431
+ if (!live) return;
432
+ text = msg;
433
+ write(paint(msg));
434
+ },
435
+ stop(msg) {
436
+ if (timer) clearInterval(timer);
437
+ timer = null;
438
+ if (!live) return;
439
+ write(msg ? `\r\u001b[2K${msg}\n` : `\r\u001b[2K`);
440
+ },
441
+ elapsed() {
442
+ return Date.now() - started;
443
+ },
444
+ };
445
+ }
446
+
447
+ // ---------------------------------------------------------------- palette
448
+
449
+ // Whether the interactive picker can run at all. Callers must check this
450
+ // first: without a TTY there are no arrow keys, so they should fall back to
451
+ // printing a plain list rather than awaiting a picker that cannot appear.
452
+ function selectable(items) {
453
+ return isTTY() && items.length > 0 && typeof process.stdin.setRawMode === "function";
454
+ }
455
+
456
+ // Scroll window for a picker whose rows outnumber `max`: the selected row
457
+ // stays visible by sliding the viewport, opencode-menu style. Pure, tested:
458
+ // returns the [start, end) slice bounds to display. When everything fits the
459
+ // whole list shows; a non-positive max degrades to the whole list too.
460
+ function pickWindow(index, total, max) {
461
+ const i = Number.isFinite(index) ? Math.max(0, Math.floor(index)) : 0;
462
+ const n = Number.isFinite(total) ? Math.max(0, Math.floor(total)) : 0;
463
+ const m = Number.isFinite(max) ? Math.floor(max) : 0;
464
+ if (m <= 0 || n <= m) return { start: 0, end: n };
465
+ const start = Math.min(Math.max(0, i - Math.floor((m - 1) / 2)), n - m);
466
+ return { start, end: start + m };
467
+ }
468
+
469
+ // The keybind footer under a picker: keys in the accent colour, verbs muted,
470
+ // so the eye lands on what to press. Degrades to plain text off-unicode.
471
+ function keyHints(pairs) {
472
+ return pairs.map(([key, verb]) => `${c.primary(key)} ${c.muted(verb)}`).join(` ${c.muted(GLYPH.dot)} `);
473
+ }
474
+
475
+ // Full-screen-ish command picker. Rendered as a block under the prompt that we
476
+ // redraw in place; the caller owns stdin for the duration via raw mode.
477
+ function select({ title = "", items = [], max = 12 }) {
478
+ if (!selectable(items)) return Promise.resolve(-1);
479
+ const input = process.stdin;
480
+ const hadRaw = Boolean(input.isRaw);
481
+
482
+ return new Promise((resolve) => {
483
+ let index = 0;
484
+ let drawn = 0;
485
+ let done = false;
486
+
487
+ const build = () => {
488
+ const out = [];
489
+ if (title) out.push(` ${c.accent(GLYPH.arrow)} ${c.bold(title)}`);
490
+ const { start, end } = pickWindow(index, items.length, max);
491
+ items.slice(start, end).forEach((item, i) => {
492
+ const at = start + i;
493
+ const on = at === index;
494
+ const mark = on ? c.primary(GLYPH.sel) : " ";
495
+ const label = on ? c.primary(c.bold(item.label)) : item.label;
496
+ const hint = item.hint ? ` ${c.muted(item.hint)}` : "";
497
+ out.push(` ${mark} ${label}${hint}`);
498
+ });
499
+ if (items.length > max) out.push(` ${c.muted(`${index + 1}/${items.length}`)}`);
500
+ out.push(` ${keyHints([["up/down", "move"], ["enter", "select"], ["esc", "cancel"]])}`);
501
+ return out;
502
+ };
503
+
504
+ const draw = () => {
505
+ if (drawn) write(`\u001b[${drawn}F`);
506
+ const body = build();
507
+ for (const line of body) write(`\u001b[2K\r${line}\n`);
508
+ for (let i = body.length; i < drawn; i += 1) write("\u001b[2K\n");
509
+ if (body.length < drawn) write(`\u001b[${drawn - body.length}A`);
510
+ drawn = body.length;
511
+ };
512
+
513
+ const clear = () => {
514
+ if (drawn) write(`\u001b[${drawn}F`);
515
+ for (let i = 0; i < drawn; i += 1) write("\u001b[2K\n");
516
+ if (drawn) write(`\u001b[${drawn}A`);
517
+ drawn = 0;
518
+ };
519
+
520
+ const onData = (chunk) => {
521
+ const s = chunk.toString("utf8");
522
+ if (s === "\u001b[A") {
523
+ index = (index - 1 + items.length) % items.length;
524
+ draw();
525
+ return;
526
+ }
527
+ if (s === "\u001b[B") {
528
+ index = (index + 1) % items.length;
529
+ draw();
530
+ return;
531
+ }
532
+ if (s === "\r" || s === "\n") return finish(index);
533
+ if (s === "\u001b" || s === "\u0003" || s === "\u0004") return finish(-1);
534
+ };
535
+
536
+ function finish(choice) {
537
+ if (done) return;
538
+ done = true;
539
+ input.removeListener("data", onData);
540
+ clear();
541
+ if (!hadRaw && input.setRawMode) input.setRawMode(false);
542
+ input.pause();
543
+ resolve(choice);
544
+ }
545
+
546
+ input.setRawMode(true);
547
+ input.resume();
548
+ input.on("data", onData);
549
+ draw();
550
+ });
551
+ }
552
+
553
+ // Live filter-as-you-type palette. Starts with `initialFilter` (the text
554
+ // after the slash so far) and lets the operator keep typing to narrow the
555
+ // list: printable keys append to the filter, backspace removes one, up/down
556
+ // moves (the viewport scrolls to keep the selection visible), enter picks,
557
+ // tab fills the highlighted row into the prompt and leaves, esc cancels.
558
+ // Resolves {index, item, filter, tabFill} where index is into the original
559
+ // `items` array (-1 on cancel). `filterFn` maps a filter string to the
560
+ // visible subset; by default it matches label+hint.
561
+ function selectLive({ title = "", items = [], max = 12, initialFilter = "", filterFn = null }) {
562
+ const base = Array.isArray(items) ? items : [];
563
+ const match = typeof filterFn === "function"
564
+ ? filterFn
565
+ : (q) => {
566
+ const needle = String(q || "").toLowerCase();
567
+ if (!needle) return base;
568
+ return base.filter((it) => `${it.label || ""} ${it.hint || ""}`.toLowerCase().includes(needle));
569
+ };
570
+ if (!selectable(base)) return Promise.resolve({ index: -1, item: null, filter: String(initialFilter || ""), tabFill: false });
571
+ const input = process.stdin;
572
+ const hadRaw = Boolean(input.isRaw);
573
+
574
+ return new Promise((resolve) => {
575
+ let filter = String(initialFilter || "");
576
+ let visible = match(filter);
577
+ let index = 0;
578
+ let drawn = 0;
579
+ let done = false;
580
+
581
+ const build = () => {
582
+ const out = [];
583
+ const count = filter || visible.length !== base.length ? ` ${c.muted(`${visible.length}/${base.length}`)}` : "";
584
+ const head = title
585
+ ? ` ${c.accent(GLYPH.arrow)} ${c.bold(title)} ${c.muted(`/${filter}`)}${count}`
586
+ : ` ${c.muted(`/${filter}`)}${count}`;
587
+ out.push(head);
588
+ const { start, end } = pickWindow(index, visible.length, max);
589
+ visible.slice(start, end).forEach((item, i) => {
590
+ const at = start + i;
591
+ const on = at === index;
592
+ const mark = on ? c.primary(GLYPH.sel) : " ";
593
+ const label = on ? c.primary(c.bold(item.label)) : item.label;
594
+ const hint = item.hint ? ` ${c.muted(item.hint)}` : "";
595
+ out.push(` ${mark} ${label}${hint}`);
596
+ });
597
+ if (!visible.length) out.push(` ${c.muted(`no match - keep typing or esc to cancel`)}`);
598
+ out.push(` ${keyHints([["type", "filter"], ["up/down", "move"], ["enter", "run"], ["tab", "fill"], ["esc", "cancel"]])}`);
599
+ return out;
600
+ };
601
+
602
+ const draw = () => {
603
+ if (drawn) write(`\u001b[${drawn}F`);
604
+ const body = build();
605
+ for (const line of body) write(`\u001b[2K\r${line}\n`);
606
+ for (let i = body.length; i < drawn; i += 1) write("\u001b[2K\n");
607
+ if (body.length < drawn) write(`\u001b[${drawn - body.length}A`);
608
+ drawn = body.length;
609
+ };
610
+
611
+ const clear = () => {
612
+ if (drawn) write(`\u001b[${drawn}F`);
613
+ for (let i = 0; i < drawn; i += 1) write("\u001b[2K\n");
614
+ if (drawn) write(`\u001b[${drawn}A`);
615
+ drawn = 0;
616
+ };
617
+
618
+ const refilter = () => {
619
+ visible = match(filter);
620
+ if (index >= visible.length) index = 0;
621
+ if (!visible.length) index = 0;
622
+ };
623
+
624
+ const onData = (chunk) => {
625
+ const s = chunk.toString("utf8");
626
+ if (s === "\u001b[A") {
627
+ if (visible.length) index = (index - 1 + visible.length) % visible.length;
628
+ draw();
629
+ return;
630
+ }
631
+ if (s === "\u001b[B") {
632
+ if (visible.length) index = (index + 1) % visible.length;
633
+ draw();
634
+ return;
635
+ }
636
+ if (s === "\r" || s === "\n") {
637
+ const item = visible[index] || null;
638
+ const original = item ? base.indexOf(item) : -1;
639
+ return finish(original, item, false);
640
+ }
641
+ // Tab fills the highlighted row into the prompt and leaves the picker
642
+ // up, so a command that takes arguments keeps the operator typing.
643
+ if (s === "\t") {
644
+ const item = visible[index] || null;
645
+ if (!item) return;
646
+ const original = base.indexOf(item);
647
+ return finish(original, item, true);
648
+ }
649
+ if (s === "\u001b" || s === "\u0003" || s === "\u0004") return finish(-1, null, false);
650
+ if (s === "\u007f" || s === "\b" || s === "\u0008") {
651
+ filter = filter.slice(0, -1);
652
+ index = 0;
653
+ refilter();
654
+ draw();
655
+ return;
656
+ }
657
+ // Ctrl-U clears the filter.
658
+ if (s === "\u0015") {
659
+ filter = "";
660
+ index = 0;
661
+ refilter();
662
+ draw();
663
+ return;
664
+ }
665
+ // Printable input refines the filter. Multi-char pastes apply char by char.
666
+ let changed = false;
667
+ for (const ch of s) {
668
+ if (ch === "\r" || ch === "\n" || ch === "\t") continue;
669
+ if (ch < " " || ch === "\u007f") continue;
670
+ filter += ch;
671
+ changed = true;
672
+ }
673
+ if (changed) {
674
+ index = 0;
675
+ refilter();
676
+ draw();
677
+ }
678
+ };
679
+
680
+ function finish(original, item, tabFill) {
681
+ if (done) return;
682
+ done = true;
683
+ input.removeListener("data", onData);
684
+ clear();
685
+ if (!hadRaw && input.setRawMode) input.setRawMode(false);
686
+ input.pause();
687
+ resolve({ index: original, item, filter, tabFill: Boolean(tabFill) });
688
+ }
689
+
690
+ input.setRawMode(true);
691
+ input.resume();
692
+ input.on("data", onData);
693
+ refilter();
694
+ draw();
695
+ });
696
+ }
697
+
698
+ // ---------------------------------------------------------------- approvals
699
+
700
+ // Permission options for a tool approval, Claude Code / opencode style.
701
+ // Elevated commands (sudo, system installs) get the shield treatment and no
702
+ // silent path; installers only offer once/deny (never always).
703
+ function permissionItems({ elevated = false, install = false } = {}) {
704
+ if (install) {
705
+ return [
706
+ { label: "Allow once", hint: "run this install now", value: "allow" },
707
+ { label: "Deny", hint: "skip this install", value: "deny" },
708
+ ];
709
+ }
710
+ if (elevated) {
711
+ return [
712
+ { label: "Allow once", hint: "run with elevated privileges this time", value: "allow" },
713
+ { label: "Always allow", hint: "remember for this command", value: "always" },
714
+ { label: "Deny", hint: "skip this command", value: "deny" },
715
+ ];
716
+ }
717
+ return [
718
+ { label: "Allow once", hint: "run this time", value: "allow" },
719
+ { label: "Always allow", hint: "remember, do not ask again", value: "always" },
720
+ { label: "Deny", hint: "skip", value: "deny" },
721
+ ];
722
+ }
723
+
724
+ // Arrow-key permission picker. Resolves "allow" | "always" | "deny".
725
+ // Falls back to -1 (deny) when no TTY is available.
726
+ async function selectPermission({ title = "approve", items = null } = {}) {
727
+ const rows = Array.isArray(items) && items.length ? items : permissionItems();
728
+ const picked = await select({ title, items: rows.map((r) => ({ label: r.label, hint: r.hint })) });
729
+ if (picked < 0) return "deny";
730
+ return (rows[picked] && rows[picked].value) || "deny";
731
+ }
732
+
733
+ // Question picker for `ask` tool calls: the model asks, the operator picks
734
+ // from a dropdown (Claude Code style). Resolves the chosen option string, or
735
+ // "" on cancel. Non-TTY resolves "" so the loop can fall back gracefully.
736
+ async function selectAnswer({ question = "", options = [] } = {}) {
737
+ const rows = (Array.isArray(options) ? options : []).map((o) => ({ label: String(o) }));
738
+ if (!rows.length) return "";
739
+ const picked = await select({ title: question.slice(0, 80) || "choose", items: rows });
740
+ if (picked < 0) return "";
741
+ return String(options[picked] ?? "");
742
+ }
743
+
744
+ module.exports = {
745
+ ESC,
746
+ GLYPH,
747
+ LOGO,
748
+ PALETTE,
749
+ c,
750
+ enabled: c.enabled,
751
+ isTTY,
752
+ resolveDepth,
753
+ supportsUnicode,
754
+ selectable,
755
+ pickWindow,
756
+ unicode: U,
757
+ width,
758
+ relTime,
759
+ visibleLength,
760
+ stripAnsi,
761
+ padVisible,
762
+ write,
763
+ errWrite,
764
+ rule,
765
+ box,
766
+ chip,
767
+ bullets,
768
+ status,
769
+ ok,
770
+ warn,
771
+ err,
772
+ info,
773
+ createStream,
774
+ stylizeLine,
775
+ stylizeInline,
776
+ stylizeFence,
777
+ createSpinner,
778
+ select,
779
+ selectLive,
780
+ permissionItems,
781
+ selectPermission,
782
+ selectAnswer,
783
+ };