killeros 2.0.19 → 2.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,590 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ decodeKittyPrintable,
4
+ Editor,
5
+ Markdown,
6
+ truncateToWidth,
7
+ visibleWidth,
8
+ wrapTextWithAnsi,
9
+ type EditorTheme,
10
+ } from "@earendil-works/pi-tui";
11
+ import type { ThemeColor } from "@earendil-works/pi-coding-agent";
12
+
13
+ export interface DisplayOption {
14
+ label: string;
15
+ description?: string;
16
+ preview?: string;
17
+ originalIndex: number;
18
+ isOther: boolean;
19
+ }
20
+
21
+ export type QuestionSelection =
22
+ | { kind: "selected"; answer: string; originalIndex: number }
23
+ | { kind: "custom"; answer: string }
24
+ | { kind: "multiple"; answers: string[]; selectedIndices: number[]; customAnswer?: string }
25
+ | { kind: "cancelled" }
26
+ | { kind: "aborted" };
27
+
28
+ export const CUSTOM_INPUT_MAX_CHARACTERS = 4_000;
29
+ export const CUSTOM_INPUT_HISTORY_LIMIT = 100;
30
+ export const CUSTOM_INPUT_HISTORY_BYTES = 64 * 1024;
31
+ export const FILTER_QUERY_MAX_CHARACTERS = 4_000;
32
+ export const FILTER_QUERY_MAX_BYTES = 16_000;
33
+
34
+ function isPrintableInput(data: string): boolean {
35
+ return data.length > 0 && !/[\u0000-\u001F\u007F-\u009F]/u.test(data);
36
+ }
37
+
38
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
39
+
40
+ function decodeQuestionFilterInput(data: string): string | undefined {
41
+ const kittyPrintable = decodeKittyPrintable(data);
42
+ if (kittyPrintable !== undefined) return isPrintableInput(kittyPrintable) ? kittyPrintable : undefined;
43
+
44
+ const pasteStart = "\x1B[200~";
45
+ const pasteEnd = "\x1B[201~";
46
+ const startIndex = data.indexOf(pasteStart);
47
+ const endIndex = data.indexOf(pasteEnd, startIndex + pasteStart.length);
48
+ if (startIndex >= 0 && endIndex >= 0) {
49
+ return data
50
+ .slice(startIndex + pasteStart.length, endIndex)
51
+ .replace(/\r\n|\r|\n/gu, "")
52
+ .replace(/\t/gu, " ")
53
+ .replace(/[\u0000-\u001F\u007F-\u009F]/gu, "");
54
+ }
55
+
56
+ return isPrintableInput(data) ? data : undefined;
57
+ }
58
+
59
+ function removeLastGrapheme(value: string): string {
60
+ const segments = [...graphemeSegmenter.segment(value)];
61
+ const last = segments.at(-1);
62
+ return last ? value.slice(0, last.index) : "";
63
+ }
64
+
65
+ function inputCharacterCount(value: string): number {
66
+ let count = 0;
67
+ for (const _character of value) count += 1;
68
+ return count;
69
+ }
70
+
71
+ export function oneLine(value: string): string {
72
+ return value.replace(/\s+/gu, " ").trim();
73
+ }
74
+
75
+ function boundedRenderLine(value: string, width: number, suffix: string): string {
76
+ return truncateToWidth(value.replace(/\r\n|\r|\n/gu, " "), width, suffix);
77
+ }
78
+
79
+ function visibleOptionRange(total: number, selected: number, capacity: number): { start: number; end: number } {
80
+ const size = Math.max(1, Math.min(total, capacity));
81
+ const start = Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
82
+ return { start, end: Math.min(total, start + size) };
83
+ }
84
+
85
+ function boundedQuestionLines(question: string, width: number, rowLimit: number): string[] {
86
+ const wrapped = wrapTextWithAnsi(question.replace(/\s+/gu, " ").trim(), width);
87
+ if (wrapped.length <= rowLimit) return wrapped;
88
+ const visible = wrapped.slice(0, rowLimit);
89
+ const finalIndex = rowLimit - 1;
90
+ const finalLine = visible[finalIndex];
91
+ if (finalLine !== undefined) visible[finalIndex] = truncateToWidth(finalLine, width, "…");
92
+ return visible;
93
+ }
94
+
95
+ function compactMultipleAnswers(answers: readonly string[], width: number): string {
96
+ const prefix = "✓ ";
97
+ if (answers.length === 0) return truncateToWidth(prefix + "No answers", width, "…");
98
+ const visible: string[] = [];
99
+ for (const [index, answer] of answers.entries()) {
100
+ const remaining = answers.length - index - 1;
101
+ const candidate = [...visible, oneLine(answer)].join(", ");
102
+ const suffix = remaining > 0 ? `, +${remaining} more` : "";
103
+ if (visibleWidth(prefix + candidate + suffix) > width) break;
104
+ visible.push(oneLine(answer));
105
+ }
106
+ if (visible.length === answers.length) return prefix + visible.join(", ");
107
+ const hidden = answers.length - visible.length;
108
+ if (visible.length === 0) return truncateToWidth(`${prefix}+${hidden} more`, width, "…");
109
+ return truncateToWidth(`${prefix}${visible.join(", ")}, +${hidden} more`, width, "…");
110
+ }
111
+
112
+ export class MultipleResultText {
113
+ private readonly answers: readonly string[];
114
+ private readonly expanded: boolean;
115
+ private readonly customAnswer: string | undefined;
116
+ private readonly color: (name: ThemeColor, text: string) => string;
117
+
118
+ constructor(
119
+ answers: readonly string[],
120
+ expanded: boolean,
121
+ customAnswer: string | undefined,
122
+ color: (name: ThemeColor, text: string) => string,
123
+ ) {
124
+ this.answers = answers;
125
+ this.expanded = expanded;
126
+ this.customAnswer = customAnswer;
127
+ this.color = color;
128
+ }
129
+
130
+ render(width: number): string[] {
131
+ if (width <= 0) return [];
132
+ if (!this.expanded) return [this.color("accent", compactMultipleAnswers(this.answers, width))];
133
+ return this.answers.flatMap((answer) => wrapTextWithAnsi(
134
+ `${this.color("success", "✓ ")}${answer === this.customAnswer ? this.color("muted", "(wrote) ") : ""}${this.color("accent", answer)}`,
135
+ width,
136
+ ));
137
+ }
138
+
139
+ invalidate(): void {}
140
+ }
141
+
142
+ export async function openQuestionUi(config: {
143
+ ctx: ExtensionContext;
144
+ signal?: AbortSignal;
145
+ question: string;
146
+ options: DisplayOption[];
147
+ originalOptions: readonly { label: string }[];
148
+ mode: "single" | "multiple";
149
+ minSelections: number;
150
+ maxSelections: number;
151
+ customInputHistory: readonly string[];
152
+ rememberCustomInput: (value: string) => boolean;
153
+ }): Promise<QuestionSelection> {
154
+ const {
155
+ ctx,
156
+ signal,
157
+ question,
158
+ options: displayOptions,
159
+ originalOptions,
160
+ mode,
161
+ minSelections,
162
+ maxSelections,
163
+ customInputHistory,
164
+ rememberCustomInput,
165
+ } = config;
166
+ const options = displayOptions;
167
+ let finishFromAbort: (() => void) | undefined;
168
+ const resultPromise = ctx.ui.custom<QuestionSelection>((tui, theme, keybindings, done) => {
169
+ let optionIndex = 0;
170
+ type EditMode = "none" | "filter" | "custom";
171
+ let editMode: EditMode = "none";
172
+ let filterQuery = "";
173
+ const selectedOriginalIndices = new Set<number>();
174
+ let customAnswer: string | undefined;
175
+ let cachedWidth: number | undefined;
176
+ let cachedRows: number | undefined;
177
+ let cachedLines: string[] | undefined;
178
+ let completed = false;
179
+
180
+ const finish = (selection: QuestionSelection): void => {
181
+ if (completed) return;
182
+ completed = true;
183
+ done(selection);
184
+ };
185
+ finishFromAbort = () => finish({ kind: "aborted" });
186
+
187
+ const keyHint = (keybinding: Parameters<typeof keybindings.getKeys>[0], description: string): string => {
188
+ const keyText = keybindings.getKeys(keybinding)
189
+ .join("/")
190
+ .split("/")
191
+ .map((key) => key.split("+").map((part) => process.platform === "darwin" && part.toLowerCase() === "alt" ? "option" : part).join("+"))
192
+ .join("/");
193
+ return theme.fg("dim", keyText) + theme.fg("muted", ` ${description}`);
194
+ };
195
+
196
+ const editorTheme: EditorTheme = {
197
+ borderColor: (text) => theme.fg("accent", text),
198
+ selectList: {
199
+ selectedPrefix: (text) => theme.fg("accent", text),
200
+ selectedText: (text) => theme.fg("accent", text),
201
+ description: (text) => theme.fg("muted", text),
202
+ scrollInfo: (text) => theme.fg("dim", text),
203
+ noMatch: (text) => theme.fg("warning", text),
204
+ },
205
+ };
206
+ const editor = new Editor(tui, editorTheme);
207
+ customInputHistory.forEach((value) => editor.addToHistory(value));
208
+
209
+ const filteredOptions = (): DisplayOption[] => {
210
+ const query = filterQuery.trim().toLowerCase();
211
+ return options.filter((option) => option.isOther
212
+ || query.length === 0
213
+ || option.label.toLowerCase().includes(query)
214
+ || option.description?.toLowerCase().includes(query));
215
+ };
216
+ const selectedCount = (): number => selectedOriginalIndices.size + (customAnswer === undefined ? 0 : 1);
217
+ const orderedMultipleSelection = () => {
218
+ const selectedIndices = [...selectedOriginalIndices].sort((left, right) => left - right);
219
+ const predefined = selectedIndices.map((index) => {
220
+ const option = originalOptions[index - 1];
221
+ if (!option) throw new Error("Question selection no longer matches an available option");
222
+ return option.label;
223
+ });
224
+ return {
225
+ answers: customAnswer === undefined ? predefined : [...predefined, customAnswer],
226
+ selectedIndices,
227
+ ...(customAnswer === undefined ? {} : { customAnswer }),
228
+ };
229
+ };
230
+
231
+ const invalidate = (): void => {
232
+ cachedWidth = undefined;
233
+ cachedRows = undefined;
234
+ cachedLines = undefined;
235
+ editor.invalidate();
236
+ };
237
+ const refresh = (): void => {
238
+ invalidate();
239
+ tui.requestRender();
240
+ };
241
+ const notifyFilterLimit = (): void => ctx.ui.notify(
242
+ `Question filters are limited to ${FILTER_QUERY_MAX_CHARACTERS.toLocaleString()} characters and ${FILTER_QUERY_MAX_BYTES.toLocaleString()} bytes`,
243
+ "error",
244
+ );
245
+ const appendFilterInput = (value: string): void => {
246
+ const next = filterQuery + value;
247
+ if (inputCharacterCount(next) > FILTER_QUERY_MAX_CHARACTERS || Buffer.byteLength(next, "utf8") > FILTER_QUERY_MAX_BYTES) {
248
+ notifyFilterLimit();
249
+ return;
250
+ }
251
+ filterQuery = next;
252
+ optionIndex = 0;
253
+ refresh();
254
+ };
255
+ const togglePredefined = (option: DisplayOption): void => {
256
+ if (selectedOriginalIndices.has(option.originalIndex)) {
257
+ selectedOriginalIndices.delete(option.originalIndex);
258
+ refresh();
259
+ return;
260
+ }
261
+ if (selectedCount() >= maxSelections) {
262
+ ctx.ui.notify(`Select at most ${maxSelections} answer${maxSelections === 1 ? "" : "s"}`, "error");
263
+ return;
264
+ }
265
+ selectedOriginalIndices.add(option.originalIndex);
266
+ refresh();
267
+ };
268
+ const enterCustomMode = (): void => {
269
+ editMode = "custom";
270
+ editor.setText(mode === "multiple" ? customAnswer ?? "" : "");
271
+ refresh();
272
+ };
273
+ const enterFilterMode = (): void => {
274
+ editMode = "filter";
275
+ editor.setText(filterQuery);
276
+ refresh();
277
+ };
278
+
279
+ editor.onSubmit = (value) => {
280
+ if (editMode === "filter") {
281
+ filterQuery = value;
282
+ optionIndex = 0;
283
+ editMode = "none";
284
+ editor.setText("");
285
+ refresh();
286
+ return;
287
+ }
288
+ const answer = value.trim();
289
+ if (answer) {
290
+ if (inputCharacterCount(answer) > CUSTOM_INPUT_MAX_CHARACTERS) {
291
+ ctx.ui.notify(`Custom answers are limited to ${CUSTOM_INPUT_MAX_CHARACTERS} characters`, "error");
292
+ return;
293
+ }
294
+ if (mode === "multiple") {
295
+ const addsSelection = customAnswer === undefined;
296
+ if (addsSelection && selectedCount() >= maxSelections) {
297
+ editor.setText(value);
298
+ ctx.ui.notify(`Select at most ${maxSelections} answer${maxSelections === 1 ? "" : "s"}`, "error");
299
+ refresh();
300
+ return;
301
+ }
302
+ if (!rememberCustomInput(answer)) {
303
+ editor.setText(value);
304
+ ctx.ui.notify(`Custom answer history is limited to ${CUSTOM_INPUT_HISTORY_BYTES} bytes`, "error");
305
+ refresh();
306
+ return;
307
+ }
308
+ customAnswer = answer;
309
+ editMode = "none";
310
+ editor.setText("");
311
+ refresh();
312
+ return;
313
+ }
314
+ if (!rememberCustomInput(answer)) {
315
+ ctx.ui.notify(`Custom answer history is limited to ${CUSTOM_INPUT_HISTORY_BYTES} bytes`, "error");
316
+ return;
317
+ }
318
+ finish({ kind: "custom", answer });
319
+ return;
320
+ }
321
+ editMode = "none";
322
+ editor.setText("");
323
+ refresh();
324
+ };
325
+
326
+ const handleEditorInput = (data: string): void => {
327
+ if (keybindings.matches(data, "tui.select.cancel")) {
328
+ editMode = "none";
329
+ editor.setText("");
330
+ refresh();
331
+ return;
332
+ }
333
+ const before = editor.getExpandedText();
334
+ editor.handleInput(data);
335
+ const after = editor.getExpandedText();
336
+ const overLimit = editMode === "filter"
337
+ ? inputCharacterCount(after) > FILTER_QUERY_MAX_CHARACTERS || Buffer.byteLength(after, "utf8") > FILTER_QUERY_MAX_BYTES
338
+ : inputCharacterCount(after) > CUSTOM_INPUT_MAX_CHARACTERS;
339
+ if (overLimit) {
340
+ editor.setText(before);
341
+ if (editMode === "filter") notifyFilterLimit();
342
+ else ctx.ui.notify(`Custom answers are limited to ${CUSTOM_INPUT_MAX_CHARACTERS} characters`, "error");
343
+ }
344
+ refresh();
345
+ };
346
+
347
+ const handleInput = (data: string): void => {
348
+ if (editMode !== "none") {
349
+ handleEditorInput(data);
350
+ return;
351
+ }
352
+
353
+ const visibleOptions = filteredOptions();
354
+ if (optionIndex >= visibleOptions.length) optionIndex = Math.max(0, visibleOptions.length - 1);
355
+ const pageSize = Math.max(1, Math.min(5, Math.ceil(Math.max(1, tui.terminal.rows - 5) / 2)));
356
+ if (keybindings.matches(data, "tui.select.up")) {
357
+ optionIndex = Math.max(0, optionIndex - 1);
358
+ refresh();
359
+ return;
360
+ }
361
+ if (keybindings.matches(data, "tui.select.down")) {
362
+ optionIndex = Math.min(visibleOptions.length - 1, optionIndex + 1);
363
+ refresh();
364
+ return;
365
+ }
366
+ if (keybindings.matches(data, "tui.select.pageUp")) {
367
+ optionIndex = Math.max(0, optionIndex - pageSize);
368
+ refresh();
369
+ return;
370
+ }
371
+ if (keybindings.matches(data, "tui.select.pageDown")) {
372
+ optionIndex = Math.min(visibleOptions.length - 1, optionIndex + pageSize);
373
+ refresh();
374
+ return;
375
+ }
376
+
377
+ const printableInput = decodeQuestionFilterInput(data);
378
+ const isPasteInput = data.includes("\x1B[200~");
379
+ if (mode === "multiple") {
380
+ const selected = visibleOptions[optionIndex];
381
+ if (!isPasteInput && printableInput === " ") {
382
+ if (!selected) return;
383
+ if (selected.isOther) {
384
+ if (customAnswer !== undefined) {
385
+ customAnswer = undefined;
386
+ refresh();
387
+ }
388
+ } else togglePredefined(selected);
389
+ return;
390
+ }
391
+ if (!isPasteInput && printableInput === "/") {
392
+ enterFilterMode();
393
+ return;
394
+ }
395
+ if (!isPasteInput && printableInput && /^[1-9]$/u.test(printableInput)) {
396
+ const numbered = visibleOptions[Number(printableInput) - 1];
397
+ if (!numbered) return;
398
+ if (numbered.isOther) enterCustomMode();
399
+ else togglePredefined(numbered);
400
+ return;
401
+ }
402
+ if (keybindings.matches(data, "tui.select.confirm")) {
403
+ if (selected?.isOther) {
404
+ enterCustomMode();
405
+ } else if (selectedCount() < minSelections) {
406
+ ctx.ui.notify(`Select at least ${minSelections} answer${minSelections === 1 ? "" : "s"}`, "error");
407
+ } else {
408
+ finish({ kind: "multiple", ...orderedMultipleSelection() });
409
+ }
410
+ return;
411
+ }
412
+ if (keybindings.matches(data, "tui.select.cancel")) {
413
+ if (filterQuery) {
414
+ filterQuery = "";
415
+ optionIndex = 0;
416
+ refresh();
417
+ } else finish({ kind: "cancelled" });
418
+ return;
419
+ }
420
+ return;
421
+ }
422
+
423
+ if (keybindings.matches(data, "tui.select.confirm")) {
424
+ const selected = visibleOptions[optionIndex];
425
+ if (!selected) return;
426
+ if (selected.isOther) enterCustomMode();
427
+ else finish({ kind: "selected", answer: selected.label, originalIndex: selected.originalIndex });
428
+ return;
429
+ }
430
+ if (keybindings.matches(data, "tui.select.cancel")) {
431
+ if (filterQuery) {
432
+ filterQuery = "";
433
+ optionIndex = 0;
434
+ refresh();
435
+ } else finish({ kind: "cancelled" });
436
+ return;
437
+ }
438
+ if (keybindings.matches(data, "tui.editor.deleteCharBackward")) {
439
+ if (filterQuery) {
440
+ filterQuery = removeLastGrapheme(filterQuery);
441
+ optionIndex = 0;
442
+ refresh();
443
+ }
444
+ return;
445
+ }
446
+ if (!isPasteInput && printableInput && /^[1-9]$/u.test(printableInput)) {
447
+ const selected = visibleOptions[Number(printableInput) - 1];
448
+ if (!selected) return;
449
+ if (selected.isOther) enterCustomMode();
450
+ else finish({ kind: "selected", answer: selected.label, originalIndex: selected.originalIndex });
451
+ return;
452
+ }
453
+ if (printableInput) appendFilterInput(printableInput);
454
+ };
455
+
456
+ const render = (width: number): string[] => {
457
+ if (width <= 0) return [];
458
+ const rowBudget = tui.terminal.rows;
459
+ if (rowBudget <= 0) return [];
460
+ if (cachedLines && cachedWidth === width && cachedRows === rowBudget) return cachedLines;
461
+ const visibleOptions = filteredOptions();
462
+ if (optionIndex >= visibleOptions.length) optionIndex = Math.max(0, visibleOptions.length - 1);
463
+ const selected = visibleOptions[optionIndex];
464
+ const position = `Option ${Math.min(optionIndex + 1, visibleOptions.length)}/${visibleOptions.length}`;
465
+ const editorText = editor.getExpandedText();
466
+ const editorCount = inputCharacterCount(editorText).toLocaleString();
467
+ const filterCount = inputCharacterCount(editMode === "filter" ? editorText : filterQuery).toLocaleString();
468
+ const compactDraft = editorText.replace(/\r\n|\r|\n/gu, " ↵ ") || (editMode === "filter" ? "Type a filter" : "Type an answer");
469
+ const selectionRange = minSelections === maxSelections ? `${minSelections}` : `${minSelections}–${maxSelections}`;
470
+ const selectionStatus = `Selected ${selectedCount()} · required ${selectionRange}`;
471
+ const optionLabel = (option: DisplayOption, index: number): string => {
472
+ if (mode === "single") return `${index === optionIndex ? ">" : " "} ${index + 1}. ${option.label}`;
473
+ const checked = option.isOther ? customAnswer !== undefined : selectedOriginalIndices.has(option.originalIndex);
474
+ const label = option.isOther && customAnswer !== undefined ? `Custom: ${oneLine(customAnswer)}` : option.label;
475
+ return `${index === optionIndex ? ">" : " "} ${checked ? "[x]" : "[ ]"} ${index + 1}. ${label}`;
476
+ };
477
+ const browseHint = mode === "multiple"
478
+ ? `space toggle • / filter • ${keyHint("tui.select.confirm", selected?.isOther ? (customAnswer ? "edit custom" : "add custom") : "submit")} • ${keyHint("tui.select.cancel", filterQuery ? "clear filter" : "cancel")}`
479
+ : `${keyHint("tui.select.confirm", "select")} • ${keyHint("tui.select.cancel", "cancel")}`;
480
+ const editHint = `${keyHint("tui.input.submit", editMode === "filter" ? "apply" : "submit")} • ${keyHint("tui.select.cancel", "options")}`;
481
+
482
+ let lines: string[];
483
+ if (rowBudget <= 2) {
484
+ if (editMode !== "none") lines = [`${editMode === "filter" ? "Filter" : "Answer"} ${editMode === "filter" ? filterCount : editorCount}/${CUSTOM_INPUT_MAX_CHARACTERS.toLocaleString()}`, compactDraft];
485
+ else if (mode === "multiple") {
486
+ const focusedRow = selected ? optionLabel(selected, optionIndex) : "";
487
+ const compactSelectionStatus = visibleWidth(selectionStatus) <= width
488
+ ? selectionStatus
489
+ : `Selected ${selectedCount()}`;
490
+ lines = focusedRow && visibleWidth(focusedRow) <= width
491
+ ? [focusedRow, compactSelectionStatus]
492
+ : [compactSelectionStatus, focusedRow];
493
+ } else lines = [`${selected ? `> ${selected.label}` : "No matching options"} · ${position}`];
494
+ } else if (rowBudget <= 5) {
495
+ lines = [
496
+ ...boundedQuestionLines(question, width, Math.max(1, rowBudget - 3)),
497
+ editMode !== "none"
498
+ ? `${editMode === "filter" ? "Filter" : "Answer"} ${editMode === "filter" ? filterCount : editorCount}/${CUSTOM_INPUT_MAX_CHARACTERS.toLocaleString()}`
499
+ : selected ? optionLabel(selected, optionIndex) : "No matching options",
500
+ editMode !== "none" ? compactDraft : mode === "multiple" ? selectionStatus : filterQuery ? `Filter ${filterCount}/${FILTER_QUERY_MAX_CHARACTERS.toLocaleString()}` : position,
501
+ editMode !== "none" ? editHint : browseHint,
502
+ ];
503
+ } else {
504
+ const questionLines = boundedQuestionLines(question, width, Math.max(1, rowBudget - 5));
505
+ const contentRows = rowBudget - questionLines.length - 4;
506
+ const optionCapacity = Math.max(1, Math.min(5, Math.ceil(contentRows / 2)));
507
+ const detailCapacity = Math.max(0, contentRows - optionCapacity);
508
+ const { start, end } = visibleOptionRange(visibleOptions.length, optionIndex, optionCapacity);
509
+ const hiddenAbove = start > 0 ? `↑ ${start}` : "";
510
+ const hiddenBelowCount = visibleOptions.length - end;
511
+ const hiddenBelow = hiddenBelowCount > 0 ? `↓ ${hiddenBelowCount}` : "";
512
+ const hiddenStatus = [hiddenAbove, hiddenBelow].filter(Boolean).join(" · ");
513
+ const progress = editMode === "filter"
514
+ ? `Filter ${filterCount}/${FILTER_QUERY_MAX_CHARACTERS.toLocaleString()}`
515
+ : editMode === "custom"
516
+ ? `Answer ${editorCount}/${CUSTOM_INPUT_MAX_CHARACTERS.toLocaleString()}`
517
+ : mode === "multiple"
518
+ ? `${selectionStatus}${hiddenStatus ? ` · ${hiddenStatus}` : ""}`
519
+ : filterQuery ? `Filter ${filterCount}/${FILTER_QUERY_MAX_CHARACTERS.toLocaleString()} · ${position}` : `${position}${hiddenStatus ? ` · ${hiddenStatus}` : ""}`;
520
+ const navigationHint = editMode !== "none" ? editHint : mode === "multiple"
521
+ ? `${keyHint("tui.select.up", "up")} • ${keyHint("tui.select.down", "down")} • ${browseHint}`
522
+ : `${keyHint("tui.select.up", "up")} • ${keyHint("tui.select.down", "down")} • ${keyHint("tui.select.confirm", "select")} • ${keyHint("tui.select.cancel", filterQuery ? "clear filter" : "cancel")}`;
523
+ lines = [
524
+ theme.fg("accent", "─".repeat(width)),
525
+ ...questionLines.map((line) => theme.fg("text", line)),
526
+ theme.fg("muted", truncateToWidth(` ${progress}`, width, "…")),
527
+ ];
528
+ if (editMode !== "none") {
529
+ const editorLines = editor.render(width);
530
+ const draftLines = editorLines.length > 2 ? editorLines.slice(1, -1) : editorLines;
531
+ lines.push(...(draftLines.length > 0 ? draftLines : [editMode === "filter" ? "Type a filter" : "Type an answer"]).slice(-contentRows));
532
+ } else {
533
+ for (let index = start; index < end; index += 1) {
534
+ const option = visibleOptions[index];
535
+ if (!option) continue;
536
+ const color: ThemeColor = index === optionIndex ? "accent" : "text";
537
+ lines.push(theme.fg(color, truncateToWidth(optionLabel(option, index), width, "…")));
538
+ }
539
+ const detailLines: string[] = [];
540
+ if (selected?.description) detailLines.push(...wrapTextWithAnsi(theme.fg("muted", selected.description), width));
541
+ if (selected?.preview) {
542
+ detailLines.push(theme.fg("accent", theme.bold("Proposal preview")));
543
+ detailLines.push(...new Markdown(selected.preview, 0, 0, {
544
+ heading: (text) => theme.fg("accent", theme.bold(text)), link: (text) => theme.fg("accent", text),
545
+ linkUrl: (text) => theme.fg("dim", text), code: (text) => theme.fg("mdCode", text),
546
+ codeBlock: (text) => theme.fg("mdCodeBlock", text), codeBlockBorder: (text) => theme.fg("mdCodeBlockBorder", text),
547
+ quote: (text) => theme.fg("mdQuote", text), quoteBorder: (text) => theme.fg("mdQuoteBorder", text),
548
+ hr: (text) => theme.fg("mdHr", text), listBullet: (text) => theme.fg("mdListBullet", text),
549
+ bold: (text) => theme.bold(text), italic: (text) => theme.italic(text), strikethrough: (text) => theme.strikethrough(text),
550
+ underline: (text) => theme.underline(text),
551
+ }, { color: (text) => theme.fg("muted", text) }).render(width));
552
+ }
553
+ if (detailCapacity > 0 && detailLines.length > detailCapacity) {
554
+ const visibleDetailRows = Math.max(0, detailCapacity - 1);
555
+ lines.push(...detailLines.slice(0, visibleDetailRows));
556
+ const hiddenRows = detailLines.length - visibleDetailRows;
557
+ lines.push(theme.fg("dim", `… ${hiddenRows} more line${hiddenRows === 1 ? "" : "s"}`));
558
+ } else lines.push(...detailLines.slice(0, detailCapacity));
559
+ }
560
+ lines.push(theme.fg("dim", truncateToWidth(` ${navigationHint}`, width, "…")));
561
+ lines.push(theme.fg("accent", "─".repeat(width)));
562
+ }
563
+ cachedWidth = width;
564
+ cachedRows = rowBudget;
565
+ cachedLines = lines.slice(0, rowBudget).map((line) => boundedRenderLine(line, width, rowBudget <= 5 ? "…" : ""));
566
+ return cachedLines;
567
+ };
568
+
569
+ let focused = false;
570
+ return {
571
+ get focused(): boolean { return focused; },
572
+ set focused(value: boolean) { focused = value; editor.focused = value; },
573
+ render,
574
+ handleInput,
575
+ invalidate,
576
+ };
577
+ });
578
+
579
+ const abortHandler = (): void => finishFromAbort?.();
580
+ signal?.addEventListener("abort", abortHandler, { once: true });
581
+ if (signal?.aborted) abortHandler();
582
+ let result: QuestionSelection;
583
+ try {
584
+ result = await resultPromise;
585
+ } finally {
586
+ signal?.removeEventListener("abort", abortHandler);
587
+ }
588
+
589
+ return result;
590
+ }