@juliusbrussee/caveman-tui 0.65.2

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 (162) hide show
  1. package/README.md +767 -0
  2. package/dist/autocomplete.d.ts +52 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +623 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/chord.d.ts +57 -0
  7. package/dist/chord.d.ts.map +1 -0
  8. package/dist/chord.js +97 -0
  9. package/dist/chord.js.map +1 -0
  10. package/dist/color-depth.d.ts +17 -0
  11. package/dist/color-depth.d.ts.map +1 -0
  12. package/dist/color-depth.js +147 -0
  13. package/dist/color-depth.js.map +1 -0
  14. package/dist/components/Chapters.d.ts +41 -0
  15. package/dist/components/Chapters.d.ts.map +1 -0
  16. package/dist/components/Chapters.js +103 -0
  17. package/dist/components/Chapters.js.map +1 -0
  18. package/dist/components/DiffView.d.ts +75 -0
  19. package/dist/components/DiffView.d.ts.map +1 -0
  20. package/dist/components/DiffView.js +170 -0
  21. package/dist/components/DiffView.js.map +1 -0
  22. package/dist/components/StatusLine.d.ts +135 -0
  23. package/dist/components/StatusLine.d.ts.map +1 -0
  24. package/dist/components/StatusLine.js +133 -0
  25. package/dist/components/StatusLine.js.map +1 -0
  26. package/dist/components/SubagentOverlay.d.ts +63 -0
  27. package/dist/components/SubagentOverlay.d.ts.map +1 -0
  28. package/dist/components/SubagentOverlay.js +124 -0
  29. package/dist/components/SubagentOverlay.js.map +1 -0
  30. package/dist/components/box.d.ts +22 -0
  31. package/dist/components/box.d.ts.map +1 -0
  32. package/dist/components/box.js +104 -0
  33. package/dist/components/box.js.map +1 -0
  34. package/dist/components/cancellable-loader.d.ts +22 -0
  35. package/dist/components/cancellable-loader.d.ts.map +1 -0
  36. package/dist/components/cancellable-loader.js +35 -0
  37. package/dist/components/cancellable-loader.js.map +1 -0
  38. package/dist/components/editor.d.ts +244 -0
  39. package/dist/components/editor.d.ts.map +1 -0
  40. package/dist/components/editor.js +1861 -0
  41. package/dist/components/editor.js.map +1 -0
  42. package/dist/components/grouped-select-list.d.ts +60 -0
  43. package/dist/components/grouped-select-list.d.ts.map +1 -0
  44. package/dist/components/grouped-select-list.js +312 -0
  45. package/dist/components/grouped-select-list.js.map +1 -0
  46. package/dist/components/image.d.ts +28 -0
  47. package/dist/components/image.d.ts.map +1 -0
  48. package/dist/components/image.js +69 -0
  49. package/dist/components/image.js.map +1 -0
  50. package/dist/components/input.d.ts +37 -0
  51. package/dist/components/input.d.ts.map +1 -0
  52. package/dist/components/input.js +426 -0
  53. package/dist/components/input.js.map +1 -0
  54. package/dist/components/loader.d.ts +26 -0
  55. package/dist/components/loader.d.ts.map +1 -0
  56. package/dist/components/loader.js +67 -0
  57. package/dist/components/loader.js.map +1 -0
  58. package/dist/components/markdown.d.ts +95 -0
  59. package/dist/components/markdown.d.ts.map +1 -0
  60. package/dist/components/markdown.js +663 -0
  61. package/dist/components/markdown.js.map +1 -0
  62. package/dist/components/select-list.d.ts +50 -0
  63. package/dist/components/select-list.d.ts.map +1 -0
  64. package/dist/components/select-list.js +159 -0
  65. package/dist/components/select-list.js.map +1 -0
  66. package/dist/components/settings-list.d.ts +50 -0
  67. package/dist/components/settings-list.d.ts.map +1 -0
  68. package/dist/components/settings-list.js +185 -0
  69. package/dist/components/settings-list.js.map +1 -0
  70. package/dist/components/spacer.d.ts +12 -0
  71. package/dist/components/spacer.d.ts.map +1 -0
  72. package/dist/components/spacer.js +23 -0
  73. package/dist/components/spacer.js.map +1 -0
  74. package/dist/components/spinner.d.ts +35 -0
  75. package/dist/components/spinner.d.ts.map +1 -0
  76. package/dist/components/spinner.js +77 -0
  77. package/dist/components/spinner.js.map +1 -0
  78. package/dist/components/streaming-markdown.d.ts +39 -0
  79. package/dist/components/streaming-markdown.d.ts.map +1 -0
  80. package/dist/components/streaming-markdown.js +137 -0
  81. package/dist/components/streaming-markdown.js.map +1 -0
  82. package/dist/components/text.d.ts +19 -0
  83. package/dist/components/text.d.ts.map +1 -0
  84. package/dist/components/text.js +89 -0
  85. package/dist/components/text.js.map +1 -0
  86. package/dist/components/truncated-text.d.ts +13 -0
  87. package/dist/components/truncated-text.d.ts.map +1 -0
  88. package/dist/components/truncated-text.js +51 -0
  89. package/dist/components/truncated-text.js.map +1 -0
  90. package/dist/editor-component.d.ts +39 -0
  91. package/dist/editor-component.d.ts.map +1 -0
  92. package/dist/editor-component.js +2 -0
  93. package/dist/editor-component.js.map +1 -0
  94. package/dist/fuzzy.d.ts +16 -0
  95. package/dist/fuzzy.d.ts.map +1 -0
  96. package/dist/fuzzy.js +107 -0
  97. package/dist/fuzzy.js.map +1 -0
  98. package/dist/index.d.ts +38 -0
  99. package/dist/index.d.ts.map +1 -0
  100. package/dist/index.js +59 -0
  101. package/dist/index.js.map +1 -0
  102. package/dist/keybindings.d.ts +193 -0
  103. package/dist/keybindings.d.ts.map +1 -0
  104. package/dist/keybindings.js +174 -0
  105. package/dist/keybindings.js.map +1 -0
  106. package/dist/keys.d.ts +170 -0
  107. package/dist/keys.d.ts.map +1 -0
  108. package/dist/keys.js +1124 -0
  109. package/dist/keys.js.map +1 -0
  110. package/dist/kill-ring.d.ts +28 -0
  111. package/dist/kill-ring.d.ts.map +1 -0
  112. package/dist/kill-ring.js +44 -0
  113. package/dist/kill-ring.js.map +1 -0
  114. package/dist/notifications.d.ts +35 -0
  115. package/dist/notifications.d.ts.map +1 -0
  116. package/dist/notifications.js +62 -0
  117. package/dist/notifications.js.map +1 -0
  118. package/dist/osc52.d.ts +28 -0
  119. package/dist/osc52.d.ts.map +1 -0
  120. package/dist/osc52.js +53 -0
  121. package/dist/osc52.js.map +1 -0
  122. package/dist/scroll-buffer.d.ts +67 -0
  123. package/dist/scroll-buffer.d.ts.map +1 -0
  124. package/dist/scroll-buffer.js +222 -0
  125. package/dist/scroll-buffer.js.map +1 -0
  126. package/dist/spinners.d.ts +26 -0
  127. package/dist/spinners.d.ts.map +1 -0
  128. package/dist/spinners.js +136 -0
  129. package/dist/spinners.js.map +1 -0
  130. package/dist/stdin-buffer.d.ts +48 -0
  131. package/dist/stdin-buffer.d.ts.map +1 -0
  132. package/dist/stdin-buffer.js +317 -0
  133. package/dist/stdin-buffer.js.map +1 -0
  134. package/dist/sync-output.d.ts +58 -0
  135. package/dist/sync-output.d.ts.map +1 -0
  136. package/dist/sync-output.js +79 -0
  137. package/dist/sync-output.js.map +1 -0
  138. package/dist/terminal-detect.d.ts +66 -0
  139. package/dist/terminal-detect.d.ts.map +1 -0
  140. package/dist/terminal-detect.js +315 -0
  141. package/dist/terminal-detect.js.map +1 -0
  142. package/dist/terminal-image.d.ts +68 -0
  143. package/dist/terminal-image.d.ts.map +1 -0
  144. package/dist/terminal-image.js +288 -0
  145. package/dist/terminal-image.js.map +1 -0
  146. package/dist/terminal.d.ts +105 -0
  147. package/dist/terminal.d.ts.map +1 -0
  148. package/dist/terminal.js +427 -0
  149. package/dist/terminal.js.map +1 -0
  150. package/dist/tui.d.ts +268 -0
  151. package/dist/tui.d.ts.map +1 -0
  152. package/dist/tui.js +1161 -0
  153. package/dist/tui.js.map +1 -0
  154. package/dist/undo-stack.d.ts +17 -0
  155. package/dist/undo-stack.d.ts.map +1 -0
  156. package/dist/undo-stack.js +25 -0
  157. package/dist/undo-stack.js.map +1 -0
  158. package/dist/utils.d.ts +78 -0
  159. package/dist/utils.d.ts.map +1 -0
  160. package/dist/utils.js +960 -0
  161. package/dist/utils.js.map +1 -0
  162. package/package.json +59 -0
