erosolar-cli 1.7.346 → 1.7.347

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 +43 -7
  67. package/dist/shell/interactiveShell.d.ts.map +1 -1
  68. package/dist/shell/interactiveShell.js +417 -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 +252 -120
  78. package/dist/shell/terminalInput.d.ts.map +1 -1
  79. package/dist/shell/terminalInput.js +1117 -541
  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 +141 -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 +180 -47
  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 +140 -259
  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,39 @@ export class TerminalInput extends EventEmitter {
133
157
  }
134
158
  }
135
159
  /**
136
- * Process raw terminal data (handles bracketed paste sequences)
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 and mouse events)
137
177
  * Returns true if the data was consumed (paste sequence)
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
+ }
140
193
  // Check for paste start
141
194
  if (data.includes(ESC.PASTE_START)) {
142
195
  this.isPasting = true;
@@ -167,6 +220,21 @@ export class TerminalInput extends EventEmitter {
167
220
  }
168
221
  return { consumed: false, passthrough: data };
169
222
  }
223
+ /**
224
+ * Handle mouse events (button, x, y coordinates, action)
225
+ */
226
+ handleMouseEvent(button, _x, _y, _action) {
227
+ // Mouse wheel events: button 64 = scroll up, button 65 = scroll down
228
+ if (button === 64) {
229
+ // Scroll up (3 lines per wheel tick)
230
+ this.scrollUp(3);
231
+ }
232
+ else if (button === 65) {
233
+ // Scroll down (3 lines per wheel tick)
234
+ this.scrollDown(3);
235
+ }
236
+ // Ignore other mouse events (clicks, drags, etc.) for now
237
+ }
170
238
  /**
171
239
  * Handle a keypress event
172
240
  */
@@ -189,306 +257,36 @@ export class TerminalInput extends EventEmitter {
189
257
  if (handled)
190
258
  return;
191
259
  }
192
- // Handle '?' for help hint (if buffer is empty)
193
- if (str === '?' && this.buffer.length === 0) {
194
- this.emit('showHelp');
195
- return;
196
- }
197
260
  // Insert printable characters
198
261
  if (str && !key?.ctrl && !key?.meta) {
199
262
  this.insertText(str);
200
263
  }
201
264
  }
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 } = this.getSize();
274
- const divider = '─'.repeat(cols);
275
- const { dim: DIM, reset: R } = UI_COLORS;
276
- // Chat box is 4 lines: divider + input + divider + controls
277
- const chatBoxHeight = 4;
278
- // Chat box starts right after content
279
- const chatBoxStartRow = this.contentEndRow + 1;
280
- // Save cursor position before rendering
281
- this.write('\x1b7');
282
- // Hide cursor during render
283
- this.write(ESC.HIDE);
284
- // Track position
285
- this.inputAreaStartRow = chatBoxStartRow;
286
- let currentRow = chatBoxStartRow;
287
- // Helper to write a line at absolute position (clears then writes)
288
- const writeLine = (content) => {
289
- this.write(ESC.TO(currentRow, 1));
290
- this.write(ESC.CLEAR_LINE);
291
- this.write(content);
292
- currentRow++;
293
- };
294
- // Top divider
295
- writeLine(`${DIM}${divider}${R}`);
296
- // Input line with > prompt
297
- const { lines, cursorCol } = this.wrapBuffer(cols - 3);
298
- const displayLine = lines[0] ?? '';
299
- const inputRow = currentRow;
300
- writeLine(`${DIM}>${R} ${displayLine}`);
301
- // Bottom divider
302
- writeLine(`${DIM}${divider}${R}`);
303
- // Mode controls line - Claude Code style
304
- this.write(ESC.TO(currentRow, 1));
305
- this.write(ESC.CLEAR_LINE);
306
- this.write(this.buildClaudeStyleControls(cols));
307
- // Track lines rendered
308
- this.flowModeRenderedLines = chatBoxHeight;
309
- // Restore cursor position (back to where content was being written)
310
- // During streaming, this keeps cursor in content area
311
- // During idle, cursor was in input area anyway
312
- this.write('\x1b8');
313
- // Show cursor
314
- this.write(ESC.SHOW);
315
- // Update tracking
316
- this.lastRenderContent = this.buffer;
317
- this.lastRenderCursor = this.cursor;
318
- }
319
- /**
320
- * Build Claude Code style controls line.
321
- * Shows: edit mode indicator (shift+tab to cycle)
322
- */
323
- buildClaudeStyleControls(cols) {
324
- const { dim: DIM, green: GREEN, yellow: YELLOW, cyan: CYAN, reset: R } = UI_COLORS;
325
- // Edit mode indicator
326
- let editModeText;
327
- if (this.editMode === 'display-edits') {
328
- editModeText = `${GREEN}⏵⏵${R} accept edits on`;
329
- }
330
- else {
331
- editModeText = `${YELLOW}⏸⏸${R} ask before edit`;
332
- }
333
- // Build controls line
334
- const parts = [` ${editModeText} ${DIM}(shift+tab to cycle)${R}`];
335
- // Add thinking mode if enabled
336
- if (this.thinkingEnabled) {
337
- parts.push(`${CYAN}💭${R}`);
338
- }
339
- // Add context usage if available
340
- if (this.contextUsage !== null) {
341
- const rem = Math.max(0, 100 - this.contextUsage);
342
- if (rem < 10) {
343
- parts.push(`${UI_COLORS.red}ctx ${rem}%${R}`);
344
- }
345
- else if (rem < 25) {
346
- parts.push(`${YELLOW}ctx ${rem}%${R}`);
347
- }
348
- }
349
- return parts.join(` ${DIM}·${R} `);
350
- }
351
265
  /**
352
266
  * Set the input mode
353
267
  *
354
- * BOTTOM PINNED with SSE: Chat box stays at terminal bottom.
355
- * Scroll region protects chat box, content scrolls above it.
268
+ * Content flows naturally - no scroll region pinning.
356
269
  */
357
270
  setMode(mode) {
358
271
  const prevMode = this.mode;
359
272
  this.mode = mode;
360
273
  if (mode === 'streaming' && prevMode !== 'streaming') {
361
- // Track streaming start time for elapsed display
362
- this.streamingStartTime = Date.now();
363
- // Ensure unified UI is initialized
364
- if (!this.unifiedUIInitialized) {
365
- this.initializeUnifiedUI();
366
- }
367
- // Start periodic render timer to keep chat box updated during streaming
368
- // This updates contentEndRow from display and re-renders chat box
369
- if (!this.streamingRenderTimer) {
370
- this.streamingRenderTimer = setInterval(() => {
371
- // Update contentEndRow from display's line count
372
- if (this.displayRef?.getTotalWrittenLines) {
373
- this.contentEndRow = this.displayRef.getTotalWrittenLines();
374
- }
375
- // Re-render chat box at updated position
376
- this.renderFloatingInputArea();
377
- }, 100); // Update every 100ms
378
- }
379
- // Initial render
274
+ this.resetStreamingRenderThrottle();
380
275
  this.renderDirty = true;
381
- this.scheduleRender();
276
+ this.render();
382
277
  }
383
278
  else if (mode !== 'streaming' && prevMode === 'streaming') {
384
- // Stop streaming render timer
385
- if (this.streamingRenderTimer) {
386
- clearInterval(this.streamingRenderTimer);
387
- this.streamingRenderTimer = null;
388
- }
389
- // Reset streaming time
390
- this.streamingStartTime = null;
391
- // Final render with accurate position
392
- this.renderDirty = true;
393
- this.scheduleRender();
394
- }
395
- }
396
- /**
397
- * Set the row where content ends (for idle mode positioning).
398
- * Input area will render starting from this row + 1.
399
- */
400
- setContentEndRow(row) {
401
- this.contentEndRow = Math.max(0, row);
402
- this.renderDirty = true;
403
- this.scheduleRender();
404
- }
405
- /**
406
- * Set available slash commands for auto-complete suggestions.
407
- */
408
- setCommands(commands) {
409
- this.commandSuggestions = commands;
410
- this.updateSuggestions();
411
- }
412
- /**
413
- * Update filtered suggestions based on current input.
414
- */
415
- updateSuggestions() {
416
- const input = this.buffer.trim();
417
- // Only show suggestions when input starts with "/"
418
- if (!input.startsWith('/')) {
419
- this.showSuggestions = false;
420
- this.filteredSuggestions = [];
421
- this.selectedSuggestionIndex = 0;
422
- return;
423
- }
424
- const query = input.toLowerCase();
425
- this.filteredSuggestions = this.commandSuggestions.filter(cmd => cmd.command.toLowerCase().startsWith(query) ||
426
- cmd.command.toLowerCase().includes(query.slice(1)));
427
- // Show suggestions if we have matches
428
- this.showSuggestions = this.filteredSuggestions.length > 0;
429
- // Keep selection in bounds
430
- if (this.selectedSuggestionIndex >= this.filteredSuggestions.length) {
431
- this.selectedSuggestionIndex = Math.max(0, this.filteredSuggestions.length - 1);
279
+ // Streaming ended - render the input area
280
+ this.resetStreamingRenderThrottle();
281
+ this.forceRender();
432
282
  }
433
283
  }
434
284
  /**
435
- * Select next suggestion (arrow down / tab).
285
+ * Legacy method - no longer used (content flows naturally).
286
+ * @deprecated Use setContentRow instead
436
287
  */
