@carrieros/cli 0.2.0 → 0.3.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.
Files changed (97) hide show
  1. package/README.md +142 -57
  2. package/dist/commands/attach.js +45 -0
  3. package/dist/commands/btw.js +78 -0
  4. package/dist/commands/changes.js +167 -0
  5. package/dist/commands/chat.js +80 -14
  6. package/dist/commands/context.js +160 -0
  7. package/dist/commands/doctor.js +46 -1
  8. package/dist/commands/files.js +84 -23
  9. package/dist/commands/help.js +1 -0
  10. package/dist/commands/history.js +88 -23
  11. package/dist/commands/login.js +31 -7
  12. package/dist/commands/memory.js +162 -0
  13. package/dist/commands/mode-model.js +39 -3
  14. package/dist/commands/modes.js +4 -1
  15. package/dist/commands/project.js +106 -0
  16. package/dist/commands/repo.js +146 -0
  17. package/dist/commands/repos.js +61 -0
  18. package/dist/commands/review.js +92 -0
  19. package/dist/commands/search.js +92 -0
  20. package/dist/commands/sessions.js +219 -65
  21. package/dist/commands/settings.js +87 -0
  22. package/dist/commands/update.js +159 -0
  23. package/dist/commands/upload.js +204 -31
  24. package/dist/commands/usage.js +212 -16
  25. package/dist/ide/editor-context.js +172 -0
  26. package/dist/ide/ide-session.js +94 -0
  27. package/dist/ide/tool-host.js +109 -0
  28. package/dist/main.js +26 -1
  29. package/dist/services/api.js +140 -6
  30. package/dist/services/chat-stream.js +145 -0
  31. package/dist/services/checkpoints.js +116 -0
  32. package/dist/services/client-tools.js +260 -0
  33. package/dist/services/command-coordinator.js +200 -0
  34. package/dist/services/command-policy.js +404 -0
  35. package/dist/services/config.js +247 -22
  36. package/dist/services/context.js +265 -20
  37. package/dist/services/device-auth.js +42 -30
  38. package/dist/services/diff.js +196 -0
  39. package/dist/services/env-policy.js +108 -0
  40. package/dist/services/file-detect.js +104 -0
  41. package/dist/services/file-resolver.js +199 -0
  42. package/dist/services/file-upload.js +126 -0
  43. package/dist/services/git-tools.js +248 -0
  44. package/dist/services/glob-match.js +164 -0
  45. package/dist/services/helper-bin.js +64 -0
  46. package/dist/services/ignore-rules.js +189 -0
  47. package/dist/services/job-helper.js +307 -0
  48. package/dist/services/local-files.js +517 -0
  49. package/dist/services/local-tools.js +432 -0
  50. package/dist/services/login-flow.js +15 -8
  51. package/dist/services/meta.js +3 -1
  52. package/dist/services/mutation-coordinator.js +161 -0
  53. package/dist/services/mutations.js +493 -0
  54. package/dist/services/open-url.js +68 -0
  55. package/dist/services/output.js +5 -2
  56. package/dist/services/packaged.js +24 -0
  57. package/dist/services/process-runner.js +406 -0
  58. package/dist/services/project-context.js +298 -0
  59. package/dist/services/redaction.js +201 -0
  60. package/dist/services/secure-store.js +197 -0
  61. package/dist/services/session-resolver.js +108 -0
  62. package/dist/services/sia.js +51 -0
  63. package/dist/services/update.js +286 -0
  64. package/dist/services/workspace-registry.js +309 -0
  65. package/dist/services/workspace.js +573 -0
  66. package/dist/shell/shell-chat.js +1028 -57
  67. package/dist/shell/shell-commands.js +200 -11
  68. package/dist/shell/shell-prompt.js +81 -8
  69. package/dist/shell/shell-renderer.js +7 -19
  70. package/dist/shell/shell-router.js +19 -3
  71. package/dist/shell/shell.js +185 -17
  72. package/dist/types/index.js +3 -1
  73. package/dist/ui/approval.js +81 -0
  74. package/dist/ui/banner.js +39 -0
  75. package/dist/ui/btw-overlay.js +230 -0
  76. package/dist/ui/change-review.js +87 -0
  77. package/dist/ui/chat-renderer.js +206 -13
  78. package/dist/ui/colors.js +4 -0
  79. package/dist/ui/command-filter.js +26 -5
  80. package/dist/ui/command-palette.js +17 -4
  81. package/dist/ui/command-registry.js +84 -9
  82. package/dist/ui/command-review.js +138 -0
  83. package/dist/ui/composer-layout.js +41 -0
  84. package/dist/ui/conversation.js +398 -0
  85. package/dist/ui/interrupt.js +35 -0
  86. package/dist/ui/live.js +3 -1
  87. package/dist/ui/markdown.js +63 -9
  88. package/dist/ui/message.js +14 -31
  89. package/dist/ui/screen-prompt.js +181 -0
  90. package/dist/ui/screen.js +1 -1
  91. package/dist/ui/select.js +185 -29
  92. package/dist/ui/sia-qa.js +213 -0
  93. package/dist/ui/text-prompt.js +74 -0
  94. package/dist/ui/trust.js +93 -0
  95. package/dist/ui/ui.js +4 -1
  96. package/package.json +13 -2
  97. package/dist/ui/activity.js +0 -77
