@astralyn/pi 0.82.4 → 0.82.5

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 (89) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/core/agent-session.d.ts.map +1 -1
  3. package/dist/core/agent-session.js +2 -2
  4. package/dist/core/agent-session.js.map +1 -1
  5. package/dist/core/extensions/index.d.ts +1 -1
  6. package/dist/core/extensions/index.d.ts.map +1 -1
  7. package/dist/core/extensions/index.js +1 -1
  8. package/dist/core/extensions/index.js.map +1 -1
  9. package/dist/core/extensions/loader.d.ts +1 -1
  10. package/dist/core/extensions/loader.d.ts.map +1 -1
  11. package/dist/core/extensions/loader.js +2 -3
  12. package/dist/core/extensions/loader.js.map +1 -1
  13. package/dist/core/extensions/types.d.ts +9 -0
  14. package/dist/core/extensions/types.d.ts.map +1 -1
  15. package/dist/core/extensions/types.js +11 -0
  16. package/dist/core/extensions/types.js.map +1 -1
  17. package/dist/extensions/question/dialog.d.ts +3 -1
  18. package/dist/extensions/question/dialog.d.ts.map +1 -1
  19. package/dist/extensions/question/dialog.js +106 -52
  20. package/dist/extensions/question/dialog.js.map +1 -1
  21. package/dist/extensions/question/index.d.ts.map +1 -1
  22. package/dist/extensions/question/index.js +2 -2
  23. package/dist/extensions/question/index.js.map +1 -1
  24. package/dist/extensions/question/render-cache.d.ts +9 -0
  25. package/dist/extensions/question/render-cache.d.ts.map +1 -1
  26. package/dist/extensions/question/render-cache.js +22 -0
  27. package/dist/extensions/question/render-cache.js.map +1 -1
  28. package/dist/extensions/question/results.d.ts.map +1 -1
  29. package/dist/extensions/question/results.js +6 -1
  30. package/dist/extensions/question/results.js.map +1 -1
  31. package/dist/extensions/question/schema.d.ts +4 -0
  32. package/dist/extensions/question/schema.d.ts.map +1 -1
  33. package/dist/extensions/question/schema.js +19 -28
  34. package/dist/extensions/question/schema.js.map +1 -1
  35. package/dist/extensions/question/types.d.ts +1 -1
  36. package/dist/extensions/question/types.d.ts.map +1 -1
  37. package/dist/extensions/question/types.js.map +1 -1
  38. package/dist/extensions/subagent/agents.d.ts.map +1 -1
  39. package/dist/extensions/subagent/agents.js +12 -6
  40. package/dist/extensions/subagent/agents.js.map +1 -1
  41. package/dist/extensions/subagent/constants.d.ts +1 -1
  42. package/dist/extensions/subagent/constants.d.ts.map +1 -1
  43. package/dist/extensions/subagent/constants.js +3 -2
  44. package/dist/extensions/subagent/constants.js.map +1 -1
  45. package/dist/extensions/subagent/runner.d.ts +1 -1
  46. package/dist/extensions/subagent/runner.d.ts.map +1 -1
  47. package/dist/extensions/subagent/runner.js +5 -1
  48. package/dist/extensions/subagent/runner.js.map +1 -1
  49. package/dist/extensions/subagent/schema.d.ts.map +1 -1
  50. package/dist/extensions/subagent/schema.js +2 -2
  51. package/dist/extensions/subagent/schema.js.map +1 -1
  52. package/dist/extensions/subagent/sdk-runner.d.ts.map +1 -1
  53. package/dist/extensions/subagent/sdk-runner.js +5 -0
  54. package/dist/extensions/subagent/sdk-runner.js.map +1 -1
  55. package/dist/extensions/subagent/types.d.ts +7 -0
  56. package/dist/extensions/subagent/types.d.ts.map +1 -1
  57. package/dist/extensions/subagent/types.js.map +1 -1
  58. package/dist/extensions/todo/constants.d.ts +1 -1
  59. package/dist/extensions/todo/constants.d.ts.map +1 -1
  60. package/dist/extensions/todo/constants.js +29 -4
  61. package/dist/extensions/todo/constants.js.map +1 -1
  62. package/dist/extensions/todo/index.d.ts +1 -1
  63. package/dist/extensions/todo/index.d.ts.map +1 -1
  64. package/dist/extensions/todo/index.js +22 -3
  65. package/dist/extensions/todo/index.js.map +1 -1
  66. package/dist/extensions/todo/schema.d.ts +6 -5
  67. package/dist/extensions/todo/schema.d.ts.map +1 -1
  68. package/dist/extensions/todo/schema.js +20 -9
  69. package/dist/extensions/todo/schema.js.map +1 -1
  70. package/dist/extensions/todo/state.d.ts +5 -1
  71. package/dist/extensions/todo/state.d.ts.map +1 -1
  72. package/dist/extensions/todo/state.js +184 -38
  73. package/dist/extensions/todo/state.js.map +1 -1
  74. package/dist/extensions/todo/view.d.ts.map +1 -1
  75. package/dist/extensions/todo/view.js +10 -6
  76. package/dist/extensions/todo/view.js.map +1 -1
  77. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  78. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  79. package/dist/modes/interactive/interactive-mode.js +34 -1
  80. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  81. package/dist/utils/coalescing-terminal.d.ts +71 -17
  82. package/dist/utils/coalescing-terminal.d.ts.map +1 -1
  83. package/dist/utils/coalescing-terminal.js +136 -31
  84. package/dist/utils/coalescing-terminal.js.map +1 -1
  85. package/docs/bundled/extensions/question.md +9 -7
  86. package/docs/bundled/extensions/subagent.md +2 -2
  87. package/docs/bundled/extensions/todo.md +5 -3
  88. package/npm-shrinkwrap.json +2 -2
  89. package/package.json +1 -1
@@ -18,29 +18,82 @@ import { ProcessTerminal } from "@earendil-works/pi-tui";
18
18
  *
19
19
  * Scrollback preservation: pi-tui's fullRender(clear) opens with
20
20
  * `2J H 3J`, wiping the terminal's scrollback, and then replays the entire
