pi-ask-user 0.5.0 → 0.5.2

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/index.ts CHANGED
@@ -9,89 +9,93 @@ import type { ExtensionAPI, Theme } from "@mariozechner/pi-coding-agent";
9
9
  import { getMarkdownTheme } from "@mariozechner/pi-coding-agent";
10
10
  import { Type } from "@sinclair/typebox";
11
11
  import {
12
- Container,
13
- type Component,
14
- decodeKittyPrintable,
15
- Editor,
16
- type EditorTheme,
17
- fuzzyFilter,
18
- Key,
19
- type Keybinding,
20
- type KeybindingsManager,
21
- Markdown,
22
- type MarkdownTheme,
23
- matchesKey,
24
- Spacer,
25
- Text,
26
- type TUI,
27
- truncateToWidth,
28
- wrapTextWithAnsi,
12
+ Container,
13
+ type Component,
14
+ decodeKittyPrintable,
15
+ Editor,
16
+ type EditorTheme,
17
+ fuzzyFilter,
18
+ Key,
19
+ type Keybinding,
20
+ type KeybindingsManager,
21
+ Markdown,
22
+ type MarkdownTheme,
23
+ matchesKey,
24
+ Spacer,
25
+ Text,
26
+ type TUI,
27
+ truncateToWidth,
28
+ wrapTextWithAnsi,
29
29
  } from "@mariozechner/pi-tui";
30
- import { renderSingleSelectRows, type QuestionOption } from "./single-select-layout";
30
+ import { renderSingleSelectRows } from "./single-select-layout";
31
+
32
+ import { createRequire } from "node:module";
33
+ const _require = createRequire(import.meta.url);
34
+ const ASK_USER_VERSION: string = (_require("./package.json") as { version: string }).version;
31
35
 
32
36
  type AskOptionInput = QuestionOption | string;
33
37
 
34
38
  interface AskParams {
35
- question: string;
36
- context?: string;
37
- options?: AskOptionInput[];
38
- allowMultiple?: boolean;
39
- allowFreeform?: boolean;
40
- timeout?: number;
39
+ question: string;
40
+ context?: string;
41
+ options?: AskOptionInput[];
42
+ allowMultiple?: boolean;
43
+ allowFreeform?: boolean;
44
+ timeout?: number;
41
45
  }
42
46
 
43
47
  interface AskToolDetails {
44
- question: string;
45
- context?: string;
46
- options: QuestionOption[];
47
- answer: string | null;
48
- cancelled: boolean;
49
- wasCustom?: boolean;
48
+ question: string;
49
+ context?: string;
50
+ options: QuestionOption[];
51
+ answer: string | null;
52
+ cancelled: boolean;
53
+ wasCustom?: boolean;
50
54
  }
51
55
 
52
56
  interface AskUIResult {
53
- answer: string;
54
- wasCustom: boolean;
57
+ answer: string;
58
+ wasCustom: boolean;
55
59
  }
56
60
 
57
61
  function normalizeOptions(options: AskOptionInput[]): QuestionOption[] {
58
- return options
59
- .map((option) => {
60
- if (typeof option === "string") {
61
- return { title: option };
62
- }
63
- if (option && typeof option === "object" && typeof option.title === "string") {
64
- return { title: option.title, description: option.description };
65
- }
66
- return null;
67
- })
68
- .filter((option): option is QuestionOption => option !== null);
62
+ return options
63
+ .map((option) => {
64
+ if (typeof option === "string") {
65
+ return { title: option };
66
+ }
67
+ if (option && typeof option === "object" && typeof option.title === "string") {
68
+ return { title: option.title, description: option.description };
69
+ }
70
+ return null;
71
+ })
72
+ .filter((option): option is QuestionOption => option !== null);
69
73
  }
70
74
 
71
75
  function formatOptionsForMessage(options: QuestionOption[]): string {
72
- return options
73
- .map((option, index) => {
74
- const desc = option.description ? ` — ${option.description}` : "";
75
- return `${index + 1}. ${option.title}${desc}`;
76
- })
77
- .join("\n");
76
+ return options
77
+ .map((option, index) => {
78
+ const desc = option.description ? ` — ${option.description}` : "";
79
+ return `${index + 1}. ${option.title}${desc}`;
80
+ })
81
+ .join("\n");
78
82
  }
79
83
 
80
84
  function createSelectListTheme(theme: Theme) {
81
- return {
82
- selectedPrefix: (t: string) => theme.fg("accent", t),
83
- selectedText: (t: string) => theme.fg("accent", t),
84
- description: (t: string) => theme.fg("muted", t),
85
- scrollInfo: (t: string) => theme.fg("dim", t),
86
- noMatch: (t: string) => theme.fg("warning", t),
87
- };
85
+ return {
86
+ selectedPrefix: (t: string) => theme.fg("accent", t),
87
+ selectedText: (t: string) => theme.fg("accent", t),
88
+ description: (t: string) => theme.fg("muted", t),
89
+ scrollInfo: (t: string) => theme.fg("dim", t),
90
+ noMatch: (t: string) => theme.fg("warning", t),
91
+ };
88
92
  }
89
93
 
90
94
  function createEditorTheme(theme: Theme): EditorTheme {
91
- return {
92
- borderColor: (s: string) => theme.fg("accent", s),
93
- selectList: createSelectListTheme(theme),
94
- };
95
+ return {
96
+ borderColor: (s: string) => theme.fg("accent", s),
97
+ selectList: createSelectListTheme(theme),
98
+ };
95
99
  }
96
100
 
97
101
  const BOX_BORDER_LEFT = "│ ";
@@ -99,56 +103,68 @@ const BOX_BORDER_RIGHT = " │";
99
103
  const BOX_BORDER_OVERHEAD = BOX_BORDER_LEFT.length + BOX_BORDER_RIGHT.length;
100
104
 
101
105
  class BoxBorderTop implements Component {
102
- private color: (s: string) => string;
103
- private title?: string;
104
- private titleColor?: (s: string) => string;
105
- constructor(color: (s: string) => string, title?: string, titleColor?: (s: string) => string) {
106
- this.color = color;
107
- this.title = title;
108
- this.titleColor = titleColor;
109
- }
110
- invalidate(): void {}
111
- render(width: number): string[] {
112
- const inner = Math.max(0, width - 2);
113
- if (!this.title || inner < this.title.length + 4) {
114
- return [this.color(`╭${"─".repeat(inner)}╮`)];
115
- }
116
- const label = ` ${this.title} `;
117
- const remaining = inner - 1 - label.length;
118
- const titleStyle = this.titleColor ?? this.color;
119
- return [
120
- this.color("╭─") + titleStyle(label) + this.color("─".repeat(Math.max(0, remaining)) + "╮"),
121
- ];
122
- }
106
+ private color: (s: string) => string;
107
+ private title?: string;
108
+ private titleColor?: (s: string) => string;
109
+ constructor(color: (s: string) => string, title?: string, titleColor?: (s: string) => string) {
110
+ this.color = color;
111
+ this.title = title;
112
+ this.titleColor = titleColor;
113
+ }
114
+ invalidate(): void { }
115
+ render(width: number): string[] {
116
+ const inner = Math.max(0, width - 2);
117
+ if (!this.title || inner < this.title.length + 4) {
118
+ return [this.color(`╭${"─".repeat(inner)}╮`)];
119
+ }
120
+ const label = ` ${this.title} `;
121
+ const remaining = inner - 1 - label.length;
122
+ const titleStyle = this.titleColor ?? this.color;
123
+ return [
124
+ this.color("╭─") + titleStyle(label) + this.color("─".repeat(Math.max(0, remaining)) + "╮"),
125
+ ];
126
+ }
123
127
  }
124
128
 
125
129
  class BoxBorderBottom implements Component {
126
- private color: (s: string) => string;
127
- constructor(color: (s: string) => string) {
128
- this.color = color;
129
- }
130
- invalidate(): void {}
131
- render(width: number): string[] {
132
- const inner = Math.max(0, width - 2);
133
- return [this.color(`╰${"─".repeat(inner)}╯`)];
134
- }
130
+ private color: (s: string) => string;
131
+ private label?: string;
132
+ private labelColor?: (s: string) => string;
133
+ constructor(color: (s: string) => string, label?: string, labelColor?: (s: string) => string) {
134
+ this.color = color;
135
+ this.label = label;
136
+ this.labelColor = labelColor;
137
+ }
138
+ invalidate(): void { }
139
+ render(width: number): string[] {
140
+ const inner = Math.max(0, width - 2);
141
+ if (!this.label || inner < this.label.length + 4) {
142
+ return [this.color(`╰${"─".repeat(inner)}╯`)];
143
+ }
144
+ const tag = ` ${this.label} `;
145
+ const leftDashes = inner - tag.length - 1;
146
+ const style = this.labelColor ?? this.color;
147
+ return [
148
+ this.color("╰" + "─".repeat(Math.max(0, leftDashes))) + style(tag) + this.color("─╯"),
149
+ ];
150
+ }
135
151
  }
136
152
 
137
153
  function formatKeyList(keys: string[]): string {
138
- return keys.join("/");
154
+ return keys.join("/");
139
155
  }
140
156
 
141
157
  function keybindingHint(
142
- theme: Theme,
143
- keybindings: KeybindingsManager,
144
- keybinding: Keybinding,
145
- description: string,
158
+ theme: Theme,
159
+ keybindings: KeybindingsManager,
160
+ keybinding: Keybinding,
161
+ description: string,
146
162
  ): string {
147
- return `${theme.fg("dim", formatKeyList(keybindings.getKeys(keybinding)))}${theme.fg("muted", ` ${description}`)}`;
163
+ return `${theme.fg("dim", formatKeyList(keybindings.getKeys(keybinding)))}${theme.fg("muted", ` ${description}`)}`;
148
164
  }
149
165
 
150
166
  function literalHint(theme: Theme, key: string, description: string): string {
151
- return `${theme.fg("dim", key)}${theme.fg("muted", ` ${description}`)}`;
167
+ return `${theme.fg("dim", key)}${theme.fg("muted", ` ${description}`)}`;
152
168
  }
153
169
 
154
170
  type AskMode = "select" | "freeform";
@@ -160,474 +176,480 @@ const SINGLE_SELECT_SPLIT_PANE_MIN_WIDTH = 84;
160
176
  const SINGLE_SELECT_SPLIT_PANE_LEFT_MIN_WIDTH = 32;
161
177
  const SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH = 28;
162
178
  const SINGLE_SELECT_SPLIT_PANE_SEPARATOR = " │ ";
179
+ const FREEFORM_SENTINEL = "\u270f\ufe0f Type custom response...";
163
180
 
