@bastani/atomic 0.8.26-alpha.5 → 0.8.26-alpha.7

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 (264) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +7 -4
  3. package/dist/builtin/intercom/CHANGELOG.md +12 -0
  4. package/dist/builtin/intercom/package.json +2 -2
  5. package/dist/builtin/mcp/CHANGELOG.md +12 -0
  6. package/dist/builtin/mcp/package.json +3 -3
  7. package/dist/builtin/subagents/CHANGELOG.md +12 -0
  8. package/dist/builtin/subagents/agents/codebase-online-researcher.md +9 -9
  9. package/dist/builtin/subagents/agents/debugger.md +6 -6
  10. package/dist/builtin/subagents/package.json +4 -4
  11. package/dist/builtin/subagents/prompts/parallel-handoff-plan.md +1 -1
  12. package/dist/builtin/subagents/skills/browser/EXAMPLES.md +151 -0
  13. package/dist/builtin/subagents/skills/browser/LICENSE.txt +21 -0
  14. package/dist/builtin/subagents/skills/browser/REFERENCE.md +451 -0
  15. package/dist/builtin/subagents/skills/browser/SKILL.md +170 -0
  16. package/dist/builtin/subagents/skills/subagent/SKILL.md +4 -4
  17. package/dist/builtin/subagents/src/runs/background/subagent-runner.ts +48 -10
  18. package/dist/builtin/subagents/src/runs/foreground/execution.ts +30 -9
  19. package/dist/builtin/subagents/src/runs/shared/final-drain.ts +34 -0
  20. package/dist/builtin/subagents/src/runs/shared/model-fallback.ts +416 -7
  21. package/dist/builtin/web-access/CHANGELOG.md +12 -0
  22. package/dist/builtin/web-access/package.json +2 -2
  23. package/dist/builtin/workflows/CHANGELOG.md +17 -0
  24. package/dist/builtin/workflows/builtin/deep-research-codebase.ts +4 -1
  25. package/dist/builtin/workflows/builtin/goal.ts +127 -99
  26. package/dist/builtin/workflows/builtin/open-claude-design.ts +224 -147
  27. package/dist/builtin/workflows/builtin/ralph.ts +160 -197
  28. package/dist/builtin/workflows/package.json +2 -2
  29. package/dist/builtin/workflows/skills/research-codebase/SKILL.md +1 -1
  30. package/dist/builtin/workflows/src/extension/index.ts +10 -2
  31. package/dist/builtin/workflows/src/extension/runtime.ts +35 -3
  32. package/dist/builtin/workflows/src/runs/background/status.ts +52 -6
  33. package/dist/builtin/workflows/src/runs/foreground/executor.ts +441 -15
  34. package/dist/builtin/workflows/src/runs/foreground/stage-runner.ts +69 -8
  35. package/dist/builtin/workflows/src/runs/shared/model-fallback.ts +402 -8
  36. package/dist/builtin/workflows/src/shared/persistence-restore.ts +182 -6
  37. package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +76 -6
  38. package/dist/builtin/workflows/src/shared/stage-prompt.ts +33 -2
  39. package/dist/builtin/workflows/src/shared/store-types.ts +31 -0
  40. package/dist/builtin/workflows/src/shared/store.ts +99 -11
  41. package/dist/builtin/workflows/src/shared/workflow-failures.ts +758 -132
  42. package/dist/builtin/workflows/src/tui/stage-chat-view.ts +9 -0
  43. package/dist/core/agent-session.d.ts +28 -1
  44. package/dist/core/agent-session.d.ts.map +1 -1
  45. package/dist/core/agent-session.js +110 -28
  46. package/dist/core/agent-session.js.map +1 -1
  47. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  48. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  49. package/dist/core/compaction/branch-summarization.js +6 -3
  50. package/dist/core/compaction/branch-summarization.js.map +1 -1
  51. package/dist/core/compaction/compaction.d.ts.map +1 -1
  52. package/dist/core/compaction/compaction.js +23 -10
  53. package/dist/core/compaction/compaction.js.map +1 -1
  54. package/dist/core/compaction/context-compaction.d.ts +61 -0
  55. package/dist/core/compaction/context-compaction.d.ts.map +1 -0
  56. package/dist/core/compaction/context-compaction.js +602 -0
  57. package/dist/core/compaction/context-compaction.js.map +1 -0
  58. package/dist/core/compaction/index.d.ts +1 -0
  59. package/dist/core/compaction/index.d.ts.map +1 -1
  60. package/dist/core/compaction/index.js +1 -0
  61. package/dist/core/compaction/index.js.map +1 -1
  62. package/dist/core/index.d.ts +1 -1
  63. package/dist/core/index.d.ts.map +1 -1
  64. package/dist/core/index.js.map +1 -1
  65. package/dist/core/session-manager.d.ts +41 -1
  66. package/dist/core/session-manager.d.ts.map +1 -1
  67. package/dist/core/session-manager.js +146 -7
  68. package/dist/core/session-manager.js.map +1 -1
  69. package/dist/core/slash-commands.d.ts.map +1 -1
  70. package/dist/core/slash-commands.js +1 -0
  71. package/dist/core/slash-commands.js.map +1 -1
  72. package/dist/core/tools/ask-user-question/tool/format-answer.d.ts +5 -5
  73. package/dist/core/tools/ask-user-question/tool/format-answer.d.ts.map +1 -1
  74. package/dist/core/tools/ask-user-question/tool/format-answer.js +5 -5
  75. package/dist/core/tools/ask-user-question/tool/format-answer.js.map +1 -1
  76. package/dist/core/tools/ask-user-question/tool/response-envelope.d.ts +16 -3
  77. package/dist/core/tools/ask-user-question/tool/response-envelope.d.ts.map +1 -1
  78. package/dist/core/tools/ask-user-question/tool/response-envelope.js +21 -3
  79. package/dist/core/tools/ask-user-question/tool/response-envelope.js.map +1 -1
  80. package/dist/index.d.ts +3 -3
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +2 -2
  83. package/dist/index.js.map +1 -1
  84. package/dist/modes/index.d.ts +1 -1
  85. package/dist/modes/index.d.ts.map +1 -1
  86. package/dist/modes/index.js.map +1 -1
  87. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  88. package/dist/modes/interactive/components/chat-session-host.js +17 -0
  89. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  90. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  91. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  92. package/dist/modes/interactive/interactive-mode.js +74 -0
  93. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  94. package/dist/modes/rpc/rpc-client.d.ts +12 -7
  95. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  96. package/dist/modes/rpc/rpc-client.js +8 -1
  97. package/dist/modes/rpc/rpc-client.js.map +1 -1
  98. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  99. package/dist/modes/rpc/rpc-mode.js +4 -0
  100. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  101. package/dist/modes/rpc/rpc-types.d.ts +13 -2
  102. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  103. package/dist/modes/rpc/rpc-types.js.map +1 -1
  104. package/docs/compaction.md +42 -23
  105. package/docs/custom-provider.md +11 -9
  106. package/docs/extensions.md +35 -35
  107. package/docs/index.md +1 -8
  108. package/docs/json.md +14 -11
  109. package/docs/packages.md +2 -0
  110. package/docs/providers.md +4 -1
  111. package/docs/quickstart.md +5 -12
  112. package/docs/rpc.md +44 -8
  113. package/docs/sdk.md +1 -8
  114. package/docs/session-format.md +25 -12
  115. package/docs/sessions.md +2 -1
  116. package/docs/skills.md +1 -15
  117. package/docs/termux.md +9 -10
  118. package/docs/themes.md +2 -2
  119. package/docs/tmux.md +3 -3
  120. package/docs/tui.md +19 -32
  121. package/docs/usage.md +2 -0
  122. package/docs/workflows.md +44 -2
  123. package/package.json +4 -12
  124. package/dist/builtin/subagents/skills/browser-use/SKILL.md +0 -234
  125. package/dist/builtin/subagents/skills/browser-use/references/cdp-python.md +0 -76
  126. package/dist/builtin/subagents/skills/browser-use/references/multi-session.md +0 -92
  127. package/node_modules/@earendil-works/pi-tui/README.md +0 -779
  128. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.d.ts +0 -54
  129. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.d.ts.map +0 -1
  130. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +0 -632
  131. package/node_modules/@earendil-works/pi-tui/dist/autocomplete.js.map +0 -1
  132. package/node_modules/@earendil-works/pi-tui/dist/components/box.d.ts +0 -22
  133. package/node_modules/@earendil-works/pi-tui/dist/components/box.d.ts.map +0 -1
  134. package/node_modules/@earendil-works/pi-tui/dist/components/box.js +0 -104
  135. package/node_modules/@earendil-works/pi-tui/dist/components/box.js.map +0 -1
  136. package/node_modules/@earendil-works/pi-tui/dist/components/cancellable-loader.d.ts +0 -22
  137. package/node_modules/@earendil-works/pi-tui/dist/components/cancellable-loader.d.ts.map +0 -1
  138. package/node_modules/@earendil-works/pi-tui/dist/components/cancellable-loader.js +0 -35
  139. package/node_modules/@earendil-works/pi-tui/dist/components/cancellable-loader.js.map +0 -1
  140. package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts +0 -249
  141. package/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts.map +0 -1
  142. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js +0 -1857
  143. package/node_modules/@earendil-works/pi-tui/dist/components/editor.js.map +0 -1
  144. package/node_modules/@earendil-works/pi-tui/dist/components/image.d.ts +0 -28
  145. package/node_modules/@earendil-works/pi-tui/dist/components/image.d.ts.map +0 -1
  146. package/node_modules/@earendil-works/pi-tui/dist/components/image.js +0 -89
  147. package/node_modules/@earendil-works/pi-tui/dist/components/image.js.map +0 -1
  148. package/node_modules/@earendil-works/pi-tui/dist/components/input.d.ts +0 -37
  149. package/node_modules/@earendil-works/pi-tui/dist/components/input.d.ts.map +0 -1
  150. package/node_modules/@earendil-works/pi-tui/dist/components/input.js +0 -378
  151. package/node_modules/@earendil-works/pi-tui/dist/components/input.js.map +0 -1
  152. package/node_modules/@earendil-works/pi-tui/dist/components/loader.d.ts +0 -31
  153. package/node_modules/@earendil-works/pi-tui/dist/components/loader.d.ts.map +0 -1
  154. package/node_modules/@earendil-works/pi-tui/dist/components/loader.js +0 -69
  155. package/node_modules/@earendil-works/pi-tui/dist/components/loader.js.map +0 -1
  156. package/node_modules/@earendil-works/pi-tui/dist/components/markdown.d.ts +0 -96
  157. package/node_modules/@earendil-works/pi-tui/dist/components/markdown.d.ts.map +0 -1
  158. package/node_modules/@earendil-works/pi-tui/dist/components/markdown.js +0 -644
  159. package/node_modules/@earendil-works/pi-tui/dist/components/markdown.js.map +0 -1
  160. package/node_modules/@earendil-works/pi-tui/dist/components/select-list.d.ts +0 -50
  161. package/node_modules/@earendil-works/pi-tui/dist/components/select-list.d.ts.map +0 -1
  162. package/node_modules/@earendil-works/pi-tui/dist/components/select-list.js +0 -159
  163. package/node_modules/@earendil-works/pi-tui/dist/components/select-list.js.map +0 -1
  164. package/node_modules/@earendil-works/pi-tui/dist/components/settings-list.d.ts +0 -50
  165. package/node_modules/@earendil-works/pi-tui/dist/components/settings-list.d.ts.map +0 -1
  166. package/node_modules/@earendil-works/pi-tui/dist/components/settings-list.js +0 -185
  167. package/node_modules/@earendil-works/pi-tui/dist/components/settings-list.js.map +0 -1
  168. package/node_modules/@earendil-works/pi-tui/dist/components/spacer.d.ts +0 -12
  169. package/node_modules/@earendil-works/pi-tui/dist/components/spacer.d.ts.map +0 -1
  170. package/node_modules/@earendil-works/pi-tui/dist/components/spacer.js +0 -23
  171. package/node_modules/@earendil-works/pi-tui/dist/components/spacer.js.map +0 -1
  172. package/node_modules/@earendil-works/pi-tui/dist/components/text.d.ts +0 -19
  173. package/node_modules/@earendil-works/pi-tui/dist/components/text.d.ts.map +0 -1
  174. package/node_modules/@earendil-works/pi-tui/dist/components/text.js +0 -89
  175. package/node_modules/@earendil-works/pi-tui/dist/components/text.js.map +0 -1
  176. package/node_modules/@earendil-works/pi-tui/dist/components/truncated-text.d.ts +0 -13
  177. package/node_modules/@earendil-works/pi-tui/dist/components/truncated-text.d.ts.map +0 -1
  178. package/node_modules/@earendil-works/pi-tui/dist/components/truncated-text.js +0 -51
  179. package/node_modules/@earendil-works/pi-tui/dist/components/truncated-text.js.map +0 -1
  180. package/node_modules/@earendil-works/pi-tui/dist/editor-component.d.ts +0 -39
  181. package/node_modules/@earendil-works/pi-tui/dist/editor-component.d.ts.map +0 -1
  182. package/node_modules/@earendil-works/pi-tui/dist/editor-component.js +0 -2
  183. package/node_modules/@earendil-works/pi-tui/dist/editor-component.js.map +0 -1
  184. package/node_modules/@earendil-works/pi-tui/dist/fuzzy.d.ts +0 -16
  185. package/node_modules/@earendil-works/pi-tui/dist/fuzzy.d.ts.map +0 -1
  186. package/node_modules/@earendil-works/pi-tui/dist/fuzzy.js +0 -110
  187. package/node_modules/@earendil-works/pi-tui/dist/fuzzy.js.map +0 -1
  188. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts +0 -23
  189. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts.map +0 -1
  190. package/node_modules/@earendil-works/pi-tui/dist/index.js +0 -32
  191. package/node_modules/@earendil-works/pi-tui/dist/index.js.map +0 -1
  192. package/node_modules/@earendil-works/pi-tui/dist/keybindings.d.ts +0 -193
  193. package/node_modules/@earendil-works/pi-tui/dist/keybindings.d.ts.map +0 -1
  194. package/node_modules/@earendil-works/pi-tui/dist/keybindings.js +0 -174
  195. package/node_modules/@earendil-works/pi-tui/dist/keybindings.js.map +0 -1
  196. package/node_modules/@earendil-works/pi-tui/dist/keys.d.ts +0 -184
  197. package/node_modules/@earendil-works/pi-tui/dist/keys.d.ts.map +0 -1
  198. package/node_modules/@earendil-works/pi-tui/dist/keys.js +0 -1173
  199. package/node_modules/@earendil-works/pi-tui/dist/keys.js.map +0 -1
  200. package/node_modules/@earendil-works/pi-tui/dist/kill-ring.d.ts +0 -28
  201. package/node_modules/@earendil-works/pi-tui/dist/kill-ring.d.ts.map +0 -1
  202. package/node_modules/@earendil-works/pi-tui/dist/kill-ring.js +0 -44
  203. package/node_modules/@earendil-works/pi-tui/dist/kill-ring.js.map +0 -1
  204. package/node_modules/@earendil-works/pi-tui/dist/native-modifiers.d.ts +0 -3
  205. package/node_modules/@earendil-works/pi-tui/dist/native-modifiers.d.ts.map +0 -1
  206. package/node_modules/@earendil-works/pi-tui/dist/native-modifiers.js +0 -53
  207. package/node_modules/@earendil-works/pi-tui/dist/native-modifiers.js.map +0 -1
  208. package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts +0 -50
  209. package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts.map +0 -1
  210. package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +0 -361
  211. package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js.map +0 -1
  212. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.d.ts +0 -90
  213. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.d.ts.map +0 -1
  214. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.js +0 -366
  215. package/node_modules/@earendil-works/pi-tui/dist/terminal-image.js.map +0 -1
  216. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +0 -113
  217. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +0 -1
  218. package/node_modules/@earendil-works/pi-tui/dist/terminal.js +0 -472
  219. package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +0 -1
  220. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +0 -227
  221. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts.map +0 -1
  222. package/node_modules/@earendil-works/pi-tui/dist/tui.js +0 -1106
  223. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +0 -1
  224. package/node_modules/@earendil-works/pi-tui/dist/undo-stack.d.ts +0 -17
  225. package/node_modules/@earendil-works/pi-tui/dist/undo-stack.d.ts.map +0 -1
  226. package/node_modules/@earendil-works/pi-tui/dist/undo-stack.js +0 -25
  227. package/node_modules/@earendil-works/pi-tui/dist/undo-stack.js.map +0 -1
  228. package/node_modules/@earendil-works/pi-tui/dist/utils.d.ts +0 -84
  229. package/node_modules/@earendil-works/pi-tui/dist/utils.d.ts.map +0 -1
  230. package/node_modules/@earendil-works/pi-tui/dist/utils.js +0 -1029
  231. package/node_modules/@earendil-works/pi-tui/dist/utils.js.map +0 -1
  232. package/node_modules/@earendil-works/pi-tui/dist/word-navigation.d.ts +0 -25
  233. package/node_modules/@earendil-works/pi-tui/dist/word-navigation.d.ts.map +0 -1
  234. package/node_modules/@earendil-works/pi-tui/dist/word-navigation.js +0 -96
  235. package/node_modules/@earendil-works/pi-tui/dist/word-navigation.js.map +0 -1
  236. package/node_modules/@earendil-works/pi-tui/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
  237. package/node_modules/@earendil-works/pi-tui/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
  238. package/node_modules/@earendil-works/pi-tui/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  239. package/node_modules/@earendil-works/pi-tui/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
  240. package/node_modules/@earendil-works/pi-tui/package.json +0 -47
  241. package/node_modules/get-east-asian-width/index.d.ts +0 -60
  242. package/node_modules/get-east-asian-width/index.js +0 -30
  243. package/node_modules/get-east-asian-width/license +0 -9
  244. package/node_modules/get-east-asian-width/lookup-data.js +0 -21
  245. package/node_modules/get-east-asian-width/lookup.js +0 -138
  246. package/node_modules/get-east-asian-width/package.json +0 -71
  247. package/node_modules/get-east-asian-width/readme.md +0 -65
  248. package/node_modules/get-east-asian-width/utilities.js +0 -24
  249. package/node_modules/marked/LICENSE.md +0 -44
  250. package/node_modules/marked/README.md +0 -106
  251. package/node_modules/marked/bin/main.js +0 -282
  252. package/node_modules/marked/bin/marked.js +0 -15
  253. package/node_modules/marked/lib/marked.cjs +0 -2211
  254. package/node_modules/marked/lib/marked.cjs.map +0 -7
  255. package/node_modules/marked/lib/marked.d.cts +0 -728
  256. package/node_modules/marked/lib/marked.d.ts +0 -728
  257. package/node_modules/marked/lib/marked.esm.js +0 -2189
  258. package/node_modules/marked/lib/marked.esm.js.map +0 -7
  259. package/node_modules/marked/lib/marked.umd.js +0 -2213
  260. package/node_modules/marked/lib/marked.umd.js.map +0 -7
  261. package/node_modules/marked/man/marked.1 +0 -111
  262. package/node_modules/marked/man/marked.1.md +0 -92
  263. package/node_modules/marked/marked.min.js +0 -69
  264. package/node_modules/marked/package.json +0 -111
