@linxiraos/pi-tui 1.4.13 → 1.5.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.
Files changed (94) hide show
  1. package/CHANGELOG.md +33 -34
  2. package/dist/types/chat/messages.d.ts +2 -0
  3. package/dist/types/chat/spotlight.d.ts +8 -3
  4. package/dist/types/chat/transcript-render-helpers.d.ts +5 -0
  5. package/dist/types/components/editor.d.ts +4 -1
  6. package/dist/types/html-form/data.d.ts +56 -0
  7. package/dist/types/html-form/dialog.d.ts +51 -0
  8. package/dist/types/html-form/media.d.ts +28 -0
  9. package/dist/types/html-form/paginate.d.ts +43 -0
  10. package/dist/types/html-form/parse.d.ts +99 -0
  11. package/dist/types/overlays/ask-dialog.d.ts +11 -6
  12. package/dist/types/overlays/copy-targets.d.ts +8 -6
  13. package/dist/types/overlays/directory-picker.d.ts +62 -0
  14. package/dist/types/overlays/hook-editor.d.ts +3 -1
  15. package/dist/types/overlays/hub-frame.d.ts +2 -0
  16. package/dist/types/overlays/model-hub.d.ts +2 -0
  17. package/dist/types/overlays/team-hub.d.ts +150 -0
  18. package/dist/types/render/row-moves.d.ts +41 -0
  19. package/dist/types/status-line/component.d.ts +5 -0
  20. package/dist/types/status-line/host.d.ts +2 -2
  21. package/dist/types/status-line/schema.d.ts +1 -1
  22. package/dist/types/status-line/types.d.ts +8 -0
  23. package/dist/types/tools/ask.d.ts +11 -49
  24. package/dist/types/tools/autoresearch.d.ts +2 -2
  25. package/dist/types/tools/eval.d.ts +4 -0
  26. package/dist/types/tools/grouped-file-output.d.ts +2 -0
  27. package/dist/types/tools/shell-viz.d.ts +6 -2
  28. package/dist/types/tools/xd-url.d.ts +6 -0
  29. package/dist/types/windows-input-mode.d.ts +8 -0
  30. package/package.json +9 -9
  31. package/src/charts/table-data.ts +18 -5
  32. package/src/chat/chat-transcript-builder.ts +27 -10
  33. package/src/chat/image-loading.ts +55 -0
  34. package/src/chat/messages.d.ts +2 -0
  35. package/src/chat/messages.ts +3 -0
  36. package/src/chat/spotlight.d.ts +8 -3
  37. package/src/chat/spotlight.ts +23 -11
  38. package/src/chat/tool-execution.ts +5 -0
  39. package/src/chat/transcript-render-helpers.d.ts +5 -0
  40. package/src/chat/transcript-render-helpers.ts +13 -0
  41. package/src/chrome/transcript-container.ts +1 -1
  42. package/src/components/editor.d.ts +4 -1
  43. package/src/components/editor.ts +3 -2
  44. package/src/components/markdown.ts +70 -12
  45. package/src/html-form/data.d.ts +56 -0
  46. package/src/html-form/data.ts +177 -0
  47. package/src/html-form/dialog.ts +1450 -0
  48. package/src/html-form/media.ts +105 -0
  49. package/src/html-form/paginate.ts +99 -0
  50. package/src/html-form/parse.d.ts +99 -0
  51. package/src/html-form/parse.ts +568 -0
  52. package/src/lang-from-path.ts +1 -0
  53. package/src/latex-block.ts +3 -3
  54. package/src/latex-to-unicode.ts +18 -5
  55. package/src/overlays/ask-dialog.ts +69 -52
  56. package/src/overlays/copy-targets.d.ts +8 -6
  57. package/src/overlays/copy-targets.ts +25 -46
  58. package/src/overlays/directory-picker.ts +387 -0
  59. package/src/overlays/hook-editor.ts +16 -15
  60. package/src/overlays/hub-frame.ts +8 -1
  61. package/src/overlays/model-hub.ts +12 -2
  62. package/src/overlays/spotlight-sheet.ts +18 -18
  63. package/src/overlays/team-hub.ts +901 -0
  64. package/src/render/row-moves.d.ts +41 -0
  65. package/src/render/row-moves.ts +109 -0
  66. package/src/setup/wizard-overlay.ts +7 -3
  67. package/src/status-line/component.ts +19 -0
  68. package/src/status-line/footer.ts +2 -2
  69. package/src/status-line/host.ts +2 -2
  70. package/src/status-line/presets.ts +6 -6
  71. package/src/status-line/schema.ts +2 -1
  72. package/src/status-line/segments.ts +31 -4
  73. package/src/status-line/startup.ts +1 -1
  74. package/src/status-line/types.ts +8 -0
  75. package/src/stdin-buffer.ts +15 -1
  76. package/src/terminal-capabilities.ts +12 -3
  77. package/src/terminal.ts +41 -3
  78. package/src/tools/ask.d.ts +11 -49
  79. package/src/tools/ask.ts +201 -606
  80. package/src/tools/autoresearch.ts +2 -2
  81. package/src/tools/debug.ts +31 -38
  82. package/src/tools/eval.d.ts +4 -0
  83. package/src/tools/eval.ts +4 -0
  84. package/src/tools/grep.ts +38 -16
  85. package/src/tools/grouped-file-output.d.ts +2 -0
  86. package/src/tools/grouped-file-output.ts +5 -0
  87. package/src/tools/shell-viz-render.ts +37 -6
  88. package/src/tools/shell-viz.d.ts +6 -2
  89. package/src/tools/shell-viz.ts +19 -6
  90. package/src/tools/xd-url.d.ts +6 -0
  91. package/src/tools/xd-url.ts +19 -1
  92. package/src/tui.ts +129 -1
  93. package/src/windows-input-mode.d.ts +8 -0
  94. package/src/windows-input-mode.ts +13 -0