164
181
  class MultiSelectList implements Component {
165
- private options: QuestionOption[];
166
- private allowFreeform: boolean;
167
- private theme: Theme;
168
- private keybindings: KeybindingsManager;
169
- private selectedIndex = 0;
170
- private checked = new Set<number>();
171
- private cachedWidth?: number;
172
- private cachedLines?: string[];
173
-
174
- public onCancel?: () => void;
175
- public onSubmit?: (result: string) => void;
176
- public onEnterFreeform?: () => void;
177
-
178
- constructor(options: QuestionOption[], allowFreeform: boolean, theme: Theme, keybindings: KeybindingsManager) {
179
- this.options = options;
180
- this.allowFreeform = allowFreeform;
181
- this.theme = theme;
182
- this.keybindings = keybindings;
183
- }
184
-
185
- invalidate(): void {
186
- this.cachedWidth = undefined;
187
- this.cachedLines = undefined;
188
- }
189
-
190
- private getItemCount(): number {
191
- return this.options.length + (this.allowFreeform ? 1 : 0);
192
- }
193
-
194
- private isFreeformRow(index: number): boolean {
195
- return this.allowFreeform && index === this.options.length;
196
- }
197
-
198
- private toggle(index: number): void {
199
- if (index < 0 || index >= this.options.length) return;
200
- if (this.checked.has(index)) this.checked.delete(index);
201
- else this.checked.add(index);
202
- }
203
-
204
- handleInput(data: string): void {
205
- if (this.keybindings.matches(data, "tui.select.cancel")) {
206
- this.onCancel?.();
207
- return;
208
- }
209
-
210
- const count = this.getItemCount();
211
- if (count === 0) {
212
- this.onCancel?.();
213
- return;
214
- }
215
-
216
- if (this.keybindings.matches(data, "tui.select.up") || matchesKey(data, Key.shift("tab"))) {
217
- this.selectedIndex = this.selectedIndex === 0 ? count - 1 : this.selectedIndex - 1;
218
- this.invalidate();
219
- return;
220
- }
221
-
222
- if (this.keybindings.matches(data, "tui.select.down") || matchesKey(data, Key.tab)) {
223
- this.selectedIndex = this.selectedIndex === count - 1 ? 0 : this.selectedIndex + 1;
224
- this.invalidate();
225
- return;
226
- }
227
-
228
- // Number keys (1-9) toggle checkboxes for normal items
229
- const numMatch = data.match(/^[1-9]$/);
230
- if (numMatch) {
231
- const idx = Number.parseInt(numMatch[0], 10) - 1;
232
- if (idx >= 0 && idx < this.options.length) {
233
- this.toggle(idx);
234
- this.selectedIndex = Math.min(idx, count - 1);
235
- this.invalidate();
236
- }
237
- return;
238
- }
239
-
240
- if (matchesKey(data, Key.space)) {
241
- if (this.isFreeformRow(this.selectedIndex)) {
242
- this.onEnterFreeform?.();
243
- return;
244
- }
245
- this.toggle(this.selectedIndex);
246
- this.invalidate();
247
- return;
248
- }
249
-
250
- if (this.keybindings.matches(data, "tui.select.confirm")) {
251
- if (this.isFreeformRow(this.selectedIndex)) {
252
- this.onEnterFreeform?.();
253
- return;
254
- }
255
-
256
- const selectedTitles = Array.from(this.checked)
257
- .sort((a, b) => a - b)
258
- .map((i) => this.options[i]?.title)
259
- .filter((t): t is string => !!t);
260
-
261
- // If nothing checked, fall back to current row
262
- const fallback = this.options[this.selectedIndex]?.title;
263
- const result = selectedTitles.length > 0 ? selectedTitles.join(", ") : fallback;
264
-
265
- if (result) this.onSubmit?.(result);
266
- else this.onCancel?.();
267
- }
268
- }
269
-
270
- render(width: number): string[] {
271
- if (this.cachedLines && this.cachedWidth === width) {
272
- return this.cachedLines;
273
- }
274
-
275
- const theme = this.theme;
276
- const count = this.getItemCount();
277
- const maxVisible = Math.min(count, 10);
278
-
279
- if (count === 0) {
280
- this.cachedLines = [theme.fg("warning", "No options")];
281
- this.cachedWidth = width;
282
- return this.cachedLines;
283
- }
284
-
285
- const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisible / 2), count - maxVisible));
286
- const endIndex = Math.min(startIndex + maxVisible, count);
287
-
288
- const lines: string[] = [];
289
-
290
- for (let i = startIndex; i < endIndex; i++) {
291
- const isSelected = i === this.selectedIndex;
292
- const prefix = isSelected ? theme.fg("accent", "→") : " ";
293
-
294
- if (this.isFreeformRow(i)) {
295
- const label = theme.fg("text", theme.bold("Type something."));
296
- const desc = theme.fg("muted", "Enter a custom response");
297
- const line = `${prefix} ${label} ${theme.fg("dim", "—")} ${desc}`;
298
- lines.push(truncateToWidth(line, width, ""));
299
- continue;
300
- }
301
-
302
- const option = this.options[i];
303
- if (!option) continue;
304
-
305
- const checkbox = this.checked.has(i) ? theme.fg("success", "[✓]") : theme.fg("dim", "[ ]");
306
- const num = theme.fg("dim", `${i + 1}.`);
307
- const title = isSelected
308
- ? theme.fg("accent", theme.bold(option.title))
309
- : theme.fg("text", theme.bold(option.title));
310
-
311
- const firstLine = `${prefix} ${num} ${checkbox} ${title}`;
312
- lines.push(truncateToWidth(firstLine, width, ""));
313
-
314
- if (option.description) {
315
- const indent = " ";
316
- const wrapWidth = Math.max(10, width - indent.length);
317
- const wrapped = wrapTextWithAnsi(option.description, wrapWidth);
318
- for (const w of wrapped) {
319
- lines.push(truncateToWidth(indent + theme.fg("muted", w), width, ""));
320
- }
321
- }
322
- }
323
-
324
- // Scroll indicator
325
- if (startIndex > 0 || endIndex < count) {
326
- lines.push(theme.fg("dim", truncateToWidth(` (${this.selectedIndex + 1}/${count})`, width, "")));
327
- }
328
-
329
- this.cachedWidth = width;
330
- this.cachedLines = lines;
331
- return lines;
332
- }
182
+ private options: QuestionOption[];
183
+ private allowFreeform: boolean;
184
+ private theme: Theme;
185
+ private keybindings: KeybindingsManager;
186
+ private selectedIndex = 0;
187
+ private checked = new Set<number>();
188
+ private cachedWidth?: number;
189
+ private cachedLines?: string[];
190
+
191
+ public onCancel?: () => void;
192
+ public onSubmit?: (result: string) => void;
193
+ public onEnterFreeform?: () => void;
194
+
195
+ constructor(options: QuestionOption[], allowFreeform: boolean, theme: Theme, keybindings: KeybindingsManager) {
196
+ this.options = options;
197
+ this.allowFreeform = allowFreeform;
198
+ this.theme = theme;
199
+ this.keybindings = keybindings;
200
+ }
201
+
202
+ invalidate(): void {
203
+ this.cachedWidth = undefined;
204
+ this.cachedLines = undefined;
205
+ }
206
+
207
+ private getItemCount(): number {
208
+ return this.options.length + (this.allowFreeform ? 1 : 0);
209
+ }
210
+
211
+ private isFreeformRow(index: number): boolean {
212
+ return this.allowFreeform && index === this.options.length;
213
+ }
214
+
215
+ private toggle(index: number): void {
216
+ if (index < 0 || index >= this.options.length) return;
217
+ if (this.checked.has(index)) this.checked.delete(index);
218
+ else this.checked.add(index);
219
+ }
220
+
221
+ handleInput(data: string): void {
222
+ if (this.keybindings.matches(data, "tui.select.cancel")) {
223
+ this.onCancel?.();
224
+ return;
225
+ }
226
+
227
+ const count = this.getItemCount();
228
+ if (count === 0) {
229
+ this.onCancel?.();
230
+ return;
231
+ }
232
+
233
+ if (this.keybindings.matches(data, "tui.select.up") || matchesKey(data, Key.shift("tab"))) {
234
+ this.selectedIndex = this.selectedIndex === 0 ? count - 1 : this.selectedIndex - 1;
235
+ this.invalidate();
236
+ return;
237
+ }
238
+
239
+ if (this.keybindings.matches(data, "tui.select.down") || matchesKey(data, Key.tab)) {
240
+ this.selectedIndex = this.selectedIndex === count - 1 ? 0 : this.selectedIndex + 1;
241
+ this.invalidate();
242
+ return;
243
+ }
244
+
245
+ // Number keys (1-9) toggle checkboxes for normal items
246
+ const numMatch = data.match(/^[1-9]$/);
247
+ if (numMatch) {
248
+ const idx = Number.parseInt(numMatch[0], 10) - 1;
249
+ if (idx >= 0 && idx < this.options.length) {
250
+ this.toggle(idx);
251
+ this.selectedIndex = Math.min(idx, count - 1);
252
+ this.invalidate();
253
+ }
254
+ return;
255
+ }
256
+
257
+ if (matchesKey(data, Key.space)) {
258
+ if (this.isFreeformRow(this.selectedIndex)) {
259
+ this.onEnterFreeform?.();
260
+ return;
261
+ }
262
+ this.toggle(this.selectedIndex);
263
+ this.invalidate();
264
+ return;
265
+ }
266
+
267
+ if (this.keybindings.matches(data, "tui.select.confirm")) {
268
+ if (this.isFreeformRow(this.selectedIndex)) {
269
+ this.onEnterFreeform?.();
270
+ return;
271
+ }
272
+
273
+ const selectedTitles = Array.from(this.checked)
274
+ .sort((a, b) => a - b)
275
+ .map((i) => this.options[i]?.title)
276
+ .filter((t): t is string => !!t);
277
+
278
+ // If nothing checked, fall back to current row
279
+ const fallback = this.options[this.selectedIndex]?.title;
280
+ const result = selectedTitles.length > 0 ? selectedTitles.join(", ") : fallback;
281
+
282
+ if (result) this.onSubmit?.(result);
283
+ else this.onCancel?.();
284
+ }
285
+ }
286
+
287
+ render(width: number): string[] {
288
+ if (this.cachedLines && this.cachedWidth === width) {
289
+ return this.cachedLines;
290
+ }
291
+
292
+ const theme = this.theme;
293
+ const count = this.getItemCount();
294
+ const maxVisible = Math.min(count, 10);
295
+
296
+ if (count === 0) {
297
+ this.cachedLines = [theme.fg("warning", "No options")];
298
+ this.cachedWidth = width;
299
+ return this.cachedLines;
300
+ }
301
+
302
+ const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisible / 2), count - maxVisible));
303
+ const endIndex = Math.min(startIndex + maxVisible, count);
304
+
305
+ const lines: string[] = [];
306
+
307
+ for (let i = startIndex; i < endIndex; i++) {
308
+ const isSelected = i === this.selectedIndex;
309
+ const prefix = isSelected ? theme.fg("accent", "→") : " ";
310
+
311
+ if (this.isFreeformRow(i)) {
312
+ const label = theme.fg("text", theme.bold("Type something."));
313
+ const desc = theme.fg("muted", "Enter a custom response");
314
+ const line = `${prefix} ${label} ${theme.fg("dim", "—")} ${desc}`;
315
+ lines.push(truncateToWidth(line, width, ""));
316
+ continue;
317
+ }
318
+
319
+ const option = this.options[i];
320
+ if (!option) continue;
321
+
322
+ const checkbox = this.checked.has(i) ? theme.fg("success", "[✓]") : theme.fg("dim", "[ ]");
323
+ const num = theme.fg("dim", `${i + 1}.`);
324
+ const title = isSelected
325
+ ? theme.fg("accent", theme.bold(option.title))
326
+ : theme.fg("text", theme.bold(option.title));
327
+
328
+ const firstLine = `${prefix} ${num} ${checkbox} ${title}`;
329
+ lines.push(truncateToWidth(firstLine, width, ""));
330
+
331
+ if (option.description) {
332
+ const indent = " ";
333
+ const wrapWidth = Math.max(10, width - indent.length);
334
+ const wrapped = wrapTextWithAnsi(option.description, wrapWidth);
335
+ for (const w of wrapped) {
336
+ lines.push(truncateToWidth(indent + theme.fg("muted", w), width, ""));
337
+ }
338
+ }
339
+ }
340
+
341
+ // Scroll indicator
342
+ if (startIndex > 0 || endIndex < count) {
343
+ lines.push(theme.fg("dim", truncateToWidth(` (${this.selectedIndex + 1}/${count})`, width, "")));
344
+ }
345
+
346
+ this.cachedWidth = width;
347
+ this.cachedLines = lines;
348
+ return lines;
349
+ }
333
350
  }
334
351
 
