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.
@@ -1,21 +1,11 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
2
  import {
3
3
  type ExtensionAPI,
4
- type ExtensionContext,
5
- type ThemeColor,
6
4
  type ToolDefinition,
7
5
  } from "@earendil-works/pi-coding-agent";
8
- import {
9
- decodeKittyPrintable,
10
- Editor,
11
- Markdown,
12
- truncateToWidth,
13
- visibleWidth,
14
- wrapTextWithAnsi,
15
- type EditorTheme,
16
- } from "@earendil-works/pi-tui";
17
6
  import { Type, type Static } from "typebox";
18
7
  import { BoundedText } from "./bounded-text.ts";
8
+ import { CUSTOM_INPUT_HISTORY_BYTES, CUSTOM_INPUT_HISTORY_LIMIT, FILTER_QUERY_MAX_BYTES, FILTER_QUERY_MAX_CHARACTERS, MultipleResultText, oneLine, openQuestionUi, type DisplayOption } from "./question-ui.ts";
19
9
  import { safeTerminalText } from "./safe-terminal-text.ts";
20
10
 
21
11
  const OptionSchema = Type.Object({
@@ -74,14 +64,6 @@ function normalizeQuestionSelection(params: QuestionParamsValue): NormalizedQues
74
64
  return { mode, minSelections, maxSelections };
75
65
  }
76
66
 
77
- interface DisplayOption {
78
- label: string;
79
- description?: string;
80
- preview?: string;
81
- originalIndex: number;
82
- isOther: boolean;
83
- }
84
-
85
67
  interface SingleQuestionDetails {
86
68
  question: string;
87
69
  options: string[];
@@ -103,121 +85,6 @@ interface MultipleQuestionDetails {
103
85
 
104
86
  type QuestionDetails = SingleQuestionDetails | MultipleQuestionDetails;
105
87
 
106
- type QuestionSelection =
107
- | { kind: "selected"; answer: string; originalIndex: number }
108
- | { kind: "custom"; answer: string }
109
- | { kind: "multiple"; answers: string[]; selectedIndices: number[]; customAnswer?: string }
110
- | { kind: "cancelled" }
111
- | { kind: "aborted" };
112
-
113
- const CUSTOM_INPUT_MAX_CHARACTERS = 4_000;
114
- const CUSTOM_INPUT_HISTORY_LIMIT = 100;
115
- const CUSTOM_INPUT_HISTORY_BYTES = 64 * 1024;
116
- const FILTER_QUERY_MAX_CHARACTERS = 4_000;
117
- const FILTER_QUERY_MAX_BYTES = 16_000;
118
-
119
- function isPrintableInput(data: string): boolean {
120
- return data.length > 0 && !/[\u0000-\u001F\u007F-\u009F]/u.test(data);
121
- }
122
-
123
- const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
124
-
125
- function decodeQuestionFilterInput(data: string): string | undefined {
126
- const kittyPrintable = decodeKittyPrintable(data);
127
- if (kittyPrintable !== undefined) return isPrintableInput(kittyPrintable) ? kittyPrintable : undefined;
128
-
129
- const pasteStart = "\x1B[200~";
130
- const pasteEnd = "\x1B[201~";
131
- const startIndex = data.indexOf(pasteStart);
132
- const endIndex = data.indexOf(pasteEnd, startIndex + pasteStart.length);
133
- if (startIndex >= 0 && endIndex >= 0) {
134
- return data
135
- .slice(startIndex + pasteStart.length, endIndex)
136
- .replace(/\r\n|\r|\n/gu, "")
137
- .replace(/\t/gu, " ")
138
- .replace(/[\u0000-\u001F\u007F-\u009F]/gu, "");
139
- }
140
-
141
- return isPrintableInput(data) ? data : undefined;
142
- }
143
-
144
- function removeLastGrapheme(value: string): string {
145
- const segments = [...graphemeSegmenter.segment(value)];
146
- const last = segments.at(-1);
147
- return last ? value.slice(0, last.index) : "";
148
- }
149
-
150
- function oneLine(value: string): string {
151
- return value.replace(/\s+/gu, " ").trim();
152
- }
153
-
154
- function boundedRenderLine(value: string, width: number, suffix: string): string {
155
- return truncateToWidth(value.replace(/\r\n|\r|\n/gu, " "), width, suffix);
156
- }
157
-
158
- function visibleOptionRange(total: number, selected: number, capacity: number): { start: number; end: number } {
159
- const size = Math.max(1, Math.min(total, capacity));
160
- const start = Math.max(0, Math.min(selected - Math.floor(size / 2), total - size));
161
- return { start, end: Math.min(total, start + size) };
162
- }
163
-
164
- function boundedQuestionLines(question: string, width: number, rowLimit: number): string[] {
165
- const wrapped = wrapTextWithAnsi(question.replace(/\s+/gu, " ").trim(), width);
166
- if (wrapped.length <= rowLimit) return wrapped;
167
- const visible = wrapped.slice(0, rowLimit);
168
- const finalIndex = rowLimit - 1;
169
- const finalLine = visible[finalIndex];
170
- if (finalLine !== undefined) visible[finalIndex] = truncateToWidth(finalLine, width, "…");
171
- return visible;
172
- }
173
-
174
- function compactMultipleAnswers(answers: readonly string[], width: number): string {
175
- const prefix = "✓ ";
176
- if (answers.length === 0) return truncateToWidth(prefix + "No answers", width, "…");
177
- const visible: string[] = [];
178
- for (const [index, answer] of answers.entries()) {
179
- const remaining = answers.length - index - 1;
180
- const candidate = [...visible, oneLine(answer)].join(", ");
181
- const suffix = remaining > 0 ? `, +${remaining} more` : "";
182
- if (visibleWidth(prefix + candidate + suffix) > width) break;
183
- visible.push(oneLine(answer));
184
- }
185
- if (visible.length === answers.length) return prefix + visible.join(", ");
186
- const hidden = answers.length - visible.length;
187
- if (visible.length === 0) return truncateToWidth(`${prefix}+${hidden} more`, width, "…");
188
- return truncateToWidth(`${prefix}${visible.join(", ")}, +${hidden} more`, width, "…");
189
- }
190
-
191
- class MultipleResultText {
192
- private readonly answers: readonly string[];
193
- private readonly expanded: boolean;
194
- private readonly customAnswer: string | undefined;
195
- private readonly color: (name: ThemeColor, text: string) => string;
196
-
197
- constructor(
198
- answers: readonly string[],
199
- expanded: boolean,
200
- customAnswer: string | undefined,
201
- color: (name: ThemeColor, text: string) => string,
202
- ) {
203
- this.answers = answers;
204
- this.expanded = expanded;
205
- this.customAnswer = customAnswer;
206
- this.color = color;
207
- }
208
-
209
- render(width: number): string[] {
210
- if (width <= 0) return [];
211
- if (!this.expanded) return [this.color("accent", compactMultipleAnswers(this.answers, width))];
212
- return this.answers.flatMap((answer) => wrapTextWithAnsi(
213
- `${this.color("success", "✓ ")}${answer === this.customAnswer ? this.color("muted", "(wrote) ") : ""}${this.color("accent", answer)}`,
214
- width,
215
- ));
216
- }
217
-
218
- invalidate(): void {}
219
- }
220
-
221
88
  export function registerQuestionTool(pi: ExtensionAPI): void {
222
89
  const customInputHistory: string[] = [];
223
90
  let customInputHistoryBytes = 0;
@@ -242,11 +109,6 @@ export function registerQuestionTool(pi: ExtensionAPI): void {
242
109
  customInputHistoryBytes += bytes;
243
110
  return true;
244
111
  };
245
- const inputCharacterCount = (value: string): number => {
246
- let count = 0;
247
- for (const _character of value) count += 1;
248
- return count;
249
- };
250
112
  pi.on("session_start", clearCustomInputHistory);
251
113
  pi.on("session_tree", clearCustomInputHistory);
252
114
  pi.on("session_shutdown", clearCustomInputHistory);
@@ -280,428 +142,19 @@ export function registerQuestionTool(pi: ExtensionAPI): void {
280
142
  { label: "Type a custom answer", originalIndex: params.options.length + 1, isOther: true },
281
143
  ];
282
144
 
283
- let finishFromAbort: (() => void) | undefined;
284
- const resultPromise = ctx.ui.custom<QuestionSelection>((tui, theme, keybindings, done) => {
285
- let optionIndex = 0;
286
- type EditMode = "none" | "filter" | "custom";
287
- let editMode: EditMode = "none";
288
- let filterQuery = "";
289
- const selectedOriginalIndices = new Set<number>();
290
- let customAnswer: string | undefined;
291
- let cachedWidth: number | undefined;
292
- let cachedRows: number | undefined;
293
- let cachedLines: string[] | undefined;
294
- let completed = false;
295
-
296
- const finish = (selection: QuestionSelection): void => {
297
- if (completed) return;
298
- completed = true;
299
- done(selection);
300
- };
301
- finishFromAbort = () => finish({ kind: "aborted" });
302
-
303
- const keyHint = (keybinding: Parameters<typeof keybindings.getKeys>[0], description: string): string => {
304
- const keyText = keybindings.getKeys(keybinding)
305
- .join("/")
306
- .split("/")
307
- .map((key) => key.split("+").map((part) => process.platform === "darwin" && part.toLowerCase() === "alt" ? "option" : part).join("+"))
308
- .join("/");
309
- return theme.fg("dim", keyText) + theme.fg("muted", ` ${description}`);
310
- };
311
-
312
- const editorTheme: EditorTheme = {
313
- borderColor: (text) => theme.fg("accent", text),
314
- selectList: {
315
- selectedPrefix: (text) => theme.fg("accent", text),
316
- selectedText: (text) => theme.fg("accent", text),
317
- description: (text) => theme.fg("muted", text),
318
- scrollInfo: (text) => theme.fg("dim", text),
319
- noMatch: (text) => theme.fg("warning", text),
320
- },
321
- };
322
- const editor = new Editor(tui, editorTheme);
323
- customInputHistory.forEach((value) => editor.addToHistory(value));
324
-
325
- const filteredOptions = (): DisplayOption[] => {
326
- const query = filterQuery.trim().toLowerCase();
327
- return options.filter((option) => option.isOther
328
- || query.length === 0
329
- || option.label.toLowerCase().includes(query)
330
- || option.description?.toLowerCase().includes(query));
331
- };
332
- const selectedCount = (): number => selectedOriginalIndices.size + (customAnswer === undefined ? 0 : 1);
333
- const orderedMultipleSelection = () => {
334
- const selectedIndices = [...selectedOriginalIndices].sort((left, right) => left - right);
335
- const predefined = selectedIndices.map((index) => {
336
- const option = params.options[index - 1];
337
- if (!option) throw new Error("Question selection no longer matches an available option");
338
- return option.label;
339
- });
340
- return {
341
- answers: customAnswer === undefined ? predefined : [...predefined, customAnswer],
342
- selectedIndices,
343
- ...(customAnswer === undefined ? {} : { customAnswer }),
344
- };
345
- };
346
-
347
- const invalidate = (): void => {
348
- cachedWidth = undefined;
349
- cachedRows = undefined;
350
- cachedLines = undefined;
351
- editor.invalidate();
352
- };
353
- const refresh = (): void => {
354
- invalidate();
355
- tui.requestRender();
356
- };
357
- const notifyFilterLimit = (): void => ctx.ui.notify(
358
- `Question filters are limited to ${FILTER_QUERY_MAX_CHARACTERS.toLocaleString()} characters and ${FILTER_QUERY_MAX_BYTES.toLocaleString()} bytes`,
359
- "error",
360
- );
361
- const appendFilterInput = (value: string): void => {
362
- const next = filterQuery + value;
363
- if (inputCharacterCount(next) > FILTER_QUERY_MAX_CHARACTERS || Buffer.byteLength(next, "utf8") > FILTER_QUERY_MAX_BYTES) {
364
- notifyFilterLimit();
365
- return;
366
- }
367
- filterQuery = next;
368
- optionIndex = 0;
369
- refresh();
370
- };
371
- const togglePredefined = (option: DisplayOption): void => {
372
- if (selectedOriginalIndices.has(option.originalIndex)) {
373
- selectedOriginalIndices.delete(option.originalIndex);
374
- refresh();
375
- return;
376
- }
377
- if (selectedCount() >= maxSelections) {
378
- ctx.ui.notify(`Select at most ${maxSelections} answer${maxSelections === 1 ? "" : "s"}`, "error");
379
- return;
380
- }
381
- selectedOriginalIndices.add(option.originalIndex);
382
- refresh();
383
- };
384
- const enterCustomMode = (): void => {
385
- editMode = "custom";
386
- editor.setText(mode === "multiple" ? customAnswer ?? "" : "");
387
- refresh();
388
- };
389
- const enterFilterMode = (): void => {
390
- editMode = "filter";
391
- editor.setText(filterQuery);
392
- refresh();
393
- };
394
-
395
- editor.onSubmit = (value) => {
396
- if (editMode === "filter") {
397
- filterQuery = value;
398
- optionIndex = 0;
399
- editMode = "none";
400
- editor.setText("");
401
- refresh();
402
- return;
403
- }
404
- const answer = value.trim();
405
- if (answer) {
406
- if (inputCharacterCount(answer) > CUSTOM_INPUT_MAX_CHARACTERS) {
407
- ctx.ui.notify(`Custom answers are limited to ${CUSTOM_INPUT_MAX_CHARACTERS} characters`, "error");
408
- return;
409
- }
410
- if (mode === "multiple") {
411
- const addsSelection = customAnswer === undefined;
412
- if (addsSelection && selectedCount() >= maxSelections) {
413
- editor.setText(value);
414
- ctx.ui.notify(`Select at most ${maxSelections} answer${maxSelections === 1 ? "" : "s"}`, "error");
415
- refresh();
416
- return;
417
- }
418
- if (!rememberCustomInput(answer)) {
419
- editor.setText(value);
420
- ctx.ui.notify(`Custom answer history is limited to ${CUSTOM_INPUT_HISTORY_BYTES} bytes`, "error");
421
- refresh();
422
- return;
423
- }
424
- customAnswer = answer;
425
- editMode = "none";
426
- editor.setText("");
427
- refresh();
428
- return;
429
- }
430
- if (!rememberCustomInput(answer)) {
431
- ctx.ui.notify(`Custom answer history is limited to ${CUSTOM_INPUT_HISTORY_BYTES} bytes`, "error");
432
- return;
433
- }
434
- finish({ kind: "custom", answer });
435
- return;
436
- }
437
- editMode = "none";
438
- editor.setText("");
439
- refresh();
440
- };
441
-
442
- const handleEditorInput = (data: string): void => {
443
- if (keybindings.matches(data, "tui.select.cancel")) {
444
- editMode = "none";
445
- editor.setText("");
446
- refresh();
447
- return;
448
- }
449
- const before = editor.getExpandedText();
450
- editor.handleInput(data);
451
- const after = editor.getExpandedText();
452
- const overLimit = editMode === "filter"
453
- ? inputCharacterCount(after) > FILTER_QUERY_MAX_CHARACTERS || Buffer.byteLength(after, "utf8") > FILTER_QUERY_MAX_BYTES
454
- : inputCharacterCount(after) > CUSTOM_INPUT_MAX_CHARACTERS;
455
- if (overLimit) {
456
- editor.setText(before);
457
- if (editMode === "filter") notifyFilterLimit();
458
- else ctx.ui.notify(`Custom answers are limited to ${CUSTOM_INPUT_MAX_CHARACTERS} characters`, "error");
459
- }
460
- refresh();
461
- };
462
-
463
- const handleInput = (data: string): void => {
464
- if (editMode !== "none") {
465
- handleEditorInput(data);
466
- return;
467
- }
468
-
469
- const visibleOptions = filteredOptions();
470
- if (optionIndex >= visibleOptions.length) optionIndex = Math.max(0, visibleOptions.length - 1);
471
- const pageSize = Math.max(1, Math.min(5, Math.ceil(Math.max(1, tui.terminal.rows - 5) / 2)));
472
- if (keybindings.matches(data, "tui.select.up")) {
473
- optionIndex = Math.max(0, optionIndex - 1);
474
- refresh();
475
- return;
476
- }
477
- if (keybindings.matches(data, "tui.select.down")) {
478
- optionIndex = Math.min(visibleOptions.length - 1, optionIndex + 1);
479
- refresh();
480
- return;
481
- }
482
- if (keybindings.matches(data, "tui.select.pageUp")) {
483
- optionIndex = Math.max(0, optionIndex - pageSize);
484
- refresh();
485
- return;
486
- }
487
- if (keybindings.matches(data, "tui.select.pageDown")) {
488
- optionIndex = Math.min(visibleOptions.length - 1, optionIndex + pageSize);
489
- refresh();
490
- return;
491
- }
492
-
493
- const printableInput = decodeQuestionFilterInput(data);
494
- const isPasteInput = data.includes("\x1B[200~");
495
- if (mode === "multiple") {
496
- const selected = visibleOptions[optionIndex];
497
- if (!isPasteInput && printableInput === " ") {
498
- if (!selected) return;
499
- if (selected.isOther) {
500
- if (customAnswer !== undefined) {
501
- customAnswer = undefined;
502
- refresh();
503
- }
504
- } else togglePredefined(selected);
505
- return;
506
- }
507
- if (!isPasteInput && printableInput === "/") {
508
- enterFilterMode();
509
- return;
510
- }
511
- if (!isPasteInput && printableInput && /^[1-9]$/u.test(printableInput)) {
512
- const numbered = visibleOptions[Number(printableInput) - 1];
513
- if (!numbered) return;
514
- if (numbered.isOther) enterCustomMode();
515
- else togglePredefined(numbered);
516
- return;
517
- }
518
- if (keybindings.matches(data, "tui.select.confirm")) {
519
- if (selected?.isOther) {
520
- enterCustomMode();
521
- } else if (selectedCount() < minSelections) {
522
- ctx.ui.notify(`Select at least ${minSelections} answer${minSelections === 1 ? "" : "s"}`, "error");
523
- } else {
524
- finish({ kind: "multiple", ...orderedMultipleSelection() });
525
- }
526
- return;
527
- }
528
- if (keybindings.matches(data, "tui.select.cancel")) {
529
- if (filterQuery) {
530
- filterQuery = "";
531
- optionIndex = 0;
532
- refresh();
533
- } else finish({ kind: "cancelled" });
534
- return;
535
- }
536
- return;
537
- }
538
-
539
- if (keybindings.matches(data, "tui.select.confirm")) {
540
- const selected = visibleOptions[optionIndex];
541
- if (!selected) return;
542
- if (selected.isOther) enterCustomMode();
543
- else finish({ kind: "selected", answer: selected.label, originalIndex: selected.originalIndex });
544
- return;
545
- }
546
- if (keybindings.matches(data, "tui.select.cancel")) {
547
- if (filterQuery) {
548
- filterQuery = "";
549
- optionIndex = 0;
550
- refresh();
551
- } else finish({ kind: "cancelled" });
552
- return;
553
- }
554
- if (keybindings.matches(data, "tui.editor.deleteCharBackward")) {
555
- if (filterQuery) {
556
- filterQuery = removeLastGrapheme(filterQuery);
557
- optionIndex = 0;
558
- refresh();
559
- }
560
- return;
561
- }
562
- if (!isPasteInput && printableInput && /^[1-9]$/u.test(printableInput)) {
563
- const selected = visibleOptions[Number(printableInput) - 1];
564
- if (!selected) return;
565
- if (selected.isOther) enterCustomMode();
566
- else finish({ kind: "selected", answer: selected.label, originalIndex: selected.originalIndex });
567
- return;
568
- }
569
- if (printableInput) appendFilterInput(printableInput);
570
- };
571
-
572
- const render = (width: number): string[] => {
573
- if (width <= 0) return [];
574
- const rowBudget = tui.terminal.rows;
575
- if (rowBudget <= 0) return [];
576
- if (cachedLines && cachedWidth === width && cachedRows === rowBudget) return cachedLines;
577
- const visibleOptions = filteredOptions();
578
- if (optionIndex >= visibleOptions.length) optionIndex = Math.max(0, visibleOptions.length - 1);
579
- const selected = visibleOptions[optionIndex];
580
- const position = `Option ${Math.min(optionIndex + 1, visibleOptions.length)}/${visibleOptions.length}`;
581
- const editorText = editor.getExpandedText();
582
- const editorCount = inputCharacterCount(editorText).toLocaleString();
583
- const filterCount = inputCharacterCount(editMode === "filter" ? editorText : filterQuery).toLocaleString();
584
- const compactDraft = editorText.replace(/\r\n|\r|\n/gu, " ↵ ") || (editMode === "filter" ? "Type a filter" : "Type an answer");
585
- const selectionRange = minSelections === maxSelections ? `${minSelections}` : `${minSelections}–${maxSelections}`;
586
- const selectionStatus = `Selected ${selectedCount()} · required ${selectionRange}`;
587
- const optionLabel = (option: DisplayOption, index: number): string => {
588
- if (mode === "single") return `${index === optionIndex ? ">" : " "} ${index + 1}. ${option.label}`;
589
- const checked = option.isOther ? customAnswer !== undefined : selectedOriginalIndices.has(option.originalIndex);
590
- const label = option.isOther && customAnswer !== undefined ? `Custom: ${oneLine(customAnswer)}` : option.label;
591
- return `${index === optionIndex ? ">" : " "} ${checked ? "[x]" : "[ ]"} ${index + 1}. ${label}`;
592
- };
593
- const browseHint = mode === "multiple"
594
- ? `space toggle • / filter • ${keyHint("tui.select.confirm", selected?.isOther ? (customAnswer ? "edit custom" : "add custom") : "submit")} • ${keyHint("tui.select.cancel", filterQuery ? "clear filter" : "cancel")}`
595
- : `${keyHint("tui.select.confirm", "select")} • ${keyHint("tui.select.cancel", "cancel")}`;
596
- const editHint = `${keyHint("tui.input.submit", editMode === "filter" ? "apply" : "submit")} • ${keyHint("tui.select.cancel", "options")}`;
597
-
598
- let lines: string[];
599
- if (rowBudget <= 2) {
600
- if (editMode !== "none") lines = [`${editMode === "filter" ? "Filter" : "Answer"} ${editMode === "filter" ? filterCount : editorCount}/${CUSTOM_INPUT_MAX_CHARACTERS.toLocaleString()}`, compactDraft];
601
- else if (mode === "multiple") {
602
- const focusedRow = selected ? optionLabel(selected, optionIndex) : "";
603
- const compactSelectionStatus = visibleWidth(selectionStatus) <= width
604
- ? selectionStatus
605
- : `Selected ${selectedCount()}`;
606
- lines = focusedRow && visibleWidth(focusedRow) <= width
607
- ? [focusedRow, compactSelectionStatus]
608
- : [compactSelectionStatus, focusedRow];
609
- } else lines = [`${selected ? `> ${selected.label}` : "No matching options"} · ${position}`];
610
- } else if (rowBudget <= 5) {
611
- lines = [
612
- ...boundedQuestionLines(question, width, Math.max(1, rowBudget - 3)),
613
- editMode !== "none"
614
- ? `${editMode === "filter" ? "Filter" : "Answer"} ${editMode === "filter" ? filterCount : editorCount}/${CUSTOM_INPUT_MAX_CHARACTERS.toLocaleString()}`
615
- : selected ? optionLabel(selected, optionIndex) : "No matching options",
616
- editMode !== "none" ? compactDraft : mode === "multiple" ? selectionStatus : filterQuery ? `Filter ${filterCount}/${FILTER_QUERY_MAX_CHARACTERS.toLocaleString()}` : position,
617
- editMode !== "none" ? editHint : browseHint,
618
- ];
619
- } else {
620
- const questionLines = boundedQuestionLines(question, width, Math.max(1, rowBudget - 5));
621
- const contentRows = rowBudget - questionLines.length - 4;
622
- const optionCapacity = Math.max(1, Math.min(5, Math.ceil(contentRows / 2)));
623
- const detailCapacity = Math.max(0, contentRows - optionCapacity);
624
- const { start, end } = visibleOptionRange(visibleOptions.length, optionIndex, optionCapacity);
625
- const hiddenAbove = start > 0 ? `↑ ${start}` : "";
626
- const hiddenBelowCount = visibleOptions.length - end;
627
- const hiddenBelow = hiddenBelowCount > 0 ? `↓ ${hiddenBelowCount}` : "";
628
- const hiddenStatus = [hiddenAbove, hiddenBelow].filter(Boolean).join(" · ");
629
- const progress = editMode === "filter"
630
- ? `Filter ${filterCount}/${FILTER_QUERY_MAX_CHARACTERS.toLocaleString()}`
631
- : editMode === "custom"
632
- ? `Answer ${editorCount}/${CUSTOM_INPUT_MAX_CHARACTERS.toLocaleString()}`
633
- : mode === "multiple"
634
- ? `${selectionStatus}${hiddenStatus ? ` · ${hiddenStatus}` : ""}`
635
- : filterQuery ? `Filter ${filterCount}/${FILTER_QUERY_MAX_CHARACTERS.toLocaleString()} · ${position}` : `${position}${hiddenStatus ? ` · ${hiddenStatus}` : ""}`;
636
- const navigationHint = editMode !== "none" ? editHint : mode === "multiple"
637
- ? `${keyHint("tui.select.up", "up")} • ${keyHint("tui.select.down", "down")} • ${browseHint}`
638
- : `${keyHint("tui.select.up", "up")} • ${keyHint("tui.select.down", "down")} • ${keyHint("tui.select.confirm", "select")} • ${keyHint("tui.select.cancel", filterQuery ? "clear filter" : "cancel")}`;
639
- lines = [
640
- theme.fg("accent", "─".repeat(width)),
641
- ...questionLines.map((line) => theme.fg("text", line)),
642
- theme.fg("muted", truncateToWidth(` ${progress}`, width, "…")),
643
- ];
644
- if (editMode !== "none") {
645
- const editorLines = editor.render(width);
646
- const draftLines = editorLines.length > 2 ? editorLines.slice(1, -1) : editorLines;
647
- lines.push(...(draftLines.length > 0 ? draftLines : [editMode === "filter" ? "Type a filter" : "Type an answer"]).slice(-contentRows));
648
- } else {
649
- for (let index = start; index < end; index += 1) {
650
- const option = visibleOptions[index];
651
- if (!option) continue;
652
- const color: ThemeColor = index === optionIndex ? "accent" : "text";
653
- lines.push(theme.fg(color, truncateToWidth(optionLabel(option, index), width, "…")));
654
- }
655
- const detailLines: string[] = [];
656
- if (selected?.description) detailLines.push(...wrapTextWithAnsi(theme.fg("muted", selected.description), width));
657
- if (selected?.preview) {
658
- detailLines.push(theme.fg("accent", theme.bold("Proposal preview")));
659
- detailLines.push(...new Markdown(selected.preview, 0, 0, {
660
- heading: (text) => theme.fg("accent", theme.bold(text)), link: (text) => theme.fg("accent", text),
661
- linkUrl: (text) => theme.fg("dim", text), code: (text) => theme.fg("mdCode", text),
662
- codeBlock: (text) => theme.fg("mdCodeBlock", text), codeBlockBorder: (text) => theme.fg("mdCodeBlockBorder", text),
663
- quote: (text) => theme.fg("mdQuote", text), quoteBorder: (text) => theme.fg("mdQuoteBorder", text),
664
- hr: (text) => theme.fg("mdHr", text), listBullet: (text) => theme.fg("mdListBullet", text),
665
- bold: (text) => theme.bold(text), italic: (text) => theme.italic(text), strikethrough: (text) => theme.strikethrough(text),
666
- underline: (text) => theme.underline(text),
667
- }, { color: (text) => theme.fg("muted", text) }).render(width));
668
- }
669
- if (detailCapacity > 0 && detailLines.length > detailCapacity) {
670
- const visibleDetailRows = Math.max(0, detailCapacity - 1);
671
- lines.push(...detailLines.slice(0, visibleDetailRows));
672
- const hiddenRows = detailLines.length - visibleDetailRows;
673
- lines.push(theme.fg("dim", `… ${hiddenRows} more line${hiddenRows === 1 ? "" : "s"}`));
674
- } else lines.push(...detailLines.slice(0, detailCapacity));
675
- }
676
- lines.push(theme.fg("dim", truncateToWidth(` ${navigationHint}`, width, "…")));
677
- lines.push(theme.fg("accent", "─".repeat(width)));
678
- }
679
- cachedWidth = width;
680
- cachedRows = rowBudget;
681
- cachedLines = lines.slice(0, rowBudget).map((line) => boundedRenderLine(line, width, rowBudget <= 5 ? "…" : ""));
682
- return cachedLines;
683
- };
684
-
685
- let focused = false;
686
- return {
687
- get focused(): boolean { return focused; },
688
- set focused(value: boolean) { focused = value; editor.focused = value; },
689
- render,
690
- handleInput,
691
- invalidate,
692
- };
145
+ const result = await openQuestionUi({
146
+ ctx,
147
+ signal,
148
+ question,
149
+ options,
150
+ originalOptions: params.options,
151
+ mode,
152
+ minSelections,
153
+ maxSelections,
154
+ customInputHistory,
155
+ rememberCustomInput,
693
156
  });
694
157
 
695
- const abortHandler = (): void => finishFromAbort?.();
696
- signal?.addEventListener("abort", abortHandler, { once: true });
697
- if (signal?.aborted) abortHandler();
698
- let result: QuestionSelection;
699
- try {
700
- result = await resultPromise;
701
- } finally {
702
- signal?.removeEventListener("abort", abortHandler);
703
- }
704
-
705
158
  const simpleOptions = params.options.map((option) => option.label);
706
159
  if (result.kind === "aborted") throw new Error("Question cancelled because the agent operation was aborted");
707
160
  if (result.kind === "cancelled" && mode === "multiple") {
@@ -82,9 +82,12 @@ export type GoalState = GoalStateCommon & (
82
82
  }
83
83
  );
84
84
 
85
+ /** Pi request outcomes for goal recovery: awaiting result, compacted, or rejected as session-too-small. */
86
+ export type AutomaticGoalCompactionOutcome = "pending" | "completed" | "skipped";
87
+
85
88
  export interface AutomaticGoalCompaction {
86
89
  pausedRevision: number;
87
- compactionSucceeded: boolean;
90
+ outcome: AutomaticGoalCompactionOutcome;
88
91
  turnSettled: boolean;
89
92
  }
90
93
 
@@ -0,0 +1,19 @@
1
+ const SECRET_PATTERNS = [
2
+ /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----/u,
3
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/u,
4
+ /\bAIza[0-9A-Za-z_-]{35}\b/u,
5
+ /\bgh(?:p|o|u|s|r)_[A-Za-z0-9]{36,255}\b/u,
6
+ /\bgithub_pat_[A-Za-z0-9_]{20,255}\b/u,
7
+ /\bglpat-[A-Za-z0-9_-]{20,255}\b/u,
8
+ /\bnpm_[A-Za-z0-9]{20,255}\b/u,
9
+ /\bsk-(?:ant-|proj-|svcacct-)?[A-Za-z0-9_-]{20,255}\b/u,
10
+ /\bsk_live_[A-Za-z0-9]{16,255}\b/u,
11
+ /\bxox[baprs]-[A-Za-z0-9-]{10,255}\b/u,
12
+ /\b[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@/iu,
13
+ /^[\t ]*["']?[\w.-]*(?:api_key|apikey|password|passwd|secret|token)[\w.-]*["']?[\t ]*(?:=|:)[\t ]*(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s#][^\r\n]*)/imu,
14
+ ] as const;
15
+
16
+ /** Detects high-confidence credential material without returning the matched value. */
17
+ export function containsLikelySecret(text: string): boolean {
18
+ return SECRET_PATTERNS.some((pattern) => pattern.test(text));
19
+ }
@@ -2,7 +2,6 @@ import { execFile } from "node:child_process";
2
2
  import { readFileSync } from "node:fs";
3
3
  import {
4
4
  CustomEditor,
5
- VERSION,
6
5
  type ExtensionAPI,
7
6
  type ExtensionContext,
8
7
  type KeybindingsManager,
@@ -383,7 +382,7 @@ class PiCodeEditor extends CustomEditor {
383
382
  for (let index = bottomBorderIndex + 1; index < lines.length; index += 1) {
384
383
  rendered.push(` ${padRight(lines[index] ?? "", innerWidth)}`);
385
384
  }
386
- return ["", ...rendered.map((line) => truncateToWidth(line, width, ""))];
385
+ return [this.runtimeTheme.fg("borderMuted", "─".repeat(width)), ...rendered.map((line) => truncateToWidth(line, width, ""))];
387
386
  }
388
387
  }
389
388