@@ -1,15 +1,18 @@
1
1
  import chalk from "chalk";
2
2
  import { c } from "./colors.js";
3
3
  import { renderCodeBlock } from "./code-block.js";
4
- import { textWidth } from "./composer-layout.js";
4
+ import { clampAnsi, contentWidth, MARGIN, textWidth } from "./composer-layout.js";
5
5
  /**
6
6
  * Self-contained Markdown → ANSI renderer (no dependency). Supports headings,
7
7
  * bold/italic, inline code, links, bullet/numbered/task lists, blockquotes,
8
8
  * horizontal rules, tables and fenced code blocks — with soft word-wrap so long
9
9
  * paragraphs never overflow or cut words. Returns col-0 lines; callers indent.
10
10
  */
11
- export function renderMarkdown(md) {
12
- const wrap = Math.max(20, textWidth() - 4);
11
+ export function renderMarkdown(md, maxWidth) {
12
+ // `maxWidth` lets a caller render into something narrower than the transcript
13
+ // — the /btw box, which spends 4 columns on its own borders. Without it the
14
+ // body would wrap to the full width and overflow the frame it sits in.
15
+ const wrap = Math.max(20, (maxWidth ?? textWidth()) - 4);
13
16
  const out = [];
14
17
  const lines = md.replace(/\r/g, "").split("\n");
15
18
  let i = 0;
@@ -44,10 +47,12 @@ export function renderMarkdown(md) {
44
47
  i++;
45
48
  continue;
46
49
  }
47
- // Heading.
50
+ // Heading — wrapped like body text; a long one would otherwise overflow.
48
51
  const h = raw.match(/^(#{1,6})\s+(.*)$/);
49
52
  if (h) {
50
- out.push(h[1].length === 1 ? c.brand(inline(h[2])) : c.title(inline(h[2])));
53
+ const paint = h[1].length === 1 ? c.brand : c.title;
54
+ for (const w of wrapText(h[2], wrap))
55
+ out.push(paint(inline(w)));
51
56
  i++;
52
57
  continue;
53
58
  }
@@ -102,9 +107,24 @@ export function renderMarkdown(md) {
102
107
  out.push(inline(w));
103
108
  i++;
104
109
  }
105
- return out;
110
+ // Backstop. Code blocks and tables size themselves from their content, and a
111
+ // future block type could forget to wrap entirely — any of which would emit a
112
+ // line wider than the terminal and corrupt the pinned composer. Callers indent
113
+ // by MARGIN, so leave room for it.
114
+ const limit = Math.max(20, contentWidth() - MARGIN.length);
115
+ return out.map((l) => clampAnsi(l, limit));
106
116
  }
107
- /** Word-wrap plain text to `width`, never cutting a word. */
117
+ /**
118
+ * Word-wrap plain text to `width`, never cutting a word — EXCEPT a word that
119
+ * cannot fit on a line of its own.
120
+ *
121
+ * A 250-character URL, hash or base64 blob has no break point, so pure
122
+ * word-wrapping emits it as one over-wide line. The terminal then wraps it into
123
+ * several physical rows while the screen engine still counts one, and the
124
+ * pinned composer below gets overwritten. Splitting such a token across lines
125
+ * keeps every character (nothing is lost, unlike clipping) while holding the
126
+ * one-line-per-row invariant everything else depends on.
127
+ */
108
128
  function wrapText(text, width) {
109
129
  const w = Math.max(20, width);
110
130
  const words = text.trim().split(/\s+/).filter(Boolean);
@@ -113,7 +133,18 @@ function wrapText(text, width) {
113
133
  const lines = [];
114
134
  let cur = "";
115
135
  for (const word of words) {
116
- if (cur && [...cur].length + 1 + [...word].length > w) {
136
+ const len = [...word].length;
137
+ if (len > w) {
138
+ if (cur) {
139
+ lines.push(cur);
140
+ cur = "";
141
+ }
142
+ const chars = [...word];
143
+ for (let i = 0; i < chars.length; i += w)
144
+ lines.push(chars.slice(i, i + w).join(""));
145
+ continue;
146
+ }
147
+ if (cur && [...cur].length + 1 + len > w) {
117
148
  lines.push(cur);
118
149
  cur = word;
119
150
  }
@@ -125,12 +156,35 @@ function wrapText(text, width) {
125
156
  lines.push(cur);
126
157
  return lines;
127
158
  }
159
+ /**
160
+ * A code-review severity, coloured by weight. A review's findings arrive as
161
+ * bold headers like `**High — \`src/x.js:12\`**`; recognising the leading
162
+ * severity word lets the terminal show it as a subtle marker (red for the
163
+ * serious ones, dim for the quiet ones) instead of undifferentiated bold. It is
164
+ * deliberately narrow — only a bold segment that STARTS with one of these five
165
+ * words is touched, so ordinary bold text is unaffected.
166
+ */
167
+ const SEVERITY_COLOR = {
168
+ critical: c.err,
169
+ high: c.err,
170
+ medium: c.warn,
171
+ low: c.dim,
172
+ info: c.accent
173
+ };
174
+ function styleBold(b) {
175
+ const m = b.match(/^(critical|high|medium|low|info)\b(.*)$/i);
176
+ if (m) {
177
+ const paint = SEVERITY_COLOR[m[1].toLowerCase()];
178
+ return chalk.bold(paint(m[1].toUpperCase())) + chalk.bold(m[2]);
179
+ }
180
+ return chalk.bold(b);
181
+ }
128
182
  /** Inline spans: links, `code`, **bold**, *italic*, ~~strike~~. */
129
183
  function inline(text) {
130
184
  return text
131
185
  .replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label) => c.accent(label))
132
186
  .replace(/`([^`]+)`/g, (_m, code) => c.accent(code))
133
- .replace(/\*\*([^*]+)\*\*/g, (_m, b) => chalk.bold(b))
187
+ .replace(/\*\*([^*]+)\*\*/g, (_m, b) => styleBold(b))
134
188
  .replace(/~~([^~]+)~~/g, (_m, s) => chalk.strikethrough(s))
135
189
  .replace(/(^|[^*])\*([^*]+)\*/g, (_m, pre, it) => `${pre}${chalk.italic(it)}`);
136
190
  }
@@ -1,38 +1,21 @@
1
- import chalk from "chalk";
2
1
  import { line } from "../services/output.js";
2
+ import { c } from "./colors.js";
3
3
  import { MARGIN, contentWidth } from "./composer-layout.js";
4
+ import { wrapText } from "./conversation.js";
4
5
  /**
5
- * Renders a user turn as a subtly-shaded bar led by a `❯` — the Claude-style
6
- * "your message" band. Fixed to the composer width (never full-terminal), so it
7
- * stays a stable UI block on resize. Long messages wrap within the bar.
6
+ * A user turn: the accent caret the composer uses, then the message.
7
+ *
8
+ * Deliberately light. This used to be a full-width shaded band, which made
9
+ * every question look like a UI panel and gave the eye something heavier than
10
+ * the answer below it. The caret alone is enough to say "you said this", and it
11
+ * matches what the composer shows while typing, so a sent message reads as the
12
+ * same thing it was a moment ago.
8
13
  */
9
- const BAR_BG = "#2b2b2e";
10
14
  export function renderUserMessage(text) {
11
- const w = contentWidth();
12
- const bar = chalk.bgHex(BAR_BG).white;
13
- for (const [i, l] of wrap(text, w - 3).entries()) {
14
- const content = (i === 0 ? "❯ " : " ") + l;
15
- line(MARGIN + bar(content.padEnd(w)));
15
+ const lines = wrapText(text.trim(), contentWidth() - 3);
16
+ line();
17
+ for (const [i, l] of lines.entries()) {
18
+ line(MARGIN + (i === 0 ? c.brandFixed("›") : " ") + " " + c.title(l));
16
19
  }
17
- line(); // single trailing blank — the next block leads straight in
18
- }
19
- function wrap(text, width) {
20
- const w = Math.max(20, width);
21
- const words = text.trim().split(/\s+/).filter(Boolean);
22
- if (!words.length)
23
- return [""];
24
- const lines = [];
25
- let cur = "";
26
- for (const word of words) {
27
- if (cur && [...cur].length + 1 + [...word].length > w) {
28
- lines.push(cur);
29
- cur = word;
30
- }
31
- else {
32
- cur = cur ? `${cur} ${word}` : word;
33
- }
34
- }
35
- if (cur)
36
- lines.push(cur);
37
- return lines;
20
+ line();
38
21
  }
@@ -0,0 +1,181 @@
1
+ import * as readline from "node:readline";
2
+ import { c } from "./colors.js";
3
+ import { screenActive, screenScrollPage, screenScrollToBottom, screenTransient } from "./screen.js";
4
+ import { selectFrame, SELECT_BACK } from "./select.js";
5
+ import { termWidth } from "./ui.js";
6
+ /**
7
+ * Prompts that render INSIDE the shell's transcript instead of taking the
8
+ * terminal over.
9
+ *
10
+ * The pickers in select.ts suspend the screen engine and paint on the raw
11
+ * terminal. That is correct for a one-off `cos model`, but inside the shell it
12
+ * swaps away the buffer holding the banner and the whole conversation — so
13
+ * while a picker is open there is nothing above it and nothing to scroll back
14
+ * to. These variants push their frame through `screenTransient`, so the
15
+ * transcript stays exactly where it was and the prompt appears beneath it, the
16
+ * way the thinking spinner already does.
17
+ *
18
+ * They only work while the screen engine is running; callers fall back to the
19
+ * select.ts versions when it isn't (`cos chat`, piped input).
20
+ */
21
+ /** True when these should be preferred over the terminal-owning pickers. */
22
+ export function inScreen() {
23
+ return screenActive() && process.stdin.isTTY === true;
24
+ }
25
+ /** Take over key handling for the duration of a prompt, then hand it back. */
26
+ export function captureKeys(onKey) {
27
+ const stdin = process.stdin;
28
+ // The composer is not reading between turns, but a stale listener from an
29
+ // earlier prompt would double-handle every keystroke.
30
+ const previous = stdin.listeners("keypress");
31
+ stdin.removeAllListeners("keypress");
32
+ readline.emitKeypressEvents(stdin);
33
+ const prevRaw = stdin.isRaw ?? false;
34
+ if (stdin.isTTY)
35
+ stdin.setRawMode(true);
36
+ stdin.resume();
37
+ stdin.on("keypress", onKey);
38
+ return () => {
39
+ stdin.removeListener("keypress", onKey);
40
+ if (stdin.isTTY)
41
+ stdin.setRawMode(prevRaw);
42
+ for (const l of previous)
43
+ stdin.on("keypress", l);
44
+ };
45
+ }
46
+ /** select.ts's picker, drawn into the transcript. Same keys, same result. */
47
+ export function pickInScreen(opts) {
48
+ const { choices } = opts;
49
+ // Only this variant can page the transcript, so only it advertises the keys.
50
+ const withScroll = { ...opts, scrollable: true };
51
+ return new Promise((resolve) => {
52
+ let selected = Math.min(Math.max(0, opts.initial ?? 0), choices.length - 1);
53
+ const paint = () => screenTransient(selectFrame(withScroll, selected));
54
+ const finish = (value) => {
55
+ release();
56
+ screenTransient([]); // the answer is echoed by the caller, not this frame
57
+ resolve(value);
58
+ };
59
+ const onKey = (str, key) => {
60
+ if (!key)
61
+ return;
62
+ if (key.name === "up" || (key.ctrl && key.name === "p")) {
63
+ selected = (selected - 1 + choices.length) % choices.length;
64
+ return paint();
65
+ }
66
+ if (key.name === "down" || (key.ctrl && key.name === "n")) {
67
+ selected = (selected + 1) % choices.length;
68
+ return paint();
69
+ }
70
+ // Look back over the conversation without losing your place. ↑↓ belong to
71
+ // the list, so paging gets its own keys.
72
+ //
73
+ // A mouse wheel can't be routed here: with the alternate buffer active,
74
+ // terminals translate wheel ticks into ↑↓ before the app sees them, so a
75
+ // scroll and a keypress are the same bytes. Separating them would mean
76
+ // enabling mouse tracking, which costs drag-to-select.
77
+ if (key.name === "pageup") {
78
+ screenScrollPage(-1);
79
+ return;
80
+ }
81
+ if (key.name === "pagedown") {
82
+ screenScrollPage(1);
83
+ return;
84
+ }
85
+ if (key.name === "end") {
86
+ screenScrollToBottom();
87
+ return;
88
+ }
89
+ if (opts.allowBack && key.name === "left")
90
+ return finish(SELECT_BACK);
91
+ if (key.name === "right" || key.name === "return" || key.name === "enter") {
92
+ return finish(choices[selected].value);
93
+ }
94
+ if (key.name === "escape" || (key.ctrl && (key.name === "c" || key.name === "d"))) {
95
+ return finish(null);
96
+ }
97
+ if (str && /^[1-9]$/.test(str)) {
98
+ const idx = Number(str) - 1;
99
+ if (idx < choices.length) {
100
+ selected = idx;
101
+ if (opts.confirmOnNumber)
102
+ return finish(choices[idx].value);
103
+ paint();
104
+ }
105
+ }
106
+ };
107
+ const release = captureKeys(onKey);
108
+ paint();
109
+ });
110
+ }
111
+ /** Word-wrap to `width` columns. */
112
+ function wrap(text, width) {
113
+ const w = Math.max(20, width);
114
+ const out = [];
115
+ let cur = "";
116
+ for (const word of text.trim().split(/\s+/).filter(Boolean)) {
117
+ if (cur && [...cur].length + 1 + [...word].length > w) {
118
+ out.push(cur);
119
+ cur = word;
120
+ }
121
+ else {
122
+ cur = cur ? `${cur} ${word}` : word;
123
+ }
124
+ }
125
+ if (cur)
126
+ out.push(cur);
127
+ return out.length ? out : [""];
128
+ }
129
+ /**
130
+ * A single-line text prompt drawn into the transcript.
131
+ *
132
+ * Line editing is deliberately minimal — type, backspace, Enter, Esc. readline
133
+ * can't be used here: it owns the terminal cursor, which is precisely what the
134
+ * screen engine is managing. Resolves the trimmed text, or null if empty or
135
+ * cancelled.
136
+ */
137
+ export function askTextInScreen(headerLines, placeholder) {
138
+ return new Promise((resolve) => {
139
+ let buffer = "";
140
+ const paint = () => {
141
+ const width = Math.min(termWidth() - 4, 92);
142
+ const shown = buffer
143
+ ? c.value(buffer)
144
+ : c.placeholder(placeholder ?? "Type your answer");
145
+ screenTransient([
146
+ ...headerLines(width),
147
+ "",
148
+ " " + c.brandFixed("❯ ") + shown + c.dim("▋"),
149
+ "",
150
+ " " + c.key("Enter") + c.dim(" confirm · ") + c.key("Esc") + c.dim(" cancel")
151
+ ]);
152
+ };
153
+ const finish = (value) => {
154
+ release();
155
+ screenTransient([]);
156
+ resolve(value);
157
+ };
158
+ const onKey = (str, key) => {
159
+ if (!key)
160
+ return;
161
+ if (key.name === "return" || key.name === "enter")
162
+ return finish(buffer.trim() || null);
163
+ if (key.name === "escape" || (key.ctrl && (key.name === "c" || key.name === "d"))) {
164
+ return finish(null);
165
+ }
166
+ if (key.name === "backspace") {
167
+ buffer = [...buffer].slice(0, -1).join("");
168
+ return paint();
169
+ }
170
+ // Printable input only — ignore control chords and navigation keys.
171
+ if (str && !key.ctrl && !key.meta && str >= " " && str !== "\x7f") {
172
+ buffer += str;
173
+ paint();
174
+ }
175
+ };
176
+ const release = captureKeys(onKey);
177
+ paint();
178
+ });
179
+ }
180
+ export { wrap as wrapForPrompt };
181
+ export { askApproval as approveInScreen } from "./approval.js";
package/dist/ui/screen.js CHANGED
@@ -107,7 +107,7 @@ function compose() {
107
107
  desired[i] = win[i] ?? "";
108
108
  // A subtle "more below" hint on the last transcript row when scrolled up.
109
109
  if (scrollOffset > 0 && contentH > 0) {
110
- desired[contentH - 1] = `${ESC}2m ↓ ${scrollOffset} more line${scrollOffset === 1 ? "" : "s"} — End to jump to latest${ESC}0m`;
110
+ desired[contentH - 1] = `${ESC}2m ↓ ${scrollOffset} more line${scrollOffset === 1 ? "" : "s"} - End to jump to latest${ESC}0m`;
111
111
  }
112
112
  for (let i = 0; i < pH; i++)
113
113
  desired[contentH + i] = palette[i] ?? "";
package/dist/ui/select.js CHANGED
@@ -2,8 +2,144 @@ import * as readline from "node:readline";
2
2
  import { c } from "./colors.js";
3
3
  import { resumeScreen, screenActive, suspendScreen } from "./screen.js";
4
4
  import { termWidth } from "./ui.js";
5
+ /** Resolved when the user pressed ← on a picker opened with `allowBack`. */
6
+ export const SELECT_BACK = "\u0000back";
7
+ /**
8
+ * One painted frame of the picker, clipped to the terminal.
9
+ *
10
+ * Split out because the same frame is drawn two ways: straight to the terminal
11
+ * (below), or into the shell's transcript via the screen engine — which is what
12
+ * keeps the banner and conversation on screen while a picker is open.
13
+ *
14
+ * Rows are hard-clipped rather than wrapped: callers count LOGICAL lines to
15
+ * rewind or size a region, so a row the terminal wraps would occupy two
16
+ * physical rows and leave half the previous frame behind.
17
+ */
18
+ export function selectFrame(opts, selected) {
19
+ const width = Math.min(termWidth() - 4, 92);
20
+ const build = (descriptionsFor) => {
21
+ const lines = headerLines(opts, width);
22
+ lines.push("");
23
+ lines.push(...optionLines(opts, selected, width, descriptionsFor));
24
+ lines.push("");
25
+ lines.push(...hintLines(opts, width));
26
+ return lines;
27
+ };
28
+ // Full descriptions cost 2-3 rows each, which on a short terminal would push
29
+ // the conversation off screen entirely — so fall back to describing only the
30
+ // highlighted option, which is still readable in full as you arrow through.
31
+ let lines = build("all");
32
+ if (opts.stacked && lines.length > roomForPrompt())
33
+ lines = build("selected");
34
+ const cols = termWidth();
35
+ return lines.map((l) => (visibleWidth(l) > cols ? clipAnsi(l, cols) : l));
36
+ }
37
+ /**
38
+ * Transcript rows a prompt may occupy — terminal height minus the 4-row
39
+ * composer, minus one so the frame never sits flush against it.
40
+ *
41
+ * Deliberately not reserving space for the conversation: the descriptions are
42
+ * the reason the prompt exists, and PgUp/PgDn can reach anything they cover.
43
+ */
44
+ function roomForPrompt() {
45
+ return Math.max(8, (process.stdout.rows ?? 24) - 5);
46
+ }
47
+ function headerLines(opts, width) {
48
+ if (opts.header)
49
+ return opts.header(width);
50
+ const lines = [" " + c.brand("─".repeat(width)), " " + c.brand.bold(opts.title)];
51
+ if (opts.description) {
52
+ for (const l of wrap(opts.description, width))
53
+ lines.push(" " + c.dim(l));
54
+ }
55
+ return lines;
56
+ }
57
+ /**
58
+ * The key legend, packed into as many lines as it needs.
59
+ *
60
+ * Wrapping rather than clipping: the last chip is what Esc does, and on this
61
+ * prompt that is "discard message" — the one hint you cannot afford to lose to
62
+ * a narrow terminal.
63
+ *
64
+ * ←→ rather than ⇄: it names both keys instead of half the pair, and it is the
65
+ * same arrow family as ↑↓ (U+2190/2192 beside U+2191/2193), so the two chips
66
+ * match in weight. ⇄ falls back to a different font in many terminals and
67
+ * rendered noticeably heavier than the arrows above it.
68
+ */
69
+ function hintLines(opts, width) {
70
+ const chips = [c.dim("↑↓ navigate")];
71
+ if (opts.allowBack)
72
+ chips.push(c.key("←→") + c.dim(` ${opts.backHint ?? "back"}`));
73
+ if (opts.scrollable)
74
+ chips.push(c.key("PgUp/PgDn") + c.dim(" scroll"));
75
+ chips.push(c.key("Enter") + c.dim(" confirm"));
76
+ chips.push(c.key("Esc") + c.dim(opts.cancelHint ? ` ${opts.cancelHint}` : " cancel"));
77
+ const SEP = " · ";
78
+ const lines = [];
79
+ let cur = "";
80
+ let curW = 0;
81
+ for (const chip of chips) {
82
+ const w = visibleWidth(chip);
83
+ if (cur && curW + SEP.length + w > width) {
84
+ lines.push(" " + cur);
85
+ cur = chip;
86
+ curW = w;
87
+ }
88
+ else {
89
+ cur = cur ? cur + c.dim(SEP) + chip : chip;
90
+ curW = curW ? curW + SEP.length + w : w;
91
+ }
92
+ }
93
+ if (cur)
94
+ lines.push(" " + cur);
95
+ return lines;
96
+ }
97
+ function optionLines(opts, selected, width, descriptionsFor) {
98
+ const { choices } = opts;
99
+ const numW = String(choices.length).length;
100
+ const lines = [];
101
+ if (!opts.stacked) {
102
+ // Column layout: label padded to a shared width, description clipped to fit.
103
+ const labelW = Math.min(30, Math.max(...choices.map((ch) => ch.label.length)));
104
+ const gutter = 2 + numW + 1 + 1 + labelW + 2;
105
+ choices.forEach((ch, i) => {
106
+ const on = i === selected;
107
+ const pointer = on ? c.brand("❯ ") : " ";
108
+ const num = c.dim(`${String(i + 1).padStart(numW)}.`);
109
+ const label = (on ? c.brand.bold : c.value)(ch.label.padEnd(labelW));
110
+ const mark = ch.current ? c.brand(" ✓") : "";
111
+ const room = width - gutter - (ch.current ? 2 : 0);
112
+ const desc = ch.description ? " " + c.dim(clip(ch.description, room)) : "";
113
+ lines.push(" " + pointer + num + " " + label + desc + mark);
114
+ });
115
+ return lines;
116
+ }
117
+ // Stacked layout: label on its own row, description wrapped beneath it and
118
+ // aligned under the label rather than the number.
119
+ const indent = " ".repeat(2 + 2 + numW + 1 + 1);
120
+ choices.forEach((ch, i) => {
121
+ const on = i === selected;
122
+ const pointer = on ? c.brand("❯ ") : " ";
123
+ const num = c.dim(`${String(i + 1).padStart(numW)}.`);
124
+ const label = (on ? c.brand.bold : c.value)(ch.label);
125
+ const mark = ch.current ? c.brand(" ✓") : "";
126
+ lines.push(" " + pointer + num + " " + label + mark);
127
+ const show = ch.description && (descriptionsFor === "all" || on);
128
+ if (show) {
129
+ // Two lines is the most a description needs; beyond that it is prose the
130
+ // list can't carry, and every extra row is one less of the conversation.
131
+ const wrapped = wrap(ch.description, width - indent.length + 2);
132
+ const shown = wrapped.slice(0, 2);
133
+ if (wrapped.length > 2)
134
+ shown[1] = shown[1].replace(/.{0,2}$/, "…");
135
+ for (const l of shown)
136
+ lines.push(indent + c.dim(l));
137
+ }
138
+ });
139
+ return lines;
140
+ }
5
141
  export function pickFromList(opts) {
6
- const { title, description = "", choices } = opts;
142
+ const { choices, confirmOnNumber = false } = opts;
7
143
  if (!process.stdin.isTTY || choices.length === 0) {
8
144
  return Promise.resolve(choices[opts.initial ?? 0]?.value ?? null);
9
145
  }
@@ -23,38 +159,14 @@ export function pickFromList(opts) {
23
159
  stdin.resume();
24
160
  let selected = Math.min(Math.max(0, opts.initial ?? 0), choices.length - 1);
25
161
  let prevUp = 0;
26
- const labelW = Math.min(30, Math.max(...choices.map((ch) => ch.label.length)));
27
- const numW = String(choices.length).length;
28
162
  const render = () => {
29
163
  if (prevUp > 0)
30
164
  readline.moveCursor(stdout, 0, -prevUp);
31
165
  readline.cursorTo(stdout, 0);
32
166
  readline.clearScreenDown(stdout);
33
- const width = Math.min(termWidth() - 4, 92);
34
- const lines = [" " + c.brand("─".repeat(width)), " " + c.brand.bold(title)];
35
- if (description) {
36
- for (const l of wrap(description, width))
37
- lines.push(" " + c.dim(l));
38
- }
39
- lines.push("");
40
- choices.forEach((ch, i) => {
41
- const on = i === selected;
42
- const pointer = on ? c.brand("❯ ") : " ";
43
- const num = c.dim(`${String(i + 1).padStart(numW)}.`);
44
- const label = (on ? c.brand.bold : c.value)(ch.label.padEnd(labelW));
45
- const desc = ch.description ? " " + c.dim(ch.description) : "";
46
- const mark = ch.current ? c.brand(" ✓") : "";
47
- lines.push(" " + pointer + num + " " + label + desc + mark);
48
- });
49
- lines.push("");
50
- lines.push(" " +
51
- c.dim("↑↓ navigate · ") +
52
- c.key("Enter") +
53
- c.dim(" confirm · ") +
54
- c.key("Esc") +
55
- c.dim(" cancel"));
56
- stdout.write(lines.join("\n"));
57
- prevUp = lines.length - 1; // cursor rests on the last line; rewind from there next time
167
+ const painted = selectFrame(opts, selected);
168
+ stdout.write(painted.join("\n"));
169
+ prevUp = painted.length - 1; // cursor rests on the last line; rewind from there next time
58
170
  };
59
171
  const finish = (val) => {
60
172
  if (prevUp > 0)
@@ -79,16 +191,25 @@ export function pickFromList(opts) {
79
191
  selected = (selected + 1) % choices.length;
80
192
  return render();
81
193
  }
194
+ // ← steps back a question, → confirms and moves on (same as Enter), so
195
+ // a multi-step flow reads as one horizontal track.
196
+ if (opts.allowBack && key.name === "left")
197
+ return finish(SELECT_BACK);
198
+ if (key.name === "right")
199
+ return finish(choices[selected].value);
82
200
  if (key.name === "return" || key.name === "enter")
83
201
  return finish(choices[selected].value);
84
202
  if (key.name === "escape" || (key.ctrl && (key.name === "c" || key.name === "d"))) {
85
203
  return finish(null);
86
204
  }
87
- // Number keys jump to an option.
205
+ // Number keys jump to an option — and confirm it directly when the
206
+ // caller asked for that (Yes/No style prompts).
88
207
  if (str && /^[1-9]$/.test(str)) {
89
208
  const idx = Number(str) - 1;
90
209
  if (idx < choices.length) {
91
210
  selected = idx;
211
+ if (confirmOnNumber)
212
+ return finish(choices[idx].value);
92
213
  render();
93
214
  }
94
215
  }
@@ -101,6 +222,41 @@ export function pickFromList(opts) {
101
222
  render();
102
223
  });
103
224
  }
225
+ const ANSI_RE = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;]*m/g;
226
+ /** Visible columns, ignoring colour codes. */
227
+ function visibleWidth(s) {
228
+ return [...s.replace(ANSI_RE, "")].length;
229
+ }
230
+ /** Truncate to `max` visible columns, keeping colour codes intact and closing
231
+ * any open run so the cut can't bleed into the next line. */
232
+ function clipAnsi(s, max) {
233
+ let out = "";
234
+ let seen = 0;
235
+ let i = 0;
236
+ while (i < s.length && seen < max) {
237
+ if (s[i] === "\x1b") {
238
+ ANSI_RE.lastIndex = i;
239
+ const m = ANSI_RE.exec(s);
240
+ if (m && m.index === i) {
241
+ out += m[0];
242
+ i += m[0].length;
243
+ continue;
244
+ }
245
+ }
246
+ out += s[i];
247
+ seen += 1;
248
+ i += 1;
249
+ }
250
+ return out + "\x1b[0m";
251
+ }
252
+ /** Trim to `max` columns, marking the cut with an ellipsis. Returns "" when
253
+ * there is no room worth using. */
254
+ function clip(text, max) {
255
+ if (max < 4)
256
+ return "";
257
+ const chars = [...text];
258
+ return chars.length <= max ? text : chars.slice(0, max - 1).join("").trimEnd() + "…";
259
+ }
104
260
  /** Minimal word wrap for the description line. */
105
261
  function wrap(text, width) {
106
262
  const w = Math.max(20, width);