erosolar-cli 1.7.356 → 1.7.358

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 (328) hide show
  1. package/README.md +24 -148
  2. package/dist/bin/erosolar.js +5 -21
  3. package/dist/bin/erosolar.js.map +1 -1
  4. package/dist/capabilities/agentSpawningCapability.d.ts.map +1 -1
  5. package/dist/capabilities/agentSpawningCapability.js +56 -31
  6. package/dist/capabilities/agentSpawningCapability.js.map +1 -1
  7. package/dist/contracts/agent-schemas.json +0 -15
  8. package/dist/contracts/tools.schema.json +0 -9
  9. package/dist/core/agent.d.ts +2 -2
  10. package/dist/core/agent.d.ts.map +1 -1
  11. package/dist/core/agent.js.map +1 -1
  12. package/dist/core/customCommands.d.ts +1 -0
  13. package/dist/core/customCommands.d.ts.map +1 -1
  14. package/dist/core/customCommands.js +3 -0
  15. package/dist/core/customCommands.js.map +1 -1
  16. package/dist/core/hooks.d.ts +113 -0
  17. package/dist/core/hooks.d.ts.map +1 -0
  18. package/dist/core/hooks.js +267 -0
  19. package/dist/core/hooks.js.map +1 -0
  20. package/dist/core/metricsTracker.d.ts +122 -0
  21. package/dist/core/metricsTracker.d.ts.map +1 -0
  22. package/dist/{alpha-zero → core}/metricsTracker.js +2 -5
  23. package/dist/core/metricsTracker.js.map +1 -0
  24. package/dist/core/securityAssessment.d.ts +91 -0
  25. package/dist/core/securityAssessment.d.ts.map +1 -0
  26. package/dist/core/securityAssessment.js +580 -0
  27. package/dist/core/securityAssessment.js.map +1 -0
  28. package/dist/core/sessionStore.d.ts +2 -0
  29. package/dist/core/sessionStore.d.ts.map +1 -1
  30. package/dist/core/sessionStore.js +1 -0
  31. package/dist/core/sessionStore.js.map +1 -1
  32. package/dist/core/toolPreconditions.d.ts.map +1 -1
  33. package/dist/core/toolPreconditions.js +0 -14
  34. package/dist/core/toolPreconditions.js.map +1 -1
  35. package/dist/core/toolRuntime.d.ts +22 -1
  36. package/dist/core/toolRuntime.d.ts.map +1 -1
  37. package/dist/core/toolRuntime.js +0 -5
  38. package/dist/core/toolRuntime.js.map +1 -1
  39. package/dist/core/toolValidation.d.ts.map +1 -1
  40. package/dist/core/toolValidation.js +14 -3
  41. package/dist/core/toolValidation.js.map +1 -1
  42. package/dist/core/validationRunner.d.ts +1 -3
  43. package/dist/core/validationRunner.d.ts.map +1 -1
  44. package/dist/core/validationRunner.js.map +1 -1
  45. package/dist/core/verification.d.ts +137 -0
  46. package/dist/core/verification.d.ts.map +1 -0
  47. package/dist/core/verification.js +323 -0
  48. package/dist/core/verification.js.map +1 -0
  49. package/dist/headless/headlessApp.d.ts.map +1 -1
  50. package/dist/headless/headlessApp.js +21 -0
  51. package/dist/headless/headlessApp.js.map +1 -1
  52. package/dist/mcp/sseClient.d.ts.map +1 -1
  53. package/dist/mcp/sseClient.js +9 -18
  54. package/dist/mcp/sseClient.js.map +1 -1
  55. package/dist/plugins/tools/build/buildPlugin.d.ts +0 -6
  56. package/dist/plugins/tools/build/buildPlugin.d.ts.map +1 -1
  57. package/dist/plugins/tools/build/buildPlugin.js +4 -10
  58. package/dist/plugins/tools/build/buildPlugin.js.map +1 -1
  59. package/dist/plugins/tools/nodeDefaults.d.ts.map +1 -1
  60. package/dist/plugins/tools/nodeDefaults.js +0 -2
  61. package/dist/plugins/tools/nodeDefaults.js.map +1 -1
  62. package/dist/runtime/agentSession.d.ts +2 -2
  63. package/dist/runtime/agentSession.d.ts.map +1 -1
  64. package/dist/runtime/agentSession.js +2 -2
  65. package/dist/runtime/agentSession.js.map +1 -1
  66. package/dist/shell/interactiveShell.d.ts +41 -7
  67. package/dist/shell/interactiveShell.d.ts.map +1 -1
  68. package/dist/shell/interactiveShell.js +399 -166
  69. package/dist/shell/interactiveShell.js.map +1 -1
  70. package/dist/shell/shellApp.d.ts +2 -0
  71. package/dist/shell/shellApp.d.ts.map +1 -1
  72. package/dist/shell/shellApp.js +82 -9
  73. package/dist/shell/shellApp.js.map +1 -1
  74. package/dist/shell/systemPrompt.d.ts.map +1 -1
  75. package/dist/shell/systemPrompt.js +1 -4
  76. package/dist/shell/systemPrompt.js.map +1 -1
  77. package/dist/shell/terminalInput.d.ts +250 -125
  78. package/dist/shell/terminalInput.d.ts.map +1 -1
  79. package/dist/shell/terminalInput.js +1061 -612
  80. package/dist/shell/terminalInput.js.map +1 -1
  81. package/dist/shell/terminalInputAdapter.d.ts +106 -24
  82. package/dist/shell/terminalInputAdapter.d.ts.map +1 -1
  83. package/dist/shell/terminalInputAdapter.js +137 -30
  84. package/dist/shell/terminalInputAdapter.js.map +1 -1
  85. package/dist/subagents/agentConfig.d.ts +27 -0
  86. package/dist/subagents/agentConfig.d.ts.map +1 -0
  87. package/dist/subagents/agentConfig.js +89 -0
  88. package/dist/subagents/agentConfig.js.map +1 -0
  89. package/dist/subagents/agentRegistry.d.ts +33 -0
  90. package/dist/subagents/agentRegistry.d.ts.map +1 -0
  91. package/dist/subagents/agentRegistry.js +162 -0
  92. package/dist/subagents/agentRegistry.js.map +1 -0
  93. package/dist/subagents/taskRunner.d.ts +7 -1
  94. package/dist/subagents/taskRunner.d.ts.map +1 -1
  95. package/dist/subagents/taskRunner.js +200 -49
  96. package/dist/subagents/taskRunner.js.map +1 -1
  97. package/dist/ui/ShellUIAdapter.d.ts +7 -1
  98. package/dist/ui/ShellUIAdapter.d.ts.map +1 -1
  99. package/dist/ui/ShellUIAdapter.js +42 -18
  100. package/dist/ui/ShellUIAdapter.js.map +1 -1
  101. package/dist/ui/display.d.ts +24 -45
  102. package/dist/ui/display.d.ts.map +1 -1
  103. package/dist/ui/display.js +148 -274
  104. package/dist/ui/display.js.map +1 -1
  105. package/dist/ui/theme.d.ts.map +1 -1
  106. package/dist/ui/theme.js +6 -8
  107. package/dist/ui/theme.js.map +1 -1
  108. package/dist/ui/toolDisplay.d.ts +0 -158
  109. package/dist/ui/toolDisplay.d.ts.map +1 -1
  110. package/dist/ui/toolDisplay.js +0 -348
  111. package/dist/ui/toolDisplay.js.map +1 -1
  112. package/dist/ui/unified/layout.d.ts +20 -0
  113. package/dist/ui/unified/layout.d.ts.map +1 -1
  114. package/dist/ui/unified/layout.js +105 -216
  115. package/dist/ui/unified/layout.js.map +1 -1
  116. package/dist/utils/frontmatter.d.ts +10 -0
  117. package/dist/utils/frontmatter.d.ts.map +1 -0
  118. package/dist/utils/frontmatter.js +78 -0
  119. package/dist/utils/frontmatter.js.map +1 -0
  120. package/package.json +4 -4
  121. package/dist/alpha-zero/agentWrapper.d.ts +0 -84
  122. package/dist/alpha-zero/agentWrapper.d.ts.map +0 -1
  123. package/dist/alpha-zero/agentWrapper.js +0 -171
  124. package/dist/alpha-zero/agentWrapper.js.map +0 -1
  125. package/dist/alpha-zero/codeEvaluator.d.ts +0 -25
  126. package/dist/alpha-zero/codeEvaluator.d.ts.map +0 -1
  127. package/dist/alpha-zero/codeEvaluator.js +0 -273
  128. package/dist/alpha-zero/codeEvaluator.js.map +0 -1
  129. package/dist/alpha-zero/competitiveRunner.d.ts +0 -66
  130. package/dist/alpha-zero/competitiveRunner.d.ts.map +0 -1
  131. package/dist/alpha-zero/competitiveRunner.js +0 -224
  132. package/dist/alpha-zero/competitiveRunner.js.map +0 -1
  133. package/dist/alpha-zero/index.d.ts +0 -67
  134. package/dist/alpha-zero/index.d.ts.map +0 -1
  135. package/dist/alpha-zero/index.js +0 -99
  136. package/dist/alpha-zero/index.js.map +0 -1
  137. package/dist/alpha-zero/introspection.d.ts +0 -128
  138. package/dist/alpha-zero/introspection.d.ts.map +0 -1
  139. package/dist/alpha-zero/introspection.js +0 -300
  140. package/dist/alpha-zero/introspection.js.map +0 -1
  141. package/dist/alpha-zero/metricsTracker.d.ts +0 -71
  142. package/dist/alpha-zero/metricsTracker.d.ts.map +0 -1
  143. package/dist/alpha-zero/metricsTracker.js.map +0 -1
  144. package/dist/alpha-zero/security/core.d.ts +0 -125
  145. package/dist/alpha-zero/security/core.d.ts.map +0 -1
  146. package/dist/alpha-zero/security/core.js +0 -271
  147. package/dist/alpha-zero/security/core.js.map +0 -1
  148. package/dist/alpha-zero/security/google.d.ts +0 -125
  149. package/dist/alpha-zero/security/google.d.ts.map +0 -1
  150. package/dist/alpha-zero/security/google.js +0 -311
  151. package/dist/alpha-zero/security/google.js.map +0 -1
  152. package/dist/alpha-zero/security/googleLoader.d.ts +0 -17
  153. package/dist/alpha-zero/security/googleLoader.d.ts.map +0 -1
  154. package/dist/alpha-zero/security/googleLoader.js +0 -41
  155. package/dist/alpha-zero/security/googleLoader.js.map +0 -1
  156. package/dist/alpha-zero/security/index.d.ts +0 -29
  157. package/dist/alpha-zero/security/index.d.ts.map +0 -1
  158. package/dist/alpha-zero/security/index.js +0 -32
  159. package/dist/alpha-zero/security/index.js.map +0 -1
  160. package/dist/alpha-zero/security/simulation.d.ts +0 -124
  161. package/dist/alpha-zero/security/simulation.d.ts.map +0 -1
  162. package/dist/alpha-zero/security/simulation.js +0 -277
  163. package/dist/alpha-zero/security/simulation.js.map +0 -1
  164. package/dist/alpha-zero/selfModification.d.ts +0 -109
  165. package/dist/alpha-zero/selfModification.d.ts.map +0 -1
  166. package/dist/alpha-zero/selfModification.js +0 -233
  167. package/dist/alpha-zero/selfModification.js.map +0 -1
  168. package/dist/alpha-zero/types.d.ts +0 -170
  169. package/dist/alpha-zero/types.d.ts.map +0 -1
  170. package/dist/alpha-zero/types.js +0 -31
  171. package/dist/alpha-zero/types.js.map +0 -1
  172. package/dist/capabilities/securityTestingCapability.d.ts +0 -13
  173. package/dist/capabilities/securityTestingCapability.d.ts.map +0 -1
  174. package/dist/capabilities/securityTestingCapability.js +0 -25
  175. package/dist/capabilities/securityTestingCapability.js.map +0 -1
  176. package/dist/core/aiFlowOptimizer.d.ts +0 -26
  177. package/dist/core/aiFlowOptimizer.d.ts.map +0 -1
  178. package/dist/core/aiFlowOptimizer.js +0 -31
  179. package/dist/core/aiFlowOptimizer.js.map +0 -1
  180. package/dist/core/aiOptimizationEngine.d.ts +0 -158
  181. package/dist/core/aiOptimizationEngine.d.ts.map +0 -1
  182. package/dist/core/aiOptimizationEngine.js +0 -428
  183. package/dist/core/aiOptimizationEngine.js.map +0 -1
  184. package/dist/core/aiOptimizationIntegration.d.ts +0 -93
  185. package/dist/core/aiOptimizationIntegration.d.ts.map +0 -1
  186. package/dist/core/aiOptimizationIntegration.js +0 -250
  187. package/dist/core/aiOptimizationIntegration.js.map +0 -1
  188. package/dist/core/enhancedErrorRecovery.d.ts +0 -100
  189. package/dist/core/enhancedErrorRecovery.d.ts.map +0 -1
  190. package/dist/core/enhancedErrorRecovery.js +0 -345
  191. package/dist/core/enhancedErrorRecovery.js.map +0 -1
  192. package/dist/core/hooksSystem.d.ts +0 -65
  193. package/dist/core/hooksSystem.d.ts.map +0 -1
  194. package/dist/core/hooksSystem.js +0 -273
  195. package/dist/core/hooksSystem.js.map +0 -1
  196. package/dist/core/memorySystem.d.ts +0 -48
  197. package/dist/core/memorySystem.d.ts.map +0 -1
  198. package/dist/core/memorySystem.js +0 -271
  199. package/dist/core/memorySystem.js.map +0 -1
  200. package/dist/core/unified/errors.d.ts +0 -189
  201. package/dist/core/unified/errors.d.ts.map +0 -1
  202. package/dist/core/unified/errors.js +0 -497
  203. package/dist/core/unified/errors.js.map +0 -1
  204. package/dist/core/unified/index.d.ts +0 -19
  205. package/dist/core/unified/index.d.ts.map +0 -1
  206. package/dist/core/unified/index.js +0 -68
  207. package/dist/core/unified/index.js.map +0 -1
  208. package/dist/core/unified/schema.d.ts +0 -101
  209. package/dist/core/unified/schema.d.ts.map +0 -1
  210. package/dist/core/unified/schema.js +0 -350
  211. package/dist/core/unified/schema.js.map +0 -1
  212. package/dist/core/unified/toolRuntime.d.ts +0 -179
  213. package/dist/core/unified/toolRuntime.d.ts.map +0 -1
  214. package/dist/core/unified/toolRuntime.js +0 -517
  215. package/dist/core/unified/toolRuntime.js.map +0 -1
  216. package/dist/core/unified/tools.d.ts +0 -127
  217. package/dist/core/unified/tools.d.ts.map +0 -1
  218. package/dist/core/unified/tools.js +0 -1333
  219. package/dist/core/unified/tools.js.map +0 -1
  220. package/dist/core/unified/types.d.ts +0 -352
  221. package/dist/core/unified/types.d.ts.map +0 -1
  222. package/dist/core/unified/types.js +0 -12
  223. package/dist/core/unified/types.js.map +0 -1
  224. package/dist/core/unified/version.d.ts +0 -209
  225. package/dist/core/unified/version.d.ts.map +0 -1
  226. package/dist/core/unified/version.js +0 -454
  227. package/dist/core/unified/version.js.map +0 -1
  228. package/dist/plugins/tools/security/securityPlugin.d.ts +0 -3
  229. package/dist/plugins/tools/security/securityPlugin.d.ts.map +0 -1
  230. package/dist/plugins/tools/security/securityPlugin.js +0 -12
  231. package/dist/plugins/tools/security/securityPlugin.js.map +0 -1
  232. package/dist/security/active-stack-security.d.ts +0 -112
  233. package/dist/security/active-stack-security.d.ts.map +0 -1
  234. package/dist/security/active-stack-security.js +0 -296
  235. package/dist/security/active-stack-security.js.map +0 -1
  236. package/dist/security/advanced-persistence-research.d.ts +0 -92
  237. package/dist/security/advanced-persistence-research.d.ts.map +0 -1
  238. package/dist/security/advanced-persistence-research.js +0 -195
  239. package/dist/security/advanced-persistence-research.js.map +0 -1
  240. package/dist/security/advanced-targeting.d.ts +0 -119
  241. package/dist/security/advanced-targeting.d.ts.map +0 -1
  242. package/dist/security/advanced-targeting.js +0 -233
  243. package/dist/security/advanced-targeting.js.map +0 -1
  244. package/dist/security/assessment/vulnerabilityAssessment.d.ts +0 -104
  245. package/dist/security/assessment/vulnerabilityAssessment.d.ts.map +0 -1
  246. package/dist/security/assessment/vulnerabilityAssessment.js +0 -315
  247. package/dist/security/assessment/vulnerabilityAssessment.js.map +0 -1
  248. package/dist/security/authorization/securityAuthorization.d.ts +0 -88
  249. package/dist/security/authorization/securityAuthorization.d.ts.map +0 -1
  250. package/dist/security/authorization/securityAuthorization.js +0 -172
  251. package/dist/security/authorization/securityAuthorization.js.map +0 -1
  252. package/dist/security/comprehensive-targeting.d.ts +0 -85
  253. package/dist/security/comprehensive-targeting.d.ts.map +0 -1
  254. package/dist/security/comprehensive-targeting.js +0 -438
  255. package/dist/security/comprehensive-targeting.js.map +0 -1
  256. package/dist/security/global-security-integration.d.ts +0 -91
  257. package/dist/security/global-security-integration.d.ts.map +0 -1
  258. package/dist/security/global-security-integration.js +0 -218
  259. package/dist/security/global-security-integration.js.map +0 -1
  260. package/dist/security/index.d.ts +0 -38
  261. package/dist/security/index.d.ts.map +0 -1
  262. package/dist/security/index.js +0 -47
  263. package/dist/security/index.js.map +0 -1
  264. package/dist/security/persistence-analyzer.d.ts +0 -56
  265. package/dist/security/persistence-analyzer.d.ts.map +0 -1
  266. package/dist/security/persistence-analyzer.js +0 -187
  267. package/dist/security/persistence-analyzer.js.map +0 -1
  268. package/dist/security/persistence-cli.d.ts +0 -36
  269. package/dist/security/persistence-cli.d.ts.map +0 -1
  270. package/dist/security/persistence-cli.js +0 -160
  271. package/dist/security/persistence-cli.js.map +0 -1
  272. package/dist/security/persistence-research.d.ts +0 -92
  273. package/dist/security/persistence-research.d.ts.map +0 -1
  274. package/dist/security/persistence-research.js +0 -364
  275. package/dist/security/persistence-research.js.map +0 -1
  276. package/dist/security/research/persistenceResearch.d.ts +0 -97
  277. package/dist/security/research/persistenceResearch.d.ts.map +0 -1
  278. package/dist/security/research/persistenceResearch.js +0 -282
  279. package/dist/security/research/persistenceResearch.js.map +0 -1
  280. package/dist/security/security-integration.d.ts +0 -74
  281. package/dist/security/security-integration.d.ts.map +0 -1
  282. package/dist/security/security-integration.js +0 -137
  283. package/dist/security/security-integration.js.map +0 -1
  284. package/dist/security/security-testing-framework.d.ts +0 -112
  285. package/dist/security/security-testing-framework.d.ts.map +0 -1
  286. package/dist/security/security-testing-framework.js +0 -364
  287. package/dist/security/security-testing-framework.js.map +0 -1
  288. package/dist/security/simulation/attackSimulation.d.ts +0 -93
  289. package/dist/security/simulation/attackSimulation.d.ts.map +0 -1
  290. package/dist/security/simulation/attackSimulation.js +0 -341
  291. package/dist/security/simulation/attackSimulation.js.map +0 -1
  292. package/dist/security/strategic-operations.d.ts +0 -100
  293. package/dist/security/strategic-operations.d.ts.map +0 -1
  294. package/dist/security/strategic-operations.js +0 -276
  295. package/dist/security/strategic-operations.js.map +0 -1
  296. package/dist/security/tool-security-wrapper.d.ts +0 -58
  297. package/dist/security/tool-security-wrapper.d.ts.map +0 -1
  298. package/dist/security/tool-security-wrapper.js +0 -156
  299. package/dist/security/tool-security-wrapper.js.map +0 -1
  300. package/dist/shell/claudeCodeStreamHandler.d.ts +0 -145
  301. package/dist/shell/claudeCodeStreamHandler.d.ts.map +0 -1
  302. package/dist/shell/claudeCodeStreamHandler.js +0 -322
  303. package/dist/shell/claudeCodeStreamHandler.js.map +0 -1
  304. package/dist/shell/inputQueueManager.d.ts +0 -144
  305. package/dist/shell/inputQueueManager.d.ts.map +0 -1
  306. package/dist/shell/inputQueueManager.js +0 -290
  307. package/dist/shell/inputQueueManager.js.map +0 -1
  308. package/dist/shell/metricsTracker.d.ts +0 -60
  309. package/dist/shell/metricsTracker.d.ts.map +0 -1
  310. package/dist/shell/metricsTracker.js +0 -119
  311. package/dist/shell/metricsTracker.js.map +0 -1
  312. package/dist/shell/streamingOutputManager.d.ts +0 -115
  313. package/dist/shell/streamingOutputManager.d.ts.map +0 -1
  314. package/dist/shell/streamingOutputManager.js +0 -225
  315. package/dist/shell/streamingOutputManager.js.map +0 -1
  316. package/dist/tools/securityTools.d.ts +0 -22
  317. package/dist/tools/securityTools.d.ts.map +0 -1
  318. package/dist/tools/securityTools.js +0 -448
  319. package/dist/tools/securityTools.js.map +0 -1
  320. package/dist/ui/persistentPrompt.d.ts +0 -50
  321. package/dist/ui/persistentPrompt.d.ts.map +0 -1
  322. package/dist/ui/persistentPrompt.js +0 -92
  323. package/dist/ui/persistentPrompt.js.map +0 -1
  324. package/dist/ui/terminalUISchema.d.ts +0 -195
  325. package/dist/ui/terminalUISchema.d.ts.map +0 -1
  326. package/dist/ui/terminalUISchema.js +0 -113
  327. package/dist/ui/terminalUISchema.js.map +0 -1
  328. package/scripts/deploy-security-capabilities.js +0 -178