335
352
  class WrappedSingleSelectList implements Component {
336
- private options: QuestionOption[];
337
- private allowFreeform: boolean;
338
- private theme: Theme;
339
- private keybindings: KeybindingsManager;
340
- private selectedIndex = 0;
341
- private searchQuery = "";
342
- private maxVisibleRows = 12;
343
- private cachedWidth?: number;
344
- private cachedLines?: string[];
345
-
346
- public onCancel?: () => void;
347
- public onSubmit?: (result: string) => void;
348
- public onEnterFreeform?: () => void;
349
-
350
- constructor(options: QuestionOption[], allowFreeform: boolean, theme: Theme, keybindings: KeybindingsManager) {
351
- this.options = options;
352
- this.allowFreeform = allowFreeform;
353
- this.theme = theme;
354
- this.keybindings = keybindings;
355
- }
356
-
357
- setMaxVisibleRows(rows: number): void {
358
- const next = Math.max(1, Math.floor(rows));
359
- if (next !== this.maxVisibleRows) {
360
- this.maxVisibleRows = next;
361
- this.invalidate();
362
- }
363
- }
364
-
365
- invalidate(): void {
366
- this.cachedWidth = undefined;
367
- this.cachedLines = undefined;
368
- }
369
-
370
- private getFilteredOptions(): QuestionOption[] {
371
- return fuzzyFilter(this.options, this.searchQuery, (option) => `${option.title} ${option.description ?? ""}`);
372
- }
373
-
374
- private getItemCount(filteredOptions: QuestionOption[]): number {
375
- return filteredOptions.length + (this.allowFreeform ? 1 : 0);
376
- }
377
-
378
- private isFreeformRow(index: number, filteredOptions: QuestionOption[]): boolean {
379
- return this.allowFreeform && index === filteredOptions.length;
380
- }
381
-
382
- private setSearchQuery(query: string): void {
383
- this.searchQuery = query;
384
- this.selectedIndex = 0;
385
- this.invalidate();
386
- }
387
-
388
- private popSearchCharacter(): void {
389
- if (!this.searchQuery) return;
390
- const characters = [...this.searchQuery];
391
- characters.pop();
392
- this.setSearchQuery(characters.join(""));
393
- }
394
-
395
- private getPrintableInput(data: string): string | null {
396
- const kittyPrintable = decodeKittyPrintable(data);
397
- if (kittyPrintable !== undefined) return kittyPrintable;
398
-
399
- const characters = [...data];
400
- if (characters.length !== 1) return null;
401
-
402
- const [character] = characters;
403
- if (!character) return null;
404
-
405
- const code = character.charCodeAt(0);
406
- if (code < 32 || code === 0x7f || (code >= 0x80 && code <= 0x9f)) {
407
- return null;
408
- }
409
-
410
- return character;
411
- }
412
-
413
- private styleListLine(line: string, width: number): string {
414
- const trimmed = line.trim();
415
-
416
- if (trimmed.startsWith("(")) {
417
- return truncateToWidth(this.theme.fg("dim", line), width, "");
418
- }
419
-
420
- if (line.startsWith(" ")) {
421
- return truncateToWidth(this.theme.fg("muted", line), width, "");
422
- }
423
-
424
- if (line.startsWith("")) {
425
- return truncateToWidth(this.theme.fg("accent", this.theme.bold(line)), width, "");
426
- }
427
-
428
- return truncateToWidth(this.theme.fg("text", line), width, "");
429
- }
430
-
431
- private getSplitPaneWidths(width: number): { left: number; right: number } | null {
432
- if (width < SINGLE_SELECT_SPLIT_PANE_MIN_WIDTH) return null;
433
-
434
- const availableWidth = width - SINGLE_SELECT_SPLIT_PANE_SEPARATOR.length;
435
- if (availableWidth < SINGLE_SELECT_SPLIT_PANE_LEFT_MIN_WIDTH + SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH) {
436
- return null;
437
- }
438
-
439
- const preferredLeftWidth = Math.floor(availableWidth * 0.42);
440
- const left = Math.max(
441
- SINGLE_SELECT_SPLIT_PANE_LEFT_MIN_WIDTH,
442
- Math.min(preferredLeftWidth, availableWidth - SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH),
443
- );
444
- const right = availableWidth - left;
445
-
446
- if (right < SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH) return null;
447
- return { left, right };
448
- }
449
-
450
- private buildListLines(width: number, filteredOptions: QuestionOption[], hideDescriptions = false): string[] {
451
- const lines: string[] = [];
452
- const count = this.getItemCount(filteredOptions);
453
- const searchValue = this.searchQuery ? this.theme.fg("text", this.searchQuery) : this.theme.fg("dim", "type to filter");
454
- lines.push(truncateToWidth(`${this.theme.fg("accent", "Filter:")} ${searchValue}`, width, ""));
455
-
456
- if (this.searchQuery && filteredOptions.length === 0) {
457
- lines.push(truncateToWidth(this.theme.fg("warning", "No matching options"), width, ""));
458
- }
459
-
460
- if (count === 0) {
461
- if (!this.searchQuery) {
462
- lines.push(truncateToWidth(this.theme.fg("warning", "No options"), width, ""));
463
- }
464
- return lines.slice(0, this.maxVisibleRows);
465
- }
466
-
467
- const maxRows = Math.max(1, this.maxVisibleRows - lines.length);
468
- const optionLines = renderSingleSelectRows({
469
- options: filteredOptions,
470
- selectedIndex: this.selectedIndex,
471
- width,
472
- allowFreeform: this.allowFreeform,
473
- maxRows,
474
- hideDescriptions,
475
- }).map((line) => this.styleListLine(line, width));
476
-
477
- lines.push(...optionLines);
478
- return lines.slice(0, this.maxVisibleRows);
479
- }
480
-
481
- private buildPreviewLines(width: number, filteredOptions: QuestionOption[], maxLines: number): string[] {
482
- if (maxLines <= 0) return [];
483
-
484
- const lines: string[] = [];
485
- const pushWrapped = (text: string, style: (line: string) => string): void => {
486
- for (const line of wrapTextWithAnsi(text, Math.max(10, width))) {
487
- lines.push(truncateToWidth(style(line), width, ""));
488
- }
489
- };
490
- const pushBlank = (): void => {
491
- if (lines.length === 0 || lines[lines.length - 1] !== "") {
492
- lines.push("");
493
- }
494
- };
495
-
496
- pushWrapped("Details", (line) => this.theme.fg("accent", this.theme.bold(line)));
497
- pushBlank();
498
-
499
- if (this.isFreeformRow(this.selectedIndex, filteredOptions)) {
500
- pushWrapped("Custom response", (line) => this.theme.fg("text", this.theme.bold(line)));
501
- pushBlank();
502
- pushWrapped("Open the editor to write any answer.", (line) => this.theme.fg("text", line));
503
- pushBlank();
504
- pushWrapped("Use this when none of the listed options fit.", (line) => this.theme.fg("muted", line));
505
- if (this.searchQuery) {
506
- pushBlank();
507
- pushWrapped(`Current filter: ${this.searchQuery}`, (line) => this.theme.fg("dim", line));
508
- }
509
- } else {
510
- const selected = filteredOptions[this.selectedIndex];
511
- if (!selected) {
512
- pushWrapped("No option selected", (line) => this.theme.fg("muted", line));
513
- } else {
514
- pushWrapped(selected.title, (line) => this.theme.fg("text", this.theme.bold(line)));
515
- pushBlank();
516
- if (selected.description?.trim()) {
517
- pushWrapped(selected.description, (line) => this.theme.fg("text", line));
518
- } else {
519
- pushWrapped("No additional details provided for this option.", (line) => this.theme.fg("muted", line));
520
- }
521
- pushBlank();
522
- pushWrapped("Press Enter to select this option.", (line) => this.theme.fg("dim", line));
523
- if (this.searchQuery) {
524
- pushBlank();
525
- pushWrapped(`Filter: ${this.searchQuery}`, (line) => this.theme.fg("dim", line));
526
- }
527
- }
528
- }
529
-
530
- while (lines.length > 0 && lines[lines.length - 1] === "") {
531
- lines.pop();
532
- }
533
-
534
- if (lines.length <= maxLines) return lines;
535
- if (maxLines === 1) return [truncateToWidth(this.theme.fg("dim", "…"), width, "")];
536
-
537
- const visibleLines = lines.slice(0, maxLines - 1);
538
- visibleLines.push(truncateToWidth(this.theme.fg("dim", "…"), width, ""));
539
- return visibleLines;
540
- }
541
-
542
- handleInput(data: string): void {
543
- if (this.searchQuery && matchesKey(data, Key.escape)) {
544
- this.setSearchQuery("");
545
- return;
546
- }
547
-
548
- if (this.keybindings.matches(data, "tui.select.cancel")) {
549
- this.onCancel?.();
550
- return;
551
- }
552
-
553
- const filteredOptions = this.getFilteredOptions();
554
- const count = this.getItemCount(filteredOptions);
555
-
556
- if ((this.keybindings.matches(data, "tui.select.up") || matchesKey(data, Key.shift("tab"))) && count > 0) {
557
- this.selectedIndex = this.selectedIndex === 0 ? count - 1 : this.selectedIndex - 1;
558
- this.invalidate();
559
- return;
560
- }
561
-
562
- if ((this.keybindings.matches(data, "tui.select.down") || matchesKey(data, Key.tab)) && count > 0) {
563
- this.selectedIndex = this.selectedIndex === count - 1 ? 0 : this.selectedIndex + 1;
564
- this.invalidate();
565
- return;
566
- }
567
-
568
- const numMatch = data.match(/^[1-9]$/);
569
- if (numMatch && count > 0) {
570
- const idx = Number.parseInt(numMatch[0], 10) - 1;
571
- if (idx >= 0 && idx < count) {
572
- this.selectedIndex = idx;
573
- this.invalidate();
574
- return;
575
- }
576
- }
577
-
578
- if (this.keybindings.matches(data, "tui.select.confirm") && count > 0) {
579
- if (this.isFreeformRow(this.selectedIndex, filteredOptions)) {
580
- this.onEnterFreeform?.();
581
- return;
582
- }
583
-
584
- const result = filteredOptions[this.selectedIndex]?.title;
585
- if (result) this.onSubmit?.(result);
586
- else this.onCancel?.();
587
- return;
588
- }
589
-
590
- if (this.keybindings.matches(data, "tui.editor.deleteCharBackward") || matchesKey(data, Key.backspace)) {
591
- this.popSearchCharacter();
592
- return;
593
- }
594
-
595
- const printableInput = this.getPrintableInput(data);
596
- if (printableInput) {
597
- this.setSearchQuery(this.searchQuery + printableInput);
598
- }
599
- }
600
-
601
- render(width: number): string[] {
602
- if (this.cachedLines && this.cachedWidth === width) {
603
- return this.cachedLines;
604
- }
605
-
606
- const filteredOptions = this.getFilteredOptions();
607
- const count = this.getItemCount(filteredOptions);
608
- this.selectedIndex = count > 0 ? Math.max(0, Math.min(this.selectedIndex, count - 1)) : 0;
609
-
610
- const splitPane = this.getSplitPaneWidths(width);
611
- let lines: string[];
612
-
613
- if (!splitPane) {
614
- lines = this.buildListLines(width, filteredOptions);
615
- } else {
616
- const listLines = this.buildListLines(splitPane.left, filteredOptions, true);
617
- const previewLines = this.buildPreviewLines(splitPane.right, filteredOptions, this.maxVisibleRows);
618
- const rowCount = Math.min(this.maxVisibleRows, Math.max(listLines.length, previewLines.length));
619
- const separator = this.theme.fg("dim", SINGLE_SELECT_SPLIT_PANE_SEPARATOR);
620
- lines = Array.from({ length: rowCount }, (_, index) => {
621
- const left = truncateToWidth(listLines[index] ?? "", splitPane.left, "", true);
622
- const right = truncateToWidth(previewLines[index] ?? "", splitPane.right, "");
623
- return `${left}${separator}${right}`;
624
- });
625
- }
626
-
627
- this.cachedWidth = width;
628
- this.cachedLines = lines;
629
- return lines;
630
- }
353
+ private options: QuestionOption[];
354
+ private allowFreeform: boolean;
355
+ private theme: Theme;
356
+ private keybindings: KeybindingsManager;
357
+ private selectedIndex = 0;
358
+ private searchQuery = "";
359
+ private maxVisibleRows = 12;
360
+ private cachedWidth?: number;
361
+ private cachedLines?: string[];
362
+
363
+ public onCancel?: () => void;
364
+ public onSubmit?: (result: string) => void;
365
+ public onEnterFreeform?: () => void;
366
+
367
+ constructor(options: QuestionOption[], allowFreeform: boolean, theme: Theme, keybindings: KeybindingsManager) {
368
+ this.options = options;
369
+ this.allowFreeform = allowFreeform;
370
+ this.theme = theme;
371
+ this.keybindings = keybindings;
372
+ }
373
+
374
+ setMaxVisibleRows(rows: number): void {
375
+ const next = Math.max(1, Math.floor(rows));
376
+ if (next !== this.maxVisibleRows) {
377
+ this.maxVisibleRows = next;
378
+ this.invalidate();
379
+ }
380
+ }
381
+
382
+ invalidate(): void {
383
+ this.cachedWidth = undefined;
384
+ this.cachedLines = undefined;
385
+ }
386
+
387
+ private getFilteredOptions(): QuestionOption[] {
388
+ return fuzzyFilter(this.options, this.searchQuery, (option) => `${option.title} ${option.description ?? ""}`);
389
+ }
390
+
391
+ private getItemCount(filteredOptions: QuestionOption[]): number {
392
+ return filteredOptions.length + (this.allowFreeform ? 1 : 0);
393
+ }
394
+
395
+ private isFreeformRow(index: number, filteredOptions: QuestionOption[]): boolean {
396
+ return this.allowFreeform && index === filteredOptions.length;
397
+ }
398
+
399
+ private setSearchQuery(query: string): void {
400
+ this.searchQuery = query;
401
+ this.selectedIndex = 0;
402
+ this.invalidate();
403
+ }
404
+
405
+ private popSearchCharacter(): void {
406
+ if (!this.searchQuery) return;
407
+ const characters = [...this.searchQuery];
408
+ characters.pop();
409
+ this.setSearchQuery(characters.join(""));
410
+ }
411
+
412
+ private getPrintableInput(data: string): string | null {
413
+ const kittyPrintable = decodeKittyPrintable(data);
414
+ if (kittyPrintable !== undefined) return kittyPrintable;
415
+
416
+ const characters = [...data];
417
+ if (characters.length !== 1) return null;
418
+
419
+ const [character] = characters;
420
+ if (!character) return null;
421
+
422
+ const code = character.charCodeAt(0);
423
+ if (code < 32 || code === 0x7f || (code >= 0x80 && code <= 0x9f)) {
424
+ return null;
425
+ }
426
+
427
+ return character;
428
+ }
429
+
430
+ private styleListLine(line: string, width: number, isSelected: boolean): string {
431
+ const trimmed = line.trim();
432
+
433
+ if (trimmed.startsWith("(")) {
434
+ return truncateToWidth(this.theme.fg("dim", line), width, "");
435
+ }
436
+
437
+ if (isSelected) {
438
+ return truncateToWidth(this.theme.fg("accent", this.theme.bold(line)), width, "");
439
+ }
440
+
441
+ if (line.startsWith(" ")) {
442
+ return truncateToWidth(this.theme.fg("muted", line), width, "");
443
+ }
444
+
445
+ if (line.startsWith("")) {
446
+ return truncateToWidth(this.theme.fg("accent", this.theme.bold(line)), width, "");
447
+ }
448
+
449
+ return truncateToWidth(this.theme.fg("text", line), width, "");
450
+ }
451
+
452
+ private getSplitPaneWidths(width: number): { left: number; right: number } | null {
453
+ if (width < SINGLE_SELECT_SPLIT_PANE_MIN_WIDTH) return null;
454
+
455
+ const availableWidth = width - SINGLE_SELECT_SPLIT_PANE_SEPARATOR.length;
456
+ if (availableWidth < SINGLE_SELECT_SPLIT_PANE_LEFT_MIN_WIDTH + SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH) {
457
+ return null;
458
+ }
459
+
460
+ const preferredLeftWidth = Math.floor(availableWidth * 0.42);
461
+ const left = Math.max(
462
+ SINGLE_SELECT_SPLIT_PANE_LEFT_MIN_WIDTH,
463
+ Math.min(preferredLeftWidth, availableWidth - SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH),
464
+ );
465
+ const right = availableWidth - left;
466
+
467
+ if (right < SINGLE_SELECT_SPLIT_PANE_RIGHT_MIN_WIDTH) return null;
468
+ return { left, right };
469
+ }
470
+
471
+ private buildListLines(width: number, filteredOptions: QuestionOption[], hideDescriptions = false): string[] {
472
+ const lines: string[] = [];
473
+ const count = this.getItemCount(filteredOptions);
474
+ const searchValue = this.searchQuery ? this.theme.fg("text", this.searchQuery) : this.theme.fg("dim", "type to filter");
475
+ lines.push(truncateToWidth(`${this.theme.fg("accent", "Filter:")} ${searchValue}`, width, ""));
476
+
477
+ if (this.searchQuery && filteredOptions.length === 0) {
478
+ lines.push(truncateToWidth(this.theme.fg("warning", "No matching options"), width, ""));
479
+ }
480
+
481
+ if (count === 0) {
482
+ if (!this.searchQuery) {
483
+ lines.push(truncateToWidth(this.theme.fg("warning", "No options"), width, ""));
484
+ }
485
+ return lines.slice(0, this.maxVisibleRows);
486
+ }
487
+
488
+ const maxRows = Math.max(1, this.maxVisibleRows - lines.length);
489
+ const optionRows = renderSingleSelectRows({
490
+ options: filteredOptions,
491
+ selectedIndex: this.selectedIndex,
492
+ width,
493
+ allowFreeform: this.allowFreeform,
494
+ maxRows,
495
+ hideDescriptions,
496
+ });
497
+ const optionLines = optionRows.map((row) => this.styleListLine(row.line, width, row.selected));
498
+
499
+ lines.push(...optionLines);
500
+ return lines.slice(0, this.maxVisibleRows);
501
+ }
502
+
503
+ private buildPreviewLines(width: number, filteredOptions: QuestionOption[], maxLines: number): string[] {
504
+ if (maxLines <= 0) return [];
505
+
506
+ let mdTheme: MarkdownTheme | undefined;
507
+ try {
508
+ mdTheme = getMarkdownTheme();
509
+ } catch { }
510
+
511
+ // Build a markdown string for the preview content
512
+ let md = "";
513
+
514
+ if (this.isFreeformRow(this.selectedIndex, filteredOptions)) {
515
+ md += "## Custom response\n\n";
516
+ md += "Open the editor to write **any** answer.\n\n";
517
+ md += "*Use this when none of the listed options fit.*\n";
518
+ if (this.searchQuery) {
519
+ md += `\n> Current filter: \`${this.searchQuery}\`\n`;
520
+ }
521
+ } else {
522
+ const selected = filteredOptions[this.selectedIndex];
523
+ if (!selected) {
524
+ md += "*No option selected*\n";
525
+ } else {
526
+ md += `## ${selected.title}\n\n`;
527
+ if (selected.description?.trim()) {
528
+ md += `${selected.description}\n`;
529
+ } else {
530
+ md += "*No additional details provided for this option.*\n";
531
+ }
532
+ md += `\n---\n\nPress \`Enter\` to select this option.\n`;
533
+ if (this.searchQuery) {
534
+ md += `\n> Filter: \`${this.searchQuery}\`\n`;
535
+ }
536
+ }
537
+ }
538
+
539
+ // Render via Markdown component if theme is available, otherwise fall back to plain text
540
+ let lines: string[];
541
+ if (mdTheme) {
542
+ const mdComponent = new Markdown(md.trim(), 0, 0, mdTheme);
543
+ lines = mdComponent.render(width);
544
+ } else {
545
+ lines = [];
546
+ for (const line of wrapTextWithAnsi(md.trim(), Math.max(10, width))) {
547
+ lines.push(truncateToWidth(line, width, ""));
548
+ }
549
+ }
550
+
551
+ // Trim trailing blanks
552
+ while (lines.length > 0 && lines[lines.length - 1]?.trim() === "") {
553
+ lines.pop();
554
+ }
555
+
556
+ if (lines.length <= maxLines) return lines;
557
+ if (maxLines === 1) return [truncateToWidth(this.theme.fg("dim", "…"), width, "")];
558
+
559
+ const visibleLines = lines.slice(0, maxLines - 1);
560
+ visibleLines.push(truncateToWidth(this.theme.fg("dim", "…"), width, ""));
561
+ return visibleLines;
562
+ }
563
+
564
+ handleInput(data: string): void {
565
+ if (this.searchQuery && matchesKey(data, Key.escape)) {
566
+ this.setSearchQuery("");
567
+ return;
568
+ }
569
+
570
+ if (this.keybindings.matches(data, "tui.select.cancel")) {
571
+ this.onCancel?.();
572
+ return;
573
+ }
574
+
575
+ const filteredOptions = this.getFilteredOptions();
576
+ const count = this.getItemCount(filteredOptions);
577
+
578
+ if ((this.keybindings.matches(data, "tui.select.up") || matchesKey(data, Key.shift("tab"))) && count > 0) {
579
+ this.selectedIndex = this.selectedIndex === 0 ? count - 1 : this.selectedIndex - 1;
580
+ this.invalidate();
581
+ return;
582
+ }
583
+
584
+ if ((this.keybindings.matches(data, "tui.select.down") || matchesKey(data, Key.tab)) && count > 0) {
585
+ this.selectedIndex = this.selectedIndex === count - 1 ? 0 : this.selectedIndex + 1;
586
+ this.invalidate();
587
+ return;
588
+ }
589
+
590
+ const numMatch = data.match(/^[1-9]$/);
591
+ if (numMatch && count > 0) {
592
+ const idx = Number.parseInt(numMatch[0], 10) - 1;
593
+ if (idx >= 0 && idx < count) {
594
+ this.selectedIndex = idx;
595
+ this.invalidate();
596
+ return;
597
+ }
598
+ }
599
+
600
+ if (this.keybindings.matches(data, "tui.select.confirm") && count > 0) {
601
+ if (this.isFreeformRow(this.selectedIndex, filteredOptions)) {
602
+ this.onEnterFreeform?.();
603
+ return;
604
+ }
605
+
606
+ const result = filteredOptions[this.selectedIndex]?.title;
607
+ if (result) this.onSubmit?.(result);
608
+ else this.onCancel?.();
609
+ return;
610
+ }
611
+
612
+ if (this.keybindings.matches(data, "tui.editor.deleteCharBackward") || matchesKey(data, Key.backspace)) {
613
+ this.popSearchCharacter();
614
+ return;
615
+ }
616
+
617
+ const printableInput = this.getPrintableInput(data);
618
+ if (printableInput) {
619
+ this.setSearchQuery(this.searchQuery + printableInput);
620
+ }
621
+ }
622
+
623
+ render(width: number): string[] {
624
+ if (this.cachedLines && this.cachedWidth === width) {
625
+ return this.cachedLines;
626
+ }
627
+
628
+ const filteredOptions = this.getFilteredOptions();
629
+ const count = this.getItemCount(filteredOptions);
630
+ this.selectedIndex = count > 0 ? Math.max(0, Math.min(this.selectedIndex, count - 1)) : 0;
631
+
632
+ const splitPane = this.getSplitPaneWidths(width);
633
+ let lines: string[];
634
+
635
+ if (!splitPane) {
636
+ lines = this.buildListLines(width, filteredOptions);
637
+ } else {
638
+ const listLines = this.buildListLines(splitPane.left, filteredOptions, true);
639
+ const previewLines = this.buildPreviewLines(splitPane.right, filteredOptions, this.maxVisibleRows);
640
+ const rowCount = Math.min(this.maxVisibleRows, Math.max(listLines.length, previewLines.length));
641
+ const separator = this.theme.fg("dim", SINGLE_SELECT_SPLIT_PANE_SEPARATOR);
642
+ lines = Array.from({ length: rowCount }, (_, index) => {
643
+ const left = truncateToWidth(listLines[index] ?? "", splitPane.left, "", true);
644
+ const right = truncateToWidth(previewLines[index] ?? "", splitPane.right, "");
645
+ return `${left}${separator}${right}`;
646
+ });
647
+ }
648
+
649
+ this.cachedWidth = width;
650
+ this.cachedLines = lines;
651
+ return lines;
652
+ }
631
653
  }
