@narumitw/pi-plan-mode 0.51.0 → 0.51.1

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,24 +1,13 @@
1
- import { stripVTControlCharacters } from "node:util";
2
- import type { ExtensionContext, KeybindingsManager, Theme } from "@earendil-works/pi-coding-agent";
3
- import {
4
- type Component,
5
- Editor,
6
- type EditorTheme,
7
- type Focusable,
8
- Key,
9
- matchesKey,
10
- sliceByColumn,
11
- type TUI,
12
- truncateToWidth,
13
- visibleWidth,
14
- } from "@earendil-works/pi-tui";
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type {
3
+ QuestionnaireAnswer,
4
+ QuestionnaireQuestion,
5
+ RunQuestionnaireResult,
6
+ } from "@narumitw/pi-tui-kit";
15
7
 
16
8
  export const PLAN_MODE_QUESTION_TOOL_NAME = "plan_mode_question";
17
9
  export const MAX_PLAN_MODE_RESPONSE_LENGTH = 4_000;
18
10
 
19
- const BRACKETED_PASTE_START = "\u001b[200~";
20
- const BRACKETED_PASTE_END = "\u001b[201~";
21
-
22
11
  export type PlanModeQuestionOption = {
23
12
  label: string;
24
13
  description?: string;
@@ -205,613 +194,75 @@ export async function askPlanModeQuestions(
205
194
  ctx: ExtensionContext,
206
195
  shouldContinue: () => boolean = () => true,
207
196
  ): Promise<PlanModeQuestionAnswer[] | undefined> {
208
- if (ctx.mode === "tui") {
209
- const answers = await ctx.ui.custom<PlanModeQuestionAnswer[] | undefined>(
210
- (tui, theme, keybindings, done) =>
211
- new PlanModeQuestionnaire({
212
- questions,
213
- tui,
214
- theme,
215
- keybindings,
216
- shouldContinue,
217
- signal: ctx.signal,
218
- onDone: done,
219
- }),
220
- );
221
- return shouldContinue() ? answers : undefined;
222
- }
223
- return askPlanModeQuestionsSequentially(questions, ctx, shouldContinue);
197
+ const { runQuestionnaire, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
198
+ if (!shouldContinue()) return undefined;
199
+ const runnerQuestions: QuestionnaireQuestion<string>[] = questions.map((question, index) => ({
200
+ id: String(index),
201
+ header: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),
202
+ prompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),
203
+ options: question.options.map((option, optionIndex) => ({
204
+ ...option,
205
+ label: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText),
206
+ })),
207
+ }));
208
+ const result = await runQuestionnaire(ctx, {
209
+ questions: runnerQuestions,
210
+ allowNotes: true,
211
+ maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,
212
+ signal: ctx.signal,
213
+ isCurrent: shouldContinue,
214
+ });
215
+ if (!shouldContinue()) return undefined;
216
+ return mapQuestionnaireResult(questions, result);
224
217
  }
225
218
 