@@ -3,15 +3,24 @@
3
3
  *
4
4
  * Design principles:
5
5
  * - Single source of truth for input state
6
+ * - Hybrid floating/scroll approach:
7
+ * - Initially: chat box floats below content
8
+ * - When terminal fills: scroll region activates, chat box pins to bottom
6
9
  * - Native bracketed paste support (no heuristics)
7
10
  * - Clean cursor model with render-time wrapping
8
11
  * - State machine for different input modes
9
12
  * - No readline dependency for display
13
+ * - Text selection enabled: mouse tracking disabled by default to preserve
14
+ * native terminal text selection and copy/paste functionality
15
+ * - Scrollback navigation via keyboard: PageUp/PageDown, Ctrl+Home/End
10
16
  */
11
17
  import { EventEmitter } from 'node:events';
12
- import { isMultilinePaste, generatePasteSummary } from '../core/multilinePasteHandler.js';
18
+ import { isMultilinePaste } from '../core/multilinePasteHandler.js';
13
19
  import { writeLock } from '../ui/writeLock.js';
14
- import { UI_COLORS, DEFAULT_UI_CONFIG, } from '../ui/terminalUISchema.js';
20
+ import { renderDivider, renderStatusLine } from '../ui/unified/layout.js';
21
+ import { isStreamingMode } from '../ui/globalWriteLock.js';
22
+ import { formatThinking } from '../ui/toolDisplay.js';
23
+ import { theme } from '../ui/theme.js';
15
24
  // ANSI escape codes
