erosolar-cli 1.7.303 → 1.7.304

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