226
- async function askPlanModeQuestionsSequentially(
219
+ function mapQuestionnaireResult(
227
220
  questions: PlanModeQuestion[],
228
- ctx: ExtensionContext,
229
- shouldContinue: () => boolean,
230
- ): Promise<PlanModeQuestionAnswer[] | undefined> {
231
- const answers: PlanModeQuestionAnswer[] = [];
232
- for (const question of questions) {
233
- const choices = question.options.map(formatPlanModeQuestionChoice);
234
- const otherChoice = `${question.options.length + 1}. Other (free-form)`;
235
- const choice = await ctx.ui.select(`${question.header}: ${question.question}`, [
236
- ...choices,
237
- otherChoice,
238
- ]);
239
- if (!shouldContinue() || !choice) return undefined;
240
- if (choice === otherChoice) {
241
- const customAnswer = await askCustomAnswer(question, ctx, shouldContinue);
242
- if (customAnswer === undefined) return undefined;
243
- answers.push(answerFor(question, customAnswer, { wasCustom: true }));
244
- continue;
245
- }
246
- const optionIndex = choices.indexOf(choice);
247
- const option = question.options[optionIndex];
248
- if (!option) return undefined;
249
- answers.push(
250
- answerFor(question, option.label, { wasCustom: false, optionIndex: optionIndex + 1 }),
251
- );
252
- }
253
- return answers;
254
- }
255
-
256
- async function askCustomAnswer(
257
- question: PlanModeQuestion,
258
- ctx: ExtensionContext,
259
- shouldContinue: () => boolean,
260
- ): Promise<string | undefined> {
261
- let draft = "";
262
- for (;;) {
263
- const customAnswer = await ctx.ui.editor(question.question, draft);
264
- if (!shouldContinue() || !customAnswer?.trim()) return undefined;
265
- if (customAnswer.length <= MAX_PLAN_MODE_RESPONSE_LENGTH) return customAnswer;
266
- draft = customAnswer;
267
- ctx.ui.notify("Custom answer must be 4,000 characters or fewer.", "warning");
268
- }
269
- }
270
-
271
- interface QuestionnaireOptions {
272
- questions: PlanModeQuestion[];
273
- tui: TUI;
274
- theme: Theme;
275
- keybindings: KeybindingsManager;
276
- shouldContinue(): boolean;
277
- signal?: AbortSignal;
278
- onDone(answers: PlanModeQuestionAnswer[] | undefined): void;
279
- }
280
-
281
- export class PlanModeQuestionnaire implements Component, Focusable {
282
- private readonly options: QuestionnaireOptions;
283
- private readonly editor: RawPreservingEditor;
284
- private readonly answers: Array<PlanModeQuestionAnswer | undefined>;
285
- private readonly selectedOptions: number[];
286
- private page = 0;
287
- private editorKind: "answer" | "note" | undefined;
288
- private message: string | undefined;
289
- private finished = false;
290
- private removeAbort = () => {};
291
- private _focused = false;
292
-
293
- constructor(options: QuestionnaireOptions) {
294
- this.options = options;
295
- this.answers = options.questions.map(() => undefined);
296
- this.selectedOptions = options.questions.map(() => 0);
297
- const editorTheme: EditorTheme = {
298
- borderColor: (text) => options.theme.fg("accent", text),
299
- selectList: {
300
- selectedPrefix: (text) => options.theme.fg("accent", text),
301
- selectedText: (text) => options.theme.fg("accent", text),
302
- description: (text) => options.theme.fg("muted", text),
303
- scrollInfo: (text) => options.theme.fg("dim", text),
304
- noMatch: (text) => options.theme.fg("warning", text),
305
- },
306
- };
307
- this.editor = new RawPreservingEditor(options.tui, editorTheme);
308
- this.editor.onChange = () => {
309
- this.message = undefined;
310
- };
311
- this.editor.onSubmit = (text) => this.submitEditor(text);
312
- if (options.signal) {
313
- const abort = () => this.finish(undefined);
314
- options.signal.addEventListener("abort", abort, { once: true });
315
- this.removeAbort = () => options.signal?.removeEventListener("abort", abort);
316
- if (options.signal.aborted) abort();
317
- }
318
- }
319
-
320
- get focused(): boolean {
321
- return this._focused;
322
- }
323
-
324
- set focused(value: boolean) {
325
- this._focused = value;
326
- this.editor.focused = value && this.editorKind !== undefined;
327
- }
328
-
329
- render(width: number): string[] {
330
- const safeWidth = Math.max(1, width);
331
- const padding = safeWidth > 1 ? " " : "";
332
- const contentWidth = Math.max(1, safeWidth - visibleWidth(padding));
333
- const border = this.options.theme.fg("border", "─".repeat(safeWidth));
334
- const lines = [border, "", ...this.renderTabs(contentWidth), ""];
335
- if (this.page === this.options.questions.length) lines.push(...this.renderReview(contentWidth));
336
- else lines.push(...this.renderQuestion(contentWidth));
337
- if (this.message)
338
- lines.push(...hardWrap(this.options.theme.fg("warning", this.message), contentWidth));
339
- lines.push("");
340
- lines.push(truncateToWidth(this.renderHints(), contentWidth), "", border);
341
- return lines.map((line) => {
342
- if (!line || line === border) return line;
343
- return `${padding}${truncateToWidth(line, contentWidth)}`;
344
- });
345
- }
346
-
347
- handleInput(data: string): void {
348
- if (this.finished) return;
349
- if (!this.options.shouldContinue() || this.isCancel(data)) {
350
- this.finish(undefined);
351
- return;
352
- }
353
- if (this.editorKind) this.handleEditorInput(data);
354
- else this.handlePageInput(data);
355
- this.options.tui.requestRender();
356
- }
357
-
358
- invalidate(): void {
359
- this.editor.invalidate();
360
- }
361
-
362
- dispose(): void {
363
- this.finish(undefined);
364
- }
365
-
366
- private isCancel(data: string): boolean {
367
- return (
368
- matchesKey(data, Key.ctrl("c")) || this.options.keybindings.matches(data, "tui.select.cancel")
369
- );
370
- }
371
-
372
- private handleEditorInput(data: string): void {
373
- const keybindings = this.options.keybindings;
374
- if (keybindings.matches(data, "tui.input.newLine")) {
375
- this.editor.handleInput(data);
376
- } else if (keybindings.matches(data, "tui.input.submit")) {
377
- this.submitEditor(this.editor.getExpandedText());
378
- } else {
379
- this.editor.handleInput(data);
380
- }
381
- }
382
-
383
- private handlePageInput(data: string): void {
384
- const keybindings = this.options.keybindings;
385
- const review = this.page === this.options.questions.length;
386
- if (keybindings.matches(data, "tui.select.up") || data === "k") {
387
- if (!review) this.moveSelection(-1);
388
- return;
389
- }
390
- if (keybindings.matches(data, "tui.select.down") || data === "j") {
391
- if (!review) this.moveSelection(1);
392
- return;
393
- }
394
- if (keybindings.matches(data, "tui.select.confirm")) {
395
- this.submitPage();
396
- return;
397
- }
398
- if (keybindings.matches(data, "tui.input.tab") || matchesKey(data, Key.right)) {
399
- this.movePage(1);
400
- return;
401
- }
402
- if (matchesKey(data, Key.shift("tab")) || matchesKey(data, Key.left)) {
403
- this.movePage(-1);
404
- return;
405
- }
406
- if (data.toLowerCase() === "n") {
407
- if (review) this.message = "Return to a question to add or edit its note.";
408
- else this.editNote();
409
- }
410
- }
411
-
412
- private renderHints(): string {
413
- const { keybindings, theme } = this.options;
414
- const cancel = cancelHint(theme, keybindings);
415
- if (this.editorKind) {
416
- return [
417
- keybindingHint(theme, keybindings, "tui.input.submit", "save"),
418
- keybindingHint(theme, keybindings, "tui.input.newLine", "newline"),
419
- cancel,
420
- ].join(" ");
421
- }
422
- const questions = rawKeyHint(theme, questionNavigationKeys(keybindings), "questions");
423
- if (this.page === this.options.questions.length) {
424
- return [
425
- keybindingHint(theme, keybindings, "tui.select.confirm", "submit"),
426
- cancel,
427
- questions,
428
- ].join(" ");
429
- }
430
- return [
431
- rawKeyHint(theme, selectionNavigationKeys(keybindings), "navigate"),
432
- keybindingHint(theme, keybindings, "tui.select.confirm", "select"),
433
- cancel,
434
- questions,
435
- rawKeyHint(theme, "n", "note"),
436
- ].join(" ");
437
- }
438
-
439
- private movePage(delta: number): void {
440
- const pageCount = this.options.questions.length + 1;
441
- this.page = (this.page + delta + pageCount) % pageCount;
442
- const answer = this.answers[this.page];
443
- const question = this.options.questions[this.page];
444
- if (answer?.wasCustom && question) {
445
- this.selectedOptions[this.page] = question.options.length;
446
- } else if (answer?.optionIndex !== undefined) {
447
- this.selectedOptions[this.page] = answer.optionIndex - 1;
448
- }
449
- this.message = undefined;
450
- }
451
-
452
- private renderTabs(width: number): string[] {
453
- const tabs = [
454
- ...this.options.questions.map((question, index) => {
455
- const label = sanitizeTerminalText(question.header) || `Question ${index + 1}`;
456
- const answered = this.answers[index] ? "✓ " : "";
457
- return this.page === index ? `[${answered}${label}]` : `${answered}${label}`;
458
- }),
459
- this.page === this.options.questions.length ? "[Review]" : "Review",
460
- ];
461
- const lines: string[] = [];
462
- let line = "";
463
- for (const tab of tabs) {
464
- const boundedTab = truncateToWidth(tab, width, "…");
465
- const candidate = line ? `${line} ${boundedTab}` : boundedTab;
466
- if (line && visibleWidth(candidate) > width) {
467
- lines.push(this.options.theme.fg("accent", line));
468
- line = boundedTab;
469
- } else {
470
- line = candidate;
471
- }
472
- }
473
- if (line) lines.push(this.options.theme.fg("accent", line));
474
- return lines;
475
- }
476
-
477
- private renderQuestion(width: number): string[] {
478
- const question = this.options.questions[this.page];
479
- if (!question) return [];
480
- const lines = hardWrap(
481
- this.options.theme.fg(
482
- "accent",
483
- this.options.theme.bold(sanitizeTerminalText(question.question)),
484
- ),
485
- width,
486
- );
487
- lines.push("");
488
- question.options.forEach((option, index) => {
489
- const selected = this.selectedOptions[this.page] === index;
490
- const cursor = selected ? "→" : " ";
491
- const label = `${cursor} ${index + 1}. ${sanitizeTerminalText(option.label)}`;
492
- const chosen = this.answers[this.page]?.optionIndex === index + 1;
493
- const description = option.description
494
- ? ` — ${sanitizeTerminalText(option.description)}`
495
- : "";
496
- const line = selected
497
- ? this.options.theme.fg("accent", `${label}${chosen ? " ✓" : ""}${description}`)
498
- : `${this.options.theme.fg("text", label)}${
499
- chosen ? this.options.theme.fg("success", " ✓") : ""
500
- }${description ? this.options.theme.fg("muted", description) : ""}`;
501
- lines.push(...hardWrapWithIndent(line, width, visibleWidth(`${cursor} ${index + 1}. `)));
502
- });
503
- const otherIndex = question.options.length;
504
- const otherSelected = this.selectedOptions[this.page] === otherIndex;
505
- const otherCursor = otherSelected ? "→" : " ";
506
- const otherLabel = `${otherCursor} ${otherIndex + 1}. Other (free-form)`;
507
- const otherChosen = this.answers[this.page]?.wasCustom === true;
508
- lines.push(
509
- otherSelected
510
- ? this.options.theme.fg("accent", `${otherLabel}${otherChosen ? " ✓" : ""}`)
511
- : `${this.options.theme.fg("text", otherLabel)}${
512
- otherChosen ? this.options.theme.fg("success", " ✓") : ""
513
- }`,
514
- );
515
- const answer = this.answers[this.page];
516
- if (answer?.wasCustom)
517
- lines.push(...labeledRaw("Answer", answer.answer, width, this.options.theme));
518
- if (answer?.note) lines.push(...labeledRaw("Note", answer.note, width, this.options.theme));
519
- if (this.editorKind) {
520
- lines.push("");
521
- lines.push(
522
- this.options.theme.fg(
523
- "accent",
524
- this.editorKind === "answer" ? "Custom answer" : "Optional note",
525
- ),
526
- );
527
- lines.push(...this.editor.render(width));
528
- }
529
- return lines;
530
- }
531
-
532
- private renderReview(width: number): string[] {
533
- const lines = [this.options.theme.fg("accent", this.options.theme.bold("Review answers")), ""];
534
- this.options.questions.forEach((question, index) => {
535
- const answer = this.answers[index];
536
- const header = sanitizeTerminalText(question.header) || `Question ${index + 1}`;
537
- const label = `${index + 1}. ${header}`;
538
- const summary = ` — ${inlineSummary(answer?.answer ?? "Unanswered")}${
539
- answer?.note ? ` · Note: ${inlineSummary(answer.note)}` : ""
540
- }`;
541
- const line = `${this.options.theme.fg("text", label)}${this.options.theme.fg("muted", summary)}`;
542
- lines.push(...hardWrapWithIndent(line, width, visibleWidth(`${index + 1}. `)));
543
- });
544
- return lines;
545
- }
546
-
547
- private moveSelection(delta: number): void {
548
- const optionCount = (this.options.questions[this.page]?.options.length ?? 0) + 1;
549
- this.selectedOptions[this.page] =
550
- ((this.selectedOptions[this.page] ?? 0) + delta + optionCount) % optionCount;
551
- }
552
-
553
- private submitPage(): void {
554
- if (this.page === this.options.questions.length) {
555
- const firstMissing = this.answers.findIndex((answer) => !answer);
556
- if (firstMissing >= 0) {
557
- this.message = "Answer every question before submitting.";
558
- return;
559
- }
560
- this.finish(
561
- this.answers.filter((answer): answer is PlanModeQuestionAnswer => answer !== undefined),
562
- );
563
- return;
564
- }
565
- const question = this.options.questions[this.page];
566
- if (!question) return;
567
- const selected = this.selectedOptions[this.page] ?? 0;
568
- if (selected === question.options.length) {
569
- this.beginEditor(
570
- "answer",
571
- this.answers[this.page]?.wasCustom ? this.answers[this.page]?.answer : "",
572
- );
573
- return;
574
- }
575
- const option = question.options[selected];
576
- if (!option) return;
577
- const previous = this.answers[this.page];
578
- this.answers[this.page] = answerFor(question, option.label, {
579
- wasCustom: false,
580
- optionIndex: selected + 1,
581
- note: previous?.optionIndex === selected + 1 ? previous.note : undefined,
582
- });
583
- this.advance();
584
- }
585
-
586
- private editNote(): void {
587
- const index = this.page;
588
- let answer = this.answers[index];
589
- const question = this.options.questions[index];
590
- const selected = this.selectedOptions[index] ?? 0;
591
- if (question && selected === question.options.length && !answer?.wasCustom) {
592
- this.beginEditor("answer", "");
593
- return;
594
- }
595
- if (question && selected < question.options.length && answer?.optionIndex !== selected + 1) {
596
- const option = question.options[selected];
597
- if (option) {
598
- answer = answerFor(question, option.label, {
599
- wasCustom: false,
600
- optionIndex: selected + 1,
601
- });
602
- this.answers[index] = answer;
603
- }
604
- }
605
- if (!answer) {
606
- this.message = "Select an answer before adding a note.";
607
- return;
608
- }
609
- this.beginEditor("note", answer.note ?? "");
610
- }
611
-
612
- private beginEditor(kind: "answer" | "note", value: string | undefined): void {
613
- this.editorKind = kind;
614
- this.editor.setText(value ?? "");
615
- this.editor.focused = this._focused;
616
- this.message = undefined;
617
- }
618
-
619
- private submitEditor(value: string): void {
620
- if (value.length > MAX_PLAN_MODE_RESPONSE_LENGTH) {
621
- this.editor.setText(value);
622
- this.message = `${this.editorKind === "answer" ? "Answer" : "Note"} must be 4,000 characters or fewer.`;
623
- this.options.tui.requestRender();
624
- return;
625
- }
626
- const index = this.page;
627
- if (this.editorKind === "answer") {
628
- if (!value.trim()) {
629
- this.editor.setText(value);
630
- this.message = "Custom answer cannot be empty.";
631
- this.options.tui.requestRender();
632
- return;
221
+ result: RunQuestionnaireResult<string>,
222
+ ): PlanModeQuestionAnswer[] | undefined {
223
+ if (result.kind !== "submitted") return undefined;
224
+ if (result.answers.length !== questions.length) {
225
+ throw new Error("Questionnaire returned an incomplete answer set");
226
+ }
227
+
228
+ const answers = new Map<number, QuestionnaireAnswer<string>>();
229
+ for (const answer of result.answers) {
230
+ const index = Number(answer.questionId);
231
+ if (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {
232
+ throw new Error("Questionnaire returned an answer for an unknown question");
233
+ }
234
+ if (answers.has(index)) throw new Error("Questionnaire returned duplicate answers");
235
+ if (answer.wasCustom) {
236
+ if (answer.optionIndex !== undefined) {
237
+ throw new Error("Questionnaire returned a custom answer with an option index");
633
238
  }
634
- const question = this.options.questions[index];
635
- if (!question) return;
636
- const previous = this.answers[index];
637
- this.answers[index] = answerFor(question, value, {
638
- wasCustom: true,
639
- note: previous?.wasCustom ? previous.note : undefined,
640
- });
641
- this.editor.setText("");
642
- this.editorKind = undefined;
643
- this.editor.focused = false;
644
- this.advance();
645
- return;
646
- }
647
- const answer = this.answers[index];
648
- if (answer) answer.note = value.trim() ? value : undefined;
649
- this.editor.setText("");
650
- this.editorKind = undefined;
651
- this.editor.focused = false;
652
- this.message = value.trim() ? "Note saved." : "Note cleared.";
653
- this.options.tui.requestRender();
654
- }
655
-
656
- private advance(): void {
657
- this.page = Math.min(this.page + 1, this.options.questions.length);
658
- this.message = undefined;
659
- }
660
-
661
- private finish(answers: PlanModeQuestionAnswer[] | undefined): void {
662
- if (this.finished) return;
663
- this.finished = true;
664
- this.removeAbort();
665
- this.removeAbort = () => {};
666
- this.editor.focused = false;
667
- this.options.onDone(answers);
668
- }
669
- }
670
-
671
- class RawPreservingEditor implements Focusable {
672
- private readonly editor: Editor;
673
- private readonly rawByMarker = new Map<string, string>();
674
- private markerCodePoint = 0xe000;
675
- private pasteBuffer: string | undefined;
676
-
677
- constructor(tui: TUI, theme: EditorTheme) {
678
- this.editor = new Editor(tui, theme, { paddingX: 0 });
679
- }
680
-
681
- get focused(): boolean {
682
- return this.editor.focused;
683
- }
684
-
685
- set focused(value: boolean) {
686
- this.editor.focused = value;
687
- }
688
-
689
- set onChange(handler: ((value: string) => void) | undefined) {
690
- this.editor.onChange = handler ? () => handler(this.getExpandedText()) : undefined;
691
- }
692
-
693
- set onSubmit(handler: ((value: string) => void) | undefined) {
694
- this.editor.onSubmit = handler ? (value) => handler(this.decode(value)) : undefined;
695
- }
696
-
697
- handleInput(data: string): void {
698
- if (this.pasteBuffer !== undefined) {
699
- this.pasteBuffer += data;
700
- this.flushPasteBuffer();
701
- return;
702
- }
703
- if (matchesKey(data, Key.backspace)) {
704
- this.editor.handleInput(data);
705
- return;
706
- }
707
- const pasteStart = data.indexOf(BRACKETED_PASTE_START);
708
- if (pasteStart >= 0) {
709
- if (pasteStart > 0) this.editor.handleInput(data.slice(0, pasteStart));
710
- this.pasteBuffer = data.slice(pasteStart + BRACKETED_PASTE_START.length);
711
- this.flushPasteBuffer();
712
- return;
713
- }
714
- if (
715
- [...data].some(
716
- (character) => isUnsafeDirectEditorCharacter(character) || this.rawByMarker.has(character),
717
- )
239
+ if (!answer.answer.trim()) return undefined;
240
+ } else if (
241
+ answer.optionIndex === undefined ||
242
+ !questions[index]?.options[answer.optionIndex - 1]
718
243
  ) {
719
- this.editor.handleInput(this.encode(data));
720
- return;
244
+ throw new Error("Questionnaire returned an invalid selected option");
721
245
  }
722
- this.editor.handleInput(data);
723
- }
724
-
725
- render(width: number): string[] {
726
- return this.editor
727
- .render(width)
728
- .map((line) =>
729
- [...line].map((character) => (this.rawByMarker.has(character) ? " " : character)).join(""),
730
- );
246
+ answers.set(index, answer);
731
247
  }
732
248
 
733
- invalidate(): void {
734
- this.editor.invalidate();
735
- }
736
-
737
- setText(value: string): void {
738
- this.rawByMarker.clear();
739
- this.markerCodePoint = 0xe000;
740
- this.pasteBuffer = undefined;
741
- this.editor.setText(this.encode(value));
742
- }
743
-
744
- getExpandedText(): string {
745
- return this.decode(this.editor.getExpandedText());
746
- }
747
-
748
- private flushPasteBuffer(): void {
749
- if (this.pasteBuffer === undefined) return;
750
- const pasteEnd = this.pasteBuffer.indexOf(BRACKETED_PASTE_END);
751
- if (pasteEnd < 0) return;
752
- const raw = this.pasteBuffer.slice(0, pasteEnd);
753
- const remaining = this.pasteBuffer.slice(pasteEnd + BRACKETED_PASTE_END.length);
754
- this.pasteBuffer = undefined;
755
- this.editor.handleInput(`${BRACKETED_PASTE_START}${this.encode(raw)}${BRACKETED_PASTE_END}`);
756
- if (remaining) this.handleInput(remaining);
757
- }
758
-
759
- private encode(value: string): string {
760
- const forbidden = new Set([
761
- ...value,
762
- ...this.editor.getExpandedText(),
763
- ...this.rawByMarker.keys(),
764
- ]);
765
- return [...value]
766
- .map((character) => {
767
- if (!isUnsafeEditorCharacter(character) && !this.rawByMarker.has(character)) {
768
- return character;
769
- }
770
- const marker = this.nextMarker(forbidden);
771
- this.rawByMarker.set(marker, character);
772
- forbidden.add(marker);
773
- return marker;
774
- })
775
- .join("");
776
- }
777
-
778
- private decode(value: string): string {
779
- return [...value].map((character) => this.rawByMarker.get(character) ?? character).join("");
780
- }
781
-
782
- private nextMarker(forbidden: ReadonlySet<string>): string {
783
- for (;;) {
784
- if (this.markerCodePoint === 0xf900) this.markerCodePoint = 0xf0000;
785
- if (this.markerCodePoint === 0xffffe) this.markerCodePoint = 0x100000;
786
- if (this.markerCodePoint > 0x10fffd) {
787
- throw new Error("Plan-mode editor exhausted its safe input markers.");
788
- }
789
- const marker = String.fromCodePoint(this.markerCodePoint++);
790
- if (!forbidden.has(marker)) return marker;
791
- }
792
- }
793
- }
794
-
795
- function isUnsafeDirectEditorCharacter(character: string): boolean {
796
- const codePoint = character.codePointAt(0) ?? 0;
797
- return (
798
- (codePoint >= 0x7f && codePoint <= 0x9f) ||
799
- codePoint === 0x2028 ||
800
- codePoint === 0x2029 ||
801
- isBidiControl(codePoint)
802
- );
249
+ return questions.map((question, index) => {
250
+ const answer = answers.get(index);
251
+ if (!answer) throw new Error("Questionnaire returned an incomplete answer set");
252
+ const answerText = answer.wasCustom
253
+ ? answer.answer
254
+ : (question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer);
255
+ return answerFor(question, answerText, {
256
+ wasCustom: answer.wasCustom,
257
+ optionIndex: answer.optionIndex,
258
+ note: answer.note,
259
+ });
260
+ });
803
261
  }
804
262
 
805
- function isUnsafeEditorCharacter(character: string): boolean {
806
- const codePoint = character.codePointAt(0) ?? 0;
807
- return (
808
- character !== "\n" &&
809
- (codePoint <= 0x1f ||
810
- (codePoint >= 0x7f && codePoint <= 0x9f) ||
811
- codePoint === 0x2028 ||
812
- codePoint === 0x2029 ||
813
- isBidiControl(codePoint))
814
- );
263
+ function displayText(value: string, fallback: string, sanitize: (value: string) => string): string {
264
+ const sanitized = sanitize(value);
265
+ return sanitized.trim() ? sanitized : fallback;
815
266
  }
816
267
 
817
268
  function answerFor(
@@ -831,10 +282,6 @@ function answerFor(
831
282
  return result;
832
283
  }
833
284
 
834
- function formatPlanModeQuestionChoice(option: PlanModeQuestionOption, index: number) {
835
- return `${index + 1}. ${option.label}${option.description ? ` — ${option.description}` : ""}`;
836
- }
837
-
838
285
  export function planModeQuestionAnswered(
839
286
  questions: PlanModeQuestion[],
840
287
  answers: PlanModeQuestionAnswer[],
@@ -872,126 +319,6 @@ function formatPlanModeQuestionPayload(payload: {
872
319
  return JSON.stringify(payload, null, 2);
873
320
  }
874
321
 
875
- export function sanitizeTerminalText(value: string): string {
876
- return [...stripVTControlCharacters(value)]
877
- .map((character) => {
878
- const codePoint = character.codePointAt(0) ?? 0;
879
- return codePoint <= 0x1f ||
880
- (codePoint >= 0x7f && codePoint <= 0x9f) ||
881
- codePoint === 0x2028 ||
882
- codePoint === 0x2029 ||
883
- isBidiControl(codePoint)
884
- ? " "
885
- : character;
886
- })
887
- .join("");
888
- }
889
-
890
- function isBidiControl(codePoint: number): boolean {
891
- return (
892
- codePoint === 0x061c ||
893
- codePoint === 0x200e ||
894
- codePoint === 0x200f ||
895
- (codePoint >= 0x202a && codePoint <= 0x202e) ||
896
- (codePoint >= 0x2066 && codePoint <= 0x2069)
897
- );
898
- }
899
-
900
- type QuestionnaireKeybinding = Parameters<KeybindingsManager["getKeys"]>[0];
901
-
902
- function keybindingHint(
903
- theme: Theme,
904
- keybindings: KeybindingsManager,
905
- keybinding: QuestionnaireKeybinding,
906
- description: string,
907
- ): string {
908
- return rawKeyHint(theme, formatHintKeys(keybindings.getKeys(keybinding)), description);
909
- }
910
-
911
- function rawKeyHint(theme: Theme, keys: string, description: string): string {
912
- return `${theme.fg("dim", keys)}${theme.fg("muted", ` ${description}`)}`;
913
- }
914
-
915
- function cancelHint(theme: Theme, keybindings: KeybindingsManager): string {
916
- return rawKeyHint(
917
- theme,
918
- formatHintKeys([...keybindings.getKeys("tui.select.cancel"), "ctrl+c"]),
919
- "cancel",
920
- );
921
- }
922
-
923
- function selectionNavigationKeys(keybindings: KeybindingsManager): string {
924
- const up = keybindings.getKeys("tui.select.up");
925
- const down = keybindings.getKeys("tui.select.down");
926
- if (up.includes("up") && down.includes("down")) {
927
- return formatHintKeys([
928
- "↑↓",
929
- ...up.filter((key) => key !== "up"),
930
- ...down.filter((key) => key !== "down"),
931
- ]);
932
- }
933
- return formatHintKeys([...up, ...down]);
934
- }
935
-
936
- function questionNavigationKeys(keybindings: KeybindingsManager): string {
937
- return formatHintKeys([...keybindings.getKeys("tui.input.tab"), "shift+tab", "←→"]);
938
- }
939
-
940
- function formatHintKeys(keys: readonly string[]): string {
941
- return [...new Set(keys)].map(formatHintKey).join("/");
942
- }
943
-
944
- function formatHintKey(key: string): string {
945
- return key
946
- .split("+")
947
- .map((part) =>
948
- process.platform === "darwin" && part.toLowerCase() === "alt" ? "option" : part,
949
- )
950
- .join("+");
951
- }
952
-
953
- function inlineSummary(value: string): string {
954
- return value.split("\n").map(sanitizeTerminalText).join(" ↵ ");
955
- }
956
-
957
- function labeledRaw(label: string, value: string, width: number, theme: Theme): string[] {
958
- const prefix = `${label}: `;
959
- const safe = sanitizeTerminalText(value);
960
- const lines = hardWrap(safe, Math.max(1, width - visibleWidth(prefix)));
961
- return lines.map((line, index) =>
962
- index === 0 ? `${theme.fg("muted", prefix)}${line}` : `${" ".repeat(prefix.length)}${line}`,
963
- );
964
- }
965
-
966
- function hardWrapWithIndent(value: string, width: number, indent: number): string[] {
967
- const safeWidth = Math.max(1, width);
968
- const safeIndent = Math.min(Math.max(0, indent), Math.max(0, safeWidth - 1));
969
- const continuationWidth = Math.max(1, safeWidth - safeIndent);
970
- const columns = visibleWidth(value);
971
- if (columns <= safeWidth) return [value];
972
- const output = [sliceByColumn(value, 0, safeWidth)];
973
- for (let column = safeWidth; column < columns; column += continuationWidth) {
974
- output.push(`${" ".repeat(safeIndent)}${sliceByColumn(value, column, continuationWidth)}`);
975
- }
976
- return output;
977
- }
978
-
979
- function hardWrap(value: string, width: number): string[] {
980
- const safeWidth = Math.max(1, width);
981
- if (!value) return [""];
982
- const output: string[] = [];
983
- for (const sourceLine of value.split("\n")) {
984
- const columns = visibleWidth(sourceLine);
985
- if (columns === 0) output.push("");
986
- else {
987
- for (let column = 0; column < columns; column += safeWidth) {
988
- output.push(sliceByColumn(sourceLine, column, safeWidth));
989
- }
990
- }
991
- }
992
- return output;
993
- }
994
-
995
322
  function isRecord(value: unknown): value is Record<string, unknown> {
996
323
  return typeof value === "object" && value !== null;
997
324
  }