16
25
  const ESC = {
17
26
  // Cursor control
@@ -21,14 +30,18 @@ const ESC = {
21
30
  SHOW: '\x1b[?25h',
22
31
  TO: (row, col) => `\x1b[${row};${col}H`,
23
32
  TO_COL: (col) => `\x1b[${col}G`,
24
- // Screen control
25
- CLEAR_SCREEN: '\x1b[2J',
26
- HOME: '\x1b[H',
27
- ALT_SCREEN_ENTER: '\x1b[?1049h', // Enter alternate screen buffer
28
- ALT_SCREEN_EXIT: '\x1b[?1049l', // Exit alternate screen buffer
29
33
  // Line control
30
34
  CLEAR_LINE: '\x1b[2K',
31
35
  CLEAR_TO_END: '\x1b[0J',
36
+ // Screen control
37
+ HOME: '\x1b[H',
38
+ CLEAR_SCREEN: '\x1b[2J',
39
+ // Alternate screen buffer (like vim/tmux)
40
+ ENTER_ALT_SCREEN: '\x1b[?1049h',
41
+ EXIT_ALT_SCREEN: '\x1b[?1049l',
42
+ // Scroll region
43
+ SET_SCROLL: (top, bottom) => `\x1b[${top};${bottom}r`,
44
+ RESET_SCROLL: '\x1b[r',
32
45
  // Style
33
46
  RESET: '\x1b[0m',
34
47
  DIM: '\x1b[2m',
@@ -40,6 +53,12 @@ const ESC = {
40
53
  PASTE_DISABLE: '\x1b[?2004l',
41
54
  PASTE_START: '\x1b[200~',
42
55
  PASTE_END: '\x1b[201~',
56
+ // Mouse tracking - Button events only (allows Shift+drag for text selection)
57
+ // Mode 1000: Track button presses/releases (wheel events included)
58
+ // Mode 1006: SGR extended format for better coordinate handling
59
+ // Note: NOT using mode 1003 (all motion) to preserve terminal text selection
60
+ MOUSE_ENABLE: '\x1b[?1000h\x1b[?1006h', // Enable button tracking + SGR mode
61
+ MOUSE_DISABLE: '\x1b[?1006l\x1b[?1000l', // Disable mouse tracking
43
62
  };
44
63
  /**
45
64
  * Unified terminal input handler
@@ -68,49 +87,54 @@ export class TerminalInput extends EventEmitter {
68
87
  statusMessage = null;
69
88
  overrideStatusMessage = null; // Secondary status (warnings, etc.)
70
89
  streamingLabel = null; // Streaming progress indicator
90
+ metaElapsedSeconds = null; // Optional elapsed time for header line
91
+ metaTokensUsed = null; // Optional token usage
92
+ metaTokenLimit = null; // Optional token window
93
+ metaThinkingMs = null; // Optional thinking duration
94
+ metaThinkingHasContent = false; // Whether collapsed thinking content exists
71
95
  lastRenderContent = '';
72
96
  lastRenderCursor = -1;
73
97
  renderDirty = false;
74
98
  isRendering = false;
75
- flowModeRenderedLines = 0; // Track lines rendered for clearing
76
- inputAreaStartRow = 0; // Track absolute row position of input area
77
- contentEndRow = 0; // Row where content ends (chat box renders below this)
78
- // Command suggestions (Claude Code style auto-complete)
79
- commandSuggestions = [];
80
- filteredSuggestions = [];
81
- selectedSuggestionIndex = 0;
82
- showSuggestions = false;
83
99
  // Lifecycle
84
100
  disposed = false;
85
101
  enabled = true;
86
102
  contextUsage = null;
103
+ contextAutoCompactThreshold = 90;
104
+ // Track current content row (starts at top, moves down)
105
+ contentRow = 1;
106
+ // Track if scroll region is currently active
107
+ scrollRegionActive = false;
108
+ thinkingModeLabel = null;
109
+ // Scrollback buffer
110
+ scrollbackBuffer = [];
111
+ maxScrollbackLines = 10000;
112
+ scrollbackOffset = 0; // 0 = at bottom (live), > 0 = scrolled up
113
+ isInScrollbackMode = false;
114
+ scrollIndicatorFrame = 0; // For animated scroll indicator
115
+ // Alternate screen state
116
+ alternateScreenActive = false;
87
117
  editMode = 'display-edits';
88
118
  verificationEnabled = true;
89
119
  autoContinueEnabled = false;
90
120
  verificationHotkey = 'alt+v';
91
121
  autoContinueHotkey = 'alt+c';
92
- // Output interceptor cleanup
93
- outputInterceptorCleanup;
94
- // Metrics tracking for status bar
95
- streamingStartTime = null;
96
- thinkingEnabled = true;
97
- modelInfo = null; // Provider · Model info
98
- // Streaming input area render timer (updates elapsed time display)
122
+ thinkingHotkey = '/thinking';
123
+ modelLabel = null;
124
+ providerLabel = null;
125
+ // Streaming render throttle
126
+ lastStreamingRender = 0;
127
+ streamingRenderInterval = 250; // ms between renders during streaming
99
128
  streamingRenderTimer = null;
100
- // Reference to display module for getting line counts during streaming
101
- displayRef = null;
102
- // Unified UI initialization flag
103
- unifiedUIInitialized = false;
104
129
  constructor(writeStream = process.stdout, config = {}) {
105
130
  super();
106
131
  this.out = writeStream;
107
- // Use schema defaults for configuration consistency
108
132
  this.config = {
109
- maxLines: config.maxLines ?? DEFAULT_UI_CONFIG.inputArea.maxLines,
110
- maxLength: config.maxLength ?? DEFAULT_UI_CONFIG.inputArea.maxLength,
133
+ maxLines: config.maxLines ?? 1000,
134
+ maxLength: config.maxLength ?? 10000,
111
135
  maxQueueSize: config.maxQueueSize ?? 100,
112
- promptChar: config.promptChar ?? DEFAULT_UI_CONFIG.inputArea.promptChar,
113
- continuationChar: config.continuationChar ?? DEFAULT_UI_CONFIG.inputArea.continuationChar,
136
+ promptChar: config.promptChar ?? '> ',
137
+ continuationChar: config.continuationChar ?? '│ ',
114
138
  };
115
139
  }
116
140
  // ===========================================================================
@@ -133,10 +157,47 @@ export class TerminalInput extends EventEmitter {
133
157
  }
134
158
  }
135
159
  /**
136
- * Process raw terminal data (handles bracketed paste sequences)
137
- * Returns true if the data was consumed (paste sequence)
160
+ * Enable mouse tracking in terminal
161
+ */
162
+ enableMouseTracking() {
163
+ if (this.isTTY()) {
164
+ this.write(ESC.MOUSE_ENABLE);
165
+ }
166
+ }
167
+ /**
168
+ * Disable mouse tracking
169
+ */
170
+ disableMouseTracking() {
171
+ if (this.isTTY()) {
172
+ this.write(ESC.MOUSE_DISABLE);
173
+ }
174
+ }
175
+ /**
176
+ * Process raw terminal data (handles bracketed paste sequences, mouse events, and escape sequences)
177
+ * Returns true if the data was consumed (paste sequence, mouse event, etc.)
138
178
  */
139
179
  processRawData(data) {
180
+ // Check for mouse events (SGR mode: \x1b[<button;x;yM or m)
181
+ const mouseMatch = data.match(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/);
182
+ if (mouseMatch) {
183
+ const button = parseInt(mouseMatch[1], 10);
184
+ const x = parseInt(mouseMatch[2], 10);
185
+ const y = parseInt(mouseMatch[3], 10);
186
+ const action = mouseMatch[4]; // 'M' = press, 'm' = release
187
+ this.handleMouseEvent(button, x, y, action);
188
+ // Remove mouse event from data and return remaining
189
+ const mouseEventEnd = data.indexOf(action) + 1;
190
+ const remaining = data.slice(mouseEventEnd);
191
+ return { consumed: true, passthrough: remaining };
192
+ }
193
+ // Filter out arrow key escape sequences (they're handled by keypress events)
194
+ // Arrow keys: \x1b[A (up), \x1b[B (down), \x1b[C (right), \x1b[D (left)
195
+ const arrowMatch = data.match(/\x1b\[[ABCD]/);
196
+ if (arrowMatch) {
197
+ // Arrow keys should be handled by keypress handler, strip them from passthrough
198
+ const filtered = data.replace(/\x1b\[[ABCD]/g, '');
199
+ return { consumed: filtered.length !== data.length, passthrough: filtered };
200
+ }
140
201
  // Check for paste start
141
202
  if (data.includes(ESC.PASTE_START)) {
142
203
  this.isPasting = true;
@@ -167,6 +228,21 @@ export class TerminalInput extends EventEmitter {
167
228
  }
168
229
  return { consumed: false, passthrough: data };
169
230
  }
231
+ /**
232
+ * Handle mouse events (button, x, y coordinates, action)
233
+ */
234
+ handleMouseEvent(button, _x, _y, _action) {
235
+ // Mouse wheel events: button 64 = scroll up, button 65 = scroll down
236
+ if (button === 64) {
237
+ // Scroll up (3 lines per wheel tick)
238
+ this.scrollUp(3);
239
+ }
240
+ else if (button === 65) {
241
+ // Scroll down (3 lines per wheel tick)
242
+ this.scrollDown(3);
243
+ }
244
+ // Ignore other mouse events (clicks, drags, etc.) for now
245
+ }
170
246
  /**
171
247
  * Handle a keypress event
172
248
  */
@@ -189,258 +265,36 @@ export class TerminalInput extends EventEmitter {
189
265
  if (handled)
190
266
  return;
191
267
  }
192
- // Handle '?' for help hint (if buffer is empty)
193
- if (str === '?' && this.buffer.length === 0) {
194
- this.emit('showHelp');
195
- return;
196
- }
197
268
  // Insert printable characters
198
269
  if (str && !key?.ctrl && !key?.meta) {
199
270
  this.insertText(str);
200
271
  }
201
272
  }
202
- // Banner content to write on init (set via setBannerContent before initializeUnifiedUI)
203
- bannerContent = null;
204
- /**
205
- * Set banner content to be written when unified UI initializes.
206
- */
207
- setBannerContent(content) {
208
- this.bannerContent = content;
209
- }
210
- /**
211
- * Initialize the unified UI system with BOTTOM PINNED chat box.
212
- *
213
- * Layout:
214
- * 1. Clear screen
215
- * 2. Write banner at top
216
- * 3. Set content cursor row after banner
217
- * 4. Render chat box at bottom (sets up scroll region)
218
- */
219
- initializeUnifiedUI() {
220
- if (this.unifiedUIInitialized) {
221
- return;
222
- }
223
- // Enter alternate screen buffer for complete terminal control
224
- this.write(ESC.ALT_SCREEN_ENTER);
225
- // Hide cursor during setup
226
- this.write(ESC.HIDE);
227
- // Clear screen and go home (in alternate buffer)
228
- this.write(ESC.HOME);
229
- this.write(ESC.CLEAR_SCREEN);
230
- // Write banner at top
231
- let bannerLines = 0;
232
- if (this.bannerContent) {
233
- const lines = this.bannerContent.split('\n');
234
- bannerLines = lines.length + 2; // +2 for trailing \n\n
235
- process.stdout.write(this.bannerContent + '\n\n');
236
- }
237
- // Set content cursor row after banner
238
- this.contentCursorRow = bannerLines > 0 ? bannerLines + 1 : 1;
239
- // Content ends at same row initially (no content yet)
240
- this.contentEndRow = this.contentCursorRow - 1;
241
- // Mark initialized
242
- this.unifiedUIInitialized = true;
243
- // Render floating chat box below content
244
- this.renderFloatingInputArea();
245
- }
246
- /**
247
- * Clear the input area at its tracked position.
248
- * Returns true if something was cleared.
249
- */
250
- clearInputArea() {
251
- if (this.inputAreaStartRow > 0 && this.flowModeRenderedLines > 0) {
252
- for (let i = 0; i < this.flowModeRenderedLines; i++) {
253
- this.write(ESC.TO(this.inputAreaStartRow + i, 1));
254
- this.write(ESC.CLEAR_LINE);
255
- }
256
- return true;
257
- }
258
- return false;
259
- }
260
- /**
261
- * Reset input area tracking state.
262
- */
263
- resetInputAreaTracking() {
264
- this.inputAreaStartRow = 0;
265
- this.flowModeRenderedLines = 0;
266
- }
267
- /**
268
- * Render chat box - FLOATING below content (no scroll regions).
269
- * Chat box appears right after content and moves down as content grows.
270
- * Content and banner scroll naturally off the top of the screen.
271
- */
272
- renderFloatingInputArea() {
273
- const { cols, rows } = this.getSize();
274
- const layout = this.buildInputLayout(cols);
275
- // Clamp start row so the full UI stays visible, even when content exceeds viewport
276
- const chatBoxHeight = layout.lines.length;
277
- const chatBoxStartRow = Math.max(1, Math.min(this.contentEndRow + 1, rows - chatBoxHeight + 1));
278
- // Save cursor position (content writer), render, then restore to avoid disrupting output
279
- this.write(ESC.SAVE);
280
- this.write(ESC.HIDE);
281
- this.inputAreaStartRow = chatBoxStartRow;
282
- let currentRow = chatBoxStartRow;
283
- // Render each line with clearing to avoid ghosting
284
- for (const line of layout.lines) {
285
- this.write(ESC.TO(currentRow, 1));
286
- this.write(ESC.CLEAR_LINE);
287
- this.write(this.fitToWidth(line, cols));
288
- currentRow++;
289
- }
290
- this.flowModeRenderedLines = chatBoxHeight;
291
- this.lastRenderContent = this.buffer;
292
- this.lastRenderCursor = this.cursor;
293
- // Restore cursor for content writes; caret is rendered virtually inside the prompt
294
- this.write(ESC.RESTORE);
295
- this.write(ESC.SHOW);
296
- }
297
273
  /**
298
274
  * Set the input mode
299
275
  *
300
- * BOTTOM PINNED with SSE: Chat box stays at terminal bottom.
301
- * Scroll region protects chat box, content scrolls above it.
276
+ * Content flows naturally - no scroll region pinning.
302
277
  */
303
278
  setMode(mode) {
304
279
  const prevMode = this.mode;
305
280
  this.mode = mode;
306
281
  if (mode === 'streaming' && prevMode !== 'streaming') {
307
- // Track streaming start time for elapsed display
308
- this.streamingStartTime = Date.now();
309
- // Ensure unified UI is initialized
310
- if (!this.unifiedUIInitialized) {
311
- this.initializeUnifiedUI();
312
- }
313
- // Start periodic render timer to keep chat box updated during streaming
314
- // This updates contentEndRow from display and re-renders chat box
315
- if (!this.streamingRenderTimer) {
316
- this.streamingRenderTimer = setInterval(() => {
317
- // Update contentEndRow from display's line count
318
- if (this.displayRef?.getTotalWrittenLines) {
319
- const next = this.displayRef.getTotalWrittenLines();
320
- if (typeof next === 'number' && Number.isFinite(next) && next !== this.contentEndRow) {
321
- this.contentEndRow = next;
322
- this.renderDirty = true;
323
- }
324
- }
325
- // Re-render chat box at updated position
326
- if (this.renderDirty) {
327
- this.render();
328
- }
329
- }, 120); // Update periodically without overwhelming output
330
- }
331
- // Initial render
282
+ this.resetStreamingRenderThrottle();
332
283
  this.renderDirty = true;
333
- this.scheduleRender();
284
+ this.render();
334
285
  }
335
286
  else if (mode !== 'streaming' && prevMode === 'streaming') {
336
- // Stop streaming render timer
337
- if (this.streamingRenderTimer) {
338
- clearInterval(this.streamingRenderTimer);
339
- this.streamingRenderTimer = null;
340
- }
341
- // Reset streaming time
342
- this.streamingStartTime = null;
343
- // Final render with accurate position
344
- this.renderDirty = true;
345
- this.scheduleRender();
346
- }
347
- }
348
- /**
349
- * Set the row where content ends (for idle mode positioning).
350
- * Input area will render starting from this row + 1.
351
- */
352
- setContentEndRow(row) {
353
- this.contentEndRow = Math.max(0, row);
354
- this.renderDirty = true;
355
- this.scheduleRender();
356
- }
357
- /**
358
- * Set available slash commands for auto-complete suggestions.
359
- */
360
- setCommands(commands) {
361
- this.commandSuggestions = commands;
362
- this.updateSuggestions();
363
- }
364
- /**
365
- * Update filtered suggestions based on current input.
366
- */
367
- updateSuggestions() {
368
- const input = this.buffer.trim();
369
- // Only show suggestions when input starts with "/"
370
- if (!input.startsWith('/')) {
371
- this.showSuggestions = false;
372
- this.filteredSuggestions = [];
373
- this.selectedSuggestionIndex = 0;
374
- return;
375
- }
376
- const query = input.toLowerCase();
377
- this.filteredSuggestions = this.commandSuggestions.filter(cmd => cmd.command.toLowerCase().startsWith(query) ||
378
- cmd.command.toLowerCase().includes(query.slice(1)));
379
- // Show suggestions if we have matches
380
- this.showSuggestions = this.filteredSuggestions.length > 0;
381
- // Keep selection in bounds
382
- if (this.selectedSuggestionIndex >= this.filteredSuggestions.length) {
383
- this.selectedSuggestionIndex = Math.max(0, this.filteredSuggestions.length - 1);
287
+ // Streaming ended - render the input area
288
+ this.resetStreamingRenderThrottle();
289
+ this.forceRender();
384
290
  }
385
291
  }
386
292
  /**
387
- * Select next suggestion (arrow down / tab).
388
- */
389
- selectNextSuggestion() {
390
- if (!this.showSuggestions || this.filteredSuggestions.length === 0)
391
- return;
392
- this.selectedSuggestionIndex = (this.selectedSuggestionIndex + 1) % this.filteredSuggestions.length;
393
- this.renderDirty = true;
394
- this.scheduleRender();
395
- }
396
- /**
397
- * Select previous suggestion (arrow up / shift+tab).
398
- */
399
- selectPrevSuggestion() {
400
- if (!this.showSuggestions || this.filteredSuggestions.length === 0)
401
- return;
402
- this.selectedSuggestionIndex = this.selectedSuggestionIndex === 0
403
- ? this.filteredSuggestions.length - 1
404
- : this.selectedSuggestionIndex - 1;
405
- this.renderDirty = true;
406
- this.scheduleRender();
407
- }
408
- /**
409
- * Accept current suggestion and insert into buffer.
410
- */
411
- acceptSuggestion() {
412
- if (!this.showSuggestions || this.filteredSuggestions.length === 0)
413
- return false;
414
- const selected = this.filteredSuggestions[this.selectedSuggestionIndex];
415
- if (!selected)
416
- return false;
417
- // Replace buffer with selected command
418
- this.buffer = selected.command + ' ';
419
- this.cursor = this.buffer.length;
420
- this.showSuggestions = false;
421
- this.renderDirty = true;
422
- this.scheduleRender();
423
- return true;
424
- }
425
- /**
426
- * Check if suggestions are visible.
427
- */
428
- areSuggestionsVisible() {
429
- return this.showSuggestions && this.filteredSuggestions.length > 0;
430
- }
431
- /**
432
- * Toggle thinking/reasoning mode
433
- */
434
- toggleThinking() {
435
- this.thinkingEnabled = !this.thinkingEnabled;
436
- this.emit('thinkingToggle', this.thinkingEnabled);
437
- this.scheduleRender();
438
- }
439
- /**
440
- * Get thinking enabled state
293
+ * Legacy method - no longer used (content flows naturally).
294
+ * @deprecated Use setContentRow instead
441
295
  */
442
- isThinkingEnabled() {
443
- return this.thinkingEnabled;
296
+ setPinnedHeaderLines(_count) {
297
+ // No-op: scroll region pinning removed
444
298
  }
445
299
  /**
446
300
  * Get current mode
@@ -473,17 +327,14 @@ export class TerminalInput extends EventEmitter {
473
327
  }
474
328
  /**
475
329
  * Clear the buffer
476
- * @param skipRender - If true, don't trigger a re-render (used during submit flow)
477
330
  */
478
- clear(skipRender = false) {
331
+ clear() {
479
332
  this.buffer = '';
480
333
  this.cursor = 0;
481
334
  this.historyIndex = -1;
482
335
  this.tempInput = '';
483
336
  this.pastePlaceholders = [];
484
- if (!skipRender) {
485
- this.scheduleRender();
486
- }
337
+ this.scheduleRender();
487
338
  }
488
339
  /**
489
340
  * Get queued inputs
@@ -554,6 +405,37 @@ export class TerminalInput extends EventEmitter {
554
405
  this.streamingLabel = next;
555
406
  this.scheduleRender();
556
407
  }
408
+ /**
409
+ * Surface meta status just above the divider (e.g., elapsed time or token usage).
410
+ */
411
+ setMetaStatus(meta) {
412
+ const nextElapsed = typeof meta.elapsedSeconds === 'number' && Number.isFinite(meta.elapsedSeconds) && meta.elapsedSeconds >= 0
413
+ ? Math.floor(meta.elapsedSeconds)
414
+ : null;
415
+ const nextTokens = typeof meta.tokensUsed === 'number' && Number.isFinite(meta.tokensUsed) && meta.tokensUsed >= 0
416
+ ? Math.floor(meta.tokensUsed)
417
+ : null;
418
+ const nextLimit = typeof meta.tokenLimit === 'number' && Number.isFinite(meta.tokenLimit) && meta.tokenLimit > 0
419
+ ? Math.floor(meta.tokenLimit)
420
+ : null;
421
+ const nextThinking = typeof meta.thinkingMs === 'number' && Number.isFinite(meta.thinkingMs) && meta.thinkingMs >= 0
422
+ ? Math.floor(meta.thinkingMs)
423
+ : null;
424
+ const nextThinkingHasContent = !!meta.thinkingHasContent;
425
+ if (this.metaElapsedSeconds === nextElapsed &&
426
+ this.metaTokensUsed === nextTokens &&
427
+ this.metaTokenLimit === nextLimit &&
428
+ this.metaThinkingMs === nextThinking &&
429
+ this.metaThinkingHasContent === nextThinkingHasContent) {
430
+ return;
431
+ }
432
+ this.metaElapsedSeconds = nextElapsed;
433
+ this.metaTokensUsed = nextTokens;
434
+ this.metaTokenLimit = nextLimit;
435
+ this.metaThinkingMs = nextThinking;
436
+ this.metaThinkingHasContent = nextThinkingHasContent;
437
+ this.scheduleRender();
438
+ }
557
439
  /**
558
440
  * Keep mode toggles (verification/auto-continue) visible in the control bar.
559
441
  * Hotkey labels remain stable so the bar looks the same before/during streaming.
@@ -563,26 +445,22 @@ export class TerminalInput extends EventEmitter {
563
445
  const nextAutoContinue = !!options.autoContinueEnabled;
564
446
  const nextVerifyHotkey = options.verificationHotkey ?? this.verificationHotkey;
565
447
  const nextAutoHotkey = options.autoContinueHotkey ?? this.autoContinueHotkey;
448
+ const nextThinkingHotkey = options.thinkingHotkey ?? this.thinkingHotkey;
449
+ const nextThinkingLabel = options.thinkingModeLabel === undefined ? this.thinkingModeLabel : (options.thinkingModeLabel || null);
566
450
  if (this.verificationEnabled === nextVerification &&
567
451
  this.autoContinueEnabled === nextAutoContinue &&
568
452
  this.verificationHotkey === nextVerifyHotkey &&
569
- this.autoContinueHotkey === nextAutoHotkey) {
453
+ this.autoContinueHotkey === nextAutoHotkey &&
454
+ this.thinkingHotkey === nextThinkingHotkey &&
455
+ this.thinkingModeLabel === nextThinkingLabel) {
570
456
  return;
571
457
  }
572
458
  this.verificationEnabled = nextVerification;
573
459
  this.autoContinueEnabled = nextAutoContinue;
574
460
  this.verificationHotkey = nextVerifyHotkey;
575
461
  this.autoContinueHotkey = nextAutoHotkey;
576
- this.scheduleRender();
577
- }
578
- /**
579
- * Set the model info string (e.g., "OpenAI · gpt-4")
580
- * This is displayed persistently above the input area.
581
- */
582
- setModelInfo(info) {
583
- if (this.modelInfo === info)
584
- return;
585
- this.modelInfo = info;
462
+ this.thinkingHotkey = nextThinkingHotkey;
463
+ this.thinkingModeLabel = nextThinkingLabel;
586
464
  this.scheduleRender();
587
465
  }
588
466
  /**
@@ -595,33 +473,174 @@ export class TerminalInput extends EventEmitter {
595
473
  this.scheduleRender();
596
474
  }
597
475
  /**
598
- * Render the input area.
599
- * During streaming: renders at terminal bottom (with scroll region)
600
- * After streaming: renders floating below content
476
+ * Surface model/provider context in the controls bar.
477
+ */
478
+ setModelContext(options) {
479
+ const nextModel = options.model?.trim() || null;
480
+ const nextProvider = options.provider?.trim() || null;
481
+ if (this.modelLabel === nextModel && this.providerLabel === nextProvider) {
482
+ return;
483
+ }
484
+ this.modelLabel = nextModel;
485
+ this.providerLabel = nextProvider;
486
+ this.scheduleRender();
487
+ }
488
+ /**
489
+ * Render the floating input area at contentRow.
490
+ *
491
+ * The chat box "floats" - it renders right below the last streamed content.
492
+ * As content is added, contentRow advances, and the chat box moves down.
493
+ * No scroll regions - pure floating behavior.
601
494
  */
602
495
  render() {
603
496
  if (!this.canRender())
604
497
  return;
605
498
  if (this.isRendering)
606
499
  return;
500
+ const streamingActive = this.mode === 'streaming' || isStreamingMode();
501
+ // During streaming, throttle re-renders
502
+ if (streamingActive && this.lastStreamingRender > 0) {
503
+ const elapsed = Date.now() - this.lastStreamingRender;
504
+ const waitMs = Math.max(0, this.streamingRenderInterval - elapsed);
505
+ if (waitMs > 0) {
506
+ this.renderDirty = true;
507
+ this.scheduleStreamingRender(waitMs);
508
+ return;
509
+ }
510
+ }
607
511
  const shouldSkip = !this.renderDirty &&
608
512
  this.buffer === this.lastRenderContent &&
609
513
  this.cursor === this.lastRenderCursor;
610
514
  this.renderDirty = false;
611
- // Skip if nothing changed (unless explicitly forced)
612
515
  if (shouldSkip) {
613
516
  return;
614
517
  }
615
- // If write lock is held, defer render
616
518
  if (writeLock.isLocked()) {
617
519
  writeLock.safeWrite(() => this.render());
618
520
  return;
619
521
  }
522
+ this.renderPinnedChatBox();
523
+ }
524
+ /**
525
+ * Unified scroll region renderer.
526
+ * Chat box is ALWAYS pinned at the bottom of the terminal.
527
+ * Content scrolls in the region above the chat box.
528
+ */
529
+ renderPinnedChatBox() {
530
+ const { rows, cols } = this.getSize();
531
+ const maxWidth = Math.max(8, cols - 4);
532
+ const streamingActive = this.mode === 'streaming' || isStreamingMode();
533
+ // Wrap buffer into display lines
534
+ const { lines, cursorLine, cursorCol } = this.wrapBuffer(maxWidth);
535
+ const maxVisible = Math.max(1, Math.min(this.config.maxLines, rows - 3));
536
+ const displayLines = Math.min(lines.length, maxVisible);
537
+ const metaLines = this.buildMetaLines(cols - 2);
538
+ // Calculate display window (keep cursor visible)
539
+ let startLine = 0;
540
+ if (lines.length > displayLines) {
541
+ startLine = Math.max(0, cursorLine - displayLines + 1);
542
+ startLine = Math.min(startLine, lines.length - displayLines);
543
+ }
544
+ const visibleLines = lines.slice(startLine, startLine + displayLines);
545
+ const adjustedCursorLine = cursorLine - startLine;
546
+ // Chat box height
547
+ const chatBoxHeight = this.getChatBoxHeight();
548
+ // ALWAYS pin chat box at absolute bottom
549
+ const chatBoxStartRow = Math.max(1, rows - chatBoxHeight + 1);
550
+ const scrollEnd = chatBoxStartRow - 1;
551
+ writeLock.lock('terminalInput.renderPinned');
620
552
  this.isRendering = true;
621
- writeLock.lock('terminalInput.render');
622
553
  try {
623
- // Always render floating right after content (no wasted space)
624
- this.renderFloatingInputArea();
554
+ this.write(ESC.SAVE);
555
+ this.write(ESC.HIDE);
556
+ // Temporarily reset scroll region to write chat box cleanly
557
+ if (this.scrollRegionActive) {
558
+ this.write(ESC.RESET_SCROLL);
559
+ }
560
+ // Clear the chat box area
561
+ for (let i = 0; i < chatBoxHeight; i++) {
562
+ const row = chatBoxStartRow + i;
563
+ if (row <= rows) {
564
+ this.write(ESC.TO(row, 1));
565
+ this.write(ESC.CLEAR_LINE);
566
+ }
567
+ }
568
+ let currentRow = chatBoxStartRow;
569
+ // Render scroll/status indicator on the left (Claude Code style)
570
+ const scrollIndicator = this.buildScrollIndicator();
571
+ // Meta/status header with scroll indicator
572
+ for (const metaLine of metaLines) {
573
+ this.write(ESC.TO(currentRow, 1));
574
+ this.write(metaLine);
575
+ currentRow += 1;
576
+ }
577
+ // Separator line with scroll status
578
+ this.write(ESC.TO(currentRow, 1));
579
+ const dividerLabel = scrollIndicator || undefined;
580
+ this.write(renderDivider(cols - 2, dividerLabel));
581
+ currentRow += 1;
582
+ // Render input lines
583
+ let finalRow = currentRow;
584
+ let finalCol = 3;
585
+ for (let i = 0; i < visibleLines.length; i++) {
586
+ const rowNum = currentRow + i;
587
+ this.write(ESC.TO(rowNum, 1));
588
+ const line = visibleLines[i] ?? '';
589
+ const isFirstLine = (startLine + i) === 0;
590
+ const isCursorLine = i === adjustedCursorLine;
591
+ this.write(ESC.BG_DARK);
592
+ this.write(ESC.DIM);
593
+ this.write(isFirstLine ? this.config.promptChar : this.config.continuationChar);
594
+ this.write(ESC.RESET);
595
+ this.write(ESC.BG_DARK);
596
+ if (isCursorLine) {
597
+ const col = Math.min(cursorCol, line.length);
598
+ const before = line.slice(0, col);
599
+ const at = col < line.length ? line[col] : ' ';
600
+ const after = col < line.length ? line.slice(col + 1) : '';
601
+ this.write(before);
602
+ this.write(ESC.REVERSE + ESC.BOLD);
603
+ this.write(at);
604
+ this.write(ESC.RESET + ESC.BG_DARK);
605
+ this.write(after);
606
+ finalRow = rowNum;
607
+ finalCol = this.config.promptChar.length + col + 1;
608
+ }
609
+ else {
610
+ this.write(line);
611
+ }
612
+ // Pad to edge
613
+ const lineLen = this.config.promptChar.length + line.length + (isCursorLine && cursorCol >= line.length ? 1 : 0);
614
+ const padding = Math.max(0, cols - lineLen - 1);
615
+ if (padding > 0)
616
+ this.write(' '.repeat(padding));
617
+ this.write(ESC.RESET);
618
+ }
619
+ // Mode controls line with all keyboard shortcuts
620
+ const controlRow = currentRow + visibleLines.length;
621
+ this.write(ESC.TO(controlRow, 1));
622
+ this.write(this.buildModeControls(cols));
623
+ // Restore scroll region and cursor
624
+ if (this.scrollRegionActive) {
625
+ // Restore scroll region
626
+ this.write(ESC.SET_SCROLL(1, scrollEnd));
627
+ // Restore cursor to where it was before rendering (preserves column position)
628
+ this.write(ESC.RESTORE);
629
+ }
630
+ else {
631
+ // Not streaming - position cursor in input box
632
+ this.write(ESC.RESTORE);
633
+ this.write(ESC.TO(finalRow, Math.min(finalCol, cols)));
634
+ }
635
+ this.write(ESC.SHOW);
636
+ // Update state
637
+ this.lastRenderContent = this.buffer;
638
+ this.lastRenderCursor = this.cursor;
639
+ this.lastStreamingRender = streamingActive ? Date.now() : 0;
640
+ if (this.streamingRenderTimer) {
641
+ clearTimeout(this.streamingRenderTimer);
642
+ this.streamingRenderTimer = null;
643
+ }
625
644
  }
626
645
  finally {
627
646
  writeLock.unlock();
@@ -629,211 +648,169 @@ export class TerminalInput extends EventEmitter {
629
648
  }
630
649
  }
631
650
  /**
632
- * Build the structured input layout according to the UI schema.
651
+ * Build compact meta line above the divider.
652
+ * Shows model/provider and key metrics in a single line.
633
653
  */
634
- buildInputLayout(cols) {
635
- const width = Math.min(cols, Math.max(DEFAULT_UI_CONFIG.banner.minWidth, Math.min(DEFAULT_UI_CONFIG.banner.maxWidth, cols)));
636
- const lines = [];
637
- lines.push(this.buildStatusBar(width));
638
- lines.push(this.buildDivider(width));
639
- lines.push(...this.buildInputLines(width));
640
- const suggestions = this.buildSuggestions(width);
641
- if (suggestions.length > 0) {
642
- lines.push(...suggestions);
643
- }
644
- lines.push(this.buildDivider(width));
645
- lines.push(this.buildModeControls(width));
646
- return { lines };
647
- }
648
- buildDivider(width) {
649
- const lineWidth = Math.max(8, Math.min(width, DEFAULT_UI_CONFIG.banner.maxWidth));
650
- return `${UI_COLORS.dim}${DEFAULT_UI_CONFIG.divider.char.repeat(lineWidth)}${UI_COLORS.reset}`;
651
- }
652
- buildInputLines(width) {
653
- const prompt = `${UI_COLORS.dim}${this.config.promptChar}${UI_COLORS.reset}`;
654
- const continuation = `${UI_COLORS.dim}${this.config.continuationChar}${UI_COLORS.reset}`;
655
- const promptWidth = this.visibleLength(prompt);
656
- const textWidth = Math.max(1, width - promptWidth);
657
- const { lines, cursorLine, cursorCol } = this.wrapBuffer(textWidth);
658
- const maxLines = Math.max(1, this.config.maxLines);
659
- const startLine = Math.max(0, lines.length - maxLines);
660
- const visibleLines = lines.slice(startLine);
661
- const caretLine = Math.max(0, cursorLine - startLine);
662
- if (!visibleLines.length) {
663
- visibleLines.push('');
664
- }
665
- return visibleLines.map((lineText, index) => {
666
- const hasCursor = caretLine === index;
667
- const cursorIndex = hasCursor ? cursorCol : null;
668
- const prefix = index === 0 ? prompt : continuation;
669
- return this.renderPromptLine(prefix, lineText, cursorIndex, textWidth, width);
670
- });
671
- }
672
- buildSuggestions(width) {
673
- if (!this.areSuggestionsVisible()) {
654
+ buildMetaLines(width) {
655
+ const leftParts = [];
656
+ const rightParts = [];
657
+ // Model/provider info (left side)
658
+ if (this.modelLabel) {
659
+ const modelText = this.providerLabel
660
+ ? `${this.modelLabel} @ ${this.providerLabel}`
661
+ : this.modelLabel;
662
+ leftParts.push({ text: modelText, tone: 'info' });
663
+ }
664
+ // Elapsed time (right side)
665
+ if (this.metaElapsedSeconds !== null) {
666
+ rightParts.push({ text: `⏱ ${this.formatElapsedLabel(this.metaElapsedSeconds)}`, tone: 'muted' });
667
+ }
668
+ // Token usage (right side)
669
+ if (this.metaTokensUsed !== null) {
670
+ const formattedUsed = this.formatTokenCount(this.metaTokensUsed);
671
+ const formattedLimit = this.metaTokenLimit ? `/${this.formatTokenCount(this.metaTokenLimit)}` : '';
672
+ rightParts.push({ text: `⊛ ${formattedUsed}${formattedLimit}`, tone: 'muted' });
673
+ }
674
+ // Context remaining warning
675
+ const tokensRemaining = this.computeTokensRemaining();
676
+ if (tokensRemaining !== null) {
677
+ const contextPct = this.contextUsage !== null ? `${100 - this.contextUsage}%` : '';
678
+ rightParts.push({ text: `↓${tokensRemaining} ${contextPct}`, tone: this.contextUsage && this.contextUsage > 80 ? 'warn' : 'muted' });
679
+ }
680
+ // Thinking indicator
681
+ if (this.metaThinkingMs !== null) {
682
+ leftParts.push({ text: formatThinking(this.metaThinkingMs, this.metaThinkingHasContent), tone: 'info' });
683
+ }
684
+ if (!leftParts.length && !rightParts.length) {
674
685
  return [];
675
686
  }
676
- const lines = [];
677
- const maxSuggestions = Math.min(3, this.filteredSuggestions.length);
678
- lines.push(this.fitToWidth(`${UI_COLORS.dim}Suggestions${UI_COLORS.reset}`, width));
679
- for (let i = 0; i < maxSuggestions; i++) {
680
- const suggestion = this.filteredSuggestions[i];
681
- if (!suggestion)
682
- continue;
683
- const isSelected = i === this.selectedSuggestionIndex;
684
- const bullet = isSelected ? `${UI_COLORS.cyan}›${UI_COLORS.reset}` : `${UI_COLORS.dim}·${UI_COLORS.reset}`;
685
- const body = `${suggestion.command} ${UI_COLORS.dim}${suggestion.description}${UI_COLORS.reset}`.trim();
686
- lines.push(this.fitToWidth(`${bullet} ${body}`, width));
687
- }
688
- return lines;
689
- }
690
- renderPromptLine(prefix, text, cursorCol, textWidth, totalWidth) {
691
- const visibleTextWidth = Math.max(1, textWidth);
692
- const padded = (text ?? '').slice(0, visibleTextWidth).padEnd(visibleTextWidth, ' ');
693
- let rendered = padded;
694
- if (cursorCol !== null && cursorCol >= 0) {
695
- const safeCol = Math.max(0, Math.min(cursorCol, Math.max(0, visibleTextWidth - 1)));
696
- const before = padded.slice(0, safeCol);
697
- const caretChar = padded[safeCol] ?? ' ';
698
- const after = padded.slice(safeCol + 1);
699
- rendered = `${before}${UI_COLORS.reverse}${caretChar || ' '}${UI_COLORS.reset}${after}`;
700
- }
701
- return this.fitToWidth(`${prefix}${rendered}`, totalWidth);
687
+ // Render left and right aligned
688
+ if (!rightParts.length || width < 50) {
689
+ return [renderStatusLine([...leftParts, ...rightParts], width)];
690
+ }
691
+ const leftWidth = Math.max(12, Math.floor(width * 0.5));
692
+ const rightWidth = Math.max(14, width - leftWidth - 1);
693
+ const leftText = renderStatusLine(leftParts, leftWidth);
694
+ const rightText = renderStatusLine(rightParts, rightWidth);
695
+ const spacing = Math.max(1, width - this.visibleLength(leftText) - this.visibleLength(rightText));
696
+ return [`${leftText}${' '.repeat(spacing)}${rightText}`];
702
697
  }
703
- visibleLength(value) {
704
- return value.replace(/\x1b\[[0-9;]*m/g, '').length;
698
+ /**
699
+ * Build mode controls line with all keyboard shortcuts and toggle states.
700
+ * Shows below the chat box input area.
701
+ */
702
+ buildModeControls(cols) {
703
+ const width = Math.max(8, cols - 2);
704
+ const parts = [];
705
+ // Streaming status
706
+ if (this.streamingLabel) {
707
+ parts.push({ text: `◐ ${this.streamingLabel}`, tone: 'info' });
708
+ parts.push({ text: `[Esc]stop`, tone: 'warn' });
709
+ }
710
+ // All keyboard shortcuts with toggle states
711
+ const editIcon = this.editMode === 'display-edits' ? '✓' : '?';
712
+ const editTone = this.editMode === 'display-edits' ? 'success' : 'muted';
713
+ parts.push({ text: `[⇧Tab]edits${editIcon}`, tone: editTone });
714
+ const verifyIcon = this.verificationEnabled ? '✓' : '○';
715
+ const verifyTone = this.verificationEnabled ? 'success' : 'muted';
716
+ parts.push({ text: `[⌥V]verify${verifyIcon}`, tone: verifyTone });
717
+ const autoIcon = this.autoContinueEnabled ? '✓' : '○';
718
+ const autoTone = this.autoContinueEnabled ? 'success' : 'muted';
719
+ parts.push({ text: `[⌥C]auto${autoIcon}`, tone: autoTone });
720
+ // Additional shortcuts
721
+ parts.push({ text: `[⌥X]clear`, tone: 'muted' });
722
+ parts.push({ text: `[PgUp/Dn]scroll`, tone: 'muted' });
723
+ // Context remaining (show when relevant)
724
+ const contextRemaining = this.computeContextRemaining();
725
+ if (contextRemaining !== null) {
726
+ const tone = contextRemaining <= 10 ? 'warn' : contextRemaining <= 30 ? 'info' : 'muted';
727
+ parts.push({ text: `${contextRemaining}%ctx`, tone });
728
+ }
729
+ return renderStatusLine(parts, width);
730
+ }
731
+ formatHotkey(hotkey) {
732
+ const normalized = hotkey.trim().toLowerCase();
733
+ if (!normalized)
734
+ return hotkey;
735
+ const parts = normalized.split('+').filter(Boolean);
736
+ // Use readable key names instead of symbols for better terminal compatibility
737
+ const map = {
738
+ shift: 'Shift',
739
+ sh: 'Shift',
740
+ alt: 'Alt',
741
+ option: 'Alt',
742
+ opt: 'Alt',
743
+ ctrl: 'Ctrl',
744
+ control: 'Ctrl',
745
+ cmd: 'Cmd',
746
+ meta: 'Cmd',
747
+ esc: 'Esc',
748
+ escape: 'Esc',
749
+ tab: 'Tab',
750
+ return: 'Enter',
751
+ enter: 'Enter',
752
+ pageup: 'PgUp',
753
+ pagedown: 'PgDn',
754
+ home: 'Home',
755
+ end: 'End',
756
+ };
757
+ const formatted = parts
758
+ .map((part) => {
759
+ const label = map[part];
760
+ if (label)
761
+ return label;
762
+ return part.length === 1 ? part.toUpperCase() : part.charAt(0).toUpperCase() + part.slice(1);
763
+ })
764
+ .join('+');
765
+ return `[${formatted}]`;
705
766
  }
706
- fitToWidth(value, width) {
707
- const target = Math.max(1, width);
708
- const visible = this.visibleLength(value);
709
- if (visible === target) {
710
- return value;
767
+ computeContextRemaining() {
768
+ if (this.contextUsage === null) {
769
+ return null;
711
770
  }
712
- if (visible < target) {
713
- return `${value}${' '.repeat(target - visible)}`;
714
- }
715
- return this.truncateToWidth(value, target);
771
+ return Math.max(0, this.contextAutoCompactThreshold - this.contextUsage);
716
772
  }
717
- truncateToWidth(value, width) {
718
- const target = Math.max(0, width);
719
- let visible = 0;
720
- let result = '';
721
- for (let i = 0; i < value.length && visible < target; i++) {
722
- const char = value[i];
723
- if (char === '\x1b') {
724
- const match = value.slice(i).match(/^\x1b\[[0-9;]*[A-Za-z]/);
725
- if (match) {
726
- result += match[0];
727
- i += match[0].length - 1;
728
- continue;
729
- }
730
- }
731
- result += char;
732
- visible += 1;
733
- }
734
- if (value.includes('\x1b') && !result.endsWith(UI_COLORS.reset)) {
735
- result += UI_COLORS.reset;
773
+ computeTokensRemaining() {
774
+ if (this.metaTokensUsed === null || this.metaTokenLimit === null) {
775
+ return null;
736
776
  }
737
- return result;
777
+ const remaining = Math.max(0, this.metaTokenLimit - this.metaTokensUsed);
778
+ return this.formatTokenCount(remaining);
738
779
  }
739
- /**
740
- * Build status bar showing streaming/ready status and key info.
741
- * This is the TOP line above the input area - minimal Claude Code style.
742
- */
743
- buildStatusBar(width) {
744
- const { green: GREEN, yellow: YELLOW, cyan: CYAN, dim: DIM, reset: R } = UI_COLORS;
745
- const segments = [];
746
- // Streaming status with elapsed time
747
- if (this.mode === 'streaming' || this.streamingLabel) {
748
- let label = this.streamingLabel || 'Streaming';
749
- if (this.streamingStartTime) {
750
- const elapsed = Math.max(0, Math.floor((Date.now() - this.streamingStartTime) / 1000));
751
- const mins = Math.floor(elapsed / 60);
752
- const secs = elapsed % 60;
753
- const elapsedLabel = mins > 0 ? `${mins}m ${secs}s` : `${secs}s`;
754
- label = `${label} ${elapsedLabel}`;
755
- }
756
- segments.push(`${GREEN}● ${label}${R}`);
757
- }
758
- // Override/warning status
759
- if (this.overrideStatusMessage) {
760
- segments.push(`${YELLOW}⚠ ${this.overrideStatusMessage}${R}`);
761
- }
762
- // Primary status message
763
- if (this.statusMessage) {
764
- segments.push(`${CYAN}${this.statusMessage}${R}`);
765
- }
766
- // Queue + paste indicators
767
- if (this.mode === 'streaming' && this.queue.length > 0) {
768
- segments.push(`${CYAN}queued ${this.queue.length}${R}`);
780
+ formatElapsedLabel(seconds) {
781
+ if (seconds < 60) {
782
+ return `${seconds}s`;
769
783
  }
770
- if (this.pastePlaceholders.length > 0) {
771
- const totalLines = this.pastePlaceholders.reduce((sum, p) => sum + p.lineCount, 0);
772
- segments.push(`${CYAN}📋 ${totalLines}L${R}`);
773
- }
774
- // Model info for quick glance
775
- if (this.modelInfo) {
776
- segments.push(`${DIM}${this.modelInfo}${R}`);
784
+ const mins = Math.floor(seconds / 60);
785
+ const secs = seconds % 60;
786
+ return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
787
+ }
788
+ formatTokenCount(value) {
789
+ if (!Number.isFinite(value)) {
790
+ return `${value}`;
777
791
  }
778
- // Default hint when idle
779
- if (!segments.length) {
780
- segments.push(`${DIM}Type a message or / for commands${R}`);
792
+ if (value >= 1_000_000) {
793
+ return `${(value / 1_000_000).toFixed(1)}M`;
781
794
  }
782
- // Multi-line indicator
783
- if (this.buffer.includes('\n')) {
784
- segments.push(`${DIM}${this.buffer.split('\n').length}L${R}`);
795
+ if (value >= 1_000) {
796
+ return `${(value / 1_000).toFixed(1)}k`;
785
797
  }
786
- const joined = segments.join(`${DIM} · ${R}`);
787
- return this.fitToWidth(joined, width);
798
+ return `${Math.round(value)}`;
799
+ }
800
+ visibleLength(value) {
801
+ const ansiPattern = /\u001B\[[0-?]*[ -/]*[@-~]/g;
802
+ return value.replace(ansiPattern, '').length;
788
803
  }
789
804
  /**
790
- * Build mode controls line showing toggles and context info.
791
- * This is the BOTTOM line below the input area - Claude Code style layout with erosolar features.
792
- *
793
- * Layout: [toggles on left] ... [context info on right]
805
+ * Debug-only snapshot used by tests to assert rendered strings without
806
+ * needing a TTY. Not used by production code.
794
807
  */
795
- buildModeControls(cols) {
796
- const maxWidth = Math.max(10, cols - 2);
797
- // Use schema-defined colors for consistency
798
- const { green: GREEN, yellow: YELLOW, cyan: CYAN, magenta: MAGENTA, red: RED, dim: DIM, reset: R } = UI_COLORS;
799
- // Mode toggles with colors (following ModeControlsSchema)
800
- const toggles = [];
801
- // Edit mode (green=auto, yellow=ask) - per schema.editMode
802
- if (this.editMode === 'display-edits') {
803
- toggles.push(`${GREEN}⏵⏵ auto-edit${R}`);
804
- }
805
- else {
806
- toggles.push(`${YELLOW}⏸⏸ ask-first${R}`);
807
- }
808
- // Thinking mode (cyan when on) - per schema.thinkingMode
809
- toggles.push(this.thinkingEnabled ? `${CYAN}💭 think${R}` : `${DIM}○ think${R}`);
810
- // Verification (green when on) - per schema.verificationMode
811
- toggles.push(this.verificationEnabled ? `${GREEN}✓ verify${R}` : `${DIM}○ verify${R}`);
812
- // Auto-continue (magenta when on) - per schema.autoContinueMode
813
- toggles.push(this.autoContinueEnabled ? `${MAGENTA}↻ auto${R}` : `${DIM}○ auto${R}`);
814
- const leftPart = toggles.join(`${DIM} · ${R}`) + `${DIM} (⇧⇥)${R}`;
815
- // Context usage with color - per schema.contextUsage thresholds
816
- const rightParts = [];
817
- if (this.contextUsage !== null) {
818
- const rem = Math.max(0, 100 - this.contextUsage);
819
- if (rem < 10)
820
- rightParts.push(`${RED}⚠ ctx: ${rem}%${R}`);
821
- else if (rem < 25)
822
- rightParts.push(`${YELLOW}! ctx: ${rem}%${R}`);
823
- else
824
- rightParts.push(`${DIM}ctx: ${rem}%${R}`);
825
- }
826
- if (this.modelInfo) {
827
- rightParts.push(`${DIM}${this.modelInfo}${R}`);
828
- }
829
- const rightPart = rightParts.join(`${DIM} · ${R}`);
830
- const leftLen = this.visibleLength(leftPart);
831
- const rightLen = this.visibleLength(rightPart);
832
- if (rightPart && leftLen + rightLen < maxWidth - 2) {
833
- return `${leftPart}${' '.repeat(Math.max(1, maxWidth - leftLen - rightLen))}${rightPart}`;
834
- }
835
- const combined = rightPart ? `${leftPart}${DIM} · ${R}${rightPart}` : leftPart;
836
- return this.fitToWidth(combined, maxWidth);
808
+ getDebugUiSnapshot(width) {
809
+ const cols = Math.max(8, width ?? this.getSize().cols);
810
+ return {
811
+ meta: this.buildMetaLines(cols - 2),
812
+ controls: this.buildModeControls(cols),
813
+ };
837
814
  }
838
815
  /**
839
816
  * Force a re-render
@@ -856,65 +833,224 @@ export class TerminalInput extends EventEmitter {
856
833
  handleResize() {
857
834
  this.lastRenderContent = '';
858
835
  this.lastRenderCursor = -1;
859
- this.scheduleRender();
836
+ this.resetStreamingRenderThrottle();
837
+ // If in scrollback mode, re-render the scrollback view with new dimensions
838
+ if (this.isInScrollbackMode) {
839
+ this.renderScrollbackView();
840
+ }
841
+ else {
842
+ this.scheduleRender();
843
+ }
860
844
  }
861
- // Track current content row for writing
862
- contentCursorRow = 1;
863
- /**
864
- * Register with display's output interceptor.
865
- * Clears chat box before writes, re-renders after with updated position.
866
- */
867
- registerOutputInterceptor(display) {
868
- if (this.outputInterceptorCleanup) {
869
- this.outputInterceptorCleanup();
870
- }
871
- // Store display reference for streaming timer to use
872
- this.displayRef = display;
873
- // Clear chat box before writes to make room for content
874
- // Re-render is done via periodic timer during streaming, or setContentEndRow after
875
- this.outputInterceptorCleanup = display.registerOutputInterceptor({
876
- beforeWrite: () => {
877
- // Clear chat box to make room for content
878
- this.clearInputArea();
879
- },
880
- afterWrite: () => {
881
- if (this.mode !== 'streaming') {
882
- if (this.displayRef?.getTotalWrittenLines) {
883
- const next = this.displayRef.getTotalWrittenLines();
884
- if (typeof next === 'number' && Number.isFinite(next)) {
885
- this.contentEndRow = next;
886
- }
887
- }
888
- this.renderDirty = true;
889
- queueMicrotask(() => this.render());
890
- }
891
- },
892
- });
845
+ /**
846
+ * Enter streaming mode with scroll region.
847
+ * Sets up terminal scroll region to exclude chat box.
848
+ */
849
+ enterStreamingScrollRegion() {
850
+ const { rows } = this.getSize();
851
+ const chatBoxHeight = this.getChatBoxHeight();
852
+ const scrollEnd = Math.max(1, rows - chatBoxHeight);
853
+ writeLock.lock('enterStreamingScrollRegion');
854
+ try {
855
+ // Set scroll region for content area (above chat box)
856
+ this.write(ESC.SET_SCROLL(1, scrollEnd));
857
+ // Position cursor at current content row
858
+ this.write(ESC.TO(Math.min(this.contentRow, scrollEnd), 1));
859
+ this.scrollRegionActive = true;
860
+ this.setStatusMessage('esc to interrupt');
861
+ }
862
+ finally {
863
+ writeLock.unlock();
864
+ }
865
+ // Render pinned chat box at bottom
866
+ this.forceRender();
893
867
  }
894
868
  /**
895
- * Dispose and clean up
869
+ * Exit streaming mode and restore normal operation.
896
870
  */
897
- dispose() {
898
- if (this.disposed)
871
+ exitStreamingScrollRegion() {
872
+ writeLock.lock('exitStreamingScrollRegion');
873
+ try {
874
+ // Reset scroll region to full terminal
875
+ this.write(ESC.RESET_SCROLL);
876
+ this.scrollRegionActive = false;
877
+ this.setStatusMessage('Ready for prompts');
878
+ }
879
+ finally {
880
+ writeLock.unlock();
881
+ }
882
+ // Final render
883
+ this.forceRender();
884
+ }
885
+ /**
886
+ * Render chat box at bottom - now uses unified renderer.
887
+ * @deprecated Use renderPinnedChatBox() directly via render()/forceRender()
888
+ */
889
+ renderChatBoxAtBottom() {
890
+ this.renderPinnedChatBox();
891
+ }
892
+ /**
893
+ * Stream content within the scroll region.
894
+ * Content is written directly and scrolls naturally.
895
+ */
896
+ streamContent(content) {
897
+ if (!content)
899
898
  return;
900
- // Clean up streaming render timer
901
- if (this.streamingRenderTimer) {
902
- clearInterval(this.streamingRenderTimer);
903
- this.streamingRenderTimer = null;
899
+ // Capture content in scrollback buffer
900
+ this.addToScrollback(content);
901
+ writeLock.lock('streamContent');
902
+ try {
903
+ // Write content - scroll region handles scrolling
904
+ this.write(content);
905
+ // Track newlines
906
+ const newlines = (content.match(/\n/g) || []).length;
907
+ this.contentRow += newlines;
904
908
  }
905
- // Clean up output interceptor
906
- if (this.outputInterceptorCleanup) {
907
- this.outputInterceptorCleanup();
908
- this.outputInterceptorCleanup = undefined;
909
+ finally {
910
+ writeLock.unlock();
909
911
  }
910
- // Reset scroll region
911
- this.write('\x1b[r');
912
- // Exit alternate screen buffer (restores main terminal)
913
- if (this.unifiedUIInitialized) {
914
- this.write(ESC.ALT_SCREEN_EXIT);
912
+ // Throttle chat box updates during streaming
913
+ this.scheduleStreamingRender(200);
914
+ }
915
+ /**
916
+ * Enable scroll region (no-op in floating mode).
917
+ */
918
+ enableScrollRegion() {
919
+ // No-op: using pure floating approach
920
+ }
921
+ /**
922
+ * Disable scroll region (no-op in floating mode).
923
+ */
924
+ disableScrollRegion() {
925
+ // No-op: using pure floating approach
926
+ }
927
+ /**
928
+ * Calculate chat box height.
929
+ */
930
+ getChatBoxHeight() {
931
+ return 5; // Fixed: divider + input + status + buffer
932
+ }
933
+ /**
934
+ * @deprecated Use streamContent() instead
935
+ * Register with display's output interceptor - kept for backwards compatibility
936
+ */
937
+ registerOutputInterceptor(_display) {
938
+ // No-op: Use streamContent() for cleaner floating chat box behavior
939
+ }
940
+ /**
941
+ * Write content above the floating chat box.
942
+ * Works both during streaming and when idle.
943
+ */
944
+ writeToScrollRegion(content) {
945
+ if (!content)
946
+ return;
947
+ // Capture content in scrollback buffer
948
+ this.addToScrollback(content);
949
+ writeLock.lock('writeToScrollRegion');
950
+ try {
951
+ // Position cursor at content row and write
952
+ this.write(ESC.TO(this.contentRow, 1));
953
+ this.write(content);
954
+ // Track newlines
955
+ const newlines = (content.match(/\n/g) || []).length;
956
+ this.contentRow += newlines;
957
+ }
958
+ finally {
959
+ writeLock.unlock();
960
+ }
961
+ // Re-render chat box below new content (only when not streaming)
962
+ if (!this.scrollRegionActive) {
963
+ this.forceRender();
964
+ }
965
+ }
966
+ /**
967
+ * Enter alternate screen buffer and clear it.
968
+ * This gives us full control over the terminal without affecting user's history.
969
+ */
970
+ enterAlternateScreen() {
971
+ writeLock.lock('enterAltScreen');
972
+ try {
973
+ this.write(ESC.ENTER_ALT_SCREEN);
974
+ this.write(ESC.HOME);
975
+ this.write(ESC.CLEAR_SCREEN);
976
+ this.contentRow = 1;
977
+ this.alternateScreenActive = true;
978
+ }
979
+ finally {
980
+ writeLock.unlock();
981
+ }
982
+ }
983
+ /**
984
+ * Exit alternate screen buffer.
985
+ * Restores the user's previous terminal content.
986
+ */
987
+ exitAlternateScreen() {
988
+ writeLock.lock('exitAltScreen');
989
+ try {
990
+ this.write(ESC.EXIT_ALT_SCREEN);
991
+ this.alternateScreenActive = false;
992
+ }
993
+ finally {
994
+ writeLock.unlock();
995
+ }
996
+ }
997
+ /**
998
+ * Check if alternate screen buffer is currently active.
999
+ */
1000
+ isAlternateScreenActive() {
1001
+ return this.alternateScreenActive;
1002
+ }
1003
+ /**
1004
+ * Get a snapshot of the scrollback buffer (for display on exit).
1005
+ */
1006
+ getScrollbackSnapshot() {
1007
+ return [...this.scrollbackBuffer];
1008
+ }
1009
+ /**
1010
+ * Clear the entire terminal screen and reset content position.
1011
+ * This removes all content including the launching command.
1012
+ */
1013
+ clearScreen() {
1014
+ writeLock.lock('clearScreen');
1015
+ try {
1016
+ this.write(ESC.HOME);
1017
+ this.write(ESC.CLEAR_SCREEN);
1018
+ this.contentRow = 1;
915
1019
  }
1020
+ finally {
1021
+ writeLock.unlock();
1022
+ }
1023
+ }
1024
+ /**
1025
+ * Reset content position to row 1.
1026
+ * Does NOT clear the terminal - content starts from current position.
1027
+ */
1028
+ resetContentPosition() {
1029
+ this.contentRow = 1;
1030
+ }
1031
+ /**
1032
+ * Set the content row explicitly (used after banner is written).
1033
+ * This tells the input where content should start flowing from.
1034
+ */
1035
+ setContentRow(row) {
1036
+ this.contentRow = Math.max(1, row);
1037
+ }
1038
+ /**
1039
+ * Get the current content row position.
1040
+ */
1041
+ getContentRow() {
1042
+ return this.contentRow;
1043
+ }
1044
+ /**
1045
+ * Dispose and clean up
1046
+ */
1047
+ dispose() {
1048
+ if (this.disposed)
1049
+ return;
916
1050
  this.disposed = true;
917
1051
  this.enabled = false;
1052
+ this.disableScrollRegion();
1053
+ this.resetStreamingRenderThrottle();
918
1054
  this.disableBracketedPaste();
919
1055
  this.buffer = '';
920
1056
  this.queue = [];
@@ -956,8 +1092,13 @@ export class TerminalInput extends EventEmitter {
956
1092
  break;
957
1093
  }
958
1094
  }
1095
+ /**
1096
+ * Handle Alt/Meta key combinations for mode toggles and navigation.
1097
+ * All major erosolar-cli features accessible via keyboard shortcuts.
1098
+ */
959
1099
  handleMetaKey(key) {
960
1100
  switch (key.name) {
1101
+ // === CURSOR MOVEMENT ===
961
1102
  case 'left':
962
1103
  case 'b':
963
1104
  this.moveCursorWordLeft();
@@ -972,14 +1113,96 @@ export class TerminalInput extends EventEmitter {
972
1113
  case 'return':
973
1114
  this.insertNewline();
974
1115
  break;
1116
+ // === MODE TOGGLES ===
975
1117
  case 'v':
1118
+ // Alt+V: Toggle verification mode (auto-tests after edits)
976
1119
  this.emit('toggleVerify');
977
1120
  break;
978
1121
  case 'c':
1122
+ // Alt+C: Toggle auto-continue mode
979
1123
  this.emit('toggleAutoContinue');
980
1124
  break;
1125
+ case 't':
1126
+ // Alt+T: Toggle/cycle thinking mode
1127
+ this.emit('toggleThinking');
1128
+ break;
1129
+ case 'e':
1130
+ // Alt+E: Toggle edit permission mode (ask/auto)
1131
+ this.toggleEditMode();
1132
+ this.emit('toggleEditMode');
1133
+ break;
1134
+ case 'x':
1135
+ // Alt+X: Clear/compact context
1136
+ this.emit('clearContext');
1137
+ break;
1138
+ // === SCROLLBACK NAVIGATION ===
1139
+ case 's':
1140
+ // Alt+S: Toggle scrollback mode
1141
+ this.toggleScrollbackMode();
1142
+ break;
1143
+ case 'up':
1144
+ // Alt+Up: Quick scroll up into history
1145
+ if (!this.isInScrollbackMode) {
1146
+ this.scrollUp(10);
1147
+ }
1148
+ else {
1149
+ this.scrollUp(1);
1150
+ }
1151
+ break;
1152
+ case 'down':
1153
+ // Alt+Down: Quick scroll down
1154
+ if (this.isInScrollbackMode) {
1155
+ this.scrollDown(1);
1156
+ }
1157
+ break;
1158
+ case 'pageup':
1159
+ // Alt+PageUp: Page up in scrollback
1160
+ this.scrollUp(this.getPageSize());
1161
+ break;
1162
+ case 'pagedown':
1163
+ // Alt+PageDown: Page down in scrollback
1164
+ this.scrollDown(this.getPageSize());
1165
+ break;
1166
+ case 'home':
1167
+ // Alt+Home: Jump to top of scrollback
1168
+ this.scrollToTop();
1169
+ break;
1170
+ case 'end':
1171
+ // Alt+End: Jump to bottom (live)
1172
+ this.scrollToBottom();
1173
+ break;
981
1174
  }
982
1175
  }
1176
+ /**
1177
+ * Get page size for scrollback navigation.
1178
+ */
1179
+ getPageSize() {
1180
+ const { rows } = this.getSize();
1181
+ const chatBoxHeight = this.getChatBoxHeight();
1182
+ return Math.max(5, rows - chatBoxHeight - 2);
1183
+ }
1184
+ /**
1185
+ * Build scroll indicator for the divider line (Claude Code style).
1186
+ * Shows scroll position when in scrollback mode, or history size hint when idle.
1187
+ */
1188
+ buildScrollIndicator() {
1189
+ const bufferSize = this.scrollbackBuffer.length;
1190
+ // In scrollback mode - show position
1191
+ if (this.isInScrollbackMode && this.scrollbackOffset > 0) {
1192
+ const { rows } = this.getSize();
1193
+ const chatBoxHeight = this.getChatBoxHeight();
1194
+ const viewportHeight = Math.max(1, rows - chatBoxHeight);
1195
+ const currentPos = Math.max(0, bufferSize - this.scrollbackOffset - viewportHeight);
1196
+ const pct = bufferSize > 0 ? Math.round((currentPos / bufferSize) * 100) : 0;
1197
+ return `↑${this.scrollbackOffset} · ${pct}% · PgUp/Dn`;
1198
+ }
1199
+ // Not in scrollback - show hint if there's history
1200
+ if (bufferSize > 20) {
1201
+ const sizeLabel = bufferSize >= 1000 ? `${Math.floor(bufferSize / 1000)}k` : `${bufferSize}`;
1202
+ return `↕${sizeLabel}L · PgUp`;
1203
+ }
1204
+ return null;
1205
+ }
983
1206
  handleSpecialKey(_str, key) {
984
1207
  switch (key.name) {
985
1208
  case 'return':
@@ -1003,38 +1226,53 @@ export class TerminalInput extends EventEmitter {
1003
1226
  this.moveCursorRight();
1004
1227
  return true;
1005
1228
  case 'up':
1006
- this.handleUp();
1229
+ // Ctrl+Shift+Up or Shift+Up: Quick scroll up in scrollback
1230
+ if ((key.ctrl && key.shift) || key.shift) {
1231
+ this.scrollUp(5);
1232
+ }
1233
+ else {
1234
+ this.handleUp();
1235
+ }
1007
1236
  return true;
1008
1237
  case 'down':
1009
- this.handleDown();
1238
+ // Ctrl+Shift+Down or Shift+Down: Quick scroll down in scrollback
1239
+ if ((key.ctrl && key.shift) || key.shift) {
1240
+ this.scrollDown(5);
1241
+ }
1242
+ else {
1243
+ this.handleDown();
1244
+ }
1010
1245
  return true;
1011
1246
  case 'home':
1012
- this.moveCursorToLineStart();
1247
+ // Ctrl+Home or in scrollback mode: scroll to top
1248
+ if (key.ctrl || this.isInScrollbackMode) {
1249
+ this.scrollToTop();
1250
+ }
1251
+ else {
1252
+ this.moveCursorToLineStart();
1253
+ }
1013
1254
  return true;
1014
1255
  case 'end':
1015
- this.moveCursorToLineEnd();
1256
+ // Ctrl+End or in scrollback mode: scroll to bottom (live mode)
1257
+ if (key.ctrl || this.isInScrollbackMode) {
1258
+ this.scrollToBottom();
1259
+ }
1260
+ else {
1261
+ this.moveCursorToLineEnd();
1262
+ }
1263
+ return true;
1264
+ case 'pageup':
1265
+ this.scrollUp(20); // Scroll up by 20 lines
1266
+ return true;
1267
+ case 'pagedown':
1268
+ this.scrollDown(20); // Scroll down by 20 lines
1016
1269
  return true;
1017
1270
  case 'tab':
1018
1271
  if (key.shift) {
1019
1272
  this.toggleEditMode();
1020
1273
  return true;
1021
1274
  }
1022
- // Tab: toggle paste expansion if in placeholder, otherwise toggle thinking
1023
- if (this.findPlaceholderAt(this.cursor)) {
1024
- this.togglePasteExpansion();
1025
- }
1026
- else {
1027
- this.toggleThinking();
1028
- }
1029
- return true;
1030
- case 'escape':
1031
- // Esc: interrupt if streaming, otherwise clear buffer
1032
- if (this.mode === 'streaming') {
1033
- this.emit('interrupt');
1034
- }
1035
- else if (this.buffer.length > 0) {
1036
- this.clear();
1037
- }
1275
+ this.insertText(' ');
1038
1276
  return true;
1039
1277
  }
1040
1278
  return false;
@@ -1052,7 +1290,6 @@ export class TerminalInput extends EventEmitter {
1052
1290
  this.insertPlainText(chunk, insertPos);
1053
1291
  this.cursor = insertPos + chunk.length;
1054
1292
  this.emit('change', this.buffer);
1055
- this.updateSuggestions();
1056
1293
  this.scheduleRender();
1057
1294
  }
1058
1295
  insertNewline() {
@@ -1077,7 +1314,6 @@ export class TerminalInput extends EventEmitter {
1077
1314
  this.cursor = Math.max(0, this.cursor - 1);
1078
1315
  }
1079
1316
  this.emit('change', this.buffer);
1080
- this.updateSuggestions();
1081
1317
  this.scheduleRender();
1082
1318
  }
1083
1319
  deleteForward() {
@@ -1305,13 +1541,12 @@ export class TerminalInput extends EventEmitter {
1305
1541
  timestamp: Date.now(),
1306
1542
  });
1307
1543
  this.emit('queue', text);
1308
- this.clear(); // Clear immediately for queued input, re-render to update queue display
1544
+ this.clear(); // Clear immediately for queued input
1309
1545
  }
1310
1546
  else {
1311
- // In idle mode, clear the input WITHOUT rendering.
1312
- // The caller will display the user message and start streaming.
1313
- // We'll render the input area again after streaming ends.
1314
- this.clear(true); // Skip render - streaming will handle display
1547
+ // In idle mode, clear the input first, then emit submit.
1548
+ // The prompt will be logged as a visible message by the caller.
1549
+ this.clear();
1315
1550
  this.emit('submit', text);
1316
1551
  }
1317
1552
  }
@@ -1328,7 +1563,9 @@ export class TerminalInput extends EventEmitter {
1328
1563
  if (available <= 0)
1329
1564
  return;
1330
1565
  const chunk = clean.slice(0, available);
1331
- if (isMultilinePaste(chunk)) {
1566
+ const isMultiline = isMultilinePaste(chunk);
1567
+ const isShortMultiline = isMultiline && this.shouldInlineMultiline(chunk);
1568
+ if (isMultiline && !isShortMultiline) {
1332
1569
  this.insertPastePlaceholder(chunk);
1333
1570
  }
1334
1571
  else {
@@ -1392,6 +1629,236 @@ export class TerminalInput extends EventEmitter {
1392
1629
  return { lines, cursorLine, cursorCol };
1393
1630
  }
1394
1631
  // ===========================================================================
1632
+ // SCROLLBACK BUFFER
1633
+ // ===========================================================================
1634
+ /**
1635
+ * Add content to the scrollback buffer for history retention
1636
+ */
1637
+ addToScrollback(content) {
1638
+ if (!content)
1639
+ return;
1640
+ // Split content into lines and add to buffer
1641
+ const lines = content.split('\n');
1642
+ for (let i = 0; i < lines.length; i++) {
1643
+ const line = lines[i];
1644
+ if (line !== undefined) {
1645
+ // Only add non-empty lines or preserve newlines between content
1646
+ if (i < lines.length - 1 || line.length > 0) {
1647
+ this.scrollbackBuffer.push(line);
1648
+ }
1649
+ }
1650
+ }
1651
+ // Trim buffer if it exceeds max size
1652
+ while (this.scrollbackBuffer.length > this.maxScrollbackLines) {
1653
+ this.scrollbackBuffer.shift();
1654
+ }
1655
+ // If we're in live mode (not scrolled up), keep offset at 0
1656
+ if (this.scrollbackOffset === 0) {
1657
+ this.isInScrollbackMode = false;
1658
+ }
1659
+ }
1660
+ /**
1661
+ * Scroll up by a number of lines (PageUp)
1662
+ */
1663
+ scrollUp(lines = 10) {
1664
+ const { rows } = this.getSize();
1665
+ const chatBoxHeight = this.getChatBoxHeight();
1666
+ const visibleLines = Math.max(1, rows - chatBoxHeight);
1667
+ // Calculate max scroll offset
1668
+ const maxOffset = Math.max(0, this.scrollbackBuffer.length - visibleLines);
1669
+ this.scrollbackOffset = Math.min(this.scrollbackOffset + lines, maxOffset);
1670
+ this.isInScrollbackMode = this.scrollbackOffset > 0;
1671
+ if (this.isInScrollbackMode) {
1672
+ this.renderScrollbackView();
1673
+ }
1674
+ }
1675
+ /**
1676
+ * Scroll down by a number of lines (PageDown)
1677
+ */
1678
+ scrollDown(lines = 10) {
1679
+ this.scrollbackOffset = Math.max(0, this.scrollbackOffset - lines);
1680
+ this.isInScrollbackMode = this.scrollbackOffset > 0;
1681
+ if (this.isInScrollbackMode) {
1682
+ this.renderScrollbackView();
1683
+ }
1684
+ else {
1685
+ // Returned to live mode - force re-render
1686
+ this.forceRender();
1687
+ }
1688
+ }
1689
+ /**
1690
+ * Jump to the top of scrollback buffer
1691
+ */
1692
+ scrollToTop() {
1693
+ const { rows } = this.getSize();
1694
+ const chatBoxHeight = this.getChatBoxHeight();
1695
+ const visibleLines = Math.max(1, rows - chatBoxHeight);
1696
+ const maxOffset = Math.max(0, this.scrollbackBuffer.length - visibleLines);
1697
+ this.scrollbackOffset = maxOffset;
1698
+ this.isInScrollbackMode = true;
1699
+ this.renderScrollbackView();
1700
+ }
1701
+ /**
1702
+ * Jump to the bottom (live mode)
1703
+ */
1704
+ scrollToBottom() {
1705
+ this.scrollbackOffset = 0;
1706
+ this.isInScrollbackMode = false;
1707
+ this.forceRender();
1708
+ }
1709
+ /**
1710
+ * Toggle scrollback mode on/off (Alt+S hotkey)
1711
+ */
1712
+ toggleScrollbackMode() {
1713
+ if (this.isInScrollbackMode) {
1714
+ this.scrollToBottom();
1715
+ }
1716
+ else if (this.scrollbackBuffer.length > 0) {
1717
+ this.scrollUp(20);
1718
+ }
1719
+ }
1720
+ /**
1721
+ * Render the scrollback buffer view with enhanced visuals
1722
+ * Features:
1723
+ * - Visual scroll position indicator
1724
+ * - Progress bar showing position in history
1725
+ * - Keyboard navigation hints
1726
+ * - Animated indicators
1727
+ */
1728
+ renderScrollbackView() {
1729
+ const { rows, cols } = this.getSize();
1730
+ const chatBoxHeight = this.getChatBoxHeight();
1731
+ const contentHeight = Math.max(1, rows - chatBoxHeight);
1732
+ writeLock.lock('renderScrollback');
1733
+ try {
1734
+ this.write(ESC.SAVE);
1735
+ this.write(ESC.HIDE);
1736
+ // Clear content area
1737
+ for (let i = 1; i <= contentHeight; i++) {
1738
+ this.write(ESC.TO(i, 1));
1739
+ this.write(ESC.CLEAR_LINE);
1740
+ }
1741
+ // Calculate which lines to show
1742
+ const totalLines = this.scrollbackBuffer.length;
1743
+ const startIdx = Math.max(0, totalLines - this.scrollbackOffset - contentHeight);
1744
+ const endIdx = Math.max(0, totalLines - this.scrollbackOffset);
1745
+ const visibleLines = this.scrollbackBuffer.slice(startIdx, endIdx);
1746
+ // Build header bar with navigation hints
1747
+ const headerInfo = this.buildScrollbackHeader(cols, totalLines, startIdx, endIdx);
1748
+ this.write(ESC.TO(1, 1));
1749
+ this.write(headerInfo);
1750
+ // Render visible lines with line numbers and visual guides
1751
+ const lineNumWidth = String(totalLines).length + 1;
1752
+ const contentStart = 2; // Start after header
1753
+ for (let i = 0; i < Math.min(visibleLines.length, contentHeight - 1); i++) {
1754
+ const line = visibleLines[i] ?? '';
1755
+ const lineNum = startIdx + i + 1;
1756
+ this.write(ESC.TO(contentStart + i, 1));
1757
+ // Line number gutter
1758
+ const numStr = String(lineNum).padStart(lineNumWidth, ' ');
1759
+ this.write(theme.ui.muted(`${numStr} │ `));
1760
+ // Content with truncation
1761
+ const gutterWidth = lineNumWidth + 4;
1762
+ const maxLen = cols - gutterWidth - 2;
1763
+ const displayLine = line.length > maxLen ? line.slice(0, maxLen - 3) + '...' : line;
1764
+ this.write(displayLine);
1765
+ }
1766
+ // Add visual scroll track on the right edge
1767
+ this.renderScrollTrack(cols, contentHeight, totalLines, startIdx, endIdx);
1768
+ this.write(ESC.RESTORE);
1769
+ this.write(ESC.SHOW);
1770
+ }
1771
+ finally {
1772
+ writeLock.unlock();
1773
+ }
1774
+ // Re-render chat box
1775
+ this.forceRender();
1776
+ }
1777
+ /**
1778
+ * Build scrollback header with navigation hints
1779
+ */
1780
+ buildScrollbackHeader(cols, totalLines, startIdx, endIdx) {
1781
+ const percentage = Math.round((endIdx / totalLines) * 100);
1782
+ // Animated scroll indicator
1783
+ const scrollFrames = ['◆', '◇', '◆', '◈'];
1784
+ this.scrollIndicatorFrame = (this.scrollIndicatorFrame + 1) % scrollFrames.length;
1785
+ const indicator = scrollFrames[this.scrollIndicatorFrame];
1786
+ // Build header parts
1787
+ const leftPart = theme.info(`${indicator} SCROLLBACK`) +
1788
+ theme.ui.muted(` [${startIdx + 1}-${endIdx} of ${totalLines}]`);
1789
+ const progressBar = this.buildProgressBar(percentage, 15);
1790
+ const rightPart = progressBar +
1791
+ theme.ui.muted(` ${percentage}%`) +
1792
+ theme.ui.muted(' │ ') +
1793
+ theme.primary('PgUp') + theme.ui.muted('/') + theme.primary('PgDn') +
1794
+ theme.ui.muted(' scroll · ') +
1795
+ theme.primary('End') + theme.ui.muted(' exit');
1796
+ const leftLen = this.visibleLength(leftPart);
1797
+ const rightLen = this.visibleLength(rightPart);
1798
+ const padding = Math.max(1, cols - leftLen - rightLen - 2);
1799
+ return `${leftPart}${' '.repeat(padding)}${rightPart}`;
1800
+ }
1801
+ /**
1802
+ * Render visual scroll track on the right side
1803
+ */
1804
+ renderScrollTrack(cols, contentHeight, totalLines, startIdx, endIdx) {
1805
+ if (totalLines <= contentHeight || cols < 40)
1806
+ return;
1807
+ const trackHeight = contentHeight - 1; // Exclude header
1808
+ const viewportRatio = (endIdx - startIdx) / totalLines;
1809
+ const positionRatio = startIdx / Math.max(1, totalLines - (endIdx - startIdx));
1810
+ // Calculate thumb size and position
1811
+ const thumbSize = Math.max(1, Math.round(viewportRatio * trackHeight));
1812
+ const thumbStart = Math.round(positionRatio * (trackHeight - thumbSize));
1813
+ // Render track on right edge
1814
+ for (let i = 0; i < trackHeight; i++) {
1815
+ const row = 2 + i; // Start after header
1816
+ this.write(ESC.TO(row, cols));
1817
+ if (i >= thumbStart && i < thumbStart + thumbSize) {
1818
+ // Thumb (viewport indicator)
1819
+ this.write(theme.accent('█'));
1820
+ }
1821
+ else {
1822
+ // Track background
1823
+ this.write(theme.ui.muted('░'));
1824
+ }
1825
+ }
1826
+ }
1827
+ /**
1828
+ * Build a visual progress bar
1829
+ */
1830
+ buildProgressBar(percentage, width = 10) {
1831
+ const filled = Math.round((percentage / 100) * width);
1832
+ const empty = width - filled;
1833
+ const bar = theme.accent('█'.repeat(filled)) +
1834
+ theme.ui.muted('░'.repeat(empty));
1835
+ return `${theme.ui.muted('[')}${bar}${theme.ui.muted(']')}`;
1836
+ }
1837
+ /**
1838
+ * Get scrollback buffer content (for persistence)
1839
+ */
1840
+ getScrollbackBuffer() {
1841
+ return [...this.scrollbackBuffer];
1842
+ }
1843
+ /**
1844
+ * Load scrollback buffer (for restoration)
1845
+ */
1846
+ loadScrollbackBuffer(lines) {
1847
+ this.scrollbackBuffer = [...lines];
1848
+ // Trim if necessary
1849
+ while (this.scrollbackBuffer.length > this.maxScrollbackLines) {
1850
+ this.scrollbackBuffer.shift();
1851
+ }
1852
+ }
1853
+ /**
1854
+ * Clear scrollback buffer
1855
+ */
1856
+ clearScrollbackBuffer() {
1857
+ this.scrollbackBuffer = [];
1858
+ this.scrollbackOffset = 0;
1859
+ this.isInScrollbackMode = false;
1860
+ }
1861
+ // ===========================================================================
1395
1862
  // UTILITIES
1396
1863
  // ===========================================================================
1397
1864
  getComposedLength() {
@@ -1464,17 +1931,19 @@ export class TerminalInput extends EventEmitter {
1464
1931
  this.shiftPlaceholders(position, text.length);
1465
1932
  this.buffer = this.buffer.slice(0, position) + text + this.buffer.slice(position);
1466
1933
  }
1934
+ shouldInlineMultiline(content) {
1935
+ const lines = content.split('\n').length;
1936
+ const maxInlineLines = 4;
1937
+ const maxInlineChars = 240;
1938
+ return lines <= maxInlineLines && content.length <= maxInlineChars;
1939
+ }
1467
1940
  findPlaceholderAt(position) {
1468
1941
  return this.pastePlaceholders.find((ph) => position >= ph.start && position < ph.end) ?? null;
1469
1942
  }
1470
- buildPlaceholder(summary) {
1943
+ buildPlaceholder(lineCount) {
1471
1944
  const id = ++this.pasteCounter;
1472
- const lang = summary.language ? ` ${summary.language.toUpperCase()}` : '';
1473
- // Show first line preview (truncated)
1474
- const preview = summary.preview.length > 30
1475
- ? `${summary.preview.slice(0, 30)}...`
1476
- : summary.preview;
1477
- const placeholder = `[📋 #${id}${lang} ${summary.lineCount}L] "${preview}"`;
1945
+ const plural = lineCount === 1 ? '' : 's';
1946
+ const placeholder = `[Pasted text #${id} +${lineCount} line${plural}]`;
1478
1947
  return { id, placeholder };
1479
1948
  }
1480
1949
  insertPastePlaceholder(content) {
@@ -1482,67 +1951,21 @@ export class TerminalInput extends EventEmitter {
1482
1951
  if (available <= 0)
1483
1952
  return;
1484
1953
  const cleanContent = content.slice(0, available);
1485
- const summary = generatePasteSummary(cleanContent);
1486
- // For short pastes (< 5 lines), show full content instead of placeholder
1487
- if (summary.lineCount < 5) {
1488
- const placeholder = this.findPlaceholderAt(this.cursor);
1489
- const insertPos = placeholder && this.cursor > placeholder.start ? placeholder.end : this.cursor;
1490
- this.insertPlainText(cleanContent, insertPos);
1491
- this.cursor = insertPos + cleanContent.length;
1492
- return;
1493
- }
1494
- const { id, placeholder } = this.buildPlaceholder(summary);
1954
+ const lineCount = cleanContent.split('\n').length;
1955
+ const { id, placeholder } = this.buildPlaceholder(lineCount);
1495
1956
  const insertPos = this.cursor;
1496
1957
  this.shiftPlaceholders(insertPos, placeholder.length);
1497
1958
  this.pastePlaceholders.push({
1498
1959
  id,
1499
1960
  content: cleanContent,
1500
- lineCount: summary.lineCount,
1961
+ lineCount,
1501
1962
  placeholder,
1502
1963
  start: insertPos,
1503
1964
  end: insertPos + placeholder.length,
1504
- summary,
1505
- expanded: false,
1506
1965
  });
1507
1966
  this.buffer = this.buffer.slice(0, insertPos) + placeholder + this.buffer.slice(insertPos);
1508
1967
  this.cursor = insertPos + placeholder.length;
1509
1968
  }
1510
- /**
1511
- * Toggle expansion of a paste placeholder at the current cursor position.
1512
- * When expanded, shows first 3 and last 2 lines of the content.
1513
- */
1514
- togglePasteExpansion() {
1515
- const placeholder = this.findPlaceholderAt(this.cursor);
1516
- if (!placeholder)
1517
- return false;
1518
- placeholder.expanded = !placeholder.expanded;
1519
- // Update the placeholder text in buffer
1520
- const newPlaceholder = placeholder.expanded
1521
- ? this.buildExpandedPlaceholder(placeholder)
1522
- : this.buildPlaceholder(placeholder.summary).placeholder;
1523
- const lengthDiff = newPlaceholder.length - placeholder.placeholder.length;
1524
- // Update buffer
1525
- this.buffer =
1526
- this.buffer.slice(0, placeholder.start) +
1527
- newPlaceholder +
1528
- this.buffer.slice(placeholder.end);
1529
- // Update placeholder tracking
1530
- placeholder.placeholder = newPlaceholder;
1531
- placeholder.end = placeholder.start + newPlaceholder.length;
1532
- // Shift other placeholders
1533
- this.shiftPlaceholders(placeholder.end, lengthDiff, placeholder.id);
1534
- this.scheduleRender();
1535
- return true;
1536
- }
1537
- buildExpandedPlaceholder(ph) {
1538
- const lines = ph.content.split('\n');
1539
- const firstLines = lines.slice(0, 3).map(l => l.slice(0, 60)).join('\n');
1540
- const lastLines = lines.length > 5
1541
- ? '\n...\n' + lines.slice(-2).map(l => l.slice(0, 60)).join('\n')
1542
- : '';
1543
- const lang = ph.summary.language ? ` ${ph.summary.language.toUpperCase()}` : '';
1544
- return `[📋 #${ph.id}${lang} ${ph.lineCount}L ▼]\n${firstLines}${lastLines}\n[/📋 #${ph.id}]`;
1545
- }
1546
1969
  deletePlaceholder(placeholder) {
1547
1970
  const length = placeholder.end - placeholder.start;
1548
1971
  this.buffer = this.buffer.slice(0, placeholder.start) + this.buffer.slice(placeholder.end);
@@ -1550,7 +1973,11 @@ export class TerminalInput extends EventEmitter {
1550
1973
  this.shiftPlaceholders(placeholder.end, -length, placeholder.id);
1551
1974
  this.cursor = placeholder.start;
1552
1975
  }
1553
- updateContextUsage(value) {
1976
+ updateContextUsage(value, autoCompactThreshold) {
1977
+ if (typeof autoCompactThreshold === 'number' && Number.isFinite(autoCompactThreshold)) {
1978
+ const boundedThreshold = Math.max(1, Math.min(100, Math.round(autoCompactThreshold)));
1979
+ this.contextAutoCompactThreshold = boundedThreshold;
1980
+ }
1554
1981
  if (value === null || !Number.isFinite(value)) {
1555
1982
  this.contextUsage = null;
1556
1983
  }
@@ -1577,6 +2004,28 @@ export class TerminalInput extends EventEmitter {
1577
2004
  const next = this.editMode === 'display-edits' ? 'ask-permission' : 'display-edits';
1578
2005
  this.setEditMode(next);
1579
2006
  }
2007
+ scheduleStreamingRender(delayMs) {
2008
+ if (this.streamingRenderTimer)
2009
+ return;
2010
+ const wait = Math.max(16, delayMs);
2011
+ this.streamingRenderTimer = setTimeout(() => {
2012
+ this.streamingRenderTimer = null;
2013
+ // During streaming, only update chat box (not full render)
2014
+ if (this.scrollRegionActive) {
2015
+ this.renderChatBoxAtBottom();
2016
+ }
2017
+ else {
2018
+ this.render();
2019
+ }
2020
+ }, wait);
2021
+ }
2022
+ resetStreamingRenderThrottle() {
2023
+ if (this.streamingRenderTimer) {
2024
+ clearTimeout(this.streamingRenderTimer);
2025
+ this.streamingRenderTimer = null;
2026
+ }
2027
+ this.lastStreamingRender = 0;
2028
+ }
1580
2029
  scheduleRender() {
1581
2030
  if (!this.canRender())
1582
2031
  return;