package/dist/tui.d.ts ADDED
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Minimal TUI implementation with differential rendering
3
+ */
4
+ import type { Terminal } from "./terminal.js";
5
+ import { visibleWidth } from "./utils.js";
6
+ /**
7
+ * Component interface - all components must implement this
8
+ */
9
+ export interface Component {
10
+ /**
11
+ * Render the component to lines for the given viewport width
12
+ * @param width - Current viewport width
13
+ * @returns Array of strings, each representing a line
14
+ */
15
+ render(width: number): string[];
16
+ /**
17
+ * Optional handler for keyboard input when component has focus
18
+ */
19
+ handleInput?(data: string): void;
20
+ /**
21
+ * If true, component receives key release events (Kitty protocol).
22
+ * Default is false - release events are filtered out.
23
+ */
24
+ wantsKeyRelease?: boolean;
25
+ /**
26
+ * Invalidate any cached rendering state.
27
+ * Called when theme changes or when component needs to re-render from scratch.
28
+ */
29
+ invalidate(): void;
30
+ }
31
+ type InputListenerResult = {
32
+ consume?: boolean;
33
+ data?: string;
34
+ } | undefined;
35
+ type InputListener = (data: string) => InputListenerResult;
36
+ /**
37
+ * Interface for components that can receive focus and display a hardware cursor.
38
+ * When focused, the component should emit CURSOR_MARKER at the cursor position
39
+ * in its render output. TUI will find this marker and position the hardware
40
+ * cursor there for proper IME candidate window positioning.
41
+ */
42
+ export interface Focusable {
43
+ /** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */
44
+ focused: boolean;
45
+ }
46
+ /** Type guard to check if a component implements Focusable */
47
+ export declare function isFocusable(component: Component | null): component is Component & Focusable;
48
+ /**
49
+ * Cursor position marker - APC (Application Program Command) sequence.
50
+ * This is a zero-width escape sequence that terminals ignore.
51
+ * Components emit this at the cursor position when focused.
52
+ * TUI finds and strips this marker, then positions the hardware cursor there.
53
+ */
54
+ export declare const CURSOR_MARKER = "\u001B_pi:c\u0007";
55
+ export { visibleWidth };
56
+ /**
57
+ * Anchor position for overlays
58
+ */
59
+ export type OverlayAnchor = "center" | "top-left" | "top-right" | "bottom-left" | "bottom-right" | "top-center" | "bottom-center" | "left-center" | "right-center";
60
+ /**
61
+ * Options for side panel positioning and sizing.
62
+ */
63
+ export interface SidePanelOptions {
64
+ /** Width in columns, or percentage of terminal width (e.g., "40%"). Default: "40%" */
65
+ width?: SizeValue;
66
+ /** Which side to place the panel. Default: "right" */
67
+ side?: "left" | "right";
68
+ }
69
+ /**
70
+ * Handle returned by showSidePanel for controlling the panel
71
+ */
72
+ export interface SidePanelHandle {
73
+ /** Remove the side panel and restore focus */
74
+ hide(): void;
75
+ }
76
+ /**
77
+ * Margin configuration for overlays
78
+ */
79
+ export interface OverlayMargin {
80
+ top?: number;
81
+ right?: number;
82
+ bottom?: number;
83
+ left?: number;
84
+ }
85
+ /** Value that can be absolute (number) or percentage (string like "50%") */
86
+ export type SizeValue = number | `${number}%`;
87
+ /**
88
+ * Options for overlay positioning and sizing.
89
+ * Values can be absolute numbers or percentage strings (e.g., "50%").
90
+ */
91
+ export interface OverlayOptions {
92
+ /** Width in columns, or percentage of terminal width (e.g., "50%") */
93
+ width?: SizeValue;
94
+ /** Minimum width in columns */
95
+ minWidth?: number;
96
+ /** Maximum height in rows, or percentage of terminal height (e.g., "50%") */
97
+ maxHeight?: SizeValue;
98
+ /** Anchor point for positioning (default: 'center') */
99
+ anchor?: OverlayAnchor;
100
+ /** Horizontal offset from anchor position (positive = right) */
101
+ offsetX?: number;
102
+ /** Vertical offset from anchor position (positive = down) */
103
+ offsetY?: number;
104
+ /** Row position: absolute number, or percentage (e.g., "25%" = 25% from top) */
105
+ row?: SizeValue;
106
+ /** Column position: absolute number, or percentage (e.g., "50%" = centered horizontally) */
107
+ col?: SizeValue;
108
+ /** Margin from terminal edges. Number applies to all sides. */
109
+ margin?: OverlayMargin | number;
110
+ /**
111
+ * Control overlay visibility based on terminal dimensions.
112
+ * If provided, overlay is only rendered when this returns true.
113
+ * Called each render cycle with current terminal dimensions.
114
+ */
115
+ visible?: (termWidth: number, termHeight: number) => boolean;
116
+ /** If true, don't capture keyboard focus when shown */
117
+ nonCapturing?: boolean;
118
+ }
119
+ /**
120
+ * Handle returned by showOverlay for controlling the overlay
121
+ */
122
+ export interface OverlayHandle {
123
+ /** Permanently remove the overlay (cannot be shown again) */
124
+ hide(): void;
125
+ /** Temporarily hide or show the overlay */
126
+ setHidden(hidden: boolean): void;
127
+ /** Check if overlay is temporarily hidden */
128
+ isHidden(): boolean;
129
+ /** Focus this overlay and bring it to the visual front */
130
+ focus(): void;
131
+ /** Release focus to the previous target */
132
+ unfocus(): void;
133
+ /** Check if this overlay currently has focus */
134
+ isFocused(): boolean;
135
+ }
136
+ /**
137
+ * Container - a component that contains other components
138
+ */
139
+ export declare class Container implements Component {
140
+ children: Component[];
141
+ addChild(component: Component): void;
142
+ removeChild(component: Component): void;
143
+ clear(): void;
144
+ invalidate(): void;
145
+ render(width: number): string[];
146
+ }
147
+ /**
148
+ * TUI - Main class for managing terminal UI with differential rendering
149
+ */
150
+ export declare class TUI extends Container {
151
+ terminal: Terminal;
152
+ private previousLines;
153
+ private previousWidth;
154
+ private previousHeight;
155
+ private focusedComponent;
156
+ private inputListeners;
157
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
158
+ onDebug?: () => void;
159
+ private renderRequested;
160
+ private renderTimer;
161
+ private lastRenderAt;
162
+ private static readonly MIN_RENDER_INTERVAL_MS;
163
+ private cursorRow;
164
+ private hardwareCursorRow;
165
+ private showHardwareCursor;
166
+ private clearOnShrink;
167
+ private maxLinesRendered;
168
+ private previousViewportTop;
169
+ private fullRedrawCount;
170
+ private stopped;
171
+ private globalBgFn;
172
+ private bottomPinnedChildren;
173
+ private sidePanelEntry;
174
+ private focusOrderCounter;
175
+ private overlayStack;
176
+ constructor(terminal: Terminal, showHardwareCursor?: boolean);
177
+ get fullRedraws(): number;
178
+ getShowHardwareCursor(): boolean;
179
+ setShowHardwareCursor(enabled: boolean): void;
180
+ getClearOnShrink(): boolean;
181
+ /**
182
+ * Set whether to trigger full re-render when content shrinks.
183
+ * When true (default), empty rows are cleared when content shrinks.
184
+ * When false, empty rows remain (reduces redraws on slower terminals).
185
+ */
186
+ setClearOnShrink(enabled: boolean): void;
187
+ setGlobalBackground(bgFn: ((text: string) => string) | null): void;
188
+ /**
189
+ * Pin the last N children to the bottom of the viewport.
190
+ * When content is shorter than the terminal, empty padding is inserted
191
+ * between main content and the pinned children to push them down.
192
+ */
193
+ setBottomPinnedChildren(count: number): void;
194
+ setFocus(component: Component | null): void;
195
+ /**
196
+ * Show an overlay component with configurable positioning and sizing.
197
+ * Returns a handle to control the overlay's visibility.
198
+ */
199
+ showOverlay(component: Component, options?: OverlayOptions): OverlayHandle;
200
+ /** Hide the topmost overlay and restore previous focus. */
201
+ hideOverlay(): void;
202
+ /** Show a side panel alongside the main content in a column layout. */
203
+ showSidePanel(component: Component, options?: SidePanelOptions): SidePanelHandle;
204
+ /** Hide the side panel and restore previous focus. */
205
+ hideSidePanel(): void;
206
+ /** Check if a side panel is currently shown. */
207
+ hasSidePanel(): boolean;
208
+ /** Check if there are any visible overlays */
209
+ hasOverlay(): boolean;
210
+ /** Check if an overlay entry is currently visible */
211
+ private isOverlayVisible;
212
+ /** Find the topmost visible capturing overlay, if any */
213
+ private getTopmostVisibleOverlay;
214
+ invalidate(): void;
215
+ start(): void;
216
+ addInputListener(listener: InputListener): () => void;
217
+ removeInputListener(listener: InputListener): void;
218
+ private queryCellSize;
219
+ stop(): void;
220
+ requestRender(force?: boolean): void;
221
+ private scheduleRender;
222
+ private handleInput;
223
+ private consumeCellSizeResponse;
224
+ /**
225
+ * Resolve overlay layout from options.
226
+ * Returns { width, row, col, maxHeight } for rendering.
227
+ */
228
+ private resolveOverlayLayout;
229
+ private resolveAnchorRow;
230
+ private resolveAnchorCol;
231
+ /** Render main content and side panel in a two-column layout. */
232
+ private renderWithSidePanel;
233
+ /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
234
+ private compositeOverlays;
235
+ /**
236
+ * Render with bottom-pinned children pushed to the bottom of the viewport.
237
+ */
238
+ private renderWithBottomPin;
239
+ private static readonly SEGMENT_RESET;
240
+ private applyLineResets;
241
+ /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
242
+ private compositeLineAt;
243
+ /**
244
+ * Find and extract cursor position from rendered lines.
245
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
246
+ * Only scans the bottom terminal height lines (visible viewport).
247
+ * @param lines - Rendered lines to search
248
+ * @param height - Terminal height (visible viewport size)
249
+ * @returns Cursor position { row, col } or null if no marker found
250
+ */
251
+ private extractCursorPosition;
252
+ /**
253
+ * Minimum terminal dimensions for a normal render.
254
+ * Below these, we fall back to a degenerate-size placeholder per
255
+ * cavekit-fullscreen-viewport R2 AC4 and R3 AC4.
256
+ */
257
+ private static readonly MIN_ROWS;
258
+ private static readonly MIN_COLS;
259
+ private renderDegenerateFrame;
260
+ private doRender;
261
+ /**
262
+ * Position the hardware cursor for IME candidate window.
263
+ * @param cursorPos The cursor position extracted from rendered output, or null
264
+ * @param totalLines Total number of rendered lines
265
+ */
266
+ private positionHardwareCursor;
267
+ }
268
+ //# sourceMappingURL=tui.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tui.d.ts","sourceRoot":"","sources":["../src/tui.ts"],"names":[],"mappings":"AAAA;;GAEG;AAOH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,OAAO,EAAyE,YAAY,EAAE,MAAM,YAAY,CAAC;AAEjH;;GAEG;AACH,MAAM,WAAW,SAAS;IACzB;;;;OAIG;IACH,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAEhC;;OAEG;IACH,WAAW,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAEjC;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B;;;OAGG;IACH,UAAU,IAAI,IAAI,CAAC;CACnB;AAED,KAAK,mBAAmB,GAAG;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC;AAC5E,KAAK,aAAa,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,mBAAmB,CAAC;AAE3D;;;;;GAKG;AACH,MAAM,WAAW,SAAS;IACzB,oFAAoF;IACpF,OAAO,EAAE,OAAO,CAAC;CACjB;AAED,8DAA8D;AAC9D,wBAAgB,WAAW,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI,GAAG,SAA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QAAQ;IA6VhB;;;;OAIG;IACH,OAAO,CAAC,sBAAsB;CAgC9B","sourcesContent":["/**\n * Minimal TUI implementation with differential rendering\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { performance } from \"node:perf_hooks\";\nimport { isKeyRelease, matchesKey } from \"./keys.js\";\nimport type { Terminal } from \"./terminal.js\";\nimport { getCapabilities, isImageLine, setCellDimensions } from \"./terminal-image.js\";\nimport { applyBackgroundToLine, extractSegments, sliceByColumn, sliceWithWidth, visibleWidth } from \"./utils.js\";\n\n/**\n * Component interface - all components must implement this\n */\nexport interface Component {\n\t/**\n\t * Render the component to lines for the given viewport width\n\t * @param width - Current viewport width\n\t * @returns Array of strings, each representing a line\n\t */\n\trender(width: number): string[];\n\n\t/**\n\t * Optional handler for keyboard input when component has focus\n\t */\n\thandleInput?(data: string): void;\n\n\t/**\n\t * If true, component receives key release events (Kitty protocol).\n\t * Default is false - release events are filtered out.\n\t */\n\twantsKeyRelease?: boolean;\n\n\t/**\n\t * Invalidate any cached rendering state.\n\t * Called when theme changes or when component needs to re-render from scratch.\n\t */\n\tinvalidate(): void;\n}\n\ntype InputListenerResult = { consume?: boolean; data?: string } | undefined;\ntype InputListener = (data: string) => InputListenerResult;\n\n/**\n * Interface for components that can receive focus and display a hardware cursor.\n * When focused, the component should emit CURSOR_MARKER at the cursor position\n * in its render output. TUI will find this marker and position the hardware\n * cursor there for proper IME candidate window positioning.\n */\nexport interface Focusable {\n\t/** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */\n\tfocused: boolean;\n}\n\n/** Type guard to check if a component implements Focusable */\nexport function isFocusable(component: Component | null): component is Component & Focusable {\n\treturn component !== null && \"focused\" in component;\n}\n\n/**\n * Cursor position marker - APC (Application Program Command) sequence.\n * This is a zero-width escape sequence that terminals ignore.\n * Components emit this at the cursor position when focused.\n * TUI finds and strips this marker, then positions the hardware cursor there.\n */\nexport const CURSOR_MARKER = \"\\x1b_pi:c\\x07\";\n\nexport { visibleWidth };\n\n/**\n * Anchor position for overlays\n */\nexport type OverlayAnchor =\n\t| \"center\"\n\t| \"top-left\"\n\t| \"top-right\"\n\t| \"bottom-left\"\n\t| \"bottom-right\"\n\t| \"top-center\"\n\t| \"bottom-center\"\n\t| \"left-center\"\n\t| \"right-center\";\n\n/**\n * Options for side panel positioning and sizing.\n */\nexport interface SidePanelOptions {\n\t/** Width in columns, or percentage of terminal width (e.g., \"40%\"). Default: \"40%\" */\n\twidth?: SizeValue;\n\t/** Which side to place the panel. Default: \"right\" */\n\tside?: \"left\" | \"right\";\n}\n\n/**\n * Handle returned by showSidePanel for controlling the panel\n */\nexport interface SidePanelHandle {\n\t/** Remove the side panel and restore focus */\n\thide(): void;\n}\n\n/**\n * Margin configuration for overlays\n */\nexport interface OverlayMargin {\n\ttop?: number;\n\tright?: number;\n\tbottom?: number;\n\tleft?: number;\n}\n\n/** Value that can be absolute (number) or percentage (string like \"50%\") */\nexport type SizeValue = number | `${number}%`;\n\n/** Parse a SizeValue into absolute value given a reference size */\nfunction parseSizeValue(value: SizeValue | undefined, referenceSize: number): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"number\") return value;\n\t// Parse percentage string like \"50%\"\n\tconst match = value.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\tif (match) {\n\t\treturn Math.floor((referenceSize * parseFloat(match[1])) / 100);\n\t}\n\treturn undefined;\n}\n\nfunction isTermuxSession(): boolean {\n\treturn Boolean(process.env.TERMUX_VERSION);\n}\n\n/**\n * Options for overlay positioning and sizing.\n * Values can be absolute numbers or percentage strings (e.g., \"50%\").\n */\nexport interface OverlayOptions {\n\t// === Sizing ===\n\t/** Width in columns, or percentage of terminal width (e.g., \"50%\") */\n\twidth?: SizeValue;\n\t/** Minimum width in columns */\n\tminWidth?: number;\n\t/** Maximum height in rows, or percentage of terminal height (e.g., \"50%\") */\n\tmaxHeight?: SizeValue;\n\n\t// === Positioning - anchor-based ===\n\t/** Anchor point for positioning (default: 'center') */\n\tanchor?: OverlayAnchor;\n\t/** Horizontal offset from anchor position (positive = right) */\n\toffsetX?: number;\n\t/** Vertical offset from anchor position (positive = down) */\n\toffsetY?: number;\n\n\t// === Positioning - percentage or absolute ===\n\t/** Row position: absolute number, or percentage (e.g., \"25%\" = 25% from top) */\n\trow?: SizeValue;\n\t/** Column position: absolute number, or percentage (e.g., \"50%\" = centered horizontally) */\n\tcol?: SizeValue;\n\n\t// === Margin from terminal edges ===\n\t/** Margin from terminal edges. Number applies to all sides. */\n\tmargin?: OverlayMargin | number;\n\n\t// === Visibility ===\n\t/**\n\t * Control overlay visibility based on terminal dimensions.\n\t * If provided, overlay is only rendered when this returns true.\n\t * Called each render cycle with current terminal dimensions.\n\t */\n\tvisible?: (termWidth: number, termHeight: number) => boolean;\n\t/** If true, don't capture keyboard focus when shown */\n\tnonCapturing?: boolean;\n}\n\n/**\n * Handle returned by showOverlay for controlling the overlay\n */\nexport interface OverlayHandle {\n\t/** Permanently remove the overlay (cannot be shown again) */\n\thide(): void;\n\t/** Temporarily hide or show the overlay */\n\tsetHidden(hidden: boolean): void;\n\t/** Check if overlay is temporarily hidden */\n\tisHidden(): boolean;\n\t/** Focus this overlay and bring it to the visual front */\n\tfocus(): void;\n\t/** Release focus to the previous target */\n\tunfocus(): void;\n\t/** Check if this overlay currently has focus */\n\tisFocused(): boolean;\n}\n\n/**\n * Container - a component that contains other components\n */\nexport class Container implements Component {\n\tchildren: Component[] = [];\n\n\taddChild(component: Component): void {\n\t\tthis.children.push(component);\n\t}\n\n\tremoveChild(component: Component): void {\n\t\tconst index = this.children.indexOf(component);\n\t\tif (index !== -1) {\n\t\t\tthis.children.splice(index, 1);\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis.children = [];\n\t}\n\n\tinvalidate(): void {\n\t\tfor (const child of this.children) {\n\t\t\tchild.invalidate?.();\n\t\t}\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\t\tfor (const child of this.children) {\n\t\t\tlines.push(...child.render(width));\n\t\t}\n\t\treturn lines;\n\t}\n}\n\n/**\n * TUI - Main class for managing terminal UI with differential rendering\n */\nexport class TUI extends Container {\n\tpublic terminal: Terminal;\n\tprivate previousLines: string[] = [];\n\tprivate previousWidth = 0;\n\tprivate previousHeight = 0;\n\tprivate focusedComponent: Component | null = null;\n\tprivate inputListeners = new Set<InputListener>();\n\n\t/** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */\n\tpublic onDebug?: () => void;\n\tprivate renderRequested = false;\n\tprivate renderTimer: NodeJS.Timeout | undefined;\n\tprivate lastRenderAt = 0;\n\tprivate static readonly MIN_RENDER_INTERVAL_MS = 16;\n\tprivate cursorRow = 0; // Logical cursor row (end of rendered content)\n\tprivate hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)\n\tprivate showHardwareCursor = process.env.PI_HARDWARE_CURSOR === \"1\";\n\tprivate clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === \"1\"; // Clear empty rows when content shrinks (default: off)\n\tprivate maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)\n\tprivate previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves\n\tprivate fullRedrawCount = 0;\n\tprivate stopped = false;\n\tprivate globalBgFn: ((text: string) => string) | null = null;\n\tprivate bottomPinnedChildren = 0;\n\n\t// Side panel for column-based layout alongside main content\n\tprivate sidePanelEntry: {\n\t\tcomponent: Component;\n\t\toptions: SidePanelOptions;\n\t\tpreFocus: Component | null;\n\t} | null = null;\n\n\t// Overlay stack for modal components rendered on top of base content\n\tprivate focusOrderCounter = 0;\n\tprivate overlayStack: {\n\t\tcomponent: Component;\n\t\toptions?: OverlayOptions;\n\t\tpreFocus: Component | null;\n\t\thidden: boolean;\n\t\tfocusOrder: number;\n\t}[] = [];\n\n\tconstructor(terminal: Terminal, showHardwareCursor?: boolean) {\n\t\tsuper();\n\t\tthis.terminal = terminal;\n\t\tif (showHardwareCursor !== undefined) {\n\t\t\tthis.showHardwareCursor = showHardwareCursor;\n\t\t}\n\t}\n\n\tget fullRedraws(): number {\n\t\treturn this.fullRedrawCount;\n\t}\n\n\tgetShowHardwareCursor(): boolean {\n\t\treturn this.showHardwareCursor;\n\t}\n\n\tsetShowHardwareCursor(enabled: boolean): void {\n\t\tif (this.showHardwareCursor === enabled) return;\n\t\tthis.showHardwareCursor = enabled;\n\t\tif (!enabled) {\n\t\t\tthis.terminal.hideCursor();\n\t\t}\n\t\tthis.requestRender();\n\t}\n\n\tgetClearOnShrink(): boolean {\n\t\treturn this.clearOnShrink;\n\t}\n\n\t/**\n\t * Set whether to trigger full re-render when content shrinks.\n\t * When true (default), empty rows are cleared when content shrinks.\n\t * When false, empty rows remain (reduces redraws on slower terminals).\n\t */\n\tsetClearOnShrink(enabled: boolean): void {\n\t\tthis.clearOnShrink = enabled;\n\t}\n\n\tsetGlobalBackground(bgFn: ((text: string) => string) | null): void {\n\t\tthis.globalBgFn = bgFn;\n\t\tthis.invalidate();\n\t\tthis.requestRender();\n\t}\n\n\t/**\n\t * Pin the last N children to the bottom of the viewport.\n\t * When content is shorter than the terminal, empty padding is inserted\n\t * between main content and the pinned children to push them down.\n\t */\n\tsetBottomPinnedChildren(count: number): void {\n\t\tthis.bottomPinnedChildren = count;\n\t}\n\n\tsetFocus(component: Component | null): void {\n\t\t// Clear focused flag on old component\n\t\tif (isFocusable(this.focusedComponent)) {\n\t\t\tthis.focusedComponent.focused = false;\n\t\t}\n\n\t\tthis.focusedComponent = component;\n\n\t\t// Set focused flag on new component\n\t\tif (isFocusable(component)) {\n\t\t\tcomponent.focused = true;\n\t\t}\n\t}\n\n\t/**\n\t * Show an overlay component with configurable positioning and sizing.\n\t * Returns a handle to control the overlay's visibility.\n\t */\n\tshowOverlay(component: Component, options?: OverlayOptions): OverlayHandle {\n\t\tconst entry = {\n\t\t\tcomponent,\n\t\t\toptions,\n\t\t\tpreFocus: this.focusedComponent,\n\t\t\thidden: false,\n\t\t\tfocusOrder: ++this.focusOrderCounter,\n\t\t};\n\t\tthis.overlayStack.push(entry);\n\t\t// Only focus if overlay is actually visible\n\t\tif (!options?.nonCapturing && this.isOverlayVisible(entry)) {\n\t\t\tthis.setFocus(component);\n\t\t}\n\t\tthis.terminal.hideCursor();\n\t\tthis.requestRender();\n\n\t\t// Return handle for controlling this overlay\n\t\treturn {\n\t\t\thide: () => {\n\t\t\t\tconst index = this.overlayStack.indexOf(entry);\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\tthis.overlayStack.splice(index, 1);\n\t\t\t\t\t// Restore focus if this overlay had focus\n\t\t\t\t\tif (this.focusedComponent === component) {\n\t\t\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\t\t\tthis.setFocus(topVisible?.component ?? entry.preFocus);\n\t\t\t\t\t}\n\t\t\t\t\tif (this.overlayStack.length === 0) this.terminal.hideCursor();\n\t\t\t\t\tthis.requestRender();\n\t\t\t\t}\n\t\t\t},\n\t\t\tsetHidden: (hidden: boolean) => {\n\t\t\t\tif (entry.hidden === hidden) return;\n\t\t\t\tentry.hidden = hidden;\n\t\t\t\t// Update focus when hiding/showing\n\t\t\t\tif (hidden) {\n\t\t\t\t\t// If this overlay had focus, move focus to next visible or preFocus\n\t\t\t\t\tif (this.focusedComponent === component) {\n\t\t\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\t\t\tthis.setFocus(topVisible?.component ?? entry.preFocus);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Restore focus to this overlay when showing (if it's actually visible)\n\t\t\t\t\tif (!options?.nonCapturing && this.isOverlayVisible(entry)) {\n\t\t\t\t\t\tentry.focusOrder = ++this.focusOrderCounter;\n\t\t\t\t\t\tthis.setFocus(component);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tisHidden: () => entry.hidden,\n\t\t\tfocus: () => {\n\t\t\t\tif (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry)) return;\n\t\t\t\tif (this.focusedComponent !== component) {\n\t\t\t\t\tthis.setFocus(component);\n\t\t\t\t}\n\t\t\t\tentry.focusOrder = ++this.focusOrderCounter;\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tunfocus: () => {\n\t\t\t\tif (this.focusedComponent !== component) return;\n\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\tthis.setFocus(topVisible && topVisible !== entry ? topVisible.component : entry.preFocus);\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tisFocused: () => this.focusedComponent === component,\n\t\t};\n\t}\n\n\t/** Hide the topmost overlay and restore previous focus. */\n\thideOverlay(): void {\n\t\tconst overlay = this.overlayStack.pop();\n\t\tif (!overlay) return;\n\t\tif (this.focusedComponent === overlay.component) {\n\t\t\t// Find topmost visible overlay, or fall back to preFocus\n\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\tthis.setFocus(topVisible?.component ?? overlay.preFocus);\n\t\t}\n\t\tif (this.overlayStack.length === 0) this.terminal.hideCursor();\n\t\tthis.requestRender();\n\t}\n\n\t/** Show a side panel alongside the main content in a column layout. */\n\tshowSidePanel(component: Component, options?: SidePanelOptions): SidePanelHandle {\n\t\tthis.sidePanelEntry = {\n\t\t\tcomponent,\n\t\t\toptions: options ?? {},\n\t\t\tpreFocus: this.focusedComponent,\n\t\t};\n\t\tthis.setFocus(component);\n\t\tthis.terminal.hideCursor();\n\t\tthis.requestRender();\n\t\treturn {\n\t\t\thide: () => this.hideSidePanel(),\n\t\t};\n\t}\n\n\t/** Hide the side panel and restore previous focus. */\n\thideSidePanel(): void {\n\t\tif (!this.sidePanelEntry) return;\n\t\tconst preFocus = this.sidePanelEntry.preFocus;\n\t\tthis.sidePanelEntry = null;\n\t\tthis.setFocus(preFocus);\n\t\tthis.requestRender();\n\t}\n\n\t/** Check if a side panel is currently shown. */\n\thasSidePanel(): boolean {\n\t\treturn this.sidePanelEntry !== null;\n\t}\n\n\t/** Check if there are any visible overlays */\n\thasOverlay(): boolean {\n\t\treturn this.overlayStack.some((o) => this.isOverlayVisible(o));\n\t}\n\n\t/** Check if an overlay entry is currently visible */\n\tprivate isOverlayVisible(entry: (typeof this.overlayStack)[number]): boolean {\n\t\tif (entry.hidden) return false;\n\t\tif (entry.options?.visible) {\n\t\t\treturn entry.options.visible(this.terminal.columns, this.terminal.rows);\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Find the topmost visible capturing overlay, if any */\n\tprivate getTopmostVisibleOverlay(): (typeof this.overlayStack)[number] | undefined {\n\t\tfor (let i = this.overlayStack.length - 1; i >= 0; i--) {\n\t\t\tif (this.overlayStack[i].options?.nonCapturing) continue;\n\t\t\tif (this.isOverlayVisible(this.overlayStack[i])) {\n\t\t\t\treturn this.overlayStack[i];\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tthis.sidePanelEntry?.component.invalidate?.();\n\t\tfor (const overlay of this.overlayStack) overlay.component.invalidate?.();\n\t}\n\n\tstart(): void {\n\t\tthis.stopped = false;\n\t\tthis.terminal.start(\n\t\t\t(data) => this.handleInput(data),\n\t\t\t() => this.requestRender(),\n\t\t);\n\t\tthis.terminal.hideCursor();\n\t\tthis.queryCellSize();\n\t\tthis.requestRender();\n\t}\n\n\taddInputListener(listener: InputListener): () => void {\n\t\tthis.inputListeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.inputListeners.delete(listener);\n\t\t};\n\t}\n\n\tremoveInputListener(listener: InputListener): void {\n\t\tthis.inputListeners.delete(listener);\n\t}\n\n\tprivate queryCellSize(): void {\n\t\t// Only query if terminal supports images (cell size is only used for image rendering)\n\t\tif (!getCapabilities().images) {\n\t\t\treturn;\n\t\t}\n\t\t// Query terminal for cell size in pixels: CSI 16 t\n\t\t// Response format: CSI 6 ; height ; width t\n\t\tthis.terminal.write(\"\\x1b[16t\");\n\t}\n\n\tstop(): void {\n\t\tif (this.stopped) return;\n\t\tthis.stopped = true;\n\t\tif (this.renderTimer) {\n\t\t\tclearTimeout(this.renderTimer);\n\t\t\tthis.renderTimer = undefined;\n\t\t}\n\t\t// Position the cursor on a fresh line below the rendered content so the\n\t\t// terminal's next prompt doesn't overwrite the last frame, and the full\n\t\t// transcript stays in scrollback (matches upstream pi-mono behavior).\n\t\tif (this.previousLines.length > 0) {\n\t\t\tconst targetRow = this.previousLines.length;\n\t\t\tconst lineDiff = targetRow - this.hardwareCursorRow;\n\t\t\tif (lineDiff > 0) {\n\t\t\t\tthis.terminal.write(`\\x1b[${lineDiff}B`);\n\t\t\t} else if (lineDiff < 0) {\n\t\t\t\tthis.terminal.write(`\\x1b[${-lineDiff}A`);\n\t\t\t}\n\t\t\tthis.terminal.write(\"\\r\\n\");\n\t\t}\n\t\tthis.terminal.showCursor();\n\t\tthis.terminal.stop();\n\t}\n\n\trequestRender(force = false): void {\n\t\tif (force) {\n\t\t\tthis.previousLines = [];\n\t\t\tthis.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear\n\t\t\tthis.previousHeight = -1; // -1 triggers heightChanged, forcing a full clear\n\t\t\tthis.cursorRow = 0;\n\t\t\tthis.hardwareCursorRow = 0;\n\t\t\tthis.maxLinesRendered = 0;\n\t\t\tthis.previousViewportTop = 0;\n\t\t\tif (this.renderTimer) {\n\t\t\t\tclearTimeout(this.renderTimer);\n\t\t\t\tthis.renderTimer = undefined;\n\t\t\t}\n\t\t\tthis.renderRequested = true;\n\t\t\tprocess.nextTick(() => {\n\t\t\t\tif (this.stopped || !this.renderRequested) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.renderRequested = false;\n\t\t\t\tthis.lastRenderAt = performance.now();\n\t\t\t\tthis.doRender();\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (this.renderRequested) return;\n\t\tthis.renderRequested = true;\n\t\tprocess.nextTick(() => this.scheduleRender());\n\t}\n\n\tprivate scheduleRender(): void {\n\t\tif (this.stopped || this.renderTimer || !this.renderRequested) {\n\t\t\treturn;\n\t\t}\n\t\tconst elapsed = performance.now() - this.lastRenderAt;\n\t\tconst delay = Math.max(0, TUI.MIN_RENDER_INTERVAL_MS - elapsed);\n\t\tthis.renderTimer = setTimeout(() => {\n\t\t\tthis.renderTimer = undefined;\n\t\t\tif (this.stopped || !this.renderRequested) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renderRequested = false;\n\t\t\tthis.lastRenderAt = performance.now();\n\t\t\tthis.doRender();\n\t\t\tif (this.renderRequested) {\n\t\t\t\tthis.scheduleRender();\n\t\t\t}\n\t\t}, delay);\n\t}\n\n\tprivate handleInput(data: string): void {\n\t\tif (this.inputListeners.size > 0) {\n\t\t\tlet current = data;\n\t\t\tfor (const listener of this.inputListeners) {\n\t\t\t\tconst result = listener(current);\n\t\t\t\tif (result?.consume) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (result?.data !== undefined) {\n\t\t\t\t\tcurrent = result.data;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (current.length === 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdata = current;\n\t\t}\n\n\t\t// Consume terminal cell size responses without blocking unrelated input.\n\t\tif (this.consumeCellSizeResponse(data)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Global debug key handler (Shift+Ctrl+D)\n\t\tif (matchesKey(data, \"shift+ctrl+d\") && this.onDebug) {\n\t\t\tthis.onDebug();\n\t\t\treturn;\n\t\t}\n\n\t\t// If focused component is an overlay, verify it's still visible\n\t\t// (visibility can change due to terminal resize or visible() callback)\n\t\tconst focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);\n\t\tif (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {\n\t\t\t// Focused overlay is no longer visible, redirect to topmost visible overlay\n\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\tif (topVisible) {\n\t\t\t\tthis.setFocus(topVisible.component);\n\t\t\t} else {\n\t\t\t\t// No visible overlays, restore to preFocus\n\t\t\t\tthis.setFocus(focusedOverlay.preFocus);\n\t\t\t}\n\t\t}\n\n\t\t// Pass input to focused component (including Ctrl+C)\n\t\t// The focused component can decide how to handle Ctrl+C\n\t\tif (this.focusedComponent?.handleInput) {\n\t\t\t// Filter out key release events unless component opts in\n\t\t\tif (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.focusedComponent.handleInput(data);\n\t\t\tthis.requestRender();\n\t\t}\n\t}\n\n\tprivate consumeCellSizeResponse(data: string): boolean {\n\t\t// Response format: ESC [ 6 ; height ; width t\n\t\tconst match = data.match(/^\\x1b\\[6;(\\d+);(\\d+)t$/);\n\t\tif (!match) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst heightPx = parseInt(match[1], 10);\n\t\tconst widthPx = parseInt(match[2], 10);\n\t\tif (heightPx <= 0 || widthPx <= 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\tsetCellDimensions({ widthPx, heightPx });\n\t\t// Invalidate all components so images re-render with correct dimensions.\n\t\tthis.invalidate();\n\t\tthis.requestRender();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Resolve overlay layout from options.\n\t * Returns { width, row, col, maxHeight } for rendering.\n\t */\n\tprivate resolveOverlayLayout(\n\t\toptions: OverlayOptions | undefined,\n\t\toverlayHeight: number,\n\t\ttermWidth: number,\n\t\ttermHeight: number,\n\t): { width: number; row: number; col: number; maxHeight: number | undefined } {\n\t\tconst opt = options ?? {};\n\n\t\t// Parse margin (clamp to non-negative)\n\t\tconst margin =\n\t\t\ttypeof opt.margin === \"number\"\n\t\t\t\t? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }\n\t\t\t\t: (opt.margin ?? {});\n\t\tconst marginTop = Math.max(0, margin.top ?? 0);\n\t\tconst marginRight = Math.max(0, margin.right ?? 0);\n\t\tconst marginBottom = Math.max(0, margin.bottom ?? 0);\n\t\tconst marginLeft = Math.max(0, margin.left ?? 0);\n\n\t\t// Available space after margins\n\t\tconst availWidth = Math.max(1, termWidth - marginLeft - marginRight);\n\t\tconst availHeight = Math.max(1, termHeight - marginTop - marginBottom);\n\n\t\t// === Resolve width ===\n\t\tlet width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);\n\t\t// Apply minWidth\n\t\tif (opt.minWidth !== undefined) {\n\t\t\twidth = Math.max(width, opt.minWidth);\n\t\t}\n\t\t// Clamp to available space\n\t\twidth = Math.max(1, Math.min(width, availWidth));\n\n\t\t// === Resolve maxHeight ===\n\t\tlet maxHeight = parseSizeValue(opt.maxHeight, termHeight);\n\t\t// Clamp to available space\n\t\tif (maxHeight !== undefined) {\n\t\t\tmaxHeight = Math.max(1, Math.min(maxHeight, availHeight));\n\t\t}\n\n\t\t// Effective overlay height (may be clamped by maxHeight)\n\t\tconst effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;\n\n\t\t// === Resolve position ===\n\t\tlet row: number;\n\t\tlet col: number;\n\n\t\tif (opt.row !== undefined) {\n\t\t\tif (typeof opt.row === \"string\") {\n\t\t\t\t// Percentage: 0% = top, 100% = bottom (overlay stays within bounds)\n\t\t\t\tconst match = opt.row.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\t\t\t\tif (match) {\n\t\t\t\t\tconst maxRow = Math.max(0, availHeight - effectiveHeight);\n\t\t\t\t\tconst percent = parseFloat(match[1]) / 100;\n\t\t\t\t\trow = marginTop + Math.floor(maxRow * percent);\n\t\t\t\t} else {\n\t\t\t\t\t// Invalid format, fall back to center\n\t\t\t\t\trow = this.resolveAnchorRow(\"center\", effectiveHeight, availHeight, marginTop);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Absolute row position\n\t\t\t\trow = opt.row;\n\t\t\t}\n\t\t} else {\n\t\t\t// Anchor-based (default: center)\n\t\t\tconst anchor = opt.anchor ?? \"center\";\n\t\t\trow = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);\n\t\t}\n\n\t\tif (opt.col !== undefined) {\n\t\t\tif (typeof opt.col === \"string\") {\n\t\t\t\t// Percentage: 0% = left, 100% = right (overlay stays within bounds)\n\t\t\t\tconst match = opt.col.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\t\t\t\tif (match) {\n\t\t\t\t\tconst maxCol = Math.max(0, availWidth - width);\n\t\t\t\t\tconst percent = parseFloat(match[1]) / 100;\n\t\t\t\t\tcol = marginLeft + Math.floor(maxCol * percent);\n\t\t\t\t} else {\n\t\t\t\t\t// Invalid format, fall back to center\n\t\t\t\t\tcol = this.resolveAnchorCol(\"center\", width, availWidth, marginLeft);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Absolute column position\n\t\t\t\tcol = opt.col;\n\t\t\t}\n\t\t} else {\n\t\t\t// Anchor-based (default: center)\n\t\t\tconst anchor = opt.anchor ?? \"center\";\n\t\t\tcol = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);\n\t\t}\n\n\t\t// Apply offsets\n\t\tif (opt.offsetY !== undefined) row += opt.offsetY;\n\t\tif (opt.offsetX !== undefined) col += opt.offsetX;\n\n\t\t// Clamp to terminal bounds (respecting margins)\n\t\trow = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));\n\t\tcol = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));\n\n\t\treturn { width, row, col, maxHeight };\n\t}\n\n\tprivate resolveAnchorRow(anchor: OverlayAnchor, height: number, availHeight: number, marginTop: number): number {\n\t\tswitch (anchor) {\n\t\t\tcase \"top-left\":\n\t\t\tcase \"top-center\":\n\t\t\tcase \"top-right\":\n\t\t\t\treturn marginTop;\n\t\t\tcase \"bottom-left\":\n\t\t\tcase \"bottom-center\":\n\t\t\tcase \"bottom-right\":\n\t\t\t\treturn marginTop + availHeight - height;\n\t\t\tcase \"left-center\":\n\t\t\tcase \"center\":\n\t\t\tcase \"right-center\":\n\t\t\t\treturn marginTop + Math.floor((availHeight - height) / 2);\n\t\t}\n\t}\n\n\tprivate resolveAnchorCol(anchor: OverlayAnchor, width: number, availWidth: number, marginLeft: number): number {\n\t\tswitch (anchor) {\n\t\t\tcase \"top-left\":\n\t\t\tcase \"left-center\":\n\t\t\tcase \"bottom-left\":\n\t\t\t\treturn marginLeft;\n\t\t\tcase \"top-right\":\n\t\t\tcase \"right-center\":\n\t\t\tcase \"bottom-right\":\n\t\t\t\treturn marginLeft + availWidth - width;\n\t\t\tcase \"top-center\":\n\t\t\tcase \"center\":\n\t\t\tcase \"bottom-center\":\n\t\t\t\treturn marginLeft + Math.floor((availWidth - width) / 2);\n\t\t}\n\t}\n\n\t/** Render main content and side panel in a two-column layout. */\n\tprivate renderWithSidePanel(termWidth: number, termHeight: number): string[] {\n\t\tconst panel = this.sidePanelEntry!;\n\t\tconst panelWidth = parseSizeValue(panel.options.width, termWidth) ?? Math.floor(termWidth * 0.4);\n\t\tconst mainWidth = Math.max(1, termWidth - panelWidth - 1); // 1 for separator\n\t\tconst isRight = (panel.options.side ?? \"right\") === \"right\";\n\n\t\tconst mainLines = this.render(isRight ? mainWidth : panelWidth);\n\t\tconst panelLines = panel.component.render(isRight ? panelWidth : mainWidth);\n\t\tconst maxRows = Math.max(mainLines.length, panelLines.length, termHeight);\n\n\t\tconst leftLines = isRight ? mainLines : panelLines;\n\t\tconst rightLines = isRight ? panelLines : mainLines;\n\t\tconst leftW = isRight ? mainWidth : panelWidth;\n\t\tconst rightW = isRight ? panelWidth : mainWidth;\n\n\t\tconst result: string[] = [];\n\t\tconst RESET = \"\\x1b[0m\";\n\n\t\tfor (let i = 0; i < maxRows; i++) {\n\t\t\tconst lRaw = leftLines[i] ?? \"\";\n\t\t\tconst rRaw = rightLines[i] ?? \"\";\n\t\t\tconst lTrunc = visibleWidth(lRaw) > leftW ? sliceByColumn(lRaw, 0, leftW, true) : lRaw;\n\t\t\tconst rTrunc = visibleWidth(rRaw) > rightW ? sliceByColumn(rRaw, 0, rightW, true) : rRaw;\n\t\t\tconst lPad = \" \".repeat(Math.max(0, leftW - visibleWidth(lTrunc)));\n\t\t\tconst rPad = \" \".repeat(Math.max(0, rightW - visibleWidth(rTrunc)));\n\t\t\tresult.push(`${lTrunc}${RESET}${lPad}│${rTrunc}${RESET}${rPad}`);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */\n\tprivate compositeOverlays(lines: string[], termWidth: number, termHeight: number): string[] {\n\t\tif (this.overlayStack.length === 0) return lines;\n\t\tconst result = [...lines];\n\n\t\t// Pre-render all visible overlays and calculate positions\n\t\tconst rendered: { overlayLines: string[]; row: number; col: number; w: number }[] = [];\n\t\tlet minLinesNeeded = result.length;\n\n\t\tconst visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));\n\t\tvisibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);\n\t\tfor (const entry of visibleEntries) {\n\t\t\tconst { component, options } = entry;\n\n\t\t\t// Get layout with height=0 first to determine width and maxHeight\n\t\t\t// (width and maxHeight don't depend on overlay height)\n\t\t\tconst { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);\n\n\t\t\t// Render component at calculated width\n\t\t\tlet overlayLines = component.render(width);\n\n\t\t\t// Apply maxHeight if specified\n\t\t\tif (maxHeight !== undefined && overlayLines.length > maxHeight) {\n\t\t\t\toverlayLines = overlayLines.slice(0, maxHeight);\n\t\t\t}\n\n\t\t\t// Get final row/col with actual overlay height\n\t\t\tconst { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);\n\n\t\t\trendered.push({ overlayLines, row, col, w: width });\n\t\t\tminLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);\n\t\t}\n\n\t\t// Pad to at least terminal height so overlays have screen-relative positions.\n\t\t// Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing\n\t\t// inflation that pushed content into scrollback on terminal widen.\n\t\tconst workingHeight = Math.max(result.length, termHeight, minLinesNeeded);\n\n\t\t// Extend result with empty lines if content is too short for overlay placement or working area\n\t\twhile (result.length < workingHeight) {\n\t\t\tresult.push(\"\");\n\t\t}\n\n\t\tconst viewportStart = Math.max(0, workingHeight - termHeight);\n\n\t\t// Composite each overlay\n\t\tfor (const { overlayLines, row, col, w } of rendered) {\n\t\t\tfor (let i = 0; i < overlayLines.length; i++) {\n\t\t\t\tconst idx = viewportStart + row + i;\n\t\t\t\tif (idx >= 0 && idx < result.length) {\n\t\t\t\t\t// Defensive: truncate overlay line to declared width before compositing\n\t\t\t\t\t// (components should already respect width, but this ensures it)\n\t\t\t\t\tconst truncatedOverlayLine =\n\t\t\t\t\t\tvisibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];\n\t\t\t\t\tresult[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Render with bottom-pinned children pushed to the bottom of the viewport.\n\t */\n\tprivate renderWithBottomPin(width: number, height: number): string[] {\n\t\tconst pinnedCount = this.bottomPinnedChildren;\n\t\tif (pinnedCount <= 0 || pinnedCount >= this.children.length) {\n\t\t\treturn this.render(width);\n\t\t}\n\n\t\tconst splitAt = this.children.length - pinnedCount;\n\t\tconst mainLines: string[] = [];\n\t\tfor (let i = 0; i < splitAt; i++) {\n\t\t\tmainLines.push(...this.children[i].render(width));\n\t\t}\n\t\tconst bottomLines: string[] = [];\n\t\tfor (let i = splitAt; i < this.children.length; i++) {\n\t\t\tbottomLines.push(...this.children[i].render(width));\n\t\t}\n\n\t\tconst totalContent = mainLines.length + bottomLines.length;\n\t\tif (totalContent >= height) {\n\t\t\treturn [...mainLines, ...bottomLines];\n\t\t}\n\n\t\tconst padCount = height - totalContent;\n\t\tconst emptyLines = new Array<string>(padCount).fill(\"\");\n\t\treturn [...mainLines, ...emptyLines, ...bottomLines];\n\t}\n\n\tprivate static readonly SEGMENT_RESET = \"\\x1b[0m\\x1b]8;;\\x07\";\n\n\tprivate applyLineResets(lines: string[], width: number): string[] {\n\t\tconst reset = TUI.SEGMENT_RESET;\n\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\tconst line = lines[i];\n\t\t\tif (!isImageLine(line)) {\n\t\t\t\tconst processedLine = this.globalBgFn ? applyBackgroundToLine(line, width, this.globalBgFn) : line;\n\t\t\t\tlines[i] = processedLine + reset;\n\t\t\t}\n\t\t}\n\t\treturn lines;\n\t}\n\n\t/** Splice overlay content into a base line at a specific column. Single-pass optimized. */\n\tprivate compositeLineAt(\n\t\tbaseLine: string,\n\t\toverlayLine: string,\n\t\tstartCol: number,\n\t\toverlayWidth: number,\n\t\ttotalWidth: number,\n\t): string {\n\t\tif (isImageLine(baseLine)) return baseLine;\n\n\t\t// Single pass through baseLine extracts both before and after segments\n\t\tconst afterStart = startCol + overlayWidth;\n\t\tconst base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);\n\n\t\t// Extract overlay with width tracking (strict=true to exclude wide chars at boundary)\n\t\tconst overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);\n\n\t\t// Pad segments to target widths\n\t\tconst beforePad = Math.max(0, startCol - base.beforeWidth);\n\t\tconst overlayPad = Math.max(0, overlayWidth - overlay.width);\n\t\tconst actualBeforeWidth = Math.max(startCol, base.beforeWidth);\n\t\tconst actualOverlayWidth = Math.max(overlayWidth, overlay.width);\n\t\tconst afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);\n\t\tconst afterPad = Math.max(0, afterTarget - base.afterWidth);\n\n\t\t// Compose result\n\t\tconst r = TUI.SEGMENT_RESET;\n\t\tconst result =\n\t\t\tbase.before +\n\t\t\t\" \".repeat(beforePad) +\n\t\t\tr +\n\t\t\toverlay.text +\n\t\t\t\" \".repeat(overlayPad) +\n\t\t\tr +\n\t\t\tbase.after +\n\t\t\t\" \".repeat(afterPad);\n\n\t\t// CRITICAL: Always verify and truncate to terminal width.\n\t\t// This is the final safeguard against width overflow which would crash the TUI.\n\t\t// Width tracking can drift from actual visible width due to:\n\t\t// - Complex ANSI/OSC sequences (hyperlinks, colors)\n\t\t// - Wide characters at segment boundaries\n\t\t// - Edge cases in segment extraction\n\t\tconst resultWidth = visibleWidth(result);\n\t\tif (resultWidth <= totalWidth) {\n\t\t\treturn result;\n\t\t}\n\t\t// Truncate with strict=true to ensure we don't exceed totalWidth\n\t\treturn sliceByColumn(result, 0, totalWidth, true);\n\t}\n\n\t/**\n\t * Find and extract cursor position from rendered lines.\n\t * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.\n\t * Only scans the bottom terminal height lines (visible viewport).\n\t * @param lines - Rendered lines to search\n\t * @param height - Terminal height (visible viewport size)\n\t * @returns Cursor position { row, col } or null if no marker found\n\t */\n\tprivate extractCursorPosition(lines: string[], height: number): { row: number; col: number } | null {\n\t\t// Only scan the bottom `height` lines (visible viewport)\n\t\tconst viewportTop = Math.max(0, lines.length - height);\n\t\tfor (let row = lines.length - 1; row >= viewportTop; row--) {\n\t\t\tconst line = lines[row];\n\t\t\tconst markerIndex = line.indexOf(CURSOR_MARKER);\n\t\t\tif (markerIndex !== -1) {\n\t\t\t\t// Calculate visual column (width of text before marker)\n\t\t\t\tconst beforeMarker = line.slice(0, markerIndex);\n\t\t\t\tconst col = visibleWidth(beforeMarker);\n\n\t\t\t\t// Strip marker from the line\n\t\t\t\tlines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);\n\n\t\t\t\treturn { row, col };\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Minimum terminal dimensions for a normal render.\n\t * Below these, we fall back to a degenerate-size placeholder per\n\t * cavekit-fullscreen-viewport R2 AC4 and R3 AC4.\n\t */\n\tprivate static readonly MIN_ROWS = 4;\n\tprivate static readonly MIN_COLS = 20;\n\n\tprivate renderDegenerateFrame(width: number, height: number): string[] {\n\t\tconst msg = \"terminal too small\";\n\t\tconst lines: string[] = [];\n\t\tif (height <= 0 || width <= 0) return lines;\n\t\tif (width >= msg.length) {\n\t\t\tconst pad = \" \".repeat(Math.max(0, Math.floor((width - msg.length) / 2)));\n\t\t\tlines.push((pad + msg).slice(0, width));\n\t\t} else {\n\t\t\tlines.push(msg.slice(0, width));\n\t\t}\n\t\twhile (lines.length < height) lines.push(\"\");\n\t\treturn lines.slice(0, height);\n\t}\n\n\tprivate doRender(): void {\n\t\tif (this.stopped) return;\n\t\tconst width = this.terminal.columns;\n\t\tconst height = this.terminal.rows;\n\n\t\t// Degenerate-size placeholder — never crash, never write outside bounds.\n\t\tif (height < TUI.MIN_ROWS || width < TUI.MIN_COLS) {\n\t\t\tconst frame = this.renderDegenerateFrame(width, height);\n\t\t\tlet buffer = \"\\x1b[?2026h\\x1b[2J\\x1b[H\";\n\t\t\tfor (let i = 0; i < frame.length; i++) {\n\t\t\t\tif (i > 0) buffer += \"\\r\\n\";\n\t\t\t\tbuffer += frame[i];\n\t\t\t}\n\t\t\tbuffer += \"\\x1b[?2026l\";\n\t\t\tthis.terminal.write(buffer);\n\t\t\tthis.previousLines = frame;\n\t\t\tthis.previousWidth = width;\n\t\t\tthis.previousHeight = height;\n\t\t\treturn;\n\t\t}\n\t\tconst widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;\n\t\tconst heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;\n\t\tconst previousBufferLength = this.previousHeight > 0 ? this.previousViewportTop + this.previousHeight : height;\n\t\tlet prevViewportTop = heightChanged ? Math.max(0, previousBufferLength - height) : this.previousViewportTop;\n\t\tlet viewportTop = prevViewportTop;\n\t\tlet hardwareCursorRow = this.hardwareCursorRow;\n\t\tconst computeLineDiff = (targetRow: number): number => {\n\t\t\tconst currentScreenRow = hardwareCursorRow - prevViewportTop;\n\t\t\tconst targetScreenRow = targetRow - viewportTop;\n\t\t\treturn targetScreenRow - currentScreenRow;\n\t\t};\n\n\t\t// Render all components to get new lines\n\t\tlet newLines: string[];\n\t\tif (this.sidePanelEntry) {\n\t\t\tnewLines = this.renderWithSidePanel(width, height);\n\t\t} else if (this.bottomPinnedChildren > 0) {\n\t\t\tnewLines = this.renderWithBottomPin(width, height);\n\t\t} else {\n\t\t\tnewLines = this.render(width);\n\t\t}\n\n\t\t// Composite overlays into the rendered lines (before differential compare)\n\t\tif (this.overlayStack.length > 0) {\n\t\t\tnewLines = this.compositeOverlays(newLines, width, height);\n\t\t}\n\n\t\t// Extract cursor position before applying line resets (marker must be found first)\n\t\tconst cursorPos = this.extractCursorPosition(newLines, height);\n\n\t\tnewLines = this.applyLineResets(newLines, width);\n\n\t\t// Pad to fill terminal height when global background is active\n\t\tif (this.globalBgFn && newLines.length < height) {\n\t\t\tconst emptyBgLine = applyBackgroundToLine(\"\", width, this.globalBgFn) + TUI.SEGMENT_RESET;\n\t\t\twhile (newLines.length < height) {\n\t\t\t\tnewLines.push(emptyBgLine);\n\t\t\t}\n\t\t}\n\n\t\t// Helper to clear scrollback and viewport and render all new lines\n\t\tconst fullRender = (clear: boolean): void => {\n\t\t\tthis.fullRedrawCount += 1;\n\t\t\tlet buffer = \"\\x1b[?2026h\"; // Begin synchronized output\n\t\t\tif (clear) buffer += \"\\x1b[2J\\x1b[H\\x1b[3J\"; // Clear screen, home, then clear scrollback\n\t\t\tfor (let i = 0; i < newLines.length; i++) {\n\t\t\t\tif (i > 0) buffer += \"\\r\\n\";\n\t\t\t\tbuffer += newLines[i];\n\t\t\t}\n\t\t\tbuffer += \"\\x1b[?2026l\"; // End synchronized output\n\t\t\tthis.terminal.write(buffer);\n\t\t\tthis.cursorRow = Math.max(0, newLines.length - 1);\n\t\t\tthis.hardwareCursorRow = this.cursorRow;\n\t\t\t// Reset max lines when clearing, otherwise track growth\n\t\t\tif (clear) {\n\t\t\t\tthis.maxLinesRendered = newLines.length;\n\t\t\t} else {\n\t\t\t\tthis.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);\n\t\t\t}\n\t\t\tconst bufferLength = Math.max(height, newLines.length);\n\t\t\tthis.previousViewportTop = Math.max(0, bufferLength - height);\n\t\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\t\t\tthis.previousLines = newLines;\n\t\t\tthis.previousWidth = width;\n\t\t\tthis.previousHeight = height;\n\t\t};\n\n\t\tconst debugRedraw = process.env.PI_DEBUG_REDRAW === \"1\";\n\t\tconst logRedraw = (reason: string): void => {\n\t\t\tif (!debugRedraw) return;\n\t\t\tconst logPath = path.join(os.homedir(), \".pi\", \"agent\", \"pi-debug.log\");\n\t\t\tconst msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\\n`;\n\t\t\tfs.appendFileSync(logPath, msg);\n\t\t};\n\n\t\t// First render - just output everything without clearing (assumes clean screen)\n\t\tif (this.previousLines.length === 0 && !widthChanged && !heightChanged) {\n\t\t\tlogRedraw(\"first render\");\n\t\t\tfullRender(false);\n\t\t\treturn;\n\t\t}\n\n\t\t// Width changes always need a full re-render because wrapping changes.\n\t\tif (widthChanged) {\n\t\t\tlogRedraw(`terminal width changed (${this.previousWidth} -> ${width})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Height changes normally need a full re-render to keep the visible viewport aligned,\n\t\t// but Termux changes height when the software keyboard shows or hides.\n\t\t// In that environment, a full redraw causes the entire history to replay on every toggle.\n\t\tif (heightChanged && !isTermuxSession()) {\n\t\t\tlogRedraw(`terminal height changed (${this.previousHeight} -> ${height})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Content shrunk below the working area and no overlays - re-render to clear empty rows\n\t\t// (overlays need the padding, so only do this when no overlays are active)\n\t\t// Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var\n\t\tif (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {\n\t\t\tlogRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Find first and last changed lines\n\t\tlet firstChanged = -1;\n\t\tlet lastChanged = -1;\n\t\tconst maxLines = Math.max(newLines.length, this.previousLines.length);\n\t\tfor (let i = 0; i < maxLines; i++) {\n\t\t\tconst oldLine = i < this.previousLines.length ? this.previousLines[i] : \"\";\n\t\t\tconst newLine = i < newLines.length ? newLines[i] : \"\";\n\n\t\t\tif (oldLine !== newLine) {\n\t\t\t\tif (firstChanged === -1) {\n\t\t\t\t\tfirstChanged = i;\n\t\t\t\t}\n\t\t\t\tlastChanged = i;\n\t\t\t}\n\t\t}\n\t\tconst appendedLines = newLines.length > this.previousLines.length;\n\t\tif (appendedLines) {\n\t\t\tif (firstChanged === -1) {\n\t\t\t\tfirstChanged = this.previousLines.length;\n\t\t\t}\n\t\t\tlastChanged = newLines.length - 1;\n\t\t}\n\t\tconst appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;\n\n\t\t// No changes - but still need to update hardware cursor position if it moved\n\t\tif (firstChanged === -1) {\n\t\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\t\t\tthis.previousViewportTop = prevViewportTop;\n\t\t\tthis.previousHeight = height;\n\t\t\treturn;\n\t\t}\n\n\t\t// All changes are in deleted lines (nothing to render, just clear)\n\t\tif (firstChanged >= newLines.length) {\n\t\t\tif (this.previousLines.length > newLines.length) {\n\t\t\t\tlet buffer = \"\\x1b[?2026h\";\n\t\t\t\t// Move to end of new content (clamp to 0 for empty content)\n\t\t\t\tconst targetRow = Math.max(0, newLines.length - 1);\n\t\t\t\tif (targetRow < prevViewportTop) {\n\t\t\t\t\tlogRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`);\n\t\t\t\t\tfullRender(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst lineDiff = computeLineDiff(targetRow);\n\t\t\t\tif (lineDiff > 0) buffer += `\\x1b[${lineDiff}B`;\n\t\t\t\telse if (lineDiff < 0) buffer += `\\x1b[${-lineDiff}A`;\n\t\t\t\tbuffer += \"\\r\";\n\t\t\t\t// Clear extra lines without scrolling\n\t\t\t\tconst extraLines = this.previousLines.length - newLines.length;\n\t\t\t\tif (extraLines > height) {\n\t\t\t\t\tlogRedraw(`extraLines > height (${extraLines} > ${height})`);\n\t\t\t\t\tfullRender(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (extraLines > 0) {\n\t\t\t\t\tbuffer += \"\\x1b[1B\";\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < extraLines; i++) {\n\t\t\t\t\tbuffer += \"\\r\\x1b[2K\";\n\t\t\t\t\tif (i < extraLines - 1) buffer += \"\\x1b[1B\";\n\t\t\t\t}\n\t\t\t\tif (extraLines > 0) {\n\t\t\t\t\tbuffer += `\\x1b[${extraLines}A`;\n\t\t\t\t}\n\t\t\t\tbuffer += \"\\x1b[?2026l\";\n\t\t\t\tthis.terminal.write(buffer);\n\t\t\t\tthis.cursorRow = targetRow;\n\t\t\t\tthis.hardwareCursorRow = targetRow;\n\t\t\t}\n\t\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\t\t\tthis.previousLines = newLines;\n\t\t\tthis.previousWidth = width;\n\t\t\tthis.previousHeight = height;\n\t\t\tthis.previousViewportTop = prevViewportTop;\n\t\t\treturn;\n\t\t}\n\n\t\t// Differential rendering can only touch what was actually visible.\n\t\t// If the first changed line is above the previous viewport, we need a full redraw.\n\t\tif (firstChanged < prevViewportTop) {\n\t\t\tlogRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Render from first changed line to end\n\t\t// Build buffer with all updates wrapped in synchronized output\n\t\tlet buffer = \"\\x1b[?2026h\"; // Begin synchronized output\n\t\tconst prevViewportBottom = prevViewportTop + height - 1;\n\t\tconst moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;\n\t\tif (moveTargetRow > prevViewportBottom) {\n\t\t\tconst currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));\n\t\t\tconst moveToBottom = height - 1 - currentScreenRow;\n\t\t\tif (moveToBottom > 0) {\n\t\t\t\tbuffer += `\\x1b[${moveToBottom}B`;\n\t\t\t}\n\t\t\tconst scroll = moveTargetRow - prevViewportBottom;\n\t\t\tbuffer += \"\\r\\n\".repeat(scroll);\n\t\t\tprevViewportTop += scroll;\n\t\t\tviewportTop += scroll;\n\t\t\thardwareCursorRow = moveTargetRow;\n\t\t}\n\n\t\t// Move cursor to first changed line (use hardwareCursorRow for actual position)\n\t\tconst lineDiff = computeLineDiff(moveTargetRow);\n\t\tif (lineDiff > 0) {\n\t\t\tbuffer += `\\x1b[${lineDiff}B`; // Move down\n\t\t} else if (lineDiff < 0) {\n\t\t\tbuffer += `\\x1b[${-lineDiff}A`; // Move up\n\t\t}\n\n\t\tbuffer += appendStart ? \"\\r\\n\" : \"\\r\"; // Move to column 0\n\n\t\t// Only render changed lines (firstChanged to lastChanged), not all lines to end\n\t\t// This reduces flicker when only a single line changes (e.g., spinner animation)\n\t\tconst renderEnd = Math.min(lastChanged, newLines.length - 1);\n\t\tfor (let i = firstChanged; i <= renderEnd; i++) {\n\t\t\tif (i > firstChanged) buffer += \"\\r\\n\";\n\t\t\tbuffer += \"\\x1b[2K\"; // Clear current line\n\t\t\tconst line = newLines[i];\n\t\t\tconst isImage = isImageLine(line);\n\t\t\tif (!isImage && visibleWidth(line) > width) {\n\t\t\t\t// Log all lines to crash file for debugging\n\t\t\t\tconst crashLogPath = path.join(os.homedir(), \".pi\", \"agent\", \"pi-crash.log\");\n\t\t\t\tconst crashData = [\n\t\t\t\t\t`Crash at ${new Date().toISOString()}`,\n\t\t\t\t\t`Terminal width: ${width}`,\n\t\t\t\t\t`Line ${i} visible width: ${visibleWidth(line)}`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"=== All rendered lines ===\",\n\t\t\t\t\t...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),\n\t\t\t\t\t\"\",\n\t\t\t\t].join(\"\\n\");\n\t\t\t\tfs.mkdirSync(path.dirname(crashLogPath), { recursive: true });\n\t\t\t\tfs.writeFileSync(crashLogPath, crashData);\n\n\t\t\t\t// Clean up terminal state before throwing\n\t\t\t\tthis.stop();\n\n\t\t\t\tconst errorMsg = [\n\t\t\t\t\t`Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"This is likely caused by a custom TUI component not truncating its output.\",\n\t\t\t\t\t\"Use visibleWidth() to measure and truncateToWidth() to truncate lines.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t`Debug log written to: ${crashLogPath}`,\n\t\t\t\t].join(\"\\n\");\n\t\t\t\tthrow new Error(errorMsg);\n\t\t\t}\n\t\t\tbuffer += line;\n\t\t}\n\n\t\t// Track where cursor ended up after rendering\n\t\tlet finalCursorRow = renderEnd;\n\n\t\t// If we had more lines before, clear them and move cursor back\n\t\tif (this.previousLines.length > newLines.length) {\n\t\t\t// Move to end of new content first if we stopped before it\n\t\t\tif (renderEnd < newLines.length - 1) {\n\t\t\t\tconst moveDown = newLines.length - 1 - renderEnd;\n\t\t\t\tbuffer += `\\x1b[${moveDown}B`;\n\t\t\t\tfinalCursorRow = newLines.length - 1;\n\t\t\t}\n\t\t\tconst extraLines = this.previousLines.length - newLines.length;\n\t\t\tfor (let i = newLines.length; i < this.previousLines.length; i++) {\n\t\t\t\tbuffer += \"\\r\\n\\x1b[2K\";\n\t\t\t}\n\t\t\t// Move cursor back to end of new content\n\t\t\tbuffer += `\\x1b[${extraLines}A`;\n\t\t}\n\n\t\tbuffer += \"\\x1b[?2026l\"; // End synchronized output\n\n\t\tif (process.env.PI_TUI_DEBUG === \"1\") {\n\t\t\tconst debugDir = \"/tmp/tui\";\n\t\t\tfs.mkdirSync(debugDir, { recursive: true });\n\t\t\tconst debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);\n\t\t\tconst debugData = [\n\t\t\t\t`firstChanged: ${firstChanged}`,\n\t\t\t\t`viewportTop: ${viewportTop}`,\n\t\t\t\t`cursorRow: ${this.cursorRow}`,\n\t\t\t\t`height: ${height}`,\n\t\t\t\t`lineDiff: ${lineDiff}`,\n\t\t\t\t`hardwareCursorRow: ${hardwareCursorRow}`,\n\t\t\t\t`renderEnd: ${renderEnd}`,\n\t\t\t\t`finalCursorRow: ${finalCursorRow}`,\n\t\t\t\t`cursorPos: ${JSON.stringify(cursorPos)}`,\n\t\t\t\t`newLines.length: ${newLines.length}`,\n\t\t\t\t`previousLines.length: ${this.previousLines.length}`,\n\t\t\t\t\"\",\n\t\t\t\t\"=== newLines ===\",\n\t\t\t\tJSON.stringify(newLines, null, 2),\n\t\t\t\t\"\",\n\t\t\t\t\"=== previousLines ===\",\n\t\t\t\tJSON.stringify(this.previousLines, null, 2),\n\t\t\t\t\"\",\n\t\t\t\t\"=== buffer ===\",\n\t\t\t\tJSON.stringify(buffer),\n\t\t\t].join(\"\\n\");\n\t\t\tfs.writeFileSync(debugPath, debugData);\n\t\t}\n\n\t\t// Write entire buffer at once\n\t\tthis.terminal.write(buffer);\n\n\t\t// Track cursor position for next render\n\t\t// cursorRow tracks end of content (for viewport calculation)\n\t\t// hardwareCursorRow tracks actual terminal cursor position (for movement)\n\t\tthis.cursorRow = Math.max(0, newLines.length - 1);\n\t\tthis.hardwareCursorRow = finalCursorRow;\n\t\t// Track terminal's working area (grows but doesn't shrink unless cleared)\n\t\tthis.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);\n\t\tthis.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);\n\n\t\t// Position hardware cursor for IME\n\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\n\t\tthis.previousLines = newLines;\n\t\tthis.previousWidth = width;\n\t\tthis.previousHeight = height;\n\t}\n\n\t/**\n\t * Position the hardware cursor for IME candidate window.\n\t * @param cursorPos The cursor position extracted from rendered output, or null\n\t * @param totalLines Total number of rendered lines\n\t */\n\tprivate positionHardwareCursor(cursorPos: { row: number; col: number } | null, totalLines: number): void {\n\t\tif (!cursorPos || totalLines <= 0) {\n\t\t\tthis.terminal.hideCursor();\n\t\t\treturn;\n\t\t}\n\n\t\t// Clamp cursor position to valid range\n\t\tconst targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));\n\t\tconst targetCol = Math.max(0, cursorPos.col);\n\n\t\t// Move cursor from current position to target\n\t\tconst rowDelta = targetRow - this.hardwareCursorRow;\n\t\tlet buffer = \"\";\n\t\tif (rowDelta > 0) {\n\t\t\tbuffer += `\\x1b[${rowDelta}B`; // Move down\n\t\t} else if (rowDelta < 0) {\n\t\t\tbuffer += `\\x1b[${-rowDelta}A`; // Move up\n\t\t}\n\t\t// Move to absolute column (1-indexed)\n\t\tbuffer += `\\x1b[${targetCol + 1}G`;\n\n\t\tif (buffer) {\n\t\t\tthis.terminal.write(buffer);\n\t\t}\n\n\t\tthis.hardwareCursorRow = targetRow;\n\t\tif (this.showHardwareCursor) {\n\t\t\tthis.terminal.showCursor();\n\t\t} else {\n\t\t\tthis.terminal.hideCursor();\n\t\t}\n\t}\n}\n"]}