@pencil-agent/nano-pencil 2.0.0-beta.2 → 2.0.0-beta.3

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 (179) hide show
  1. package/dist/build-meta.json +3 -3
  2. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-continuations.d.ts +17 -0
  3. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-continuations.js +60 -0
  4. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-stream-events.d.ts +19 -0
  5. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-stream-events.js +55 -0
  6. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-tool-results.d.ts +10 -0
  7. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-tool-results.js +137 -0
  8. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-tool-summaries.d.ts +22 -0
  9. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop-tool-summaries.js +64 -0
  10. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop.d.ts +26 -0
  11. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-loop.js +913 -0
  12. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-run-result.d.ts +9 -0
  13. package/dist/node_modules/@pencil-agent/agent-core/dist/agent-run-result.js +32 -0
  14. package/dist/node_modules/@pencil-agent/agent-core/dist/agent.d.ts +215 -0
  15. package/dist/node_modules/@pencil-agent/agent-core/dist/agent.js +522 -0
  16. package/dist/node_modules/@pencil-agent/agent-core/dist/errors.d.ts +62 -0
  17. package/dist/node_modules/@pencil-agent/agent-core/dist/errors.js +146 -0
  18. package/dist/node_modules/@pencil-agent/agent-core/dist/index.d.ts +14 -0
  19. package/dist/node_modules/@pencil-agent/agent-core/dist/index.js +19 -0
  20. package/dist/node_modules/@pencil-agent/agent-core/dist/proxy.d.ts +91 -0
  21. package/dist/node_modules/@pencil-agent/agent-core/dist/proxy.js +279 -0
  22. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-agent-loop.d.ts +15 -0
  23. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-agent-loop.js +625 -0
  24. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-streaming-tool-executor.d.ts +33 -0
  25. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-streaming-tool-executor.js +189 -0
  26. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-tool-orchestration.d.ts +35 -0
  27. package/dist/node_modules/@pencil-agent/agent-core/dist/structured-adaptive-tool-orchestration.js +319 -0
  28. package/dist/node_modules/@pencil-agent/agent-core/dist/types.d.ts +417 -0
  29. package/dist/node_modules/@pencil-agent/agent-core/dist/types.js +13 -0
  30. package/dist/node_modules/@pencil-agent/agent-core/package.json +28 -0
  31. package/dist/node_modules/@pencil-agent/ai/dist/api-registry.d.ts +27 -0
  32. package/dist/node_modules/@pencil-agent/ai/dist/api-registry.js +152 -0
  33. package/dist/node_modules/@pencil-agent/ai/dist/cli.d.ts +2 -0
  34. package/dist/node_modules/@pencil-agent/ai/dist/cli.js +121 -0
  35. package/dist/node_modules/@pencil-agent/ai/dist/config-path.d.ts +1 -0
  36. package/dist/node_modules/@pencil-agent/ai/dist/config-path.js +17 -0
  37. package/dist/node_modules/@pencil-agent/ai/dist/debug-logger.d.ts +94 -0
  38. package/dist/node_modules/@pencil-agent/ai/dist/debug-logger.js +218 -0
  39. package/dist/node_modules/@pencil-agent/ai/dist/env-api-keys.d.ts +8 -0
  40. package/dist/node_modules/@pencil-agent/ai/dist/env-api-keys.js +107 -0
  41. package/dist/node_modules/@pencil-agent/ai/dist/env.d.ts +7 -0
  42. package/dist/node_modules/@pencil-agent/ai/dist/env.js +7 -0
  43. package/dist/node_modules/@pencil-agent/ai/dist/events.d.ts +8 -0
  44. package/dist/node_modules/@pencil-agent/ai/dist/events.js +7 -0
  45. package/dist/node_modules/@pencil-agent/ai/dist/index.d.ts +27 -0
  46. package/dist/node_modules/@pencil-agent/ai/dist/index.js +20 -0
  47. package/dist/node_modules/@pencil-agent/ai/dist/json.d.ts +7 -0
  48. package/dist/node_modules/@pencil-agent/ai/dist/json.js +7 -0
  49. package/dist/node_modules/@pencil-agent/ai/dist/models.d.ts +31 -0
  50. package/dist/node_modules/@pencil-agent/ai/dist/models.generated.d.ts +15159 -0
  51. package/dist/node_modules/@pencil-agent/ai/dist/models.generated.js +14928 -0
  52. package/dist/node_modules/@pencil-agent/ai/dist/models.js +60 -0
  53. package/dist/node_modules/@pencil-agent/ai/dist/overflow.d.ts +7 -0
  54. package/dist/node_modules/@pencil-agent/ai/dist/overflow.js +7 -0
  55. package/dist/node_modules/@pencil-agent/ai/dist/providers/amazon-bedrock.d.ts +20 -0
  56. package/dist/node_modules/@pencil-agent/ai/dist/providers/amazon-bedrock.js +606 -0
  57. package/dist/node_modules/@pencil-agent/ai/dist/providers/anthropic.d.ts +38 -0
  58. package/dist/node_modules/@pencil-agent/ai/dist/providers/anthropic.js +737 -0
  59. package/dist/node_modules/@pencil-agent/ai/dist/providers/azure-openai-responses.d.ts +21 -0
  60. package/dist/node_modules/@pencil-agent/ai/dist/providers/azure-openai-responses.js +193 -0
  61. package/dist/node_modules/@pencil-agent/ai/dist/providers/github-copilot-headers.d.ts +13 -0
  62. package/dist/node_modules/@pencil-agent/ai/dist/providers/github-copilot-headers.js +34 -0
  63. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-gemini-cli.d.ts +79 -0
  64. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-gemini-cli.js +753 -0
  65. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-shared.d.ts +70 -0
  66. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-shared.js +311 -0
  67. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-vertex.d.ts +20 -0
  68. package/dist/node_modules/@pencil-agent/ai/dist/providers/google-vertex.js +380 -0
  69. package/dist/node_modules/@pencil-agent/ai/dist/providers/google.d.ts +18 -0
  70. package/dist/node_modules/@pencil-agent/ai/dist/providers/google.js +360 -0
  71. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-codex-responses.d.ts +8 -0
  72. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-codex-responses.js +704 -0
  73. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-completions.d.ts +20 -0
  74. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-completions.js +870 -0
  75. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-responses-shared.d.ts +22 -0
  76. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-responses-shared.js +432 -0
  77. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-responses.d.ts +19 -0
  78. package/dist/node_modules/@pencil-agent/ai/dist/providers/openai-responses.js +207 -0
  79. package/dist/node_modules/@pencil-agent/ai/dist/providers/register-builtins.d.ts +8 -0
  80. package/dist/node_modules/@pencil-agent/ai/dist/providers/register-builtins.js +86 -0
  81. package/dist/node_modules/@pencil-agent/ai/dist/providers/simple-options.d.ts +13 -0
  82. package/dist/node_modules/@pencil-agent/ai/dist/providers/simple-options.js +40 -0
  83. package/dist/node_modules/@pencil-agent/ai/dist/providers/transform-messages.d.ts +13 -0
  84. package/dist/node_modules/@pencil-agent/ai/dist/providers/transform-messages.js +175 -0
  85. package/dist/node_modules/@pencil-agent/ai/dist/registry.d.ts +8 -0
  86. package/dist/node_modules/@pencil-agent/ai/dist/registry.js +8 -0
  87. package/dist/node_modules/@pencil-agent/ai/dist/schema.d.ts +10 -0
  88. package/dist/node_modules/@pencil-agent/ai/dist/schema.js +9 -0
  89. package/dist/node_modules/@pencil-agent/ai/dist/stream.d.ts +25 -0
  90. package/dist/node_modules/@pencil-agent/ai/dist/stream.js +324 -0
  91. package/dist/node_modules/@pencil-agent/ai/dist/types.d.ts +306 -0
  92. package/dist/node_modules/@pencil-agent/ai/dist/types.js +7 -0
  93. package/dist/node_modules/@pencil-agent/ai/dist/utils/event-stream-types.d.ts +12 -0
  94. package/dist/node_modules/@pencil-agent/ai/dist/utils/event-stream-types.js +7 -0
  95. package/dist/node_modules/@pencil-agent/ai/dist/utils/event-stream.d.ts +31 -0
  96. package/dist/node_modules/@pencil-agent/ai/dist/utils/event-stream.js +98 -0
  97. package/dist/node_modules/@pencil-agent/ai/dist/utils/http-proxy.d.ts +13 -0
  98. package/dist/node_modules/@pencil-agent/ai/dist/utils/http-proxy.js +20 -0
  99. package/dist/node_modules/@pencil-agent/ai/dist/utils/json-parse.d.ts +14 -0
  100. package/dist/node_modules/@pencil-agent/ai/dist/utils/json-parse.js +34 -0
  101. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/anthropic.d.ts +22 -0
  102. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/anthropic.js +109 -0
  103. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/decode-credential.d.ts +12 -0
  104. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/decode-credential.js +25 -0
  105. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/github-copilot.d.ts +35 -0
  106. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/github-copilot.js +286 -0
  107. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/google-antigravity.d.ts +31 -0
  108. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/google-antigravity.js +378 -0
  109. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/google-gemini-cli.d.ts +31 -0
  110. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/google-gemini-cli.js +483 -0
  111. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/index.d.ts +60 -0
  112. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/index.js +131 -0
  113. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/openai-codex.d.ts +39 -0
  114. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/openai-codex.js +385 -0
  115. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/pkce.d.ts +18 -0
  116. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/pkce.js +36 -0
  117. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/types.d.ts +52 -0
  118. package/dist/node_modules/@pencil-agent/ai/dist/utils/oauth/types.js +7 -0
  119. package/dist/node_modules/@pencil-agent/ai/dist/utils/overflow.d.ts +57 -0
  120. package/dist/node_modules/@pencil-agent/ai/dist/utils/overflow.js +120 -0
  121. package/dist/node_modules/@pencil-agent/ai/dist/utils/sanitize-unicode.d.ts +16 -0
  122. package/dist/node_modules/@pencil-agent/ai/dist/utils/sanitize-unicode.js +20 -0
  123. package/dist/node_modules/@pencil-agent/ai/dist/utils/typebox-helpers.d.ts +22 -0
  124. package/dist/node_modules/@pencil-agent/ai/dist/utils/typebox-helpers.js +26 -0
  125. package/dist/node_modules/@pencil-agent/ai/dist/utils/validation.d.ts +23 -0
  126. package/dist/node_modules/@pencil-agent/ai/dist/utils/validation.js +78 -0
  127. package/dist/node_modules/@pencil-agent/ai/package.json +94 -0
  128. package/dist/node_modules/@pencil-agent/tui/dist/autocomplete.d.ts +62 -0
  129. package/dist/node_modules/@pencil-agent/tui/dist/autocomplete.js +624 -0
  130. package/dist/node_modules/@pencil-agent/tui/dist/components/box.d.ts +27 -0
  131. package/dist/node_modules/@pencil-agent/tui/dist/components/box.js +109 -0
  132. package/dist/node_modules/@pencil-agent/tui/dist/components/cancellable-loader.d.ts +27 -0
  133. package/dist/node_modules/@pencil-agent/tui/dist/components/cancellable-loader.js +40 -0
  134. package/dist/node_modules/@pencil-agent/tui/dist/components/editor.d.ts +218 -0
  135. package/dist/node_modules/@pencil-agent/tui/dist/components/editor.js +1697 -0
  136. package/dist/node_modules/@pencil-agent/tui/dist/components/image.d.ts +33 -0
  137. package/dist/node_modules/@pencil-agent/tui/dist/components/image.js +74 -0
  138. package/dist/node_modules/@pencil-agent/tui/dist/components/input.d.ts +42 -0
  139. package/dist/node_modules/@pencil-agent/tui/dist/components/input.js +438 -0
  140. package/dist/node_modules/@pencil-agent/tui/dist/components/loader.d.ts +26 -0
  141. package/dist/node_modules/@pencil-agent/tui/dist/components/loader.js +54 -0
  142. package/dist/node_modules/@pencil-agent/tui/dist/components/markdown.d.ts +100 -0
  143. package/dist/node_modules/@pencil-agent/tui/dist/components/markdown.js +634 -0
  144. package/dist/node_modules/@pencil-agent/tui/dist/components/select-list.d.ts +37 -0
  145. package/dist/node_modules/@pencil-agent/tui/dist/components/select-list.js +157 -0
  146. package/dist/node_modules/@pencil-agent/tui/dist/components/settings-list.d.ts +55 -0
  147. package/dist/node_modules/@pencil-agent/tui/dist/components/settings-list.js +190 -0
  148. package/dist/node_modules/@pencil-agent/tui/dist/components/spacer.d.ts +17 -0
  149. package/dist/node_modules/@pencil-agent/tui/dist/components/spacer.js +28 -0
  150. package/dist/node_modules/@pencil-agent/tui/dist/components/text.d.ts +24 -0
  151. package/dist/node_modules/@pencil-agent/tui/dist/components/text.js +94 -0
  152. package/dist/node_modules/@pencil-agent/tui/dist/components/truncated-text.d.ts +18 -0
  153. package/dist/node_modules/@pencil-agent/tui/dist/components/truncated-text.js +56 -0
  154. package/dist/node_modules/@pencil-agent/tui/dist/editor-component.d.ts +51 -0
  155. package/dist/node_modules/@pencil-agent/tui/dist/editor-component.js +7 -0
  156. package/dist/node_modules/@pencil-agent/tui/dist/fuzzy.d.ts +32 -0
  157. package/dist/node_modules/@pencil-agent/tui/dist/fuzzy.js +152 -0
  158. package/dist/node_modules/@pencil-agent/tui/dist/index.d.ts +28 -0
  159. package/dist/node_modules/@pencil-agent/tui/dist/index.js +37 -0
  160. package/dist/node_modules/@pencil-agent/tui/dist/keybindings.d.ts +44 -0
  161. package/dist/node_modules/@pencil-agent/tui/dist/keybindings.js +119 -0
  162. package/dist/node_modules/@pencil-agent/tui/dist/keys.d.ts +149 -0
  163. package/dist/node_modules/@pencil-agent/tui/dist/keys.js +948 -0
  164. package/dist/node_modules/@pencil-agent/tui/dist/kill-ring.d.ts +33 -0
  165. package/dist/node_modules/@pencil-agent/tui/dist/kill-ring.js +49 -0
  166. package/dist/node_modules/@pencil-agent/tui/dist/stdin-buffer.d.ts +38 -0
  167. package/dist/node_modules/@pencil-agent/tui/dist/stdin-buffer.js +307 -0
  168. package/dist/node_modules/@pencil-agent/tui/dist/terminal-image.d.ts +73 -0
  169. package/dist/node_modules/@pencil-agent/tui/dist/terminal-image.js +287 -0
  170. package/dist/node_modules/@pencil-agent/tui/dist/terminal.d.ts +86 -0
  171. package/dist/node_modules/@pencil-agent/tui/dist/terminal.js +266 -0
  172. package/dist/node_modules/@pencil-agent/tui/dist/tui.d.ts +219 -0
  173. package/dist/node_modules/@pencil-agent/tui/dist/tui.js +1001 -0
  174. package/dist/node_modules/@pencil-agent/tui/dist/undo-stack.d.ts +22 -0
  175. package/dist/node_modules/@pencil-agent/tui/dist/undo-stack.js +30 -0
  176. package/dist/node_modules/@pencil-agent/tui/dist/utils.d.ts +83 -0
  177. package/dist/node_modules/@pencil-agent/tui/dist/utils.js +811 -0
  178. package/dist/node_modules/@pencil-agent/tui/package.json +37 -0
  179. package/package.json +3 -2