21
- * transcript. Content-driven triggers (a line changing above the viewport
22
- * during streaming markdown reflow, large content shrinks) fire this
23
- * routinely, which erases pre-session shell history and — in terminals that
24
- * clamp the scroll offset when scrollback vanishes, notably Windows
25
- * Terminal — yanks a scrolled-up viewport to the top of the buffer
26
- * (upstream #6502, #5576, #6050; rejected upstream fix #4204). Frames
27
- * matching that shape are rewritten to overwrite the visible screen in place
28
- * (home, erase-and-rewrite each row, erase below) with only the bottom
29
- * viewport-height rows, which leaves scrollback (and the reader's scroll
30
- * position) untouched while producing a byte-identical final screen state.
31
- * ED 2 is avoided entirely because conhost/Windows Terminal implement it by
32
- * scrolling the screen contents into scrollback rather than erasing in
33
- * place. Width-change redraws keep the upstream wipe because
34
- * re-wrapped content genuinely invalidates old scrollback, and frames
35
- * containing kitty graphics pass through untouched. A frame that does not
36
- * match the expected shape is passed through unchanged, so if upstream
37
- * reshapes its render output the wrapper degrades back to stock behavior.
21
+ * transcript. During streaming, content-driven triggers (a line changing
22
+ * above the viewport during markdown reflow) fire this routinely, which — in
23
+ * terminals that clamp the scroll offset when scrollback vanishes, notably
24
+ * Windows Terminal — yanks a scrolled-up reader to the top of the buffer on
25
+ * every reflow (upstream #6502, #5576, #6050; rejected upstream fix #4204).
26
+ *
27
+ * Preservation is therefore windowed, not permanent: the host enables it via
28
+ * setScrollbackPreservation while an agent run is mutating the transcript
29
+ * (and keeps it on until the user's next input after the run settles, since
30
+ * they may still be scrolled up reading), and leaves it off otherwise. An
31
+ * idle-session full redraw — Ctrl+O toggles, mode switches — passes through
32
+ * with upstream's wipe-and-replay, whose result is byte-perfect: scrollback
33
+ * becomes the clean new transcript. Mid-run user toggles can arm
34
+ * passNextFullRedraw for the same clean replay on their own frame.
35
+ *
36
+ * While preservation is active, a matching frame is rewritten to repaint
37
+ * without the wipe. With setViewportTopProvider wired, the rewrite knows
38
+ * which transcript line the visible screen starts at, so a frame that grew
39
+ * the transcript repaints the on-screen rows with the new content at those
40
+ * same positions and then scrolls the extra lines in at the bottom row.
41
+ * Each bottom-row newline pushes the top row — already repainted with the
42
+ * correct new content — into scrollback, exactly like ordinary streaming
43
+ * output, so scrollback ends up byte-equivalent to the upstream full replay
44
+ * without ever clearing it. Without the provider, or when the transcript
45
+ * shrank (lines cannot be pulled back out of scrollback), the rewrite falls
46
+ * back to overwriting the visible screen in place with the bottom
47
+ * viewport-height rows, at the cost of a stale seam above the screen. ED 2
48
+ * is avoided entirely in rewritten frames because conhost/Windows Terminal
49
+ * implement it by scrolling the screen contents into scrollback rather than
50
+ * erasing in place.
51
+ *
52
+ * Width- and height-change redraws keep the upstream wipe because re-wrapped
53
+ * content genuinely invalidates old scrollback, and frames containing kitty
54
+ * graphics pass through untouched. A frame that does not match the expected
55
+ * shape is passed through unchanged, so if upstream reshapes its render
56
+ * output the wrapper degrades back to stock behavior.
38
57
  */
39
58
  export declare class CoalescingTerminal extends ProcessTerminal {
40
59
  private pending;
41
60
  private flushQueued;
42
61
  private lastWriteColumns;
62
+ private lastWriteRows;
63
+ private viewportTopProvider;
64
+ private preserve;
65
+ private passArmed;
43
66
  private flushOnExit;
67
+ /**
68
+ * Enable or disable the scrollback-preserving rewrite. Preservation is
69
+ * only worth its imperfections (stale renderings above the screen, seams
70
+ * on shrink) while the transcript is mutating on its own and the reader
71
+ * may be scrolled up — i.e. during an agent run and until the user's next
72
+ * input after it settles. Outside that window every full redraw passes
73
+ * through with upstream's wipe-and-replay, whose result is byte-perfect:
74
+ * scrollback becomes the clean new transcript. Default: disabled.
75
+ */
76
+ setScrollbackPreservation(enabled: boolean): void;
77
+ /**
78
+ * Arm a one-shot exemption for an explicit user action (Ctrl+O tool
79
+ * expansion, thinking visibility) so its own full redraw keeps the
80
+ * upstream wipe-and-replay even while preservation is active mid-run.
81
+ * The user just pressed a key, so they are interacting at the bottom;
82
+ * a clean replay beats preservation's stale-seam trade-offs there. The
83
+ * flag is cleared by the next write so it cannot leak onto a later
84
+ * streaming redraw.
85
+ */
86
+ passNextFullRedraw(): void;
87
+ /**
88
+ * Wire the renderer's notion of which transcript line the visible screen
89
+ * currently starts at (pi-tui's `previousViewportTop`). Full-redraw frames
90
+ * that grew the transcript then scroll the new above-screen lines into
91
+ * scrollback instead of dropping them. The provider is read while the
92
+ * frame is being written, i.e. before the renderer updates its own
93
+ * bookkeeping for that frame; returning undefined falls back to the
94
+ * bottom-anchored in-place repaint.
95
+ */
96
+ setViewportTopProvider(provider: () => number | undefined): void;
44
97
  constructor();
45
98
  write(data: string): void;
46
99
  moveBy(lines: number): void;
@@ -57,6 +110,7 @@ export declare class CoalescingTerminal extends ProcessTerminal {
57
110
  * touching kitty images — passes through unchanged.
58
111
  */
59
112
  private preserveScrollback;
113
+ private readViewportTop;
60
114
  private flush;
61
115
  }
62
116
  //# sourceMappingURL=coalescing-terminal.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"coalescing-terminal.d.ts","sourceRoot":"","sources":["../../src/utils/coalescing-terminal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AASzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,qBAAa,kBAAmB,SAAQ,eAAe;IACtD,OAAO,CAAC,OAAO,CAAM;IACrB,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,gBAAgB,CAAqB;IAC7C,OAAO,CAAC,WAAW,CAAsB;IAEzC,cAKC;IAEQ,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAMjC;IAIQ,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAMnC;IAEQ,UAAU,IAAI,IAAI,CAE1B;IAEQ,UAAU,IAAI,IAAI,CAE1B;IAEQ,SAAS,IAAI,IAAI,CAEzB;IAEQ,eAAe,IAAI,IAAI,CAE/B;IAEQ,WAAW,IAAI,IAAI,CAE3B;IAEQ,IAAI,IAAI,IAAI,CAMpB;IAED;;;;;OAKG;IACH,OAAO,CAAC,kBAAkB;IAwC1B,OAAO,CAAC,KAAK;CASb","sourcesContent":["import { ProcessTerminal } from \"@earendil-works/pi-tui\";\n\nconst SYNC_START = \"\\x1b[?2026h\";\nconst SYNC_END = \"\\x1b[?2026l\";\n/** Clear screen, home, clear scrollback — pi-tui's fullRender(clear) preamble. */\nconst CLEAR_WITH_SCROLLBACK = \"\\x1b[2J\\x1b[H\\x1b[3J\";\n/** Kitty graphics APC prefix; frames touching images interleave cursor moves. */\nconst KITTY_APC_PREFIX = \"\\x1b_G\";\n\n/**\n * ProcessTerminal that (1) coalesces every write issued within one synchronous\n * task into a single stdout write and (2) keeps content-driven full redraws\n * from destroying the terminal's scrollback.\n *\n * Coalescing: pi-tui emits each render pass as several separate stdout\n * writes: the frame wrapped in synchronized output (CSI ?2026h/l), then a\n * relative cursor move that parks the hardware cursor at the focused\n * component's caret for IME composition, then a cursor visibility toggle.\n * Terminals that anchor the IME candidate window to the hardware cursor\n * (Windows Terminal and other ConPTY hosts, WezTerm) can process the frame\n * write before the reposition write arrives, briefly leaving the cursor at\n * the end of the last repainted line. With an IME active this makes the\n * candidate window jump between the caret and the right edge of the input\n * line on every keystroke. Merging the writes makes each frame atomic, so the\n * only cursor position a terminal can observe is the final one.\n *\n * Scrollback preservation: pi-tui's fullRender(clear) opens with\n * `2J H 3J`, wiping the terminal's scrollback, and then replays the entire\n * transcript. Content-driven triggers (a line changing above the viewport\n * during streaming markdown reflow, large content shrinks) fire this\n * routinely, which erases pre-session shell history and — in terminals that\n * clamp the scroll offset when scrollback vanishes, notably Windows\n * Terminal — yanks a scrolled-up viewport to the top of the buffer\n * (upstream #6502, #5576, #6050; rejected upstream fix #4204). Frames\n * matching that shape are rewritten to overwrite the visible screen in place\n * (home, erase-and-rewrite each row, erase below) with only the bottom\n * viewport-height rows, which leaves scrollback (and the reader's scroll\n * position) untouched while producing a byte-identical final screen state.\n * ED 2 is avoided entirely because conhost/Windows Terminal implement it by\n * scrolling the screen contents into scrollback rather than erasing in\n * place. Width-change redraws keep the upstream wipe because\n * re-wrapped content genuinely invalidates old scrollback, and frames\n * containing kitty graphics pass through untouched. A frame that does not\n * match the expected shape is passed through unchanged, so if upstream\n * reshapes its render output the wrapper degrades back to stock behavior.\n */\nexport class CoalescingTerminal extends ProcessTerminal {\n\tprivate pending = \"\";\n\tprivate flushQueued = false;\n\tprivate lastWriteColumns: number | undefined;\n\tprivate flushOnExit = () => this.flush();\n\n\tconstructor() {\n\t\tsuper();\n\t\t// A synchronous process.exit() before the queued microtask runs would\n\t\t// otherwise drop the final frame.\n\t\tprocess.on(\"exit\", this.flushOnExit);\n\t}\n\n\toverride write(data: string): void {\n\t\tif (data.length === 0) return;\n\t\tthis.pending += this.preserveScrollback(data);\n\t\tif (this.flushQueued) return;\n\t\tthis.flushQueued = true;\n\t\tqueueMicrotask(() => this.flush());\n\t}\n\n\t// Route every escape-sequence helper through the coalescing buffer so a\n\t// caller mixing helpers with write() keeps its output ordered.\n\toverride moveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\tthis.write(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\tthis.write(`\\x1b[${-lines}A`);\n\t\t}\n\t}\n\n\toverride hideCursor(): void {\n\t\tthis.write(\"\\x1b[?25l\");\n\t}\n\n\toverride showCursor(): void {\n\t\tthis.write(\"\\x1b[?25h\");\n\t}\n\n\toverride clearLine(): void {\n\t\tthis.write(\"\\x1b[K\");\n\t}\n\n\toverride clearFromCursor(): void {\n\t\tthis.write(\"\\x1b[J\");\n\t}\n\n\toverride clearScreen(): void {\n\t\tthis.write(\"\\x1b[2J\\x1b[H\");\n\t}\n\n\toverride stop(): void {\n\t\t// ProcessTerminal.stop() writes its teardown sequences directly to\n\t\t// stdout, so pending frame data must go out first.\n\t\tthis.flush();\n\t\tprocess.removeListener(\"exit\", this.flushOnExit);\n\t\tsuper.stop();\n\t}\n\n\t/**\n\t * Rewrite a full-redraw frame (`?2026h 2J H 3J <lines> ?2026l`) so it\n\t * repaints the screen without wiping scrollback. Anything that does not\n\t * match this exact shape — including width-change redraws and frames\n\t * touching kitty images — passes through unchanged.\n\t */\n\tprivate preserveScrollback(data: string): string {\n\t\tconst columns = this.columns;\n\t\tconst widthChanged = this.lastWriteColumns !== undefined && this.lastWriteColumns !== columns;\n\t\tthis.lastWriteColumns = columns;\n\n\t\tconst prefix = SYNC_START + CLEAR_WITH_SCROLLBACK;\n\t\tif (!data.startsWith(prefix) || !data.endsWith(SYNC_END)) {\n\t\t\treturn data;\n\t\t}\n\t\t// Re-wrapped content invalidates what scrollback holds; keep the wipe.\n\t\tif (widthChanged) {\n\t\t\treturn data;\n\t\t}\n\t\tif (data.includes(KITTY_APC_PREFIX)) {\n\t\t\treturn data;\n\t\t}\n\t\tconst body = data.slice(prefix.length, data.length - SYNC_END.length);\n\t\t// A second clear inside one write means the frame shape changed\n\t\t// upstream; bail out rather than guess.\n\t\tif (body.includes(CLEAR_WITH_SCROLLBACK)) {\n\t\t\treturn data;\n\t\t}\n\t\t// Repaint only the bottom viewport-height rows, overwriting the screen\n\t\t// in place: home, erase-and-rewrite each row, erase whatever remains\n\t\t// below. Writing the full transcript after a screen clear would push a\n\t\t// duplicate copy of everything above the viewport into scrollback; the\n\t\t// truncated overwrite produces the exact same final screen and cursor\n\t\t// position as the full replay (rows beyond the screen would have\n\t\t// scrolled out anyway). ED 2 (`2J`) is deliberately avoided even for\n\t\t// the visible screen: conhost/Windows Terminal implement it by\n\t\t// scrolling the current screen into scrollback (cls compatibility), so\n\t\t// without the `3J` wipe each redraw would stack another screenful of\n\t\t// duplicates into history.\n\t\tconst lines = body.split(\"\\r\\n\");\n\t\tconst rows = this.rows;\n\t\tconst kept = lines.length > rows ? lines.slice(lines.length - rows) : lines;\n\t\tconst repaint = kept.map((line) => `\\x1b[2K${line}`).join(\"\\r\\n\");\n\t\treturn `${SYNC_START}\\x1b[H${repaint}\\x1b[J${SYNC_END}`;\n\t}\n\n\tprivate flush(): void {\n\t\tthis.flushQueued = false;\n\t\tif (this.pending.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst data = this.pending;\n\t\tthis.pending = \"\";\n\t\tsuper.write(data);\n\t}\n}\n"]}
1
+ {"version":3,"file":"coalescing-terminal.d.ts","sourceRoot":"","sources":["../../src/utils/coalescing-terminal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AASzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AACH,qBAAa,kBAAmB,SAAQ,eAAe;IACtD,OAAO,CAAC,OAAO,CAAM;IACrB,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,gBAAgB,CAAqB;IAC7C,OAAO,CAAC,aAAa,CAAqB;IAC1C,OAAO,CAAC,mBAAmB,CAAyC;IACpE,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,WAAW,CAAsB;IAEzC;;;;;;;;OAQG;IACH,yBAAyB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAEhD;IAED;;;;;;;;OAQG;IACH,kBAAkB,IAAI,IAAI,CAEzB;IAED;;;;;;;;OAQG;IACH,sBAAsB,CAAC,QAAQ,EAAE,MAAM,MAAM,GAAG,SAAS,GAAG,IAAI,CAE/D;IAED,cAKC;IAEQ,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAMjC;IAIQ,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAMnC;IAEQ,UAAU,IAAI,IAAI,CAE1B;IAEQ,UAAU,IAAI,IAAI,CAE1B;IAEQ,SAAS,IAAI,IAAI,CAEzB;IAEQ,eAAe,IAAI,IAAI,CAE/B;IAEQ,WAAW,IAAI,IAAI,CAE3B;IAEQ,IAAI,IAAI,IAAI,CAMpB;IAED;;;;;OAKG;IACH,OAAO,CAAC,kBAAkB;IA2E1B,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,KAAK;CASb","sourcesContent":["import { ProcessTerminal } from \"@earendil-works/pi-tui\";\n\nconst SYNC_START = \"\\x1b[?2026h\";\nconst SYNC_END = \"\\x1b[?2026l\";\n/** Clear screen, home, clear scrollback — pi-tui's fullRender(clear) preamble. */\nconst CLEAR_WITH_SCROLLBACK = \"\\x1b[2J\\x1b[H\\x1b[3J\";\n/** Kitty graphics APC prefix; frames touching images interleave cursor moves. */\nconst KITTY_APC_PREFIX = \"\\x1b_G\";\n\n/**\n * ProcessTerminal that (1) coalesces every write issued within one synchronous\n * task into a single stdout write and (2) keeps content-driven full redraws\n * from destroying the terminal's scrollback.\n *\n * Coalescing: pi-tui emits each render pass as several separate stdout\n * writes: the frame wrapped in synchronized output (CSI ?2026h/l), then a\n * relative cursor move that parks the hardware cursor at the focused\n * component's caret for IME composition, then a cursor visibility toggle.\n * Terminals that anchor the IME candidate window to the hardware cursor\n * (Windows Terminal and other ConPTY hosts, WezTerm) can process the frame\n * write before the reposition write arrives, briefly leaving the cursor at\n * the end of the last repainted line. With an IME active this makes the\n * candidate window jump between the caret and the right edge of the input\n * line on every keystroke. Merging the writes makes each frame atomic, so the\n * only cursor position a terminal can observe is the final one.\n *\n * Scrollback preservation: pi-tui's fullRender(clear) opens with\n * `2J H 3J`, wiping the terminal's scrollback, and then replays the entire\n * transcript. During streaming, content-driven triggers (a line changing\n * above the viewport during markdown reflow) fire this routinely, which — in\n * terminals that clamp the scroll offset when scrollback vanishes, notably\n * Windows Terminal — yanks a scrolled-up reader to the top of the buffer on\n * every reflow (upstream #6502, #5576, #6050; rejected upstream fix #4204).\n *\n * Preservation is therefore windowed, not permanent: the host enables it via\n * setScrollbackPreservation while an agent run is mutating the transcript\n * (and keeps it on until the user's next input after the run settles, since\n * they may still be scrolled up reading), and leaves it off otherwise. An\n * idle-session full redraw — Ctrl+O toggles, mode switches — passes through\n * with upstream's wipe-and-replay, whose result is byte-perfect: scrollback\n * becomes the clean new transcript. Mid-run user toggles can arm\n * passNextFullRedraw for the same clean replay on their own frame.\n *\n * While preservation is active, a matching frame is rewritten to repaint\n * without the wipe. With setViewportTopProvider wired, the rewrite knows\n * which transcript line the visible screen starts at, so a frame that grew\n * the transcript repaints the on-screen rows with the new content at those\n * same positions and then scrolls the extra lines in at the bottom row.\n * Each bottom-row newline pushes the top row — already repainted with the\n * correct new content — into scrollback, exactly like ordinary streaming\n * output, so scrollback ends up byte-equivalent to the upstream full replay\n * without ever clearing it. Without the provider, or when the transcript\n * shrank (lines cannot be pulled back out of scrollback), the rewrite falls\n * back to overwriting the visible screen in place with the bottom\n * viewport-height rows, at the cost of a stale seam above the screen. ED 2\n * is avoided entirely in rewritten frames because conhost/Windows Terminal\n * implement it by scrolling the screen contents into scrollback rather than\n * erasing in place.\n *\n * Width- and height-change redraws keep the upstream wipe because re-wrapped\n * content genuinely invalidates old scrollback, and frames containing kitty\n * graphics pass through untouched. A frame that does not match the expected\n * shape is passed through unchanged, so if upstream reshapes its render\n * output the wrapper degrades back to stock behavior.\n */\nexport class CoalescingTerminal extends ProcessTerminal {\n\tprivate pending = \"\";\n\tprivate flushQueued = false;\n\tprivate lastWriteColumns: number | undefined;\n\tprivate lastWriteRows: number | undefined;\n\tprivate viewportTopProvider: (() => number | undefined) | undefined;\n\tprivate preserve = false;\n\tprivate passArmed = false;\n\tprivate flushOnExit = () => this.flush();\n\n\t/**\n\t * Enable or disable the scrollback-preserving rewrite. Preservation is\n\t * only worth its imperfections (stale renderings above the screen, seams\n\t * on shrink) while the transcript is mutating on its own and the reader\n\t * may be scrolled up — i.e. during an agent run and until the user's next\n\t * input after it settles. Outside that window every full redraw passes\n\t * through with upstream's wipe-and-replay, whose result is byte-perfect:\n\t * scrollback becomes the clean new transcript. Default: disabled.\n\t */\n\tsetScrollbackPreservation(enabled: boolean): void {\n\t\tthis.preserve = enabled;\n\t}\n\n\t/**\n\t * Arm a one-shot exemption for an explicit user action (Ctrl+O tool\n\t * expansion, thinking visibility) so its own full redraw keeps the\n\t * upstream wipe-and-replay even while preservation is active mid-run.\n\t * The user just pressed a key, so they are interacting at the bottom;\n\t * a clean replay beats preservation's stale-seam trade-offs there. The\n\t * flag is cleared by the next write so it cannot leak onto a later\n\t * streaming redraw.\n\t */\n\tpassNextFullRedraw(): void {\n\t\tthis.passArmed = true;\n\t}\n\n\t/**\n\t * Wire the renderer's notion of which transcript line the visible screen\n\t * currently starts at (pi-tui's `previousViewportTop`). Full-redraw frames\n\t * that grew the transcript then scroll the new above-screen lines into\n\t * scrollback instead of dropping them. The provider is read while the\n\t * frame is being written, i.e. before the renderer updates its own\n\t * bookkeeping for that frame; returning undefined falls back to the\n\t * bottom-anchored in-place repaint.\n\t */\n\tsetViewportTopProvider(provider: () => number | undefined): void {\n\t\tthis.viewportTopProvider = provider;\n\t}\n\n\tconstructor() {\n\t\tsuper();\n\t\t// A synchronous process.exit() before the queued microtask runs would\n\t\t// otherwise drop the final frame.\n\t\tprocess.on(\"exit\", this.flushOnExit);\n\t}\n\n\toverride write(data: string): void {\n\t\tif (data.length === 0) return;\n\t\tthis.pending += this.preserveScrollback(data);\n\t\tif (this.flushQueued) return;\n\t\tthis.flushQueued = true;\n\t\tqueueMicrotask(() => this.flush());\n\t}\n\n\t// Route every escape-sequence helper through the coalescing buffer so a\n\t// caller mixing helpers with write() keeps its output ordered.\n\toverride moveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\tthis.write(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\tthis.write(`\\x1b[${-lines}A`);\n\t\t}\n\t}\n\n\toverride hideCursor(): void {\n\t\tthis.write(\"\\x1b[?25l\");\n\t}\n\n\toverride showCursor(): void {\n\t\tthis.write(\"\\x1b[?25h\");\n\t}\n\n\toverride clearLine(): void {\n\t\tthis.write(\"\\x1b[K\");\n\t}\n\n\toverride clearFromCursor(): void {\n\t\tthis.write(\"\\x1b[J\");\n\t}\n\n\toverride clearScreen(): void {\n\t\tthis.write(\"\\x1b[2J\\x1b[H\");\n\t}\n\n\toverride stop(): void {\n\t\t// ProcessTerminal.stop() writes its teardown sequences directly to\n\t\t// stdout, so pending frame data must go out first.\n\t\tthis.flush();\n\t\tprocess.removeListener(\"exit\", this.flushOnExit);\n\t\tsuper.stop();\n\t}\n\n\t/**\n\t * Rewrite a full-redraw frame (`?2026h 2J H 3J <lines> ?2026l`) so it\n\t * repaints the screen without wiping scrollback. Anything that does not\n\t * match this exact shape — including width-change redraws and frames\n\t * touching kitty images — passes through unchanged.\n\t */\n\tprivate preserveScrollback(data: string): string {\n\t\tconst columns = this.columns;\n\t\tconst rows = this.rows;\n\t\tconst widthChanged = this.lastWriteColumns !== undefined && this.lastWriteColumns !== columns;\n\t\tconst heightChanged = this.lastWriteRows !== undefined && this.lastWriteRows !== rows;\n\t\tthis.lastWriteColumns = columns;\n\t\tthis.lastWriteRows = rows;\n\t\t// One-shot: the very next write is the armed toggle's own frame (or a\n\t\t// differential frame when the toggle stayed inside the viewport, in\n\t\t// which case no exemption is needed and the flag must not linger).\n\t\tconst passAllowed = this.passArmed;\n\t\tthis.passArmed = false;\n\n\t\tconst prefix = SYNC_START + CLEAR_WITH_SCROLLBACK;\n\t\tif (!data.startsWith(prefix) || !data.endsWith(SYNC_END)) {\n\t\t\treturn data;\n\t\t}\n\t\t// Outside the preservation window (idle sessions, pre-session UI) and\n\t\t// for armed user toggles, upstream's wipe-and-replay is byte-perfect;\n\t\t// let it through.\n\t\tif (!this.preserve || passAllowed) {\n\t\t\treturn data;\n\t\t}\n\t\t// Re-wrapped/re-flowed content invalidates what scrollback holds and\n\t\t// where the screen sits in it; keep the wipe.\n\t\tif (widthChanged || heightChanged) {\n\t\t\treturn data;\n\t\t}\n\t\tif (data.includes(KITTY_APC_PREFIX)) {\n\t\t\treturn data;\n\t\t}\n\t\tconst body = data.slice(prefix.length, data.length - SYNC_END.length);\n\t\t// A second clear inside one write means the frame shape changed\n\t\t// upstream; bail out rather than guess.\n\t\tif (body.includes(CLEAR_WITH_SCROLLBACK)) {\n\t\t\treturn data;\n\t\t}\n\t\t// ED 2 (`2J`) is deliberately avoided in both rewrites below: conhost/\n\t\t// Windows Terminal implement it by scrolling the current screen into\n\t\t// scrollback (cls compatibility), so without the `3J` wipe each redraw\n\t\t// would stack another screenful of duplicates into history.\n\t\tconst lines = body.split(\"\\r\\n\");\n\t\tconst newViewportTop = Math.max(0, lines.length - rows);\n\t\tconst viewportTop = this.readViewportTop();\n\t\tif (viewportTop !== undefined && viewportTop <= newViewportTop) {\n\t\t\t// The transcript grew (or held steady): repaint the rows currently\n\t\t\t// on screen with the new content at those same transcript\n\t\t\t// positions, then scroll the remaining lines in at the bottom row.\n\t\t\t// Each bottom-row newline pushes the already-repainted top row into\n\t\t\t// scrollback, so scrollback receives exactly the new lines the\n\t\t\t// upstream replay would have put there — no wipe, no loss.\n\t\t\tconst onScreen = lines.slice(viewportTop, viewportTop + rows);\n\t\t\tconst scrolled = lines.slice(viewportTop + rows);\n\t\t\tlet repaint = onScreen.map((line) => `\\x1b[2K${line}`).join(\"\\r\\n\");\n\t\t\tfor (const line of scrolled) {\n\t\t\t\trepaint += `\\r\\n\\x1b[2K${line}`;\n\t\t\t}\n\t\t\treturn `${SYNC_START}\\x1b[H${repaint}\\x1b[J${SYNC_END}`;\n\t\t}\n\t\t// Fallback (no provider, or the transcript shrank — lines cannot be\n\t\t// pulled back out of scrollback): repaint only the bottom\n\t\t// viewport-height rows, overwriting the screen in place: home,\n\t\t// erase-and-rewrite each row, erase whatever remains below. Writing the\n\t\t// full transcript after a screen clear would push a duplicate copy of\n\t\t// everything above the viewport into scrollback; the truncated\n\t\t// overwrite produces the exact same final screen and cursor position as\n\t\t// the full replay (rows beyond the screen would have scrolled out\n\t\t// anyway).\n\t\tconst kept = lines.length > rows ? lines.slice(lines.length - rows) : lines;\n\t\tconst repaint = kept.map((line) => `\\x1b[2K${line}`).join(\"\\r\\n\");\n\t\treturn `${SYNC_START}\\x1b[H${repaint}\\x1b[J${SYNC_END}`;\n\t}\n\n\t// The provider reaches into the renderer's bookkeeping; treat anything\n\t// unexpected as \"unknown\" and fall back rather than corrupt the screen.\n\tprivate readViewportTop(): number | undefined {\n\t\tif (!this.viewportTopProvider) return undefined;\n\t\ttry {\n\t\t\tconst value = this.viewportTopProvider();\n\t\t\treturn typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate flush(): void {\n\t\tthis.flushQueued = false;\n\t\tif (this.pending.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst data = this.pending;\n\t\tthis.pending = \"\";\n\t\tsuper.write(data);\n\t}\n}\n"]}
@@ -24,29 +24,88 @@ const KITTY_APC_PREFIX = "\x1b_G";
24
24
  *
25
25
  * Scrollback preservation: pi-tui's fullRender(clear) opens with
26
26
  * `2J H 3J`, wiping the terminal's scrollback, and then replays the entire
27
- * transcript. Content-driven triggers (a line changing above the viewport
28
- * during streaming markdown reflow, large content shrinks) fire this
29
- * routinely, which erases pre-session shell history and — in terminals that
30
- * clamp the scroll offset when scrollback vanishes, notably Windows
31
- * Terminal — yanks a scrolled-up viewport to the top of the buffer
32
- * (upstream #6502, #5576, #6050; rejected upstream fix #4204). Frames
33
- * matching that shape are rewritten to overwrite the visible screen in place
34
- * (home, erase-and-rewrite each row, erase below) with only the bottom
35
- * viewport-height rows, which leaves scrollback (and the reader's scroll
36
- * position) untouched while producing a byte-identical final screen state.
37
- * ED 2 is avoided entirely because conhost/Windows Terminal implement it by
38
- * scrolling the screen contents into scrollback rather than erasing in
39
- * place. Width-change redraws keep the upstream wipe because
40
- * re-wrapped content genuinely invalidates old scrollback, and frames
41
- * containing kitty graphics pass through untouched. A frame that does not
42
- * match the expected shape is passed through unchanged, so if upstream
43
- * reshapes its render output the wrapper degrades back to stock behavior.
27
+ * transcript. During streaming, content-driven triggers (a line changing
28
+ * above the viewport during markdown reflow) fire this routinely, which — in
29
+ * terminals that clamp the scroll offset when scrollback vanishes, notably
30
+ * Windows Terminal — yanks a scrolled-up reader to the top of the buffer on
31
+ * every reflow (upstream #6502, #5576, #6050; rejected upstream fix #4204).
32
+ *
33
+ * Preservation is therefore windowed, not permanent: the host enables it via
34
+ * setScrollbackPreservation while an agent run is mutating the transcript
35
+ * (and keeps it on until the user's next input after the run settles, since
36
+ * they may still be scrolled up reading), and leaves it off otherwise. An
37
+ * idle-session full redraw — Ctrl+O toggles, mode switches — passes through
38
+ * with upstream's wipe-and-replay, whose result is byte-perfect: scrollback
39
+ * becomes the clean new transcript. Mid-run user toggles can arm
40
+ * passNextFullRedraw for the same clean replay on their own frame.
41
+ *
42
+ * While preservation is active, a matching frame is rewritten to repaint
43
+ * without the wipe. With setViewportTopProvider wired, the rewrite knows
44
+ * which transcript line the visible screen starts at, so a frame that grew
45
+ * the transcript repaints the on-screen rows with the new content at those
46
+ * same positions and then scrolls the extra lines in at the bottom row.
47
+ * Each bottom-row newline pushes the top row — already repainted with the
48
+ * correct new content — into scrollback, exactly like ordinary streaming
49
+ * output, so scrollback ends up byte-equivalent to the upstream full replay
50
+ * without ever clearing it. Without the provider, or when the transcript
51
+ * shrank (lines cannot be pulled back out of scrollback), the rewrite falls
52
+ * back to overwriting the visible screen in place with the bottom
53
+ * viewport-height rows, at the cost of a stale seam above the screen. ED 2
54
+ * is avoided entirely in rewritten frames because conhost/Windows Terminal
55
+ * implement it by scrolling the screen contents into scrollback rather than
56
+ * erasing in place.
57
+ *
58
+ * Width- and height-change redraws keep the upstream wipe because re-wrapped
59
+ * content genuinely invalidates old scrollback, and frames containing kitty
60
+ * graphics pass through untouched. A frame that does not match the expected
61
+ * shape is passed through unchanged, so if upstream reshapes its render
62
+ * output the wrapper degrades back to stock behavior.
44
63
  */
45
64
  export class CoalescingTerminal extends ProcessTerminal {
46
65
  pending = "";
47
66
  flushQueued = false;
48
67
  lastWriteColumns;
68
+ lastWriteRows;
69
+ viewportTopProvider;
70
+ preserve = false;
71
+ passArmed = false;
49
72
  flushOnExit = () => this.flush();
73
+ /**
74
+ * Enable or disable the scrollback-preserving rewrite. Preservation is
75
+ * only worth its imperfections (stale renderings above the screen, seams
76
+ * on shrink) while the transcript is mutating on its own and the reader
77
+ * may be scrolled up — i.e. during an agent run and until the user's next
78
+ * input after it settles. Outside that window every full redraw passes
79
+ * through with upstream's wipe-and-replay, whose result is byte-perfect:
80
+ * scrollback becomes the clean new transcript. Default: disabled.
81
+ */
82
+ setScrollbackPreservation(enabled) {
83
+ this.preserve = enabled;
84
+ }
85
+ /**
86
+ * Arm a one-shot exemption for an explicit user action (Ctrl+O tool
87
+ * expansion, thinking visibility) so its own full redraw keeps the
88
+ * upstream wipe-and-replay even while preservation is active mid-run.
89
+ * The user just pressed a key, so they are interacting at the bottom;
90
+ * a clean replay beats preservation's stale-seam trade-offs there. The
91
+ * flag is cleared by the next write so it cannot leak onto a later
92
+ * streaming redraw.
93
+ */
94
+ passNextFullRedraw() {
95
+ this.passArmed = true;
96
+ }
97
+ /**
98
+ * Wire the renderer's notion of which transcript line the visible screen
99
+ * currently starts at (pi-tui's `previousViewportTop`). Full-redraw frames
100
+ * that grew the transcript then scroll the new above-screen lines into
101
+ * scrollback instead of dropping them. The provider is read while the
102
+ * frame is being written, i.e. before the renderer updates its own
103
+ * bookkeeping for that frame; returning undefined falls back to the
104
+ * bottom-anchored in-place repaint.
105
+ */
106
+ setViewportTopProvider(provider) {
107
+ this.viewportTopProvider = provider;
108
+ }
50
109
  constructor() {
51
110
  super();
52
111
  // A synchronous process.exit() before the queued microtask runs would
@@ -102,14 +161,29 @@ export class CoalescingTerminal extends ProcessTerminal {
102
161
  */
103
162
  preserveScrollback(data) {
104
163
  const columns = this.columns;
164
+ const rows = this.rows;
105
165
  const widthChanged = this.lastWriteColumns !== undefined && this.lastWriteColumns !== columns;
166
+ const heightChanged = this.lastWriteRows !== undefined && this.lastWriteRows !== rows;
106
167
  this.lastWriteColumns = columns;
168
+ this.lastWriteRows = rows;
169
+ // One-shot: the very next write is the armed toggle's own frame (or a
170
+ // differential frame when the toggle stayed inside the viewport, in
171
+ // which case no exemption is needed and the flag must not linger).
172
+ const passAllowed = this.passArmed;
173
+ this.passArmed = false;
107
174
  const prefix = SYNC_START + CLEAR_WITH_SCROLLBACK;
108
175
  if (!data.startsWith(prefix) || !data.endsWith(SYNC_END)) {
109
176
  return data;
110
177
  }
111
- // Re-wrapped content invalidates what scrollback holds; keep the wipe.
112
- if (widthChanged) {
178
+ // Outside the preservation window (idle sessions, pre-session UI) and
179
+ // for armed user toggles, upstream's wipe-and-replay is byte-perfect;
180
+ // let it through.
181
+ if (!this.preserve || passAllowed) {
182
+ return data;
183
+ }
184
+ // Re-wrapped/re-flowed content invalidates what scrollback holds and
185
+ // where the screen sits in it; keep the wipe.
186
+ if (widthChanged || heightChanged) {
113
187
  return data;
114
188
  }
115
189
  if (data.includes(KITTY_APC_PREFIX)) {
@@ -121,23 +195,54 @@ export class CoalescingTerminal extends ProcessTerminal {
121
195
  if (body.includes(CLEAR_WITH_SCROLLBACK)) {
122
196
  return data;
123
197
  }
124
- // Repaint only the bottom viewport-height rows, overwriting the screen
125
- // in place: home, erase-and-rewrite each row, erase whatever remains
126
- // below. Writing the full transcript after a screen clear would push a
127
- // duplicate copy of everything above the viewport into scrollback; the
128
- // truncated overwrite produces the exact same final screen and cursor
129
- // position as the full replay (rows beyond the screen would have
130
- // scrolled out anyway). ED 2 (`2J`) is deliberately avoided even for
131
- // the visible screen: conhost/Windows Terminal implement it by
132
- // scrolling the current screen into scrollback (cls compatibility), so
133
- // without the `3J` wipe each redraw would stack another screenful of
134
- // duplicates into history.
198
+ // ED 2 (`2J`) is deliberately avoided in both rewrites below: conhost/
199
+ // Windows Terminal implement it by scrolling the current screen into
200
+ // scrollback (cls compatibility), so without the `3J` wipe each redraw
201
+ // would stack another screenful of duplicates into history.
135
202
  const lines = body.split("\r\n");
136
- const rows = this.rows;
203
+ const newViewportTop = Math.max(0, lines.length - rows);
204
+ const viewportTop = this.readViewportTop();
205
+ if (viewportTop !== undefined && viewportTop <= newViewportTop) {
206
+ // The transcript grew (or held steady): repaint the rows currently
207
+ // on screen with the new content at those same transcript
208
+ // positions, then scroll the remaining lines in at the bottom row.
209
+ // Each bottom-row newline pushes the already-repainted top row into
210
+ // scrollback, so scrollback receives exactly the new lines the
211
+ // upstream replay would have put there — no wipe, no loss.
212
+ const onScreen = lines.slice(viewportTop, viewportTop + rows);
213
+ const scrolled = lines.slice(viewportTop + rows);
214
+ let repaint = onScreen.map((line) => `\x1b[2K${line}`).join("\r\n");
215
+ for (const line of scrolled) {
216
+ repaint += `\r\n\x1b[2K${line}`;
217
+ }
218
+ return `${SYNC_START}\x1b[H${repaint}\x1b[J${SYNC_END}`;
219
+ }
220
+ // Fallback (no provider, or the transcript shrank — lines cannot be
221
+ // pulled back out of scrollback): repaint only the bottom
222
+ // viewport-height rows, overwriting the screen in place: home,
223
+ // erase-and-rewrite each row, erase whatever remains below. Writing the
224
+ // full transcript after a screen clear would push a duplicate copy of
225
+ // everything above the viewport into scrollback; the truncated
226
+ // overwrite produces the exact same final screen and cursor position as
227
+ // the full replay (rows beyond the screen would have scrolled out
228
+ // anyway).
137
229
  const kept = lines.length > rows ? lines.slice(lines.length - rows) : lines;
138
230
  const repaint = kept.map((line) => `\x1b[2K${line}`).join("\r\n");
139
231
  return `${SYNC_START}\x1b[H${repaint}\x1b[J${SYNC_END}`;
140
232
  }
233
+ // The provider reaches into the renderer's bookkeeping; treat anything
234
+ // unexpected as "unknown" and fall back rather than corrupt the screen.
235
+ readViewportTop() {
236
+ if (!this.viewportTopProvider)
237
+ return undefined;
238
+ try {
239
+ const value = this.viewportTopProvider();
240
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
241
+ }
242
+ catch {
243
+ return undefined;
244
+ }
245
+ }
141
246
  flush() {
142
247
  this.flushQueued = false;
143
248
  if (this.pending.length === 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"coalescing-terminal.js","sourceRoot":"","sources":["../../src/utils/coalescing-terminal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,MAAM,UAAU,GAAG,aAAa,CAAC;AACjC,MAAM,QAAQ,GAAG,aAAa,CAAC;AAC/B,oFAAkF;AAClF,MAAM,qBAAqB,GAAG,sBAAsB,CAAC;AACrD,iFAAiF;AACjF,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AAElC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,MAAM,OAAO,kBAAmB,SAAQ,eAAe;IAC9C,OAAO,GAAG,EAAE,CAAC;IACb,WAAW,GAAG,KAAK,CAAC;IACpB,gBAAgB,CAAqB;IACrC,WAAW,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;IAEzC,cAAc;QACb,KAAK,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,CAAC,CAAC;QACjC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,MAAM,IAAI,GAAG,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;QAC5E,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAClE,OAAO,GAAG,UAAU,SAAS,OAAO,SAAS,QAAQ,EAAE,CAAC;IAAA,CACxD;IAEO,KAAK,GAAS;QACrB,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QACzB,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,OAAO;QACR,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAAA,CAClB;CACD","sourcesContent":["import { ProcessTerminal } from \"@earendil-works/pi-tui\";\n\nconst SYNC_START = \"\\x1b[?2026h\";\nconst SYNC_END = \"\\x1b[?2026l\";\n/** Clear screen, home, clear scrollback — pi-tui's fullRender(clear) preamble. */\nconst CLEAR_WITH_SCROLLBACK = \"\\x1b[2J\\x1b[H\\x1b[3J\";\n/** Kitty graphics APC prefix; frames touching images interleave cursor moves. */\nconst KITTY_APC_PREFIX = \"\\x1b_G\";\n\n/**\n * ProcessTerminal that (1) coalesces every write issued within one synchronous\n * task into a single stdout write and (2) keeps content-driven full redraws\n * from destroying the terminal's scrollback.\n *\n * Coalescing: pi-tui emits each render pass as several separate stdout\n * writes: the frame wrapped in synchronized output (CSI ?2026h/l), then a\n * relative cursor move that parks the hardware cursor at the focused\n * component's caret for IME composition, then a cursor visibility toggle.\n * Terminals that anchor the IME candidate window to the hardware cursor\n * (Windows Terminal and other ConPTY hosts, WezTerm) can process the frame\n * write before the reposition write arrives, briefly leaving the cursor at\n * the end of the last repainted line. With an IME active this makes the\n * candidate window jump between the caret and the right edge of the input\n * line on every keystroke. Merging the writes makes each frame atomic, so the\n * only cursor position a terminal can observe is the final one.\n *\n * Scrollback preservation: pi-tui's fullRender(clear) opens with\n * `2J H 3J`, wiping the terminal's scrollback, and then replays the entire\n * transcript. Content-driven triggers (a line changing above the viewport\n * during streaming markdown reflow, large content shrinks) fire this\n * routinely, which erases pre-session shell history and — in terminals that\n * clamp the scroll offset when scrollback vanishes, notably Windows\n * Terminal — yanks a scrolled-up viewport to the top of the buffer\n * (upstream #6502, #5576, #6050; rejected upstream fix #4204). Frames\n * matching that shape are rewritten to overwrite the visible screen in place\n * (home, erase-and-rewrite each row, erase below) with only the bottom\n * viewport-height rows, which leaves scrollback (and the reader's scroll\n * position) untouched while producing a byte-identical final screen state.\n * ED 2 is avoided entirely because conhost/Windows Terminal implement it by\n * scrolling the screen contents into scrollback rather than erasing in\n * place. Width-change redraws keep the upstream wipe because\n * re-wrapped content genuinely invalidates old scrollback, and frames\n * containing kitty graphics pass through untouched. A frame that does not\n * match the expected shape is passed through unchanged, so if upstream\n * reshapes its render output the wrapper degrades back to stock behavior.\n */\nexport class CoalescingTerminal extends ProcessTerminal {\n\tprivate pending = \"\";\n\tprivate flushQueued = false;\n\tprivate lastWriteColumns: number | undefined;\n\tprivate flushOnExit = () => this.flush();\n\n\tconstructor() {\n\t\tsuper();\n\t\t// A synchronous process.exit() before the queued microtask runs would\n\t\t// otherwise drop the final frame.\n\t\tprocess.on(\"exit\", this.flushOnExit);\n\t}\n\n\toverride write(data: string): void {\n\t\tif (data.length === 0) return;\n\t\tthis.pending += this.preserveScrollback(data);\n\t\tif (this.flushQueued) return;\n\t\tthis.flushQueued = true;\n\t\tqueueMicrotask(() => this.flush());\n\t}\n\n\t// Route every escape-sequence helper through the coalescing buffer so a\n\t// caller mixing helpers with write() keeps its output ordered.\n\toverride moveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\tthis.write(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\tthis.write(`\\x1b[${-lines}A`);\n\t\t}\n\t}\n\n\toverride hideCursor(): void {\n\t\tthis.write(\"\\x1b[?25l\");\n\t}\n\n\toverride showCursor(): void {\n\t\tthis.write(\"\\x1b[?25h\");\n\t}\n\n\toverride clearLine(): void {\n\t\tthis.write(\"\\x1b[K\");\n\t}\n\n\toverride clearFromCursor(): void {\n\t\tthis.write(\"\\x1b[J\");\n\t}\n\n\toverride clearScreen(): void {\n\t\tthis.write(\"\\x1b[2J\\x1b[H\");\n\t}\n\n\toverride stop(): void {\n\t\t// ProcessTerminal.stop() writes its teardown sequences directly to\n\t\t// stdout, so pending frame data must go out first.\n\t\tthis.flush();\n\t\tprocess.removeListener(\"exit\", this.flushOnExit);\n\t\tsuper.stop();\n\t}\n\n\t/**\n\t * Rewrite a full-redraw frame (`?2026h 2J H 3J <lines> ?2026l`) so it\n\t * repaints the screen without wiping scrollback. Anything that does not\n\t * match this exact shape — including width-change redraws and frames\n\t * touching kitty images — passes through unchanged.\n\t */\n\tprivate preserveScrollback(data: string): string {\n\t\tconst columns = this.columns;\n\t\tconst widthChanged = this.lastWriteColumns !== undefined && this.lastWriteColumns !== columns;\n\t\tthis.lastWriteColumns = columns;\n\n\t\tconst prefix = SYNC_START + CLEAR_WITH_SCROLLBACK;\n\t\tif (!data.startsWith(prefix) || !data.endsWith(SYNC_END)) {\n\t\t\treturn data;\n\t\t}\n\t\t// Re-wrapped content invalidates what scrollback holds; keep the wipe.\n\t\tif (widthChanged) {\n\t\t\treturn data;\n\t\t}\n\t\tif (data.includes(KITTY_APC_PREFIX)) {\n\t\t\treturn data;\n\t\t}\n\t\tconst body = data.slice(prefix.length, data.length - SYNC_END.length);\n\t\t// A second clear inside one write means the frame shape changed\n\t\t// upstream; bail out rather than guess.\n\t\tif (body.includes(CLEAR_WITH_SCROLLBACK)) {\n\t\t\treturn data;\n\t\t}\n\t\t// Repaint only the bottom viewport-height rows, overwriting the screen\n\t\t// in place: home, erase-and-rewrite each row, erase whatever remains\n\t\t// below. Writing the full transcript after a screen clear would push a\n\t\t// duplicate copy of everything above the viewport into scrollback; the\n\t\t// truncated overwrite produces the exact same final screen and cursor\n\t\t// position as the full replay (rows beyond the screen would have\n\t\t// scrolled out anyway). ED 2 (`2J`) is deliberately avoided even for\n\t\t// the visible screen: conhost/Windows Terminal implement it by\n\t\t// scrolling the current screen into scrollback (cls compatibility), so\n\t\t// without the `3J` wipe each redraw would stack another screenful of\n\t\t// duplicates into history.\n\t\tconst lines = body.split(\"\\r\\n\");\n\t\tconst rows = this.rows;\n\t\tconst kept = lines.length > rows ? lines.slice(lines.length - rows) : lines;\n\t\tconst repaint = kept.map((line) => `\\x1b[2K${line}`).join(\"\\r\\n\");\n\t\treturn `${SYNC_START}\\x1b[H${repaint}\\x1b[J${SYNC_END}`;\n\t}\n\n\tprivate flush(): void {\n\t\tthis.flushQueued = false;\n\t\tif (this.pending.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst data = this.pending;\n\t\tthis.pending = \"\";\n\t\tsuper.write(data);\n\t}\n}\n"]}
1
+ {"version":3,"file":"coalescing-terminal.js","sourceRoot":"","sources":["../../src/utils/coalescing-terminal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,MAAM,UAAU,GAAG,aAAa,CAAC;AACjC,MAAM,QAAQ,GAAG,aAAa,CAAC;AAC/B,oFAAkF;AAClF,MAAM,qBAAqB,GAAG,sBAAsB,CAAC;AACrD,iFAAiF;AACjF,MAAM,gBAAgB,GAAG,QAAQ,CAAC;AAElC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AACH,MAAM,OAAO,k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AG,IAAI,CAAC,mBAAmB,EAAE,CAAC;YACzC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;QAC/F,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,SAAS,CAAC;QAClB,CAAC;IAAA,CACD;IAEO,KAAK,GAAS;QACrB,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;QACzB,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC/B,OAAO;QACR,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAClB,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAAA,CAClB;CACD","sourcesContent":["import { ProcessTerminal } from \"@earendil-works/pi-tui\";\n\nconst SYNC_START = \"\\x1b[?2026h\";\nconst SYNC_END = \"\\x1b[?2026l\";\n/** Clear screen, home, clear scrollback — pi-tui's fullRender(clear) preamble. */\nconst CLEAR_WITH_SCROLLBACK = \"\\x1b[2J\\x1b[H\\x1b[3J\";\n/** Kitty graphics APC prefix; frames touching images interleave cursor moves. */\nconst KITTY_APC_PREFIX = \"\\x1b_G\";\n\n/**\n * ProcessTerminal that (1) coalesces every write issued within one synchronous\n * task into a single stdout write and (2) keeps content-driven full redraws\n * from destroying the terminal's scrollback.\n *\n * Coalescing: pi-tui emits each render pass as several separate stdout\n * writes: the frame wrapped in synchronized output (CSI ?2026h/l), then a\n * relative cursor move that parks the hardware cursor at the focused\n * component's caret for IME composition, then a cursor visibility toggle.\n * Terminals that anchor the IME candidate window to the hardware cursor\n * (Windows Terminal and other ConPTY hosts, WezTerm) can process the frame\n * write before the reposition write arrives, briefly leaving the cursor at\n * the end of the last repainted line. With an IME active this makes the\n * candidate window jump between the caret and the right edge of the input\n * line on every keystroke. Merging the writes makes each frame atomic, so the\n * only cursor position a terminal can observe is the final one.\n *\n * Scrollback preservation: pi-tui's fullRender(clear) opens with\n * `2J H 3J`, wiping the terminal's scrollback, and then replays the entire\n * transcript. During streaming, content-driven triggers (a line changing\n * above the viewport during markdown reflow) fire this routinely, which — in\n * terminals that clamp the scroll offset when scrollback vanishes, notably\n * Windows Terminal — yanks a scrolled-up reader to the top of the buffer on\n * every reflow (upstream #6502, #5576, #6050; rejected upstream fix #4204).\n *\n * Preservation is therefore windowed, not permanent: the host enables it via\n * setScrollbackPreservation while an agent run is mutating the transcript\n * (and keeps it on until the user's next input after the run settles, since\n * they may still be scrolled up reading), and leaves it off otherwise. An\n * idle-session full redraw — Ctrl+O toggles, mode switches — passes through\n * with upstream's wipe-and-replay, whose result is byte-perfect: scrollback\n * becomes the clean new transcript. Mid-run user toggles can arm\n * passNextFullRedraw for the same clean replay on their own frame.\n *\n * While preservation is active, a matching frame is rewritten to repaint\n * without the wipe. With setViewportTopProvider wired, the rewrite knows\n * which transcript line the visible screen starts at, so a frame that grew\n * the transcript repaints the on-screen rows with the new content at those\n * same positions and then scrolls the extra lines in at the bottom row.\n * Each bottom-row newline pushes the top row — already repainted with the\n * correct new content — into scrollback, exactly like ordinary streaming\n * output, so scrollback ends up byte-equivalent to the upstream full replay\n * without ever clearing it. Without the provider, or when the transcript\n * shrank (lines cannot be pulled back out of scrollback), the rewrite falls\n * back to overwriting the visible screen in place with the bottom\n * viewport-height rows, at the cost of a stale seam above the screen. ED 2\n * is avoided entirely in rewritten frames because conhost/Windows Terminal\n * implement it by scrolling the screen contents into scrollback rather than\n * erasing in place.\n *\n * Width- and height-change redraws keep the upstream wipe because re-wrapped\n * content genuinely invalidates old scrollback, and frames containing kitty\n * graphics pass through untouched. A frame that does not match the expected\n * shape is passed through unchanged, so if upstream reshapes its render\n * output the wrapper degrades back to stock behavior.\n */\nexport class CoalescingTerminal extends ProcessTerminal {\n\tprivate pending = \"\";\n\tprivate flushQueued = false;\n\tprivate lastWriteColumns: number | undefined;\n\tprivate lastWriteRows: number | undefined;\n\tprivate viewportTopProvider: (() => number | undefined) | undefined;\n\tprivate preserve = false;\n\tprivate passArmed = false;\n\tprivate flushOnExit = () => this.flush();\n\n\t/**\n\t * Enable or disable the scrollback-preserving rewrite. Preservation is\n\t * only worth its imperfections (stale renderings above the screen, seams\n\t * on shrink) while the transcript is mutating on its own and the reader\n\t * may be scrolled up — i.e. during an agent run and until the user's next\n\t * input after it settles. Outside that window every full redraw passes\n\t * through with upstream's wipe-and-replay, whose result is byte-perfect:\n\t * scrollback becomes the clean new transcript. Default: disabled.\n\t */\n\tsetScrollbackPreservation(enabled: boolean): void {\n\t\tthis.preserve = enabled;\n\t}\n\n\t/**\n\t * Arm a one-shot exemption for an explicit user action (Ctrl+O tool\n\t * expansion, thinking visibility) so its own full redraw keeps the\n\t * upstream wipe-and-replay even while preservation is active mid-run.\n\t * The user just pressed a key, so they are interacting at the bottom;\n\t * a clean replay beats preservation's stale-seam trade-offs there. The\n\t * flag is cleared by the next write so it cannot leak onto a later\n\t * streaming redraw.\n\t */\n\tpassNextFullRedraw(): void {\n\t\tthis.passArmed = true;\n\t}\n\n\t/**\n\t * Wire the renderer's notion of which transcript line the visible screen\n\t * currently starts at (pi-tui's `previousViewportTop`). Full-redraw frames\n\t * that grew the transcript then scroll the new above-screen lines into\n\t * scrollback instead of dropping them. The provider is read while the\n\t * frame is being written, i.e. before the renderer updates its own\n\t * bookkeeping for that frame; returning undefined falls back to the\n\t * bottom-anchored in-place repaint.\n\t */\n\tsetViewportTopProvider(provider: () => number | undefined): void {\n\t\tthis.viewportTopProvider = provider;\n\t}\n\n\tconstructor() {\n\t\tsuper();\n\t\t// A synchronous process.exit() before the queued microtask runs would\n\t\t// otherwise drop the final frame.\n\t\tprocess.on(\"exit\", this.flushOnExit);\n\t}\n\n\toverride write(data: string): void {\n\t\tif (data.length === 0) return;\n\t\tthis.pending += this.preserveScrollback(data);\n\t\tif (this.flushQueued) return;\n\t\tthis.flushQueued = true;\n\t\tqueueMicrotask(() => this.flush());\n\t}\n\n\t// Route every escape-sequence helper through the coalescing buffer so a\n\t// caller mixing helpers with write() keeps its output ordered.\n\toverride moveBy(lines: number): void {\n\t\tif (lines > 0) {\n\t\t\tthis.write(`\\x1b[${lines}B`);\n\t\t} else if (lines < 0) {\n\t\t\tthis.write(`\\x1b[${-lines}A`);\n\t\t}\n\t}\n\n\toverride hideCursor(): void {\n\t\tthis.write(\"\\x1b[?25l\");\n\t}\n\n\toverride showCursor(): void {\n\t\tthis.write(\"\\x1b[?25h\");\n\t}\n\n\toverride clearLine(): void {\n\t\tthis.write(\"\\x1b[K\");\n\t}\n\n\toverride clearFromCursor(): void {\n\t\tthis.write(\"\\x1b[J\");\n\t}\n\n\toverride clearScreen(): void {\n\t\tthis.write(\"\\x1b[2J\\x1b[H\");\n\t}\n\n\toverride stop(): void {\n\t\t// ProcessTerminal.stop() writes its teardown sequences directly to\n\t\t// stdout, so pending frame data must go out first.\n\t\tthis.flush();\n\t\tprocess.removeListener(\"exit\", this.flushOnExit);\n\t\tsuper.stop();\n\t}\n\n\t/**\n\t * Rewrite a full-redraw frame (`?2026h 2J H 3J <lines> ?2026l`) so it\n\t * repaints the screen without wiping scrollback. Anything that does not\n\t * match this exact shape — including width-change redraws and frames\n\t * touching kitty images — passes through unchanged.\n\t */\n\tprivate preserveScrollback(data: string): string {\n\t\tconst columns = this.columns;\n\t\tconst rows = this.rows;\n\t\tconst widthChanged = this.lastWriteColumns !== undefined && this.lastWriteColumns !== columns;\n\t\tconst heightChanged = this.lastWriteRows !== undefined && this.lastWriteRows !== rows;\n\t\tthis.lastWriteColumns = columns;\n\t\tthis.lastWriteRows = rows;\n\t\t// One-shot: the very next write is the armed toggle's own frame (or a\n\t\t// differential frame when the toggle stayed inside the viewport, in\n\t\t// which case no exemption is needed and the flag must not linger).\n\t\tconst passAllowed = this.passArmed;\n\t\tthis.passArmed = false;\n\n\t\tconst prefix = SYNC_START + CLEAR_WITH_SCROLLBACK;\n\t\tif (!data.startsWith(prefix) || !data.endsWith(SYNC_END)) {\n\t\t\treturn data;\n\t\t}\n\t\t// Outside the preservation window (idle sessions, pre-session UI) and\n\t\t// for armed user toggles, upstream's wipe-and-replay is byte-perfect;\n\t\t// let it through.\n\t\tif (!this.preserve || passAllowed) {\n\t\t\treturn data;\n\t\t}\n\t\t// Re-wrapped/re-flowed content invalidates what scrollback holds and\n\t\t// where the screen sits in it; keep the wipe.\n\t\tif (widthChanged || heightChanged) {\n\t\t\treturn data;\n\t\t}\n\t\tif (data.includes(KITTY_APC_PREFIX)) {\n\t\t\treturn data;\n\t\t}\n\t\tconst body = data.slice(prefix.length, data.length - SYNC_END.length);\n\t\t// A second clear inside one write means the frame shape changed\n\t\t// upstream; bail out rather than guess.\n\t\tif (body.includes(CLEAR_WITH_SCROLLBACK)) {\n\t\t\treturn data;\n\t\t}\n\t\t// ED 2 (`2J`) is deliberately avoided in both rewrites below: conhost/\n\t\t// Windows Terminal implement it by scrolling the current screen into\n\t\t// scrollback (cls compatibility), so without the `3J` wipe each redraw\n\t\t// would stack another screenful of duplicates into history.\n\t\tconst lines = body.split(\"\\r\\n\");\n\t\tconst newViewportTop = Math.max(0, lines.length - rows);\n\t\tconst viewportTop = this.readViewportTop();\n\t\tif (viewportTop !== undefined && viewportTop <= newViewportTop) {\n\t\t\t// The transcript grew (or held steady): repaint the rows currently\n\t\t\t// on screen with the new content at those same transcript\n\t\t\t// positions, then scroll the remaining lines in at the bottom row.\n\t\t\t// Each bottom-row newline pushes the already-repainted top row into\n\t\t\t// scrollback, so scrollback receives exactly the new lines the\n\t\t\t// upstream replay would have put there — no wipe, no loss.\n\t\t\tconst onScreen = lines.slice(viewportTop, viewportTop + rows);\n\t\t\tconst scrolled = lines.slice(viewportTop + rows);\n\t\t\tlet repaint = onScreen.map((line) => `\\x1b[2K${line}`).join(\"\\r\\n\");\n\t\t\tfor (const line of scrolled) {\n\t\t\t\trepaint += `\\r\\n\\x1b[2K${line}`;\n\t\t\t}\n\t\t\treturn `${SYNC_START}\\x1b[H${repaint}\\x1b[J${SYNC_END}`;\n\t\t}\n\t\t// Fallback (no provider, or the transcript shrank — lines cannot be\n\t\t// pulled back out of scrollback): repaint only the bottom\n\t\t// viewport-height rows, overwriting the screen in place: home,\n\t\t// erase-and-rewrite each row, erase whatever remains below. Writing the\n\t\t// full transcript after a screen clear would push a duplicate copy of\n\t\t// everything above the viewport into scrollback; the truncated\n\t\t// overwrite produces the exact same final screen and cursor position as\n\t\t// the full replay (rows beyond the screen would have scrolled out\n\t\t// anyway).\n\t\tconst kept = lines.length > rows ? lines.slice(lines.length - rows) : lines;\n\t\tconst repaint = kept.map((line) => `\\x1b[2K${line}`).join(\"\\r\\n\");\n\t\treturn `${SYNC_START}\\x1b[H${repaint}\\x1b[J${SYNC_END}`;\n\t}\n\n\t// The provider reaches into the renderer's bookkeeping; treat anything\n\t// unexpected as \"unknown\" and fall back rather than corrupt the screen.\n\tprivate readViewportTop(): number | undefined {\n\t\tif (!this.viewportTopProvider) return undefined;\n\t\ttry {\n\t\t\tconst value = this.viewportTopProvider();\n\t\t\treturn typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate flush(): void {\n\t\tthis.flushQueued = false;\n\t\tif (this.pending.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tconst data = this.pending;\n\t\tthis.pending = \"\";\n\t\tsuper.write(data);\n\t}\n}\n"]}
@@ -7,13 +7,15 @@ Adds a `question` tool for asking one to four multiple-choice questions when the
7
7
  - Each option requires a concise description of its consequence or trade-off. Questions, labels, descriptions, and previews have input-length limits so the dialog stays usable.
8
8
  - A single single-select question submits as soon as the user selects an option.
9
9
  - A multi-question flow advances after each single-select answer; multi-select uses `Space` to toggle choices and Enter to continue. Once every question is answered, a **Review answers** view requires explicit submission.
10
+ - Options are numbered; pressing `1`–`9` jumps to the matching option — selecting it in single-select, toggling it in multi-select. The custom-answer row's number opens its input.
10
11
  - `←` / `→` switch between adjacent questions without wrapping. The tab bar marks answered questions and the Review state.
11
12
  - `Chat about this` is available after the choices. It returns a `needs_clarification` outcome so the model explains or reformulates instead of treating the user as having declined.
12
- - `Type something.` is appended automatically for custom answers. Authored options may not use reserved labels (`Other`, `Type something.`, `Chat about this`, `Next`).
13
- - `Tab` opens a note editor for the focused option; in multi-select, the option must be selected first. On the custom-answer row, it opens custom-answer input.
14
- - Multi-select custom answers stay on the `Type something.` row, are selected when saved, and can be toggled with `Space` without losing text.
15
- - `preview` shows focused single-select content beside the choices on wide terminals and beneath them on narrow terminals. Preview height is capped and reports hidden lines.
13
+ - `Type something.` is appended automatically for custom answers. Authored options may not use reserved labels (`Other`, `Type something.`, `Chat about this`); the comparison is case-insensitive and ignores surrounding whitespace.
14
+ - `Tab` opens a note editor for the focused option; in multi-select, the option must be selected first. In single-select it also selects the option, and cancelling the note editor with `Esc` restores the previous selection. On the custom-answer row, it opens custom-answer input.
15
+ - Multi-select custom answers stay on the `Type something.` row, are selected when saved, and can be toggled with `Space` without losing text. Enter on that row opens the input while no custom answer exists yet.
16
+ - `preview` shows focused single-select content beside the choices on wide terminals and beneath them on narrow terminals. Preview height is capped and reports hidden lines. Previews on multi-select questions are rejected with a `preview_multiselect` error.
16
17
  - The dialog is available only in TUI mode. RPC, JSON, and print calls return a structured `no_ui` error rather than attempting a custom component.
18
+ - Aborting the turn closes the dialog and resolves the call as cancelled with the answers given so far.
17
19
 
18
20
  ## Result contract
19
21
 
@@ -28,7 +30,7 @@ Adds a `question` tool for asking one to four multiple-choice questions when the
28
30
  }
29
31
  ```
30
32
 
31
- Only `content` reaches the model. Successful results are numbered, clearly identify single/custom/multi answers, retain notes, and state when a preview was selected without echoing its full source. Model-facing output is capped at 12,000 characters; if it is truncated, the result instructs the model to ask a focused follow-up question. Notes and custom answers are capped at 4,000 characters in the dialog.
33
+ Only `content` reaches the model. Successful results are numbered, clearly identify single/custom/multi answers, retain notes, and state when a preview was selected without echoing its full source. Cancelling — via `Esc` or a turn abort — lists any answers already given as partial answers alongside the decline message. Model-facing output is capped at 12,000 characters; if it is truncated, the result instructs the model to ask a focused follow-up question. Notes and custom answers are capped at 4,000 characters in the dialog.
32
34
 
33
35
  The transcript uses a private `renderCall` / `renderResult` only to replace raw question JSON and model-oriented result text with concise user summaries. Pi retains its native tool shell, pending/error state, and collapsed/expanded behavior.
34
36
 
@@ -42,7 +44,7 @@ The transcript uses a private `renderCall` / `renderResult` only to replace raw
42
44
  ## Implementation notes
43
45
 
44
46
  - Uses Pi's native `ctx.ui.custom()` lifecycle; no state is shared with another extension.
45
- - The render cache is keyed by terminal width **and height**, because preview height depends on available rows and Pi resize only requests a render.
46
- - `validateQuestions` enforces uniqueness, reserved-label rejection, and text budgets beyond what the JSON schema can express.
47
+ - The render cache is keyed by terminal width **and height**, because preview height depends on available rows and Pi resize only requests a render. Preview markdown rendering is additionally memoized per text and dimensions so editor keystrokes don't re-parse previews.
48
+ - `validateQuestions` enforces only what the JSON schema cannot express: case-insensitive uniqueness, reserved-label rejection, and the preview/multi-select conflict. Length and count limits are enforced against the schema before the tool executes.
47
49
  - Dialog navigation follows Pi's injected select/input keybindings where applicable; custom actions such as Space-to-toggle remain explicit in the footer.
48
50
 
@@ -50,9 +50,9 @@ Project definitions are loaded only after Pi trusts the project. Invalid Markdow
50
50
  Built-in profiles:
51
51
 
52
52
  - `general`: read, bash, edit, and write.
53
- - `explorer`: read-only `read`, `grep`, `find`, and `ls`.
53
+ - `explorer`: `read`, `grep`, `find`, and `ls`, plus `bash` constrained by its system prompt to read-only inspection (git history, counting, and similar).
54
54
 
55
- A profile may only allow Pi built-in tools. Child sessions load no extensions, skills, or prompt templates, so a worker cannot recursively call `subagent` or inherit unrelated extension capabilities. Project context files such as `AGENTS.md` remain available.
55
+ A profile may only allow Pi built-in tools. Child sessions load no extensions, skills, or prompt templates, so a worker cannot recursively call `subagent` or inherit unrelated extension capabilities. Project context files such as `AGENTS.md` remain available, except for the built-in `explorer`, which skips them: read-only exploration needs no commit/PR rules, and the parent interprets its results.
56
56
 
57
57
  ## Model and thinking selection
58
58
 
@@ -4,10 +4,12 @@ Adds a `todo` tool plus `/todos` for multi-step work, with a live overlay above
4
4
 
5
5
  ## Behavior
6
6
 
7
- - Actions: `create`, `update`, `list`, `get`, `delete`, `clear`. Statuses: `pending`, `in_progress`, `completed`, `deleted`. `list` accepts an optional `status` filter and `includeDeleted`; `status: "deleted"` includes tombstones directly.
7
+ - Actions: `create`, `update`, `list`, `get`, `delete`, `clear`. Statuses: `pending`, `in_progress`, `completed`, `deleted`. `list` accepts an optional `status` filter and `includeDeleted`; `status: "deleted"` includes tombstones directly. Parameters that do not apply to the chosen action are rejected with guidance (for example `blockedBy` on `update` points at `addBlockedBy`/`removeBlockedBy`) instead of being silently ignored.
8
8
  - The live overlay renders above the editor and hides itself when there are no visible tasks.
9
- - Creation always starts a task as `pending`; `blockedBy` dependencies are supported for sequencing, and missing dependencies, deleted dependencies, self-dependencies, and cycles are rejected. A task cannot move to `in_progress` or `completed` until every `blockedBy` dependency is `completed`.
10
- - Deletion — via `delete` or `update` with `status: "deleted"` — leaves an immutable tombstone for branch history, removes that task from every dependent `blockedBy` list, and therefore releases dependents. `clear` empties the list without reusing ids.
9
+ - Creation always starts a task as `pending` and requires both `subject` and `description` (what done means); `blockedBy` dependencies are supported for sequencing, and missing dependencies, deleted dependencies, self-dependencies, and cycles are rejected. A task cannot move to `in_progress` or `completed` until every `blockedBy` dependency is `completed` (a task that is already active may still take on a new incomplete dependency — a prerequisite discovered mid-work).
10
+ - `update` manages both edge directions: `addBlockedBy`/`removeBlockedBy` change what the task waits on, `addBlocks`/`removeBlocks` change what waits on it (stored as the targets' `blockedBy`, with the same validation and cycle checks). An empty string removes `description`, `activeForm`, or `owner`; `metadata` merges with `null` deleting keys.
11
+ - `list` lines show only unresolved blockers plus the task's `@owner`; full `blockedBy`/`blocks` detail lives in `get`.
12
+ - Deletion — via `delete` or `update` with `status: "deleted"` — leaves an immutable tombstone for branch history, removes that task from every dependent `blockedBy` list, and therefore releases dependents; the tool result names pending dependents that ended up fully unblocked. A deletion cannot be combined with other field edits in the same call. `clear` empties the list without reusing ids.
11
13
  - Newly completed tasks remain visible for 30 seconds, then drop from the overlay; historical completions loaded by `/reload` or `/tree` stay hidden so live work remains prominent.
12
14
  - **Exactly one `in_progress`.** Moving a task to `in_progress` auto-demotes any other `in_progress` tasks to `pending`; the tool result lists demoted ids so the model sees the side effect.
13
15
  - **Verification soft nudge.** When a completion leaves the list fully done with 3+ completed tasks and no subject/description matching `verif|test|check|review`, the tool result appends a short NOTE (text only — `details` schema unchanged).
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@astralyn/pi",
3
- "version": "0.82.4",
3
+ "version": "0.82.5",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@astralyn/pi",
9
- "version": "0.82.4",
9
+ "version": "0.82.5",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@earendil-works/pi-agent-core": "0.82.1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astralyn/pi",
3
- "version": "0.82.4",
3
+ "version": "0.82.5",
4
4
  "description": "Coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "piConfig": {