@@ -40,6 +40,11 @@ export interface AskDialogPromptValue {
40
40
  images?: ImageContent[];
41
41
  }
42
42
 
43
+ /** A prompt left without submitting: what it still held, offered again when the custom answer reopens. */
44
+ export interface AskDialogPromptDraft {
45
+ draft: AskDialogPromptValue;
46
+ }
47
+
43
48
  /** Submitted answer to one dialog question. */
44
49
  export interface ExtensionAskDialogResultItem {
45
50
  id: string;
@@ -139,12 +144,13 @@ export interface AskDialogPrompt {
139
144
  interface AskDialogCallbacks {
140
145
  onSubmit(result: ExtensionAskDialogSubmitResult): void;
141
146
  onCancel(): void;
142
- onPrompt(prompt: AskDialogPrompt, prefill?: string): Promise<string | undefined>;
143
- /** Prompt that accepts pasted images; without it, prompts use `onPrompt`. */
147
+ /** Resolves the submitted text; on cancel, the editor's draft, or `undefined` when none is kept. */
148
+ onPrompt(prompt: AskDialogPrompt, prefill?: string): Promise<string | AskDialogPromptDraft | undefined>;
149
+ /** Prompt that accepts pasted images; without it, prompts use `onPrompt`. Resolves like `onPrompt`. */
144
150
  onImagePrompt?(
145
151
  prompt: AskDialogPrompt,
146
152
  prefill: AskDialogPromptValue | undefined,
147
- ): Promise<AskDialogPromptValue | undefined>;
153
+ ): Promise<AskDialogPromptValue | AskDialogPromptDraft | undefined>;
148
154
  }
149
155
 
150
156
  /**
@@ -153,7 +159,7 @@ interface AskDialogCallbacks {
153
159
  * keys are the explicit hand-off: they release the guard for the rest of the
154
160
  * dialog's life and the draft stays parked (intact) beneath it.
155
161
  */
156
- interface AskDialogInputGuard {
162
+ export interface AskDialogInputGuard {
157
163
  isBlocked(): boolean;
158
164
  handleInput(keyData: string): void;
159
165
  /** Shown after the release keys while the guard holds input. */
@@ -175,6 +181,8 @@ interface QuestionState {
175
181
  selectedOptions: Set<string>;
176
182
  customInput: string | undefined;
177
183
  customInputImages: ImageContent[] | undefined;
184
+ /** Unsubmitted custom answer left by a cancelled prompt; prefills the next one over `customInput`. */
185
+ customDraft: AskDialogPromptValue | undefined;
178
186
  note: string | undefined;
179
187
  noteImages: ImageContent[] | undefined;
180
188
  noteRowKey: string | undefined;
@@ -437,10 +445,17 @@ function describeRowDetail(
437
445
  return spans.length > 0 ? spans : undefined;
438
446
  }
439
447
 
448
+ /** A prompt's outcome: the submitted value, or after a cancel the draft the host kept, if any. */
449
+ type PromptOutcome =
450
+ | { submitted: true; text: string; images: ImageContent[] | undefined }
451
+ | { submitted: false; draft: AskDialogPromptValue | undefined };
452
+
440
453
  /** Normalize the result of either prompt callback. */
441
- function splitPromptInput(input: string | AskDialogPromptValue): { text: string; images: ImageContent[] | undefined } {
442
- if (typeof input === "string") return { text: input, images: undefined };
443
- return { text: input.text, images: input.images?.length ? input.images : undefined };
454
+ function promptOutcome(result: string | AskDialogPromptValue | AskDialogPromptDraft | undefined): PromptOutcome {
455
+ if (result === undefined) return { submitted: false, draft: undefined };
456
+ if (typeof result === "string") return { submitted: true, text: result, images: undefined };
457
+ if ("draft" in result) return { submitted: false, draft: result.draft };
458
+ return { submitted: true, text: result.text, images: result.images?.length ? result.images : undefined };
444
459
  }
445
460
 
446
461
  function clearNote(state: QuestionState): void {
@@ -600,12 +615,6 @@ export class AskDialogComponent implements Component {
600
615
  #countdownDeadline = 0;
601
616
  /** Once-a-second re-describe while the native countdown ring is shown. */
602
617
  #ringTick: NodeJS.Timeout | undefined;
603
- /**
604
- * The answer whose pick just moved the dialog on to the next question. Note annotates it, not the
605
- * next question's highlighted row, until that question is answered or any other input arrives:
606
- * a Tern click commits a single-choice row, so picking then pressing Note is the mouse flow.
607
- */
608
- #justAnswered: { questionIndex: number; rowKey: string } | undefined;
609
618
  readonly #panel: OverlayPanel;
610
619
  readonly #headerRegion: PanelRows;
611
620
  readonly #bodyRegion: PanelRows;
@@ -625,6 +634,7 @@ export class AskDialogComponent implements Component {
625
634
  selectedOptions: new Set<string>(),
626
635
  customInput: undefined,
627
636
  customInputImages: undefined,
637
+ customDraft: undefined,
628
638
  note: undefined,
629
639
  noteImages: undefined,
630
640
  noteRowKey: undefined,
@@ -703,7 +713,6 @@ export class AskDialogComponent implements Component {
703
713
  // closed/prompt guards, matching HookSelector/HookInput semantics.
704
714
  this.#countdown?.reset();
705
715
  this.#native = undefined;
706
- if (keyData !== "n" && keyData !== "N") this.#justAnswered = undefined;
707
716
  if (matchesSelectCancel(keyData)) {
708
717
  this.#finishCancel();
709
718
  return;
@@ -945,6 +954,8 @@ export class AskDialogComponent implements Component {
945
954
  ...(detail ? { detail } : {}),
946
955
  ...(recommended ? { value: [span("Recommended")] } : {}),
947
956
  ...(checked ? { tone: "accent" as const, ...(question.multi ? { icon: "check" } : {}) } : {}),
957
+ // Notes this row without picking it, wherever the cursor is.
958
+ actions: { menu: ["note"] },
948
959
  },
949
960
  undefined,
950
961
  rowItem.key,
@@ -1038,7 +1049,7 @@ export class AskDialogComponent implements Component {
1038
1049
  });
1039
1050
  const note = actionButton("Note", "note", {
1040
1051
  keys: "n",
1041
- title: "Add a note to the highlighted answer, or to the one just picked n",
1052
+ title: "Add a note to the highlighted answer n",
1042
1053
  });
1043
1054
  return actionBar([...lead, null, note, skip, submit]);
1044
1055
  }
@@ -1047,12 +1058,11 @@ export class AskDialogComponent implements Component {
1047
1058
  * Pointer actions: a tab click switches to it; a click on an answer row is
1048
1059
  * Enter on it (Space for a multi-select option, so it toggles; its
1049
1060
  * double-click `activate` is Enter); the action bar's Submit, Note and Skip
1050
- * run what Enter (see {@link #pressEnter} for Other), `n` and Esc run on the highlighted row; Hide/Show
1051
- * collapse and restore the dialog.
1061
+ * run what Enter (see {@link #pressEnter} for Other), `n` and Esc run on the highlighted row, and a
1062
+ * row's menu Note highlights that row and notes it; Hide/Show collapse and restore the dialog.
1052
1063
  */
1053
1064
  handleNativeEvent(event: NativeUiEvent): void {
1054
1065
  if (this.#closed || this.#promptActive) return;
1055
- if (event.type !== "action" || event.act !== "note") this.#justAnswered = undefined;
1056
1066
  if (event.type === "action") {
1057
1067
  if (event.act === "cancel") {
1058
1068
  this.#finishCancel();
@@ -1066,7 +1076,7 @@ export class AskDialogComponent implements Component {
1066
1076
  // A pointer action on the dialog is an explicit hand-off from the draft.
1067
1077
  this.#releaseGuardForPointer();
1068
1078
  if (event.act === "submit") this.#pressEnter();
1069
- else if (event.act === "note") this.#pressNote();
1079
+ else if (event.act === "note") this.#noteFromPointer(event.key);
1070
1080
  return;
1071
1081
  }
1072
1082
  if (event.type !== "select" && event.type !== "activate") return;
@@ -1116,37 +1126,38 @@ export class AskDialogComponent implements Component {
1116
1126
  const rowItem = active ? this.#questionRows(active.question)[active.state.cursorIndex] : undefined;
1117
1127
  if (!active || !rowItem) return;
1118
1128
  if (rowItem.kind === "other" && this.#hasSubmitTab()) {
1119
- this.#advanceAfterQuestion(active.state.customInput === undefined ? undefined : rowItem.key);
1129
+ this.#advanceAfterQuestion();
1120
1130
  return;
1121
1131
  }
1122
1132
  this.#commitRow(active.question, active.state, rowItem, true);
1123
1133
  this.#requestRender();
1124
1134
  }
1125
1135
 
1126
- /** `n`: a note on the {@link #noteTarget} row (questions only). */
1136
+ /** `n`: a note on the highlighted row of the question shown (questions only). */
1127
1137
  #pressNote(): void {
1128
1138
  if (this.#isSubmitTab()) return;
1129
1139
  this.#countdown?.reset();
1130
- const target = this.#noteTarget();
1131
- if (target) void this.#promptForNote(target.question, target.state, target.rowItem);
1140
+ const active = this.#activeQuestionState();
1141
+ const rowItem = active ? this.#questionRows(active.question)[active.state.cursorIndex] : undefined;
1142
+ if (active && rowItem) void this.#promptForNote(active.question, active.state, rowItem);
1132
1143
  }
1133
1144
 
1134
1145
  /**
1135
- * The row a note goes to: the answer just picked while the question it moved on to is still
1136
- * unanswered, else the highlighted row.
1146
+ * Note from the action bar (keypath `…/note`: the highlighted row) or from a row's menu (keypath
1147
+ * `…/q<i>/<row>`: that row, highlighted first). A menu on a list the dialog has moved past does nothing.
1137
1148
  */
1138
- #noteTarget(): { question: ExtensionAskDialogQuestion; state: QuestionState; rowItem: QuestionRow } | undefined {
1139
- const active = this.#activeQuestionState();
1140
- if (!active) return undefined;
1141
- const last = this.#justAnswered;
1142
- if (last && last.questionIndex !== this.#currentQuestionIndex() && !isAnswered(active.state)) {
1143
- const question = this.#questions[last.questionIndex];
1144
- const state = this.#states[last.questionIndex];
1145
- const rowItem = question ? this.#questionRows(question).find(row => row.key === last.rowKey) : undefined;
1146
- if (question && state && rowItem) return { question, state, rowItem };
1149
+ #noteFromPointer(keypath: string): void {
1150
+ const [listKey, rowKey] = keypath.split("/").slice(-2);
1151
+ if (listKey && /^q\d+$/.test(listKey)) {
1152
+ const active = this.#activeQuestionState();
1153
+ if (!active || this.#isSubmitTab() || listKey !== `q${this.#currentQuestionIndex()}`) return;
1154
+ const index = this.#questionRows(active.question).findIndex(row => row.key === rowKey);
1155
+ if (index < 0) return;
1156
+ active.state.cursorIndex = index;
1157
+ active.state.manualScroll = false;
1158
+ this.#requestRender();
1147
1159
  }
1148
- const rowItem = this.#questionRows(active.question)[active.state.cursorIndex];
1149
- return rowItem ? { question: active.question, state: active.state, rowItem } : undefined;
1160
+ this.#pressNote();
1150
1161
  }
1151
1162
 
1152
1163
  /** Re-describe once a second while a countdown ring is shown (the ring's value is data, not a terminal clock). */
@@ -1448,7 +1459,7 @@ export class AskDialogComponent implements Component {
1448
1459
  // focused option; Space toggles. Advances to the next question
1449
1460
  // (submitting only for a single-question dialog), matching
1450
1461
  // single-select Enter (#8252).
1451
- this.#advanceAfterQuestion(state.selectedOptions.has(option.label) ? rowItem.key : undefined);
1462
+ this.#advanceAfterQuestion();
1452
1463
  return;
1453
1464
  }
1454
1465
  if (state.selectedOptions.has(option.label)) {
@@ -1464,7 +1475,7 @@ export class AskDialogComponent implements Component {
1464
1475
  state.customInput = undefined;
1465
1476
  state.customInputImages = undefined;
1466
1477
  clearNoteUnlessRow(state, rowItem.key);
1467
- this.#advanceAfterQuestion(rowItem.key);
1478
+ this.#advanceAfterQuestion();
1468
1479
  }
1469
1480
 
1470
1481
  #handleSubmitTabInput(keyData: string): void {
@@ -1489,13 +1500,9 @@ export class AskDialogComponent implements Component {
1489
1500
  this.#submitScrollOffset = 0;
1490
1501
  }
1491
1502
 
1492
- /** Move past the current question; `answeredRowKey` is the row whose pick did it, for {@link #noteTarget}. */
1493
- #advanceAfterQuestion(answeredRowKey?: string): void {
1503
+ /** Move past the current question (submits a single-question dialog). */
1504
+ #advanceAfterQuestion(): void {
1494
1505
  const current = this.#currentQuestionIndex();
1495
- this.#justAnswered =
1496
- answeredRowKey !== undefined && this.#questions.length > 1
1497
- ? { questionIndex: current, rowKey: answeredRowKey }
1498
- : undefined;
1499
1506
  if (this.#questions.length === 1) {
1500
1507
  this.#finishSubmit();
1501
1508
  return;
@@ -1512,7 +1519,7 @@ export class AskDialogComponent implements Component {
1512
1519
  #openPrompt(
1513
1520
  prompt: AskDialogPrompt,
1514
1521
  prefill: AskDialogPromptValue | undefined,
1515
- ): Promise<string | AskDialogPromptValue | undefined> {
1522
+ ): Promise<string | AskDialogPromptValue | AskDialogPromptDraft | undefined> {
1516
1523
  return this.callbacks.onImagePrompt
1517
1524
  ? this.callbacks.onImagePrompt(prompt, prefill)
1518
1525
  : this.callbacks.onPrompt(prompt, prefill?.text);
@@ -1525,11 +1532,21 @@ export class AskDialogComponent implements Component {
1525
1532
  ): Promise<void> {
1526
1533
  this.#promptActive = true;
1527
1534
  try {
1535
+ // A cancelled edit's draft wins over the submitted answer it was revising.
1528
1536
  const prefill =
1529
- state.customInput === undefined ? undefined : { text: state.customInput, images: state.customInputImages };
1537
+ state.customDraft ??
1538
+ (state.customInput === undefined
1539
+ ? undefined
1540
+ : { text: state.customInput, images: state.customInputImages });
1530
1541
  const result = await this.#openPrompt({ title: "Custom answer", question: question.question }, prefill);
1531
- if (result === undefined || this.#closed) return;
1532
- const input = splitPromptInput(result);
1542
+ if (this.#closed) return;
1543
+ const input = promptOutcome(result);
1544
+ if (!input.submitted) {
1545
+ const draft = input.draft;
1546
+ state.customDraft = draft && (draft.text.trim() !== "" || draft.images?.length) ? draft : undefined;
1547
+ return;
1548
+ }
1549
+ state.customDraft = undefined;
1533
1550
  if (input.text.trim() === "") {
1534
1551
  // Submitting an empty value unselects the custom answer.
1535
1552
  state.customInput = undefined;
@@ -1547,7 +1564,7 @@ export class AskDialogComponent implements Component {
1547
1564
  this.#activeTabIndex = this.#submitTabIndex();
1548
1565
  this.#submitScrollOffset = 0;
1549
1566
  } else {
1550
- this.#advanceAfterQuestion(rowItem.key);
1567
+ this.#advanceAfterQuestion();
1551
1568
  }
1552
1569
  } finally {
1553
1570
  this.#promptActive = false;
@@ -1570,12 +1587,12 @@ export class AskDialogComponent implements Component {
1570
1587
  { title: `Note for ${rowItem.label}`, question: question.question },
1571
1588
  prefill,
1572
1589
  );
1573
- if (result === undefined || this.#closed) return;
1574
- const note = splitPromptInput(result);
1590
+ if (this.#closed) return;
1591
+ const note = promptOutcome(result);
1592
+ if (!note.submitted) return;
1575
1593
  state.note = note.text;
1576
1594
  state.noteImages = note.images;
1577
1595
  state.noteRowKey = rowItem.key;
1578
- this.#justAnswered = undefined;
1579
1596
  } finally {
1580
1597
  this.#promptActive = false;
1581
1598
  this.#runDeferredTimeout();
@@ -7,9 +7,9 @@ export interface CodeBlock {
7
7
  /** Block body with the trailing newline stripped. */
8
8
  code: string;
9
9
  }
10
- /** A blockquote block: a maximal run of `>`-prefixed lines from markdown. */
10
+ /** A blockquote block, as the renderer draws it. */
11
11
  export interface QuoteBlock {
12
- /** Block body with each line's `>` marker (and one optional space) removed. */
12
+ /** Block body with the `>` markers removed. */
13
13
  text: string;
14
14
  }
15
15
  /** A drillable block within an assistant message, in document order. */
@@ -26,10 +26,12 @@ export interface LastCommand {
26
26
  language: string;
27
27
  }
28
28
  /**
29
- * Split assistant markdown into drillable blocks — fenced code and `>`-quoted
30
- * runs — in document order. Fences mask their bodies, so a `>` line inside a
31
- * code block is never mistaken for a quote. An unclosed fence is treated as
32
- * ordinary text, matching the fenced-block grammar.
29
+ * Split assistant markdown into drillable blocks — fenced code and
30
+ * blockquotes — in document order. Tokenization is the renderer's own
31
+ * ({@link lexDocument}), so fences nested in list items, fence closing rules,
32
+ * list boundaries and lazy quote continuations agree with the screen. Code
33
+ * inside a quote stays part of the quote; indented (non-fenced) code blocks
34
+ * are not offered.
33
35
  */
34
36
  export declare function extractBlocks(text: string): MessageBlock[];
35
37
  /** Extract fenced code blocks from assistant markdown, in document order. */
@@ -1,6 +1,7 @@
1
1
  import type { AgentMessage } from "@linxiraos/pi-agent-core";
2
2
  import type { ToolCall } from "@linxiraos/pi-ai";
3
- import { extractMarkdownLinks } from "../index";
3
+ import type { Token, Tokens } from "@linxiraos/pi-utils/marked";
4
+ import { extractMarkdownLinks, lexDocument } from "../index";
4
5
 
5
6
  /** A fenced code block extracted from assistant markdown. */
6
7
  export interface CodeBlock {
@@ -10,9 +11,9 @@ export interface CodeBlock {
10
11
  code: string;
11
12
  }
12
13
 
13
- /** A blockquote block: a maximal run of `>`-prefixed lines from markdown. */
14
+ /** A blockquote block, as the renderer draws it. */
14
15
  export interface QuoteBlock {
15
- /** Block body with each line's `>` marker (and one optional space) removed. */
16
+ /** Block body with the `>` markers removed. */
16
17
  text: string;
17
18
  }
18
19
 
@@ -27,56 +28,34 @@ export interface LastCommand {
27
28
  language: string;
28
29
  }
29
30
 
30
- const OPEN_FENCE_RE = /^```([^\n]*)$/;
31
- const CLOSE_FENCE_RE = /^```/;
32
- const QUOTE_LINE_RE = /^>(.*)$/;
33
-
34
31
  /**
35
- * Split assistant markdown into drillable blocks — fenced code and `>`-quoted
36
- * runs — in document order. Fences mask their bodies, so a `>` line inside a
37
- * code block is never mistaken for a quote. An unclosed fence is treated as
38
- * ordinary text, matching the fenced-block grammar.
32
+ * Split assistant markdown into drillable blocks — fenced code and
33
+ * blockquotes — in document order. Tokenization is the renderer's own
34
+ * ({@link lexDocument}), so fences nested in list items, fence closing rules,
35
+ * list boundaries and lazy quote continuations agree with the screen. Code
36
+ * inside a quote stays part of the quote; indented (non-fenced) code blocks
37
+ * are not offered.
39
38
  */
40
39
  export function extractBlocks(text: string): MessageBlock[] {
41
40
  const blocks: MessageBlock[] = [];
42
- const lines = text.split("\n");
43
- let quote: string[] | undefined;
44
- const flushQuote = () => {
45
- if (quote) {
46
- blocks.push({ kind: "quote", text: quote.join("\n") });
47
- quote = undefined;
48
- }
49
- };
50
-
51
- for (let i = 0; i < lines.length; i++) {
52
- const line = lines[i]!;
53
- const open = OPEN_FENCE_RE.exec(line);
54
- if (open) {
55
- let close = -1;
56
- for (let k = i + 1; k < lines.length; k++) {
57
- if (CLOSE_FENCE_RE.test(lines[k]!)) {
58
- close = k;
59
- break;
41
+ const walk = (tokens: readonly Token[] | undefined): void => {
42
+ if (!tokens) return;
43
+ for (const token of tokens) {
44
+ if (token.type === "code") {
45
+ const code = token as Tokens.Code;
46
+ if (code.codeBlockStyle !== "indented") {
47
+ blocks.push({ kind: "code", lang: (code.lang ?? "").trim(), code: code.text });
60
48
  }
61
- }
62
- if (close !== -1) {
63
- flushQuote();
64
- blocks.push({ kind: "code", lang: open[1].trim(), code: lines.slice(i + 1, close).join("\n") });
65
- i = close;
66
- continue;
49
+ } else if (token.type === "blockquote") {
50
+ blocks.push({ kind: "quote", text: (token as Tokens.Blockquote).text.replace(/\n+$/, "") });
51
+ } else if (token.type === "list") {
52
+ walk((token as Tokens.List).items);
53
+ } else if (token.type === "list_item") {
54
+ walk((token as Tokens.ListItem).tokens);
67
55
  }
68
56
  }
69
-
70
- const quoted = QUOTE_LINE_RE.exec(line);
71
- if (quoted) {
72
- // Strip the `>` marker plus one optional following space.
73
- quote ??= [];
74
- quote.push(quoted[1].startsWith(" ") ? quoted[1].slice(1) : quoted[1]);
75
- } else {
76
- flushQuote();
77
- }
78
- }
79
- flushQuote();
57
+ };
58
+ walk(lexDocument(text));
80
59
  return blocks;
81
60
  }
82
61