@@ -0,0 +1,1001 @@
1
+ /**
2
+ * Minimal TUI implementation with differential rendering
3
+ */
4
+ /**
5
+ * [WHO]: Component, Focusable, isFocusable, CURSOR_MARKER, visibleWidth
6
+ * [FROM]: Depends on node:fs, node:os, node:path, ./keys.js, ./terminal-image.js
7
+ * [TO]: Consumed by core/lib/tui/src/index.ts
8
+ * [HERE]: core/lib/tui/src/tui.ts -
9
+ */
10
+ import * as fs from "node:fs";
11
+ import * as os from "node:os";
12
+ import * as path from "node:path";
13
+ import { isKeyRelease, matchesKey } from "./keys.js";
14
+ import { getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
15
+ import { extractSegments, sliceByColumn, sliceWithWidth, visibleWidth } from "./utils.js";
16
+ /** Type guard to check if a component implements Focusable */
17
+ export function isFocusable(component) {
18
+ return component !== null && "focused" in component;
19
+ }
20
+ function shouldUseSynchronizedOutput() {
21
+ if (process.env.NANOPENCIL_SYNC_OUTPUT === "0") {
22
+ return false;
23
+ }
24
+ if (process.env.NANOPENCIL_SYNC_OUTPUT === "1") {
25
+ return true;
26
+ }
27
+ const termProgram = process.env.TERM_PROGRAM?.toLowerCase() || "";
28
+ // GPU-renderer / "AI terminal" emulators have shown intermittent delayed
29
+ // or hidden frame presentation when we wrap diffs in DEC mode 2026
30
+ // (BSU/ESU). They appear to hold the frame buffer until they detect a
31
+ // terminator they recognize, which manifests as "typed input not visible
32
+ // until the model finishes streaming." Until each one's 2026 path is
33
+ // verified, prefer plain writes.
34
+ const SYNC_OUTPUT_BLOCKLIST = new Set([
35
+ "warpterminal", // Warp
36
+ "waveterm", // Wave Terminal
37
+ ]);
38
+ return !SYNC_OUTPUT_BLOCKLIST.has(termProgram);
39
+ }
40
+ /**
41
+ * Cursor position marker - APC (Application Program Command) sequence.
42
+ * This is a zero-width escape sequence that terminals ignore.
43
+ * Components emit this at the cursor position when focused.
44
+ * TUI finds and strips this marker, then positions the hardware cursor there.
45
+ */
46
+ export const CURSOR_MARKER = "\x1b_pi:c\x07";
47
+ export { visibleWidth };
48
+ /** Parse a SizeValue into absolute value given a reference size */
49
+ function parseSizeValue(value, referenceSize) {
50
+ if (value === undefined)
51
+ return undefined;
52
+ if (typeof value === "number")
53
+ return value;
54
+ // Parse percentage string like "50%"
55
+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
56
+ if (match) {
57
+ return Math.floor((referenceSize * parseFloat(match[1])) / 100);
58
+ }
59
+ return undefined;
60
+ }
61
+ /**
62
+ * Container - a component that contains other components
63
+ */
64
+ export class Container {
65
+ children = [];
66
+ addChild(component) {
67
+ this.children.push(component);
68
+ }
69
+ removeChild(component) {
70
+ const index = this.children.indexOf(component);
71
+ if (index !== -1) {
72
+ this.children.splice(index, 1);
73
+ }
74
+ }
75
+ clear() {
76
+ this.children = [];
77
+ }
78
+ invalidate() {
79
+ for (const child of this.children) {
80
+ child.invalidate?.();
81
+ }
82
+ }
83
+ render(width) {
84
+ const lines = [];
85
+ for (const child of this.children) {
86
+ lines.push(...child.render(width));
87
+ }
88
+ return lines;
89
+ }
90
+ }
91
+ /**
92
+ * TUI - Main class for managing terminal UI with differential rendering
93
+ */
94
+ export class TUI extends Container {
95
+ terminal;
96
+ previousLines = [];
97
+ previousWidth = 0;
98
+ focusedComponent = null;
99
+ inputListeners = new Set();
100
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
101
+ onDebug;
102
+ renderRequested = false;
103
+ renderWaiters = [];
104
+ cursorRow = 0; // Logical cursor row (end of rendered content)
105
+ hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
106
+ inputBuffer = ""; // Buffer for parsing terminal responses
107
+ cellSizeQueryPending = false;
108
+ showHardwareCursor = process.env.NANOPENCIL_HARDWARE_CURSOR === "1";
109
+ clearOnShrink = process.env.NANOPENCIL_CLEAR_ON_SHRINK === "1"; // Clear empty rows when content shrinks (default: off)
110
+ maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)
111
+ previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves
112
+ fullRedrawCount = 0;
113
+ stopped = false;
114
+ synchronizedOutputEnabled = shouldUseSynchronizedOutput();
115
+ // Overlay stack for modal components rendered on top of base content
116
+ overlayStack = [];
117
+ constructor(terminal, showHardwareCursor) {
118
+ super();
119
+ this.terminal = terminal;
120
+ if (showHardwareCursor !== undefined) {
121
+ this.showHardwareCursor = showHardwareCursor;
122
+ }
123
+ }
124
+ get fullRedraws() {
125
+ return this.fullRedrawCount;
126
+ }
127
+ getShowHardwareCursor() {
128
+ return this.showHardwareCursor;
129
+ }
130
+ setShowHardwareCursor(enabled) {
131
+ if (this.showHardwareCursor === enabled)
132
+ return;
133
+ this.showHardwareCursor = enabled;
134
+ if (!enabled) {
135
+ this.terminal.hideCursor();
136
+ }
137
+ this.requestRender();
138
+ }
139
+ getClearOnShrink() {
140
+ return this.clearOnShrink;
141
+ }
142
+ /**
143
+ * Set whether to trigger full re-render when content shrinks.
144
+ * When true (default), empty rows are cleared when content shrinks.
145
+ * When false, empty rows remain (reduces redraws on slower terminals).
146
+ */
147
+ setClearOnShrink(enabled) {
148
+ this.clearOnShrink = enabled;
149
+ }
150
+ wrapRenderBuffer(buffer) {
151
+ if (!this.synchronizedOutputEnabled) {
152
+ return buffer;
153
+ }
154
+ return `\x1b[?2026h${buffer}\x1b[?2026l`;
155
+ }
156
+ setFocus(component) {
157
+ // Clear focused flag on old component
158
+ if (isFocusable(this.focusedComponent)) {
159
+ this.focusedComponent.focused = false;
160
+ }
161
+ this.focusedComponent = component;
162
+ // Set focused flag on new component
163
+ if (isFocusable(component)) {
164
+ component.focused = true;
165
+ }
166
+ }
167
+ /**
168
+ * Show an overlay component with configurable positioning and sizing.
169
+ * Returns a handle to control the overlay's visibility.
170
+ */
171
+ showOverlay(component, options) {
172
+ const entry = { component, options, preFocus: this.focusedComponent, hidden: false };
173
+ this.overlayStack.push(entry);
174
+ // Only focus if overlay is actually visible
175
+ if (this.isOverlayVisible(entry)) {
176
+ this.setFocus(component);
177
+ }
178
+ this.terminal.hideCursor();
179
+ this.requestRender();
180
+ // Return handle for controlling this overlay
181
+ return {
182
+ hide: () => {
183
+ const index = this.overlayStack.indexOf(entry);
184
+ if (index !== -1) {
185
+ this.overlayStack.splice(index, 1);
186
+ // Restore focus if this overlay had focus
187
+ if (this.focusedComponent === component) {
188
+ const topVisible = this.getTopmostVisibleOverlay();
189
+ this.setFocus(topVisible?.component ?? entry.preFocus);
190
+ }
191
+ if (this.overlayStack.length === 0)
192
+ this.terminal.hideCursor();
193
+ this.requestRender();
194
+ }
195
+ },
196
+ setHidden: (hidden) => {
197
+ if (entry.hidden === hidden)
198
+ return;
199
+ entry.hidden = hidden;
200
+ // Update focus when hiding/showing
201
+ if (hidden) {
202
+ // If this overlay had focus, move focus to next visible or preFocus
203
+ if (this.focusedComponent === component) {
204
+ const topVisible = this.getTopmostVisibleOverlay();
205
+ this.setFocus(topVisible?.component ?? entry.preFocus);
206
+ }
207
+ }
208
+ else {
209
+ // Restore focus to this overlay when showing (if it's actually visible)
210
+ if (this.isOverlayVisible(entry)) {
211
+ this.setFocus(component);
212
+ }
213
+ }
214
+ this.requestRender();
215
+ },
216
+ isHidden: () => entry.hidden,
217
+ };
218
+ }
219
+ /** Hide the topmost overlay and restore previous focus. */
220
+ hideOverlay() {
221
+ const overlay = this.overlayStack.pop();
222
+ if (!overlay)
223
+ return;
224
+ // Find topmost visible overlay, or fall back to preFocus
225
+ const topVisible = this.getTopmostVisibleOverlay();
226
+ this.setFocus(topVisible?.component ?? overlay.preFocus);
227
+ if (this.overlayStack.length === 0)
228
+ this.terminal.hideCursor();
229
+ this.requestRender();
230
+ }
231
+ /** Check if there are any visible overlays */
232
+ hasOverlay() {
233
+ return this.overlayStack.some((o) => this.isOverlayVisible(o));
234
+ }
235
+ /** Check if an overlay entry is currently visible */
236
+ isOverlayVisible(entry) {
237
+ if (entry.hidden)
238
+ return false;
239
+ if (entry.options?.visible) {
240
+ return entry.options.visible(this.terminal.columns, this.terminal.rows);
241
+ }
242
+ return true;
243
+ }
244
+ /** Find the topmost visible overlay, if any */
245
+ getTopmostVisibleOverlay() {
246
+ for (let i = this.overlayStack.length - 1; i >= 0; i--) {
247
+ if (this.isOverlayVisible(this.overlayStack[i])) {
248
+ return this.overlayStack[i];
249
+ }
250
+ }
251
+ return undefined;
252
+ }
253
+ invalidate() {
254
+ super.invalidate();
255
+ for (const overlay of this.overlayStack)
256
+ overlay.component.invalidate?.();
257
+ }
258
+ start() {
259
+ this.stopped = false;
260
+ this.terminal.start((data) => this.handleInput(data), () => this.requestRender());
261
+ this.terminal.hideCursor();
262
+ this.queryCellSize();
263
+ this.requestRender();
264
+ }
265
+ addInputListener(listener) {
266
+ this.inputListeners.add(listener);
267
+ return () => {
268
+ this.inputListeners.delete(listener);
269
+ };
270
+ }
271
+ removeInputListener(listener) {
272
+ this.inputListeners.delete(listener);
273
+ }
274
+ queryCellSize() {
275
+ // Only query if terminal supports images (cell size is only used for image rendering)
276
+ if (!getCapabilities().images) {
277
+ return;
278
+ }
279
+ // Query terminal for cell size in pixels: CSI 16 t
280
+ // Response format: CSI 6 ; height ; width t
281
+ this.cellSizeQueryPending = true;
282
+ this.terminal.write("\x1b[16t");
283
+ }
284
+ stop() {
285
+ this.stopped = true;
286
+ // Move cursor to the end of the content to prevent overwriting/artifacts on exit
287
+ if (this.previousLines.length > 0) {
288
+ const targetRow = this.previousLines.length; // Line after the last content
289
+ const lineDiff = targetRow - this.hardwareCursorRow;
290
+ if (lineDiff > 0) {
291
+ this.terminal.write(`\x1b[${lineDiff}B`);
292
+ }
293
+ else if (lineDiff < 0) {
294
+ this.terminal.write(`\x1b[${-lineDiff}A`);
295
+ }
296
+ this.terminal.write("\r\n");
297
+ }
298
+ this.terminal.showCursor();
299
+ this.terminal.stop();
300
+ }
301
+ requestRender(force = false) {
302
+ if (force) {
303
+ this.previousLines = [];
304
+ this.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
305
+ this.cursorRow = 0;
306
+ this.hardwareCursorRow = 0;
307
+ this.maxLinesRendered = 0;
308
+ this.previousViewportTop = 0;
309
+ }
310
+ if (this.renderRequested)
311
+ return;
312
+ this.renderRequested = true;
313
+ process.nextTick(() => {
314
+ const waiters = this.renderWaiters.splice(0);
315
+ this.renderRequested = false;
316
+ try {
317
+ this.doRender();
318
+ }
319
+ finally {
320
+ for (const resolve of waiters) {
321
+ resolve();
322
+ }
323
+ }
324
+ });
325
+ }
326
+ async awaitRender() {
327
+ if (!this.renderRequested) {
328
+ return;
329
+ }
330
+ await new Promise((resolve) => {
331
+ this.renderWaiters.push(resolve);
332
+ });
333
+ }
334
+ handleInput(data) {
335
+ if (this.inputListeners.size > 0) {
336
+ let current = data;
337
+ for (const listener of this.inputListeners) {
338
+ const result = listener(current);
339
+ if (result?.consume) {
340
+ return;
341
+ }
342
+ if (result?.data !== undefined) {
343
+ current = result.data;
344
+ }
345
+ }
346
+ if (current.length === 0) {
347
+ return;
348
+ }
349
+ data = current;
350
+ }
351
+ // If we're waiting for cell size response, buffer input and parse
352
+ if (this.cellSizeQueryPending) {
353
+ this.inputBuffer += data;
354
+ const filtered = this.parseCellSizeResponse();
355
+ if (filtered.length === 0)
356
+ return;
357
+ data = filtered;
358
+ }
359
+ // Global debug key handler (Shift+Ctrl+D)
360
+ if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
361
+ this.onDebug();
362
+ return;
363
+ }
364
+ // If focused component is an overlay, verify it's still visible
365
+ // (visibility can change due to terminal resize or visible() callback)
366
+ const focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);
367
+ if (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {
368
+ // Focused overlay is no longer visible, redirect to topmost visible overlay
369
+ const topVisible = this.getTopmostVisibleOverlay();
370
+ if (topVisible) {
371
+ this.setFocus(topVisible.component);
372
+ }
373
+ else {
374
+ // No visible overlays, restore to preFocus
375
+ this.setFocus(focusedOverlay.preFocus);
376
+ }
377
+ }
378
+ // Pass input to focused component (including Ctrl+C)
379
+ // The focused component can decide how to handle Ctrl+C
380
+ if (this.focusedComponent?.handleInput) {
381
+ // Filter out key release events unless component opts in
382
+ if (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {
383
+ return;
384
+ }
385
+ this.focusedComponent.handleInput(data);
386
+ this.requestRender();
387
+ }
388
+ }
389
+ parseCellSizeResponse() {
390
+ // Response format: ESC [ 6 ; height ; width t
391
+ // Match the response pattern
392
+ const responsePattern = /\x1b\[6;(\d+);(\d+)t/;
393
+ const match = this.inputBuffer.match(responsePattern);
394
+ if (match) {
395
+ const heightPx = parseInt(match[1], 10);
396
+ const widthPx = parseInt(match[2], 10);
397
+ if (heightPx > 0 && widthPx > 0) {
398
+ setCellDimensions({ widthPx, heightPx });
399
+ // Invalidate all components so images re-render with correct dimensions
400
+ this.invalidate();
401
+ this.requestRender();
402
+ }
403
+ // Remove the response from buffer
404
+ this.inputBuffer = this.inputBuffer.replace(responsePattern, "");
405
+ this.cellSizeQueryPending = false;
406
+ }
407
+ // Check if we have a partial cell size response starting (wait for more data)
408
+ // Patterns that could be incomplete cell size response: \x1b, \x1b[, \x1b[6, \x1b[6;...(no t yet)
409
+ const partialCellSizePattern = /\x1b(\[6?;?[\d;]*)?$/;
410
+ if (partialCellSizePattern.test(this.inputBuffer)) {
411
+ // Check if it's actually a complete different escape sequence (ends with a letter)
412
+ // Cell size response ends with 't', Kitty keyboard ends with 'u', arrows end with A-D, etc.
413
+ const lastChar = this.inputBuffer[this.inputBuffer.length - 1];
414
+ if (!/[a-zA-Z~]/.test(lastChar)) {
415
+ // Doesn't end with a terminator, might be incomplete - wait for more
416
+ return "";
417
+ }
418
+ }
419
+ // No cell size response found, return buffered data as user input
420
+ const result = this.inputBuffer;
421
+ this.inputBuffer = "";
422
+ this.cellSizeQueryPending = false; // Give up waiting
423
+ return result;
424
+ }
425
+ /**
426
+ * Resolve overlay layout from options.
427
+ * Returns { width, row, col, maxHeight } for rendering.
428
+ */
429
+ resolveOverlayLayout(options, overlayHeight, termWidth, termHeight) {
430
+ const opt = options ?? {};
431
+ // Parse margin (clamp to non-negative)
432
+ const margin = typeof opt.margin === "number"
433
+ ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
434
+ : (opt.margin ?? {});
435
+ const marginTop = Math.max(0, margin.top ?? 0);
436
+ const marginRight = Math.max(0, margin.right ?? 0);
437
+ const marginBottom = Math.max(0, margin.bottom ?? 0);
438
+ const marginLeft = Math.max(0, margin.left ?? 0);
439
+ // Available space after margins
440
+ const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
441
+ const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
442
+ // === Resolve width ===
443
+ let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
444
+ // Apply minWidth
445
+ if (opt.minWidth !== undefined) {
446
+ width = Math.max(width, opt.minWidth);
447
+ }
448
+ // Clamp to available space
449
+ width = Math.max(1, Math.min(width, availWidth));
450
+ // === Resolve maxHeight ===
451
+ let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
452
+ // Clamp to available space
453
+ if (maxHeight !== undefined) {
454
+ maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
455
+ }
456
+ // Effective overlay height (may be clamped by maxHeight)
457
+ const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
458
+ // === Resolve position ===
459
+ let row;
460
+ let col;
461
+ if (opt.row !== undefined) {
462
+ if (typeof opt.row === "string") {
463
+ // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
464
+ const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
465
+ if (match) {
466
+ const maxRow = Math.max(0, availHeight - effectiveHeight);
467
+ const percent = parseFloat(match[1]) / 100;
468
+ row = marginTop + Math.floor(maxRow * percent);
469
+ }
470
+ else {
471
+ // Invalid format, fall back to center
472
+ row = this.resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
473
+ }
474
+ }
475
+ else {
476
+ // Absolute row position
477
+ row = opt.row;
478
+ }
479
+ }
480
+ else {
481
+ // Anchor-based (default: center)
482
+ const anchor = opt.anchor ?? "center";
483
+ row = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
484
+ }
485
+ if (opt.col !== undefined) {
486
+ if (typeof opt.col === "string") {
487
+ // Percentage: 0% = left, 100% = right (overlay stays within bounds)
488
+ const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
489
+ if (match) {
490
+ const maxCol = Math.max(0, availWidth - width);
491
+ const percent = parseFloat(match[1]) / 100;
492
+ col = marginLeft + Math.floor(maxCol * percent);
493
+ }
494
+ else {
495
+ // Invalid format, fall back to center
496
+ col = this.resolveAnchorCol("center", width, availWidth, marginLeft);
497
+ }
498
+ }
499
+ else {
500
+ // Absolute column position
501
+ col = opt.col;
502
+ }
503
+ }
504
+ else {
505
+ // Anchor-based (default: center)
506
+ const anchor = opt.anchor ?? "center";
507
+ col = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);
508
+ }
509
+ // Apply offsets
510
+ if (opt.offsetY !== undefined)
511
+ row += opt.offsetY;
512
+ if (opt.offsetX !== undefined)
513
+ col += opt.offsetX;
514
+ // Clamp to terminal bounds (respecting margins)
515
+ row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
516
+ col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
517
+ return { width, row, col, maxHeight };
518
+ }
519
+ resolveAnchorRow(anchor, height, availHeight, marginTop) {
520
+ switch (anchor) {
521
+ case "top-left":
522
+ case "top-center":
523
+ case "top-right":
524
+ return marginTop;
525
+ case "bottom-left":
526
+ case "bottom-center":
527
+ case "bottom-right":
528
+ return marginTop + availHeight - height;
529
+ case "left-center":
530
+ case "center":
531
+ case "right-center":
532
+ return marginTop + Math.floor((availHeight - height) / 2);
533
+ }
534
+ }
535
+ resolveAnchorCol(anchor, width, availWidth, marginLeft) {
536
+ switch (anchor) {
537
+ case "top-left":
538
+ case "left-center":
539
+ case "bottom-left":
540
+ return marginLeft;
541
+ case "top-right":
542
+ case "right-center":
543
+ case "bottom-right":
544
+ return marginLeft + availWidth - width;
545
+ case "top-center":
546
+ case "center":
547
+ case "bottom-center":
548
+ return marginLeft + Math.floor((availWidth - width) / 2);
549
+ }
550
+ }
551
+ /** Composite all overlays into content lines (in stack order, later = on top). */
552
+ compositeOverlays(lines, termWidth, termHeight) {
553
+ if (this.overlayStack.length === 0)
554
+ return lines;
555
+ const result = [...lines];
556
+ // Pre-render all visible overlays and calculate positions
557
+ const rendered = [];
558
+ let minLinesNeeded = result.length;
559
+ for (const entry of this.overlayStack) {
560
+ // Skip invisible overlays (hidden or visible() returns false)
561
+ if (!this.isOverlayVisible(entry))
562
+ continue;
563
+ const { component, options } = entry;
564
+ // Get layout with height=0 first to determine width and maxHeight
565
+ // (width and maxHeight don't depend on overlay height)
566
+ const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
567
+ // Render component at calculated width
568
+ let overlayLines = component.render(width);
569
+ // Apply maxHeight if specified
570
+ if (maxHeight !== undefined && overlayLines.length > maxHeight) {
571
+ overlayLines = overlayLines.slice(0, maxHeight);
572
+ }
573
+ // Get final row/col with actual overlay height
574
+ const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
575
+ rendered.push({ overlayLines, row, col, w: width });
576
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
577
+ }
578
+ // Ensure result covers the terminal working area to keep overlay positioning stable across resizes.
579
+ // maxLinesRendered can exceed current content length after a shrink; pad to keep viewportStart consistent.
580
+ const workingHeight = Math.max(this.maxLinesRendered, minLinesNeeded);
581
+ // Extend result with empty lines if content is too short for overlay placement or working area
582
+ while (result.length < workingHeight) {
583
+ result.push("");
584
+ }
585
+ const viewportStart = Math.max(0, workingHeight - termHeight);
586
+ // Track which lines were modified for final verification
587
+ const modifiedLines = new Set();
588
+ // Composite each overlay
589
+ for (const { overlayLines, row, col, w } of rendered) {
590
+ for (let i = 0; i < overlayLines.length; i++) {
591
+ const idx = viewportStart + row + i;
592
+ if (idx >= 0 && idx < result.length) {
593
+ // Defensive: truncate overlay line to declared width before compositing
594
+ // (components should already respect width, but this ensures it)
595
+ const truncatedOverlayLine = visibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];
596
+ result[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
597
+ modifiedLines.add(idx);
598
+ }
599
+ }
600
+ }
601
+ // Final verification: ensure no composited line exceeds terminal width
602
+ // This is a belt-and-suspenders safeguard - compositeLineAt should already
603
+ // guarantee this, but we verify here to prevent crashes from any edge cases
604
+ // Only check lines that were actually modified (optimization)
605
+ for (const idx of modifiedLines) {
606
+ const lineWidth = visibleWidth(result[idx]);
607
+ if (lineWidth > termWidth) {
608
+ result[idx] = sliceByColumn(result[idx], 0, termWidth, true);
609
+ }
610
+ }
611
+ return result;
612
+ }
613
+ static SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07";
614
+ applyLineResets(lines) {
615
+ const reset = TUI.SEGMENT_RESET;
616
+ for (let i = 0; i < lines.length; i++) {
617
+ const line = lines[i];
618
+ if (!isImageLine(line)) {
619
+ lines[i] = line + reset;
620
+ }
621
+ }
622
+ return lines;
623
+ }
624
+ /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
625
+ compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
626
+ if (isImageLine(baseLine))
627
+ return baseLine;
628
+ // Single pass through baseLine extracts both before and after segments
629
+ const afterStart = startCol + overlayWidth;
630
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
631
+ // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
632
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
633
+ // Pad segments to target widths
634
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
635
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
636
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
637
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
638
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
639
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
640
+ // Compose result
641
+ const r = TUI.SEGMENT_RESET;
642
+ const result = base.before +
643
+ " ".repeat(beforePad) +
644
+ r +
645
+ overlay.text +
646
+ " ".repeat(overlayPad) +
647
+ r +
648
+ base.after +
649
+ " ".repeat(afterPad);
650
+ // CRITICAL: Always verify and truncate to terminal width.
651
+ // This is the final safeguard against width overflow which would crash the TUI.
652
+ // Width tracking can drift from actual visible width due to:
653
+ // - Complex ANSI/OSC sequences (hyperlinks, colors)
654
+ // - Wide characters at segment boundaries
655
+ // - Edge cases in segment extraction
656
+ const resultWidth = visibleWidth(result);
657
+ if (resultWidth <= totalWidth) {
658
+ return result;
659
+ }
660
+ // Truncate with strict=true to ensure we don't exceed totalWidth
661
+ return sliceByColumn(result, 0, totalWidth, true);
662
+ }
663
+ /**
664
+ * Find and extract cursor position from rendered lines.
665
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
666
+ * Only scans the bottom terminal height lines (visible viewport).
667
+ * @param lines - Rendered lines to search
668
+ * @param height - Terminal height (visible viewport size)
669
+ * @returns Cursor position { row, col } or null if no marker found
670
+ */
671
+ extractCursorPosition(lines, height) {
672
+ // Only scan the bottom `height` lines (visible viewport)
673
+ const viewportTop = Math.max(0, lines.length - height);
674
+ for (let row = lines.length - 1; row >= viewportTop; row--) {
675
+ const line = lines[row];
676
+ const markerIndex = line.indexOf(CURSOR_MARKER);
677
+ if (markerIndex !== -1) {
678
+ // Calculate visual column (width of text before marker)
679
+ const beforeMarker = line.slice(0, markerIndex);
680
+ const col = visibleWidth(beforeMarker);
681
+ // Strip marker from the line
682
+ lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
683
+ return { row, col };
684
+ }
685
+ }
686
+ return null;
687
+ }
688
+ doRender() {
689
+ if (this.stopped)
690
+ return;
691
+ const width = this.terminal.columns;
692
+ const height = this.terminal.rows;
693
+ let viewportTop = Math.max(0, this.maxLinesRendered - height);
694
+ let prevViewportTop = this.previousViewportTop;
695
+ let hardwareCursorRow = this.hardwareCursorRow;
696
+ const computeLineDiff = (targetRow) => {
697
+ const currentScreenRow = hardwareCursorRow - prevViewportTop;
698
+ const targetScreenRow = targetRow - viewportTop;
699
+ return targetScreenRow - currentScreenRow;
700
+ };
701
+ // Render all components to get new lines
702
+ let newLines = this.render(width);
703
+ // Composite overlays into the rendered lines (before differential compare)
704
+ if (this.overlayStack.length > 0) {
705
+ newLines = this.compositeOverlays(newLines, width, height);
706
+ }
707
+ // Extract cursor position before applying line resets (marker must be found first)
708
+ const cursorPos = this.extractCursorPosition(newLines, height);
709
+ newLines = this.applyLineResets(newLines);
710
+ // Width changed - need full re-render (line wrapping changes)
711
+ const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
712
+ // Helper to clear scrollback and viewport and render all new lines
713
+ const fullRender = (clear) => {
714
+ this.fullRedrawCount += 1;
715
+ let buffer = "";
716
+ if (clear)
717
+ buffer += "\x1b[3J\x1b[2J\x1b[H"; // Clear scrollback, screen, and home
718
+ for (let i = 0; i < newLines.length; i++) {
719
+ if (i > 0)
720
+ buffer += "\r\n";
721
+ buffer += newLines[i];
722
+ }
723
+ this.terminal.write(this.wrapRenderBuffer(buffer));
724
+ this.cursorRow = Math.max(0, newLines.length - 1);
725
+ this.hardwareCursorRow = this.cursorRow;
726
+ // Reset max lines when clearing, otherwise track growth
727
+ if (clear) {
728
+ this.maxLinesRendered = newLines.length;
729
+ }
730
+ else {
731
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
732
+ }
733
+ this.previousViewportTop = Math.max(0, this.maxLinesRendered - height);
734
+ this.positionHardwareCursor(cursorPos, newLines.length);
735
+ this.previousLines = newLines;
736
+ this.previousWidth = width;
737
+ };
738
+ const debugRedraw = process.env.NANOPENCIL_DEBUG_REDRAW === "1";
739
+ const logRedraw = (reason) => {
740
+ if (!debugRedraw)
741
+ return;
742
+ const logPath = path.join(os.homedir(), ".nanopencil", "agent", "nanopencil-debug.log");
743
+ const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
744
+ fs.appendFileSync(logPath, msg);
745
+ };
746
+ // First render - just output everything without clearing (assumes clean screen)
747
+ if (this.previousLines.length === 0 && !widthChanged) {
748
+ logRedraw("first render");
749
+ fullRender(false);
750
+ return;
751
+ }
752
+ // Width changed - full re-render (line wrapping changes)
753
+ if (widthChanged) {
754
+ logRedraw(`width changed (${this.previousWidth} -> ${width})`);
755
+ fullRender(true);
756
+ return;
757
+ }
758
+ // Content shrunk below the working area and no overlays - re-render to clear empty rows
759
+ // (overlays need the padding, so only do this when no overlays are active)
760
+ // Configurable via setClearOnShrink() or NANOPENCIL_CLEAR_ON_SHRINK=0 env var
761
+ if (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {
762
+ logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);
763
+ fullRender(true);
764
+ return;
765
+ }
766
+ // Find first and last changed lines
767
+ let firstChanged = -1;
768
+ let lastChanged = -1;
769
+ const maxLines = Math.max(newLines.length, this.previousLines.length);
770
+ for (let i = 0; i < maxLines; i++) {
771
+ const oldLine = i < this.previousLines.length ? this.previousLines[i] : "";
772
+ const newLine = i < newLines.length ? newLines[i] : "";
773
+ if (oldLine !== newLine) {
774
+ if (firstChanged === -1) {
775
+ firstChanged = i;
776
+ }
777
+ lastChanged = i;
778
+ }
779
+ }
780
+ const appendedLines = newLines.length > this.previousLines.length;
781
+ if (appendedLines) {
782
+ if (firstChanged === -1) {
783
+ firstChanged = this.previousLines.length;
784
+ }
785
+ lastChanged = newLines.length - 1;
786
+ }
787
+ const appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;
788
+ // No changes - but still need to update hardware cursor position if it moved
789
+ if (firstChanged === -1) {
790
+ this.positionHardwareCursor(cursorPos, newLines.length);
791
+ this.previousViewportTop = Math.max(0, this.maxLinesRendered - height);
792
+ return;
793
+ }
794
+ // All changes are in deleted lines (nothing to render, just clear)
795
+ if (firstChanged >= newLines.length) {
796
+ if (this.previousLines.length > newLines.length) {
797
+ let buffer = "";
798
+ // Move to end of new content (clamp to 0 for empty content)
799
+ const targetRow = Math.max(0, newLines.length - 1);
800
+ const lineDiff = computeLineDiff(targetRow);
801
+ if (lineDiff > 0)
802
+ buffer += `\x1b[${lineDiff}B`;
803
+ else if (lineDiff < 0)
804
+ buffer += `\x1b[${-lineDiff}A`;
805
+ buffer += "\r";
806
+ // Clear extra lines without scrolling
807
+ const extraLines = this.previousLines.length - newLines.length;
808
+ if (extraLines > height) {
809
+ logRedraw(`extraLines > height (${extraLines} > ${height})`);
810
+ fullRender(true);
811
+ return;
812
+ }
813
+ if (extraLines > 0) {
814
+ buffer += "\x1b[1B";
815
+ }
816
+ for (let i = 0; i < extraLines; i++) {
817
+ buffer += "\r\x1b[2K";
818
+ if (i < extraLines - 1)
819
+ buffer += "\x1b[1B";
820
+ }
821
+ if (extraLines > 0) {
822
+ buffer += `\x1b[${extraLines}A`;
823
+ }
824
+ this.terminal.write(this.wrapRenderBuffer(buffer));
825
+ this.cursorRow = targetRow;
826
+ this.hardwareCursorRow = targetRow;
827
+ }
828
+ this.positionHardwareCursor(cursorPos, newLines.length);
829
+ this.previousLines = newLines;
830
+ this.previousWidth = width;
831
+ this.previousViewportTop = Math.max(0, this.maxLinesRendered - height);
832
+ return;
833
+ }
834
+ // Check if firstChanged is above what was previously visible
835
+ // Use previousLines.length (not maxLinesRendered) to avoid false positives after content shrinks
836
+ const previousContentViewportTop = Math.max(0, this.previousLines.length - height);
837
+ if (firstChanged < previousContentViewportTop) {
838
+ // First change is above previous viewport - need full re-render
839
+ logRedraw(`firstChanged < viewportTop (${firstChanged} < ${previousContentViewportTop})`);
840
+ fullRender(true);
841
+ return;
842
+ }
843
+ // Render from first changed line to end
844
+ // Build buffer with all updates wrapped in synchronized output
845
+ let buffer = "";
846
+ const prevViewportBottom = prevViewportTop + height - 1;
847
+ const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
848
+ if (moveTargetRow > prevViewportBottom) {
849
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
850
+ const moveToBottom = height - 1 - currentScreenRow;
851
+ if (moveToBottom > 0) {
852
+ buffer += `\x1b[${moveToBottom}B`;
853
+ }
854
+ const scroll = moveTargetRow - prevViewportBottom;
855
+ buffer += "\r\n".repeat(scroll);
856
+ prevViewportTop += scroll;
857
+ viewportTop += scroll;
858
+ hardwareCursorRow = moveTargetRow;
859
+ }
860
+ // Move cursor to first changed line (use hardwareCursorRow for actual position)
861
+ const lineDiff = computeLineDiff(moveTargetRow);
862
+ if (lineDiff > 0) {
863
+ buffer += `\x1b[${lineDiff}B`; // Move down
864
+ }
865
+ else if (lineDiff < 0) {
866
+ buffer += `\x1b[${-lineDiff}A`; // Move up
867
+ }
868
+ buffer += appendStart ? "\r\n" : "\r"; // Move to column 0
869
+ // Only render changed lines (firstChanged to lastChanged), not all lines to end
870
+ // This reduces flicker when only a single line changes (e.g., spinner animation)
871
+ const renderEnd = Math.min(lastChanged, newLines.length - 1);
872
+ for (let i = firstChanged; i <= renderEnd; i++) {
873
+ if (i > firstChanged)
874
+ buffer += "\r\n";
875
+ buffer += "\x1b[2K"; // Clear current line
876
+ const line = newLines[i];
877
+ const isImage = isImageLine(line);
878
+ if (!isImage && visibleWidth(line) > width) {
879
+ // Log all lines to crash file for debugging
880
+ const crashLogPath = path.join(os.homedir(), ".nanopencil", "agent", "nanopencil-crash.log");
881
+ const crashData = [
882
+ `Crash at ${new Date().toISOString()}`,
883
+ `Terminal width: ${width}`,
884
+ `Line ${i} visible width: ${visibleWidth(line)}`,
885
+ "",
886
+ "=== All rendered lines ===",
887
+ ...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),
888
+ "",
889
+ ].join("\n");
890
+ fs.mkdirSync(path.dirname(crashLogPath), { recursive: true });
891
+ fs.writeFileSync(crashLogPath, crashData);
892
+ // Clean up terminal state before throwing
893
+ this.stop();
894
+ const errorMsg = [
895
+ `Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,
896
+ "",
897
+ "This is likely caused by a custom TUI component not truncating its output.",
898
+ "Use visibleWidth() to measure and truncateToWidth() to truncate lines.",
899
+ "",
900
+ `Debug log written to: ${crashLogPath}`,
901
+ ].join("\n");
902
+ throw new Error(errorMsg);
903
+ }
904
+ buffer += line;
905
+ }
906
+ // Track where cursor ended up after rendering
907
+ let finalCursorRow = renderEnd;
908
+ // If we had more lines before, clear them and move cursor back
909
+ if (this.previousLines.length > newLines.length) {
910
+ // Move to end of new content first if we stopped before it
911
+ if (renderEnd < newLines.length - 1) {
912
+ const moveDown = newLines.length - 1 - renderEnd;
913
+ buffer += `\x1b[${moveDown}B`;
914
+ finalCursorRow = newLines.length - 1;
915
+ }
916
+ const extraLines = this.previousLines.length - newLines.length;
917
+ for (let i = newLines.length; i < this.previousLines.length; i++) {
918
+ buffer += "\r\n\x1b[2K";
919
+ }
920
+ // Move cursor back to end of new content
921
+ buffer += `\x1b[${extraLines}A`;
922
+ }
923
+ if (process.env.NANOPENCIL_TUI_DEBUG === "1") {
924
+ const debugDir = "/tmp/tui";
925
+ fs.mkdirSync(debugDir, { recursive: true });
926
+ const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
927
+ const debugData = [
928
+ `firstChanged: ${firstChanged}`,
929
+ `viewportTop: ${viewportTop}`,
930
+ `cursorRow: ${this.cursorRow}`,
931
+ `height: ${height}`,
932
+ `lineDiff: ${lineDiff}`,
933
+ `hardwareCursorRow: ${hardwareCursorRow}`,
934
+ `renderEnd: ${renderEnd}`,
935
+ `finalCursorRow: ${finalCursorRow}`,
936
+ `cursorPos: ${JSON.stringify(cursorPos)}`,
937
+ `newLines.length: ${newLines.length}`,
938
+ `previousLines.length: ${this.previousLines.length}`,
939
+ "",
940
+ "=== newLines ===",
941
+ JSON.stringify(newLines, null, 2),
942
+ "",
943
+ "=== previousLines ===",
944
+ JSON.stringify(this.previousLines, null, 2),
945
+ "",
946
+ "=== buffer ===",
947
+ JSON.stringify(buffer),
948
+ ].join("\n");
949
+ fs.writeFileSync(debugPath, debugData);
950
+ }
951
+ // Write entire buffer at once
952
+ this.terminal.write(this.wrapRenderBuffer(buffer));
953
+ // Track cursor position for next render
954
+ // cursorRow tracks end of content (for viewport calculation)
955
+ // hardwareCursorRow tracks actual terminal cursor position (for movement)
956
+ this.cursorRow = Math.max(0, newLines.length - 1);
957
+ this.hardwareCursorRow = finalCursorRow;
958
+ // Track terminal's working area (grows but doesn't shrink unless cleared)
959
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
960
+ this.previousViewportTop = Math.max(0, this.maxLinesRendered - height);
961
+ // Position hardware cursor for IME
962
+ this.positionHardwareCursor(cursorPos, newLines.length);
963
+ this.previousLines = newLines;
964
+ this.previousWidth = width;
965
+ }
966
+ /**
967
+ * Position the hardware cursor for IME candidate window.
968
+ * @param cursorPos The cursor position extracted from rendered output, or null
969
+ * @param totalLines Total number of rendered lines
970
+ */
971
+ positionHardwareCursor(cursorPos, totalLines) {
972
+ if (!cursorPos || totalLines <= 0) {
973
+ this.terminal.hideCursor();
974
+ return;
975
+ }
976
+ // Clamp cursor position to valid range
977
+ const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
978
+ const targetCol = Math.max(0, cursorPos.col);
979
+ // Move cursor from current position to target
980
+ const rowDelta = targetRow - this.hardwareCursorRow;
981
+ let buffer = "";
982
+ if (rowDelta > 0) {
983
+ buffer += `\x1b[${rowDelta}B`; // Move down
984
+ }
985
+ else if (rowDelta < 0) {
986
+ buffer += `\x1b[${-rowDelta}A`; // Move up
987
+ }
988
+ // Move to absolute column (1-indexed)
989
+ buffer += `\x1b[${targetCol + 1}G`;
990
+ if (buffer) {
991
+ this.terminal.write(buffer);
992
+ }
993
+ this.hardwareCursorRow = targetRow;
994
+ if (this.showHardwareCursor) {
995
+ this.terminal.showCursor();
996
+ }
997
+ else {
998
+ this.terminal.hideCursor();
999
+ }
1000
+ }
1001
+ }