632
654
 
633
655
  /**
@@ -635,562 +657,619 @@ class WrappedSingleSelectList implements Component {
635
657
  * component between SelectList/MultiSelectList and an Editor (freeform mode).
636
658
  */
637
659
  class AskComponent extends Container {
638
- private question: string;
639
- private context?: string;
640
- private options: QuestionOption[];
641
- private allowMultiple: boolean;
642
- private allowFreeform: boolean;
643
- private tui: TUI;
644
- private theme: Theme;
645
- private keybindings: KeybindingsManager;
646
- private onDone: (result: AskUIResult | null) => void;
647
-
648
- private mode: AskMode = "select";
649
-
650
- // Static layout components
651
- private titleText: Text;
652
- private questionText: Text;
653
- private contextComponent?: Component;
654
- private modeContainer: Container;
655
- private helpText: Text;
656
-
657
- // Mode components
658
- private singleSelectList?: WrappedSingleSelectList;
659
- private multiSelectList?: MultiSelectList;
660
- private editor?: Editor;
661
-
662
- // Focusable - propagate to Editor for IME cursor positioning
663
- private _focused = false;
664
- get focused(): boolean {
665
- return this._focused;
666
- }
667
- set focused(value: boolean) {
668
- this._focused = value;
669
- if (this.editor && this.mode === "freeform") {
670
- (this.editor as any).focused = value;
671
- }
672
- }
673
-
674
- constructor(
675
- question: string,
676
- context: string | undefined,
677
- options: QuestionOption[],
678
- allowMultiple: boolean,
679
- allowFreeform: boolean,
680
- tui: TUI,
681
- theme: Theme,
682
- keybindings: KeybindingsManager,
683
- onDone: (result: AskUIResult | null) => void,
684
- ) {
685
- super();
686
-
687
- this.question = question;
688
- this.context = context;
689
- this.options = options;
690
- this.allowMultiple = allowMultiple;
691
- this.allowFreeform = allowFreeform;
692
- this.tui = tui;
693
- this.theme = theme;
694
- this.keybindings = keybindings;
695
- this.onDone = onDone;
696
-
697
- // Layout skeleton
698
- this.addChild(new BoxBorderTop(
699
- (s: string) => theme.fg("accent", s),
700
- "ask_user",
701
- (s: string) => theme.fg("dim", theme.bold(s)),
702
- ));
703
- this.addChild(new Spacer(1));
704
-
705
- this.titleText = new Text("", 1, 0);
706
- this.addChild(this.titleText);
707
- this.addChild(new Spacer(1));
708
-
709
- this.questionText = new Text("", 1, 0);
710
- this.addChild(this.questionText);
711
-
712
- if (this.context) {
713
- this.addChild(new Spacer(1));
714
- let mdTheme: MarkdownTheme | undefined;
715
- try {
716
- mdTheme = getMarkdownTheme();
717
- } catch {}
718
- if (mdTheme) {
719
- this.contextComponent = new Markdown("", 1, 0, mdTheme);
720
- } else {
721
- this.contextComponent = new Text("", 1, 0);
722
- }
723
- this.addChild(this.contextComponent);
724
- }
725
-
726
- this.addChild(new Spacer(1));
727
-
728
- this.modeContainer = new Container();
729
- this.addChild(this.modeContainer);
730
-
731
- this.addChild(new Spacer(1));
732
- this.helpText = new Text("", 1, 0);
733
- this.addChild(this.helpText);
734
-
735
- this.addChild(new Spacer(1));
736
- this.addChild(new BoxBorderBottom((s: string) => theme.fg("accent", s)));
737
-
738
- this.updateStaticText();
739
- this.showSelectMode();
740
- }
741
-
742
- override invalidate(): void {
743
- super.invalidate();
744
- this.updateStaticText();
745
- this.updateHelpText();
746
- }
747
-
748
- override render(width: number): string[] {
749
- const innerWidth = Math.max(1, width - BOX_BORDER_OVERHEAD);
750
-
751
- if (this.mode === "select" && !this.allowMultiple) {
752
- const overlayMaxHeight = Math.max(12, Math.floor(this.tui.terminal.rows * ASK_OVERLAY_MAX_HEIGHT_RATIO));
753
- const staticLines = this.countStaticLines(innerWidth);
754
- const availableOptionRows = Math.max(4, overlayMaxHeight - staticLines);
755
- this.ensureSingleSelectList().setMaxVisibleRows(availableOptionRows);
756
- }
757
-
758
- // Render children at the inner width (excluding side border characters)
759
- const rawLines = super.render(innerWidth);
760
-
761
- // First and last lines are the top/bottom box borders — pass through at full width.
762
- // All inner lines get wrapped with side borders.
763
- const borderColor = (s: string) => this.theme.fg("accent", s);
764
- const titleColor = (s: string) => this.theme.fg("dim", this.theme.bold(s));
765
- return rawLines.map((line, index) => {
766
- if (index === 0 || index === rawLines.length - 1) {
767
- // Box top/bottom borders already rendered at innerWidth — re-render at full width
768
- if (index === 0) return new BoxBorderTop(borderColor, "ask_user", titleColor).render(width)[0];
769
- return new BoxBorderBottom(borderColor).render(width)[0];
770
- }
771
- const padded = truncateToWidth(line, innerWidth, "", true);
772
- return `${borderColor(BOX_BORDER_LEFT)}${padded}${borderColor(BOX_BORDER_RIGHT)}`;
773
- });
774
- }
775
-
776
- private countWrappedLines(text: string, width: number): number {
777
- return Math.max(1, wrapTextWithAnsi(text, Math.max(10, width - 2)).length);
778
- }
779
-
780
- private countStaticLines(width: number): number {
781
- const titleLines = 1;
782
- const questionLines = this.countWrappedLines(this.question, width);
783
- const contextLines = this.context ? 1 + this.countWrappedLines(this.context, width) : 0;
784
- const helpLines = 1;
785
- const borderLines = 2;
786
- const spacerLines = this.context ? 6 : 5;
787
- return borderLines + spacerLines + titleLines + questionLines + contextLines + helpLines;
788
- }
789
-
790
- private updateStaticText(): void {
791
- const theme = this.theme;
792
- this.titleText.setText(theme.fg("accent", theme.bold("Question")));
793
- this.questionText.setText(theme.fg("text", theme.bold(this.question)));
794
- if (this.contextComponent && this.context) {
795
- if (this.contextComponent instanceof Markdown) {
796
- (this.contextComponent as Markdown).setText(
797
- `**Context:**\n${this.context}`,
798
- );
799
- } else {
800
- (this.contextComponent as Text).setText(
801
- `${theme.fg("accent", theme.bold("Context:"))}\n${theme.fg("dim", this.context)}`,
802
- );
803
- }
804
- }
805
- }
806
-
807
- private updateHelpText(): void {
808
- const theme = this.theme;
809
- if (this.mode === "freeform") {
810
- const alternateCancelKeys = this.keybindings
811
- .getKeys("tui.select.cancel")
812
- .filter((key) => key !== "escape" && key !== "esc");
813
- const hints = [
814
- keybindingHint(theme, this.keybindings, "tui.input.submit", "submit"),
815
- keybindingHint(theme, this.keybindings, "tui.input.newLine", "newline"),
816
- literalHint(theme, "esc", "back"),
817
- alternateCancelKeys.length > 0 ? literalHint(theme, formatKeyList(alternateCancelKeys), "cancel") : null,
818
- ]
819
- .filter((hint): hint is string => !!hint)
820
- .join(" ");
821
- this.helpText.setText(theme.fg("dim", hints));
822
- return;
823
- }
824
-
825
- if (this.allowMultiple) {
826
- const hints = [
827
- literalHint(theme, "↑↓", "navigate"),
828
- literalHint(theme, "space", "toggle"),
829
- keybindingHint(theme, this.keybindings, "tui.select.confirm", "submit"),
830
- keybindingHint(theme, this.keybindings, "tui.select.cancel", "cancel"),
831
- ].join(" ");
832
- this.helpText.setText(theme.fg("dim", hints));
833
- } else {
834
- const alternateCancelKeys = this.keybindings
835
- .getKeys("tui.select.cancel")
836
- .filter((key) => key !== "escape" && key !== "esc");
837
- const hints = [
838
- literalHint(theme, "type", "filter"),
839
- keybindingHint(theme, this.keybindings, "tui.editor.deleteCharBackward", "erase"),
840
- literalHint(theme, "↑↓", "navigate"),
841
- keybindingHint(theme, this.keybindings, "tui.select.confirm", "select"),
842
- literalHint(theme, "esc", "clear/cancel"),
843
- alternateCancelKeys.length > 0
844
- ? literalHint(theme, formatKeyList(alternateCancelKeys), "cancel")
845
- : null,
846
- ]
847
- .filter((hint): hint is string => !!hint)
848
- .join(" ");
849
- this.helpText.setText(theme.fg("dim", hints));
850
- }
851
- }
852
-
853
- private ensureSingleSelectList(): WrappedSingleSelectList {
854
- if (this.singleSelectList) return this.singleSelectList;
855
-
856
- const list = new WrappedSingleSelectList(this.options, this.allowFreeform, this.theme, this.keybindings);
857
- list.onSubmit = (result) => this.onDone({ answer: result, wasCustom: false });
858
- list.onCancel = () => this.onDone(null);
859
- list.onEnterFreeform = () => this.showFreeformMode();
860
-
861
- this.singleSelectList = list;
862
- return list;
863
- }
864
-
865
- private ensureMultiSelectList(): MultiSelectList {
866
- if (this.multiSelectList) return this.multiSelectList;
867
-
868
- const list = new MultiSelectList(this.options, this.allowFreeform, this.theme, this.keybindings);
869
- list.onCancel = () => this.onDone(null);
870
- list.onSubmit = (result) => this.onDone({ answer: result, wasCustom: false });
871
- list.onEnterFreeform = () => this.showFreeformMode();
872
-
873
- this.multiSelectList = list;
874
- return list;
875
- }
876
-
877
- private ensureEditor(): Editor {
878
- if (this.editor) return this.editor;
879
- const editor = new Editor(this.tui, createEditorTheme(this.theme));
880
- editor.disableSubmit = false;
881
- editor.onSubmit = (text: string) => {
882
- const trimmed = text.trim();
883
- this.onDone(trimmed ? { answer: trimmed, wasCustom: true } : null);
884
- };
885
- this.editor = editor;
886
- return editor;
887
- }
888
-
889
- private showSelectMode(): void {
890
- this.mode = "select";
891
- this.modeContainer.clear();
892
-
893
- if (this.allowMultiple) {
894
- this.modeContainer.addChild(this.ensureMultiSelectList());
895
- } else {
896
- this.modeContainer.addChild(this.ensureSingleSelectList());
897
- }
898
-
899
- this.updateHelpText();
900
- this.invalidate();
901
- this.tui.requestRender();
902
- }
903
-
904
- private showFreeformMode(): void {
905
- this.mode = "freeform";
906
- this.modeContainer.clear();
907
-
908
- const editor = this.ensureEditor();
909
- (editor as any).focused = this._focused;
910
-
911
- this.modeContainer.addChild(new Text(this.theme.fg("accent", this.theme.bold("Custom response")), 1, 0));
912
- this.modeContainer.addChild(new Spacer(1));
913
- this.modeContainer.addChild(editor);
914
-
915
- this.updateHelpText();
916
- this.invalidate();
917
- this.tui.requestRender();
918
- }
919
-
920
- handleInput(data: string): void {
921
- if (this.mode === "freeform") {
922
- if (matchesKey(data, Key.escape)) {
923
- this.showSelectMode();
924
- return;
925
- }
926
-
927
- if (this.keybindings.matches(data, "tui.select.cancel")) {
928
- this.onDone(null);
929
- return;
930
- }
931
-
932
- this.ensureEditor().handleInput(data);
933
- this.tui.requestRender();
934
- return;
935
- }
936
-
937
- // Selection mode
938
- if (this.allowMultiple) {
939
- this.ensureMultiSelectList().handleInput?.(data);
940
- this.tui.requestRender();
941
- return;
942
- }
943
-
944
- this.ensureSingleSelectList().handleInput?.(data);
945
- this.tui.requestRender();
946
- }
660
+ private question: string;
661
+ private context?: string;
662
+ private options: QuestionOption[];
663
+ private allowMultiple: boolean;
664
+ private allowFreeform: boolean;
665
+ private tui: TUI;
666
+ private theme: Theme;
667
+ private keybindings: KeybindingsManager;
668
+ private onDone: (result: AskUIResult | null) => void;
669
+
670
+ private mode: AskMode = "select";
671
+
672
+ // Static layout components
673
+ private titleText: Text;
674
+ private questionText: Text;
675
+ private contextComponent?: Component;
676
+ private modeContainer: Container;
677
+ private helpText: Text;
678
+
679
+ // Mode components
680
+ private singleSelectList?: WrappedSingleSelectList;
681
+ private multiSelectList?: MultiSelectList;
682
+ private editor?: Editor;
683
+
684
+ // Focusable - propagate to Editor for IME cursor positioning
685
+ private _focused = false;
686
+ get focused(): boolean {
687
+ return this._focused;
688
+ }
689
+ set focused(value: boolean) {
690
+ this._focused = value;
691
+ if (this.editor && this.mode === "freeform") {
692
+ (this.editor as any).focused = value;
693
+ }
694
+ }
695
+
696
+ constructor(
697
+ question: string,
698
+ context: string | undefined,
699
+ options: QuestionOption[],
700
+ allowMultiple: boolean,
701
+ allowFreeform: boolean,
702
+ tui: TUI,
703
+ theme: Theme,
704
+ keybindings: KeybindingsManager,
705
+ onDone: (result: AskUIResult | null) => void,
706
+ ) {
707
+ super();
708
+
709
+ this.question = question;
710
+ this.context = context;
711
+ this.options = options;
712
+ this.allowMultiple = allowMultiple;
713
+ this.allowFreeform = allowFreeform;
714
+ this.tui = tui;
715
+ this.theme = theme;
716
+ this.keybindings = keybindings;
717
+ this.onDone = onDone;
718
+
719
+ // Layout skeleton
720
+ this.addChild(new BoxBorderTop(
721
+ (s: string) => theme.fg("accent", s),
722
+ "ask_user",
723
+ (s: string) => theme.fg("dim", theme.bold(s)),
724
+ ));
725
+ this.addChild(new Spacer(1));
726
+
727
+ this.titleText = new Text("", 1, 0);
728
+ this.addChild(this.titleText);
729
+ this.addChild(new Spacer(1));
730
+
731
+ this.questionText = new Text("", 1, 0);
732
+ this.addChild(this.questionText);
733
+
734
+ if (this.context) {
735
+ this.addChild(new Spacer(1));
736
+ let mdTheme: MarkdownTheme | undefined;
737
+ try {
738
+ mdTheme = getMarkdownTheme();
739
+ } catch { }
740
+ if (mdTheme) {
741
+ this.contextComponent = new Markdown("", 1, 0, mdTheme);
742
+ } else {
743
+ this.contextComponent = new Text("", 1, 0);
744
+ }
745
+ this.addChild(this.contextComponent);
746
+ }
747
+
748
+ this.addChild(new Spacer(1));
749
+
750
+ this.modeContainer = new Container();
751
+ this.addChild(this.modeContainer);
752
+
753
+ this.addChild(new Spacer(1));
754
+ this.helpText = new Text("", 1, 0);
755
+ this.addChild(this.helpText);
756
+
757
+ this.addChild(new Spacer(1));
758
+ this.addChild(new BoxBorderBottom(
759
+ (s: string) => theme.fg("accent", s),
760
+ `v${ASK_USER_VERSION}`,
761
+ (s: string) => theme.fg("dim", s),
762
+ ));
763
+
764
+ this.updateStaticText();
765
+ this.showSelectMode();
766
+ }
767
+
768
+ override invalidate(): void {
769
+ super.invalidate();
770
+ this.updateStaticText();
771
+ this.updateHelpText();
772
+ }
773
+
774
+ override render(width: number): string[] {
775
+ const innerWidth = Math.max(1, width - BOX_BORDER_OVERHEAD);
776
+
777
+ if (this.mode === "select" && !this.allowMultiple) {
778
+ const overlayMaxHeight = Math.max(12, Math.floor(this.tui.terminal.rows * ASK_OVERLAY_MAX_HEIGHT_RATIO));
779
+ const staticLines = this.countStaticLines(innerWidth);
780
+ const availableOptionRows = Math.max(4, overlayMaxHeight - staticLines);
781
+ this.ensureSingleSelectList().setMaxVisibleRows(availableOptionRows);
782
+ }
783
+
784
+ // Render children at the inner width (excluding side border characters)
785
+ const rawLines = super.render(innerWidth);
786
+
787
+ // First and last lines are the top/bottom box borders — pass through at full width.
788
+ // All inner lines get wrapped with side borders.
789
+ const borderColor = (s: string) => this.theme.fg("accent", s);
790
+ const titleColor = (s: string) => this.theme.fg("dim", this.theme.bold(s));
791
+ return rawLines.map((line, index) => {
792
+ if (index === 0 || index === rawLines.length - 1) {
793
+ // Box top/bottom borders already rendered at innerWidth re-render at full width
794
+ if (index === 0) return new BoxBorderTop(borderColor, "ask_user", titleColor).render(width)[0];
795
+ return new BoxBorderBottom(borderColor, `v${ASK_USER_VERSION}`, (s: string) => this.theme.fg("dim", s)).render(width)[0];
796
+ }
797
+ const padded = truncateToWidth(line, innerWidth, "", true);
798
+ return `${borderColor(BOX_BORDER_LEFT)}${padded}${borderColor(BOX_BORDER_RIGHT)}`;
799
+ });
800
+ }
801
+
802
+ private countWrappedLines(text: string, width: number): number {
803
+ return Math.max(1, wrapTextWithAnsi(text, Math.max(10, width - 2)).length);
804
+ }
805
+
806
+ private countStaticLines(width: number): number {
807
+ const titleLines = 1;
808
+ const questionLines = this.countWrappedLines(this.question, width);
809
+ const contextLines = this.context ? 1 + this.countWrappedLines(this.context, width) : 0;
810
+ const helpLines = 1;
811
+ const borderLines = 2;
812
+ const spacerLines = this.context ? 6 : 5;
813
+ return borderLines + spacerLines + titleLines + questionLines + contextLines + helpLines;
814
+ }
815
+
816
+ private updateStaticText(): void {
817
+ const theme = this.theme;
818
+ this.titleText.setText(theme.fg("accent", theme.bold("Question")));
819
+ this.questionText.setText(theme.fg("text", theme.bold(this.question)));
820
+ if (this.contextComponent && this.context) {
821
+ if (this.contextComponent instanceof Markdown) {
822
+ (this.contextComponent as Markdown).setText(
823
+ `**Context:**\n${this.context}`,
824
+ );
825
+ } else {
826
+ (this.contextComponent as Text).setText(
827
+ `${theme.fg("accent", theme.bold("Context:"))}\n${theme.fg("dim", this.context)}`,
828
+ );
829
+ }
830
+ }
831
+ }
832
+
833
+ private updateHelpText(): void {
834
+ const theme = this.theme;
835
+ if (this.mode === "freeform") {
836
+ const alternateCancelKeys = this.keybindings
837
+ .getKeys("tui.select.cancel")
838
+ .filter((key) => key !== "escape" && key !== "esc");
839
+ const hints = [
840
+ keybindingHint(theme, this.keybindings, "tui.input.submit", "submit"),
841
+ keybindingHint(theme, this.keybindings, "tui.input.newLine", "newline"),
842
+ literalHint(theme, "esc", "back"),
843
+ alternateCancelKeys.length > 0 ? literalHint(theme, formatKeyList(alternateCancelKeys), "cancel") : null,
844
+ ]
845
+ .filter((hint): hint is string => !!hint)
846
+ .join(" • ");
847
+ this.helpText.setText(theme.fg("dim", hints));
848
+ return;
849
+ }
850
+
851
+ if (this.allowMultiple) {
852
+ const hints = [
853
+ literalHint(theme, "↑↓", "navigate"),
854
+ literalHint(theme, "space", "toggle"),
855
+ keybindingHint(theme, this.keybindings, "tui.select.confirm", "submit"),
856
+ keybindingHint(theme, this.keybindings, "tui.select.cancel", "cancel"),
857
+ ].join("");
858
+ this.helpText.setText(theme.fg("dim", hints));
859
+ } else {
860
+ const alternateCancelKeys = this.keybindings
861
+ .getKeys("tui.select.cancel")
862
+ .filter((key) => key !== "escape" && key !== "esc");
863
+ const hints = [
864
+ literalHint(theme, "type", "filter"),
865
+ keybindingHint(theme, this.keybindings, "tui.editor.deleteCharBackward", "erase"),
866
+ literalHint(theme, "↑↓", "navigate"),
867
+ keybindingHint(theme, this.keybindings, "tui.select.confirm", "select"),
868
+ literalHint(theme, "esc", "clear/cancel"),
869
+ alternateCancelKeys.length > 0
870
+ ? literalHint(theme, formatKeyList(alternateCancelKeys), "cancel")
871
+ : null,
872
+ ]
873
+ .filter((hint): hint is string => !!hint)
874
+ .join(" • ");
875
+ this.helpText.setText(theme.fg("dim", hints));
876
+ }
877
+ }
878
+
879
+ private ensureSingleSelectList(): WrappedSingleSelectList {
880
+ if (this.singleSelectList) return this.singleSelectList;
881
+
882
+ const list = new WrappedSingleSelectList(this.options, this.allowFreeform, this.theme, this.keybindings);
883
+ list.onSubmit = (result) => this.onDone({ answer: result, wasCustom: false });
884
+ list.onCancel = () => this.onDone(null);
885
+ list.onEnterFreeform = () => this.showFreeformMode();
886
+
887
+ this.singleSelectList = list;
888
+ return list;
889
+ }
890
+
891
+ private ensureMultiSelectList(): MultiSelectList {
892
+ if (this.multiSelectList) return this.multiSelectList;
893
+
894
+ const list = new MultiSelectList(this.options, this.allowFreeform, this.theme, this.keybindings);
895
+ list.onCancel = () => this.onDone(null);
896
+ list.onSubmit = (result) => this.onDone({ answer: result, wasCustom: false });
897
+ list.onEnterFreeform = () => this.showFreeformMode();
898
+
899
+ this.multiSelectList = list;
900
+ return list;
901
+ }
902
+
903
+ private ensureEditor(): Editor {
904
+ if (this.editor) return this.editor;
905
+ const editor = new Editor(this.tui, createEditorTheme(this.theme));
906
+ editor.disableSubmit = false;
907
+ editor.onSubmit = (text: string) => {
908
+ const trimmed = text.trim();
909
+ this.onDone(trimmed ? { answer: trimmed, wasCustom: true } : null);
910
+ };
911
+ this.editor = editor;
912
+ return editor;
913
+ }
914
+
915
+ private showSelectMode(): void {
916
+ this.mode = "select";
917
+ this.modeContainer.clear();
918
+
919
+ if (this.allowMultiple) {
920
+ this.modeContainer.addChild(this.ensureMultiSelectList());
921
+ } else {
922
+ this.modeContainer.addChild(this.ensureSingleSelectList());
923
+ }
924
+
925
+ this.updateHelpText();
926
+ this.invalidate();
927
+ this.tui.requestRender();
928
+ }
929
+
930
+ private showFreeformMode(): void {
931
+ this.mode = "freeform";
932
+ this.modeContainer.clear();
933
+
934
+ const editor = this.ensureEditor();
935
+ (editor as any).focused = this._focused;
936
+
937
+ this.modeContainer.addChild(new Text(this.theme.fg("accent", this.theme.bold("Custom response")), 1, 0));
938
+ this.modeContainer.addChild(new Spacer(1));
939
+ this.modeContainer.addChild(editor);
940
+
941
+ this.updateHelpText();
942
+ this.invalidate();
943
+ this.tui.requestRender();
944
+ }
945
+
946
+ handleInput(data: string): void {
947
+ if (this.mode === "freeform") {
948
+ if (matchesKey(data, Key.escape)) {
949
+ this.showSelectMode();
950
+ return;
951
+ }
952
+
953
+ if (this.keybindings.matches(data, "tui.select.cancel")) {
954
+ this.onDone(null);
955
+ return;
956
+ }
957
+
958
+ this.ensureEditor().handleInput(data);
959
+ this.tui.requestRender();
960
+ return;
961
+ }
962
+
963
+ // Selection mode
964
+ if (this.allowMultiple) {
965
+ this.ensureMultiSelectList().handleInput?.(data);
966
+ this.tui.requestRender();
967
+ return;
968
+ }
969
+
970
+ this.ensureSingleSelectList().handleInput?.(data);
971
+ this.tui.requestRender();
972
+ }
973
+ }
974
+
975
+ /**
976
+ * RPC/headless fallback: use dialog methods (select/input) instead of the rich TUI overlay.
977
+ * ctx.ui.custom() returns undefined in RPC mode, so we degrade gracefully.
978
+ */
979
+ async function askViaDialogs(
980
+ ui: { select: Function; input: Function },
981
+ question: string,
982
+ context: string | undefined,
983
+ options: QuestionOption[],
984
+ allowMultiple: boolean,
985
+ allowFreeform: boolean,
986
+ timeout?: number,
987
+ ): Promise<AskUIResult | null> {
988
+ const dialogOpts = timeout ? { timeout } : undefined;
989
+ const prompt = context ? `${question}\n\nContext:\n${context}` : question;
990
+
991
+ if (allowMultiple) {
992
+ // Multi-select degrades to a freeform input with options listed in the prompt.
993
+ // RPC's select() is single-choice only; input() lets the user type freely.
994
+ const optionList = formatOptionsForMessage(options);
995
+ const answer = await ui.input(
996
+ `${prompt}\n\nOptions (select one or more):\n${optionList}`,
997
+ "Type your selection(s)...",
998
+ dialogOpts,
999
+ ) as string | undefined;
1000
+ if (!answer) return null;
1001
+ return { answer: answer.trim(), wasCustom: true };
1002
+ }
1003
+
1004
+ // Single-select: present options via ctx.ui.select()
1005
+ const selectOptions = options.map((o) => o.title);
1006
+ if (allowFreeform) selectOptions.push(FREEFORM_SENTINEL);
1007
+
1008
+ const selected = await ui.select(prompt, selectOptions, dialogOpts) as string | undefined;
1009
+ if (!selected) return null;
1010
+
1011
+ if (selected === FREEFORM_SENTINEL) {
1012
+ const answer = await ui.input(prompt, "Type your answer...", dialogOpts) as string | undefined;
1013
+ if (!answer) return null;
1014
+ return { answer: answer.trim(), wasCustom: true };
1015
+ }
1016
+
1017
+ return { answer: selected, wasCustom: false };
947
1018
  }