@@ -1,1106 +0,0 @@
1
- /**
2
- * Minimal TUI implementation with differential rendering
3
- */
4
- import * as fs from "node:fs";
5
- import * as os from "node:os";
6
- import * as path from "node:path";
7
- import { performance } from "node:perf_hooks";
8
- import { isKeyRelease, matchesKey } from "./keys.js";
9
- import { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
10
- import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth } from "./utils.js";
11
- const KITTY_SEQUENCE_PREFIX = "\x1b_G";
12
- function extractKittyImageIds(line) {
13
- const sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);
14
- if (sequenceStart === -1)
15
- return [];
16
- const paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;
17
- const paramsEnd = line.indexOf(";", paramsStart);
18
- if (paramsEnd === -1)
19
- return [];
20
- const params = line.slice(paramsStart, paramsEnd);
21
- for (const param of params.split(",")) {
22
- const [key, value] = param.split("=", 2);
23
- if (key !== "i" || value === undefined)
24
- continue;
25
- const id = Number(value);
26
- if (Number.isInteger(id) && id > 0 && id <= 0xffffffff) {
27
- return [id];
28
- }
29
- }
30
- return [];
31
- }
32
- /** Type guard to check if a component implements Focusable */
33
- export function isFocusable(component) {
34
- return component !== null && "focused" in component;
35
- }
36
- /**
37
- * Cursor position marker - APC (Application Program Command) sequence.
38
- * This is a zero-width escape sequence that terminals ignore.
39
- * Components emit this at the cursor position when focused.
40
- * TUI finds and strips this marker, then positions the hardware cursor there.
41
- */
42
- export const CURSOR_MARKER = "\x1b_pi:c\x07";
43
- export { visibleWidth };
44
- /** Parse a SizeValue into absolute value given a reference size */
45
- function parseSizeValue(value, referenceSize) {
46
- if (value === undefined)
47
- return undefined;
48
- if (typeof value === "number")
49
- return value;
50
- // Parse percentage string like "50%"
51
- const match = value.match(/^(\d+(?:\.\d+)?)%$/);
52
- if (match) {
53
- return Math.floor((referenceSize * parseFloat(match[1])) / 100);
54
- }
55
- return undefined;
56
- }
57
- function isTermuxSession() {
58
- return Boolean(process.env.TERMUX_VERSION);
59
- }
60
- /**
61
- * Container - a component that contains other components
62
- */
63
- export class Container {
64
- children = [];
65
- addChild(component) {
66
- this.children.push(component);
67
- }
68
- removeChild(component) {
69
- const index = this.children.indexOf(component);
70
- if (index !== -1) {
71
- this.children.splice(index, 1);
72
- }
73
- }
74
- clear() {
75
- this.children = [];
76
- }
77
- invalidate() {
78
- for (const child of this.children) {
79
- child.invalidate?.();
80
- }
81
- }
82
- render(width) {
83
- const lines = [];
84
- for (const child of this.children) {
85
- const childLines = child.render(width);
86
- for (const line of childLines) {
87
- lines.push(line);
88
- }
89
- }
90
- return lines;
91
- }
92
- }
93
- /**
94
- * TUI - Main class for managing terminal UI with differential rendering
95
- */
96
- export class TUI extends Container {
97
- terminal;
98
- previousLines = [];
99
- previousKittyImageIds = new Set();
100
- previousWidth = 0;
101
- previousHeight = 0;
102
- focusedComponent = null;
103
- inputListeners = new Set();
104
- /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
105
- onDebug;
106
- renderRequested = false;
107
- renderTimer;
108
- lastRenderAt = 0;
109
- static MIN_RENDER_INTERVAL_MS = 16;
110
- cursorRow = 0; // Logical cursor row (end of rendered content)
111
- hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
112
- showHardwareCursor = process.env.PI_HARDWARE_CURSOR === "1";
113
- clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === "1"; // Clear empty rows when content shrinks (default: off)
114
- maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)
115
- previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves
116
- fullRedrawCount = 0;
117
- stopped = false;
118
- // Overlay stack for modal components rendered on top of base content
119
- focusOrderCounter = 0;
120
- overlayStack = [];
121
- constructor(terminal, showHardwareCursor) {
122
- super();
123
- this.terminal = terminal;
124
- if (showHardwareCursor !== undefined) {
125
- this.showHardwareCursor = showHardwareCursor;
126
- }
127
- }
128
- get fullRedraws() {
129
- return this.fullRedrawCount;
130
- }
131
- getShowHardwareCursor() {
132
- return this.showHardwareCursor;
133
- }
134
- setShowHardwareCursor(enabled) {
135
- if (this.showHardwareCursor === enabled)
136
- return;
137
- this.showHardwareCursor = enabled;
138
- if (!enabled) {
139
- this.terminal.hideCursor();
140
- }
141
- this.requestRender();
142
- }
143
- getClearOnShrink() {
144
- return this.clearOnShrink;
145
- }
146
- /**
147
- * Set whether to trigger full re-render when content shrinks.
148
- * When true (default), empty rows are cleared when content shrinks.
149
- * When false, empty rows remain (reduces redraws on slower terminals).
150
- */
151
- setClearOnShrink(enabled) {
152
- this.clearOnShrink = enabled;
153
- }
154
- setFocus(component) {
155
- // Clear focused flag on old component
156
- if (isFocusable(this.focusedComponent)) {
157
- this.focusedComponent.focused = false;
158
- }
159
- this.focusedComponent = component;
160
- // Set focused flag on new component
161
- if (isFocusable(component)) {
162
- component.focused = true;
163
- }
164
- }
165
- /**
166
- * Show an overlay component with configurable positioning and sizing.
167
- * Returns a handle to control the overlay's visibility.
168
- */
169
- showOverlay(component, options) {
170
- const entry = {
171
- component,
172
- options,
173
- preFocus: this.focusedComponent,
174
- hidden: false,
175
- focusOrder: ++this.focusOrderCounter,
176
- };
177
- this.overlayStack.push(entry);
178
- // Only focus if overlay is actually visible
179
- if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
180
- this.setFocus(component);
181
- }
182
- this.terminal.hideCursor();
183
- this.requestRender();
184
- // Return handle for controlling this overlay
185
- return {
186
- hide: () => {
187
- const index = this.overlayStack.indexOf(entry);
188
- if (index !== -1) {
189
- this.overlayStack.splice(index, 1);
190
- // Restore focus if this overlay had focus
191
- if (this.focusedComponent === component) {
192
- const topVisible = this.getTopmostVisibleOverlay();
193
- this.setFocus(topVisible?.component ?? entry.preFocus);
194
- }
195
- if (this.overlayStack.length === 0)
196
- this.terminal.hideCursor();
197
- this.requestRender();
198
- }
199
- },
200
- setHidden: (hidden) => {
201
- if (entry.hidden === hidden)
202
- return;
203
- entry.hidden = hidden;
204
- // Update focus when hiding/showing
205
- if (hidden) {
206
- // If this overlay had focus, move focus to next visible or preFocus
207
- if (this.focusedComponent === component) {
208
- const topVisible = this.getTopmostVisibleOverlay();
209
- this.setFocus(topVisible?.component ?? entry.preFocus);
210
- }
211
- }
212
- else {
213
- // Restore focus to this overlay when showing (if it's actually visible)
214
- if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
215
- entry.focusOrder = ++this.focusOrderCounter;
216
- this.setFocus(component);
217
- }
218
- }
219
- this.requestRender();
220
- },
221
- isHidden: () => entry.hidden,
222
- focus: () => {
223
- if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry))
224
- return;
225
- if (this.focusedComponent !== component) {
226
- this.setFocus(component);
227
- }
228
- entry.focusOrder = ++this.focusOrderCounter;
229
- this.requestRender();
230
- },
231
- unfocus: () => {
232
- if (this.focusedComponent !== component)
233
- return;
234
- const topVisible = this.getTopmostVisibleOverlay();
235
- this.setFocus(topVisible && topVisible !== entry ? topVisible.component : entry.preFocus);
236
- this.requestRender();
237
- },
238
- isFocused: () => this.focusedComponent === component,
239
- };
240
- }
241
- /** Hide the topmost overlay and restore previous focus. */
242
- hideOverlay() {
243
- const overlay = this.overlayStack.pop();
244
- if (!overlay)
245
- return;
246
- if (this.focusedComponent === overlay.component) {
247
- // Find topmost visible overlay, or fall back to preFocus
248
- const topVisible = this.getTopmostVisibleOverlay();
249
- this.setFocus(topVisible?.component ?? overlay.preFocus);
250
- }
251
- if (this.overlayStack.length === 0)
252
- this.terminal.hideCursor();
253
- this.requestRender();
254
- }
255
- /** Check if there are any visible overlays */
256
- hasOverlay() {
257
- return this.overlayStack.some((o) => this.isOverlayVisible(o));
258
- }
259
- /** Check if an overlay entry is currently visible */
260
- isOverlayVisible(entry) {
261
- if (entry.hidden)
262
- return false;
263
- if (entry.options?.visible) {
264
- return entry.options.visible(this.terminal.columns, this.terminal.rows);
265
- }
266
- return true;
267
- }
268
- /** Find the topmost visible capturing overlay, if any */
269
- getTopmostVisibleOverlay() {
270
- for (let i = this.overlayStack.length - 1; i >= 0; i--) {
271
- if (this.overlayStack[i].options?.nonCapturing)
272
- continue;
273
- if (this.isOverlayVisible(this.overlayStack[i])) {
274
- return this.overlayStack[i];
275
- }
276
- }
277
- return undefined;
278
- }
279
- invalidate() {
280
- super.invalidate();
281
- for (const overlay of this.overlayStack)
282
- overlay.component.invalidate?.();
283
- }
284
- start() {
285
- this.stopped = false;
286
- this.terminal.start((data) => this.handleInput(data), () => this.requestRender());
287
- this.terminal.hideCursor();
288
- this.queryCellSize();
289
- this.requestRender();
290
- }
291
- addInputListener(listener) {
292
- this.inputListeners.add(listener);
293
- return () => {
294
- this.inputListeners.delete(listener);
295
- };
296
- }
297
- removeInputListener(listener) {
298
- this.inputListeners.delete(listener);
299
- }
300
- queryCellSize() {
301
- // Only query if terminal supports images (cell size is only used for image rendering)
302
- if (!getCapabilities().images) {
303
- return;
304
- }
305
- // Query terminal for cell size in pixels: CSI 16 t
306
- // Response format: CSI 6 ; height ; width t
307
- this.terminal.write("\x1b[16t");
308
- }
309
- stop() {
310
- this.stopped = true;
311
- if (this.renderTimer) {
312
- clearTimeout(this.renderTimer);
313
- this.renderTimer = undefined;
314
- }
315
- // Move cursor to the end of the content to prevent overwriting/artifacts on exit
316
- if (this.previousLines.length > 0) {
317
- const targetRow = this.previousLines.length; // Line after the last content
318
- const lineDiff = targetRow - this.hardwareCursorRow;
319
- if (lineDiff > 0) {
320
- this.terminal.write(`\x1b[${lineDiff}B`);
321
- }
322
- else if (lineDiff < 0) {
323
- this.terminal.write(`\x1b[${-lineDiff}A`);
324
- }
325
- this.terminal.write("\r\n");
326
- }
327
- this.terminal.showCursor();
328
- this.terminal.stop();
329
- }
330
- requestRender(force = false) {
331
- if (force) {
332
- this.previousLines = [];
333
- this.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
334
- this.previousHeight = -1; // -1 triggers heightChanged, forcing a full clear
335
- this.cursorRow = 0;
336
- this.hardwareCursorRow = 0;
337
- this.maxLinesRendered = 0;
338
- this.previousViewportTop = 0;
339
- if (this.renderTimer) {
340
- clearTimeout(this.renderTimer);
341
- this.renderTimer = undefined;
342
- }
343
- this.renderRequested = true;
344
- process.nextTick(() => {
345
- if (this.stopped || !this.renderRequested) {
346
- return;
347
- }
348
- this.renderRequested = false;
349
- this.lastRenderAt = performance.now();
350
- this.doRender();
351
- });
352
- return;
353
- }
354
- if (this.renderRequested)
355
- return;
356
- this.renderRequested = true;
357
- process.nextTick(() => this.scheduleRender());
358
- }
359
- scheduleRender() {
360
- if (this.stopped || this.renderTimer || !this.renderRequested) {
361
- return;
362
- }
363
- const elapsed = performance.now() - this.lastRenderAt;
364
- const delay = Math.max(0, TUI.MIN_RENDER_INTERVAL_MS - elapsed);
365
- this.renderTimer = setTimeout(() => {
366
- this.renderTimer = undefined;
367
- if (this.stopped || !this.renderRequested) {
368
- return;
369
- }
370
- this.renderRequested = false;
371
- this.lastRenderAt = performance.now();
372
- this.doRender();
373
- if (this.renderRequested) {
374
- this.scheduleRender();
375
- }
376
- }, delay);
377
- }
378
- handleInput(data) {
379
- if (this.inputListeners.size > 0) {
380
- let current = data;
381
- for (const listener of this.inputListeners) {
382
- const result = listener(current);
383
- if (result?.consume) {
384
- return;
385
- }
386
- if (result?.data !== undefined) {
387
- current = result.data;
388
- }
389
- }
390
- if (current.length === 0) {
391
- return;
392
- }
393
- data = current;
394
- }
395
- // Consume terminal cell size responses without blocking unrelated input.
396
- if (this.consumeCellSizeResponse(data)) {
397
- return;
398
- }
399
- // Global debug key handler (Shift+Ctrl+D)
400
- if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
401
- this.onDebug();
402
- return;
403
- }
404
- // If focused component is an overlay, verify it's still visible
405
- // (visibility can change due to terminal resize or visible() callback)
406
- const focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);
407
- if (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {
408
- // Focused overlay is no longer visible, redirect to topmost visible overlay
409
- const topVisible = this.getTopmostVisibleOverlay();
410
- if (topVisible) {
411
- this.setFocus(topVisible.component);
412
- }
413
- else {
414
- // No visible overlays, restore to preFocus
415
- this.setFocus(focusedOverlay.preFocus);
416
- }
417
- }
418
- // Pass input to focused component (including Ctrl+C)
419
- // The focused component can decide how to handle Ctrl+C
420
- if (this.focusedComponent?.handleInput) {
421
- // Filter out key release events unless component opts in
422
- if (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {
423
- return;
424
- }
425
- this.focusedComponent.handleInput(data);
426
- this.requestRender();
427
- }
428
- }
429
- consumeCellSizeResponse(data) {
430
- // Response format: ESC [ 6 ; height ; width t
431
- const match = data.match(/^\x1b\[6;(\d+);(\d+)t$/);
432
- if (!match) {
433
- return false;
434
- }
435
- const heightPx = parseInt(match[1], 10);
436
- const widthPx = parseInt(match[2], 10);
437
- if (heightPx <= 0 || widthPx <= 0) {
438
- return true;
439
- }
440
- setCellDimensions({ widthPx, heightPx });
441
- // Invalidate all components so images re-render with correct dimensions.
442
- this.invalidate();
443
- this.requestRender();
444
- return true;
445
- }
446
- /**
447
- * Resolve overlay layout from options.
448
- * Returns { width, row, col, maxHeight } for rendering.
449
- */
450
- resolveOverlayLayout(options, overlayHeight, termWidth, termHeight) {
451
- const opt = options ?? {};
452
- // Parse margin (clamp to non-negative)
453
- const margin = typeof opt.margin === "number"
454
- ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
455
- : (opt.margin ?? {});
456
- const marginTop = Math.max(0, margin.top ?? 0);
457
- const marginRight = Math.max(0, margin.right ?? 0);
458
- const marginBottom = Math.max(0, margin.bottom ?? 0);
459
- const marginLeft = Math.max(0, margin.left ?? 0);
460
- // Available space after margins
461
- const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
462
- const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
463
- // === Resolve width ===
464
- let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
465
- // Apply minWidth
466
- if (opt.minWidth !== undefined) {
467
- width = Math.max(width, opt.minWidth);
468
- }
469
- // Clamp to available space
470
- width = Math.max(1, Math.min(width, availWidth));
471
- // === Resolve maxHeight ===
472
- let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
473
- // Clamp to available space
474
- if (maxHeight !== undefined) {
475
- maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
476
- }
477
- // Effective overlay height (may be clamped by maxHeight)
478
- const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
479
- // === Resolve position ===
480
- let row;
481
- let col;
482
- if (opt.row !== undefined) {
483
- if (typeof opt.row === "string") {
484
- // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
485
- const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
486
- if (match) {
487
- const maxRow = Math.max(0, availHeight - effectiveHeight);
488
- const percent = parseFloat(match[1]) / 100;
489
- row = marginTop + Math.floor(maxRow * percent);
490
- }
491
- else {
492
- // Invalid format, fall back to center
493
- row = this.resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
494
- }
495
- }
496
- else {
497
- // Absolute row position
498
- row = opt.row;
499
- }
500
- }
501
- else {
502
- // Anchor-based (default: center)
503
- const anchor = opt.anchor ?? "center";
504
- row = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
505
- }
506
- if (opt.col !== undefined) {
507
- if (typeof opt.col === "string") {
508
- // Percentage: 0% = left, 100% = right (overlay stays within bounds)
509
- const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
510
- if (match) {
511
- const maxCol = Math.max(0, availWidth - width);
512
- const percent = parseFloat(match[1]) / 100;
513
- col = marginLeft + Math.floor(maxCol * percent);
514
- }
515
- else {
516
- // Invalid format, fall back to center
517
- col = this.resolveAnchorCol("center", width, availWidth, marginLeft);
518
- }
519
- }
520
- else {
521
- // Absolute column position
522
- col = opt.col;
523
- }
524
- }
525
- else {
526
- // Anchor-based (default: center)
527
- const anchor = opt.anchor ?? "center";
528
- col = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);
529
- }
530
- // Apply offsets
531
- if (opt.offsetY !== undefined)
532
- row += opt.offsetY;
533
- if (opt.offsetX !== undefined)
534
- col += opt.offsetX;
535
- // Clamp to terminal bounds (respecting margins)
536
- row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
537
- col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
538
- return { width, row, col, maxHeight };
539
- }
540
- resolveAnchorRow(anchor, height, availHeight, marginTop) {
541
- switch (anchor) {
542
- case "top-left":
543
- case "top-center":
544
- case "top-right":
545
- return marginTop;
546
- case "bottom-left":
547
- case "bottom-center":
548
- case "bottom-right":
549
- return marginTop + availHeight - height;
550
- case "left-center":
551
- case "center":
552
- case "right-center":
553
- return marginTop + Math.floor((availHeight - height) / 2);
554
- }
555
- }
556
- resolveAnchorCol(anchor, width, availWidth, marginLeft) {
557
- switch (anchor) {
558
- case "top-left":
559
- case "left-center":
560
- case "bottom-left":
561
- return marginLeft;
562
- case "top-right":
563
- case "right-center":
564
- case "bottom-right":
565
- return marginLeft + availWidth - width;
566
- case "top-center":
567
- case "center":
568
- case "bottom-center":
569
- return marginLeft + Math.floor((availWidth - width) / 2);
570
- }
571
- }
572
- /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
573
- compositeOverlays(lines, termWidth, termHeight) {
574
- if (this.overlayStack.length === 0)
575
- return lines;
576
- const result = [...lines];
577
- // Pre-render all visible overlays and calculate positions
578
- const rendered = [];
579
- let minLinesNeeded = result.length;
580
- const visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));
581
- visibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);
582
- for (const entry of visibleEntries) {
583
- const { component, options } = entry;
584
- // Get layout with height=0 first to determine width and maxHeight
585
- // (width and maxHeight don't depend on overlay height)
586
- const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
587
- // Render component at calculated width
588
- let overlayLines = component.render(width);
589
- // Apply maxHeight if specified
590
- if (maxHeight !== undefined && overlayLines.length > maxHeight) {
591
- overlayLines = overlayLines.slice(0, maxHeight);
592
- }
593
- // Get final row/col with actual overlay height
594
- const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
595
- rendered.push({ overlayLines, row, col, w: width });
596
- minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
597
- }
598
- // Pad to at least terminal height so overlays have screen-relative positions.
599
- // Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing
600
- // inflation that pushed content into scrollback on terminal widen.
601
- const workingHeight = Math.max(result.length, termHeight, minLinesNeeded);
602
- // Extend result with empty lines if content is too short for overlay placement or working area
603
- while (result.length < workingHeight) {
604
- result.push("");
605
- }
606
- const viewportStart = Math.max(0, workingHeight - termHeight);
607
- // Composite each overlay
608
- for (const { overlayLines, row, col, w } of rendered) {
609
- for (let i = 0; i < overlayLines.length; i++) {
610
- const idx = viewportStart + row + i;
611
- if (idx >= 0 && idx < result.length) {
612
- // Defensive: truncate overlay line to declared width before compositing
613
- // (components should already respect width, but this ensures it)
614
- const truncatedOverlayLine = visibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];
615
- result[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
616
- }
617
- }
618
- }
619
- return result;
620
- }
621
- static SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07";
622
- applyLineResets(lines) {
623
- const reset = TUI.SEGMENT_RESET;
624
- for (let i = 0; i < lines.length; i++) {
625
- const line = lines[i];
626
- if (!isImageLine(line)) {
627
- lines[i] = normalizeTerminalOutput(line) + reset;
628
- }
629
- }
630
- return lines;
631
- }
632
- collectKittyImageIds(lines) {
633
- const ids = new Set();
634
- for (const line of lines) {
635
- for (const id of extractKittyImageIds(line)) {
636
- ids.add(id);
637
- }
638
- }
639
- return ids;
640
- }
641
- deleteKittyImages(ids) {
642
- let buffer = "";
643
- for (const id of ids) {
644
- buffer += deleteKittyImage(id);
645
- }
646
- return buffer;
647
- }
648
- expandLastChangedForKittyImages(firstChanged, lastChanged) {
649
- let expandedLastChanged = lastChanged;
650
- for (let i = firstChanged; i < this.previousLines.length; i++) {
651
- if (extractKittyImageIds(this.previousLines[i]).length > 0) {
652
- expandedLastChanged = Math.max(expandedLastChanged, i);
653
- }
654
- }
655
- return expandedLastChanged;
656
- }
657
- deleteChangedKittyImages(firstChanged, lastChanged) {
658
- if (firstChanged < 0 || lastChanged < firstChanged)
659
- return "";
660
- const ids = new Set();
661
- const maxLine = Math.min(lastChanged, this.previousLines.length - 1);
662
- for (let i = firstChanged; i <= maxLine; i++) {
663
- for (const id of extractKittyImageIds(this.previousLines[i] ?? "")) {
664
- ids.add(id);
665
- }
666
- }
667
- return this.deleteKittyImages(ids);
668
- }
669
- /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
670
- compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
671
- if (isImageLine(baseLine))
672
- return baseLine;
673
- // Single pass through baseLine extracts both before and after segments
674
- const afterStart = startCol + overlayWidth;
675
- const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
676
- // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
677
- const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
678
- // Pad segments to target widths
679
- const beforePad = Math.max(0, startCol - base.beforeWidth);
680
- const overlayPad = Math.max(0, overlayWidth - overlay.width);
681
- const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
682
- const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
683
- const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
684
- const afterPad = Math.max(0, afterTarget - base.afterWidth);
685
- // Compose result
686
- const r = TUI.SEGMENT_RESET;
687
- const result = base.before +
688
- " ".repeat(beforePad) +
689
- r +
690
- overlay.text +
691
- " ".repeat(overlayPad) +
692
- r +
693
- base.after +
694
- " ".repeat(afterPad);
695
- // CRITICAL: Always verify and truncate to terminal width.
696
- // This is the final safeguard against width overflow which would crash the TUI.
697
- // Width tracking can drift from actual visible width due to:
698
- // - Complex ANSI/OSC sequences (hyperlinks, colors)
699
- // - Wide characters at segment boundaries
700
- // - Edge cases in segment extraction
701
- const resultWidth = visibleWidth(result);
702
- if (resultWidth <= totalWidth) {
703
- return result;
704
- }
705
- // Truncate with strict=true to ensure we don't exceed totalWidth
706
- return sliceByColumn(result, 0, totalWidth, true);
707
- }
708
- /**
709
- * Find and extract cursor position from rendered lines.
710
- * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
711
- * Only scans the bottom terminal height lines (visible viewport).
712
- * @param lines - Rendered lines to search
713
- * @param height - Terminal height (visible viewport size)
714
- * @returns Cursor position { row, col } or null if no marker found
715
- */
716
- extractCursorPosition(lines, height) {
717
- // Only scan the bottom `height` lines (visible viewport)
718
- const viewportTop = Math.max(0, lines.length - height);
719
- for (let row = lines.length - 1; row >= viewportTop; row--) {
720
- const line = lines[row];
721
- const markerIndex = line.indexOf(CURSOR_MARKER);
722
- if (markerIndex !== -1) {
723
- // Calculate visual column (width of text before marker)
724
- const beforeMarker = line.slice(0, markerIndex);
725
- const col = visibleWidth(beforeMarker);
726
- // Strip marker from the line
727
- lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
728
- return { row, col };
729
- }
730
- }
731
- return null;
732
- }
733
- doRender() {
734
- if (this.stopped)
735
- return;
736
- const width = this.terminal.columns;
737
- const height = this.terminal.rows;
738
- const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
739
- const heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;
740
- const previousBufferLength = this.previousHeight > 0 ? this.previousViewportTop + this.previousHeight : height;
741
- let prevViewportTop = heightChanged ? Math.max(0, previousBufferLength - height) : this.previousViewportTop;
742
- let viewportTop = prevViewportTop;
743
- let hardwareCursorRow = this.hardwareCursorRow;
744
- const computeLineDiff = (targetRow) => {
745
- const currentScreenRow = hardwareCursorRow - prevViewportTop;
746
- const targetScreenRow = targetRow - viewportTop;
747
- return targetScreenRow - currentScreenRow;
748
- };
749
- // Render all components to get new lines
750
- let newLines = this.render(width);
751
- // Composite overlays into the rendered lines (before differential compare)
752
- if (this.overlayStack.length > 0) {
753
- newLines = this.compositeOverlays(newLines, width, height);
754
- }
755
- // Extract cursor position before applying line resets (marker must be found first)
756
- const cursorPos = this.extractCursorPosition(newLines, height);
757
- newLines = this.applyLineResets(newLines);
758
- // Sync renderer state for strict no-write skips. This intentionally avoids
759
- // cursor movement or visibility calls so off-viewport-only frames emit zero bytes.
760
- const commitState = () => {
761
- this.cursorRow = Math.max(0, newLines.length - 1);
762
- this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
763
- this.previousViewportTop = prevViewportTop;
764
- this.previousLines = newLines;
765
- this.previousKittyImageIds = this.collectKittyImageIds(newLines);
766
- this.previousWidth = width;
767
- this.previousHeight = height;
768
- };
769
- // Helper to clear viewport (and optionally scrollback) and render new lines.
770
- // `clear === true` preserves scrollback; `clear === "scrollback"` wipes it.
771
- const fullRender = (clear) => {
772
- this.fullRedrawCount += 1;
773
- let buffer = "\x1b[?2026h"; // Begin synchronized output
774
- const wipesScrollback = clear === "scrollback";
775
- const viewportOnlyClear = clear === true;
776
- const clearsViewport = viewportOnlyClear || wipesScrollback;
777
- if (wipesScrollback) {
778
- buffer += this.deleteKittyImages(this.previousKittyImageIds);
779
- buffer += "\x1b[2J\x1b[H\x1b[3J"; // Clear screen, home, then clear scrollback
780
- }
781
- else if (viewportOnlyClear) {
782
- buffer += this.deleteKittyImages(this.previousKittyImageIds);
783
- buffer += "\x1b[2J\x1b[H"; // Clear screen + home, preserve scrollback
784
- }
785
- // For viewport-only clears, write only visible rows so preserved scrollback
786
- // is not duplicated by replaying the full logical buffer.
787
- const startLine = viewportOnlyClear ? Math.max(0, newLines.length - height) : 0;
788
- for (let i = startLine; i < newLines.length; i++) {
789
- if (i > startLine)
790
- buffer += "\r\n";
791
- buffer += newLines[i];
792
- }
793
- buffer += "\x1b[?2026l"; // End synchronized output
794
- this.terminal.write(buffer);
795
- this.cursorRow = Math.max(0, newLines.length - 1);
796
- this.hardwareCursorRow = this.cursorRow;
797
- // Reset max lines after any viewport clear; otherwise track growth.
798
- if (clearsViewport) {
799
- this.maxLinesRendered = newLines.length;
800
- }
801
- else {
802
- this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
803
- }
804
- const bufferLength = Math.max(height, newLines.length);
805
- this.previousViewportTop = Math.max(0, bufferLength - height);
806
- this.positionHardwareCursor(cursorPos, newLines.length);
807
- this.previousLines = newLines;
808
- this.previousKittyImageIds = this.collectKittyImageIds(newLines);
809
- this.previousWidth = width;
810
- this.previousHeight = height;
811
- };
812
- const debugRedraw = process.env.PI_DEBUG_REDRAW === "1";
813
- const logRedraw = (reason) => {
814
- if (!debugRedraw)
815
- return;
816
- const logPath = path.join(os.homedir(), ".pi", "agent", "pi-debug.log");
817
- const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
818
- fs.appendFileSync(logPath, msg);
819
- };
820
- // First render - just output everything without clearing (assumes clean screen)
821
- if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
822
- logRedraw("first render");
823
- fullRender(false);
824
- return;
825
- }
826
- // Width changes always need a full re-render because wrapping changes.
827
- // Existing scrollback was wrapped at the old width, so wipe it only here.
828
- if (widthChanged) {
829
- logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`);
830
- fullRender("scrollback");
831
- return;
832
- }
833
- // Height changes normally need a full re-render to keep the visible viewport aligned,
834
- // but Termux changes height when the software keyboard shows or hides.
835
- // In that environment, a full redraw causes the entire history to replay on every toggle.
836
- if (heightChanged && !isTermuxSession()) {
837
- logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`);
838
- fullRender(true);
839
- return;
840
- }
841
- // Content shrunk below the working area and no overlays - re-render to clear empty rows
842
- // (overlays need the padding, so only do this when no overlays are active)
843
- // Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var
844
- if (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {
845
- logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);
846
- fullRender(true);
847
- return;
848
- }
849
- // Find first and last changed lines
850
- let firstChanged = -1;
851
- let lastChanged = -1;
852
- const maxLines = Math.max(newLines.length, this.previousLines.length);
853
- for (let i = 0; i < maxLines; i++) {
854
- const oldLine = i < this.previousLines.length ? this.previousLines[i] : "";
855
- const newLine = i < newLines.length ? newLines[i] : "";
856
- if (oldLine !== newLine) {
857
- if (firstChanged === -1) {
858
- firstChanged = i;
859
- }
860
- lastChanged = i;
861
- }
862
- }
863
- const appendedLines = newLines.length > this.previousLines.length;
864
- if (appendedLines) {
865
- if (firstChanged === -1) {
866
- firstChanged = this.previousLines.length;
867
- }
868
- lastChanged = newLines.length - 1;
869
- }
870
- if (firstChanged !== -1) {
871
- lastChanged = this.expandLastChangedForKittyImages(firstChanged, lastChanged);
872
- }
873
- const appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;
874
- // No changes - but still need to update hardware cursor position if it moved
875
- if (firstChanged === -1) {
876
- this.positionHardwareCursor(cursorPos, newLines.length);
877
- this.previousViewportTop = prevViewportTop;
878
- this.previousHeight = height;
879
- return;
880
- }
881
- // All changes are in deleted lines (nothing to render, just clear)
882
- if (firstChanged >= newLines.length) {
883
- if (this.previousLines.length > newLines.length) {
884
- let buffer = "\x1b[?2026h";
885
- buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
886
- // Move to end of new content (clamp to 0 for empty content)
887
- const targetRow = Math.max(0, newLines.length - 1);
888
- if (targetRow < prevViewportTop) {
889
- logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`);
890
- fullRender(true);
891
- return;
892
- }
893
- const lineDiff = computeLineDiff(targetRow);
894
- if (lineDiff > 0)
895
- buffer += `\x1b[${lineDiff}B`;
896
- else if (lineDiff < 0)
897
- buffer += `\x1b[${-lineDiff}A`;
898
- buffer += "\r";
899
- // Clear extra lines without scrolling
900
- const extraLines = this.previousLines.length - newLines.length;
901
- if (extraLines > height) {
902
- logRedraw(`extraLines > height (${extraLines} > ${height})`);
903
- fullRender(true);
904
- return;
905
- }
906
- if (extraLines > 0) {
907
- buffer += "\x1b[1B";
908
- }
909
- for (let i = 0; i < extraLines; i++) {
910
- buffer += "\r\x1b[2K";
911
- if (i < extraLines - 1)
912
- buffer += "\x1b[1B";
913
- }
914
- if (extraLines > 0) {
915
- buffer += `\x1b[${extraLines}A`;
916
- }
917
- buffer += "\x1b[?2026l";
918
- this.terminal.write(buffer);
919
- this.cursorRow = targetRow;
920
- this.hardwareCursorRow = targetRow;
921
- }
922
- this.positionHardwareCursor(cursorPos, newLines.length);
923
- this.previousLines = newLines;
924
- this.previousKittyImageIds = this.collectKittyImageIds(newLines);
925
- this.previousWidth = width;
926
- this.previousHeight = height;
927
- this.previousViewportTop = prevViewportTop;
928
- return;
929
- }
930
- // Strict off-viewport same-count changes are state-only: visible pixels and
931
- // bottom anchoring are unchanged, so writing would only disturb scrollback.
932
- if (lastChanged < prevViewportTop && newLines.length === this.previousLines.length) {
933
- commitState();
934
- return;
935
- }
936
- // Differential rendering can only touch what was actually visible.
937
- // If the first changed line is above the previous viewport, we need a full redraw.
938
- if (firstChanged < prevViewportTop) {
939
- logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);
940
- fullRender(true);
941
- return;
942
- }
943
- // Render from first changed line to end
944
- // Build buffer with all updates wrapped in synchronized output
945
- let buffer = "\x1b[?2026h"; // Begin synchronized output
946
- buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
947
- const prevViewportBottom = prevViewportTop + height - 1;
948
- const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
949
- if (moveTargetRow > prevViewportBottom) {
950
- const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
951
- const moveToBottom = height - 1 - currentScreenRow;
952
- if (moveToBottom > 0) {
953
- buffer += `\x1b[${moveToBottom}B`;
954
- }
955
- const scroll = moveTargetRow - prevViewportBottom;
956
- buffer += "\r\n".repeat(scroll);
957
- prevViewportTop += scroll;
958
- viewportTop += scroll;
959
- hardwareCursorRow = moveTargetRow;
960
- }
961
- // Move cursor to first changed line (use hardwareCursorRow for actual position)
962
- const lineDiff = computeLineDiff(moveTargetRow);
963
- if (lineDiff > 0) {
964
- buffer += `\x1b[${lineDiff}B`; // Move down
965
- }
966
- else if (lineDiff < 0) {
967
- buffer += `\x1b[${-lineDiff}A`; // Move up
968
- }
969
- buffer += appendStart ? "\r\n" : "\r"; // Move to column 0
970
- // Only render changed lines (firstChanged to lastChanged), not all lines to end
971
- // This reduces flicker when only a single line changes (e.g., spinner animation)
972
- const renderEnd = Math.min(lastChanged, newLines.length - 1);
973
- for (let i = firstChanged; i <= renderEnd; i++) {
974
- if (i > firstChanged)
975
- buffer += "\r\n";
976
- buffer += "\x1b[2K"; // Clear current line
977
- const line = newLines[i];
978
- const isImage = isImageLine(line);
979
- if (!isImage && visibleWidth(line) > width) {
980
- // Log all lines to crash file for debugging
981
- const crashLogPath = path.join(os.homedir(), ".pi", "agent", "pi-crash.log");
982
- const crashData = [
983
- `Crash at ${new Date().toISOString()}`,
984
- `Terminal width: ${width}`,
985
- `Line ${i} visible width: ${visibleWidth(line)}`,
986
- "",
987
- "=== All rendered lines ===",
988
- ...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),
989
- "",
990
- ].join("\n");
991
- fs.mkdirSync(path.dirname(crashLogPath), { recursive: true });
992
- fs.writeFileSync(crashLogPath, crashData);
993
- // Clean up terminal state before throwing
994
- this.stop();
995
- const errorMsg = [
996
- `Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,
997
- "",
998
- "This is likely caused by a custom TUI component not truncating its output.",
999
- "Use visibleWidth() to measure and truncateToWidth() to truncate lines.",
1000
- "",
1001
- `Debug log written to: ${crashLogPath}`,
1002
- ].join("\n");
1003
- throw new Error(errorMsg);
1004
- }
1005
- buffer += line;
1006
- }
1007
- // Track where cursor ended up after rendering
1008
- let finalCursorRow = renderEnd;
1009
- // If we had more lines before, clear them and move cursor back
1010
- if (this.previousLines.length > newLines.length) {
1011
- // Move to end of new content first if we stopped before it
1012
- if (renderEnd < newLines.length - 1) {
1013
- const moveDown = newLines.length - 1 - renderEnd;
1014
- buffer += `\x1b[${moveDown}B`;
1015
- finalCursorRow = newLines.length - 1;
1016
- }
1017
- const extraLines = this.previousLines.length - newLines.length;
1018
- for (let i = newLines.length; i < this.previousLines.length; i++) {
1019
- buffer += "\r\n\x1b[2K";
1020
- }
1021
- // Move cursor back to end of new content
1022
- buffer += `\x1b[${extraLines}A`;
1023
- }
1024
- buffer += "\x1b[?2026l"; // End synchronized output
1025
- if (process.env.PI_TUI_DEBUG === "1") {
1026
- const debugDir = "/tmp/tui";
1027
- fs.mkdirSync(debugDir, { recursive: true });
1028
- const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
1029
- const debugData = [
1030
- `firstChanged: ${firstChanged}`,
1031
- `viewportTop: ${viewportTop}`,
1032
- `cursorRow: ${this.cursorRow}`,
1033
- `height: ${height}`,
1034
- `lineDiff: ${lineDiff}`,
1035
- `hardwareCursorRow: ${hardwareCursorRow}`,
1036
- `renderEnd: ${renderEnd}`,
1037
- `finalCursorRow: ${finalCursorRow}`,
1038
- `cursorPos: ${JSON.stringify(cursorPos)}`,
1039
- `newLines.length: ${newLines.length}`,
1040
- `previousLines.length: ${this.previousLines.length}`,
1041
- "",
1042
- "=== newLines ===",
1043
- JSON.stringify(newLines, null, 2),
1044
- "",
1045
- "=== previousLines ===",
1046
- JSON.stringify(this.previousLines, null, 2),
1047
- "",
1048
- "=== buffer ===",
1049
- JSON.stringify(buffer),
1050
- ].join("\n");
1051
- fs.writeFileSync(debugPath, debugData);
1052
- }
1053
- // Write entire buffer at once
1054
- this.terminal.write(buffer);
1055
- // Track cursor position for next render
1056
- // cursorRow tracks end of content (for viewport calculation)
1057
- // hardwareCursorRow tracks actual terminal cursor position (for movement)
1058
- this.cursorRow = Math.max(0, newLines.length - 1);
1059
- this.hardwareCursorRow = finalCursorRow;
1060
- // Track terminal's working area (grows but doesn't shrink unless cleared)
1061
- this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1062
- this.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);
1063
- // Position hardware cursor for IME
1064
- this.positionHardwareCursor(cursorPos, newLines.length);
1065
- this.previousLines = newLines;
1066
- this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1067
- this.previousWidth = width;
1068
- this.previousHeight = height;
1069
- }
1070
- /**
1071
- * Position the hardware cursor for IME candidate window.
1072
- * @param cursorPos The cursor position extracted from rendered output, or null
1073
- * @param totalLines Total number of rendered lines
1074
- */
1075
- positionHardwareCursor(cursorPos, totalLines) {
1076
- if (!cursorPos || totalLines <= 0) {
1077
- this.terminal.hideCursor();
1078
- return;
1079
- }
1080
- // Clamp cursor position to valid range
1081
- const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
1082
- const targetCol = Math.max(0, cursorPos.col);
1083
- // Move cursor from current position to target
1084
- const rowDelta = targetRow - this.hardwareCursorRow;
1085
- let buffer = "";
1086
- if (rowDelta > 0) {
1087
- buffer += `\x1b[${rowDelta}B`; // Move down
1088
- }
1089
- else if (rowDelta < 0) {
1090
- buffer += `\x1b[${-rowDelta}A`; // Move up
1091
- }
1092
- // Move to absolute column (1-indexed)
1093
- buffer += `\x1b[${targetCol + 1}G`;
1094
- if (buffer) {
1095
- this.terminal.write(buffer);
1096
- }
1097
- this.hardwareCursorRow = targetRow;
1098
- if (this.showHardwareCursor) {
1099
- this.terminal.showCursor();
1100
- }
1101
- else {
1102
- this.terminal.hideCursor();
1103
- }
1104
- }
1105
- }
1106
- //# sourceMappingURL=tui.js.map