erosolar-cli 1.7.327 → 1.7.328

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 (323) hide show
  1. package/README.md +148 -24
  2. package/dist/alpha-zero/agentWrapper.d.ts +84 -0
  3. package/dist/alpha-zero/agentWrapper.d.ts.map +1 -0
  4. package/dist/alpha-zero/agentWrapper.js +171 -0
  5. package/dist/alpha-zero/agentWrapper.js.map +1 -0
  6. package/dist/alpha-zero/codeEvaluator.d.ts +25 -0
  7. package/dist/alpha-zero/codeEvaluator.d.ts.map +1 -0
  8. package/dist/alpha-zero/codeEvaluator.js +273 -0
  9. package/dist/alpha-zero/codeEvaluator.js.map +1 -0
  10. package/dist/alpha-zero/competitiveRunner.d.ts +66 -0
  11. package/dist/alpha-zero/competitiveRunner.d.ts.map +1 -0
  12. package/dist/alpha-zero/competitiveRunner.js +224 -0
  13. package/dist/alpha-zero/competitiveRunner.js.map +1 -0
  14. package/dist/alpha-zero/index.d.ts +67 -0
  15. package/dist/alpha-zero/index.d.ts.map +1 -0
  16. package/dist/alpha-zero/index.js +99 -0
  17. package/dist/alpha-zero/index.js.map +1 -0
  18. package/dist/alpha-zero/introspection.d.ts +128 -0
  19. package/dist/alpha-zero/introspection.d.ts.map +1 -0
  20. package/dist/alpha-zero/introspection.js +300 -0
  21. package/dist/alpha-zero/introspection.js.map +1 -0
  22. package/dist/alpha-zero/metricsTracker.d.ts +71 -0
  23. package/dist/alpha-zero/metricsTracker.d.ts.map +1 -0
  24. package/dist/{core → alpha-zero}/metricsTracker.js +5 -2
  25. package/dist/alpha-zero/metricsTracker.js.map +1 -0
  26. package/dist/alpha-zero/security/core.d.ts +125 -0
  27. package/dist/alpha-zero/security/core.d.ts.map +1 -0
  28. package/dist/alpha-zero/security/core.js +271 -0
  29. package/dist/alpha-zero/security/core.js.map +1 -0
  30. package/dist/alpha-zero/security/google.d.ts +125 -0
  31. package/dist/alpha-zero/security/google.d.ts.map +1 -0
  32. package/dist/alpha-zero/security/google.js +311 -0
  33. package/dist/alpha-zero/security/google.js.map +1 -0
  34. package/dist/alpha-zero/security/googleLoader.d.ts +17 -0
  35. package/dist/alpha-zero/security/googleLoader.d.ts.map +1 -0
  36. package/dist/alpha-zero/security/googleLoader.js +41 -0
  37. package/dist/alpha-zero/security/googleLoader.js.map +1 -0
  38. package/dist/alpha-zero/security/index.d.ts +29 -0
  39. package/dist/alpha-zero/security/index.d.ts.map +1 -0
  40. package/dist/alpha-zero/security/index.js +32 -0
  41. package/dist/alpha-zero/security/index.js.map +1 -0
  42. package/dist/alpha-zero/security/simulation.d.ts +124 -0
  43. package/dist/alpha-zero/security/simulation.d.ts.map +1 -0
  44. package/dist/alpha-zero/security/simulation.js +277 -0
  45. package/dist/alpha-zero/security/simulation.js.map +1 -0
  46. package/dist/alpha-zero/selfModification.d.ts +109 -0
  47. package/dist/alpha-zero/selfModification.d.ts.map +1 -0
  48. package/dist/alpha-zero/selfModification.js +233 -0
  49. package/dist/alpha-zero/selfModification.js.map +1 -0
  50. package/dist/alpha-zero/types.d.ts +170 -0
  51. package/dist/alpha-zero/types.d.ts.map +1 -0
  52. package/dist/alpha-zero/types.js +31 -0
  53. package/dist/alpha-zero/types.js.map +1 -0
  54. package/dist/bin/erosolar.js +21 -5
  55. package/dist/bin/erosolar.js.map +1 -1
  56. package/dist/capabilities/agentSpawningCapability.d.ts.map +1 -1
  57. package/dist/capabilities/agentSpawningCapability.js +31 -56
  58. package/dist/capabilities/agentSpawningCapability.js.map +1 -1
  59. package/dist/capabilities/securityTestingCapability.d.ts +13 -0
  60. package/dist/capabilities/securityTestingCapability.d.ts.map +1 -0
  61. package/dist/capabilities/securityTestingCapability.js +25 -0
  62. package/dist/capabilities/securityTestingCapability.js.map +1 -0
  63. package/dist/contracts/agent-schemas.json +15 -0
  64. package/dist/contracts/tools.schema.json +9 -0
  65. package/dist/core/agent.d.ts +2 -2
  66. package/dist/core/agent.d.ts.map +1 -1
  67. package/dist/core/agent.js.map +1 -1
  68. package/dist/core/aiFlowOptimizer.d.ts +26 -0
  69. package/dist/core/aiFlowOptimizer.d.ts.map +1 -0
  70. package/dist/core/aiFlowOptimizer.js +31 -0
  71. package/dist/core/aiFlowOptimizer.js.map +1 -0
  72. package/dist/core/aiOptimizationEngine.d.ts +158 -0
  73. package/dist/core/aiOptimizationEngine.d.ts.map +1 -0
  74. package/dist/core/aiOptimizationEngine.js +428 -0
  75. package/dist/core/aiOptimizationEngine.js.map +1 -0
  76. package/dist/core/aiOptimizationIntegration.d.ts +93 -0
  77. package/dist/core/aiOptimizationIntegration.d.ts.map +1 -0
  78. package/dist/core/aiOptimizationIntegration.js +250 -0
  79. package/dist/core/aiOptimizationIntegration.js.map +1 -0
  80. package/dist/core/customCommands.d.ts +0 -1
  81. package/dist/core/customCommands.d.ts.map +1 -1
  82. package/dist/core/customCommands.js +0 -3
  83. package/dist/core/customCommands.js.map +1 -1
  84. package/dist/core/enhancedErrorRecovery.d.ts +100 -0
  85. package/dist/core/enhancedErrorRecovery.d.ts.map +1 -0
  86. package/dist/core/enhancedErrorRecovery.js +345 -0
  87. package/dist/core/enhancedErrorRecovery.js.map +1 -0
  88. package/dist/core/hooksSystem.d.ts +65 -0
  89. package/dist/core/hooksSystem.d.ts.map +1 -0
  90. package/dist/core/hooksSystem.js +273 -0
  91. package/dist/core/hooksSystem.js.map +1 -0
  92. package/dist/core/memorySystem.d.ts +48 -0
  93. package/dist/core/memorySystem.d.ts.map +1 -0
  94. package/dist/core/memorySystem.js +271 -0
  95. package/dist/core/memorySystem.js.map +1 -0
  96. package/dist/core/toolPreconditions.d.ts.map +1 -1
  97. package/dist/core/toolPreconditions.js +14 -0
  98. package/dist/core/toolPreconditions.js.map +1 -1
  99. package/dist/core/toolRuntime.d.ts +1 -22
  100. package/dist/core/toolRuntime.d.ts.map +1 -1
  101. package/dist/core/toolRuntime.js +5 -0
  102. package/dist/core/toolRuntime.js.map +1 -1
  103. package/dist/core/toolValidation.d.ts.map +1 -1
  104. package/dist/core/toolValidation.js +3 -14
  105. package/dist/core/toolValidation.js.map +1 -1
  106. package/dist/core/unified/errors.d.ts +189 -0
  107. package/dist/core/unified/errors.d.ts.map +1 -0
  108. package/dist/core/unified/errors.js +497 -0
  109. package/dist/core/unified/errors.js.map +1 -0
  110. package/dist/core/unified/index.d.ts +19 -0
  111. package/dist/core/unified/index.d.ts.map +1 -0
  112. package/dist/core/unified/index.js +68 -0
  113. package/dist/core/unified/index.js.map +1 -0
  114. package/dist/core/unified/schema.d.ts +101 -0
  115. package/dist/core/unified/schema.d.ts.map +1 -0
  116. package/dist/core/unified/schema.js +350 -0
  117. package/dist/core/unified/schema.js.map +1 -0
  118. package/dist/core/unified/toolRuntime.d.ts +179 -0
  119. package/dist/core/unified/toolRuntime.d.ts.map +1 -0
  120. package/dist/core/unified/toolRuntime.js +517 -0
  121. package/dist/core/unified/toolRuntime.js.map +1 -0
  122. package/dist/core/unified/tools.d.ts +127 -0
  123. package/dist/core/unified/tools.d.ts.map +1 -0
  124. package/dist/core/unified/tools.js +1333 -0
  125. package/dist/core/unified/tools.js.map +1 -0
  126. package/dist/core/unified/types.d.ts +352 -0
  127. package/dist/core/unified/types.d.ts.map +1 -0
  128. package/dist/core/unified/types.js +12 -0
  129. package/dist/core/unified/types.js.map +1 -0
  130. package/dist/core/unified/version.d.ts +209 -0
  131. package/dist/core/unified/version.d.ts.map +1 -0
  132. package/dist/core/unified/version.js +454 -0
  133. package/dist/core/unified/version.js.map +1 -0
  134. package/dist/core/validationRunner.d.ts +3 -1
  135. package/dist/core/validationRunner.d.ts.map +1 -1
  136. package/dist/core/validationRunner.js.map +1 -1
  137. package/dist/headless/headlessApp.d.ts.map +1 -1
  138. package/dist/headless/headlessApp.js +0 -21
  139. package/dist/headless/headlessApp.js.map +1 -1
  140. package/dist/mcp/sseClient.d.ts.map +1 -1
  141. package/dist/mcp/sseClient.js +18 -9
  142. package/dist/mcp/sseClient.js.map +1 -1
  143. package/dist/plugins/tools/build/buildPlugin.d.ts +6 -0
  144. package/dist/plugins/tools/build/buildPlugin.d.ts.map +1 -1
  145. package/dist/plugins/tools/build/buildPlugin.js +10 -4
  146. package/dist/plugins/tools/build/buildPlugin.js.map +1 -1
  147. package/dist/plugins/tools/nodeDefaults.d.ts.map +1 -1
  148. package/dist/plugins/tools/nodeDefaults.js +2 -0
  149. package/dist/plugins/tools/nodeDefaults.js.map +1 -1
  150. package/dist/plugins/tools/security/securityPlugin.d.ts +3 -0
  151. package/dist/plugins/tools/security/securityPlugin.d.ts.map +1 -0
  152. package/dist/plugins/tools/security/securityPlugin.js +12 -0
  153. package/dist/plugins/tools/security/securityPlugin.js.map +1 -0
  154. package/dist/runtime/agentSession.d.ts +2 -2
  155. package/dist/runtime/agentSession.d.ts.map +1 -1
  156. package/dist/runtime/agentSession.js +2 -2
  157. package/dist/runtime/agentSession.js.map +1 -1
  158. package/dist/security/active-stack-security.d.ts +112 -0
  159. package/dist/security/active-stack-security.d.ts.map +1 -0
  160. package/dist/security/active-stack-security.js +296 -0
  161. package/dist/security/active-stack-security.js.map +1 -0
  162. package/dist/security/advanced-persistence-research.d.ts +92 -0
  163. package/dist/security/advanced-persistence-research.d.ts.map +1 -0
  164. package/dist/security/advanced-persistence-research.js +195 -0
  165. package/dist/security/advanced-persistence-research.js.map +1 -0
  166. package/dist/security/advanced-targeting.d.ts +119 -0
  167. package/dist/security/advanced-targeting.d.ts.map +1 -0
  168. package/dist/security/advanced-targeting.js +233 -0
  169. package/dist/security/advanced-targeting.js.map +1 -0
  170. package/dist/security/assessment/vulnerabilityAssessment.d.ts +104 -0
  171. package/dist/security/assessment/vulnerabilityAssessment.d.ts.map +1 -0
  172. package/dist/security/assessment/vulnerabilityAssessment.js +315 -0
  173. package/dist/security/assessment/vulnerabilityAssessment.js.map +1 -0
  174. package/dist/security/authorization/securityAuthorization.d.ts +88 -0
  175. package/dist/security/authorization/securityAuthorization.d.ts.map +1 -0
  176. package/dist/security/authorization/securityAuthorization.js +172 -0
  177. package/dist/security/authorization/securityAuthorization.js.map +1 -0
  178. package/dist/security/comprehensive-targeting.d.ts +85 -0
  179. package/dist/security/comprehensive-targeting.d.ts.map +1 -0
  180. package/dist/security/comprehensive-targeting.js +438 -0
  181. package/dist/security/comprehensive-targeting.js.map +1 -0
  182. package/dist/security/global-security-integration.d.ts +91 -0
  183. package/dist/security/global-security-integration.d.ts.map +1 -0
  184. package/dist/security/global-security-integration.js +218 -0
  185. package/dist/security/global-security-integration.js.map +1 -0
  186. package/dist/security/index.d.ts +38 -0
  187. package/dist/security/index.d.ts.map +1 -0
  188. package/dist/security/index.js +47 -0
  189. package/dist/security/index.js.map +1 -0
  190. package/dist/security/persistence-analyzer.d.ts +56 -0
  191. package/dist/security/persistence-analyzer.d.ts.map +1 -0
  192. package/dist/security/persistence-analyzer.js +187 -0
  193. package/dist/security/persistence-analyzer.js.map +1 -0
  194. package/dist/security/persistence-cli.d.ts +36 -0
  195. package/dist/security/persistence-cli.d.ts.map +1 -0
  196. package/dist/security/persistence-cli.js +160 -0
  197. package/dist/security/persistence-cli.js.map +1 -0
  198. package/dist/security/persistence-research.d.ts +92 -0
  199. package/dist/security/persistence-research.d.ts.map +1 -0
  200. package/dist/security/persistence-research.js +364 -0
  201. package/dist/security/persistence-research.js.map +1 -0
  202. package/dist/security/research/persistenceResearch.d.ts +97 -0
  203. package/dist/security/research/persistenceResearch.d.ts.map +1 -0
  204. package/dist/security/research/persistenceResearch.js +282 -0
  205. package/dist/security/research/persistenceResearch.js.map +1 -0
  206. package/dist/security/security-integration.d.ts +74 -0
  207. package/dist/security/security-integration.d.ts.map +1 -0
  208. package/dist/security/security-integration.js +137 -0
  209. package/dist/security/security-integration.js.map +1 -0
  210. package/dist/security/security-testing-framework.d.ts +112 -0
  211. package/dist/security/security-testing-framework.d.ts.map +1 -0
  212. package/dist/security/security-testing-framework.js +364 -0
  213. package/dist/security/security-testing-framework.js.map +1 -0
  214. package/dist/security/simulation/attackSimulation.d.ts +93 -0
  215. package/dist/security/simulation/attackSimulation.d.ts.map +1 -0
  216. package/dist/security/simulation/attackSimulation.js +341 -0
  217. package/dist/security/simulation/attackSimulation.js.map +1 -0
  218. package/dist/security/strategic-operations.d.ts +100 -0
  219. package/dist/security/strategic-operations.d.ts.map +1 -0
  220. package/dist/security/strategic-operations.js +276 -0
  221. package/dist/security/strategic-operations.js.map +1 -0
  222. package/dist/security/tool-security-wrapper.d.ts +58 -0
  223. package/dist/security/tool-security-wrapper.d.ts.map +1 -0
  224. package/dist/security/tool-security-wrapper.js +156 -0
  225. package/dist/security/tool-security-wrapper.js.map +1 -0
  226. package/dist/shell/claudeCodeStreamHandler.d.ts +145 -0
  227. package/dist/shell/claudeCodeStreamHandler.d.ts.map +1 -0
  228. package/dist/shell/claudeCodeStreamHandler.js +322 -0
  229. package/dist/shell/claudeCodeStreamHandler.js.map +1 -0
  230. package/dist/shell/inputQueueManager.d.ts +144 -0
  231. package/dist/shell/inputQueueManager.d.ts.map +1 -0
  232. package/dist/shell/inputQueueManager.js +290 -0
  233. package/dist/shell/inputQueueManager.js.map +1 -0
  234. package/dist/shell/interactiveShell.d.ts +7 -16
  235. package/dist/shell/interactiveShell.d.ts.map +1 -1
  236. package/dist/shell/interactiveShell.js +164 -235
  237. package/dist/shell/interactiveShell.js.map +1 -1
  238. package/dist/shell/metricsTracker.d.ts +60 -0
  239. package/dist/shell/metricsTracker.d.ts.map +1 -0
  240. package/dist/shell/metricsTracker.js +119 -0
  241. package/dist/shell/metricsTracker.js.map +1 -0
  242. package/dist/shell/shellApp.d.ts +0 -2
  243. package/dist/shell/shellApp.d.ts.map +1 -1
  244. package/dist/shell/shellApp.js +9 -40
  245. package/dist/shell/shellApp.js.map +1 -1
  246. package/dist/shell/streamingOutputManager.d.ts +115 -0
  247. package/dist/shell/streamingOutputManager.d.ts.map +1 -0
  248. package/dist/shell/streamingOutputManager.js +225 -0
  249. package/dist/shell/streamingOutputManager.js.map +1 -0
  250. package/dist/shell/systemPrompt.d.ts.map +1 -1
  251. package/dist/shell/systemPrompt.js +4 -1
  252. package/dist/shell/systemPrompt.js.map +1 -1
  253. package/dist/shell/terminalInput.d.ts +116 -149
  254. package/dist/shell/terminalInput.d.ts.map +1 -1
  255. package/dist/shell/terminalInput.js +527 -639
  256. package/dist/shell/terminalInput.js.map +1 -1
  257. package/dist/shell/terminalInputAdapter.d.ts +20 -79
  258. package/dist/shell/terminalInputAdapter.d.ts.map +1 -1
  259. package/dist/shell/terminalInputAdapter.js +30 -99
  260. package/dist/shell/terminalInputAdapter.js.map +1 -1
  261. package/dist/subagents/taskRunner.d.ts +1 -7
  262. package/dist/subagents/taskRunner.d.ts.map +1 -1
  263. package/dist/subagents/taskRunner.js +47 -180
  264. package/dist/subagents/taskRunner.js.map +1 -1
  265. package/dist/tools/securityTools.d.ts +22 -0
  266. package/dist/tools/securityTools.d.ts.map +1 -0
  267. package/dist/tools/securityTools.js +448 -0
  268. package/dist/tools/securityTools.js.map +1 -0
  269. package/dist/ui/ShellUIAdapter.d.ts.map +1 -1
  270. package/dist/ui/ShellUIAdapter.js +12 -13
  271. package/dist/ui/ShellUIAdapter.js.map +1 -1
  272. package/dist/ui/display.d.ts +45 -24
  273. package/dist/ui/display.d.ts.map +1 -1
  274. package/dist/ui/display.js +259 -140
  275. package/dist/ui/display.js.map +1 -1
  276. package/dist/ui/persistentPrompt.d.ts +50 -0
  277. package/dist/ui/persistentPrompt.d.ts.map +1 -0
  278. package/dist/ui/persistentPrompt.js +92 -0
  279. package/dist/ui/persistentPrompt.js.map +1 -0
  280. package/dist/ui/terminalUISchema.d.ts +195 -0
  281. package/dist/ui/terminalUISchema.d.ts.map +1 -0
  282. package/dist/ui/terminalUISchema.js +113 -0
  283. package/dist/ui/terminalUISchema.js.map +1 -0
  284. package/dist/ui/theme.d.ts.map +1 -1
  285. package/dist/ui/theme.js +8 -6
  286. package/dist/ui/theme.js.map +1 -1
  287. package/dist/ui/toolDisplay.d.ts +158 -0
  288. package/dist/ui/toolDisplay.d.ts.map +1 -1
  289. package/dist/ui/toolDisplay.js +348 -0
  290. package/dist/ui/toolDisplay.js.map +1 -1
  291. package/dist/ui/unified/layout.d.ts +0 -1
  292. package/dist/ui/unified/layout.d.ts.map +1 -1
  293. package/dist/ui/unified/layout.js +25 -15
  294. package/dist/ui/unified/layout.js.map +1 -1
  295. package/package.json +4 -4
  296. package/scripts/deploy-security-capabilities.js +178 -0
  297. package/dist/core/hooks.d.ts +0 -113
  298. package/dist/core/hooks.d.ts.map +0 -1
  299. package/dist/core/hooks.js +0 -267
  300. package/dist/core/hooks.js.map +0 -1
  301. package/dist/core/metricsTracker.d.ts +0 -122
  302. package/dist/core/metricsTracker.d.ts.map +0 -1
  303. package/dist/core/metricsTracker.js.map +0 -1
  304. package/dist/core/securityAssessment.d.ts +0 -91
  305. package/dist/core/securityAssessment.d.ts.map +0 -1
  306. package/dist/core/securityAssessment.js +0 -580
  307. package/dist/core/securityAssessment.js.map +0 -1
  308. package/dist/core/verification.d.ts +0 -137
  309. package/dist/core/verification.d.ts.map +0 -1
  310. package/dist/core/verification.js +0 -323
  311. package/dist/core/verification.js.map +0 -1
  312. package/dist/subagents/agentConfig.d.ts +0 -27
  313. package/dist/subagents/agentConfig.d.ts.map +0 -1
  314. package/dist/subagents/agentConfig.js +0 -89
  315. package/dist/subagents/agentConfig.js.map +0 -1
  316. package/dist/subagents/agentRegistry.d.ts +0 -33
  317. package/dist/subagents/agentRegistry.d.ts.map +0 -1
  318. package/dist/subagents/agentRegistry.js +0 -162
  319. package/dist/subagents/agentRegistry.js.map +0 -1
  320. package/dist/utils/frontmatter.d.ts +0 -10
  321. package/dist/utils/frontmatter.d.ts.map +0 -1
  322. package/dist/utils/frontmatter.js +0 -78
  323. package/dist/utils/frontmatter.js.map +0 -1