437
- selectNextSuggestion() {
438
- if (!this.showSuggestions || this.filteredSuggestions.length === 0)
439
- return;
440
- this.selectedSuggestionIndex = (this.selectedSuggestionIndex + 1) % this.filteredSuggestions.length;
441
- this.renderDirty = true;
442
- this.scheduleRender();
443
- }
444
- /**
445
- * Select previous suggestion (arrow up / shift+tab).
446
- */
447
- selectPrevSuggestion() {
448
- if (!this.showSuggestions || this.filteredSuggestions.length === 0)
449
- return;
450
- this.selectedSuggestionIndex = this.selectedSuggestionIndex === 0
451
- ? this.filteredSuggestions.length - 1
452
- : this.selectedSuggestionIndex - 1;
453
- this.renderDirty = true;
454
- this.scheduleRender();
455
- }
456
- /**
457
- * Accept current suggestion and insert into buffer.
458
- */
459
- acceptSuggestion() {
460
- if (!this.showSuggestions || this.filteredSuggestions.length === 0)
461
- return false;
462
- const selected = this.filteredSuggestions[this.selectedSuggestionIndex];
463
- if (!selected)
464
- return false;
465
- // Replace buffer with selected command
466
- this.buffer = selected.command + ' ';
467
- this.cursor = this.buffer.length;
468
- this.showSuggestions = false;
469
- this.renderDirty = true;
470
- this.scheduleRender();
471
- return true;
472
- }
473
- /**
474
- * Check if suggestions are visible.
475
- */
476
- areSuggestionsVisible() {
477
- return this.showSuggestions && this.filteredSuggestions.length > 0;
478
- }
479
- /**
480
- * Toggle thinking/reasoning mode
481
- */
482
- toggleThinking() {
483
- this.thinkingEnabled = !this.thinkingEnabled;
484
- this.emit('thinkingToggle', this.thinkingEnabled);
485
- this.scheduleRender();
486
- }
487
- /**
488
- * Get thinking enabled state
489
- */
490
- isThinkingEnabled() {
491
- return this.thinkingEnabled;
288
+ setPinnedHeaderLines(_count) {
289
+ // No-op: scroll region pinning removed
492
290
  }
493
291
  /**
494
292
  * Get current mode
@@ -521,17 +319,14 @@ export class TerminalInput extends EventEmitter {
521
319
  }
522
320
  /**
523
321
  * Clear the buffer
524
- * @param skipRender - If true, don't trigger a re-render (used during submit flow)
525
322
  */
526
- clear(skipRender = false) {
323
+ clear() {
527
324
  this.buffer = '';
528
325
  this.cursor = 0;
529
326
  this.historyIndex = -1;
530
327
  this.tempInput = '';
531
328
  this.pastePlaceholders = [];
532
- if (!skipRender) {
533
- this.scheduleRender();
534
- }
329
+ this.scheduleRender();
535
330
  }
536
331
  /**
537
332
  * Get queued inputs
@@ -602,6 +397,37 @@ export class TerminalInput extends EventEmitter {
602
397
  this.streamingLabel = next;
603
398
  this.scheduleRender();
604
399
  }
400
+ /**
401
+ * Surface meta status just above the divider (e.g., elapsed time or token usage).
402
+ */
403
+ setMetaStatus(meta) {
404
+ const nextElapsed = typeof meta.elapsedSeconds === 'number' && Number.isFinite(meta.elapsedSeconds) && meta.elapsedSeconds >= 0
405
+ ? Math.floor(meta.elapsedSeconds)
406
+ : null;
407
+ const nextTokens = typeof meta.tokensUsed === 'number' && Number.isFinite(meta.tokensUsed) && meta.tokensUsed >= 0
408
+ ? Math.floor(meta.tokensUsed)
409
+ : null;
410
+ const nextLimit = typeof meta.tokenLimit === 'number' && Number.isFinite(meta.tokenLimit) && meta.tokenLimit > 0
411
+ ? Math.floor(meta.tokenLimit)
412
+ : null;
413
+ const nextThinking = typeof meta.thinkingMs === 'number' && Number.isFinite(meta.thinkingMs) && meta.thinkingMs >= 0
414
+ ? Math.floor(meta.thinkingMs)
415
+ : null;
416
+ const nextThinkingHasContent = !!meta.thinkingHasContent;
417
+ if (this.metaElapsedSeconds === nextElapsed &&
418
+ this.metaTokensUsed === nextTokens &&
419
+ this.metaTokenLimit === nextLimit &&
420
+ this.metaThinkingMs === nextThinking &&
421
+ this.metaThinkingHasContent === nextThinkingHasContent) {
422
+ return;
423
+ }
424
+ this.metaElapsedSeconds = nextElapsed;
425
+ this.metaTokensUsed = nextTokens;
426
+ this.metaTokenLimit = nextLimit;
427
+ this.metaThinkingMs = nextThinking;
428
+ this.metaThinkingHasContent = nextThinkingHasContent;
429
+ this.scheduleRender();
430
+ }
605
431
  /**
606
432
  * Keep mode toggles (verification/auto-continue) visible in the control bar.
607
433
  * Hotkey labels remain stable so the bar looks the same before/during streaming.
@@ -611,26 +437,22 @@ export class TerminalInput extends EventEmitter {
611
437
  const nextAutoContinue = !!options.autoContinueEnabled;
612
438
  const nextVerifyHotkey = options.verificationHotkey ?? this.verificationHotkey;
613
439
  const nextAutoHotkey = options.autoContinueHotkey ?? this.autoContinueHotkey;
440
+ const nextThinkingHotkey = options.thinkingHotkey ?? this.thinkingHotkey;
441
+ const nextThinkingLabel = options.thinkingModeLabel === undefined ? this.thinkingModeLabel : (options.thinkingModeLabel || null);
614
442
  if (this.verificationEnabled === nextVerification &&
615
443
  this.autoContinueEnabled === nextAutoContinue &&
616
444
  this.verificationHotkey === nextVerifyHotkey &&
617
- this.autoContinueHotkey === nextAutoHotkey) {
445
+ this.autoContinueHotkey === nextAutoHotkey &&
446
+ this.thinkingHotkey === nextThinkingHotkey &&
447
+ this.thinkingModeLabel === nextThinkingLabel) {
618
448
  return;
619
449
  }
620
450
  this.verificationEnabled = nextVerification;
621
451
  this.autoContinueEnabled = nextAutoContinue;
622
452
  this.verificationHotkey = nextVerifyHotkey;
623
453
  this.autoContinueHotkey = nextAutoHotkey;
624
- this.scheduleRender();
625
- }
626
- /**
627
- * Set the model info string (e.g., "OpenAI · gpt-4")
628
- * This is displayed persistently above the input area.
629
- */
630
- setModelInfo(info) {
631
- if (this.modelInfo === info)
632
- return;
633
- this.modelInfo = info;
454
+ this.thinkingHotkey = nextThinkingHotkey;
455
+ this.thinkingModeLabel = nextThinkingLabel;
634
456
  this.scheduleRender();
635
457
  }
636
458
  /**
@@ -643,33 +465,174 @@ export class TerminalInput extends EventEmitter {
643
465
  this.scheduleRender();
644
466
  }
645
467
  /**
646
- * Render the input area.
647
- * During streaming: renders at terminal bottom (with scroll region)
648
- * After streaming: renders floating below content
468
+ * Surface model/provider context in the controls bar.
469
+ */
470
+ setModelContext(options) {
471
+ const nextModel = options.model?.trim() || null;
472
+ const nextProvider = options.provider?.trim() || null;
473
+ if (this.modelLabel === nextModel && this.providerLabel === nextProvider) {
474
+ return;
475
+ }
476
+ this.modelLabel = nextModel;
477
+ this.providerLabel = nextProvider;
478
+ this.scheduleRender();
479
+ }
480
+ /**
481
+ * Render the floating input area at contentRow.
482
+ *
483
+ * The chat box "floats" - it renders right below the last streamed content.
484
+ * As content is added, contentRow advances, and the chat box moves down.
485
+ * No scroll regions - pure floating behavior.
649
486
  */
650
487
  render() {
651
488
  if (!this.canRender())
652
489
  return;
653
490
  if (this.isRendering)
654
491
  return;
492
+ const streamingActive = this.mode === 'streaming' || isStreamingMode();
493
+ // During streaming, throttle re-renders
494
+ if (streamingActive && this.lastStreamingRender > 0) {
495
+ const elapsed = Date.now() - this.lastStreamingRender;
496
+ const waitMs = Math.max(0, this.streamingRenderInterval - elapsed);
497
+ if (waitMs > 0) {
498
+ this.renderDirty = true;
499
+ this.scheduleStreamingRender(waitMs);
500
+ return;
501
+ }
502
+ }
655
503
  const shouldSkip = !this.renderDirty &&
656
504
  this.buffer === this.lastRenderContent &&
657
505
  this.cursor === this.lastRenderCursor;
658
506
  this.renderDirty = false;
659
- // Skip if nothing changed (unless explicitly forced)
660
507
  if (shouldSkip) {
661
508
  return;
662
509
  }
663
- // If write lock is held, defer render
664
510
  if (writeLock.isLocked()) {
665
511
  writeLock.safeWrite(() => this.render());
666
512
  return;
667
513
  }
514
+ this.renderPinnedChatBox();
515
+ }
516
+ /**
517
+ * Unified scroll region renderer.
518
+ * Chat box is ALWAYS pinned at the bottom of the terminal.
519
+ * Content scrolls in the region above the chat box.
520
+ */
521
+ renderPinnedChatBox() {
522
+ const { rows, cols } = this.getSize();
523
+ const maxWidth = Math.max(8, cols - 4);
524
+ const streamingActive = this.mode === 'streaming' || isStreamingMode();
525
+ // Wrap buffer into display lines
526
+ const { lines, cursorLine, cursorCol } = this.wrapBuffer(maxWidth);
527
+ const maxVisible = Math.max(1, Math.min(this.config.maxLines, rows - 3));
528
+ const displayLines = Math.min(lines.length, maxVisible);
529
+ const metaLines = this.buildMetaLines(cols - 2);
530
+ // Calculate display window (keep cursor visible)
531
+ let startLine = 0;
532
+ if (lines.length > displayLines) {
533
+ startLine = Math.max(0, cursorLine - displayLines + 1);
534
+ startLine = Math.min(startLine, lines.length - displayLines);
535
+ }
536
+ const visibleLines = lines.slice(startLine, startLine + displayLines);
537
+ const adjustedCursorLine = cursorLine - startLine;
538
+ // Chat box height
539
+ const chatBoxHeight = this.getChatBoxHeight();
540
+ // ALWAYS pin chat box at absolute bottom
541
+ const chatBoxStartRow = Math.max(1, rows - chatBoxHeight + 1);
542
+ const scrollEnd = chatBoxStartRow - 1;
543
+ writeLock.lock('terminalInput.renderPinned');
668
544
  this.isRendering = true;
669
- writeLock.lock('terminalInput.render');
670
545
  try {
671
- // Always render floating right after content (no wasted space)
672
- this.renderFloatingInputArea();
546
+ this.write(ESC.SAVE);
547
+ this.write(ESC.HIDE);
548
+ // Temporarily reset scroll region to write chat box cleanly
549
+ if (this.scrollRegionActive) {
550
+ this.write(ESC.RESET_SCROLL);
551
+ }
552
+ // Clear the chat box area
553
+ for (let i = 0; i < chatBoxHeight; i++) {
554
+ const row = chatBoxStartRow + i;
555
+ if (row <= rows) {
556
+ this.write(ESC.TO(row, 1));
557
+ this.write(ESC.CLEAR_LINE);
558
+ }
559
+ }
560
+ let currentRow = chatBoxStartRow;
561
+ // Render scroll/status indicator on the left (Claude Code style)
562
+ const scrollIndicator = this.buildScrollIndicator();
563
+ // Meta/status header with scroll indicator
564
+ for (const metaLine of metaLines) {
565
+ this.write(ESC.TO(currentRow, 1));
566
+ this.write(metaLine);
567
+ currentRow += 1;
568
+ }
569
+ // Separator line with scroll status
570
+ this.write(ESC.TO(currentRow, 1));
571
+ const dividerLabel = scrollIndicator || undefined;
572
+ this.write(renderDivider(cols - 2, dividerLabel));
573
+ currentRow += 1;
574
+ // Render input lines
575
+ let finalRow = currentRow;
576
+ let finalCol = 3;
577
+ for (let i = 0; i < visibleLines.length; i++) {
578
+ const rowNum = currentRow + i;
579
+ this.write(ESC.TO(rowNum, 1));
580
+ const line = visibleLines[i] ?? '';
581
+ const isFirstLine = (startLine + i) === 0;
582
+ const isCursorLine = i === adjustedCursorLine;
583
+ this.write(ESC.BG_DARK);
584
+ this.write(ESC.DIM);
585
+ this.write(isFirstLine ? this.config.promptChar : this.config.continuationChar);
586
+ this.write(ESC.RESET);
587
+ this.write(ESC.BG_DARK);
588
+ if (isCursorLine) {
589
+ const col = Math.min(cursorCol, line.length);
590
+ const before = line.slice(0, col);
591
+ const at = col < line.length ? line[col] : ' ';
592
+ const after = col < line.length ? line.slice(col + 1) : '';
593
+ this.write(before);
594
+ this.write(ESC.REVERSE + ESC.BOLD);
595
+ this.write(at);
596
+ this.write(ESC.RESET + ESC.BG_DARK);
597
+ this.write(after);
598
+ finalRow = rowNum;
599
+ finalCol = this.config.promptChar.length + col + 1;
600
+ }
601
+ else {
602
+ this.write(line);
603
+ }
604
+ // Pad to edge
605
+ const lineLen = this.config.promptChar.length + line.length + (isCursorLine && cursorCol >= line.length ? 1 : 0);
606
+ const padding = Math.max(0, cols - lineLen - 1);
607
+ if (padding > 0)
608
+ this.write(' '.repeat(padding));
609
+ this.write(ESC.RESET);
610
+ }
611
+ // Mode controls line with all keyboard shortcuts
612
+ const controlRow = currentRow + visibleLines.length;
613
+ this.write(ESC.TO(controlRow, 1));
614
+ this.write(this.buildModeControls(cols));
615
+ // Restore scroll region and cursor
616
+ if (this.scrollRegionActive) {
617
+ // Restore scroll region
618
+ this.write(ESC.SET_SCROLL(1, scrollEnd));
619
+ // Restore cursor to where it was before rendering (preserves column position)
620
+ this.write(ESC.RESTORE);
621
+ }
622
+ else {
623
+ // Not streaming - position cursor in input box
624
+ this.write(ESC.RESTORE);
625
+ this.write(ESC.TO(finalRow, Math.min(finalCol, cols)));
626
+ }
627
+ this.write(ESC.SHOW);
628
+ // Update state
629
+ this.lastRenderContent = this.buffer;
630
+ this.lastRenderCursor = this.cursor;
631
+ this.lastStreamingRender = streamingActive ? Date.now() : 0;
632
+ if (this.streamingRenderTimer) {
633
+ clearTimeout(this.streamingRenderTimer);
634
+ this.streamingRenderTimer = null;
635
+ }
673
636
  }
674
637
  finally {
675
638
  writeLock.unlock();
@@ -677,99 +640,231 @@ export class TerminalInput extends EventEmitter {
677
640
  }
678
641
  }
679
642
  /**
680
- * Build status bar showing streaming/ready status and key info.
681
- * This is the TOP line above the input area - minimal Claude Code style.
643
+ * Build compact meta line above the divider.
644
+ * Shows model/provider and key metrics in a single line.
682
645
  */
683
- buildStatusBar(cols) {
684
- const maxWidth = cols - 2;
685
- const parts = [];
686
- // Streaming status with elapsed time (left side)
687
- if (this.mode === 'streaming') {
688
- let statusText = '● Streaming';
689
- if (this.streamingStartTime) {
690
- const elapsed = Math.floor((Date.now() - this.streamingStartTime) / 1000);
691
- const mins = Math.floor(elapsed / 60);
692
- const secs = elapsed % 60;
693
- statusText += mins > 0 ? ` ${mins}m ${secs}s` : ` ${secs}s`;
694
- }
695
- parts.push(`\x1b[32m${statusText}\x1b[0m`); // Green
646
+ buildMetaLines(width) {
647
+ const leftParts = [];
648
+ const rightParts = [];
649
+ // Model/provider info (left side)
650
+ if (this.modelLabel) {
651
+ const modelText = this.providerLabel
652
+ ? `${this.modelLabel} @ ${this.providerLabel}`
653
+ : this.modelLabel;
654
+ leftParts.push({ text: modelText, tone: 'info' });
655
+ }
656
+ // Elapsed time (right side)
657
+ if (this.metaElapsedSeconds !== null) {
658
+ rightParts.push({ text: `⏱ ${this.formatElapsedLabel(this.metaElapsedSeconds)}`, tone: 'muted' });
659
+ }
660
+ // Token usage (right side)
661
+ if (this.metaTokensUsed !== null) {
662
+ const formattedUsed = this.formatTokenCount(this.metaTokensUsed);
663
+ const formattedLimit = this.metaTokenLimit ? `/${this.formatTokenCount(this.metaTokenLimit)}` : '';
664
+ rightParts.push({ text: `⊛ ${formattedUsed}${formattedLimit}`, tone: 'muted' });
665
+ }
666
+ // Context remaining warning
667
+ const tokensRemaining = this.computeTokensRemaining();
668
+ if (tokensRemaining !== null) {
669
+ const contextPct = this.contextUsage !== null ? `${100 - this.contextUsage}%` : '';
670
+ rightParts.push({ text: `↓${tokensRemaining} ${contextPct}`, tone: this.contextUsage && this.contextUsage > 80 ? 'warn' : 'muted' });
671
+ }
672
+ // Thinking indicator
673
+ if (this.metaThinkingMs !== null) {
674
+ leftParts.push({ text: formatThinking(this.metaThinkingMs, this.metaThinkingHasContent), tone: 'info' });
675
+ }
676
+ if (!leftParts.length && !rightParts.length) {
677
+ return [];
678
+ }
679
+ // Render left and right aligned
680
+ if (!rightParts.length || width < 50) {
681
+ return [renderStatusLine([...leftParts, ...rightParts], width)];
682
+ }
683
+ const leftWidth = Math.max(12, Math.floor(width * 0.5));
684
+ const rightWidth = Math.max(14, width - leftWidth - 1);
685
+ const leftText = renderStatusLine(leftParts, leftWidth);
686
+ const rightText = renderStatusLine(rightParts, rightWidth);
687
+ const spacing = Math.max(1, width - this.visibleLength(leftText) - this.visibleLength(rightText));
688
+ return [`${leftText}${' '.repeat(spacing)}${rightText}`];
689
+ }
690
+ /**
691
+ * Build mode controls line with all keyboard shortcuts.
692
+ * Shows status, all toggles, and contextual information.
693
+ * Enhanced with comprehensive feature status display.
694
+ */
695
+ buildModeControls(cols) {
696
+ const width = Math.max(8, cols - 2);
697
+ const leftParts = [];
698
+ const rightParts = [];
699
+ // Streaming indicator with animated spinner
700
+ if (this.streamingLabel) {
701
+ leftParts.push({ text: `◐ ${this.streamingLabel}`, tone: 'info' });
702
+ }
703
+ // Override status (warnings, errors)
704
+ if (this.overrideStatusMessage) {
705
+ leftParts.push({ text: `⚠ ${this.overrideStatusMessage}`, tone: 'warn' });
706
+ }
707
+ // Main status message
708
+ if (this.statusMessage) {
709
+ leftParts.push({ text: this.statusMessage, tone: this.streamingLabel ? 'muted' : 'info' });
710
+ }
711
+ // === SCROLLBACK INDICATOR ===
712
+ if (this.isInScrollbackMode && this.scrollbackOffset > 0) {
713
+ const scrollInfo = `↑${this.scrollbackOffset}`;
714
+ leftParts.push({ text: scrollInfo, tone: 'info' });
715
+ // Show scrollback help hint
716
+ leftParts.push({ text: `${this.formatHotkey('alt+s')}exit`, tone: 'muted' });
717
+ }
718
+ // === KEYBOARD SHORTCUTS ===
719
+ // Interrupt shortcut (during streaming)
720
+ if (this.mode === 'streaming' || this.scrollRegionActive) {
721
+ leftParts.push({ text: `${this.formatHotkey('esc')} stop`, tone: 'warn' });
722
+ }
723
+ // Edit mode toggle (Shift+Tab)
724
+ const editHotkey = this.formatHotkey('shift+tab');
725
+ const editIcon = this.editMode === 'display-edits' ? '✓' : '?';
726
+ const editLabel = this.editMode === 'display-edits' ? 'edits:auto' : 'edits:ask';
727
+ const editTone = this.editMode === 'display-edits' ? 'success' : 'muted';
728
+ leftParts.push({ text: `${editHotkey}${editIcon}${editLabel}`, tone: editTone });
729
+ // Verification toggle (Alt+V)
730
+ const verifyIcon = this.verificationEnabled ? '✓' : '○';
731
+ const verifyHotkey = this.formatHotkey(this.verificationHotkey || 'alt+v');
732
+ const verifyLabel = this.verificationEnabled ? 'verify' : 'no-verify';
733
+ leftParts.push({ text: `${verifyHotkey}${verifyIcon}${verifyLabel}`, tone: this.verificationEnabled ? 'success' : 'muted' });
734
+ // Auto-continue toggle (Alt+C)
735
+ const autoIcon = this.autoContinueEnabled ? '↻' : '○';
736
+ const continueHotkey = this.formatHotkey(this.autoContinueHotkey || 'alt+c');
737
+ const continueLabel = this.autoContinueEnabled ? 'auto' : 'manual';
738
+ leftParts.push({ text: `${continueHotkey}${autoIcon}${continueLabel}`, tone: this.autoContinueEnabled ? 'info' : 'muted' });
739
+ // Thinking mode toggle (if available)
740
+ if (this.thinkingModeLabel) {
741
+ const thinkingHotkey = this.formatHotkey(this.thinkingHotkey || '/thinking');
742
+ rightParts.push({ text: `${thinkingHotkey}◐${this.thinkingModeLabel}`, tone: 'info' });
743
+ }
744
+ // === CONTEXTUAL INFO ===
745
+ // Queued commands
746
+ if (this.queue.length > 0) {
747
+ const queueIcon = this.mode === 'streaming' ? '⏳' : '▸';
748
+ leftParts.push({ text: `${queueIcon}${this.queue.length}queued`, tone: 'info' });
749
+ }
750
+ // Scrollback buffer size (when significant)
751
+ if (this.scrollbackBuffer.length > 100 && !this.isInScrollbackMode) {
752
+ const bufferHint = `${this.formatHotkey('alt+s')}↕${Math.floor(this.scrollbackBuffer.length / 100) * 100}+L`;
753
+ rightParts.push({ text: bufferHint, tone: 'muted' });
696
754
  }
697
- // Queue indicator during streaming
698
- if (this.mode === 'streaming' && this.queue.length > 0) {
699
- parts.push(`\x1b[36mqueued: ${this.queue.length}\x1b[0m`); // Cyan
755
+ // Multi-line indicator
756
+ if (this.buffer.includes('\n')) {
757
+ const lineCount = this.buffer.split('\n').length;
758
+ rightParts.push({ text: `${lineCount}L`, tone: 'muted' });
700
759
  }
701
760
  // Paste indicator
702
761
  if (this.pastePlaceholders.length > 0) {
703
- const totalLines = this.pastePlaceholders.reduce((sum, p) => sum + p.lineCount, 0);
704
- parts.push(`\x1b[36m📋 ${totalLines}L\x1b[0m`);
762
+ const latest = this.pastePlaceholders[this.pastePlaceholders.length - 1];
763
+ rightParts.push({
764
+ text: `paste#${latest.id}+${latest.lineCount}L`,
765
+ tone: 'info',
766
+ });
705
767
  }
706
- // Override/warning status
707
- if (this.overrideStatusMessage) {
708
- parts.push(`\x1b[33m⚠ ${this.overrideStatusMessage}\x1b[0m`); // Yellow
768
+ // Context remaining warning with visual indicator
769
+ const contextRemaining = this.computeContextRemaining();
770
+ if (contextRemaining !== null) {
771
+ const tone = contextRemaining <= 10 ? 'warn' : contextRemaining <= 30 ? 'info' : 'muted';
772
+ const icon = contextRemaining <= 10 ? '⚠' : '⊛';
773
+ const label = contextRemaining === 0 && this.contextUsage !== null
774
+ ? `${icon}compact!`
775
+ : `${icon}${contextRemaining}%`;
776
+ rightParts.push({ text: label, tone });
777
+ }
778
+ // Model/provider quick reference (compact)
779
+ if (this.modelLabel && !this.streamingLabel) {
780
+ const shortModel = this.modelLabel.length > 12 ? this.modelLabel.slice(0, 10) + '..' : this.modelLabel;
781
+ rightParts.push({ text: shortModel, tone: 'muted' });
782
+ }
783
+ // Render: left-aligned shortcuts, right-aligned context info
784
+ if (!rightParts.length || width < 60) {
785
+ const merged = rightParts.length ? [...leftParts, ...rightParts] : leftParts;
786
+ return renderStatusLine(merged, width);
787
+ }
788
+ const leftWidth = Math.max(12, Math.floor(width * 0.65));
789
+ const rightWidth = Math.max(14, width - leftWidth - 1);
790
+ const leftText = renderStatusLine(leftParts, leftWidth);
791
+ const rightText = renderStatusLine(rightParts, rightWidth);
792
+ const spacing = Math.max(1, width - this.visibleLength(leftText) - this.visibleLength(rightText));
793
+ return `${leftText}${' '.repeat(spacing)}${rightText}`;
794
+ }
795
+ formatHotkey(hotkey) {
796
+ const normalized = hotkey.trim().toLowerCase();
797
+ if (!normalized)
798
+ return hotkey;
799
+ const parts = normalized.split('+').filter(Boolean);
800
+ const map = {
801
+ shift: '⇧',
802
+ sh: '⇧',
803
+ alt: '⌥',
804
+ option: '⌥',
805
+ opt: '⌥',
806
+ ctrl: '⌃',
807
+ control: '⌃',
808
+ cmd: '⌘',
809
+ meta: '⌘',
810
+ };
811
+ const formatted = parts
812
+ .map((part) => {
813
+ const symbol = map[part];
814
+ if (symbol)
815
+ return symbol;
816
+ return part.length === 1 ? part.toUpperCase() : part.toUpperCase();
817
+ })
818
+ .join('');
819
+ return formatted || hotkey;
820
+ }
821
+ computeContextRemaining() {
822
+ if (this.contextUsage === null) {
823
+ return null;
709
824
  }
710
- // If idle with empty buffer, show quick shortcuts
711
- if (this.mode !== 'streaming' && this.buffer.length === 0 && parts.length === 0) {
712
- return `${ESC.DIM}Type a message or / for commands${ESC.RESET}`;
825
+ return Math.max(0, this.contextAutoCompactThreshold - this.contextUsage);
826
+ }
827
+ computeTokensRemaining() {
828
+ if (this.metaTokensUsed === null || this.metaTokenLimit === null) {
829
+ return null;
713
830
  }
714
- // Multi-line indicator
715
- if (this.buffer.includes('\n')) {
716
- parts.push(`${ESC.DIM}${this.buffer.split('\n').length}L${ESC.RESET}`);
831
+ const remaining = Math.max(0, this.metaTokenLimit - this.metaTokensUsed);
832
+ return this.formatTokenCount(remaining);
833
+ }
834
+ formatElapsedLabel(seconds) {
835
+ if (seconds < 60) {
836
+ return `${seconds}s`;
717
837
  }
718
- if (parts.length === 0) {
719
- return ''; // Empty status bar when idle
838
+ const mins = Math.floor(seconds / 60);
839
+ const secs = seconds % 60;
840
+ return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
841
+ }
842
+ formatTokenCount(value) {
843
+ if (!Number.isFinite(value)) {
844
+ return `${value}`;
720
845
  }
721
- const joined = parts.join(`${ESC.DIM} · ${ESC.RESET}`);
722
- return joined.slice(0, maxWidth);
846
+ if (value >= 1_000_000) {
847
+ return `${(value / 1_000_000).toFixed(1)}M`;
848
+ }
849
+ if (value >= 1_000) {
850
+ return `${(value / 1_000).toFixed(1)}k`;
851
+ }
852
+ return `${Math.round(value)}`;
853
+ }
854
+ visibleLength(value) {
855
+ const ansiPattern = /\u001B\[[0-?]*[ -/]*[@-~]/g;
856
+ return value.replace(ansiPattern, '').length;
723
857
  }
724
858
  /**
725
- * Build mode controls line showing toggles and context info.
726
- * This is the BOTTOM line below the input area - Claude Code style layout with erosolar features.
727
- *
728
- * Layout: [toggles on left] ... [context info on right]
859
+ * Debug-only snapshot used by tests to assert rendered strings without
860
+ * needing a TTY. Not used by production code.
729
861
  */
730
- buildModeControls(cols) {
731
- const maxWidth = cols - 2;
732
- // Use schema-defined colors for consistency
733
- const { green: GREEN, yellow: YELLOW, cyan: CYAN, magenta: MAGENTA, red: RED, dim: DIM, reset: R } = UI_COLORS;
734
- // Mode toggles with colors (following ModeControlsSchema)
735
- const toggles = [];
736
- // Edit mode (green=auto, yellow=ask) - per schema.editMode
737
- if (this.editMode === 'display-edits') {
738
- toggles.push(`${GREEN}⏵⏵ auto-edit${R}`);
739
- }
740
- else {
741
- toggles.push(`${YELLOW}⏸⏸ ask-first${R}`);
742
- }
743
- // Thinking mode (cyan when on) - per schema.thinkingMode
744
- toggles.push(this.thinkingEnabled ? `${CYAN}💭 think${R}` : `${DIM}○ think${R}`);
745
- // Verification (green when on) - per schema.verificationMode
746
- toggles.push(this.verificationEnabled ? `${GREEN}✓ verify${R}` : `${DIM}○ verify${R}`);
747
- // Auto-continue (magenta when on) - per schema.autoContinueMode
748
- toggles.push(this.autoContinueEnabled ? `${MAGENTA}↻ auto${R}` : `${DIM}○ auto${R}`);
749
- const leftPart = toggles.join(`${DIM} · ${R}`) + `${DIM} (⇧⇥)${R}`;
750
- // Context usage with color - per schema.contextUsage thresholds
751
- let rightPart = '';
752
- if (this.contextUsage !== null) {
753
- const rem = Math.max(0, 100 - this.contextUsage);
754
- // Thresholds: critical < 10%, warning < 25%
755
- if (rem < 10)
756
- rightPart = `${RED}⚠ ctx: ${rem}%${R}`;
757
- else if (rem < 25)
758
- rightPart = `${YELLOW}! ctx: ${rem}%${R}`;
759
- else
760
- rightPart = `${DIM}ctx: ${rem}%${R}`;
761
- }
762
- // Calculate visible lengths (strip ANSI)
763
- const strip = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');
764
- const leftLen = strip(leftPart).length;
765
- const rightLen = strip(rightPart).length;
766
- if (leftLen + rightLen < maxWidth - 4) {
767
- return `${leftPart}${' '.repeat(maxWidth - leftLen - rightLen)}${rightPart}`;
768
- }
769
- if (rightLen > 0 && leftLen + 8 < maxWidth) {
770
- return `${leftPart} ${rightPart}`;
771
- }
772
- return leftPart;
862
+ getDebugUiSnapshot(width) {
863
+ const cols = Math.max(8, width ?? this.getSize().cols);
864
+ return {
865
+ meta: this.buildMetaLines(cols - 2),
866
+ controls: this.buildModeControls(cols),
867
+ };
773
868
  }
774
869
  /**
775
870
  * Force a re-render
@@ -792,56 +887,224 @@ export class TerminalInput extends EventEmitter {
792
887
  handleResize() {
793
888
  this.lastRenderContent = '';
794
889
  this.lastRenderCursor = -1;
795
- this.scheduleRender();
890
+ this.resetStreamingRenderThrottle();
891
+ // If in scrollback mode, re-render the scrollback view with new dimensions
892
+ if (this.isInScrollbackMode) {
893
+ this.renderScrollbackView();
894
+ }
895
+ else {
896
+ this.scheduleRender();
897
+ }
796
898
  }
797
- // Track current content row for writing
798
- contentCursorRow = 1;
799
- /**
800
- * Register with display's output interceptor.
801
- * Clears chat box before writes, re-renders after with updated position.
802
- */
803
- registerOutputInterceptor(display) {
804
- if (this.outputInterceptorCleanup) {
805
- this.outputInterceptorCleanup();
806
- }
807
- // Store display reference for streaming timer to use
808
- this.displayRef = display;
809
- // Clear chat box before writes to make room for content
810
- // Re-render is done via periodic timer during streaming, or setContentEndRow after
811
- this.outputInterceptorCleanup = display.registerOutputInterceptor({
812
- beforeWrite: () => {
813
- // Clear chat box to make room for content
814
- this.clearInputArea();
815
- },
816
- afterWrite: () => {
817
- // Render is handled by streaming timer or setContentEndRow
818
- },
819
- });
899
+ /**
900
+ * Enter streaming mode with scroll region.
901
+ * Sets up terminal scroll region to exclude chat box.
902
+ */
903
+ enterStreamingScrollRegion() {
904
+ const { rows } = this.getSize();
905
+ const chatBoxHeight = this.getChatBoxHeight();
906
+ const scrollEnd = Math.max(1, rows - chatBoxHeight);
907
+ writeLock.lock('enterStreamingScrollRegion');
908
+ try {
909
+ // Set scroll region for content area (above chat box)
910
+ this.write(ESC.SET_SCROLL(1, scrollEnd));
911
+ // Position cursor at current content row
912
+ this.write(ESC.TO(Math.min(this.contentRow, scrollEnd), 1));
913
+ this.scrollRegionActive = true;
914
+ this.setStatusMessage('esc to interrupt');
915
+ }
916
+ finally {
917
+ writeLock.unlock();
918
+ }
919
+ // Render pinned chat box at bottom
920
+ this.forceRender();
820
921
  }
821
922
  /**
822
- * Dispose and clean up
923
+ * Exit streaming mode and restore normal operation.
823
924
  */
824
- dispose() {
825
- if (this.disposed)
925
+ exitStreamingScrollRegion() {
926
+ writeLock.lock('exitStreamingScrollRegion');
927
+ try {
928
+ // Reset scroll region to full terminal
929
+ this.write(ESC.RESET_SCROLL);
930
+ this.scrollRegionActive = false;
931
+ this.setStatusMessage('Ready for prompts');
932
+ }
933
+ finally {
934
+ writeLock.unlock();
935
+ }
936
+ // Final render
937
+ this.forceRender();
938
+ }
939
+ /**
940
+ * Render chat box at bottom - now uses unified renderer.
941
+ * @deprecated Use renderPinnedChatBox() directly via render()/forceRender()
942
+ */
943
+ renderChatBoxAtBottom() {
944
+ this.renderPinnedChatBox();
945
+ }
946
+ /**
947
+ * Stream content within the scroll region.
948
+ * Content is written directly and scrolls naturally.
949
+ */
950
+ streamContent(content) {
951
+ if (!content)
826
952
  return;
827
- // Clean up streaming render timer
828
- if (this.streamingRenderTimer) {
829
- clearInterval(this.streamingRenderTimer);
830
- this.streamingRenderTimer = null;
953
+ // Capture content in scrollback buffer
954
+ this.addToScrollback(content);
955
+ writeLock.lock('streamContent');
956
+ try {
957
+ // Write content - scroll region handles scrolling
958
+ this.write(content);
959
+ // Track newlines
960
+ const newlines = (content.match(/\n/g) || []).length;
961
+ this.contentRow += newlines;
962
+ }
963
+ finally {
964
+ writeLock.unlock();
965
+ }
966
+ // Throttle chat box updates during streaming
967
+ this.scheduleStreamingRender(200);
968
+ }
969
+ /**
970
+ * Enable scroll region (no-op in floating mode).
971
+ */
972
+ enableScrollRegion() {
973
+ // No-op: using pure floating approach
974
+ }
975
+ /**
976
+ * Disable scroll region (no-op in floating mode).
977
+ */
978
+ disableScrollRegion() {
979
+ // No-op: using pure floating approach
980
+ }
981
+ /**
982
+ * Calculate chat box height.
983
+ */
984
+ getChatBoxHeight() {
985
+ return 6; // Fixed: meta + divider + input + controls + buffer
986
+ }
987
+ /**
988
+ * @deprecated Use streamContent() instead
989
+ * Register with display's output interceptor - kept for backwards compatibility
990
+ */
991
+ registerOutputInterceptor(_display) {
992
+ // No-op: Use streamContent() for cleaner floating chat box behavior
993
+ }
994
+ /**
995
+ * Write content above the floating chat box.
996
+ * Works both during streaming and when idle.
997
+ */
998
+ writeToScrollRegion(content) {
999
+ if (!content)
1000
+ return;
1001
+ // Capture content in scrollback buffer
1002
+ this.addToScrollback(content);
1003
+ writeLock.lock('writeToScrollRegion');
1004
+ try {
1005
+ // Position cursor at content row and write
1006
+ this.write(ESC.TO(this.contentRow, 1));
1007
+ this.write(content);
1008
+ // Track newlines
1009
+ const newlines = (content.match(/\n/g) || []).length;
1010
+ this.contentRow += newlines;
831
1011
  }
832
- // Clean up output interceptor
833
- if (this.outputInterceptorCleanup) {
834
- this.outputInterceptorCleanup();
835
- this.outputInterceptorCleanup = undefined;
1012
+ finally {
1013
+ writeLock.unlock();
836
1014
  }
837
- // Reset scroll region
838
- this.write('\x1b[r');
839
- // Exit alternate screen buffer (restores main terminal)
840
- if (this.unifiedUIInitialized) {
841
- this.write(ESC.ALT_SCREEN_EXIT);
1015
+ // Re-render chat box below new content (only when not streaming)
1016
+ if (!this.scrollRegionActive) {
1017
+ this.forceRender();
842
1018
  }
1019
+ }
1020
+ /**
1021
+ * Enter alternate screen buffer and clear it.
1022
+ * This gives us full control over the terminal without affecting user's history.
1023
+ */
1024
+ enterAlternateScreen() {
1025
+ writeLock.lock('enterAltScreen');
1026
+ try {
1027
+ this.write(ESC.ENTER_ALT_SCREEN);
1028
+ this.write(ESC.HOME);
1029
+ this.write(ESC.CLEAR_SCREEN);
1030
+ this.contentRow = 1;
1031
+ this.alternateScreenActive = true;
1032
+ }
1033
+ finally {
1034
+ writeLock.unlock();
1035
+ }
1036
+ }
1037
+ /**
1038
+ * Exit alternate screen buffer.
1039
+ * Restores the user's previous terminal content.
1040
+ */
1041
+ exitAlternateScreen() {
1042
+ writeLock.lock('exitAltScreen');
1043
+ try {
1044
+ this.write(ESC.EXIT_ALT_SCREEN);
1045
+ this.alternateScreenActive = false;
1046
+ }
1047
+ finally {
1048
+ writeLock.unlock();
1049
+ }
1050
+ }
1051
+ /**
1052
+ * Check if alternate screen buffer is currently active.
1053
+ */
1054
+ isAlternateScreenActive() {
1055
+ return this.alternateScreenActive;
1056
+ }
1057
+ /**
1058
+ * Get a snapshot of the scrollback buffer (for display on exit).
1059
+ */
1060
+ getScrollbackSnapshot() {
1061
+ return [...this.scrollbackBuffer];
1062
+ }
1063
+ /**
1064
+ * Clear the entire terminal screen and reset content position.
1065
+ * This removes all content including the launching command.
1066
+ */
1067
+ clearScreen() {
1068
+ writeLock.lock('clearScreen');
1069
+ try {
1070
+ this.write(ESC.HOME);
1071
+ this.write(ESC.CLEAR_SCREEN);
1072
+ this.contentRow = 1;
1073
+ }
1074
+ finally {
1075
+ writeLock.unlock();
1076
+ }
1077
+ }
1078
+ /**
1079
+ * Reset content position to row 1.
1080
+ * Does NOT clear the terminal - content starts from current position.
1081
+ */
1082
+ resetContentPosition() {
1083
+ this.contentRow = 1;
1084
+ }
1085
+ /**
1086
+ * Set the content row explicitly (used after banner is written).
1087
+ * This tells the input where content should start flowing from.
1088
+ */
1089
+ setContentRow(row) {
1090
+ this.contentRow = Math.max(1, row);
1091
+ }
1092
+ /**
1093
+ * Get the current content row position.
1094
+ */
1095
+ getContentRow() {
1096
+ return this.contentRow;
1097
+ }
1098
+ /**
1099
+ * Dispose and clean up
1100
+ */
1101
+ dispose() {
1102
+ if (this.disposed)
1103
+ return;
843
1104
  this.disposed = true;
844
1105
  this.enabled = false;
1106
+ this.disableScrollRegion();
1107
+ this.resetStreamingRenderThrottle();
845
1108
  this.disableBracketedPaste();
846
1109
  this.buffer = '';
847
1110
  this.queue = [];
@@ -883,8 +1146,13 @@ export class TerminalInput extends EventEmitter {
883
1146
  break;
884
1147
  }
885
1148
  }
1149
+ /**
1150
+ * Handle Alt/Meta key combinations for mode toggles and navigation.
1151
+ * All major erosolar-cli features accessible via keyboard shortcuts.
1152
+ */
886
1153
  handleMetaKey(key) {
887
1154
  switch (key.name) {
1155
+ // === CURSOR MOVEMENT ===
888
1156
  case 'left':
889
1157
  case 'b':
890
1158
  this.moveCursorWordLeft();
@@ -899,14 +1167,96 @@ export class TerminalInput extends EventEmitter {
899
1167
  case 'return':
900
1168
  this.insertNewline();
901
1169
  break;
1170
+ // === MODE TOGGLES ===
902
1171
  case 'v':
1172
+ // Alt+V: Toggle verification mode (auto-tests after edits)
903
1173
  this.emit('toggleVerify');
904
1174
  break;
905
1175
  case 'c':
1176
+ // Alt+C: Toggle auto-continue mode
906
1177
  this.emit('toggleAutoContinue');
907
1178
  break;
1179
+ case 't':
1180
+ // Alt+T: Toggle/cycle thinking mode
1181
+ this.emit('toggleThinking');
1182
+ break;
1183
+ case 'e':
1184
+ // Alt+E: Toggle edit permission mode (ask/auto)
1185
+ this.toggleEditMode();
1186
+ this.emit('toggleEditMode');
1187
+ break;
1188
+ case 'x':
1189
+ // Alt+X: Clear/compact context
1190
+ this.emit('clearContext');
1191
+ break;
1192
+ // === SCROLLBACK NAVIGATION ===
1193
+ case 's':
1194
+ // Alt+S: Toggle scrollback mode
1195
+ this.toggleScrollbackMode();
1196
+ break;
1197
+ case 'up':
1198
+ // Alt+Up: Quick scroll up into history
1199
+ if (!this.isInScrollbackMode) {
1200
+ this.scrollUp(10);
1201
+ }
1202
+ else {
1203
+ this.scrollUp(1);
1204
+ }
1205
+ break;
1206
+ case 'down':
1207
+ // Alt+Down: Quick scroll down
1208
+ if (this.isInScrollbackMode) {
1209
+ this.scrollDown(1);
1210
+ }
1211
+ break;
1212
+ case 'pageup':
1213
+ // Alt+PageUp: Page up in scrollback
1214
+ this.scrollUp(this.getPageSize());
1215
+ break;
1216
+ case 'pagedown':
1217
+ // Alt+PageDown: Page down in scrollback
1218
+ this.scrollDown(this.getPageSize());
1219
+ break;
1220
+ case 'home':
1221
+ // Alt+Home: Jump to top of scrollback
1222
+ this.scrollToTop();
1223
+ break;
1224
+ case 'end':
1225
+ // Alt+End: Jump to bottom (live)
1226
+ this.scrollToBottom();
1227
+ break;
908
1228
  }
909
1229
  }
1230
+ /**
1231
+ * Get page size for scrollback navigation.
1232
+ */
1233
+ getPageSize() {
1234
+ const { rows } = this.getSize();
1235
+ const chatBoxHeight = this.getChatBoxHeight();
1236
+ return Math.max(5, rows - chatBoxHeight - 2);
1237
+ }
1238
+ /**
1239
+ * Build scroll indicator for the divider line (Claude Code style).
1240
+ * Shows scroll position when in scrollback mode, or history size hint when idle.
1241
+ */
1242
+ buildScrollIndicator() {
1243
+ const bufferSize = this.scrollbackBuffer.length;
1244
+ // In scrollback mode - show position
1245
+ if (this.isInScrollbackMode && this.scrollbackOffset > 0) {
1246
+ const { rows } = this.getSize();
1247
+ const chatBoxHeight = this.getChatBoxHeight();
1248
+ const viewportHeight = Math.max(1, rows - chatBoxHeight);
1249
+ const currentPos = Math.max(0, bufferSize - this.scrollbackOffset - viewportHeight);
1250
+ const pct = bufferSize > 0 ? Math.round((currentPos / bufferSize) * 100) : 0;
1251
+ return `↑${this.scrollbackOffset} · ${pct}% · PgUp/Dn`;
1252
+ }
1253
+ // Not in scrollback - show hint if there's history
1254
+ if (bufferSize > 20) {
1255
+ const sizeLabel = bufferSize >= 1000 ? `${Math.floor(bufferSize / 1000)}k` : `${bufferSize}`;
1256
+ return `↕${sizeLabel}L · PgUp`;
1257
+ }
1258
+ return null;
1259
+ }
910
1260
  handleSpecialKey(_str, key) {
911
1261
  switch (key.name) {
912
1262
  case 'return':
@@ -930,38 +1280,53 @@ export class TerminalInput extends EventEmitter {
930
1280
  this.moveCursorRight();
931
1281
  return true;
932
1282
  case 'up':
933
- this.handleUp();
1283
+ // Ctrl+Shift+Up or Shift+Up: Quick scroll up in scrollback
1284
+ if ((key.ctrl && key.shift) || key.shift) {
1285
+ this.scrollUp(5);
1286
+ }
1287
+ else {
1288
+ this.handleUp();
1289
+ }
934
1290
  return true;
935
1291
  case 'down':
936
- this.handleDown();
1292
+ // Ctrl+Shift+Down or Shift+Down: Quick scroll down in scrollback
1293
+ if ((key.ctrl && key.shift) || key.shift) {
1294
+ this.scrollDown(5);
1295
+ }
1296
+ else {
1297
+ this.handleDown();
1298
+ }
937
1299
  return true;
938
1300
  case 'home':
939
- this.moveCursorToLineStart();
1301
+ // Ctrl+Home or in scrollback mode: scroll to top
1302
+ if (key.ctrl || this.isInScrollbackMode) {
1303
+ this.scrollToTop();
1304
+ }
1305
+ else {
1306
+ this.moveCursorToLineStart();
1307
+ }
940
1308
  return true;
941
1309
  case 'end':
942
- this.moveCursorToLineEnd();
1310
+ // Ctrl+End or in scrollback mode: scroll to bottom (live mode)
1311
+ if (key.ctrl || this.isInScrollbackMode) {
1312
+ this.scrollToBottom();
1313
+ }
1314
+ else {
1315
+ this.moveCursorToLineEnd();
1316
+ }
1317
+ return true;
1318
+ case 'pageup':
1319
+ this.scrollUp(20); // Scroll up by 20 lines
1320
+ return true;
1321
+ case 'pagedown':
1322
+ this.scrollDown(20); // Scroll down by 20 lines
943
1323
  return true;
944
1324
  case 'tab':
945
1325
  if (key.shift) {
946
1326
  this.toggleEditMode();
947
1327
  return true;
948
1328
  }
949
- // Tab: toggle paste expansion if in placeholder, otherwise toggle thinking
950
- if (this.findPlaceholderAt(this.cursor)) {
951
- this.togglePasteExpansion();
952
- }
953
- else {
954
- this.toggleThinking();
955
- }
956
- return true;
957
- case 'escape':
958
- // Esc: interrupt if streaming, otherwise clear buffer
959
- if (this.mode === 'streaming') {
960
- this.emit('interrupt');
961
- }
962
- else if (this.buffer.length > 0) {
963
- this.clear();
964
- }
1329
+ this.insertText(' ');
965
1330
  return true;
966
1331
  }
967
1332
  return false;
@@ -979,7 +1344,6 @@ export class TerminalInput extends EventEmitter {
979
1344
  this.insertPlainText(chunk, insertPos);
980
1345
  this.cursor = insertPos + chunk.length;
981
1346
  this.emit('change', this.buffer);
982
- this.updateSuggestions();
983
1347
  this.scheduleRender();
984
1348
  }
985
1349
  insertNewline() {
@@ -1004,7 +1368,6 @@ export class TerminalInput extends EventEmitter {
1004
1368
  this.cursor = Math.max(0, this.cursor - 1);
1005
1369
  }
1006
1370
  this.emit('change', this.buffer);
1007
- this.updateSuggestions();
1008
1371
  this.scheduleRender();
1009
1372
  }
1010
1373
  deleteForward() {
@@ -1232,13 +1595,12 @@ export class TerminalInput extends EventEmitter {
1232
1595
  timestamp: Date.now(),
1233
1596
  });
1234
1597
  this.emit('queue', text);
1235
- this.clear(); // Clear immediately for queued input, re-render to update queue display
1598
+ this.clear(); // Clear immediately for queued input
1236
1599
  }
1237
1600
  else {
1238
- // In idle mode, clear the input WITHOUT rendering.
1239
- // The caller will display the user message and start streaming.
1240
- // We'll render the input area again after streaming ends.
1241
- this.clear(true); // Skip render - streaming will handle display
1601
+ // In idle mode, clear the input first, then emit submit.
1602
+ // The prompt will be logged as a visible message by the caller.
1603
+ this.clear();
1242
1604
  this.emit('submit', text);
1243
1605
  }
1244
1606
  }
@@ -1255,7 +1617,9 @@ export class TerminalInput extends EventEmitter {
1255
1617
  if (available <= 0)
1256
1618
  return;
1257
1619
  const chunk = clean.slice(0, available);
1258
- if (isMultilinePaste(chunk)) {
1620
+ const isMultiline = isMultilinePaste(chunk);
1621
+ const isShortMultiline = isMultiline && this.shouldInlineMultiline(chunk);
1622
+ if (isMultiline && !isShortMultiline) {
1259
1623
  this.insertPastePlaceholder(chunk);
1260
1624
  }
1261
1625
  else {
@@ -1319,6 +1683,236 @@ export class TerminalInput extends EventEmitter {
1319
1683
  return { lines, cursorLine, cursorCol };
1320
1684
  }
1321
1685
  // ===========================================================================
1686
+ // SCROLLBACK BUFFER
1687
+ // ===========================================================================
1688
+ /**
1689
+ * Add content to the scrollback buffer for history retention
1690
+ */
1691
+ addToScrollback(content) {
1692
+ if (!content)
1693
+ return;
1694
+ // Split content into lines and add to buffer
1695
+ const lines = content.split('\n');
1696
+ for (let i = 0; i < lines.length; i++) {
1697
+ const line = lines[i];
1698
+ if (line !== undefined) {
1699
+ // Only add non-empty lines or preserve newlines between content
1700
+ if (i < lines.length - 1 || line.length > 0) {
1701
+ this.scrollbackBuffer.push(line);
1702
+ }
1703
+ }
1704
+ }
1705
+ // Trim buffer if it exceeds max size
1706
+ while (this.scrollbackBuffer.length > this.maxScrollbackLines) {
1707
+ this.scrollbackBuffer.shift();
1708
+ }
1709
+ // If we're in live mode (not scrolled up), keep offset at 0
1710
+ if (this.scrollbackOffset === 0) {
1711
+ this.isInScrollbackMode = false;
1712
+ }
1713
+ }
1714
+ /**
1715
+ * Scroll up by a number of lines (PageUp)
1716
+ */
1717
+ scrollUp(lines = 10) {
1718
+ const { rows } = this.getSize();
1719
+ const chatBoxHeight = this.getChatBoxHeight();
1720
+ const visibleLines = Math.max(1, rows - chatBoxHeight);
1721
+ // Calculate max scroll offset
1722
+ const maxOffset = Math.max(0, this.scrollbackBuffer.length - visibleLines);
1723
+ this.scrollbackOffset = Math.min(this.scrollbackOffset + lines, maxOffset);
1724
+ this.isInScrollbackMode = this.scrollbackOffset > 0;
1725
+ if (this.isInScrollbackMode) {
1726
+ this.renderScrollbackView();
1727
+ }
1728
+ }
1729
+ /**
1730
+ * Scroll down by a number of lines (PageDown)
1731
+ */
1732
+ scrollDown(lines = 10) {
1733
+ this.scrollbackOffset = Math.max(0, this.scrollbackOffset - lines);
1734
+ this.isInScrollbackMode = this.scrollbackOffset > 0;
1735
+ if (this.isInScrollbackMode) {
1736
+ this.renderScrollbackView();
1737
+ }
1738
+ else {
1739
+ // Returned to live mode - force re-render
1740
+ this.forceRender();
1741
+ }
1742
+ }
1743
+ /**
1744
+ * Jump to the top of scrollback buffer
1745
+ */
1746
+ scrollToTop() {
1747
+ const { rows } = this.getSize();
1748
+ const chatBoxHeight = this.getChatBoxHeight();
1749
+ const visibleLines = Math.max(1, rows - chatBoxHeight);
1750
+ const maxOffset = Math.max(0, this.scrollbackBuffer.length - visibleLines);
1751
+ this.scrollbackOffset = maxOffset;
1752
+ this.isInScrollbackMode = true;
1753
+ this.renderScrollbackView();
1754
+ }
1755
+ /**
1756
+ * Jump to the bottom (live mode)
1757
+ */
1758
+ scrollToBottom() {
1759
+ this.scrollbackOffset = 0;
1760
+ this.isInScrollbackMode = false;
1761
+ this.forceRender();
1762
+ }
1763
+ /**
1764
+ * Toggle scrollback mode on/off (Alt+S hotkey)
1765
+ */
1766
+ toggleScrollbackMode() {
1767
+ if (this.isInScrollbackMode) {
1768
+ this.scrollToBottom();
1769
+ }
1770
+ else if (this.scrollbackBuffer.length > 0) {
1771
+ this.scrollUp(20);
1772
+ }
1773
+ }
1774
+ /**
1775
+ * Render the scrollback buffer view with enhanced visuals
1776
+ * Features:
1777
+ * - Visual scroll position indicator
1778
+ * - Progress bar showing position in history
1779
+ * - Keyboard navigation hints
1780
+ * - Animated indicators
1781
+ */
1782
+ renderScrollbackView() {
1783
+ const { rows, cols } = this.getSize();
1784
+ const chatBoxHeight = this.getChatBoxHeight();
1785
+ const contentHeight = Math.max(1, rows - chatBoxHeight);
1786
+ writeLock.lock('renderScrollback');
1787
+ try {
1788
+ this.write(ESC.SAVE);
1789
+ this.write(ESC.HIDE);
1790
+ // Clear content area
1791
+ for (let i = 1; i <= contentHeight; i++) {
1792
+ this.write(ESC.TO(i, 1));
1793
+ this.write(ESC.CLEAR_LINE);
1794
+ }
1795
+ // Calculate which lines to show
1796
+ const totalLines = this.scrollbackBuffer.length;
1797
+ const startIdx = Math.max(0, totalLines - this.scrollbackOffset - contentHeight);
1798
+ const endIdx = Math.max(0, totalLines - this.scrollbackOffset);
1799
+ const visibleLines = this.scrollbackBuffer.slice(startIdx, endIdx);
1800
+ // Build header bar with navigation hints
1801
+ const headerInfo = this.buildScrollbackHeader(cols, totalLines, startIdx, endIdx);
1802
+ this.write(ESC.TO(1, 1));
1803
+ this.write(headerInfo);
1804
+ // Render visible lines with line numbers and visual guides
1805
+ const lineNumWidth = String(totalLines).length + 1;
1806
+ const contentStart = 2; // Start after header
1807
+ for (let i = 0; i < Math.min(visibleLines.length, contentHeight - 1); i++) {
1808
+ const line = visibleLines[i] ?? '';
1809
+ const lineNum = startIdx + i + 1;
1810
+ this.write(ESC.TO(contentStart + i, 1));
1811
+ // Line number gutter
1812
+ const numStr = String(lineNum).padStart(lineNumWidth, ' ');
1813
+ this.write(theme.ui.muted(`${numStr} │ `));
1814
+ // Content with truncation
1815
+ const gutterWidth = lineNumWidth + 4;
1816
+ const maxLen = cols - gutterWidth - 2;
1817
+ const displayLine = line.length > maxLen ? line.slice(0, maxLen - 3) + '...' : line;
1818
+ this.write(displayLine);
1819
+ }
1820
+ // Add visual scroll track on the right edge
1821
+ this.renderScrollTrack(cols, contentHeight, totalLines, startIdx, endIdx);
1822
+ this.write(ESC.RESTORE);
1823
+ this.write(ESC.SHOW);
1824
+ }
1825
+ finally {
1826
+ writeLock.unlock();
1827
+ }
1828
+ // Re-render chat box
1829
+ this.forceRender();
1830
+ }
1831
+ /**
1832
+ * Build scrollback header with navigation hints
1833
+ */
1834
+ buildScrollbackHeader(cols, totalLines, startIdx, endIdx) {
1835
+ const percentage = Math.round((endIdx / totalLines) * 100);
1836
+ // Animated scroll indicator
1837
+ const scrollFrames = ['◆', '◇', '◆', '◈'];
1838
+ this.scrollIndicatorFrame = (this.scrollIndicatorFrame + 1) % scrollFrames.length;
1839
+ const indicator = scrollFrames[this.scrollIndicatorFrame];
1840
+ // Build header parts
1841
+ const leftPart = theme.info(`${indicator} SCROLLBACK`) +
1842
+ theme.ui.muted(` [${startIdx + 1}-${endIdx} of ${totalLines}]`);
1843
+ const progressBar = this.buildProgressBar(percentage, 15);
1844
+ const rightPart = progressBar +
1845
+ theme.ui.muted(` ${percentage}%`) +
1846
+ theme.ui.muted(' │ ') +
1847
+ theme.primary('PgUp') + theme.ui.muted('/') + theme.primary('PgDn') +
1848
+ theme.ui.muted(' scroll · ') +
1849
+ theme.primary('End') + theme.ui.muted(' exit');
1850
+ const leftLen = this.visibleLength(leftPart);
1851
+ const rightLen = this.visibleLength(rightPart);
1852
+ const padding = Math.max(1, cols - leftLen - rightLen - 2);
1853
+ return `${leftPart}${' '.repeat(padding)}${rightPart}`;
1854
+ }
1855
+ /**
1856
+ * Render visual scroll track on the right side
1857
+ */
1858
+ renderScrollTrack(cols, contentHeight, totalLines, startIdx, endIdx) {
1859
+ if (totalLines <= contentHeight || cols < 40)
1860
+ return;
1861
+ const trackHeight = contentHeight - 1; // Exclude header
1862
+ const viewportRatio = (endIdx - startIdx) / totalLines;
1863
+ const positionRatio = startIdx / Math.max(1, totalLines - (endIdx - startIdx));
1864
+ // Calculate thumb size and position
1865
+ const thumbSize = Math.max(1, Math.round(viewportRatio * trackHeight));
1866
+ const thumbStart = Math.round(positionRatio * (trackHeight - thumbSize));
1867
+ // Render track on right edge
1868
+ for (let i = 0; i < trackHeight; i++) {
1869
+ const row = 2 + i; // Start after header
1870
+ this.write(ESC.TO(row, cols));
1871
+ if (i >= thumbStart && i < thumbStart + thumbSize) {
1872
+ // Thumb (viewport indicator)
1873
+ this.write(theme.accent('█'));
1874
+ }
1875
+ else {
1876
+ // Track background
1877
+ this.write(theme.ui.muted('░'));
1878
+ }
1879
+ }
1880
+ }
1881
+ /**
1882
+ * Build a visual progress bar
1883
+ */
1884
+ buildProgressBar(percentage, width = 10) {
1885
+ const filled = Math.round((percentage / 100) * width);
1886
+ const empty = width - filled;
1887
+ const bar = theme.accent('█'.repeat(filled)) +
1888
+ theme.ui.muted('░'.repeat(empty));
1889
+ return `${theme.ui.muted('[')}${bar}${theme.ui.muted(']')}`;
1890
+ }
1891
+ /**
1892
+ * Get scrollback buffer content (for persistence)
1893
+ */
1894
+ getScrollbackBuffer() {
1895
+ return [...this.scrollbackBuffer];
1896
+ }
1897
+ /**
1898
+ * Load scrollback buffer (for restoration)
1899
+ */
1900
+ loadScrollbackBuffer(lines) {
1901
+ this.scrollbackBuffer = [...lines];
1902
+ // Trim if necessary
1903
+ while (this.scrollbackBuffer.length > this.maxScrollbackLines) {
1904
+ this.scrollbackBuffer.shift();
1905
+ }
1906
+ }
1907
+ /**
1908
+ * Clear scrollback buffer
1909
+ */
1910
+ clearScrollbackBuffer() {
1911
+ this.scrollbackBuffer = [];
1912
+ this.scrollbackOffset = 0;
1913
+ this.isInScrollbackMode = false;
1914
+ }
1915
+ // ===========================================================================
1322
1916
  // UTILITIES
1323
1917
  // ===========================================================================
1324
1918
  getComposedLength() {
@@ -1391,17 +1985,19 @@ export class TerminalInput extends EventEmitter {
1391
1985
  this.shiftPlaceholders(position, text.length);
1392
1986
  this.buffer = this.buffer.slice(0, position) + text + this.buffer.slice(position);
1393
1987
  }
1988
+ shouldInlineMultiline(content) {
1989
+ const lines = content.split('\n').length;
1990
+ const maxInlineLines = 4;
1991
+ const maxInlineChars = 240;
1992
+ return lines <= maxInlineLines && content.length <= maxInlineChars;
1993
+ }
1394
1994
  findPlaceholderAt(position) {
1395
1995
  return this.pastePlaceholders.find((ph) => position >= ph.start && position < ph.end) ?? null;
1396
1996
  }
1397
- buildPlaceholder(summary) {
1997
+ buildPlaceholder(lineCount) {
1398
1998
  const id = ++this.pasteCounter;
1399
- const lang = summary.language ? ` ${summary.language.toUpperCase()}` : '';
1400
- // Show first line preview (truncated)
1401
- const preview = summary.preview.length > 30
1402
- ? `${summary.preview.slice(0, 30)}...`
1403
- : summary.preview;
1404
- const placeholder = `[📋 #${id}${lang} ${summary.lineCount}L] "${preview}"`;
1999
+ const plural = lineCount === 1 ? '' : 's';
2000
+ const placeholder = `[Pasted text #${id} +${lineCount} line${plural}]`;
1405
2001
  return { id, placeholder };
1406
2002
  }
1407
2003
  insertPastePlaceholder(content) {
@@ -1409,67 +2005,21 @@ export class TerminalInput extends EventEmitter {
1409
2005
  if (available <= 0)
1410
2006
  return;
1411
2007
  const cleanContent = content.slice(0, available);
1412
- const summary = generatePasteSummary(cleanContent);
1413
- // For short pastes (< 5 lines), show full content instead of placeholder
1414
- if (summary.lineCount < 5) {
1415
- const placeholder = this.findPlaceholderAt(this.cursor);
1416
- const insertPos = placeholder && this.cursor > placeholder.start ? placeholder.end : this.cursor;
1417
- this.insertPlainText(cleanContent, insertPos);
1418
- this.cursor = insertPos + cleanContent.length;
1419
- return;
1420
- }
1421
- const { id, placeholder } = this.buildPlaceholder(summary);
2008
+ const lineCount = cleanContent.split('\n').length;
2009
+ const { id, placeholder } = this.buildPlaceholder(lineCount);
1422
2010
  const insertPos = this.cursor;
1423
2011
  this.shiftPlaceholders(insertPos, placeholder.length);
1424
2012
  this.pastePlaceholders.push({
1425
2013
  id,
1426
2014
  content: cleanContent,
1427
- lineCount: summary.lineCount,
2015
+ lineCount,
1428
2016
  placeholder,
1429
2017
  start: insertPos,
1430
2018
  end: insertPos + placeholder.length,
1431
- summary,
1432
- expanded: false,
1433
2019
  });
1434
2020
  this.buffer = this.buffer.slice(0, insertPos) + placeholder + this.buffer.slice(insertPos);
1435
2021
  this.cursor = insertPos + placeholder.length;
1436
2022
  }
1437
- /**
1438
- * Toggle expansion of a paste placeholder at the current cursor position.
1439
- * When expanded, shows first 3 and last 2 lines of the content.
1440
- */
1441
- togglePasteExpansion() {
1442
- const placeholder = this.findPlaceholderAt(this.cursor);
1443
- if (!placeholder)
1444
- return false;
1445
- placeholder.expanded = !placeholder.expanded;
1446
- // Update the placeholder text in buffer
1447
- const newPlaceholder = placeholder.expanded
1448
- ? this.buildExpandedPlaceholder(placeholder)
1449
- : this.buildPlaceholder(placeholder.summary).placeholder;
1450
- const lengthDiff = newPlaceholder.length - placeholder.placeholder.length;
1451
- // Update buffer
1452
- this.buffer =
1453
- this.buffer.slice(0, placeholder.start) +
1454
- newPlaceholder +
1455
- this.buffer.slice(placeholder.end);
1456
- // Update placeholder tracking
1457
- placeholder.placeholder = newPlaceholder;
1458
- placeholder.end = placeholder.start + newPlaceholder.length;
1459
- // Shift other placeholders
1460
- this.shiftPlaceholders(placeholder.end, lengthDiff, placeholder.id);
1461
- this.scheduleRender();
1462
- return true;
1463
- }
1464
- buildExpandedPlaceholder(ph) {
1465
- const lines = ph.content.split('\n');
1466
- const firstLines = lines.slice(0, 3).map(l => l.slice(0, 60)).join('\n');
1467
- const lastLines = lines.length > 5
1468
- ? '\n...\n' + lines.slice(-2).map(l => l.slice(0, 60)).join('\n')
1469
- : '';
1470
- const lang = ph.summary.language ? ` ${ph.summary.language.toUpperCase()}` : '';
1471
- return `[📋 #${ph.id}${lang} ${ph.lineCount}L ▼]\n${firstLines}${lastLines}\n[/📋 #${ph.id}]`;
1472
- }
1473
2023
  deletePlaceholder(placeholder) {
1474
2024
  const length = placeholder.end - placeholder.start;
1475
2025
  this.buffer = this.buffer.slice(0, placeholder.start) + this.buffer.slice(placeholder.end);
@@ -1477,7 +2027,11 @@ export class TerminalInput extends EventEmitter {
1477
2027
  this.shiftPlaceholders(placeholder.end, -length, placeholder.id);
1478
2028
  this.cursor = placeholder.start;
1479
2029
  }
1480
- updateContextUsage(value) {
2030
+ updateContextUsage(value, autoCompactThreshold) {
2031
+ if (typeof autoCompactThreshold === 'number' && Number.isFinite(autoCompactThreshold)) {
2032
+ const boundedThreshold = Math.max(1, Math.min(100, Math.round(autoCompactThreshold)));
2033
+ this.contextAutoCompactThreshold = boundedThreshold;
2034
+ }
1481
2035
  if (value === null || !Number.isFinite(value)) {
1482
2036
  this.contextUsage = null;
1483
2037
  }
@@ -1504,6 +2058,28 @@ export class TerminalInput extends EventEmitter {
1504
2058
  const next = this.editMode === 'display-edits' ? 'ask-permission' : 'display-edits';
1505
2059
  this.setEditMode(next);
1506
2060
  }
2061
+ scheduleStreamingRender(delayMs) {
2062
+ if (this.streamingRenderTimer)
2063
+ return;
2064
+ const wait = Math.max(16, delayMs);
2065
+ this.streamingRenderTimer = setTimeout(() => {
2066
+ this.streamingRenderTimer = null;
2067
+ // During streaming, only update chat box (not full render)
2068
+ if (this.scrollRegionActive) {
2069
+ this.renderChatBoxAtBottom();
2070
+ }
2071
+ else {
2072
+ this.render();
2073
+ }
2074
+ }, wait);
2075
+ }
2076
+ resetStreamingRenderThrottle() {
2077
+ if (this.streamingRenderTimer) {
2078
+ clearTimeout(this.streamingRenderTimer);
2079
+ this.streamingRenderTimer = null;
2080
+ }
2081
+ this.lastStreamingRender = 0;
2082
+ }
1507
2083
  scheduleRender() {
1508
2084
  if (!this.canRender())
1509
2085
  return;