948
1019
 
949
- export default function (pi: ExtensionAPI) {
950
- pi.registerTool({
951
- name: "ask_user",
952
- label: "Ask User",
953
- description:
954
- "Ask the user a question with optional multiple-choice answers. Use this to gather information interactively. Before calling, gather context with tools (read/exa/ref) and pass a short summary via the context field.",
955
- promptSnippet:
956
- "Ask the user a question with optional multiple-choice answers to gather information interactively",
957
- promptGuidelines: [
958
- "Before calling ask_user, gather context with tools (read/exa/ref) and pass a short summary via the context field.",
959
- "Use ask_user when the user's intent is ambiguous, when a decision requires explicit user input, or when multiple valid options exist.",
960
- ],
961
- parameters: Type.Object({
962
- question: Type.String({ description: "The question to ask the user" }),
963
- context: Type.Optional(
964
- Type.String({
965
- description: "Relevant context to show before the question (summary of findings)",
966
- }),
967
- ),
968
- options: Type.Optional(
969
- Type.Array(
970
- Type.Union([
971
- Type.String({ description: "Short title for this option" }),
972
- Type.Object({
973
- title: Type.String({ description: "Short title for this option" }),
974
- description: Type.Optional(
975
- Type.String({ description: "Longer description explaining this option" }),
976
- ),
977
- }),
978
- ]),
979
- { description: "List of options for the user to choose from" },
980
- ),
981
- ),
982
- allowMultiple: Type.Optional(
983
- Type.Boolean({ description: "Allow selecting multiple options. Default: false" }),
984
- ),
985
- allowFreeform: Type.Optional(
986
- Type.Boolean({ description: "Add a freeform text option. Default: true" }),
987
- ),
988
- timeout: Type.Optional(
989
- Type.Number({ description: "Auto-dismiss after N milliseconds. Returns null (cancelled) when expired." }),
990
- ),
991
- }),
992
-
993
- async execute(_toolCallId, params, signal, onUpdate, ctx) {
994
- if (signal?.aborted) {
995
- return {
996
- content: [{ type: "text", text: "Cancelled" }],
997
- details: { question: params.question, options: [], answer: null, cancelled: true } as AskToolDetails,
998
- };
999
- }
1000
-
1001
- const {
1002
- question,
1003
- context,
1004
- options: rawOptions = [],
1005
- allowMultiple = false,
1006
- allowFreeform = true,
1007
- timeout,
1008
- } = params as AskParams;
1009
- const options = normalizeOptions(rawOptions);
1010
- const normalizedContext = context?.trim() || undefined;
1011
-
1012
- if (!ctx.hasUI || !ctx.ui) {
1013
- const optionText = options.length > 0 ? `\n\nOptions:\n${formatOptionsForMessage(options)}` : "";
1014
- const freeformHint = allowFreeform ? "\n\nYou can also answer freely." : "";
1015
- const contextText = normalizedContext ? `\n\nContext:\n${normalizedContext}` : "";
1016
- return {
1017
- content: [
1018
- {
1019
- type: "text",
1020
- text: `Ask requires interactive mode. Please answer:\n\n${question}${contextText}${optionText}${freeformHint}`,
1021
- },
1022
- ],
1023
- isError: true,
1024
- details: { question, context: normalizedContext, options, answer: null, cancelled: true } as AskToolDetails,
1025
- };
1026
- }
1027
-
1028
- // If no options provided, fall back to freeform input prompt.
1029
- if (options.length === 0) {
1030
- const prompt = normalizedContext ? `${question}\n\nContext:\n${normalizedContext}` : question;
1031
- const answer = await ctx.ui.input(prompt, "Type your answer...", timeout ? { timeout } : undefined);
1032
-
1033
- if (!answer) {
1034
- return {
1035
- content: [{ type: "text", text: "User cancelled the question" }],
1036
- details: { question, context: normalizedContext, options, answer: null, cancelled: true } as AskToolDetails,
1037
- };
1038
- }
1039
-
1040
- pi.events.emit("ask:answered", { question, context: normalizedContext, answer, wasCustom: true });
1041
- return {
1042
- content: [{ type: "text", text: `User answered: ${answer}` }],
1043
- details: { question, context: normalizedContext, options, answer, cancelled: false, wasCustom: true } as AskToolDetails,
1044
- };
1045
- }
1046
-
1047
- onUpdate?.({
1048
- content: [{ type: "text", text: "Waiting for user input..." }],
1049
- details: { question, context: normalizedContext, options, answer: null, cancelled: false },
1050
- });
1051
-
1052
- let result: AskUIResult | null;
1053
- try {
1054
- result = await ctx.ui.custom<AskUIResult | null>(
1055
- (tui, theme, keybindings, done) => {
1056
- // Wire AbortSignal so agent cancellation auto-dismisses the overlay
1057
- if (signal) {
1058
- const onAbort = () => done(null);
1059
- signal.addEventListener("abort", onAbort, { once: true });
1060
- }
1061
-
1062
- // Wire timeout for overlay mode
1063
- if (timeout && timeout > 0) {
1064
- setTimeout(() => done(null), timeout);
1065
- }
1066
-
1067
- return new AskComponent(
1068
- question,
1069
- normalizedContext,
1070
- options,
1071
- allowMultiple,
1072
- allowFreeform,
1073
- tui,
1074
- theme,
1075
- keybindings,
1076
- done,
1077
- );
1078
- },
1079
- {
1080
- overlay: true,
1081
- overlayOptions: {
1082
- anchor: "center",
1083
- width: ASK_OVERLAY_WIDTH,
1084
- minWidth: ASK_OVERLAY_MIN_WIDTH,
1085
- maxHeight: "85%",
1086
- margin: 1,
1087
- },
1088
- },
1089
- );
1090
- } catch (error) {
1091
- const message =
1092
- error instanceof Error ? `${error.message}\n${error.stack ?? ""}` : String(error);
1093
- return {
1094
- content: [{ type: "text", text: `Ask tool failed: ${message}` }],
1095
- isError: true,
1096
- details: { error: message },
1097
- };
1098
- }
1099
-
1100
- if (result === null) {
1101
- pi.events.emit("ask:cancelled", { question, context: normalizedContext, options });
1102
- return {
1103
- content: [{ type: "text", text: "User cancelled the question" }],
1104
- details: { question, context: normalizedContext, options, answer: null, cancelled: true } as AskToolDetails,
1105
- };
1106
- }
1107
-
1108
- pi.events.emit("ask:answered", {
1109
- question,
1110
- context: normalizedContext,
1111
- answer: result.answer,
1112
- wasCustom: result.wasCustom,
1113
- });
1114
- return {
1115
- content: [{ type: "text", text: `User answered: ${result.answer}` }],
1116
- details: {
1117
- question,
1118
- context: normalizedContext,
1119
- options,
1120
- answer: result.answer,
1121
- cancelled: false,
1122
- wasCustom: result.wasCustom,
1123
- } as AskToolDetails,
1124
- };
1125
- },
1126
-
1127
- renderCall(args, theme) {
1128
- const question = (args.question as string) || "";
1129
- const rawOptions = Array.isArray(args.options) ? args.options : [];
1130
- let text = theme.fg("toolTitle", theme.bold("ask_user "));
1131
- text += theme.fg("muted", question);
1132
- if (rawOptions.length > 0) {
1133
- const labels = rawOptions.map((o: unknown) =>
1134
- typeof o === "string" ? o : (o as QuestionOption)?.title ?? "",
1135
- );
1136
- text += "\n" + theme.fg("dim", ` ${rawOptions.length} option(s): ${labels.join(", ")}`);
1137
- }
1138
- if (args.allowMultiple) {
1139
- text += theme.fg("dim", " [multi-select]");
1140
- }
1141
- return new Text(text, 0, 0);
1142
- },
1143
-
1144
- renderResult(result, options, theme) {
1145
- const details = result.details as (AskToolDetails & { error?: string }) | undefined;
1146
-
1147
- if (details?.error) {
1148
- return new Text(theme.fg("error", `✗ ${details.error}`), 0, 0);
1149
- }
1150
-
1151
- if (options.isPartial) {
1152
- const waitingText = result.content
1153
- ?.filter((part: { type?: string; text?: string }) => part?.type === "text")
1154
- .map((part: { text?: string }) => part.text ?? "")
1155
- .join("\n")
1156
- .trim() || "Waiting for user input...";
1157
- return new Text(theme.fg("muted", waitingText), 0, 0);
1158
- }
1159
-
1160
- if (!details || details.cancelled) {
1161
- return new Text(theme.fg("warning", "Cancelled"), 0, 0);
1162
- }
1163
-
1164
- const answer = details.answer ?? "";
1165
- let text = theme.fg("success", "✓ ");
1166
- if (details.wasCustom) {
1167
- text += theme.fg("muted", "(wrote) ");
1168
- }
1169
- text += theme.fg("accent", answer);
1170
-
1171
- if (options.expanded) {
1172
- const selectedTitles = new Set(
1173
- answer
1174
- .split(",")
1175
- .map((value) => value.trim())
1176
- .filter(Boolean),
1177
- );
1178
- text += "\n" + theme.fg("dim", `Q: ${details.question}`);
1179
- if (details.context) {
1180
- text += "\n" + theme.fg("dim", details.context);
1181
- }
1182
- if (details.options && details.options.length > 0) {
1183
- text += "\n" + theme.fg("dim", "Options:");
1184
- for (const opt of details.options) {
1185
- const desc = opt.description ? ` — ${opt.description}` : "";
1186
- const isSelected = opt.title === answer || selectedTitles.has(opt.title);
1187
- const marker = isSelected ? theme.fg("success", "●") : theme.fg("dim", "○");
1188
- text += `\n ${marker} ${theme.fg("dim", opt.title)}${theme.fg("dim", desc)}`;
1189
- }
1190
- }
1191
- }
1192
-
1193
- return new Text(text, 0, 0);
1194
- },
1195
- });
1020
+ export default function(pi: ExtensionAPI) {
1021
+ pi.registerTool({
1022
+ name: "ask_user",
1023
+ label: "Ask User",
1024
+ description:
1025
+ "Ask the user a question with optional multiple-choice answers. Use this to gather information interactively. Before calling, gather context with tools (read/web/ref) and pass a short summary via the context field.",
1026
+ promptSnippet:
1027
+ "Ask the user a question with optional multiple-choice answers to gather information interactively",
1028
+ promptGuidelines: [
1029
+ "Before calling ask_user, gather context with tools (read/web/ref) and pass a short summary via the context field.",
1030
+ "Use ask_user when the user's intent is ambiguous, when a decision requires explicit user input, or when multiple valid options exist.",
1031
+ ],
1032
+ parameters: Type.Object({
1033
+ question: Type.String({ description: "The question to ask the user" }),
1034
+ context: Type.Optional(
1035
+ Type.String({
1036
+ description: "Relevant context to show before the question (summary of findings)",
1037
+ }),
1038
+ ),
1039
+ options: Type.Optional(
1040
+ Type.Array(
1041
+ Type.Union([
1042
+ Type.String({ description: "Short title for this option" }),
1043
+ Type.Object({
1044
+ title: Type.String({ description: "Short title for this option" }),
1045
+ description: Type.Optional(
1046
+ Type.String({ description: "Longer description explaining this option" }),
1047
+ ),
1048
+ }),
1049
+ ]),
1050
+ { description: "List of options for the user to choose from" },
1051
+ ),
1052
+ ),
1053
+ allowMultiple: Type.Optional(
1054
+ Type.Boolean({ description: "Allow selecting multiple options. Default: false" }),
1055
+ ),
1056
+ allowFreeform: Type.Optional(
1057
+ Type.Boolean({ description: "Add a freeform text option. Default: true" }),
1058
+ ),
1059
+ timeout: Type.Optional(
1060
+ Type.Number({ description: "Auto-dismiss after N milliseconds. Returns null (cancelled) when expired." }),
1061
+ ),
1062
+ }),
1063
+
1064
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
1065
+ if (signal?.aborted) {
1066
+ return {
1067
+ content: [{ type: "text", text: "Cancelled" }],
1068
+ details: { question: params.question, options: [], answer: null, cancelled: true } as AskToolDetails,
1069
+ };
1070
+ }
1071
+
1072
+ const {
1073
+ question,
1074
+ context,
1075
+ options: rawOptions = [],
1076
+ allowMultiple = false,
1077
+ allowFreeform = true,
1078
+ timeout,
1079
+ } = params as AskParams;
1080
+ const options = normalizeOptions(rawOptions);
1081
+ const normalizedContext = context?.trim() || undefined;
1082
+
1083
+ if (!ctx.hasUI || !ctx.ui) {
1084
+ const optionText = options.length > 0 ? `\n\nOptions:\n${formatOptionsForMessage(options)}` : "";
1085
+ const freeformHint = allowFreeform ? "\n\nYou can also answer freely." : "";
1086
+ const contextText = normalizedContext ? `\n\nContext:\n${normalizedContext}` : "";
1087
+ return {
1088
+ content: [
1089
+ {
1090
+ type: "text",
1091
+ text: `Ask requires interactive mode. Please answer:\n\n${question}${contextText}${optionText}${freeformHint}`,
1092
+ },
1093
+ ],
1094
+ isError: true,
1095
+ details: { question, context: normalizedContext, options, answer: null, cancelled: true } as AskToolDetails,
1096
+ };
1097
+ }
1098
+
1099
+ // If no options provided, fall back to freeform input prompt.
1100
+ if (options.length === 0) {
1101
+ const prompt = normalizedContext ? `${question}\n\nContext:\n${normalizedContext}` : question;
1102
+ const answer = await ctx.ui.input(prompt, "Type your answer...", timeout ? { timeout } : undefined);
1103
+
1104
+ if (!answer) {
1105
+ return {
1106
+ content: [{ type: "text", text: "User cancelled the question" }],
1107
+ details: { question, context: normalizedContext, options, answer: null, cancelled: true } as AskToolDetails,
1108
+ };
1109
+ }
1110
+
1111
+ pi.events.emit("ask:answered", { question, context: normalizedContext, answer, wasCustom: true });
1112
+ return {
1113
+ content: [{ type: "text", text: `User answered: ${answer}` }],
1114
+ details: { question, context: normalizedContext, options, answer, cancelled: false, wasCustom: true } as AskToolDetails,
1115
+ };
1116
+ }
1117
+
1118
+ onUpdate?.({
1119
+ content: [{ type: "text", text: "Waiting for user input..." }],
1120
+ details: { question, context: normalizedContext, options, answer: null, cancelled: false },
1121
+ });
1122
+
1123
+ let result: AskUIResult | null;
1124
+ try {
1125
+ // custom() returns undefined in RPC/headless mode — fall back to dialog methods
1126
+ const customResult = await ctx.ui.custom<AskUIResult | null>(
1127
+ (tui, theme, keybindings, done) => {
1128
+ // Wire AbortSignal so agent cancellation auto-dismisses the overlay
1129
+ if (signal) {
1130
+ const onAbort = () => done(null);
1131
+ signal.addEventListener("abort", onAbort, { once: true });
1132
+ }
1133
+
1134
+ // Wire timeout for overlay mode
1135
+ if (timeout && timeout > 0) {
1136
+ setTimeout(() => done(null), timeout);
1137
+ }
1138
+
1139
+ return new AskComponent(
1140
+ question,
1141
+ normalizedContext,
1142
+ options,
1143
+ allowMultiple,
1144
+ allowFreeform,
1145
+ tui,
1146
+ theme,
1147
+ keybindings,
1148
+ done,
1149
+ );
1150
+ },
1151
+ {
1152
+ overlay: true,
1153
+ overlayOptions: {
1154
+ anchor: "center",
1155
+ width: ASK_OVERLAY_WIDTH,
1156
+ minWidth: ASK_OVERLAY_MIN_WIDTH,
1157
+ maxHeight: "85%",
1158
+ margin: 1,
1159
+ },
1160
+ },
1161
+ );
1162
+
1163
+ if (customResult !== undefined) {
1164
+ result = customResult;
1165
+ } else {
1166
+ // RPC/headless mode: degrade to select()/input() dialog protocol
1167
+ result = await askViaDialogs(ctx.ui, question, normalizedContext, options, allowMultiple, allowFreeform, timeout);
1168
+ }
1169
+ } catch (error) {
1170
+ const message =
1171
+ error instanceof Error ? `${error.message}\n${error.stack ?? ""}` : String(error);
1172
+ return {
1173
+ content: [{ type: "text", text: `Ask tool failed: ${message}` }],
1174
+ isError: true,
1175
+ details: { error: message },
1176
+ };
1177
+ }
1178
+
1179
+ if (result === null) {
1180
+ pi.events.emit("ask:cancelled", { question, context: normalizedContext, options });
1181
+ return {
1182
+ content: [{ type: "text", text: "User cancelled the question" }],
1183
+ details: { question, context: normalizedContext, options, answer: null, cancelled: true } as AskToolDetails,
1184
+ };
1185
+ }
1186
+
1187
+ pi.events.emit("ask:answered", {
1188
+ question,
1189
+ context: normalizedContext,
1190
+ answer: result.answer,
1191
+ wasCustom: result.wasCustom,
1192
+ });
1193
+ return {
1194
+ content: [{ type: "text", text: `User answered: ${result.answer}` }],
1195
+ details: {
1196
+ question,
1197
+ context: normalizedContext,
1198
+ options,
1199
+ answer: result.answer,
1200
+ cancelled: false,
1201
+ wasCustom: result.wasCustom,
1202
+ } as AskToolDetails,
1203
+ };
1204
+ },
1205
+
1206
+ renderCall(args, theme) {
1207
+ const question = (args.question as string) || "";
1208
+ const rawOptions = Array.isArray(args.options) ? args.options : [];
1209
+ let text = theme.fg("toolTitle", theme.bold("ask_user "));
1210
+ text += theme.fg("muted", question);
1211
+ if (rawOptions.length > 0) {
1212
+ const labels = rawOptions.map((o: unknown) =>
1213
+ typeof o === "string" ? o : (o as QuestionOption)?.title ?? "",
1214
+ );
1215
+ text += "\n" + theme.fg("dim", ` ${rawOptions.length} option(s): ${labels.join(", ")}`);
1216
+ }
1217
+ if (args.allowMultiple) {
1218
+ text += theme.fg("dim", " [multi-select]");
1219
+ }
1220
+ return new Text(text, 0, 0);
1221
+ },
1222
+
1223
+ renderResult(result, options, theme) {
1224
+ const details = result.details as (AskToolDetails & { error?: string }) | undefined;
1225
+
1226
+ if (details?.error) {
1227
+ return new Text(theme.fg("error", `✗ ${details.error}`), 0, 0);
1228
+ }
1229
+
1230
+ if (options.isPartial) {
1231
+ const waitingText = result.content
1232
+ ?.filter((part: { type?: string; text?: string }) => part?.type === "text")
1233
+ .map((part: { text?: string }) => part.text ?? "")
1234
+ .join("\n")
1235
+ .trim() || "Waiting for user input...";
1236
+ return new Text(theme.fg("muted", waitingText), 0, 0);
1237
+ }
1238
+
1239
+ if (!details || details.cancelled) {
1240
+ return new Text(theme.fg("warning", "Cancelled"), 0, 0);
1241
+ }
1242
+
1243
+ const answer = details.answer ?? "";
1244
+ let text = theme.fg("success", "✓ ");
1245
+ if (details.wasCustom) {
1246
+ text += theme.fg("muted", "(wrote) ");
1247
+ }
1248
+ text += theme.fg("accent", answer);
1249
+
1250
+ if (options.expanded) {
1251
+ const selectedTitles = new Set(
1252
+ answer
1253
+ .split(",")
1254
+ .map((value) => value.trim())
1255
+ .filter(Boolean),
1256
+ );
1257
+ text += "\n" + theme.fg("dim", `Q: ${details.question}`);
1258
+ if (details.context) {
1259
+ text += "\n" + theme.fg("dim", details.context);
1260
+ }
1261
+ if (details.options && details.options.length > 0) {
1262
+ text += "\n" + theme.fg("dim", "Options:");
1263
+ for (const opt of details.options) {
1264
+ const desc = opt.description ? ` — ${opt.description}` : "";
1265
+ const isSelected = opt.title === answer || selectedTitles.has(opt.title);
1266
+ const marker = isSelected ? theme.fg("success", "●") : theme.fg("dim", "○");
1267
+ text += `\n ${marker} ${theme.fg("dim", opt.title)}${theme.fg("dim", desc)}`;
1268
+ }
1269
+ }
1270
+ }
1271
+
1272
+ return new Text(text, 0, 0);
1273
+ },
1274
+ });
1196
1275
  }