@@ -3,21 +3,15 @@
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
9
6
  * - Native bracketed paste support (no heuristics)
10
7
  * - Clean cursor model with render-time wrapping
11
8
  * - State machine for different input modes
12
9
  * - No readline dependency for display
13
10
  */
14
11
  import { EventEmitter } from 'node:events';
15
- import { isMultilinePaste } from '../core/multilinePasteHandler.js';
12
+ import { isMultilinePaste, generatePasteSummary } from '../core/multilinePasteHandler.js';
16
13
  import { writeLock } from '../ui/writeLock.js';
17
- import { renderDivider, renderStatusLine } from '../ui/unified/layout.js';
18
- import { isStreamingMode } from '../ui/globalWriteLock.js';
19
- import { formatThinking } from '../ui/toolDisplay.js';
20
- import { theme } from '../ui/theme.js';
14
+ import { UI_COLORS, DEFAULT_UI_CONFIG, } from '../ui/terminalUISchema.js';
21
15
  // ANSI escape codes
22
16
  const ESC = {
23
17
  // Cursor control
@@ -27,18 +21,14 @@ const ESC = {
27
21
  SHOW: '\x1b[?25h',
28
22
  TO: (row, col) => `\x1b[${row};${col}H`,
29
23
  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
30
29
  // Line control
31
30
  CLEAR_LINE: '\x1b[2K',
32
31
  CLEAR_TO_END: '\x1b[0J',
33
- // Screen control
34
- HOME: '\x1b[H',
35
- CLEAR_SCREEN: '\x1b[2J',
36
- // Alternate screen buffer (like vim/tmux)
37
- ENTER_ALT_SCREEN: '\x1b[?1049h',
38
- EXIT_ALT_SCREEN: '\x1b[?1049l',
39
- // Scroll region
40
- SET_SCROLL: (top, bottom) => `\x1b[${top};${bottom}r`,
41
- RESET_SCROLL: '\x1b[r',
42
32
  // Style
43
33
  RESET: '\x1b[0m',
44
34
  DIM: '\x1b[2m',
@@ -78,46 +68,47 @@ export class TerminalInput extends EventEmitter {
78
68
  statusMessage = null;
79
69
  overrideStatusMessage = null; // Secondary status (warnings, etc.)
80
70
  streamingLabel = null; // Streaming progress indicator
81
- metaElapsedSeconds = null; // Optional elapsed time for header line
82
- metaTokensUsed = null; // Optional token usage
83
- metaTokenLimit = null; // Optional token window
84
- metaThinkingMs = null; // Optional thinking duration
85
- metaThinkingHasContent = false; // Whether collapsed thinking content exists
86
71
  lastRenderContent = '';
87
72
  lastRenderCursor = -1;
88
73
  renderDirty = false;
89
74
  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;
90
83
  // Lifecycle
91
84
  disposed = false;
92
85
  enabled = true;
93
86
  contextUsage = null;
94
- contextAutoCompactThreshold = 90;
95
- // Track current content row (starts at top, moves down)
96
- contentRow = 1;
97
- // Track if scroll region is currently active
98
- scrollRegionActive = false;
99
- thinkingModeLabel = null;
100
87
  editMode = 'display-edits';
101
88
  verificationEnabled = true;
102
89
  autoContinueEnabled = false;
103
90
  verificationHotkey = 'alt+v';
104
91
  autoContinueHotkey = 'alt+c';
105
- thinkingHotkey = '/thinking';
106
- modelLabel = null;
107
- providerLabel = null;
108
- // Streaming render throttle
109
- lastStreamingRender = 0;
110
- streamingRenderInterval = 250; // ms between renders during streaming
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)
111
99
  streamingRenderTimer = null;
100
+ // Unified UI initialization flag
101
+ unifiedUIInitialized = false;
112
102
  constructor(writeStream = process.stdout, config = {}) {
113
103
  super();
114
104
  this.out = writeStream;
105
+ // Use schema defaults for configuration consistency
115
106
  this.config = {
116
- maxLines: config.maxLines ?? 1000,
117
- maxLength: config.maxLength ?? 10000,
107
+ maxLines: config.maxLines ?? DEFAULT_UI_CONFIG.inputArea.maxLines,
108
+ maxLength: config.maxLength ?? DEFAULT_UI_CONFIG.inputArea.maxLength,
118
109
  maxQueueSize: config.maxQueueSize ?? 100,
119
- promptChar: config.promptChar ?? '> ',
120
- continuationChar: config.continuationChar ?? '│ ',
110
+ promptChar: config.promptChar ?? DEFAULT_UI_CONFIG.inputArea.promptChar,
111
+ continuationChar: config.continuationChar ?? DEFAULT_UI_CONFIG.inputArea.continuationChar,
121
112
  };
122
113
  }
123
114
  // ===========================================================================
@@ -196,36 +187,299 @@ export class TerminalInput extends EventEmitter {
196
187
  if (handled)
197
188
  return;
198
189
  }
190
+ // Handle '?' for help hint (if buffer is empty)
191
+ if (str === '?' && this.buffer.length === 0) {
192
+ this.emit('showHelp');
193
+ return;
194
+ }
199
195
  // Insert printable characters
200
196
  if (str && !key?.ctrl && !key?.meta) {
201
197
  this.insertText(str);
202
198
  }
203
199
  }
200
+ // Banner content to write on init (set via setBannerContent before initializeUnifiedUI)
201
+ bannerContent = null;
202
+ /**
203
+ * Set banner content to be written when unified UI initializes.
204
+ */
205
+ setBannerContent(content) {
206
+ this.bannerContent = content;
207
+ }
208
+ /**
209
+ * Initialize the unified UI system with BOTTOM PINNED chat box.
210
+ *
211
+ * Layout:
212
+ * 1. Clear screen
213
+ * 2. Write banner at top
214
+ * 3. Set content cursor row after banner
215
+ * 4. Render chat box at bottom (sets up scroll region)
216
+ */
217
+ initializeUnifiedUI() {
218
+ if (this.unifiedUIInitialized) {
219
+ return;
220
+ }
221
+ // Enter alternate screen buffer for complete terminal control
222
+ this.write(ESC.ALT_SCREEN_ENTER);
223
+ // Hide cursor during setup
224
+ this.write(ESC.HIDE);
225
+ // Clear screen and go home (in alternate buffer)
226
+ this.write(ESC.HOME);
227
+ this.write(ESC.CLEAR_SCREEN);
228
+ // Write banner at top
229
+ let bannerLines = 0;
230
+ if (this.bannerContent) {
231
+ const lines = this.bannerContent.split('\n');
232
+ bannerLines = lines.length + 2; // +2 for trailing \n\n
233
+ process.stdout.write(this.bannerContent + '\n\n');
234
+ }
235
+ // Set content cursor row after banner
236
+ this.contentCursorRow = bannerLines > 0 ? bannerLines + 1 : 1;
237
+ // Mark initialized
238
+ this.unifiedUIInitialized = true;
239
+ // Render chat box at bottom (sets scroll region)
240
+ this.renderFloatingInputArea();
241
+ // Position cursor at content row and show
242
+ this.write(ESC.TO(this.contentCursorRow, 1));
243
+ this.write(ESC.SHOW);
244
+ }
245
+ /**
246
+ * Clear the input area at its tracked position.
247
+ * Returns true if something was cleared.
248
+ */
249
+ clearInputArea() {
250
+ if (this.inputAreaStartRow > 0 && this.flowModeRenderedLines > 0) {
251
+ for (let i = 0; i < this.flowModeRenderedLines; i++) {
252
+ this.write(ESC.TO(this.inputAreaStartRow + i, 1));
253
+ this.write(ESC.CLEAR_LINE);
254
+ }
255
+ return true;
256
+ }
257
+ return false;
258
+ }
259
+ /**
260
+ * Reset input area tracking state.
261
+ */
262
+ resetInputAreaTracking() {
263
+ this.inputAreaStartRow = 0;
264
+ this.flowModeRenderedLines = 0;
265
+ }
266
+ /**
267
+ * Render chat box - BOTTOM PINNED with scroll region (SSE).
268
+ * Chat box is always at terminal bottom, content scrolls above it.
269
+ */
270
+ renderFloatingInputArea() {
271
+ const { rows, cols } = this.getSize();
272
+ const divider = '─'.repeat(cols);
273
+ const { dim: DIM, reset: R } = UI_COLORS;
274
+ // Chat box is 4 lines: divider + input + divider + controls
275
+ const chatBoxHeight = 4;
276
+ const chatBoxStartRow = rows - chatBoxHeight + 1;
277
+ const scrollRegionBottom = chatBoxStartRow - 1;
278
+ // Scroll region starts after banner (contentCursorRow), ends before chat box
279
+ const scrollRegionTop = Math.max(1, this.contentCursorRow);
280
+ // Save cursor position BEFORE changing scroll region
281
+ this.write('\x1b7');
282
+ // Set scroll region to protect BOTH banner (top) and chat box (bottom)
283
+ // Content scrolls in rows [scrollRegionTop, scrollRegionBottom]
284
+ if (scrollRegionBottom > scrollRegionTop) {
285
+ this.write(`\x1b[${scrollRegionTop};${scrollRegionBottom}r`);
286
+ }
287
+ // Hide cursor during render
288
+ this.write(ESC.HIDE);
289
+ // Track position
290
+ this.inputAreaStartRow = chatBoxStartRow;
291
+ let currentRow = chatBoxStartRow;
292
+ // Helper to write a line at absolute position (clears then writes)
293
+ const writeLine = (content) => {
294
+ this.write(ESC.TO(currentRow, 1));
295
+ this.write(ESC.CLEAR_LINE);
296
+ this.write(content);
297
+ currentRow++;
298
+ };
299
+ // Top divider
300
+ writeLine(`${DIM}${divider}${R}`);
301
+ // Input line with > prompt
302
+ const { lines, cursorCol } = this.wrapBuffer(cols - 3);
303
+ const displayLine = lines[0] ?? '';
304
+ const inputRow = currentRow;
305
+ writeLine(`${DIM}>${R} ${displayLine}`);
306
+ // Bottom divider
307
+ writeLine(`${DIM}${divider}${R}`);
308
+ // Mode controls line - Claude Code style
309
+ this.write(ESC.TO(currentRow, 1));
310
+ this.write(ESC.CLEAR_LINE);
311
+ this.write(this.buildClaudeStyleControls(cols));
312
+ // Track lines rendered
313
+ this.flowModeRenderedLines = chatBoxHeight;
314
+ // Restore cursor to where it was before rendering
315
+ this.write('\x1b8');
316
+ // Show cursor
317
+ this.write(ESC.SHOW);
318
+ // Update tracking
319
+ this.lastRenderContent = this.buffer;
320
+ this.lastRenderCursor = this.cursor;
321
+ }
322
+ /**
323
+ * Build Claude Code style controls line.
324
+ * Shows: edit mode indicator (shift+tab to cycle)
325
+ */
326
+ buildClaudeStyleControls(cols) {
327
+ const { dim: DIM, green: GREEN, yellow: YELLOW, cyan: CYAN, reset: R } = UI_COLORS;
328
+ // Edit mode indicator
329
+ let editModeText;
330
+ if (this.editMode === 'display-edits') {
331
+ editModeText = `${GREEN}⏵⏵${R} accept edits on`;
332
+ }
333
+ else {
334
+ editModeText = `${YELLOW}⏸⏸${R} ask before edit`;
335
+ }
336
+ // Build controls line
337
+ const parts = [` ${editModeText} ${DIM}(shift+tab to cycle)${R}`];
338
+ // Add thinking mode if enabled
339
+ if (this.thinkingEnabled) {
340
+ parts.push(`${CYAN}💭${R}`);
341
+ }
342
+ // Add context usage if available
343
+ if (this.contextUsage !== null) {
344
+ const rem = Math.max(0, 100 - this.contextUsage);
345
+ if (rem < 10) {
346
+ parts.push(`${UI_COLORS.red}ctx ${rem}%${R}`);
347
+ }
348
+ else if (rem < 25) {
349
+ parts.push(`${YELLOW}ctx ${rem}%${R}`);
350
+ }
351
+ }
352
+ return parts.join(` ${DIM}·${R} `);
353
+ }
204
354
  /**
205
355
  * Set the input mode
206
356
  *
207
- * Content flows naturally - no scroll region pinning.
357
+ * BOTTOM PINNED with SSE: Chat box stays at terminal bottom.
358
+ * Scroll region protects chat box, content scrolls above it.
208
359
  */
209
360
  setMode(mode) {
210
361
  const prevMode = this.mode;
211
362
  this.mode = mode;
212
363
  if (mode === 'streaming' && prevMode !== 'streaming') {
213
- this.resetStreamingRenderThrottle();
364
+ // Track streaming start time for elapsed display
365
+ this.streamingStartTime = Date.now();
366
+ // Ensure unified UI is initialized
367
+ if (!this.unifiedUIInitialized) {
368
+ this.initializeUnifiedUI();
369
+ }
370
+ // Re-render to ensure scroll region is set correctly
214
371
  this.renderDirty = true;
215
- this.render();
372
+ this.scheduleRender();
216
373
  }
217
374
  else if (mode !== 'streaming' && prevMode === 'streaming') {
218
- // Streaming ended - render the input area
219
- this.resetStreamingRenderThrottle();
220
- this.forceRender();
375
+ // Stop streaming render timer (if any)
376
+ if (this.streamingRenderTimer) {
377
+ clearInterval(this.streamingRenderTimer);
378
+ this.streamingRenderTimer = null;
379
+ }
380
+ // Reset streaming time
381
+ this.streamingStartTime = null;
382
+ // Re-render chat box
383
+ this.renderDirty = true;
384
+ this.scheduleRender();
385
+ }
386
+ }
387
+ /**
388
+ * Set the row where content ends (for idle mode positioning).
389
+ * Input area will render starting from this row + 1.
390
+ */
391
+ setContentEndRow(row) {
392
+ this.contentEndRow = Math.max(0, row);
393
+ this.renderDirty = true;
394
+ this.scheduleRender();
395
+ }
396
+ /**
397
+ * Set available slash commands for auto-complete suggestions.
398
+ */
399
+ setCommands(commands) {
400
+ this.commandSuggestions = commands;
401
+ this.updateSuggestions();
402
+ }
403
+ /**
404
+ * Update filtered suggestions based on current input.
405
+ */
406
+ updateSuggestions() {
407
+ const input = this.buffer.trim();
408
+ // Only show suggestions when input starts with "/"
409
+ if (!input.startsWith('/')) {
410
+ this.showSuggestions = false;
411
+ this.filteredSuggestions = [];
412
+ this.selectedSuggestionIndex = 0;
413
+ return;
414
+ }
415
+ const query = input.toLowerCase();
416
+ this.filteredSuggestions = this.commandSuggestions.filter(cmd => cmd.command.toLowerCase().startsWith(query) ||
417
+ cmd.command.toLowerCase().includes(query.slice(1)));
418
+ // Show suggestions if we have matches
419
+ this.showSuggestions = this.filteredSuggestions.length > 0;
420
+ // Keep selection in bounds
421
+ if (this.selectedSuggestionIndex >= this.filteredSuggestions.length) {
422
+ this.selectedSuggestionIndex = Math.max(0, this.filteredSuggestions.length - 1);
221
423
  }
222
424
  }
223
425
  /**
224
- * Legacy method - no longer used (content flows naturally).
225
- * @deprecated Use setContentRow instead
426
+ * Select next suggestion (arrow down / tab).
226
427
  */
227
- setPinnedHeaderLines(_count) {
228
- // No-op: scroll region pinning removed
428
+ selectNextSuggestion() {
429
+ if (!this.showSuggestions || this.filteredSuggestions.length === 0)
430
+ return;
431
+ this.selectedSuggestionIndex = (this.selectedSuggestionIndex + 1) % this.filteredSuggestions.length;
432
+ this.renderDirty = true;
433
+ this.scheduleRender();
434
+ }
435
+ /**
436
+ * Select previous suggestion (arrow up / shift+tab).
437
+ */
438
+ selectPrevSuggestion() {
439
+ if (!this.showSuggestions || this.filteredSuggestions.length === 0)
440
+ return;
441
+ this.selectedSuggestionIndex = this.selectedSuggestionIndex === 0
442
+ ? this.filteredSuggestions.length - 1
443
+ : this.selectedSuggestionIndex - 1;
444
+ this.renderDirty = true;
445
+ this.scheduleRender();
446
+ }
447
+ /**
448
+ * Accept current suggestion and insert into buffer.
449
+ */
450
+ acceptSuggestion() {
451
+ if (!this.showSuggestions || this.filteredSuggestions.length === 0)
452
+ return false;
453
+ const selected = this.filteredSuggestions[this.selectedSuggestionIndex];
454
+ if (!selected)
455
+ return false;
456
+ // Replace buffer with selected command
457
+ this.buffer = selected.command + ' ';
458
+ this.cursor = this.buffer.length;
459
+ this.showSuggestions = false;
460
+ this.renderDirty = true;
461
+ this.scheduleRender();
462
+ return true;
463
+ }
464
+ /**
465
+ * Check if suggestions are visible.
466
+ */
467
+ areSuggestionsVisible() {
468
+ return this.showSuggestions && this.filteredSuggestions.length > 0;
469
+ }
470
+ /**
471
+ * Toggle thinking/reasoning mode
472
+ */
473
+ toggleThinking() {
474
+ this.thinkingEnabled = !this.thinkingEnabled;
475
+ this.emit('thinkingToggle', this.thinkingEnabled);
476
+ this.scheduleRender();
477
+ }
478
+ /**
479
+ * Get thinking enabled state
480
+ */
481
+ isThinkingEnabled() {
482
+ return this.thinkingEnabled;
229
483
  }
230
484
  /**
231
485
  * Get current mode
@@ -258,14 +512,17 @@ export class TerminalInput extends EventEmitter {
258
512
  }
259
513
  /**
260
514
  * Clear the buffer
515
+ * @param skipRender - If true, don't trigger a re-render (used during submit flow)
261
516
  */
262
- clear() {
517
+ clear(skipRender = false) {
263
518
  this.buffer = '';
264
519
  this.cursor = 0;
265
520
  this.historyIndex = -1;
266
521
  this.tempInput = '';
267
522
  this.pastePlaceholders = [];
268
- this.scheduleRender();
523
+ if (!skipRender) {
524
+ this.scheduleRender();
525
+ }
269
526
  }
270
527
  /**
271
528
  * Get queued inputs
@@ -336,37 +593,6 @@ export class TerminalInput extends EventEmitter {
336
593
  this.streamingLabel = next;
337
594
  this.scheduleRender();
338
595
  }
339
- /**
340
- * Surface meta status just above the divider (e.g., elapsed time or token usage).
341
- */
342
- setMetaStatus(meta) {
343
- const nextElapsed = typeof meta.elapsedSeconds === 'number' && Number.isFinite(meta.elapsedSeconds) && meta.elapsedSeconds >= 0
344
- ? Math.floor(meta.elapsedSeconds)
345
- : null;
346
- const nextTokens = typeof meta.tokensUsed === 'number' && Number.isFinite(meta.tokensUsed) && meta.tokensUsed >= 0
347
- ? Math.floor(meta.tokensUsed)
348
- : null;
349
- const nextLimit = typeof meta.tokenLimit === 'number' && Number.isFinite(meta.tokenLimit) && meta.tokenLimit > 0
350
- ? Math.floor(meta.tokenLimit)
351
- : null;
352
- const nextThinking = typeof meta.thinkingMs === 'number' && Number.isFinite(meta.thinkingMs) && meta.thinkingMs >= 0
353
- ? Math.floor(meta.thinkingMs)
354
- : null;
355
- const nextThinkingHasContent = !!meta.thinkingHasContent;
356
- if (this.metaElapsedSeconds === nextElapsed &&
357
- this.metaTokensUsed === nextTokens &&
358
- this.metaTokenLimit === nextLimit &&
359
- this.metaThinkingMs === nextThinking &&
360
- this.metaThinkingHasContent === nextThinkingHasContent) {
361
- return;
362
- }
363
- this.metaElapsedSeconds = nextElapsed;
364
- this.metaTokensUsed = nextTokens;
365
- this.metaTokenLimit = nextLimit;
366
- this.metaThinkingMs = nextThinking;
367
- this.metaThinkingHasContent = nextThinkingHasContent;
368
- this.scheduleRender();
369
- }
370
596
  /**
371
597
  * Keep mode toggles (verification/auto-continue) visible in the control bar.
372
598
  * Hotkey labels remain stable so the bar looks the same before/during streaming.
@@ -376,22 +602,26 @@ export class TerminalInput extends EventEmitter {
376
602
  const nextAutoContinue = !!options.autoContinueEnabled;
377
603
  const nextVerifyHotkey = options.verificationHotkey ?? this.verificationHotkey;
378
604
  const nextAutoHotkey = options.autoContinueHotkey ?? this.autoContinueHotkey;
379
- const nextThinkingHotkey = options.thinkingHotkey ?? this.thinkingHotkey;
380
- const nextThinkingLabel = options.thinkingModeLabel === undefined ? this.thinkingModeLabel : (options.thinkingModeLabel || null);
381
605
  if (this.verificationEnabled === nextVerification &&
382
606
  this.autoContinueEnabled === nextAutoContinue &&
383
607
  this.verificationHotkey === nextVerifyHotkey &&
384
- this.autoContinueHotkey === nextAutoHotkey &&
385
- this.thinkingHotkey === nextThinkingHotkey &&
386
- this.thinkingModeLabel === nextThinkingLabel) {
608
+ this.autoContinueHotkey === nextAutoHotkey) {
387
609
  return;
388
610
  }
389
611
  this.verificationEnabled = nextVerification;
390
612
  this.autoContinueEnabled = nextAutoContinue;
391
613
  this.verificationHotkey = nextVerifyHotkey;
392
614
  this.autoContinueHotkey = nextAutoHotkey;
393
- this.thinkingHotkey = nextThinkingHotkey;
394
- this.thinkingModeLabel = nextThinkingLabel;
615
+ this.scheduleRender();
616
+ }
617
+ /**
618
+ * Set the model info string (e.g., "OpenAI · gpt-4")
619
+ * This is displayed persistently above the input area.
620
+ */
621
+ setModelInfo(info) {
622
+ if (this.modelInfo === info)
623
+ return;
624
+ this.modelInfo = info;
395
625
  this.scheduleRender();
396
626
  }
397
627
  /**
@@ -404,161 +634,33 @@ export class TerminalInput extends EventEmitter {
404
634
  this.scheduleRender();
405
635
  }
406
636
  /**
407
- * Surface model/provider context in the controls bar.
408
- */
409
- setModelContext(options) {
410
- const nextModel = options.model?.trim() || null;
411
- const nextProvider = options.provider?.trim() || null;
412
- if (this.modelLabel === nextModel && this.providerLabel === nextProvider) {
413
- return;
414
- }
415
- this.modelLabel = nextModel;
416
- this.providerLabel = nextProvider;
417
- this.scheduleRender();
418
- }
419
- /**
420
- * Render the floating input area at contentRow.
421
- *
422
- * The chat box "floats" - it renders right below the last streamed content.
423
- * As content is added, contentRow advances, and the chat box moves down.
424
- * No scroll regions - pure floating behavior.
637
+ * Render the input area.
638
+ * During streaming: renders at terminal bottom (with scroll region)
639
+ * After streaming: renders floating below content
425
640
  */
426
641
  render() {
427
642
  if (!this.canRender())
428
643
  return;
429
644
  if (this.isRendering)
430
645
  return;
431
- const streamingActive = this.mode === 'streaming' || isStreamingMode();
432
- // During streaming, throttle re-renders
433
- if (streamingActive && this.lastStreamingRender > 0) {
434
- const elapsed = Date.now() - this.lastStreamingRender;
435
- const waitMs = Math.max(0, this.streamingRenderInterval - elapsed);
436
- if (waitMs > 0) {
437
- this.renderDirty = true;
438
- this.scheduleStreamingRender(waitMs);
439
- return;
440
- }
441
- }
442
646
  const shouldSkip = !this.renderDirty &&
443
647
  this.buffer === this.lastRenderContent &&
444
648
  this.cursor === this.lastRenderCursor;
445
649
  this.renderDirty = false;
650
+ // Skip if nothing changed (unless explicitly forced)
446
651
  if (shouldSkip) {
447
652
  return;
448
653
  }
654
+ // If write lock is held, defer render
449
655
  if (writeLock.isLocked()) {
450
656
  writeLock.safeWrite(() => this.render());
451
657
  return;
452
658
  }
453
- this.renderFloatingInputArea();
454
- }
455
- /**
456
- * Core floating input area renderer.
457
- * Chat box always floats at contentRow (below streamed content).
458
- * This creates "persistent bottom floating" behavior.
459
- */
460
- renderFloatingInputArea() {
461
- const { rows, cols } = this.getSize();
462
- const maxWidth = Math.max(8, cols - 4);
463
- const streamingActive = this.mode === 'streaming' || isStreamingMode();
464
- // Wrap buffer into display lines
465
- const { lines, cursorLine, cursorCol } = this.wrapBuffer(maxWidth);
466
- const maxVisible = Math.max(1, Math.min(this.config.maxLines, rows - 3));
467
- const displayLines = Math.min(lines.length, maxVisible);
468
- const metaLines = this.buildMetaLines(cols - 2);
469
- // Calculate display window (keep cursor visible)
470
- let startLine = 0;
471
- if (lines.length > displayLines) {
472
- startLine = Math.max(0, cursorLine - displayLines + 1);
473
- startLine = Math.min(startLine, lines.length - displayLines);
474
- }
475
- const visibleLines = lines.slice(startLine, startLine + displayLines);
476
- const adjustedCursorLine = cursorLine - startLine;
477
- // Chat box height (must match getChatBoxHeight calculation)
478
- const chatBoxHeight = metaLines.length + 1 + displayLines + 1;
479
- // During streaming, skip rendering to avoid cursor positioning corruption
480
- if (this.scrollRegionActive) {
481
- return;
482
- }
483
- // Pin chat box at bottom of terminal
484
- const chatBoxStartRow = Math.max(1, rows - chatBoxHeight + 1);
485
- writeLock.lock('terminalInput.renderFloating');
486
659
  this.isRendering = true;
660
+ writeLock.lock('terminalInput.render');
487
661
  try {
488
- // Hide cursor during render
489
- this.write(ESC.HIDE);
490
- this.write(ESC.RESET);
491
- // Clear the chat box area
492
- for (let i = 0; i < chatBoxHeight; i++) {
493
- const row = chatBoxStartRow + i;
494
- if (row <= rows) {
495
- this.write(ESC.TO(row, 1));
496
- this.write(ESC.CLEAR_LINE);
497
- }
498
- }
499
- let currentRow = chatBoxStartRow;
500
- // Meta/status header
501
- for (const metaLine of metaLines) {
502
- this.write(ESC.TO(currentRow, 1));
503
- this.write(metaLine);
504
- currentRow += 1;
505
- }
506
- // Separator line
507
- this.write(ESC.TO(currentRow, 1));
508
- this.write(renderDivider(cols - 2));
509
- currentRow += 1;
510
- // Render input lines
511
- let finalRow = currentRow;
512
- let finalCol = 3;
513
- for (let i = 0; i < visibleLines.length; i++) {
514
- const rowNum = currentRow + i;
515
- this.write(ESC.TO(rowNum, 1));
516
- const line = visibleLines[i] ?? '';
517
- const isFirstLine = (startLine + i) === 0;
518
- const isCursorLine = i === adjustedCursorLine;
519
- this.write(ESC.BG_DARK);
520
- this.write(ESC.DIM);
521
- this.write(isFirstLine ? this.config.promptChar : this.config.continuationChar);
522
- this.write(ESC.RESET);
523
- this.write(ESC.BG_DARK);
524
- if (isCursorLine) {
525
- const col = Math.min(cursorCol, line.length);
526
- const before = line.slice(0, col);
527
- const at = col < line.length ? line[col] : ' ';
528
- const after = col < line.length ? line.slice(col + 1) : '';
529
- this.write(before);
530
- this.write(ESC.REVERSE + ESC.BOLD);
531
- this.write(at);
532
- this.write(ESC.RESET + ESC.BG_DARK);
533
- this.write(after);
534
- finalRow = rowNum;
535
- finalCol = this.config.promptChar.length + col + 1;
536
- }
537
- else {
538
- this.write(line);
539
- }
540
- // Pad to edge
541
- const lineLen = this.config.promptChar.length + line.length + (isCursorLine && cursorCol >= line.length ? 1 : 0);
542
- const padding = Math.max(0, cols - lineLen - 1);
543
- if (padding > 0)
544
- this.write(' '.repeat(padding));
545
- this.write(ESC.RESET);
546
- }
547
- // Mode controls line
548
- const controlRow = currentRow + visibleLines.length;
549
- this.write(ESC.TO(controlRow, 1));
550
- this.write(this.buildModeControls(cols));
551
- // Position cursor in input box
552
- this.write(ESC.TO(finalRow, Math.min(finalCol, cols)));
553
- this.write(ESC.SHOW);
554
- // Update state
555
- this.lastRenderContent = this.buffer;
556
- this.lastRenderCursor = this.cursor;
557
- this.lastStreamingRender = streamingActive ? Date.now() : 0;
558
- if (this.streamingRenderTimer) {
559
- clearTimeout(this.streamingRenderTimer);
560
- this.streamingRenderTimer = null;
561
- }
662
+ // Always render floating right after content (no wasted space)
663
+ this.renderFloatingInputArea();
562
664
  }
563
665
  finally {
564
666
  writeLock.unlock();
@@ -566,181 +668,99 @@ export class TerminalInput extends EventEmitter {
566
668
  }
567
669
  }
568
670
  /**
569
- * Build compact meta line above the divider.
570
- * Shows model/provider and key metrics in a single line.
571
- * Status message is shown in mode controls to avoid duplication.
671
+ * Build status bar showing streaming/ready status and key info.
672
+ * This is the TOP line above the input area - minimal Claude Code style.
572
673
  */
573
- buildMetaLines(width) {
674
+ buildStatusBar(cols) {
675
+ const maxWidth = cols - 2;
574
676
  const parts = [];
575
- // Model/provider info
576
- if (this.modelLabel) {
577
- const modelText = this.providerLabel
578
- ? `${this.modelLabel} @ ${this.providerLabel}`
579
- : this.modelLabel;
580
- parts.push({ text: modelText, tone: 'info' });
581
- }
582
- // Elapsed time
583
- if (this.metaElapsedSeconds !== null) {
584
- parts.push({ text: this.formatElapsedLabel(this.metaElapsedSeconds), tone: 'muted' });
585
- }
586
- // Token usage (compact)
587
- if (this.metaTokensUsed !== null) {
588
- const formattedUsed = this.formatTokenCount(this.metaTokensUsed);
589
- const formattedLimit = this.metaTokenLimit ? `/${this.formatTokenCount(this.metaTokenLimit)}` : '';
590
- parts.push({ text: `${formattedUsed}${formattedLimit}`, tone: 'muted' });
591
- }
592
- // Context remaining (only show if concerning)
593
- const tokensRemaining = this.computeTokensRemaining();
594
- if (tokensRemaining !== null) {
595
- parts.push({ text: `↓${tokensRemaining}`, tone: 'muted' });
596
- }
597
- // Thinking indicator
598
- if (this.metaThinkingMs !== null) {
599
- parts.push({ text: formatThinking(this.metaThinkingMs, this.metaThinkingHasContent), tone: 'info' });
600
- }
601
- if (!parts.length) {
602
- return [];
603
- }
604
- return [renderStatusLine(parts, width)];
605
- }
606
- /**
607
- * Build Claude Code style mode controls line.
608
- * Combines streaming label + override status + main status for simultaneous display.
609
- */
610
- buildModeControls(cols) {
611
- const width = Math.max(8, cols - 2);
612
- const leftParts = [];
613
- const rightParts = [];
614
- if (this.streamingLabel) {
615
- leftParts.push({ text: `◐ ${this.streamingLabel}`, tone: 'info' });
616
- }
617
- if (this.overrideStatusMessage) {
618
- leftParts.push({ text: `⚠ ${this.overrideStatusMessage}`, tone: 'warn' });
619
- }
620
- if (this.statusMessage) {
621
- leftParts.push({ text: this.statusMessage, tone: this.streamingLabel ? 'muted' : 'info' });
622
- }
623
- const editHotkey = this.formatHotkey('shift+tab');
624
- const editLabel = this.editMode === 'display-edits' ? 'edits: accept' : 'edits: ask';
625
- const editTone = this.editMode === 'display-edits' ? 'success' : 'muted';
626
- leftParts.push({ text: `${editHotkey} ${editLabel}`, tone: editTone });
627
- const verifyHotkey = this.formatHotkey(this.verificationHotkey);
628
- const verifyLabel = this.verificationEnabled ? 'verify:on' : 'verify:off';
629
- leftParts.push({ text: `${verifyHotkey} ${verifyLabel}`, tone: this.verificationEnabled ? 'success' : 'muted' });
630
- const continueHotkey = this.formatHotkey(this.autoContinueHotkey);
631
- const continueLabel = this.autoContinueEnabled ? 'auto:on' : 'auto:off';
632
- leftParts.push({ text: `${continueHotkey} ${continueLabel}`, tone: this.autoContinueEnabled ? 'info' : 'muted' });
633
- if (this.queue.length > 0 && this.mode !== 'streaming') {
634
- leftParts.push({ text: `queued ${this.queue.length}`, tone: 'info' });
677
+ // Streaming status with elapsed time (left side)
678
+ if (this.mode === 'streaming') {
679
+ let statusText = '● Streaming';
680
+ if (this.streamingStartTime) {
681
+ const elapsed = Math.floor((Date.now() - this.streamingStartTime) / 1000);
682
+ const mins = Math.floor(elapsed / 60);
683
+ const secs = elapsed % 60;
684
+ statusText += mins > 0 ? ` ${mins}m ${secs}s` : ` ${secs}s`;
685
+ }
686
+ parts.push(`\x1b[32m${statusText}\x1b[0m`); // Green
635
687
  }
636
- if (this.buffer.includes('\n')) {
637
- const lineCount = this.buffer.split('\n').length;
638
- leftParts.push({ text: `${lineCount} lines`, tone: 'muted' });
688
+ // Queue indicator during streaming
689
+ if (this.mode === 'streaming' && this.queue.length > 0) {
690
+ parts.push(`\x1b[36mqueued: ${this.queue.length}\x1b[0m`); // Cyan
639
691
  }
692
+ // Paste indicator
640
693
  if (this.pastePlaceholders.length > 0) {
641
- const latest = this.pastePlaceholders[this.pastePlaceholders.length - 1];
642
- leftParts.push({
643
- text: `paste #${latest.id} +${latest.lineCount} lines (⌫ to drop)`,
644
- tone: 'info',
645
- });
646
- }
647
- const contextRemaining = this.computeContextRemaining();
648
- if (this.thinkingModeLabel) {
649
- const thinkingHotkey = this.formatHotkey(this.thinkingHotkey);
650
- rightParts.push({ text: `${thinkingHotkey} thinking:${this.thinkingModeLabel}`, tone: 'info' });
651
- }
652
- // Model info is now in meta lines only - no duplication here
653
- if (contextRemaining !== null) {
654
- const tone = contextRemaining <= 10 ? 'warn' : 'muted';
655
- const label = contextRemaining === 0 && this.contextUsage !== null
656
- ? 'Context auto-compact imminent'
657
- : `Context left until auto-compact: ${contextRemaining}%`;
658
- rightParts.push({ text: label, tone });
659
- }
660
- if (!rightParts.length || width < 60) {
661
- const merged = rightParts.length ? [...leftParts, ...rightParts] : leftParts;
662
- return renderStatusLine(merged, width);
663
- }
664
- const leftWidth = Math.max(12, Math.floor(width * 0.6));
665
- const rightWidth = Math.max(14, width - leftWidth - 1);
666
- const leftText = renderStatusLine(leftParts, leftWidth);
667
- const rightText = renderStatusLine(rightParts, rightWidth);
668
- const spacing = Math.max(1, width - this.visibleLength(leftText) - this.visibleLength(rightText));
669
- return `${leftText}${' '.repeat(spacing)}${rightText}`;
670
- }
671
- formatHotkey(hotkey) {
672
- const normalized = hotkey.trim().toLowerCase();
673
- if (!normalized)
674
- return hotkey;
675
- const parts = normalized.split('+').filter(Boolean);
676
- const map = {
677
- shift: '⇧',
678
- sh: '⇧',
679
- alt: '⌥',
680
- option: '⌥',
681
- opt: '⌥',
682
- ctrl: '⌃',
683
- control: '⌃',
684
- cmd: '⌘',
685
- meta: '⌘',
686
- };
687
- const formatted = parts
688
- .map((part) => {
689
- const symbol = map[part];
690
- if (symbol)
691
- return symbol;
692
- return part.length === 1 ? part.toUpperCase() : part.toUpperCase();
693
- })
694
- .join('');
695
- return formatted || hotkey;
696
- }
697
- computeContextRemaining() {
698
- if (this.contextUsage === null) {
699
- return null;
700
- }
701
- return Math.max(0, this.contextAutoCompactThreshold - this.contextUsage);
702
- }
703
- computeTokensRemaining() {
704
- if (this.metaTokensUsed === null || this.metaTokenLimit === null) {
705
- return null;
694
+ const totalLines = this.pastePlaceholders.reduce((sum, p) => sum + p.lineCount, 0);
695
+ parts.push(`\x1b[36m📋 ${totalLines}L\x1b[0m`);
706
696
  }
707
- const remaining = Math.max(0, this.metaTokenLimit - this.metaTokensUsed);
708
- return this.formatTokenCount(remaining);
709
- }
710
- formatElapsedLabel(seconds) {
711
- if (seconds < 60) {
712
- return `${seconds}s`;
697
+ // Override/warning status
698
+ if (this.overrideStatusMessage) {
699
+ parts.push(`\x1b[33m⚠ ${this.overrideStatusMessage}\x1b[0m`); // Yellow
713
700
  }
714
- const mins = Math.floor(seconds / 60);
715
- const secs = seconds % 60;
716
- return secs > 0 ? `${mins}m ${secs}s` : `${mins}m`;
717
- }
718
- formatTokenCount(value) {
719
- if (!Number.isFinite(value)) {
720
- return `${value}`;
701
+ // If idle with empty buffer, show quick shortcuts
702
+ if (this.mode !== 'streaming' && this.buffer.length === 0 && parts.length === 0) {
703
+ return `${ESC.DIM}Type a message or / for commands${ESC.RESET}`;
721
704
  }
722
- if (value >= 1_000_000) {
723
- return `${(value / 1_000_000).toFixed(1)}M`;
705
+ // Multi-line indicator
706
+ if (this.buffer.includes('\n')) {
707
+ parts.push(`${ESC.DIM}${this.buffer.split('\n').length}L${ESC.RESET}`);
724
708
  }
725
- if (value >= 1_000) {
726
- return `${(value / 1_000).toFixed(1)}k`;
709
+ if (parts.length === 0) {
710
+ return ''; // Empty status bar when idle
727
711
  }
728
- return `${Math.round(value)}`;
729
- }
730
- visibleLength(value) {
731
- const ansiPattern = /\u001B\[[0-?]*[ -/]*[@-~]/g;
732
- return value.replace(ansiPattern, '').length;
712
+ const joined = parts.join(`${ESC.DIM} · ${ESC.RESET}`);
713
+ return joined.slice(0, maxWidth);
733
714
  }
734
715
  /**
735
- * Debug-only snapshot used by tests to assert rendered strings without
736
- * needing a TTY. Not used by production code.
716
+ * Build mode controls line showing toggles and context info.
717
+ * This is the BOTTOM line below the input area - Claude Code style layout with erosolar features.
718
+ *
719
+ * Layout: [toggles on left] ... [context info on right]
737
720
  */
738
- getDebugUiSnapshot(width) {
739
- const cols = Math.max(8, width ?? this.getSize().cols);
740
- return {
741
- meta: this.buildMetaLines(cols - 2),
742
- controls: this.buildModeControls(cols),
743
- };
721
+ buildModeControls(cols) {
722
+ const maxWidth = cols - 2;
723
+ // Use schema-defined colors for consistency
724
+ const { green: GREEN, yellow: YELLOW, cyan: CYAN, magenta: MAGENTA, red: RED, dim: DIM, reset: R } = UI_COLORS;
725
+ // Mode toggles with colors (following ModeControlsSchema)
726
+ const toggles = [];
727
+ // Edit mode (green=auto, yellow=ask) - per schema.editMode
728
+ if (this.editMode === 'display-edits') {
729
+ toggles.push(`${GREEN}⏵⏵ auto-edit${R}`);
730
+ }
731
+ else {
732
+ toggles.push(`${YELLOW}⏸⏸ ask-first${R}`);
733
+ }
734
+ // Thinking mode (cyan when on) - per schema.thinkingMode
735
+ toggles.push(this.thinkingEnabled ? `${CYAN}💭 think${R}` : `${DIM}○ think${R}`);
736
+ // Verification (green when on) - per schema.verificationMode
737
+ toggles.push(this.verificationEnabled ? `${GREEN}✓ verify${R}` : `${DIM}○ verify${R}`);
738
+ // Auto-continue (magenta when on) - per schema.autoContinueMode
739
+ toggles.push(this.autoContinueEnabled ? `${MAGENTA}↻ auto${R}` : `${DIM}○ auto${R}`);
740
+ const leftPart = toggles.join(`${DIM} · ${R}`) + `${DIM} (⇧⇥)${R}`;
741
+ // Context usage with color - per schema.contextUsage thresholds
742
+ let rightPart = '';
743
+ if (this.contextUsage !== null) {
744
+ const rem = Math.max(0, 100 - this.contextUsage);
745
+ // Thresholds: critical < 10%, warning < 25%
746
+ if (rem < 10)
747
+ rightPart = `${RED}⚠ ctx: ${rem}%${R}`;
748
+ else if (rem < 25)
749
+ rightPart = `${YELLOW}! ctx: ${rem}%${R}`;
750
+ else
751
+ rightPart = `${DIM}ctx: ${rem}%${R}`;
752
+ }
753
+ // Calculate visible lengths (strip ANSI)
754
+ const strip = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');
755
+ const leftLen = strip(leftPart).length;
756
+ const rightLen = strip(rightPart).length;
757
+ if (leftLen + rightLen < maxWidth - 4) {
758
+ return `${leftPart}${' '.repeat(maxWidth - leftLen - rightLen)}${rightPart}`;
759
+ }
760
+ if (rightLen > 0 && leftLen + 8 < maxWidth) {
761
+ return `${leftPart} ${rightPart}`;
762
+ }
763
+ return leftPart;
744
764
  }
745
765
  /**
746
766
  * Force a re-render
@@ -763,214 +783,34 @@ export class TerminalInput extends EventEmitter {
763
783
  handleResize() {
764
784
  this.lastRenderContent = '';
765
785
  this.lastRenderCursor = -1;
766
- this.resetStreamingRenderThrottle();
767
786
  this.scheduleRender();
768
787
  }
788
+ // Track current content row for writing
789
+ contentCursorRow = 1;
769
790
  /**
770
- * Enter streaming mode with scroll region.
771
- * Sets up terminal scroll region to exclude chat box.
772
- */
773
- enterStreamingScrollRegion() {
774
- const { rows } = this.getSize();
775
- const chatBoxHeight = this.getChatBoxHeight();
776
- const scrollEnd = Math.max(1, rows - chatBoxHeight);
777
- writeLock.lock('enterStreamingScrollRegion');
778
- try {
779
- // Set scroll region for content area
780
- this.write(ESC.SET_SCROLL(1, scrollEnd));
781
- // Position cursor at current content row
782
- this.write(ESC.TO(Math.min(this.contentRow, scrollEnd), 1));
783
- this.scrollRegionActive = true;
784
- this.setStatusMessage('esc to interrupt');
785
- }
786
- finally {
787
- writeLock.unlock();
788
- }
789
- // Render chat box at bottom (outside scroll region)
790
- this.renderChatBoxAtBottom();
791
- }
792
- /**
793
- * Exit streaming mode and restore normal operation.
794
- */
795
- exitStreamingScrollRegion() {
796
- writeLock.lock('exitStreamingScrollRegion');
797
- try {
798
- // Reset scroll region to full terminal
799
- this.write(ESC.RESET_SCROLL);
800
- this.scrollRegionActive = false;
801
- this.setStatusMessage('Ready for prompts');
802
- }
803
- finally {
804
- writeLock.unlock();
805
- }
806
- // Final render
807
- this.forceRender();
808
- }
809
- /**
810
- * Render just the chat box at the bottom of terminal.
811
- * Used during streaming to update status without affecting content.
812
- */
813
- renderChatBoxAtBottom() {
814
- const { rows, cols: width } = this.getSize();
815
- const chatBoxHeight = this.getChatBoxHeight();
816
- const chatBoxStartRow = Math.max(1, rows - chatBoxHeight + 1);
817
- const metaLines = this.buildMetaLines(width);
818
- const modeControls = this.buildModeControls(width);
819
- const divider = theme.ui.muted('─'.repeat(width));
820
- // Get input area content
821
- const lines = this.buffer.split('\n');
822
- const maxDisplayLines = 3;
823
- const displayLines = Math.min(lines.length, maxDisplayLines);
824
- const visibleLines = lines.slice(Math.max(0, lines.length - displayLines));
825
- writeLock.lock('renderChatBoxAtBottom');
826
- try {
827
- this.write(ESC.SAVE);
828
- this.write(ESC.HIDE);
829
- let row = chatBoxStartRow;
830
- // Meta lines
831
- for (const line of metaLines) {
832
- this.write(ESC.TO(row++, 1));
833
- this.write(ESC.CLEAR_LINE);
834
- this.write(line);
835
- }
836
- // Divider
837
- this.write(ESC.TO(row++, 1));
838
- this.write(ESC.CLEAR_LINE);
839
- this.write(divider);
840
- // Input area
841
- for (const line of visibleLines) {
842
- this.write(ESC.TO(row++, 1));
843
- this.write(ESC.CLEAR_LINE);
844
- this.write(this.config.promptChar);
845
- this.write(line);
846
- }
847
- // Mode controls
848
- this.write(ESC.TO(row, 1));
849
- this.write(ESC.CLEAR_LINE);
850
- this.write(modeControls);
851
- this.write(ESC.RESTORE);
852
- this.write(ESC.SHOW);
853
- }
854
- finally {
855
- writeLock.unlock();
856
- }
857
- }
858
- /**
859
- * Stream content within the scroll region.
860
- * Content is written directly and scrolls naturally.
861
- */
862
- streamContent(content) {
863
- if (!content)
864
- return;
865
- writeLock.lock('streamContent');
866
- try {
867
- // Write content - scroll region handles scrolling
868
- this.write(content);
869
- // Track newlines
870
- const newlines = (content.match(/\n/g) || []).length;
871
- this.contentRow += newlines;
872
- }
873
- finally {
874
- writeLock.unlock();
875
- }
876
- // Throttle chat box updates during streaming
877
- this.scheduleStreamingRender(200);
878
- }
879
- /**
880
- * Enable scroll region (no-op in floating mode).
881
- */
882
- enableScrollRegion() {
883
- // No-op: using pure floating approach
884
- }
885
- /**
886
- * Disable scroll region (no-op in floating mode).
887
- */
888
- disableScrollRegion() {
889
- // No-op: using pure floating approach
890
- }
891
- /**
892
- * Calculate chat box height.
893
- */
894
- getChatBoxHeight() {
895
- return 6; // Fixed: meta + divider + input + controls + buffer
896
- }
897
- /**
898
- * @deprecated Use streamContent() instead
899
- * Register with display's output interceptor - kept for backwards compatibility
900
- */
901
- registerOutputInterceptor(_display) {
902
- // No-op: Use streamContent() for cleaner floating chat box behavior
903
- }
904
- /**
905
- * @deprecated Use streamContent() instead
906
- * Write content above the floating chat box.
907
- */
908
- writeToScrollRegion(content) {
909
- this.streamContent(content);
910
- }
911
- /**
912
- * Enter alternate screen buffer and clear it.
913
- * This gives us full control over the terminal without affecting user's history.
914
- */
915
- enterAlternateScreen() {
916
- writeLock.lock('enterAltScreen');
917
- try {
918
- this.write(ESC.ENTER_ALT_SCREEN);
919
- this.write(ESC.HOME);
920
- this.write(ESC.CLEAR_SCREEN);
921
- this.contentRow = 1;
922
- }
923
- finally {
924
- writeLock.unlock();
925
- }
926
- }
927
- /**
928
- * Exit alternate screen buffer.
929
- * Restores the user's previous terminal content.
930
- */
931
- exitAlternateScreen() {
932
- writeLock.lock('exitAltScreen');
933
- try {
934
- this.write(ESC.EXIT_ALT_SCREEN);
935
- }
936
- finally {
937
- writeLock.unlock();
938
- }
939
- }
940
- /**
941
- * Clear the entire terminal screen and reset content position.
942
- * This removes all content including the launching command.
943
- */
944
- clearScreen() {
945
- writeLock.lock('clearScreen');
946
- try {
947
- this.write(ESC.HOME);
948
- this.write(ESC.CLEAR_SCREEN);
949
- this.contentRow = 1;
950
- }
951
- finally {
952
- writeLock.unlock();
953
- }
954
- }
955
- /**
956
- * Reset content position to row 1.
957
- * Does NOT clear the terminal - content starts from current position.
958
- */
959
- resetContentPosition() {
960
- this.contentRow = 1;
961
- }
962
- /**
963
- * Set the content row explicitly (used after banner is written).
964
- * This tells the input where content should start flowing from.
791
+ * Register with display's output interceptor.
792
+ * With scroll regions (SSE), explicitly position cursor before writes.
965
793
  */
966
- setContentRow(row) {
967
- this.contentRow = Math.max(1, row);
968
- }
969
- /**
970
- * Get the current content row position.
971
- */
972
- getContentRow() {
973
- return this.contentRow;
794
+ registerOutputInterceptor(display) {
795
+ if (this.outputInterceptorCleanup) {
796
+ this.outputInterceptorCleanup();
797
+ }
798
+ this.outputInterceptorCleanup = display.registerOutputInterceptor({
799
+ beforeWrite: () => {
800
+ // Set scroll region: from after banner to before chat box
801
+ // This protects both banner (at top) and chat box (at bottom)
802
+ const scrollTop = this.contentCursorRow;
803
+ const scrollBottom = this.inputAreaStartRow - 1;
804
+ if (scrollTop > 0 && scrollBottom > scrollTop) {
805
+ this.write(`\x1b[${scrollTop};${scrollBottom}r`);
806
+ // Position cursor at bottom of scroll region for new content
807
+ this.write(ESC.TO(scrollBottom, 1));
808
+ }
809
+ },
810
+ afterWrite: () => {
811
+ // Content written; cursor naturally advances
812
+ },
813
+ });
974
814
  }
975
815
  /**
976
816
  * Dispose and clean up
@@ -978,10 +818,24 @@ export class TerminalInput extends EventEmitter {
978
818
  dispose() {
979
819
  if (this.disposed)
980
820
  return;
821
+ // Clean up streaming render timer
822
+ if (this.streamingRenderTimer) {
823
+ clearInterval(this.streamingRenderTimer);
824
+ this.streamingRenderTimer = null;
825
+ }
826
+ // Clean up output interceptor
827
+ if (this.outputInterceptorCleanup) {
828
+ this.outputInterceptorCleanup();
829
+ this.outputInterceptorCleanup = undefined;
830
+ }
831
+ // Reset scroll region
832
+ this.write('\x1b[r');
833
+ // Exit alternate screen buffer (restores main terminal)
834
+ if (this.unifiedUIInitialized) {
835
+ this.write(ESC.ALT_SCREEN_EXIT);
836
+ }
981
837
  this.disposed = true;
982
838
  this.enabled = false;
983
- this.disableScrollRegion();
984
- this.resetStreamingRenderThrottle();
985
839
  this.disableBracketedPaste();
986
840
  this.buffer = '';
987
841
  this.queue = [];
@@ -1086,7 +940,22 @@ export class TerminalInput extends EventEmitter {
1086
940
  this.toggleEditMode();
1087
941
  return true;
1088
942
  }
1089
- this.insertText(' ');
943
+ // Tab: toggle paste expansion if in placeholder, otherwise toggle thinking
944
+ if (this.findPlaceholderAt(this.cursor)) {
945
+ this.togglePasteExpansion();
946
+ }
947
+ else {
948
+ this.toggleThinking();
949
+ }
950
+ return true;
951
+ case 'escape':
952
+ // Esc: interrupt if streaming, otherwise clear buffer
953
+ if (this.mode === 'streaming') {
954
+ this.emit('interrupt');
955
+ }
956
+ else if (this.buffer.length > 0) {
957
+ this.clear();
958
+ }
1090
959
  return true;
1091
960
  }
1092
961
  return false;
@@ -1104,6 +973,7 @@ export class TerminalInput extends EventEmitter {
1104
973
  this.insertPlainText(chunk, insertPos);
1105
974
  this.cursor = insertPos + chunk.length;
1106
975
  this.emit('change', this.buffer);
976
+ this.updateSuggestions();
1107
977
  this.scheduleRender();
1108
978
  }
1109
979
  insertNewline() {
@@ -1128,6 +998,7 @@ export class TerminalInput extends EventEmitter {
1128
998
  this.cursor = Math.max(0, this.cursor - 1);
1129
999
  }
1130
1000
  this.emit('change', this.buffer);
1001
+ this.updateSuggestions();
1131
1002
  this.scheduleRender();
1132
1003
  }
1133
1004
  deleteForward() {
@@ -1355,12 +1226,13 @@ export class TerminalInput extends EventEmitter {
1355
1226
  timestamp: Date.now(),
1356
1227
  });
1357
1228
  this.emit('queue', text);
1358
- this.clear(); // Clear immediately for queued input
1229
+ this.clear(); // Clear immediately for queued input, re-render to update queue display
1359
1230
  }
1360
1231
  else {
1361
- // In idle mode, clear the input first, then emit submit.
1362
- // The prompt will be logged as a visible message by the caller.
1363
- this.clear();
1232
+ // In idle mode, clear the input WITHOUT rendering.
1233
+ // The caller will display the user message and start streaming.
1234
+ // We'll render the input area again after streaming ends.
1235
+ this.clear(true); // Skip render - streaming will handle display
1364
1236
  this.emit('submit', text);
1365
1237
  }
1366
1238
  }
@@ -1377,9 +1249,7 @@ export class TerminalInput extends EventEmitter {
1377
1249
  if (available <= 0)
1378
1250
  return;
1379
1251
  const chunk = clean.slice(0, available);
1380
- const isMultiline = isMultilinePaste(chunk);
1381
- const isShortMultiline = isMultiline && this.shouldInlineMultiline(chunk);
1382
- if (isMultiline && !isShortMultiline) {
1252
+ if (isMultilinePaste(chunk)) {
1383
1253
  this.insertPastePlaceholder(chunk);
1384
1254
  }
1385
1255
  else {
@@ -1515,19 +1385,17 @@ export class TerminalInput extends EventEmitter {
1515
1385
  this.shiftPlaceholders(position, text.length);
1516
1386
  this.buffer = this.buffer.slice(0, position) + text + this.buffer.slice(position);
1517
1387
  }
1518
- shouldInlineMultiline(content) {
1519
- const lines = content.split('\n').length;
1520
- const maxInlineLines = 4;
1521
- const maxInlineChars = 240;
1522
- return lines <= maxInlineLines && content.length <= maxInlineChars;
1523
- }
1524
1388
  findPlaceholderAt(position) {
1525
1389
  return this.pastePlaceholders.find((ph) => position >= ph.start && position < ph.end) ?? null;
1526
1390
  }
1527
- buildPlaceholder(lineCount) {
1391
+ buildPlaceholder(summary) {
1528
1392
  const id = ++this.pasteCounter;
1529
- const plural = lineCount === 1 ? '' : 's';
1530
- const placeholder = `[Pasted text #${id} +${lineCount} line${plural}]`;
1393
+ const lang = summary.language ? ` ${summary.language.toUpperCase()}` : '';
1394
+ // Show first line preview (truncated)
1395
+ const preview = summary.preview.length > 30
1396
+ ? `${summary.preview.slice(0, 30)}...`
1397
+ : summary.preview;
1398
+ const placeholder = `[📋 #${id}${lang} ${summary.lineCount}L] "${preview}"`;
1531
1399
  return { id, placeholder };
1532
1400
  }
1533
1401
  insertPastePlaceholder(content) {
@@ -1535,21 +1403,67 @@ export class TerminalInput extends EventEmitter {
1535
1403
  if (available <= 0)
1536
1404
  return;
1537
1405
  const cleanContent = content.slice(0, available);
1538
- const lineCount = cleanContent.split('\n').length;
1539
- const { id, placeholder } = this.buildPlaceholder(lineCount);
1406
+ const summary = generatePasteSummary(cleanContent);
1407
+ // For short pastes (< 5 lines), show full content instead of placeholder
1408
+ if (summary.lineCount < 5) {
1409
+ const placeholder = this.findPlaceholderAt(this.cursor);
1410
+ const insertPos = placeholder && this.cursor > placeholder.start ? placeholder.end : this.cursor;
1411
+ this.insertPlainText(cleanContent, insertPos);
1412
+ this.cursor = insertPos + cleanContent.length;
1413
+ return;
1414
+ }
1415
+ const { id, placeholder } = this.buildPlaceholder(summary);
1540
1416
  const insertPos = this.cursor;
1541
1417
  this.shiftPlaceholders(insertPos, placeholder.length);
1542
1418
  this.pastePlaceholders.push({
1543
1419
  id,
1544
1420
  content: cleanContent,
1545
- lineCount,
1421
+ lineCount: summary.lineCount,
1546
1422
  placeholder,
1547
1423
  start: insertPos,
1548
1424
  end: insertPos + placeholder.length,
1425
+ summary,
1426
+ expanded: false,
1549
1427
  });
1550
1428
  this.buffer = this.buffer.slice(0, insertPos) + placeholder + this.buffer.slice(insertPos);
1551
1429
  this.cursor = insertPos + placeholder.length;
1552
1430
  }
1431
+ /**
1432
+ * Toggle expansion of a paste placeholder at the current cursor position.
1433
+ * When expanded, shows first 3 and last 2 lines of the content.
1434
+ */
1435
+ togglePasteExpansion() {
1436
+ const placeholder = this.findPlaceholderAt(this.cursor);
1437
+ if (!placeholder)
1438
+ return false;
1439
+ placeholder.expanded = !placeholder.expanded;
1440
+ // Update the placeholder text in buffer
1441
+ const newPlaceholder = placeholder.expanded
1442
+ ? this.buildExpandedPlaceholder(placeholder)
1443
+ : this.buildPlaceholder(placeholder.summary).placeholder;
1444
+ const lengthDiff = newPlaceholder.length - placeholder.placeholder.length;
1445
+ // Update buffer
1446
+ this.buffer =
1447
+ this.buffer.slice(0, placeholder.start) +
1448
+ newPlaceholder +
1449
+ this.buffer.slice(placeholder.end);
1450
+ // Update placeholder tracking
1451
+ placeholder.placeholder = newPlaceholder;
1452
+ placeholder.end = placeholder.start + newPlaceholder.length;
1453
+ // Shift other placeholders
1454
+ this.shiftPlaceholders(placeholder.end, lengthDiff, placeholder.id);
1455
+ this.scheduleRender();
1456
+ return true;
1457
+ }
1458
+ buildExpandedPlaceholder(ph) {
1459
+ const lines = ph.content.split('\n');
1460
+ const firstLines = lines.slice(0, 3).map(l => l.slice(0, 60)).join('\n');
1461
+ const lastLines = lines.length > 5
1462
+ ? '\n...\n' + lines.slice(-2).map(l => l.slice(0, 60)).join('\n')
1463
+ : '';
1464
+ const lang = ph.summary.language ? ` ${ph.summary.language.toUpperCase()}` : '';
1465
+ return `[📋 #${ph.id}${lang} ${ph.lineCount}L ▼]\n${firstLines}${lastLines}\n[/📋 #${ph.id}]`;
1466
+ }
1553
1467
  deletePlaceholder(placeholder) {
1554
1468
  const length = placeholder.end - placeholder.start;
1555
1469
  this.buffer = this.buffer.slice(0, placeholder.start) + this.buffer.slice(placeholder.end);
@@ -1557,11 +1471,7 @@ export class TerminalInput extends EventEmitter {
1557
1471
  this.shiftPlaceholders(placeholder.end, -length, placeholder.id);
1558
1472
  this.cursor = placeholder.start;
1559
1473
  }
1560
- updateContextUsage(value, autoCompactThreshold) {
1561
- if (typeof autoCompactThreshold === 'number' && Number.isFinite(autoCompactThreshold)) {
1562
- const boundedThreshold = Math.max(1, Math.min(100, Math.round(autoCompactThreshold)));
1563
- this.contextAutoCompactThreshold = boundedThreshold;
1564
- }
1474
+ updateContextUsage(value) {
1565
1475
  if (value === null || !Number.isFinite(value)) {
1566
1476
  this.contextUsage = null;
1567
1477
  }
@@ -1588,28 +1498,6 @@ export class TerminalInput extends EventEmitter {
1588
1498
  const next = this.editMode === 'display-edits' ? 'ask-permission' : 'display-edits';
1589
1499
  this.setEditMode(next);
1590
1500
  }
1591
- scheduleStreamingRender(delayMs) {
1592
- if (this.streamingRenderTimer)
1593
- return;
1594
- const wait = Math.max(16, delayMs);
1595
- this.streamingRenderTimer = setTimeout(() => {
1596
- this.streamingRenderTimer = null;
1597
- // During streaming, only update chat box (not full render)
1598
- if (this.scrollRegionActive) {
1599
- this.renderChatBoxAtBottom();
1600
- }
1601
- else {
1602
- this.render();
1603
- }
1604
- }, wait);
1605
- }
1606
- resetStreamingRenderThrottle() {
1607
- if (this.streamingRenderTimer) {
1608
- clearTimeout(this.streamingRenderTimer);
1609
- this.streamingRenderTimer = null;
1610
- }
1611
- this.lastStreamingRender = 0;
1612
- }
1613
1501
  scheduleRender() {
1614
1502
  if (!this.canRender())
1615
1503
  return;