@causyne/agent 1.20.122 → 1.20.127

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 (641) hide show
  1. package/bin/causyne.js +38 -15
  2. package/docs/SECURITY_REVIEW.md +42 -6
  3. package/package.json +7 -7
  4. package/src/acp/agentCatalog.js +74 -50
  5. package/src/acp/agentCatalog.ts +82 -49
  6. package/src/acp/client.js +309 -86
  7. package/src/acp/client.ts +291 -84
  8. package/src/acp/protocol.js +147 -3
  9. package/src/acp/protocol.ts +181 -4
  10. package/src/acp/server.js +418 -45
  11. package/src/acp/server.ts +404 -47
  12. package/src/agent/abortableDelay.js +2 -2
  13. package/src/agent/abortableDelay.ts +2 -2
  14. package/src/agent/errorClassifier.js +51 -7
  15. package/src/agent/errorClassifier.ts +52 -6
  16. package/src/agent/providerFailure.js +1 -1
  17. package/src/agent/providerFailure.ts +7 -1
  18. package/src/agent/toolArgValidator.js +38 -4
  19. package/src/agent/toolArgValidator.ts +39 -4
  20. package/src/agent/toolTurnIntegrity.js +28 -7
  21. package/src/agent/toolTurnIntegrity.ts +25 -6
  22. package/src/agent/workspaceBoundary.js +30 -4
  23. package/src/agent/workspaceBoundary.ts +32 -4
  24. package/src/agentLoop.js +673 -236
  25. package/src/agentLoop.ts +705 -233
  26. package/src/approvalPolicy.js +61 -10
  27. package/src/approvalPolicy.ts +69 -11
  28. package/src/auditLog.js +641 -48
  29. package/src/auditLog.ts +661 -0
  30. package/src/autoUpdate.js +32 -5
  31. package/src/autoUpdate.ts +27 -5
  32. package/src/backgroundTasks.js +328 -0
  33. package/src/backgroundTasks.ts +339 -0
  34. package/src/benchmarks/codingEval.js +558 -0
  35. package/src/benchmarks/codingEval.ts +628 -0
  36. package/src/benchmarks/planCache.js +115 -134
  37. package/src/benchmarks/planCache.ts +163 -0
  38. package/src/browser/browserRuntime.js +52 -0
  39. package/src/browser/browserRuntime.ts +55 -0
  40. package/src/browser/causyneBrowser.js +914 -13
  41. package/src/browser/causyneBrowser.ts +1075 -35
  42. package/src/browser/searchProviders.js +94 -6
  43. package/src/browser/searchProviders.ts +89 -6
  44. package/src/browser/urlPolicy.js +22 -2
  45. package/src/browser/urlPolicy.ts +19 -2
  46. package/src/browser/workspacePathSafety.js +6 -4
  47. package/src/browser/workspacePathSafety.ts +7 -4
  48. package/src/capabilities.js +18 -17
  49. package/src/capabilities.ts +38 -0
  50. package/src/checkpoints.js +1241 -1127
  51. package/src/checkpoints.ts +1377 -0
  52. package/src/cliMode.js +718 -754
  53. package/src/cliMode.ts +792 -0
  54. package/src/codebase/repoMap.js +656 -0
  55. package/src/codebase/repoMap.ts +664 -0
  56. package/src/commands.js +3806 -2513
  57. package/src/commands.ts +4162 -0
  58. package/src/compiledSkills.js +8052 -8054
  59. package/src/compiledSkills.ts +8078 -0
  60. package/src/config.js +118 -1
  61. package/src/config.ts +124 -1
  62. package/src/configVault.js +29 -2
  63. package/src/configVault.ts +26 -2
  64. package/src/contextManager.js +473 -557
  65. package/src/contextManager.ts +599 -0
  66. package/src/continuum/adapters/antigravity.js +8 -3
  67. package/src/continuum/adapters/antigravity.ts +8 -3
  68. package/src/continuum/sanitizer.js +23 -1
  69. package/src/continuum/sanitizer.ts +23 -1
  70. package/src/continuum/ui/continuumPicker.js +0 -2
  71. package/src/continuum/ui/continuumPicker.ts +0 -2
  72. package/src/continuum/ui/continuumPickerView.js +0 -2
  73. package/src/continuum/ui/continuumPickerView.ts +4 -20
  74. package/src/core/contextCompactor.js +142 -14
  75. package/src/core/contextCompactor.ts +150 -15
  76. package/src/core/goalLoop.js +257 -0
  77. package/src/core/goalLoop.ts +310 -0
  78. package/src/creative/liveBridge.js +3 -2
  79. package/src/creative/liveBridge.ts +4 -2
  80. package/src/creative/studioScripts.js +1 -1
  81. package/src/creative/studioScripts.ts +1 -1
  82. package/src/decideTools.js +7 -2
  83. package/src/decideTools.ts +7 -2
  84. package/src/decisionPolicy.js +10 -2
  85. package/src/decisionPolicy.ts +10 -2
  86. package/src/designPalettes.js +72 -84
  87. package/src/designPalettes.ts +111 -0
  88. package/src/devMode.js +2 -2
  89. package/src/devMode.ts +6 -0
  90. package/src/diffReview.js +370 -0
  91. package/src/diffReview.ts +407 -0
  92. package/src/dynamicCatalogue.js +311 -11
  93. package/src/dynamicCatalogue.ts +331 -11
  94. package/src/embodimentSession.js +143 -154
  95. package/src/embodimentSession.ts +173 -0
  96. package/src/engines/installer.js +60 -29
  97. package/src/engines/installer.ts +73 -22
  98. package/src/enterprisePolicy.js +660 -0
  99. package/src/enterprisePolicy.ts +728 -0
  100. package/src/entrypoint.js +646 -268
  101. package/src/entrypoint.ts +740 -0
  102. package/src/game/causyneCoreBridge.js +686 -0
  103. package/src/game/causyneCoreBridge.ts +702 -0
  104. package/src/game/gameLauncher.js +287 -0
  105. package/src/game/gameLauncher.ts +352 -0
  106. package/src/game/gameProvisioner.js +425 -0
  107. package/src/game/gameProvisioner.ts +488 -0
  108. package/src/gitSnapshot.js +417 -312
  109. package/src/gitSnapshot.ts +500 -0
  110. package/src/headlessCli.js +343 -25
  111. package/src/headlessCli.ts +343 -20
  112. package/src/hooks.js +247 -26
  113. package/src/hooks.ts +236 -26
  114. package/src/ignoreRules.js +297 -0
  115. package/src/ignoreRules.ts +308 -0
  116. package/src/implementationPlan.js +7 -6
  117. package/src/implementationPlan.ts +8 -6
  118. package/src/infra/atomicWriter.js +127 -18
  119. package/src/infra/atomicWriter.ts +141 -20
  120. package/src/launchIntent.js +85 -4
  121. package/src/launchIntent.ts +88 -4
  122. package/src/licensing/entitlements.js +553 -237
  123. package/src/licensing/entitlements.ts +590 -0
  124. package/src/licensing/policy.js +17 -1
  125. package/src/licensing/policy.ts +31 -0
  126. package/src/lsp/lspCatalog.js +398 -0
  127. package/src/lsp/lspCatalog.ts +452 -0
  128. package/src/lsp/lspClient.js +770 -0
  129. package/src/lsp/lspClient.ts +862 -0
  130. package/src/lsp/lspProtocol.js +121 -0
  131. package/src/lsp/lspProtocol.ts +140 -0
  132. package/src/mcp/mcpClient.js +69 -8
  133. package/src/mcp/mcpClient.ts +66 -9
  134. package/src/mcp/mcpRegistry.js +255 -15
  135. package/src/mcp/mcpRegistry.ts +241 -14
  136. package/src/mcp/mcpSecurity.js +6 -7
  137. package/src/mcp/mcpSecurity.ts +7 -6
  138. package/src/memory/contextBudget.js +2 -0
  139. package/src/memory/contextBudget.ts +1 -0
  140. package/src/memory/episodicStore.js +2 -5
  141. package/src/memory/episodicStore.ts +2 -5
  142. package/src/memory.js +80 -32
  143. package/src/memory.ts +111 -0
  144. package/src/memoryManager.js +151 -143
  145. package/src/memoryManager.ts +182 -0
  146. package/src/modelCatalogue.js +172 -195
  147. package/src/modelCatalogue.ts +201 -0
  148. package/src/modelIds.js +8 -27
  149. package/src/modelIds.ts +33 -0
  150. package/src/modelVariants.js +645 -0
  151. package/src/modelVariants.ts +717 -0
  152. package/src/observer/evidence.js +5 -1
  153. package/src/observer/evidence.ts +5 -1
  154. package/src/osKeychain.js +17 -9
  155. package/src/osKeychain.ts +14 -9
  156. package/src/outputRecovery.js +3 -2
  157. package/src/outputRecovery.ts +4 -2
  158. package/src/outputStore.js +210 -156
  159. package/src/outputStore.ts +321 -0
  160. package/src/permissionPresets.js +327 -0
  161. package/src/permissionPresets.ts +361 -0
  162. package/src/planCache.js +3 -6
  163. package/src/planCache.ts +3 -6
  164. package/src/plugins/pluginManager.js +689 -461
  165. package/src/plugins/pluginManager.ts +807 -0
  166. package/src/plugins/pluginRunner.js +82 -37
  167. package/src/plugins/pluginRunner.ts +98 -0
  168. package/src/plugins/pluginSkills.js +47 -9
  169. package/src/plugins/pluginSkills.ts +46 -8
  170. package/src/pluginsFactory/discovery.js +0 -1
  171. package/src/pluginsFactory/discovery.ts +0 -1
  172. package/src/pluginsFactory/templates.js +17 -4
  173. package/src/pluginsFactory/templates.ts +17 -4
  174. package/src/prWorkflow.js +337 -0
  175. package/src/prWorkflow.ts +376 -0
  176. package/src/procSignal.js +1 -2
  177. package/src/procSignal.ts +1 -3
  178. package/src/projectInstructions.js +319 -0
  179. package/src/projectInstructions.ts +361 -0
  180. package/src/providers/acp.js +234 -49
  181. package/src/providers/acp.ts +240 -50
  182. package/src/providers/anthropic.js +152 -47
  183. package/src/providers/anthropic.ts +152 -45
  184. package/src/providers/antigravity.js +620 -356
  185. package/src/providers/antigravity.ts +621 -357
  186. package/src/providers/base.js +9 -2
  187. package/src/providers/base.ts +10 -2
  188. package/src/providers/byokHttp.js +134 -18
  189. package/src/providers/byokHttp.ts +181 -19
  190. package/src/providers/byokStream.js +183 -44
  191. package/src/providers/byokStream.ts +179 -62
  192. package/src/providers/dashscope-byok.js +50 -8
  193. package/src/providers/dashscope-byok.ts +59 -13
  194. package/src/providers/deepseek.js +12 -3
  195. package/src/providers/deepseek.ts +12 -3
  196. package/src/providers/factory.js +41 -0
  197. package/src/providers/factory.ts +42 -0
  198. package/src/providers/gemini.js +74 -22
  199. package/src/providers/gemini.ts +78 -26
  200. package/src/providers/moonshot.js +60 -8
  201. package/src/providers/moonshot.ts +64 -14
  202. package/src/providers/muse.js +6 -0
  203. package/src/providers/muse.ts +8 -0
  204. package/src/providers/ollama.js +299 -21
  205. package/src/providers/ollama.ts +331 -29
  206. package/src/providers/openai-compatible.js +81 -12
  207. package/src/providers/openai-compatible.ts +89 -18
  208. package/src/providers/openai.js +87 -6
  209. package/src/providers/openai.ts +74 -6
  210. package/src/providers/openrouter.js +248 -66
  211. package/src/providers/openrouter.ts +243 -70
  212. package/src/providers/qwen-byok.js +50 -8
  213. package/src/providers/qwen-byok.ts +59 -13
  214. package/src/providers/wireNormalizer.js +66 -0
  215. package/src/providers/wireNormalizer.ts +64 -0
  216. package/src/providers/xai.js +31 -8
  217. package/src/providers/xai.ts +38 -14
  218. package/src/provisioning/capabilityConsent.js +29 -11
  219. package/src/provisioning/capabilityConsent.ts +42 -0
  220. package/src/provisioning/capabilityProvisioner.js +309 -197
  221. package/src/provisioning/capabilityProvisioner.ts +413 -0
  222. package/src/provisioning/capabilityTools.js +31 -17
  223. package/src/provisioning/capabilityTools.ts +43 -0
  224. package/src/provisioning/npmInstall.js +33 -5
  225. package/src/provisioning/npmInstall.ts +33 -5
  226. package/src/reporting.js +330 -326
  227. package/src/reporting.ts +484 -0
  228. package/src/sandbox.js +71 -0
  229. package/src/sandbox.ts +81 -0
  230. package/src/scheduler/scheduler.js +372 -0
  231. package/src/scheduler/scheduler.ts +433 -0
  232. package/src/sessionJournal.js +24 -3
  233. package/src/sessionJournal.ts +18 -3
  234. package/src/sessionSearchIndex.js +267 -0
  235. package/src/sessionSearchIndex.ts +311 -0
  236. package/src/sessionStore.js +1 -2
  237. package/src/sessionStore.ts +2 -0
  238. package/src/skillsManager.js +2 -3
  239. package/src/skillsManager.ts +2 -3
  240. package/src/slopDetector.js +202 -265
  241. package/src/slopDetector.ts +279 -0
  242. package/src/smartToolsUse.js +10 -4
  243. package/src/smartToolsUse.ts +10 -4
  244. package/src/stallGuard.js +10 -3
  245. package/src/stallGuard.ts +9 -3
  246. package/src/taskBuffer.js +91 -40
  247. package/src/taskBuffer.ts +94 -0
  248. package/src/tokenTracker.js +78 -11
  249. package/src/tokenTracker.ts +69 -11
  250. package/src/toolPacks.js +11 -0
  251. package/src/toolPacks.ts +11 -0
  252. package/src/tools/applyPatch.js +610 -0
  253. package/src/tools/applyPatch.ts +661 -0
  254. package/src/tools/archive.js +135 -21
  255. package/src/tools/archive.ts +136 -21
  256. package/src/tools/astryxOracle.js +77 -72
  257. package/src/tools/astryxOracle.ts +95 -0
  258. package/src/tools/axSnapshot.js +127 -147
  259. package/src/tools/axSnapshot.ts +174 -0
  260. package/src/tools/backgroundTask.js +86 -0
  261. package/src/tools/backgroundTask.ts +121 -0
  262. package/src/tools/blenderAutomator.js +434 -390
  263. package/src/tools/blenderAutomator.ts +623 -0
  264. package/src/tools/checkSystemSpecs.js +54 -61
  265. package/src/tools/checkSystemSpecs.ts +73 -0
  266. package/src/tools/clipboard.js +42 -31
  267. package/src/tools/clipboard.ts +61 -0
  268. package/src/tools/codeSearchAst.js +359 -91
  269. package/src/tools/codeSearchAst.ts +399 -0
  270. package/src/tools/codeSearcher.js +179 -37
  271. package/src/tools/codeSearcher.ts +188 -33
  272. package/src/tools/codeTools.js +208 -245
  273. package/src/tools/codeTools.ts +271 -0
  274. package/src/tools/codebaseSearch.js +5 -0
  275. package/src/tools/codebaseSearch.ts +5 -0
  276. package/src/tools/desktopAct.js +185 -197
  277. package/src/tools/desktopAct.ts +257 -0
  278. package/src/tools/dynamicLoader.js +4 -40
  279. package/src/tools/dynamicLoader.ts +13 -0
  280. package/src/tools/executeProceduralMedia.js +117 -86
  281. package/src/tools/executeProceduralMedia.ts +135 -0
  282. package/src/tools/fileTracker.js +74 -0
  283. package/src/tools/fileTracker.ts +94 -0
  284. package/src/tools/fsDelete.js +57 -47
  285. package/src/tools/fsDelete.ts +80 -0
  286. package/src/tools/fsEdit.js +192 -74
  287. package/src/tools/fsEdit.ts +201 -72
  288. package/src/tools/fsMove.js +79 -52
  289. package/src/tools/fsMove.ts +108 -0
  290. package/src/tools/fsRead.js +54 -15
  291. package/src/tools/fsRead.ts +55 -15
  292. package/src/tools/fsSearch.js +5 -0
  293. package/src/tools/fsSearch.ts +5 -0
  294. package/src/tools/fsWrite.js +14 -6
  295. package/src/tools/fsWrite.ts +14 -6
  296. package/src/tools/gameAiBehaviorTree.js +74 -91
  297. package/src/tools/gameAiBehaviorTree.ts +219 -0
  298. package/src/tools/gameAnimationRig.js +128 -147
  299. package/src/tools/gameAnimationRig.ts +215 -0
  300. package/src/tools/gameAssetFetcher.js +403 -441
  301. package/src/tools/gameAssetFetcher.ts +477 -0
  302. package/src/tools/gameAssetHarvester.js +171 -200
  303. package/src/tools/gameAssetHarvester.ts +261 -0
  304. package/src/tools/gameAudioSynth.js +223 -259
  305. package/src/tools/gameAudioSynth.ts +255 -0
  306. package/src/tools/gameBuilder.js +100 -91
  307. package/src/tools/gameBuilder.ts +913 -0
  308. package/src/tools/gameCanvasAudit.js +138 -96
  309. package/src/tools/gameCanvasAudit.ts +157 -0
  310. package/src/tools/gameCinematicSequencer.js +93 -111
  311. package/src/tools/gameCinematicSequencer.ts +165 -0
  312. package/src/tools/gameDataForge.js +115 -118
  313. package/src/tools/gameDataForge.ts +151 -0
  314. package/src/tools/gameDialogueTreeGen.js +125 -156
  315. package/src/tools/gameDialogueTreeGen.ts +159 -0
  316. package/src/tools/gameEconomyBalancer.js +150 -153
  317. package/src/tools/gameEconomyBalancer.ts +186 -0
  318. package/src/tools/gameEntitySpawner.js +91 -108
  319. package/src/tools/gameEntitySpawner.ts +209 -0
  320. package/src/tools/gameLoreForge.js +125 -147
  321. package/src/tools/gameLoreForge.ts +162 -0
  322. package/src/tools/gameQuestArcBuilder.js +105 -144
  323. package/src/tools/gameQuestArcBuilder.ts +147 -0
  324. package/src/tools/gameSceneBuilder.js +143 -149
  325. package/src/tools/gameSceneBuilder.ts +196 -0
  326. package/src/tools/gameShaderForge.js +83 -101
  327. package/src/tools/gameShaderForge.ts +181 -0
  328. package/src/tools/gameTilemapGenerator.js +99 -129
  329. package/src/tools/gameTilemapGenerator.ts +158 -0
  330. package/src/tools/gameUiHudBuilder.js +109 -129
  331. package/src/tools/gameUiHudBuilder.ts +300 -0
  332. package/src/tools/gameVfxEmitterGen.js +86 -89
  333. package/src/tools/gameVfxEmitterGen.ts +133 -0
  334. package/src/tools/gameWebRuntimeInspector.js +153 -86
  335. package/src/tools/gameWebRuntimeInspector.ts +167 -0
  336. package/src/tools/generateMediaViaApi.js +57 -15
  337. package/src/tools/generateMediaViaApi.ts +56 -15
  338. package/src/tools/gitExec.js +133 -86
  339. package/src/tools/gitExec.ts +146 -0
  340. package/src/tools/gitWorktree.js +115 -0
  341. package/src/tools/gitWorktree.ts +150 -0
  342. package/src/tools/godotAutomator.js +417 -394
  343. package/src/tools/godotAutomator.ts +530 -0
  344. package/src/tools/lspCodeIntel.js +217 -0
  345. package/src/tools/lspCodeIntel.ts +260 -0
  346. package/src/tools/manageLocalAiDependencies.js +242 -206
  347. package/src/tools/manageLocalAiDependencies.ts +288 -0
  348. package/src/tools/multiEdit.js +16 -76
  349. package/src/tools/multiEdit.ts +20 -77
  350. package/src/tools/nativeEngine.js +2 -2
  351. package/src/tools/nativeEngine.ts +2 -2
  352. package/src/tools/openSourceToolProvisioner.js +2 -2
  353. package/src/tools/openSourceToolProvisioner.ts +2 -2
  354. package/src/tools/osSandbox.js +152 -15
  355. package/src/tools/osSandbox.ts +148 -15
  356. package/src/tools/palmierAutomator.js +147 -95
  357. package/src/tools/palmierAutomator.ts +171 -0
  358. package/src/tools/payloadSanitizer.js +0 -1
  359. package/src/tools/payloadSanitizer.ts +0 -1
  360. package/src/tools/pdfReader.js +197 -104
  361. package/src/tools/pdfReader.ts +216 -0
  362. package/src/tools/persistentShell.js +267 -144
  363. package/src/tools/persistentShell.ts +314 -0
  364. package/src/tools/pluginManager.js +84 -72
  365. package/src/tools/pluginManager.ts +109 -0
  366. package/src/tools/presentDeliverable.js +103 -0
  367. package/src/tools/presentDeliverable.ts +127 -0
  368. package/src/tools/printer.js +278 -296
  369. package/src/tools/printer.ts +326 -0
  370. package/src/tools/procTerm.js +96 -83
  371. package/src/tools/procTerm.ts +127 -0
  372. package/src/tools/processList.js +45 -48
  373. package/src/tools/processList.ts +73 -0
  374. package/src/tools/ptcRuntime.js +444 -0
  375. package/src/tools/ptcRuntime.ts +490 -0
  376. package/src/tools/ptyTerminal.js +1096 -0
  377. package/src/tools/ptyTerminal.ts +1231 -0
  378. package/src/tools/registry.js +308 -287
  379. package/src/tools/registry.ts +495 -0
  380. package/src/tools/repoMap.js +46 -0
  381. package/src/tools/repoMap.ts +66 -0
  382. package/src/tools/subagentOrchestrator.js +404 -348
  383. package/src/tools/subagentOrchestrator.ts +457 -0
  384. package/src/tools/sysRun.js +83 -26
  385. package/src/tools/sysRun.ts +80 -26
  386. package/src/tools/toolForge.js +84 -67
  387. package/src/tools/toolForge.ts +102 -0
  388. package/src/tools/toolOutputStore.js +26 -4
  389. package/src/tools/toolOutputStore.ts +22 -4
  390. package/src/tools/toolPathSafety.js +262 -0
  391. package/src/tools/toolPathSafety.ts +308 -0
  392. package/src/tools/toolScanner.js +28 -0
  393. package/src/tools/toolScanner.ts +29 -0
  394. package/src/tools/toolSelfRepair.js +21 -6
  395. package/src/tools/toolSelfRepair.ts +26 -6
  396. package/src/tools/walkerSafety.ts +1 -0
  397. package/src/tools/webFetch.js +163 -13
  398. package/src/tools/webFetch.ts +150 -13
  399. package/src/tools/webSearch.js +123 -36
  400. package/src/tools/webSearch.ts +124 -33
  401. package/src/toolsList.js +5 -0
  402. package/src/toolsList.ts +5 -0
  403. package/src/tui/ask.js +159 -168
  404. package/src/tui/ask.ts +259 -0
  405. package/src/tui/banner.js +5 -1
  406. package/src/tui/banner.ts +6 -1
  407. package/src/tui/block.js +0 -1
  408. package/src/tui/block.ts +0 -1
  409. package/src/tui/chatRenderer.js +1194 -1443
  410. package/src/tui/chatRenderer.ts +1335 -0
  411. package/src/tui/clipboardImage.js +36 -12
  412. package/src/tui/clipboardImage.ts +39 -13
  413. package/src/tui/clipboardSync.js +34 -9
  414. package/src/tui/clipboardSync.ts +38 -9
  415. package/src/tui/codeProgress.js +0 -1
  416. package/src/tui/codeProgress.ts +0 -1
  417. package/src/tui/completion.js +396 -371
  418. package/src/tui/completion.ts +575 -0
  419. package/src/tui/composerControls.js +212 -34
  420. package/src/tui/composerControls.ts +235 -34
  421. package/src/tui/consoleGuard.js +27 -7
  422. package/src/tui/consoleGuard.ts +29 -7
  423. package/src/tui/dialogs.js +867 -733
  424. package/src/tui/dialogs.ts +971 -0
  425. package/src/tui/diff.js +205 -195
  426. package/src/tui/diff.ts +336 -0
  427. package/src/tui/history.js +143 -108
  428. package/src/tui/history.ts +167 -0
  429. package/src/tui/home.js +166 -161
  430. package/src/tui/home.ts +252 -0
  431. package/src/tui/invocation.js +59 -67
  432. package/src/tui/invocation.ts +116 -0
  433. package/src/tui/keys.js +437 -420
  434. package/src/tui/keys.ts +597 -0
  435. package/src/tui/lineEditor.js +477 -432
  436. package/src/tui/lineEditor.ts +542 -0
  437. package/src/tui/messageActionPlacement.js +0 -1
  438. package/src/tui/messageActionPlacement.ts +0 -1
  439. package/src/tui/messageInteraction.js +0 -2
  440. package/src/tui/messageInteraction.ts +0 -2
  441. package/src/tui/modelPicker.js +22 -15
  442. package/src/tui/modelPicker.ts +25 -18
  443. package/src/tui/observerPicker.js +0 -2
  444. package/src/tui/observerPicker.ts +0 -2
  445. package/src/tui/overlay.js +2 -6
  446. package/src/tui/overlay.ts +2 -6
  447. package/src/tui/prompt.js +1818 -2151
  448. package/src/tui/prompt.ts +1872 -0
  449. package/src/tui/runningLight.js +0 -1
  450. package/src/tui/runningLight.ts +0 -1
  451. package/src/tui/selectList.js +369 -349
  452. package/src/tui/selectList.ts +433 -0
  453. package/src/tui/sessionPicker.js +0 -1
  454. package/src/tui/sessionPicker.ts +0 -1
  455. package/src/tui/sessionPickerView.js +0 -2
  456. package/src/tui/sessionPickerView.ts +4 -21
  457. package/src/tui/sessionSidebar.js +3 -1
  458. package/src/tui/sessionSidebar.ts +4 -1
  459. package/src/tui/setup.js +39 -14
  460. package/src/tui/setup.ts +45 -14
  461. package/src/tui/skillAuthoring.js +0 -2
  462. package/src/tui/skillAuthoring.ts +0 -3
  463. package/src/tui/stageSurface.js +829 -909
  464. package/src/tui/stageSurface.ts +1003 -0
  465. package/src/tui/statusLine.js +7 -4
  466. package/src/tui/statusLine.ts +9 -3
  467. package/src/tui/terminalInputFramer.js +82 -69
  468. package/src/tui/terminalInputFramer.ts +116 -0
  469. package/src/tui/text.js +25 -10
  470. package/src/tui/text.ts +24 -10
  471. package/src/tui/textLayout.js +0 -1
  472. package/src/tui/textLayout.ts +0 -1
  473. package/src/tui/theme.js +245 -250
  474. package/src/tui/theme.ts +441 -0
  475. package/src/tui/thinkingBox.js +0 -1
  476. package/src/tui/thinkingBox.ts +0 -1
  477. package/src/tui/transcript.js +239 -216
  478. package/src/tui/transcript.ts +324 -0
  479. package/src/tui/turnRail.js +53 -54
  480. package/src/tui/turnRail.ts +51 -49
  481. package/src/tui/usageCard.js +0 -2
  482. package/src/tui/usageCard.ts +0 -2
  483. package/src/tui/workspaceSwitch.js +4 -2
  484. package/src/tui/workspaceSwitch.ts +5 -2
  485. package/src/types/contracts.ts +4 -1
  486. package/src/utils/browserOpen.js +107 -0
  487. package/src/utils/browserOpen.ts +129 -0
  488. package/src/utils/cli_ui.js +0 -0
  489. package/src/utils/cli_ui.ts +158 -0
  490. package/src/utils/winSpawn.js +248 -0
  491. package/src/utils/winSpawn.ts +275 -0
  492. package/src/verification/boundedExplorer.js +138 -107
  493. package/src/verification/boundedExplorer.ts +154 -0
  494. package/src/verification/byokSmokeProbe.js +193 -0
  495. package/src/verification/byokSmokeProbe.ts +234 -0
  496. package/src/verification/cliProbe.js +144 -110
  497. package/src/verification/cliProbe.ts +170 -0
  498. package/src/verification/featureMap.js +105 -75
  499. package/src/verification/featureMap.ts +124 -0
  500. package/src/verification/interactivePty.js +195 -100
  501. package/src/verification/interactivePty.ts +333 -0
  502. package/src/verification/propertyProbe.js +109 -101
  503. package/src/verification/propertyProbe.ts +159 -0
  504. package/src/verification/ptyProbe.js +168 -73
  505. package/src/verification/ptyProbe.ts +254 -0
  506. package/src/verification/skillCatalog.js +25 -25
  507. package/src/verification/skillCatalog.ts +66 -0
  508. package/src/verification/statechart.js +140 -127
  509. package/src/verification/statechart.ts +196 -0
  510. package/src/verification/uiRuntime.js +80 -49
  511. package/src/verification/uiRuntime.ts +88 -0
  512. package/src/version.js +37 -32
  513. package/src/version.ts +45 -0
  514. package/src/web/client/browserPanel.js +702 -0
  515. package/src/web/client/browserPanel.ts +663 -0
  516. package/src/web/client/chatStream.js +309 -0
  517. package/src/web/client/chatStream.ts +289 -0
  518. package/src/web/client/cliPanel.js +165 -0
  519. package/src/web/client/cliPanel.ts +171 -0
  520. package/src/web/client/composer.js +204 -0
  521. package/src/web/client/composer.ts +209 -0
  522. package/src/web/client/diffPanel.js +176 -0
  523. package/src/web/client/diffPanel.ts +203 -0
  524. package/src/web/client/dom.js +220 -0
  525. package/src/web/client/dom.ts +221 -0
  526. package/src/web/client/filesAndCanvas.js +231 -0
  527. package/src/web/client/filesAndCanvas.ts +238 -0
  528. package/src/web/client/gameLauncherUi.js +78 -0
  529. package/src/web/client/gameLauncherUi.ts +78 -0
  530. package/src/web/client/main.js +301 -0
  531. package/src/web/client/main.ts +368 -0
  532. package/src/web/client/markdown.js +364 -0
  533. package/src/web/client/markdown.ts +373 -0
  534. package/src/web/client/modelPicker.js +455 -0
  535. package/src/web/client/modelPicker.ts +451 -0
  536. package/src/web/client/permissionPresetsUi.js +307 -0
  537. package/src/web/client/permissionPresetsUi.ts +333 -0
  538. package/src/web/client/sessions.js +353 -0
  539. package/src/web/client/sessions.ts +372 -0
  540. package/src/web/client/settingsModal.js +191 -0
  541. package/src/web/client/settingsModal.ts +176 -0
  542. package/src/web/client/state.js +250 -0
  543. package/src/web/client/state.ts +233 -0
  544. package/src/web/client/streamSmoother.js +127 -0
  545. package/src/web/client/streamSmoother.ts +119 -0
  546. package/src/web/client/studioLayout.js +54 -0
  547. package/src/web/client/studioLayout.ts +60 -0
  548. package/src/web/client/studioShell.js +327 -0
  549. package/src/web/client/studioShell.ts +340 -0
  550. package/src/web/client/studioStart.js +77 -0
  551. package/src/web/client/studioStart.ts +89 -0
  552. package/src/web/client/terminalPanel.js +357 -0
  553. package/src/web/client/terminalPanel.ts +345 -0
  554. package/src/web/client/turnView.js +934 -0
  555. package/src/web/client/turnView.ts +981 -0
  556. package/src/web/client/types.js +1 -0
  557. package/src/web/client/types.ts +319 -0
  558. package/src/web/client/validators.js +106 -0
  559. package/src/web/client/validators.ts +96 -0
  560. package/src/web/guiLauncher.js +89 -0
  561. package/src/web/guiLauncher.ts +119 -0
  562. package/src/web/server/activeRuns.js +152 -0
  563. package/src/web/server/activeRuns.ts +171 -0
  564. package/src/web/server/routesBrowser.js +355 -0
  565. package/src/web/server/routesBrowser.ts +386 -0
  566. package/src/web/server/routesChat.js +304 -0
  567. package/src/web/server/routesChat.ts +347 -0
  568. package/src/web/server/routesCore.js +472 -0
  569. package/src/web/server/routesCore.ts +522 -0
  570. package/src/web/server/routesTerminal.js +162 -0
  571. package/src/web/server/routesTerminal.ts +182 -0
  572. package/src/web/server/routesWorkspace.js +510 -0
  573. package/src/web/server/routesWorkspace.ts +546 -0
  574. package/src/web/server/security.js +98 -0
  575. package/src/web/server/security.ts +108 -0
  576. package/src/web/server/sessionTranscript.js +586 -0
  577. package/src/web/server/sessionTranscript.ts +566 -0
  578. package/src/web/server/staticAssets.js +80 -0
  579. package/src/web/server/staticAssets.ts +91 -0
  580. package/src/web/server/types.js +1 -0
  581. package/src/web/server/types.ts +135 -0
  582. package/src/web/server/workspaceFiles.js +368 -0
  583. package/src/web/server/workspaceFiles.ts +363 -0
  584. package/src/web/skybridgeBrowserBridge.js +256 -0
  585. package/src/web/skybridgeBrowserBridge.ts +285 -0
  586. package/src/web/skybridgeBrowserMcp.js +730 -0
  587. package/src/web/skybridgeBrowserMcp.ts +813 -0
  588. package/src/web/skybridgeServer.js +249 -0
  589. package/src/web/skybridgeServer.ts +305 -0
  590. package/src/web/skybridgeUi.js +38 -0
  591. package/src/web/skybridgeUi.ts +47 -0
  592. package/src/web/styles/agent.css +380 -0
  593. package/src/web/styles/composer.css +193 -0
  594. package/src/web/styles/overlays.css +436 -0
  595. package/src/web/styles/shell.css +387 -0
  596. package/src/web/styles/studio.css +723 -0
  597. package/src/web/styles/thread.css +221 -0
  598. package/src/web/styles/tokens.css +94 -0
  599. package/src/web/ui/brandMark.js +73 -0
  600. package/src/web/ui/brandMark.ts +82 -0
  601. package/src/web/ui/modalsTemplate.js +139 -0
  602. package/src/web/ui/modalsTemplate.ts +139 -0
  603. package/src/web/ui/sidebarTemplate.js +63 -0
  604. package/src/web/ui/sidebarTemplate.ts +64 -0
  605. package/src/web/ui/studioTemplate.js +258 -0
  606. package/src/web/ui/studioTemplate.ts +258 -0
  607. package/src/web/ui/workspaceTemplate.js +72 -0
  608. package/src/web/ui/workspaceTemplate.ts +73 -0
  609. package/src/worktreeManager.js +526 -0
  610. package/src/worktreeManager.ts +567 -0
  611. package/src/zeroCostFailover.js +168 -0
  612. package/src/zeroCostFailover.ts +198 -0
  613. package/src/zeroCostRouting.js +391 -0
  614. package/src/zeroCostRouting.ts +437 -0
  615. package/src/agentLoop.d.ts +0 -65
  616. package/src/auditLog.d.ts +0 -3
  617. package/src/checkpoints.d.ts +0 -4
  618. package/src/compiledSkills.d.ts +0 -5
  619. package/src/contextManager.d.ts +0 -14
  620. package/src/designPalettes.d.ts +0 -2
  621. package/src/devMode.d.ts +0 -1
  622. package/src/embodimentSession.d.ts +0 -2
  623. package/src/licensing/entitlements.d.ts +0 -14
  624. package/src/memory.d.ts +0 -13
  625. package/src/memoryManager.d.ts +0 -1
  626. package/src/modelCatalogue.d.ts +0 -6
  627. package/src/modelIds.d.ts +0 -2
  628. package/src/outputStore.d.ts +0 -4
  629. package/src/plugins/pluginManager.d.ts +0 -7
  630. package/src/providers/antigravity.d.ts +0 -19
  631. package/src/provisioning/capabilityProvisioner.d.ts +0 -12
  632. package/src/slopDetector.d.ts +0 -3
  633. package/src/taskBuffer.d.ts +0 -1
  634. package/src/tools/desktopAct.d.ts +0 -10
  635. package/src/tools/registry.d.ts +0 -5
  636. package/src/tui/chatRenderer.d.ts +0 -27
  637. package/src/tui/diff.d.ts +0 -3
  638. package/src/utils/cli_ui.d.ts +0 -19
  639. package/src/utils/paths.d.ts +0 -3
  640. package/src/verification/skillCatalog.d.ts +0 -1
  641. package/src/version.d.ts +0 -1
package/src/tui/prompt.js CHANGED
@@ -16,7 +16,6 @@
16
16
  // never be the reason chat does not start.
17
17
  //
18
18
  // Pure Node. No dependency, no shell.
19
-
20
19
  import { KeyDecoder, bracketedPaste } from './keys.js';
21
20
  import { TerminalInputFramer, INPUT_PREFIX_TIMEOUT_MS, shouldTreatAsAtomicPaste } from './terminalInputFramer.js';
22
21
  import { LineEditor } from './lineEditor.js';
@@ -26,15 +25,15 @@ import { removeInlineSlashToken, isInlineSkillInvocation } from './inlineSlash.j
26
25
  import { paint, dim, bold, GLYPHS, terminalWidth, HAS_COLOR } from './theme.js';
27
26
  import { barBlock, GUTTER } from './block.js';
28
27
  import { composerGeometry } from './composerGeometry.js';
29
- import { visibleWidth, truncate, wrapBlock, shortenHome, safeDisplay, stripAnsi } from './text.js';
28
+ import { visibleWidth, truncate, wrapBlock, shortenHome, safeDisplay } from './text.js';
30
29
  import { pickExample, fitHints } from './banner.js';
31
30
  import { panelRows } from './overlay.js';
32
31
  import { renderUsageCardRows, renderStatusCardRows, collectUsageCardData } from './usageCard.js';
33
32
  import { buildStatusText } from '../reporting.js';
33
+ import { formatPermissionPresetLabel } from '../permissionPresets.js';
34
34
  import { commandPalette, skillPicker, ApprovalLayer, DecisionLayer, ConfirmLayer, HomeLayer, TextLayer } from './dialogs.js';
35
35
  import { describeTool } from './toolDisplay.js';
36
- import { readClipboardSync, writeClipboardSync } from './clipboardSync.js';
37
- import { readClipboardImageSync, formatByteSize, loadLocalImageAttachment } from './clipboardImage.js';
36
+ import { writeClipboardSync } from './clipboardSync.js';
38
37
  import { pasteIntoChatbox } from './chatboxClipboard.js';
39
38
  import { handleViewportWheel, handleScrollbarMouse } from './scrollInteraction.js';
40
39
  import { centerRows, sessionRows, dialogWidth, dialogHeight } from './layout.js';
@@ -44,2191 +43,1859 @@ import { isStartupDialog, startupDialogView } from './homeView.js';
44
43
  import { handleMessageMouse, handleMessageActionMenuMouse, isMouseMotion } from './messageInteraction.js';
45
44
  import { handleTurnRailMouse } from './turnRail.js';
46
45
  import { runWithStageWrite } from './consoleGuard.js';
47
- import {
48
- resetTurnInterruptState,
49
- shouldAcceptStatusUpdate,
50
- triggerTurnInterrupt,
51
- handlePromptCtrlC,
52
- handlePromptEscape
53
- } from './composerControls.js';
54
-
46
+ import { resetTurnInterruptState, shouldAcceptStatusUpdate, triggerTurnInterrupt, handlePromptCtrlC, handlePromptEscape } from './composerControls.js';
55
47
  const CTRL_C_WINDOW_MS = 2000;
56
-
57
48
  // Rows the editor may occupy before it starts scrolling internally.
58
- //
59
- // Without a cap, pasting a 200-line file draws 200 rows and erase() then walks
60
- // 200 rows back up every keystroke. The live region has to stay small enough
61
- // that the conversation above it is never pushed off the screen.
62
49
  const MAX_PROMPT_ROWS = 8;
63
-
64
50
  // How long to wait for a resize gesture to settle before repainting.
65
- //
66
- // A window drag delivers a resize event per step — dozens per second. Painting
67
- // the live region on each one is what filled the screen with overlapping copies
68
- // of the input row. One repaint per gesture is both correct and invisible to the
69
- // user at this delay.
70
51
  const RESIZE_SETTLE_MS = 60;
71
-
72
- // Air. The two rows that were missing.
73
- //
74
- // opencode's prompt box carries paddingTop={1} INSIDE its filled surface and a
75
- // one-row bordered spacer between the box and the footer
76
- // (component/prompt/index.tsx:1361-1363, :1487-1497). Causyne had neither: the
77
- // caret sat on the very first row of the fill and the footer was welded to the
78
- // bottom of the box, which is what made the whole thing read as jammed into the
79
- // last four rows of the terminal.
80
- //
81
- // They are constants rather than magic numbers in the layout because the caret
82
- // row is computed from them — get that wrong and the cursor parks on the wrong
83
- // line, which is the class of bug erase() exists to prevent.
84
52
  const PROMPT_PAD_TOP = 1;
85
53
  const PROMPT_PAD_BOTTOM = 1;
86
54
  const FOOTER_GAP = 1;
87
-
88
- // Air is what a roomy terminal can afford, and the first thing a cramped one
89
- // gives up.
90
- //
91
- // opencode's spacers carry `minHeight={0} flexShrink={1}` (routes/home.tsx:73-80)
92
- // precisely so they collapse before anything with content does. Causyne has no
93
- // flex engine, so the same idea is arithmetic — and it is not decoration: on a
94
- // 17-row terminal the extra row made the banner plus the band come to exactly 17,
95
- // which costs the top of the wordmark. UX-03's sweep is what caught it.
96
55
  const ROOMY_TERMINAL_ROWS = 20;
97
56
  const CRAMPED_TERMINAL_ROWS = 18;
98
-
99
57
  /** Can this process own the keyboard? */
100
58
  export function isInteractive() {
101
- if (process.env.CAUSYNE_SIMPLE_INPUT === '1') return false;
102
- return Boolean(process.stdin.isTTY && process.stdout.isTTY);
59
+ if (process.env.CAUSYNE_SIMPLE_INPUT === '1')
60
+ return false;
61
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
103
62
  }
104
-
105
63
  export class ChatPrompt {
106
- constructor(options = {}) {
107
- this.out = options.out || process.stdout;
108
- this.input = options.input || process.stdin;
109
- this.root = options.root || process.cwd();
110
- this.focusDir = options.focusDir || null;
111
- this.onInterrupt = options.onInterrupt || (() => {});
112
-
113
- // The Stage, when one is running. Null means the scrollback renderer, which
114
- // is what every non-TTY, dumb terminal and CAUSYNE_STAGE=off session gets.
115
- this.surface = options.surface || null;
116
- this.onExit = options.onExit || (() => process.exit(0));
117
- this.onExpand = options.onExpand || (() => {});
118
- this.onOpenMode = options.onOpenMode || null;
119
- this.onOpenModel = options.onOpenModel || null;
120
- this.onOpenVariant = options.onOpenVariant || null;
121
- this.messageActionLoop = options.messageActionLoop || null;
122
- this.getMode = options.getMode || (() => 'B');
123
-
124
- this.editor = new LineEditor();
125
- this.history = options.history || new PromptHistory();
126
- this.index = new FileIndex(this.root);
127
- this._unsubscribeFileIndex = null;
128
- this.bindFileIndex(this.index);
129
- this.decoder = new KeyDecoder();
130
- this.inputFramer = new TerminalInputFramer();
131
- this.inputFrameTimer = null;
132
- this.decoderRecoveryTimer = null;
133
-
134
- this.busy = false;
135
- this.active = false;
136
- this.exitHook = null;
137
- this.drawnRows = 0;
138
- this.usageCard = null;
139
- this.usageCardLoading = false;
140
- this.statusCard = null;
141
- this.statusCardUsage = null;
142
- this.infoPanelVersion = 0;
143
- this.usageRefreshPending = false;
144
-
145
- // Which row of the drawn block the caret is parked on.
146
- //
147
- // erase() has to walk back up to the FIRST row of the block. It used to
148
- // assume the caret was on the last one and move up drawnRows - 1 — but
149
- // draw() deliberately parks it on the editor's cursor row, which is higher
150
- // whenever a completion picker or a notice is showing, or the caret sits on
151
- // an earlier line of a multiline message. The difference was walked up past
152
- // the top of the block and then erased with \x1b[J, destroying that many
153
- // rows of real conversation above the prompt.
154
- this.cursorRow = 0;
155
-
156
- // The status row of the live region, and the clock that animates it.
157
- this.renderer = options.renderer || null;
158
- this.statusMessage = '';
159
- this.tick = 0;
160
- this.tickTimer = null;
161
-
162
- // One concrete example, chosen per session — `ask anything` teaches a new
163
- // user nothing about what this agent can actually be asked to do.
164
- this.example = pickExample();
165
-
166
- // Commands for the palette, and the dialog that currently owns the keyboard.
167
- //
168
- // Dialogs use the live stage as a centered temporary view and restore the
169
- // transcript when dismissed. Terminal scrollback is not repainted.
170
- this.commands = options.commands || [];
171
-
172
- // Is this line a COMMAND rather than a message?
173
- //
174
- // Injected rather than imported: commands.js pulls in the compiled skill
175
- // payload, the MCP registry and the slop detector, and this file's whole
176
- // premise is that it depends on nothing. The rule still lives in exactly
177
- // one place (commands.js isCommandInput) — cliMode hands it down.
178
- this.isCommand = typeof options.isCommand === 'function' ? options.isCommand : () => false;
179
- this.layer = null;
180
- this.queue = [];
181
- this.waiter = null;
182
- // Each submission owns its attachments; later pasted images must not leak
183
- // into a turn which was already sent.
184
- this.currentSubmissionAttachments = null;
185
- this.completion = null;
186
- this.selected = 0;
187
- this.lastCtrlC = 0;
188
- this.interruptedTurn = false;
189
- this.notice = '';
190
- this.redrawScheduled = false;
191
- this.resizeTimer = null;
192
- this.suspendedSurface = null;
193
- this.pendingAttachments = [];
194
- }
195
-
196
- // -------------------------------------------------------------------------
197
- // Lifecycle
198
- // -------------------------------------------------------------------------
199
-
200
- writeControl(sequence) {
201
- if (!sequence) return;
202
- runWithStageWrite(() => {
203
- this.out.write(sequence);
204
- });
205
- }
206
-
207
- start() {
208
- if (this.active) return;
209
- this.active = true;
210
- this.inputFramer.clear();
211
- this.input.setRawMode(true);
212
- this.input.resume();
213
- this.input.on('data', this.handleData);
214
- this.writeControl(bracketedPaste(true));
215
- // Node's normal exit does not guarantee ChatPrompt.stop() is called.
216
- // Always restore bracketed paste and raw stdin when the process exits.
217
- this.exitHook = () => {
218
- try { this.writeControl(bracketedPaste(false)); } catch { /* terminal already closed */ }
219
- try { this.input.setRawMode(false); } catch { /* stdin already closed */ }
220
- };
221
- process.once('exit', this.exitHook);
222
- // Rows are laid out against the terminal width; without this they stay stale
223
- // until the next keystroke, and a narrowed terminal wraps rows that erase()
224
- // is still counting as one.
225
- if (typeof this.out.on === 'function') this.out.on('resize', this.handleResize);
226
- }
227
-
228
- stop() {
229
- if (!this.active) return;
230
- this.active = false;
231
- if (this.layer) {
232
- const layer = this.layer;
233
- this.layer = null;
234
- if (typeof layer.answer === 'function') layer.answer(false);
235
- }
236
- this.stopTick();
237
- if (this.inputFrameTimer) { clearTimeout(this.inputFrameTimer); this.inputFrameTimer = null; }
238
- if (this.decoderRecoveryTimer) { clearTimeout(this.decoderRecoveryTimer); this.decoderRecoveryTimer = null; }
239
- this.inputFramer.clear();
240
- this.decoder.pending = Buffer.alloc(0);
241
- if (this.resizeTimer) { clearTimeout(this.resizeTimer); this.resizeTimer = null; }
242
- this.erase();
243
- // The exit contract (UX-01 rev 2 clause d): the band collapses and the whole
244
- // session is flushed into real terminal scrollback, so leaving Causyne leaves
245
- // a transcript behind exactly as it always has.
246
- if (this.surface) this.surface.close();
247
- this.writeControl(bracketedPaste(false));
248
- if (typeof this.out.removeListener === 'function') this.out.removeListener('resize', this.handleResize);
249
- this.input.off('data', this.handleData);
250
- try { this.input.setRawMode(false); } catch (e) { /* already closed */ }
251
- this.input.pause();
252
- if (this.exitHook) {
253
- process.removeListener('exit', this.exitHook);
254
- this.exitHook = null;
255
- }
256
- }
257
-
258
- /**
259
- * The terminal changed size. Take the live region down before redrawing it.
260
- *
261
- * This used to zero drawnRows and cursorRow and then schedule a draw. Zeroing
262
- * the counters is what erase() reads to decide how far to walk back up — so
263
- * with them at zero it returned IMMEDIATELY and removed nothing, while the
264
- * caret was still parked mid-block at column 2 from the previous draw. The
265
- * redraw then wrote a fresh copy starting at that column, on top of a row that
266
- * already had content.
267
- *
268
- * One stale copy per event. Dragging a window emits hundreds, and the result
269
- * was a screen filled edge to edge with overlapping copies of the input row.
270
- *
271
- * Erasing with the pre-resize geometry is approximate — the terminal has
272
- * already reflowed what we drew — but approximate removal is categorically
273
- * better than none, and the debounce below means it happens once per gesture
274
- * instead of once per pixel.
275
- */
276
- handleResize = () => {
277
- if (!this.resizeTimer) this.erase();
278
- // The Stage owns its own geometry and cannot repaint a band whose height it
279
- // no longer knows. Resizing it here, before the settle timer, would do it
280
- // once per pixel of a drag; it is done in the settled callback below.
281
- // A drag delivers a continuous stream of these. Redrawing on every one is
282
- // both the corruption above and a huge amount of pointless output; settle
283
- // first, then draw once.
284
- if (this.resizeTimer) clearTimeout(this.resizeTimer);
285
- this.resizeTimer = setTimeout(() => {
286
- this.resizeTimer = null;
287
- // Geometry from before the reflow is meaningless now. Drop it AFTER the
288
- // erase above has used it, not before.
289
- this.drawnRows = 0;
290
- this.cursorRow = 0;
291
- // A stage that can no longer fit gives the band back and hands the
292
- // session to the scrollback renderer rather than painting into a region
293
- // too short to hold a viewport.
294
- const settled = settleStageResize(this.surface, this.suspendedSurface);
295
- this.surface = settled.current;
296
- this.suspendedSurface = settled.suspended;
297
- if (settled.restored) this.attachSurface(settled.current);
298
- this.draw();
299
- }, RESIZE_SETTLE_MS);
300
- if (this.resizeTimer.unref) this.resizeTimer.unref();
301
- };
302
-
303
- handleData = (chunk) => {
304
- // KeyDecoder expects complete escape prefixes. A PTY may split ESC from
305
- // `[<button;x;yM`; framing these bytes first prevents mouse coordinates
306
- // from becoming chat content. Do not decode bulk paste before this step.
307
- const frames = this.inputFramer.push(chunk);
308
- for (const frame of frames) this.handleFramedData(frame);
309
- if (this.inputFrameTimer) { clearTimeout(this.inputFrameTimer); this.inputFrameTimer = null; }
310
- if (this.inputFramer.hasPending) {
311
- this.inputFrameTimer = setTimeout(() => {
64
+ out;
65
+ input;
66
+ root;
67
+ focusDir;
68
+ onInterrupt;
69
+ surface;
70
+ onExit;
71
+ onExpand;
72
+ onOpenMode;
73
+ onCycleMode;
74
+ onOpenModel;
75
+ onOpenVariant;
76
+ onOpenVariantList;
77
+ messageActionLoop;
78
+ getMode;
79
+ editor;
80
+ history;
81
+ index;
82
+ _unsubscribeFileIndex;
83
+ decoder;
84
+ inputFramer;
85
+ inputFrameTimer;
86
+ decoderRecoveryTimer;
87
+ busy;
88
+ active;
89
+ exitHook;
90
+ drawnRows;
91
+ usageCard;
92
+ usageCardLoading;
93
+ statusCard;
94
+ statusCardUsage;
95
+ infoPanelVersion;
96
+ usageRefreshPending;
97
+ cursorRow;
98
+ renderer;
99
+ statusMessage;
100
+ tick;
101
+ tickTimer;
102
+ example;
103
+ commands;
104
+ isCommand;
105
+ layer;
106
+ queue;
107
+ waiter;
108
+ currentSubmissionAttachments;
109
+ completion;
110
+ selected;
111
+ lastCtrlC;
112
+ interruptedTurn;
113
+ notice;
114
+ redrawScheduled;
115
+ resizeTimer;
116
+ suspendedSurface;
117
+ pendingAttachments;
118
+ pickerLayout;
119
+ constructor(options = {}) {
120
+ const opts = options && typeof options === 'object' ? options : {};
121
+ this.out = opts.out || process.stdout;
122
+ this.input = opts.input || process.stdin;
123
+ this.root = opts.root || process.cwd();
124
+ this.focusDir = opts.focusDir || null;
125
+ this.onInterrupt = opts.onInterrupt || (() => { });
126
+ this.surface = opts.surface || null;
127
+ this.onExit = opts.onExit || (() => process.exit(0));
128
+ this.onExpand = opts.onExpand || (() => { });
129
+ this.onOpenMode = opts.onOpenMode || null;
130
+ this.onCycleMode = opts.onCycleMode || null;
131
+ this.onOpenModel = opts.onOpenModel || null;
132
+ this.onOpenVariant = opts.onOpenVariant || null;
133
+ this.onOpenVariantList = opts.onOpenVariantList || null;
134
+ this.messageActionLoop = opts.messageActionLoop || null;
135
+ this.getMode = opts.getMode || (() => 'workspace-write');
136
+ this.editor = new LineEditor();
137
+ this.history = opts.history || new PromptHistory();
138
+ this.index = new FileIndex(this.root);
139
+ this._unsubscribeFileIndex = null;
140
+ this.bindFileIndex(this.index);
141
+ this.decoder = new KeyDecoder();
142
+ this.inputFramer = new TerminalInputFramer();
312
143
  this.inputFrameTimer = null;
313
- for (const frame of this.inputFramer.flush()) this.handleFramedData(frame);
314
- }, INPUT_PREFIX_TIMEOUT_MS);
315
- this.inputFrameTimer.unref?.();
316
- }
317
- };
318
-
319
- flushCharBatch(charBatch) {
320
- if (!charBatch) return '';
321
- this.prepareKeyboardState(true);
322
- this.editor.insert(charBatch);
323
- if (charBatch.length < 60 && !charBatch.includes('\n')) {
324
- this.refreshCompletion();
325
- } else {
326
- this.completion = null;
327
- }
328
- return '';
329
- }
330
-
331
- prepareKeyboardState(clearNotice) {
332
- if (clearNotice && this.notice && !this.layer) this.notice = '';
333
- if (this.surface && typeof this.surface.captureMouse === 'function') {
334
- if (this.surface.captureMouse() && typeof this.notice === 'string' && this.notice.startsWith('top of this view')) {
144
+ this.decoderRecoveryTimer = null;
145
+ this.busy = false;
146
+ this.active = false;
147
+ this.exitHook = null;
148
+ this.drawnRows = 0;
149
+ this.usageCard = null;
150
+ this.usageCardLoading = false;
151
+ this.statusCard = null;
152
+ this.statusCardUsage = null;
153
+ this.infoPanelVersion = 0;
154
+ this.usageRefreshPending = false;
155
+ this.cursorRow = 0;
156
+ this.renderer = opts.renderer || null;
157
+ this.statusMessage = '';
158
+ this.tick = 0;
159
+ this.tickTimer = null;
160
+ this.example = pickExample();
161
+ this.commands = opts.commands || [];
162
+ this.isCommand = typeof opts.isCommand === 'function' ? opts.isCommand : () => false;
163
+ this.layer = null;
164
+ this.queue = [];
165
+ this.waiter = null;
166
+ this.currentSubmissionAttachments = null;
167
+ this.completion = null;
168
+ this.selected = 0;
169
+ this.lastCtrlC = 0;
170
+ this.interruptedTurn = false;
335
171
  this.notice = '';
336
- }
172
+ this.redrawScheduled = false;
173
+ this.resizeTimer = null;
174
+ this.suspendedSurface = null;
175
+ this.pendingAttachments = [];
176
+ this.pickerLayout = null;
177
+ }
178
+ // -------------------------------------------------------------------------
179
+ // Lifecycle
180
+ // -------------------------------------------------------------------------
181
+ writeControl(sequence) {
182
+ if (!sequence)
183
+ return;
184
+ runWithStageWrite(() => {
185
+ this.out.write(sequence);
186
+ });
337
187
  }
338
- if (this.surface) {
339
- this.surface.turnRailHoverSuppressed = false;
340
- if (this.surface.hoveredTurnIndex !== null && this.surface.hoveredTurnIndex !== undefined) {
341
- this.surface.hoveredTurnIndex = null;
342
- this.surface.hoveredTurnAnchorY = null;
343
- this.scheduleDraw();
344
- }
345
- }
346
- }
347
-
348
- handleFramedData = (chunk) => {
349
- let motionOnly = true;
350
- const str = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString('utf8') : '';
351
- // Unbracketed bulk input remains atomic ONLY when no control sequence
352
- // is still in flight. This fixes mixed mouse/typing chunks that previously
353
- // bypassed KeyDecoder and leaked CSI tails into the composer.
354
- if (!this.layer && shouldTreatAsAtomicPaste(chunk, this.decoder)) {
355
- try {
356
- this.handleKey({ name: 'paste', text: str, sequence: '' });
357
- } catch (error) {
358
- this.notice = `paste failed: ${error instanceof Error ? error.message : String(error)}`;
359
- this.scheduleDraw();
360
- }
361
- this.draw();
362
- return;
363
- }
364
-
365
- const keys = this.decoder.decode(chunk);
366
- // A truncated CSI/X10 mouse report must not swallow the next user keystroke.
367
- // Paste is exempt: its terminator may arrive across many chunks.
368
- if (this.decoderRecoveryTimer) clearTimeout(this.decoderRecoveryTimer);
369
- this.decoderRecoveryTimer = null;
370
- if (!this.decoder.inPaste && this.decoder.pending.length > 0) {
371
- this.decoderRecoveryTimer = setTimeout(() => {
372
- this.decoderRecoveryTimer = null;
373
- const recovered = this.decoder.drainIncomplete();
374
- for (const event of recovered) this.handleKey(event);
375
- if (recovered.length) this.scheduleDraw();
376
- }, 180);
377
- this.decoderRecoveryTimer.unref?.();
378
- }
379
- let charBatch = '';
380
-
381
- for (let i = 0; i < keys.length; i++) {
382
- const key = keys[i];
383
- if (!this.layer && key.name === 'char' && typeof key.text === 'string' && !key.alt && !key.ctrl) {
384
- charBatch += key.text;
385
- motionOnly = false;
386
- continue;
387
- }
388
- if (charBatch.length > 0) {
389
- charBatch = this.flushCharBatch(charBatch);
390
- }
391
- if (key.name !== 'mouse' || !isMouseMotion(key.sequence)) motionOnly = false;
392
- try {
393
- this.handleKey(key);
394
- } catch (e) {
395
- // A key handler must never take the session down. Say so once and
396
- // carry on, rather than dying silently the way the old catch(e){} did.
397
- this.notice = `input error: ${e instanceof Error ? e.message : String(e)}`;
398
- this.scheduleDraw();
399
- }
400
- }
401
-
402
- if (charBatch.length > 0) {
403
- charBatch = this.flushCharBatch(charBatch);
404
- }
405
-
406
- // All-motion chunks repaint only when the hovered message actually changes.
407
- if (!motionOnly) this.draw();
408
- };
409
-
410
- /**
411
- * Let the transcript print without fighting the prompt for the same rows.
412
- *
413
- * The renderer writes upward from where the cursor is; the prompt lives at the
414
- * bottom. Without this the two interleave and leave debris on screen.
415
- */
416
- attach(renderer) {
417
- renderer.onBeforeWrite = () => this.erase();
418
- renderer.onAfterWrite = () => this.scheduleDraw();
419
-
420
- // Take the status line over from the renderer's spinner.
421
- //
422
- // That spinner writes straight to stdout with readline.cursorTo(out, 0),
423
- // which lands on whatever row the caret is on — and after draw() that is a
424
- // row INSIDE the prompt block. Every 90 ms frame overwrote the prompt's first
425
- // row and clearLine ate the rest, leaving drawnRows describing a block that
426
- // was no longer on screen. It also bypassed onBeforeWrite/onAfterWrite
427
- // entirely, so the prompt never got a chance to lift itself out of the way.
428
- //
429
- // The renderer already has the right behaviour for this: the quiet path it
430
- // uses in full-screen mode, which reports status instead of animating it.
431
- // Reuse that and make the status a row of the live region.
432
- this.renderer = renderer;
433
- if (this.surface) this.surface.sidebarStatus = renderer.status;
434
- renderer.quietStatus = true;
435
- renderer.onStatusChange = (message) => {
436
- if (!shouldAcceptStatusUpdate(this)) return;
437
- this.statusMessage = message;
438
- this.scheduleDraw();
188
+ start() {
189
+ if (this.active)
190
+ return;
191
+ this.active = true;
192
+ this.inputFramer.clear();
193
+ this.input.setRawMode(true);
194
+ this.input.resume();
195
+ this.input.on('data', this.handleData);
196
+ this.writeControl(bracketedPaste(true));
197
+ this.exitHook = () => {
198
+ try {
199
+ this.writeControl(bracketedPaste(false));
200
+ }
201
+ catch { /* terminal already closed */ }
202
+ try {
203
+ this.input.setRawMode(false);
204
+ }
205
+ catch { /* stdin already closed */ }
206
+ };
207
+ process.once('exit', this.exitHook);
208
+ if (typeof this.out.on === 'function')
209
+ this.out.on('resize', this.handleResize);
210
+ }
211
+ stop() {
212
+ if (!this.active) {
213
+ if (this.waiter) {
214
+ const resolve = this.waiter;
215
+ this.waiter = null;
216
+ resolve(null);
217
+ }
218
+ return;
219
+ }
220
+ this.active = false;
221
+ if (this.layer) {
222
+ const layer = this.layer;
223
+ this.layer = null;
224
+ if (typeof layer.answer === 'function')
225
+ layer.answer(false);
226
+ }
227
+ if (this.waiter) {
228
+ const resolve = this.waiter;
229
+ this.waiter = null;
230
+ resolve(null);
231
+ }
232
+ if (typeof this._unsubscribeFileIndex === 'function') {
233
+ this._unsubscribeFileIndex();
234
+ this._unsubscribeFileIndex = null;
235
+ }
236
+ this.index?.dispose();
237
+ this.stopTick();
238
+ if (this.inputFrameTimer) {
239
+ clearTimeout(this.inputFrameTimer);
240
+ this.inputFrameTimer = null;
241
+ }
242
+ if (this.decoderRecoveryTimer) {
243
+ clearTimeout(this.decoderRecoveryTimer);
244
+ this.decoderRecoveryTimer = null;
245
+ }
246
+ this.inputFramer.clear();
247
+ this.decoder.pending = Buffer.alloc(0);
248
+ if (this.resizeTimer) {
249
+ clearTimeout(this.resizeTimer);
250
+ this.resizeTimer = null;
251
+ }
252
+ this.erase();
253
+ if (this.surface)
254
+ this.surface.close();
255
+ this.writeControl(bracketedPaste(false));
256
+ if (typeof this.out.removeListener === 'function')
257
+ this.out.removeListener('resize', this.handleResize);
258
+ this.input.off('data', this.handleData);
259
+ try {
260
+ this.input.setRawMode(false);
261
+ }
262
+ catch { /* already closed */ }
263
+ this.input.pause();
264
+ if (this.exitHook) {
265
+ process.removeListener('exit', this.exitHook);
266
+ this.exitHook = null;
267
+ }
268
+ }
269
+ handleResize = () => {
270
+ if (!this.resizeTimer)
271
+ this.erase();
272
+ if (this.resizeTimer)
273
+ clearTimeout(this.resizeTimer);
274
+ this.resizeTimer = setTimeout(() => {
275
+ this.resizeTimer = null;
276
+ this.drawnRows = 0;
277
+ this.cursorRow = 0;
278
+ const settled = settleStageResize(this.surface, this.suspendedSurface);
279
+ this.surface = settled.current;
280
+ this.suspendedSurface = settled.suspended;
281
+ if (settled.restored)
282
+ this.attachSurface(settled.current);
283
+ this.draw();
284
+ }, RESIZE_SETTLE_MS);
285
+ if (this.resizeTimer.unref)
286
+ this.resizeTimer.unref();
439
287
  };
440
- renderer.onPlanChange = (plan) => {
441
- if (this.surface) this.surface.sidebarPlan = plan;
442
- this.scheduleDraw();
443
- return this.surface && sidebarVisible(this.surface.width, false, this.surface.env) ? 'sidebar' : undefined;
288
+ handleData = (chunk) => {
289
+ const frames = this.inputFramer.push(chunk);
290
+ for (const frame of frames)
291
+ this.handleFramedData(frame);
292
+ if (this.inputFrameTimer) {
293
+ clearTimeout(this.inputFrameTimer);
294
+ this.inputFrameTimer = null;
295
+ }
296
+ if (this.inputFramer.hasPending) {
297
+ this.inputFrameTimer = setTimeout(() => {
298
+ this.inputFrameTimer = null;
299
+ for (const frame of this.inputFramer.flush())
300
+ this.handleFramedData(frame);
301
+ }, INPUT_PREFIX_TIMEOUT_MS);
302
+ this.inputFrameTimer.unref?.();
303
+ }
304
+ };
305
+ flushCharBatch(charBatch) {
306
+ if (!charBatch)
307
+ return '';
308
+ this.prepareKeyboardState(true);
309
+ this.editor.insert(charBatch);
310
+ if (charBatch.length < 60 && !charBatch.includes('\n')) {
311
+ this.refreshCompletion();
312
+ }
313
+ else {
314
+ this.completion = null;
315
+ }
316
+ return '';
317
+ }
318
+ prepareKeyboardState(clearNotice) {
319
+ if (clearNotice && this.notice && !this.layer)
320
+ this.notice = '';
321
+ if (this.surface && typeof this.surface.captureMouse === 'function') {
322
+ if (this.surface.captureMouse() && typeof this.notice === 'string' && this.notice.startsWith('top of this view')) {
323
+ this.notice = '';
324
+ }
325
+ }
326
+ if (this.surface) {
327
+ this.surface.turnRailHoverSuppressed = false;
328
+ if (this.surface.hoveredTurnIndex !== null && this.surface.hoveredTurnIndex !== undefined) {
329
+ this.surface.hoveredTurnIndex = null;
330
+ this.surface.hoveredTurnAnchorY = null;
331
+ this.scheduleDraw();
332
+ }
333
+ }
334
+ }
335
+ handleFramedData = (chunk) => {
336
+ let motionOnly = true;
337
+ const str = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString('utf8') : '';
338
+ if (!this.layer && shouldTreatAsAtomicPaste(chunk, this.decoder)) {
339
+ try {
340
+ this.handleKey({ name: 'paste', text: str, sequence: '' });
341
+ }
342
+ catch (error) {
343
+ this.notice = `paste failed: ${this.sanitizeSingleLine(error instanceof Error ? error.message : String(error))}`;
344
+ this.scheduleDraw();
345
+ }
346
+ this.draw();
347
+ return;
348
+ }
349
+ const keys = this.decoder.decode(chunk);
350
+ if (this.decoderRecoveryTimer)
351
+ clearTimeout(this.decoderRecoveryTimer);
352
+ this.decoderRecoveryTimer = null;
353
+ if (!this.decoder.inPaste && this.decoder.pending.length > 0) {
354
+ this.decoderRecoveryTimer = setTimeout(() => {
355
+ this.decoderRecoveryTimer = null;
356
+ const recovered = this.decoder.drainIncomplete();
357
+ for (const event of recovered)
358
+ this.handleKey(event);
359
+ if (recovered.length)
360
+ this.scheduleDraw();
361
+ }, 180);
362
+ this.decoderRecoveryTimer.unref?.();
363
+ }
364
+ let charBatch = '';
365
+ for (let i = 0; i < keys.length; i++) {
366
+ const key = keys[i];
367
+ if (!key)
368
+ continue;
369
+ if (!this.layer && key.name === 'char' && typeof key.text === 'string' && !key.alt && !key.ctrl) {
370
+ charBatch += key.text;
371
+ motionOnly = false;
372
+ continue;
373
+ }
374
+ if (charBatch.length > 0) {
375
+ charBatch = this.flushCharBatch(charBatch);
376
+ }
377
+ if (key.name !== 'mouse' || !isMouseMotion(key.sequence))
378
+ motionOnly = false;
379
+ try {
380
+ this.handleKey(key);
381
+ }
382
+ catch (e) {
383
+ this.notice = `input error: ${this.sanitizeSingleLine(e instanceof Error ? e.message : String(e))}`;
384
+ this.scheduleDraw();
385
+ }
386
+ }
387
+ if (charBatch.length > 0) {
388
+ charBatch = this.flushCharBatch(charBatch);
389
+ }
390
+ if (!motionOnly)
391
+ this.draw();
444
392
  };
445
- }
446
-
447
- /**
448
- * The footer row: spinner, elapsed, steps, tokens, cost, model.
449
- *
450
- * One clock drives it, and only while a turn is running — an idle prompt costs
451
- * no timer at all. Rendered through the renderer's own StatusLine so the
452
- * usage_update counters it accumulates are the ones displayed.
453
- */
454
- statusRow(width) {
455
- if (!this.renderer || !this.renderer.status) return [];
456
- const status = this.renderer.status;
457
-
458
- // Between turns the working numbers are all zero and the line said "ready"
459
- // beside a model name — two facts nobody can act on. opencode's permanent
460
- // footer shows the working directory and what the context window has left,
461
- // which is what the idle form carries instead.
462
- if (!this.busy) {
463
- return [status.renderIdle({
464
- width: Math.max(10, width),
465
- hint: this.commands.length > 0 ? 'ctrl+p commands' : ''
466
- })];
467
- }
468
-
469
- const frame = GLYPHS.spinner[this.tick % GLYPHS.spinner.length];
470
- const since = this.renderer.turnStartedAt;
471
- return [status.render({
472
- message: this.statusMessage || 'working',
473
- elapsedMs: since ? Date.now() - since : 0,
474
- steps: this.renderer.stepCount || 0,
475
- width: Math.max(10, width - 1),
476
- spinnerFrame: frame,
477
- tick: this.tick
478
- })];
479
- }
480
-
481
- /**
482
- * The line inside the input box: mode, model, provider.
483
- *
484
- * opencode puts exactly this row at the foot of its prompt box
485
- * (`Build · MiMo V2.5 Free OpenCode Zen`), and it is the one place the fact
486
- * that matters most — which model is about to spend the user's money — is
487
- * visible at the moment they press enter. Causyne showed it once in the session
488
- * header and then never again.
489
- */
490
- agentRow(width) {
491
- const status = this.renderer && this.renderer.status;
492
- if (!status) return null;
493
-
494
- const mode = `${this.busy ? 'Working' : 'Build'} ${this.getMode()}`;
495
- const parts = [bold(paint('accent', mode))];
496
- if (status.model) parts.push(bold(paint('ink', status.model)));
497
- const line = parts.join(dim(` ${GLYPHS.dot} `));
498
- const trailing = [status.provider, status.tier].filter(Boolean).join(' ');
499
- const base = trailing ? `${line} ${dim(trailing)}` : line;
500
- const details = [];
501
- if (this.queue.length) details.push(`${this.queue.length} queued`);
502
- if (this.editor.lines.length > 1) details.push(`${this.editor.lines.length} lines`);
503
- const extra = details.length ? dim(` ${GLYPHS.dot} ${details.join(' · ')}`) : '';
504
- const withMeta = visibleWidth(base) + visibleWidth(extra) <= width ? base + extra : base;
505
- const hints = dim(' Ctrl+G mode · Alt+M model · Ctrl+T variant');
506
- const full = visibleWidth(withMeta) + visibleWidth(hints) <= width ? withMeta + hints : withMeta;
507
- return visibleWidth(full) > width ? truncate(full, width, GLYPHS.ellipsis) : full;
508
- }
509
-
510
- /** Persistent checklist shown outside the chat transcript. */
511
- planRows(width) {
512
- if (this.surface && sidebarVisible(this.surface.width, false, this.surface.env)) return [];
513
- const plan = this.renderer && Array.isArray(this.renderer.latestPlan) ? this.renderer.latestPlan : [];
514
- if (plan.length === 0) return [];
515
- const completed = plan.filter(item => item.status === 'completed').length;
516
- const stageMax = this.surface?.stage?.maxHeight || this.out?.rows || 24;
517
- if (stageMax < 22) {
518
- const activeStep = plan.find(item => item.status === 'in_progress') || plan.find(item => item.status !== 'completed') || plan[0];
519
- const stepText = activeStep ? (activeStep.text || activeStep.step || '') : '';
520
- const summary = `${paint('accent', GLYPHS.skill || '✦')} ${bold('plan')} ${dim(`(${completed}/${plan.length})`)} ${dim('·')} ${truncate(safeDisplay(stepText), Math.max(8, width - 24), GLYPHS.ellipsis)}`;
521
- return [summary, ''];
522
- }
523
- const rows = [`${bold(paint('accent', 'implementation plan'))} ${dim(`${completed}/${plan.length}`)}`];
524
- // When the sidebar is absent, keep the active task visible instead of
525
- // permanently showing the first five (often already completed) steps.
526
- const limit = Math.min(plan.length, 5);
527
- const active = plan.findIndex(item => item.status === 'in_progress');
528
- const pending = plan.findIndex(item => item.status !== 'completed');
529
- const focus = active >= 0 ? active : pending >= 0 ? pending : plan.length - 1;
530
- const start = Math.max(0, Math.min(focus - 1, plan.length - limit));
531
- if (start > 0) rows.push(` ${dim(`${GLYPHS.ellipsis} ${start} earlier`)}`);
532
- for (const item of plan.slice(start, start + limit)) {
533
- const mark = item.status === 'completed'
534
- ? paint('success', GLYPHS.check)
535
- : item.status === 'in_progress'
536
- ? paint('accent', GLYPHS.arrow)
537
- : paint('muted', GLYPHS.dot);
538
- rows.push(` ${mark} ${truncate(safeDisplay(item.text || item.step || ''), Math.max(8, width - 5), GLYPHS.ellipsis)}`);
539
- }
540
- const remaining = plan.length - start - limit;
541
- if (remaining > 0) rows.push(` ${dim(`${GLYPHS.ellipsis} ${remaining} later`)}`);
542
- rows.push('');
543
- return rows;
544
- }
545
-
546
- startTick() {
547
- if (this.tickTimer) return;
548
- this.tickTimer = setInterval(() => {
549
- this.tick++;
550
- if (this.busy) this.scheduleDraw();
551
- // Keep the pinned usage/status view current without disk reads every 125 ms.
552
- if (this.busy && (this.usageCard || this.statusCard !== null) && this.tick % 32 === 0) {
553
- this.refreshPinnedPanels();
554
- }
555
- }, 125);
556
- if (this.tickTimer.unref) this.tickTimer.unref();
557
- }
558
-
559
- stopTick() {
560
- if (!this.tickTimer) return;
561
- clearInterval(this.tickTimer);
562
- this.tickTimer = null;
563
- }
564
-
565
- openLayer(layer) {
566
- this.closeLayer();
567
- this.layer = layer;
568
- if (this.surface?.stage) this.surface.stage.invalidate();
569
- this.draw();
570
- return layer;
571
- }
572
-
573
- closeLayer() {
574
- const layer = this.layer;
575
- if (!layer) return;
576
- this.layer = null;
577
- // Dismissing a question is an ANSWER, and the safe answer is no. A layer that
578
- // is torn down without one would otherwise leave its promise pending forever
579
- // and hang the turn.
580
- if (typeof layer.answer === 'function') layer.answer(false);
581
- if (this.surface?.stage) this.surface.stage.invalidate();
582
- this.draw();
583
- }
584
-
585
- /** Every command in the app, fuzzy-searchable. */
586
- openPalette() {
587
- if (this.commands.length === 0) {
588
- this.notice = 'no commands available';
589
- return;
590
- }
591
- this.openLayer(commandPalette(this.commands, (command) => {
592
- // Run it the way the user would have typed it, so there is one execution
593
- // path for a command however it was reached.
594
- this.editor.setText(`/${command.name}`);
595
- this.layer = null;
596
- this.submit();
597
- }));
598
- }
599
-
600
-
601
- openHome(items, onPick) {
602
- if (!Array.isArray(items) || items.length === 0) {
603
- this.notice = 'no actions available';
604
- this.scheduleDraw();
605
- return null;
606
- }
607
- return this.openLayer(new HomeLayer({
608
- items,
609
- onPick: (item) => {
393
+ attach(renderer) {
394
+ renderer.onBeforeWrite = () => this.erase();
395
+ renderer.onAfterWrite = () => this.scheduleDraw();
396
+ this.renderer = renderer;
397
+ if (this.surface)
398
+ this.surface.sidebarStatus = renderer.status;
399
+ renderer.quietStatus = true;
400
+ renderer.onStatusChange = (message) => {
401
+ if (!shouldAcceptStatusUpdate(this))
402
+ return;
403
+ this.statusMessage = message;
404
+ this.scheduleDraw();
405
+ };
406
+ renderer.onPlanChange = (plan) => {
407
+ if (this.surface)
408
+ this.surface.sidebarPlan = plan;
409
+ this.scheduleDraw();
410
+ return this.surface && sidebarVisible(this.surface.width, false, this.surface.env) ? 'sidebar' : undefined;
411
+ };
412
+ }
413
+ statusRow(width) {
414
+ if (!this.renderer || !this.renderer.status)
415
+ return [];
416
+ const status = this.renderer.status;
417
+ if (!this.busy) {
418
+ return [status.renderIdle({
419
+ width: Math.max(10, width),
420
+ hint: this.commands.length > 0 ? 'ctrl+p commands' : ''
421
+ })];
422
+ }
423
+ const frame = GLYPHS.spinner[this.tick % GLYPHS.spinner.length] ?? '*';
424
+ const since = this.renderer.turnStartedAt;
425
+ return [status.render({
426
+ message: this.statusMessage || 'working',
427
+ elapsedMs: since ? Date.now() - since : 0,
428
+ steps: this.renderer.stepCount || 0,
429
+ width: Math.max(10, width - 1),
430
+ spinnerFrame: frame,
431
+ tick: this.tick
432
+ })];
433
+ }
434
+ agentRow(width) {
435
+ const status = this.renderer && this.renderer.status;
436
+ if (!status)
437
+ return null;
438
+ const presetLabel = formatPermissionPresetLabel(this.getMode());
439
+ const mode = this.busy ? `Working · ${presetLabel}` : presetLabel;
440
+ const parts = [bold(paint('accent', mode))];
441
+ if (status.model)
442
+ parts.push(bold(paint('ink', status.model)));
443
+ if (status.variant)
444
+ parts.push(paint('accent', `[${status.variant}]`));
445
+ const line = parts.join(dim(` ${GLYPHS.dot} `));
446
+ const trailing = [status.provider, status.tier].filter(Boolean).join(' ');
447
+ const base = trailing ? `${line} ${dim(trailing)}` : line;
448
+ const details = [];
449
+ if (this.queue.length)
450
+ details.push(`${this.queue.length} queued`);
451
+ if (this.editor.lines.length > 1)
452
+ details.push(`${this.editor.lines.length} lines`);
453
+ const extra = details.length ? dim(` ${GLYPHS.dot} ${details.join(' · ')}`) : '';
454
+ const withMeta = visibleWidth(base) + visibleWidth(extra) <= width ? base + extra : base;
455
+ const hints = dim(' Ctrl+G/⇧Tab permissions · Alt+M model · Ctrl+T variant');
456
+ const full = visibleWidth(withMeta) + visibleWidth(hints) <= width ? withMeta + hints : withMeta;
457
+ return visibleWidth(full) > width ? truncate(full, width, GLYPHS.ellipsis) : full;
458
+ }
459
+ planRows(width) {
460
+ if (this.surface && sidebarVisible(this.surface.width, false, this.surface.env))
461
+ return [];
462
+ const plan = this.renderer && Array.isArray(this.renderer.latestPlan) ? this.renderer.latestPlan : [];
463
+ if (plan.length === 0)
464
+ return [];
465
+ const completed = plan.filter(item => item.status === 'completed').length;
466
+ const stageMax = this.surface?.stage?.maxHeight || this.out?.rows || 24;
467
+ if (stageMax < 22) {
468
+ const activeStep = plan.find(item => item.status === 'in_progress') || plan.find(item => item.status !== 'completed') || plan[0];
469
+ const stepText = activeStep ? (activeStep.text || activeStep.step || '') : '';
470
+ const summary = `${paint('accent', GLYPHS.skill || '✦')} ${bold('plan')} ${dim(`(${completed}/${plan.length})`)} ${dim('·')} ${truncate(safeDisplay(stepText), Math.max(8, width - 24), GLYPHS.ellipsis)}`;
471
+ return [summary, ''];
472
+ }
473
+ const rows = [`${bold(paint('accent', 'implementation plan'))} ${dim(`${completed}/${plan.length}`)}`];
474
+ const limit = Math.min(plan.length, 5);
475
+ const active = plan.findIndex(item => item.status === 'in_progress');
476
+ const pending = plan.findIndex(item => item.status !== 'completed');
477
+ const focus = active >= 0 ? active : pending >= 0 ? pending : plan.length - 1;
478
+ const start = Math.max(0, Math.min(focus - 1, plan.length - limit));
479
+ if (start > 0)
480
+ rows.push(` ${dim(`${GLYPHS.ellipsis} ${start} earlier`)}`);
481
+ for (const item of plan.slice(start, start + limit)) {
482
+ const mark = item.status === 'completed'
483
+ ? paint('success', GLYPHS.check)
484
+ : item.status === 'in_progress'
485
+ ? paint('accent', GLYPHS.arrow)
486
+ : paint('muted', GLYPHS.dot);
487
+ rows.push(` ${mark} ${truncate(safeDisplay(item.text || item.step || ''), Math.max(8, width - 5), GLYPHS.ellipsis)}`);
488
+ }
489
+ const remaining = plan.length - start - limit;
490
+ if (remaining > 0)
491
+ rows.push(` ${dim(`${GLYPHS.ellipsis} ${remaining} later`)}`);
492
+ rows.push('');
493
+ return rows;
494
+ }
495
+ startTick() {
496
+ if (this.tickTimer)
497
+ return;
498
+ this.tickTimer = setInterval(() => {
499
+ this.tick++;
500
+ if (this.busy)
501
+ this.scheduleDraw();
502
+ if (this.busy && (this.usageCard || this.statusCard !== null) && this.tick % 32 === 0) {
503
+ this.refreshPinnedPanels();
504
+ }
505
+ }, 125);
506
+ if (this.tickTimer.unref)
507
+ this.tickTimer.unref();
508
+ }
509
+ stopTick() {
510
+ if (!this.tickTimer)
511
+ return;
512
+ clearInterval(this.tickTimer);
513
+ this.tickTimer = null;
514
+ }
515
+ openLayer(layer) {
516
+ this.closeLayer();
517
+ this.layer = layer;
518
+ if (this.surface?.stage)
519
+ this.surface.stage.invalidate();
520
+ this.draw();
521
+ return layer;
522
+ }
523
+ closeLayer() {
524
+ const layer = this.layer;
525
+ if (!layer)
526
+ return;
610
527
  this.layer = null;
611
- return onPick ? onPick(item) : null;
612
- }
613
- }));
614
- }
615
-
616
- /**
617
- * Put text on the input line, ready to be added to.
618
- *
619
- * Picking from the skill browser lands here: the command is written for you
620
- * and the caret sits after it, so the next thing you type is what you want
621
- * done. A picker that ran the skill on selection would give you no way to say
622
- * that.
623
- */
624
- setText(text) {
625
- this.editor.setText(String(text == null ? '' : text));
626
- this.completion = null;
627
- this.scheduleDraw();
628
- }
629
-
630
- /** Update active model and provider displayed in agentRow and status footer. */
631
- updateModel(provider, model) {
632
- if (this.renderer && this.renderer.status) {
633
- this.renderer.status.setSession({
634
- provider: provider ? String(provider) : '',
635
- model: model ? String(model) : ''
636
- });
637
- }
638
- this.scheduleDraw();
639
- }
640
-
641
- /**
642
- * Browse the compiled skill library.
643
- *
644
- * 100 skills cannot be a flat listing — that is what overflowed the terminal
645
- * at five. The picker is the same SelectLayer that already backs ctrl+p, so
646
- * fuzzy search, grouping and scrolling come for free, and every row is
647
- * truncated to the panel rather than to the terminal.
648
- */
649
- browseSkills(skills, onOpen) {
650
- if (!Array.isArray(skills) || skills.length === 0) {
651
- this.notice = 'no skills are compiled into this build';
652
- this.scheduleDraw();
653
- return;
654
- }
655
- this.openLayer(skillPicker(skills, (skill) => {
656
- this.layer = null;
657
- if (onOpen) onOpen(skill);
658
- }));
659
- }
660
-
661
- /** Show local command output inside the live region, never in chat scrollback. */
662
- showText(title, text, options = {}) {
663
- const panelWidth = dialogWidth(this.width(), options.width || 76);
664
- const contentWidth = Math.max(12, panelWidth - 4);
665
- let lines = wrapBlock(safeDisplay(String(text == null ? '' : text)), contentWidth, { hang: 0 });
666
- if (lines.length > 0 && lines[0].trim().toLowerCase() === String(title || '').trim().toLowerCase()) {
667
- lines = lines.slice(1);
668
- if (lines.length > 0 && /^[-─═_]+$/.test(lines[0].trim())) {
669
- lines = lines.slice(1);
670
- }
671
- }
672
- return this.openLayer(new TextLayer({
673
- title: String(title || 'Details'),
674
- lines: options.danger ? lines.map((line) => paint('danger', line)) : lines,
675
- width: panelWidth,
676
- height: options.height || 20
677
- }));
678
- }
679
-
680
- /** Usage and Status are non-modal panels: ordinary chat must not close them. */
681
- async toggleUsageCard(loop = null) {
682
- if (this.usageCard || this.usageCardLoading) {
683
- this.closeUsageCard();
684
- return false;
685
- }
686
- const version = ++this.infoPanelVersion;
687
- this.statusCard = null;
688
- this.statusCardUsage = null;
689
- this.usageCardLoading = true;
690
- try {
691
- const data = await collectUsageCardData(loop || this.messageActionLoop);
692
- if (version !== this.infoPanelVersion || !this.usageCardLoading) return false;
693
- this.usageCard = data;
694
- this.usageCardLoading = false;
695
- this.scheduleDraw();
696
- return true;
697
- } catch (error) {
698
- if (version === this.infoPanelVersion) {
699
- this.usageCardLoading = false;
700
- this.notice = this.sanitizeSingleLine(error instanceof Error ? error.message : String(error));
528
+ if (typeof layer.answer === 'function')
529
+ layer.answer(false);
530
+ if (this.surface?.stage)
531
+ this.surface.stage.invalidate();
532
+ this.draw();
533
+ }
534
+ openPalette() {
535
+ if (this.commands.length === 0) {
536
+ this.notice = 'no commands available';
537
+ return;
538
+ }
539
+ this.openLayer(commandPalette(this.commands, (command) => {
540
+ this.editor.setText(`/${command.name}`);
541
+ this.layer = null;
542
+ this.submit();
543
+ }));
544
+ }
545
+ openHome(items, onPick) {
546
+ if (!Array.isArray(items) || items.length === 0) {
547
+ this.notice = 'no actions available';
548
+ this.scheduleDraw();
549
+ return null;
550
+ }
551
+ return this.openLayer(new HomeLayer({
552
+ items,
553
+ onPick: (item) => {
554
+ this.layer = null;
555
+ return onPick ? onPick(item) : null;
556
+ }
557
+ }));
558
+ }
559
+ setText(text) {
560
+ this.editor.setText(String(text == null ? '' : text));
561
+ this.completion = null;
701
562
  this.scheduleDraw();
702
- }
703
- return false;
704
- }
705
- }
706
-
707
- showUsageCard(loop = null) {
708
- return this.toggleUsageCard(loop);
709
- }
710
-
711
- closeUsageCard() {
712
- if (!this.usageCard && !this.usageCardLoading) return false;
713
- ++this.infoPanelVersion; // Invalidate an in-flight open or refresh.
714
- this.usageCard = null;
715
- this.usageCardLoading = false;
716
- this.scheduleDraw();
717
- return true;
718
- }
719
-
720
- async refreshUsageCard(loop = null) {
721
- if (!this.usageCard || this.usageRefreshPending) return false;
722
- const version = this.infoPanelVersion;
723
- this.usageRefreshPending = true;
724
- try {
725
- const data = await collectUsageCardData(loop || this.messageActionLoop);
726
- if (version !== this.infoPanelVersion || !this.usageCard) return false;
727
- this.usageCard = data;
728
- this.scheduleDraw();
729
- return true;
730
- } catch {
731
- // A transient ledger read failure must not close an already visible panel.
732
- return false;
733
- } finally {
734
- this.usageRefreshPending = false;
735
- }
736
- }
737
-
738
- toggleStatusCard(loop = null) {
739
- if (this.statusCard !== null) {
740
- this.closeStatusCard();
741
- return false;
742
- }
743
- const targetLoop = loop || this.messageActionLoop;
744
- ++this.infoPanelVersion; // A pending usage read must not reopen a replaced panel.
745
- this.usageCard = null;
746
- this.usageCardLoading = false;
747
- this.statusCardUsage = null;
748
- this.statusCard = buildStatusText({ loop: targetLoop });
749
- this.scheduleDraw();
750
- void this.refreshStatusCardMeta(targetLoop);
751
- return true;
752
- }
753
-
754
- closeStatusCard() {
755
- if (this.statusCard === null) return false;
756
- ++this.infoPanelVersion;
757
- this.statusCard = null;
758
- this.statusCardUsage = null;
759
- this.scheduleDraw();
760
- return true;
761
- }
762
-
763
- async refreshStatusCardMeta(loop = null) {
764
- if (this.statusCard === null) return false;
765
- const version = this.infoPanelVersion;
766
- try {
767
- const data = await collectUsageCardData(loop || this.messageActionLoop);
768
- if (version !== this.infoPanelVersion || this.statusCard === null) return false;
769
- this.statusCardUsage = data;
770
- this.scheduleDraw();
771
- return true;
772
- } catch {
773
- return false;
774
- }
775
- }
776
-
777
- refreshPinnedPanels(loop = null) {
778
- const targetLoop = loop || this.messageActionLoop;
779
- if (this.usageCard) void this.refreshUsageCard(targetLoop);
780
- if (this.statusCard !== null) {
781
- this.statusCard = buildStatusText({ loop: targetLoop });
782
- this.scheduleDraw();
783
- void this.refreshStatusCardMeta(targetLoop);
784
- }
785
- }
786
-
787
- statusCardRows(width) {
788
- if (this.statusCard === null) return [];
789
- return renderStatusCardRows(this.statusCard, this.statusCardUsage, width);
790
- }
791
-
792
- /**
793
- * Ask for approval of a tool call: risk, arguments and a scrollable diff.
794
- *
795
- * Replaces an inquirer.prompt() that took stdin while this prompt was already
796
- * holding it in raw mode — the two contended, and the confirm could arrive on
797
- * top of a half-drawn prompt.
798
- */
799
- approve(request = {}) {
800
- return new Promise((resolve) => {
801
- // Only the curated verb — "run", "overwrite", "delete". The layer already
802
- // renders the arguments (or a diff) underneath, so passing a rendered
803
- // argument summary as `detail` printed the same line twice.
804
- const { verb } = describeTool(request.tool, request.args || {});
805
- // Resolve with WHICH option was chosen, not just yes/no: 'always' has to
806
- // reach the caller so it can record a standing approval. A bare boolean
807
- // would have silently downgraded it to 'once'.
808
- this.openLayer(new ApprovalLayer({
809
- request,
810
- verb,
811
- onAnswer: (approved, scope) => resolve({ approved, scope: scope || (approved ? 'once' : 'reject') })
812
- }));
813
- });
814
- }
815
-
816
- /** Ask for a durable implementation choice, with a free-form option. */
817
- decide(request = {}) {
818
- return new Promise((resolve) => {
819
- this.openLayer(new DecisionLayer({ request, onAnswer: resolve }));
820
- });
821
- }
822
-
823
- /** A plain yes/no, for the questions that are not tool approvals. */
824
- confirm(message, options = {}) {
825
- return new Promise((resolve) => {
826
- let settled = false;
827
- const settle = (answer) => { if (!settled) { settled = true; resolve(Boolean(answer)); } };
828
- const layer = new ConfirmLayer({
829
- message,
830
- defaultAnswer: options.defaultAnswer === true,
831
- onAnswer: settle
832
- });
833
- this.openLayer(layer);
834
- });
835
- }
836
-
837
- /**
838
- * Columns available on the stream this prompt actually writes to.
839
- *
840
- * draw() used to call the global terminalWidth(), which reads
841
- * process.stdout.columns. That is right in production — `out` IS stdout — but
842
- * it means the widget cannot be measured against anything else, and a panel
843
- * sized from the wrong width overflows and wraps, which corrupts erase()'s row
844
- * count and starts eating the conversation above.
845
- */
846
- width() {
847
- // The Stage keeps the composer at one readable measure through the session.
848
- if (this.surface && typeof this.surface.composeWidth === 'function') {
849
- const asked = this.surface.composeWidth();
850
- if (Number.isFinite(asked) && asked > 0) return Math.max(20, asked);
851
- }
852
-
853
- const columns = this.out && this.out.columns;
854
- // No ceiling. The prompt is chrome: the box, its fill and the footer are the
855
- // surface the user is typing into, and they follow the window. A clamp at
856
- // 120 left a stretched terminal two-thirds covered and one-third empty.
857
- return Number.isFinite(columns) && columns > 0
858
- ? Math.max(20, columns)
859
- : terminalWidth();
860
- }
861
-
862
- scheduleDraw() {
863
- if (this.redrawScheduled || !this.active) return;
864
- this.redrawScheduled = true;
865
- setImmediate(() => {
866
- this.redrawScheduled = false;
867
- this.draw();
868
- });
869
- }
870
-
871
- // -------------------------------------------------------------------------
872
- // Reading
873
- // -------------------------------------------------------------------------
874
-
875
- /**
876
- * Render submitted user message into the chat transcript.
877
- */
878
- renderSubmittedUserMessage(text) {
879
- if (this.surface?.homeInfo) this.surface.leaveHome();
880
- if (this.renderer?.renderUserMessage) this.renderer.renderUserMessage(text);
881
- else this.commit('user', (width) => {
882
- const blockWidth = Math.max(8, width);
883
- return barBlock(
884
- wrapBlock(safeDisplay(text), Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - GUTTER), { hang: 0 }),
885
- { width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' }
886
- );
887
- });
888
- }
889
-
890
- /** Restore attachments if an earlier submission was handled as a local command. */
891
- restoreUnconsumedAttachments() {
892
- if (Array.isArray(this.currentSubmissionAttachments) && this.currentSubmissionAttachments.length) {
893
- this.pendingAttachments = this.currentSubmissionAttachments.concat(this.pendingAttachments);
894
- }
895
- this.currentSubmissionAttachments = null;
896
- }
897
-
898
- takeSubmissionAttachments() {
899
- const attachments = Array.isArray(this.pendingAttachments) ? this.pendingAttachments : [];
900
- this.pendingAttachments = [];
901
- return attachments;
902
- }
903
-
904
- /** Queue text with its attachments. Local command values retain their existing type. */
905
- enqueueSubmission(text, { rendered = false } = {}) {
906
- if (!Array.isArray(this.queue)) this.queue = [];
907
- if (this.isCommand(text)) {
908
- this.queue.push(text);
909
- } else {
910
- this.queue.push({ kind: 'chat-submission', text, attachments: this.takeSubmissionAttachments(), rendered });
911
- }
912
- }
913
-
914
- /** Read in FIFO order and display a submitted message only once dispatched. */
915
- read() {
916
- this.restoreUnconsumedAttachments();
917
- if (this.queue.length > 0) {
918
- const entry = this.queue.shift();
919
- const submission = entry && typeof entry === 'object' && entry.kind === 'chat-submission';
920
- const text = submission ? entry.text : entry;
921
- if (submission) this.currentSubmissionAttachments = entry.attachments;
922
- if (typeof text === 'string' && !this.isCommand(text) && !(submission && entry.rendered)) {
923
- this.renderSubmittedUserMessage(text);
924
- }
925
- this.scheduleDraw();
926
- return Promise.resolve(text);
927
- }
928
- return new Promise((resolve) => { this.waiter = resolve; });
929
- }
930
-
931
- /**
932
- * Resolve a pending read() with a value nobody typed.
933
- *
934
- * The home menu needs this: picking an action must satisfy the same read()
935
- * the keyboard would have satisfied, or the caller sits waiting for a line
936
- * that is never coming. It deliberately does NOT echo, add to history or
937
- * touch the editor — an action is not a message, and showing `start` in the
938
- * transcript as though the user had said it would be a lie about what
939
- * happened. If no read is outstanding the value queues, exactly as a typed
940
- * line would while a turn is running.
941
- */
942
- deliver(value) {
943
- if (this.waiter) {
944
- const resolve = this.waiter;
945
- this.waiter = null;
946
- resolve(value);
947
- return true;
948
- }
949
- this.queue.push(value);
950
- return false;
951
- }
952
-
953
- /**
954
- * Consume and return any pending multimodal attachments (e.g. pasted screenshots).
955
- */
956
- consumeAttachments() {
957
- // An empty submission snapshot still takes precedence over a future draft.
958
- if (this.currentSubmissionAttachments !== null) {
959
- const attachments = this.currentSubmissionAttachments;
960
- this.currentSubmissionAttachments = null;
961
- return Array.isArray(attachments) ? attachments : [];
962
- }
963
- return this.takeSubmissionAttachments();
964
- }
965
-
966
- /**
967
- * Paste clipboard content: seamlessly supports text and screenshot images.
968
- */
969
- pasteClipboard() {
970
- pasteIntoChatbox(this);
971
- }
972
-
973
- setBusy(busy) {
974
- this.busy = busy;
975
- resetTurnInterruptState(this, busy);
976
- if (busy) this.startTick(); else this.stopTick();
977
- if (!busy && this.usageCard) void this.refreshUsageCard();
978
- if (this.statusCard !== null) {
979
- this.statusCard = buildStatusText({ loop: this.messageActionLoop });
980
- if (!busy) void this.refreshStatusCardMeta(this.messageActionLoop);
981
- }
982
- if (this.surface?.stage) this.surface.stage.invalidate();
983
- this.draw();
984
- }
985
-
986
- submit() {
987
- const text = this.editor.getText();
988
- if (!text.trim()) return;
989
- if (!Array.isArray(this.queue)) this.queue = [];
990
- // busy=false does not imply read() is awaiting: command dispatch has gaps.
991
- if ((this.busy || !this.waiter) && this.queue.length >= 32
992
- && !/^\/(?:stop|interrupt)$/i.test(text.trim())) {
993
- this.notice = '32 queued messages: wait for a turn to complete before adding another';
994
- this.scheduleDraw();
995
- return;
996
- }
997
-
998
- this.erase();
999
- this.history.add(text);
1000
- this.editor.clear();
1001
- this.completion = null;
1002
- // Do not dismiss a pinned information panel on any chat submission,
1003
- // queued prompt, or agent run. Only Esc or the same command closes it.
1004
- // Instant slash command shortcuts that operate directly on the prompt surface
1005
- if ((text.trim().toLowerCase() === '/usage' || text.trim().toLowerCase() === '/cost')
1006
- && typeof this.toggleUsageCard === 'function') {
1007
- void this.toggleUsageCard();
1008
- return;
1009
- }
1010
- if (text.trim().toLowerCase() === '/status' && typeof this.toggleStatusCard === 'function') {
1011
- this.toggleStatusCard();
1012
- return;
1013
- }
1014
-
1015
- if (text === '/observer' || text === '/observer status') {
1016
- import('./observerPicker.js').then(({ runInteractiveObserverPicker }) => {
1017
- void runInteractiveObserverPicker(this);
1018
- }).catch((err) => {
1019
- this.notice = err instanceof Error ? err.message : String(err);
563
+ }
564
+ updateModel(provider, model, variant) {
565
+ const nextProvider = provider ? String(provider) : '';
566
+ const nextModel = model ? String(model) : '';
567
+ const sessionUpdate = {
568
+ provider: nextProvider,
569
+ model: nextModel
570
+ };
571
+ if (variant !== undefined) {
572
+ sessionUpdate.variant = variant ? String(variant) : '';
573
+ }
574
+ if (this.renderer && this.renderer.status) {
575
+ this.renderer.status.setSession(sessionUpdate);
576
+ }
577
+ if (this.surface && typeof this.surface.setSessionInfo === 'function') {
578
+ this.surface.setSessionInfo(sessionUpdate);
579
+ }
1020
580
  this.scheduleDraw();
1021
- });
1022
- return;
1023
- }
1024
-
1025
- // Control commands take priority over busy turns so the user is never locked out.
1026
- // Commands like /stop, /new, /model, /session, /sessions, /continuum, /clear can interrupt
1027
- // a stalled/long-running turn and execute immediately.
1028
- // Match a COMPLETE command token. Prefix tests made unrelated
1029
- // commands such as /newsletter interrupt an active agent turn.
1030
- const commandToken = text.trim().split(/\s+/, 1)[0].toLowerCase();
1031
- const isControlCommand = this.isCommand(text) && new Set([
1032
- '/stop', '/interrupt', '/new', '/model', '/models',
1033
- '/session', '/sessions', '/continuum', '/clear'
1034
- ]).has(commandToken);
1035
-
1036
- // Immediate abort signals interrupt the running turn directly without queuing as a future task.
1037
- if ((text === '/stop' || text === '/interrupt') && this.busy) {
1038
- this.interrupt();
1039
- this.notice = 'Interrupted';
1040
- this.scheduleDraw();
1041
- return;
1042
- }
1043
-
1044
- if (isControlCommand && this.busy) {
1045
- this.interrupt();
1046
- }
1047
-
1048
- if (this.busy) {
1049
- // If user typed another slash command while busy, notify them rather than queuing
1050
- // it as a chat prompt to the model.
1051
- if (this.isCommand(text)) {
1052
- this.notice = `Command ${text} queued — will execute when current turn completes`;
1053
- } else {
1054
- this.notice = `queued (${this.queue.length + 1}) — sends when this turn ends`;
1055
- }
1056
- this.enqueueSubmission(text);
1057
- this.scheduleDraw();
1058
- return;
1059
- }
1060
-
1061
- // A command is control input, not conversation. Its handler decides whether
1062
- // to open a picker, show a text dialog, or perform an action. Keeping the
1063
- // invocation out of the transcript preserves the boundary between local UI
1064
- // and messages that were actually sent to the model.
1065
- if (this.isCommand(text)) {
1066
- const settle = this.waiter;
1067
- this.waiter = null;
1068
- if (settle) settle(text);
1069
- else {
1070
- this.enqueueSubmission(text); // no waiter yet: retain the command
1071
- this.notice = `queued (${this.queue.length}) — sends when ready`;
1072
- this.scheduleDraw?.();
1073
- }
1074
- return;
1075
- }
1076
-
1077
- const resolve = this.waiter;
1078
- this.waiter = null;
1079
- if (resolve) {
1080
- this.restoreUnconsumedAttachments();
1081
- this.currentSubmissionAttachments = this.takeSubmissionAttachments();
1082
- this.renderSubmittedUserMessage(text);
1083
- resolve(text);
1084
- } else {
1085
- // Display the user's submitted message immediately, as before, but
1086
- // retain it until the CLI registers its next read() waiter.
1087
- // The rendered marker prevents a duplicate transcript entry at dequeue.
1088
- this.renderSubmittedUserMessage(text);
1089
- this.enqueueSubmission(text, { rendered: true });
1090
- this.notice = `queued (${this.queue.length}) — sends when ready`;
1091
- this.scheduleDraw?.();
1092
- }
1093
- }
1094
-
1095
- // -------------------------------------------------------------------------
1096
- // Keys
1097
- // -------------------------------------------------------------------------
1098
-
1099
- handleKey(key) {
1100
- const clearNotice = key.name === 'char' || key.name === 'paste' || key.name === 'backspace' || key.name === 'delete';
1101
- if (clearNotice && this.notice && !this.layer) {
1102
- this.notice = '';
1103
- }
1104
-
1105
- // The wheel was handed to the terminal at the top of the band; the moment
1106
- // the user types again they are driving this prompt, so take it back.
1107
- if (key.name !== 'wheel' && key.name !== 'mouse') {
1108
- this.prepareKeyboardState(false);
1109
- }
1110
-
1111
- if (key.ctrl && key.name === 'c') {
1112
- if (this.layer) { this.closeLayer(); return; }
1113
- if (this.editor.hasSelection) {
1114
- const text = this.editor.getSelectedText();
1115
- writeClipboardSync(text);
1116
- this.editor.killRing = text;
1117
- this.notice = `copied selection (${text.length} chars) to clipboard`;
581
+ }
582
+ browseSkills(skills, onOpen) {
583
+ if (!Array.isArray(skills) || skills.length === 0) {
584
+ this.notice = 'no skills are compiled into this build';
585
+ this.scheduleDraw();
586
+ return;
587
+ }
588
+ this.openLayer(skillPicker(skills, (skill) => {
589
+ this.layer = null;
590
+ if (onOpen)
591
+ onOpen(skill);
592
+ }));
593
+ }
594
+ showText(title, text, options = {}) {
595
+ const opts = options && typeof options === 'object' ? options : {};
596
+ const panelWidth = dialogWidth(this.width(), opts.width || 76);
597
+ const contentWidth = Math.max(12, panelWidth - 4);
598
+ let lines = wrapBlock(safeDisplay(String(text == null ? '' : text)), contentWidth, { hang: 0 });
599
+ if (lines.length > 0 && (lines[0] ?? '').trim().toLowerCase() === String(title || '').trim().toLowerCase()) {
600
+ lines = lines.slice(1);
601
+ if (lines.length > 0 && /^[-─═_]+$/.test((lines[0] ?? '').trim())) {
602
+ lines = lines.slice(1);
603
+ }
604
+ }
605
+ return this.openLayer(new TextLayer({
606
+ title: String(title || 'Details'),
607
+ lines: opts.danger ? lines.map((line) => paint('danger', line)) : lines,
608
+ width: panelWidth,
609
+ height: opts.height || 20
610
+ }));
611
+ }
612
+ async toggleUsageCard(loop = null) {
613
+ if (this.usageCard || this.usageCardLoading) {
614
+ this.closeUsageCard();
615
+ return false;
616
+ }
617
+ const version = ++this.infoPanelVersion;
618
+ this.statusCard = null;
619
+ this.statusCardUsage = null;
620
+ this.usageCardLoading = true;
621
+ try {
622
+ const data = await collectUsageCardData(loop || this.messageActionLoop);
623
+ if (version !== this.infoPanelVersion || !this.usageCardLoading)
624
+ return false;
625
+ this.usageCard = data;
626
+ this.usageCardLoading = false;
627
+ this.scheduleDraw();
628
+ return true;
629
+ }
630
+ catch (error) {
631
+ if (version === this.infoPanelVersion) {
632
+ this.usageCardLoading = false;
633
+ this.notice = this.sanitizeSingleLine(error instanceof Error ? error.message : String(error));
634
+ this.scheduleDraw();
635
+ }
636
+ return false;
637
+ }
638
+ }
639
+ showUsageCard(loop = null) {
640
+ return this.toggleUsageCard(loop);
641
+ }
642
+ closeUsageCard() {
643
+ if (!this.usageCard && !this.usageCardLoading)
644
+ return false;
645
+ ++this.infoPanelVersion;
646
+ this.usageCard = null;
647
+ this.usageCardLoading = false;
1118
648
  this.scheduleDraw();
1119
- return;
1120
- }
1121
- return this.handleCtrlC();
1122
- }
1123
- if (key.ctrl && key.name === 'd' && this.editor.isEmpty) return this.onExit();
1124
-
1125
- // A dialog owns the keyboard while it is up — the editor must not also see
1126
- // the keystroke, or typing a filter would edit the message behind it.
1127
- // This MUST route before any default key handling (like paste) so modal
1128
- // dialogs (e.g. InputLayer for API keys) receive bracketed paste events.
1129
- if (this.layer) {
1130
- const previousSelection = this.layer.messageActions ? this.layer.list?.selected : null;
1131
- const action = key.name === 'mouse' && this.layer.messageActions
1132
- ? handleMessageActionMenuMouse(this.layer, key)
1133
- : this.layer.key(key);
1134
- if (this.layer?.messageActions && isMouseMotion(key.sequence)
1135
- && previousSelection !== this.layer.list?.selected) this.scheduleDraw();
1136
- if (action === 'close') { this.closeLayer(); return; }
1137
- // A layer may hand a key BACK rather than swallow it. The home menu does
1138
- // this for every printable character, so `↑↓` picks an action while typing
1139
- // goes to the input line in the same frame: 'dismiss' closes the menu and
1140
- // lets the key through, 'passthrough' leaves the menu up and lets it
1141
- // through. Silence still means "mine, ignored", so every other layer stays
1142
- // strictly modal — a dialog that leaks keys is the bug Layer exists to
1143
- // prevent, and only a layer that opts in by name can do it.
1144
- if (action === 'dismiss') this.closeLayer();
1145
- else if (action !== 'passthrough') return;
1146
- }
1147
-
1148
- if (key.name === 'paste-too-large') {
1149
- this.notice = 'Paste exceeds 2 MiB; input unchanged. Attach a file or reduce the selection.';
1150
- this.scheduleDraw();
1151
- return;
1152
- }
1153
-
1154
- if (key.name === 'paste') {
1155
- if (this.surface && typeof this.surface.captureMouse === 'function') {
1156
- this.surface.captureMouse();
1157
- }
1158
- pasteIntoChatbox(this, key.text);
1159
- return;
1160
- }
1161
-
1162
- if (this.completion && this.handleCompletionKey(key)) return;
1163
- if (this.handleScrollKey(key)) return;
1164
-
1165
- const isModeControl = Boolean(key.ctrl && key.name === 'g');
1166
- const control = isModeControl ? this.onOpenMode
1167
- : key.alt && key.name === 'm' ? this.onOpenModel
1168
- : key.ctrl && key.name === 't' ? this.onOpenVariant : null;
1169
- if (control) {
1170
- if (this.busy && !isModeControl) {
1171
- this.notice = 'Finish or interrupt the current turn before switching controls';
649
+ return true;
650
+ }
651
+ async refreshUsageCard(loop = null) {
652
+ if (!this.usageCard || this.usageRefreshPending)
653
+ return false;
654
+ const version = this.infoPanelVersion;
655
+ this.usageRefreshPending = true;
656
+ try {
657
+ const data = await collectUsageCardData(loop || this.messageActionLoop);
658
+ if (version !== this.infoPanelVersion || !this.usageCard)
659
+ return false;
660
+ this.usageCard = data;
661
+ this.scheduleDraw();
662
+ return true;
663
+ }
664
+ catch {
665
+ return false;
666
+ }
667
+ finally {
668
+ this.usageRefreshPending = false;
669
+ }
670
+ }
671
+ toggleStatusCard(loop = null) {
672
+ if (this.statusCard !== null) {
673
+ this.closeStatusCard();
674
+ return false;
675
+ }
676
+ const targetLoop = loop || this.messageActionLoop;
677
+ ++this.infoPanelVersion;
678
+ this.usageCard = null;
679
+ this.usageCardLoading = false;
680
+ this.statusCardUsage = null;
681
+ this.statusCard = buildStatusText({ loop: targetLoop });
682
+ this.scheduleDraw();
683
+ void this.refreshStatusCardMeta(targetLoop);
684
+ return true;
685
+ }
686
+ closeStatusCard() {
687
+ if (this.statusCard === null)
688
+ return false;
689
+ ++this.infoPanelVersion;
690
+ this.statusCard = null;
691
+ this.statusCardUsage = null;
1172
692
  this.scheduleDraw();
1173
- } else {
1174
- Promise.resolve(control()).catch(error => {
1175
- this.notice = this.sanitizeSingleLine(error instanceof Error ? error.message : String(error));
1176
- this.scheduleDraw();
693
+ return true;
694
+ }
695
+ async refreshStatusCardMeta(loop = null) {
696
+ if (this.statusCard === null)
697
+ return false;
698
+ const version = this.infoPanelVersion;
699
+ try {
700
+ const data = await collectUsageCardData(loop || this.messageActionLoop);
701
+ if (version !== this.infoPanelVersion || this.statusCard === null)
702
+ return false;
703
+ this.statusCardUsage = data;
704
+ this.scheduleDraw();
705
+ return true;
706
+ }
707
+ catch {
708
+ return false;
709
+ }
710
+ }
711
+ refreshPinnedPanels(loop = null) {
712
+ const targetLoop = loop || this.messageActionLoop;
713
+ if (this.usageCard)
714
+ void this.refreshUsageCard(targetLoop);
715
+ if (this.statusCard !== null) {
716
+ this.statusCard = buildStatusText({ loop: targetLoop });
717
+ this.scheduleDraw();
718
+ void this.refreshStatusCardMeta(targetLoop);
719
+ }
720
+ }
721
+ statusCardRows(width) {
722
+ if (this.statusCard === null)
723
+ return [];
724
+ return renderStatusCardRows(this.statusCard, this.statusCardUsage, width);
725
+ }
726
+ approve(request = {}) {
727
+ return new Promise((resolve) => {
728
+ const { verb } = describeTool(request.tool, request.args || {});
729
+ this.openLayer(new ApprovalLayer({
730
+ request,
731
+ verb,
732
+ onAnswer: (approved, scope) => resolve({ approved, scope: scope || (approved ? 'once' : 'reject') })
733
+ }));
734
+ });
735
+ }
736
+ decide(request = {}) {
737
+ return new Promise((resolve) => {
738
+ this.openLayer(new DecisionLayer({ request, onAnswer: resolve }));
739
+ });
740
+ }
741
+ confirm(message, options = {}) {
742
+ const opts = options && typeof options === 'object' ? options : {};
743
+ return new Promise((resolve) => {
744
+ let settled = false;
745
+ const settle = (answer) => { if (!settled) {
746
+ settled = true;
747
+ resolve(Boolean(answer));
748
+ } };
749
+ const layer = new ConfirmLayer({
750
+ message,
751
+ defaultAnswer: opts.defaultAnswer === true,
752
+ onAnswer: settle
753
+ });
754
+ this.openLayer(layer);
1177
755
  });
1178
- }
1179
- return;
1180
- }
1181
-
1182
- switch (key.name) {
1183
- case 'escape': return this.handleEscape();
1184
- case 'enter':
1185
- if (key.alt || key.shift) { this.editor.newline(); return this.refreshCompletion(); }
1186
- return this.submit();
1187
- case 'tab':
1188
- if (key.shift) return;
1189
- return this.openCompletion(true);
1190
- case 'backspace':
1191
- if (key.alt) this.editor.killWordLeft(); else this.editor.backspace();
1192
- return this.refreshCompletion();
1193
- case 'delete': this.editor.deleteForward(); return this.refreshCompletion();
1194
- case 'left': return (key.ctrl || key.alt) ? this.editor.moveWordLeft(Boolean(key.shift)) : this.editor.moveLeft(Boolean(key.shift));
1195
- case 'right': return (key.ctrl || key.alt) ? this.editor.moveWordRight(Boolean(key.shift)) : this.editor.moveRight(Boolean(key.shift));
1196
- case 'home': return this.editor.moveHome(Boolean(key.shift));
1197
- case 'end': return this.editor.moveEnd(Boolean(key.shift));
1198
- case 'up':
1199
- if (key.shift) return this.editor.moveUp(true);
1200
- return this.historyOrMove(-1);
1201
- case 'down':
1202
- if (key.shift) return this.editor.moveDown(true);
1203
- return this.historyOrMove(1);
1204
- case 'pageup':
1205
- if (key.shift) { this.editor.moveHome(true); this.editor.line = 0; return; }
1206
- break;
1207
- case 'pagedown':
1208
- if (key.shift) { this.editor.moveEnd(true); this.editor.line = this.editor.lines.length - 1; return; }
1209
- break;
1210
- case 'char': this.editor.insert(key.text); return this.refreshCompletion();
1211
- default: break;
1212
- }
1213
-
1214
- if (key.ctrl) {
1215
- switch (key.name) {
1216
- case 'a': return this.editor.moveHome();
1217
- case 'e': return this.editor.moveEnd();
1218
- case 'k': this.editor.killToEnd(); return this.refreshCompletion();
1219
- case 'u': this.editor.killToStart(); return this.refreshCompletion();
1220
- case 'w': this.editor.killWordLeft(); return this.refreshCompletion();
1221
- case 'y': this.editor.yank(); return this.refreshCompletion();
1222
- case 'x': {
1223
- if (this.cutSelection()) return;
1224
- break;
1225
- }
1226
- case 'p': return this.openPalette();
1227
- case 'l': return this.clearScreen();
1228
- case 'o': return this.expand();
1229
- case 'v': return this.pasteClipboard();
1230
- default: break;
1231
- }
1232
- }
1233
- if (key.alt && key.name === 'a') {
1234
- this.editor.selectAll();
1235
- this.notice = 'selected all input text';
1236
- this.scheduleDraw();
1237
- return;
1238
- }
1239
- if (key.alt && key.name === 'x') {
1240
- if (this.cutSelection()) return;
1241
- }
1242
- if (key.alt && (key.name === 'c' || key.name === 'w')) {
1243
- const text = this.editor.hasSelection
1244
- ? this.editor.getSelectedText()
1245
- : this.editor.getText();
1246
- if (text) {
756
+ }
757
+ width() {
758
+ if (this.surface && typeof this.surface.composeWidth === 'function') {
759
+ const asked = this.surface.composeWidth();
760
+ if (Number.isFinite(asked) && asked > 0)
761
+ return Math.max(20, asked);
762
+ }
763
+ const columns = this.out && this.out.columns;
764
+ return Number.isFinite(columns) && columns > 0
765
+ ? Math.max(20, columns)
766
+ : terminalWidth();
767
+ }
768
+ scheduleDraw() {
769
+ if (this.redrawScheduled || !this.active)
770
+ return;
771
+ this.redrawScheduled = true;
772
+ setImmediate(() => {
773
+ this.redrawScheduled = false;
774
+ this.draw();
775
+ });
776
+ }
777
+ renderSubmittedUserMessage(text) {
778
+ if (this.surface?.homeInfo)
779
+ this.surface.leaveHome();
780
+ if (this.renderer?.renderUserMessage)
781
+ this.renderer.renderUserMessage(text);
782
+ else
783
+ this.commit('user', (width) => {
784
+ const blockWidth = Math.max(8, width);
785
+ return barBlock(wrapBlock(safeDisplay(text), Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - GUTTER), { hang: 0 }), { width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' });
786
+ });
787
+ }
788
+ restoreUnconsumedAttachments() {
789
+ if (Array.isArray(this.currentSubmissionAttachments) && this.currentSubmissionAttachments.length) {
790
+ this.pendingAttachments = this.currentSubmissionAttachments.concat(this.pendingAttachments);
791
+ }
792
+ this.currentSubmissionAttachments = null;
793
+ }
794
+ takeSubmissionAttachments() {
795
+ const attachments = Array.isArray(this.pendingAttachments) ? this.pendingAttachments : [];
796
+ this.pendingAttachments = [];
797
+ return attachments;
798
+ }
799
+ enqueueSubmission(text, { rendered = false } = {}) {
800
+ if (!Array.isArray(this.queue))
801
+ this.queue = [];
802
+ if (this.isCommand(text)) {
803
+ this.queue.push(text);
804
+ }
805
+ else {
806
+ this.queue.push({ kind: 'chat-submission', text, attachments: this.takeSubmissionAttachments(), rendered });
807
+ }
808
+ }
809
+ read() {
810
+ this.restoreUnconsumedAttachments();
811
+ if (this.queue.length > 0) {
812
+ const entry = this.queue.shift();
813
+ const submission = Boolean(entry && typeof entry === 'object' && entry.kind === 'chat-submission');
814
+ const text = submission ? entry.text : entry;
815
+ if (submission)
816
+ this.currentSubmissionAttachments = entry.attachments;
817
+ if (typeof text === 'string' && !this.isCommand(text) && !(submission && entry.rendered)) {
818
+ this.renderSubmittedUserMessage(text);
819
+ }
820
+ this.scheduleDraw();
821
+ return Promise.resolve(text);
822
+ }
823
+ return new Promise((resolve) => { this.waiter = resolve; });
824
+ }
825
+ deliver(value) {
826
+ if (this.waiter) {
827
+ const resolve = this.waiter;
828
+ this.waiter = null;
829
+ resolve(value);
830
+ return true;
831
+ }
832
+ this.queue.push(value);
833
+ return false;
834
+ }
835
+ consumeAttachments() {
836
+ if (this.currentSubmissionAttachments !== null) {
837
+ const attachments = this.currentSubmissionAttachments;
838
+ this.currentSubmissionAttachments = null;
839
+ return Array.isArray(attachments) ? attachments : [];
840
+ }
841
+ return this.takeSubmissionAttachments();
842
+ }
843
+ pasteClipboard() {
844
+ pasteIntoChatbox(this);
845
+ }
846
+ setBusy(busy) {
847
+ this.busy = busy;
848
+ resetTurnInterruptState(this, busy);
849
+ if (busy)
850
+ this.startTick();
851
+ else
852
+ this.stopTick();
853
+ if (!busy && this.usageCard)
854
+ void this.refreshUsageCard();
855
+ if (this.statusCard !== null) {
856
+ this.statusCard = buildStatusText({ loop: this.messageActionLoop });
857
+ if (!busy)
858
+ void this.refreshStatusCardMeta(this.messageActionLoop);
859
+ }
860
+ if (this.surface?.stage)
861
+ this.surface.stage.invalidate();
862
+ this.draw();
863
+ }
864
+ submit() {
865
+ const text = this.editor.getText();
866
+ if (!text.trim())
867
+ return;
868
+ if (!Array.isArray(this.queue))
869
+ this.queue = [];
870
+ if ((this.busy || !this.waiter) && this.queue.length >= 32
871
+ && !/^\/(?:stop|interrupt)$/i.test(text.trim())) {
872
+ this.notice = '32 queued messages: wait for a turn to complete before adding another';
873
+ this.scheduleDraw();
874
+ return;
875
+ }
876
+ this.erase();
877
+ this.history.add(text);
878
+ this.editor.clear();
879
+ this.completion = null;
880
+ const trimmedLower = text.trim().toLowerCase();
881
+ if ((trimmedLower === '/usage' || trimmedLower === '/cost')
882
+ && typeof this.toggleUsageCard === 'function') {
883
+ void this.toggleUsageCard();
884
+ return;
885
+ }
886
+ if (trimmedLower === '/status' && typeof this.toggleStatusCard === 'function') {
887
+ this.toggleStatusCard();
888
+ return;
889
+ }
890
+ if (trimmedLower === '/observer' || trimmedLower === '/observer status') {
891
+ import('./observerPicker.js').then(({ runInteractiveObserverPicker }) => {
892
+ void runInteractiveObserverPicker(this);
893
+ }).catch((err) => {
894
+ this.notice = this.sanitizeSingleLine(err instanceof Error ? err.message : String(err));
895
+ this.scheduleDraw();
896
+ });
897
+ return;
898
+ }
899
+ const commandToken = (trimmedLower.split(/\s+/, 1)[0] ?? '').toLowerCase();
900
+ const isControlCommand = this.isCommand(text) && new Set([
901
+ '/stop', '/interrupt', '/new', '/model', '/models',
902
+ '/variant', '/effort', '/reasoning', '/cortex',
903
+ '/gui', '/web', '/studio', '/game',
904
+ '/session', '/sessions', '/continuum', '/clear'
905
+ ]).has(commandToken);
906
+ if ((trimmedLower === '/stop' || trimmedLower === '/interrupt') && this.busy) {
907
+ this.interrupt();
908
+ this.notice = 'Interrupted';
909
+ this.scheduleDraw();
910
+ return;
911
+ }
912
+ if (isControlCommand && this.busy) {
913
+ this.interrupt();
914
+ }
915
+ if (this.busy) {
916
+ if (this.isCommand(text)) {
917
+ this.notice = `Command ${this.sanitizeSingleLine(text)} queued — will execute when current turn completes`;
918
+ }
919
+ else {
920
+ this.notice = `queued (${this.queue.length + 1}) — sends when this turn ends`;
921
+ }
922
+ this.enqueueSubmission(text);
923
+ this.scheduleDraw();
924
+ return;
925
+ }
926
+ if (this.isCommand(text)) {
927
+ const settle = this.waiter;
928
+ this.waiter = null;
929
+ if (settle)
930
+ settle(text);
931
+ else {
932
+ this.enqueueSubmission(text);
933
+ this.notice = `queued (${this.queue.length}) — sends when ready`;
934
+ this.scheduleDraw?.();
935
+ }
936
+ return;
937
+ }
938
+ const resolve = this.waiter;
939
+ this.waiter = null;
940
+ if (resolve) {
941
+ this.restoreUnconsumedAttachments();
942
+ this.currentSubmissionAttachments = this.takeSubmissionAttachments();
943
+ this.renderSubmittedUserMessage(text);
944
+ resolve(text);
945
+ }
946
+ else {
947
+ this.renderSubmittedUserMessage(text);
948
+ this.enqueueSubmission(text, { rendered: true });
949
+ this.notice = `queued (${this.queue.length}) — sends when ready`;
950
+ this.scheduleDraw?.();
951
+ }
952
+ }
953
+ // -------------------------------------------------------------------------
954
+ // Keys
955
+ // -------------------------------------------------------------------------
956
+ handleKey(key) {
957
+ const clearNotice = key.name === 'char' || key.name === 'paste' || key.name === 'backspace' || key.name === 'delete';
958
+ if (clearNotice && this.notice && !this.layer) {
959
+ this.notice = '';
960
+ }
961
+ if (key.name !== 'wheel' && key.name !== 'mouse') {
962
+ this.prepareKeyboardState(false);
963
+ }
964
+ if (key.ctrl && key.name === 'c') {
965
+ if (this.layer) {
966
+ this.closeLayer();
967
+ return;
968
+ }
969
+ if (this.editor.hasSelection) {
970
+ const text = this.editor.getSelectedText();
971
+ try {
972
+ writeClipboardSync(text);
973
+ }
974
+ catch { /* clipboard unavailable */ }
975
+ this.editor.killRing = text;
976
+ this.notice = `copied selection (${text.length} chars) to clipboard`;
977
+ this.scheduleDraw();
978
+ return;
979
+ }
980
+ return this.handleCtrlC();
981
+ }
982
+ if (key.ctrl && key.name === 'd' && this.editor.isEmpty)
983
+ return this.onExit();
984
+ if (this.layer) {
985
+ const previousSelection = this.layer.messageActions ? this.layer.list?.selected : null;
986
+ const action = key.name === 'mouse' && this.layer.messageActions
987
+ ? handleMessageActionMenuMouse(this.layer, key)
988
+ : this.layer.key(key);
989
+ if (this.layer?.messageActions && isMouseMotion(key.sequence)
990
+ && previousSelection !== this.layer.list?.selected)
991
+ this.scheduleDraw();
992
+ if (action === 'close') {
993
+ this.closeLayer();
994
+ return;
995
+ }
996
+ if (action === 'dismiss')
997
+ this.closeLayer();
998
+ else if (action !== 'passthrough')
999
+ return;
1000
+ }
1001
+ if (key.name === 'paste-too-large') {
1002
+ this.notice = 'Paste exceeds 2 MiB; input unchanged. Attach a file or reduce the selection.';
1003
+ this.scheduleDraw();
1004
+ return;
1005
+ }
1006
+ if (key.name === 'paste') {
1007
+ if (this.surface && typeof this.surface.captureMouse === 'function') {
1008
+ this.surface.captureMouse();
1009
+ }
1010
+ pasteIntoChatbox(this, key.text);
1011
+ return;
1012
+ }
1013
+ if (this.completion && this.handleCompletionKey(key))
1014
+ return;
1015
+ if (this.handleScrollKey(key))
1016
+ return;
1017
+ const isModeControl = Boolean((key.ctrl && key.name === 'g') || (key.shift && key.name === 'tab' && this.onCycleMode));
1018
+ const control = (key.ctrl && key.name === 'g') ? this.onOpenMode
1019
+ : (key.shift && key.name === 'tab' && this.onCycleMode) ? this.onCycleMode
1020
+ : key.alt && key.name === 'm' ? this.onOpenModel
1021
+ : key.ctrl && key.name === 't' ? this.onOpenVariant
1022
+ : key.alt && key.name === 't' ? (this.onOpenVariantList || this.onOpenVariant) : null;
1023
+ if (control) {
1024
+ if (this.busy && !isModeControl) {
1025
+ this.notice = 'Finish or interrupt the current turn before switching controls';
1026
+ this.scheduleDraw();
1027
+ }
1028
+ else {
1029
+ Promise.resolve(control()).catch((error) => {
1030
+ this.notice = this.sanitizeSingleLine(error instanceof Error ? error.message : String(error));
1031
+ this.scheduleDraw();
1032
+ });
1033
+ }
1034
+ return;
1035
+ }
1036
+ switch (key.name) {
1037
+ case 'escape': return this.handleEscape();
1038
+ case 'enter':
1039
+ if (key.alt || key.shift) {
1040
+ this.editor.newline();
1041
+ return this.refreshCompletion();
1042
+ }
1043
+ return this.submit();
1044
+ case 'tab':
1045
+ if (key.shift)
1046
+ return;
1047
+ return this.openCompletion(true);
1048
+ case 'backspace':
1049
+ if (key.alt)
1050
+ this.editor.killWordLeft();
1051
+ else
1052
+ this.editor.backspace();
1053
+ return this.refreshCompletion();
1054
+ case 'delete':
1055
+ this.editor.deleteForward();
1056
+ return this.refreshCompletion();
1057
+ case 'left': return (key.ctrl || key.alt) ? this.editor.moveWordLeft(Boolean(key.shift)) : this.editor.moveLeft(Boolean(key.shift));
1058
+ case 'right': return (key.ctrl || key.alt) ? this.editor.moveWordRight(Boolean(key.shift)) : this.editor.moveRight(Boolean(key.shift));
1059
+ case 'home': return this.editor.moveHome(Boolean(key.shift));
1060
+ case 'end': return this.editor.moveEnd(Boolean(key.shift));
1061
+ case 'up':
1062
+ if (key.shift)
1063
+ return this.editor.moveUp(true);
1064
+ return this.historyOrMove(-1);
1065
+ case 'down':
1066
+ if (key.shift)
1067
+ return this.editor.moveDown(true);
1068
+ return this.historyOrMove(1);
1069
+ case 'pageup':
1070
+ if (key.shift) {
1071
+ this.editor.moveHome(true);
1072
+ this.editor.line = 0;
1073
+ return;
1074
+ }
1075
+ break;
1076
+ case 'pagedown':
1077
+ if (key.shift) {
1078
+ this.editor.moveEnd(true);
1079
+ this.editor.line = this.editor.lines.length - 1;
1080
+ return;
1081
+ }
1082
+ break;
1083
+ case 'char':
1084
+ this.editor.insert(key.text);
1085
+ return this.refreshCompletion();
1086
+ default: break;
1087
+ }
1088
+ if (key.ctrl) {
1089
+ switch (key.name) {
1090
+ case 'a': return this.editor.moveHome();
1091
+ case 'e': return this.editor.moveEnd();
1092
+ case 'k':
1093
+ this.editor.killToEnd();
1094
+ return this.refreshCompletion();
1095
+ case 'u':
1096
+ this.editor.killToStart();
1097
+ return this.refreshCompletion();
1098
+ case 'w':
1099
+ this.editor.killWordLeft();
1100
+ return this.refreshCompletion();
1101
+ case 'y':
1102
+ this.editor.yank();
1103
+ return this.refreshCompletion();
1104
+ case 'x': {
1105
+ if (this.cutSelection())
1106
+ return;
1107
+ break;
1108
+ }
1109
+ case 'p': return this.openPalette();
1110
+ case 'l': return this.clearScreen();
1111
+ case 'o': return this.expand();
1112
+ case 'v': return this.pasteClipboard();
1113
+ default: break;
1114
+ }
1115
+ }
1116
+ if (key.alt && key.name === 'a') {
1117
+ this.editor.selectAll();
1118
+ this.notice = 'selected all input text';
1119
+ this.scheduleDraw();
1120
+ return;
1121
+ }
1122
+ if (key.alt && key.name === 'x') {
1123
+ if (this.cutSelection())
1124
+ return;
1125
+ }
1126
+ if (key.alt && (key.name === 'c' || key.name === 'w')) {
1127
+ const text = this.editor.hasSelection
1128
+ ? this.editor.getSelectedText()
1129
+ : this.editor.getText();
1130
+ if (text) {
1131
+ writeClipboardSync(text);
1132
+ this.editor.killRing = text;
1133
+ this.notice = this.editor.hasSelection
1134
+ ? `copied selection (${text.length} chars) to clipboard`
1135
+ : 'copied input to clipboard';
1136
+ }
1137
+ else {
1138
+ this.notice = 'input is empty (nothing to copy)';
1139
+ }
1140
+ this.scheduleDraw();
1141
+ return;
1142
+ }
1143
+ if (key.alt && key.name === 'v')
1144
+ return this.pasteClipboard();
1145
+ if (key.alt && key.name === 'b')
1146
+ return this.editor.moveWordLeft();
1147
+ if (key.alt && key.name === 'f')
1148
+ return this.editor.moveWordRight();
1149
+ }
1150
+ handleScrollKey(key) {
1151
+ const viewport = this.surface && this.surface.viewport;
1152
+ if (key.name === 'mouse') {
1153
+ if (handleTurnRailMouse(key, this.surface, this))
1154
+ return true;
1155
+ if (this.messageActionLoop && isMouseMotion(key.sequence)) {
1156
+ return handleMessageMouse(this, this.messageActionLoop, key);
1157
+ }
1158
+ if (handleScrollbarMouse(key, viewport, this.surface, this))
1159
+ return true;
1160
+ if (!this.layer && this.messageActionLoop)
1161
+ return handleMessageMouse(this, this.messageActionLoop, key);
1162
+ return true;
1163
+ }
1164
+ if (key.name === 'wheel') {
1165
+ if (!viewport || !key.wheel)
1166
+ return true;
1167
+ const layout = this.surface?.turnRailLayout;
1168
+ const card = layout?.cardRect;
1169
+ const pointerX = key.wheel.x;
1170
+ const pointerY = key.wheel.y;
1171
+ const relativeY = pointerY - (Number.isFinite(layout?.stageTop) ? layout.stageTop : 0);
1172
+ if (card && Array.isArray(card.groupTurns) &&
1173
+ Number.isFinite(pointerX) && Number.isFinite(pointerY) &&
1174
+ pointerX >= card.x && pointerX < card.x + card.width &&
1175
+ relativeY >= card.y && relativeY < card.y + card.height &&
1176
+ (key.wheel.direction === 'up' || key.wheel.direction === 'down')) {
1177
+ const previous = Number.isFinite(this.surface.turnRailCardOffset)
1178
+ ? this.surface.turnRailCardOffset : 0;
1179
+ const maximum = Number.isFinite(card.maxOffset) ? Math.max(0, card.maxOffset) : 0;
1180
+ const change = key.wheel.direction === 'up' ? -1 : 1;
1181
+ const current = Math.max(0, Math.min(maximum, previous + change));
1182
+ if (current !== previous) {
1183
+ this.surface.turnRailCardOffset = current;
1184
+ this.scheduleDraw();
1185
+ }
1186
+ return true;
1187
+ }
1188
+ if (this.renderer?.scrollCodePanel?.(key, this.surface)) {
1189
+ if (typeof this.scheduleDraw === 'function')
1190
+ this.scheduleDraw();
1191
+ else
1192
+ this.draw();
1193
+ return true;
1194
+ }
1195
+ if (this.renderer?.scrollThinkingPanel?.(key, this.surface)) {
1196
+ if (typeof this.scheduleDraw === 'function')
1197
+ this.scheduleDraw();
1198
+ else
1199
+ this.draw();
1200
+ return true;
1201
+ }
1202
+ return handleViewportWheel(key, viewport, this.surface, this);
1203
+ }
1204
+ if (!viewport)
1205
+ return false;
1206
+ const clearTurnRailFocus = () => {
1207
+ if (!this.surface)
1208
+ return;
1209
+ this.surface.activeTurnIndex = null;
1210
+ this.surface.hoveredTurnIndex = null;
1211
+ this.surface.hoveredTurnAnchorY = null;
1212
+ };
1213
+ if (key.name === 'pageup') {
1214
+ clearTurnRailFocus();
1215
+ if (key.shift)
1216
+ viewport.toTop();
1217
+ else
1218
+ viewport.pageUp();
1219
+ return true;
1220
+ }
1221
+ if (key.name === 'pagedown') {
1222
+ clearTurnRailFocus();
1223
+ if (key.shift)
1224
+ viewport.toBottom();
1225
+ else
1226
+ viewport.pageDown();
1227
+ return true;
1228
+ }
1229
+ if (key.shift && key.name === 'up') {
1230
+ if (!this.editor.isEmpty)
1231
+ return false;
1232
+ clearTurnRailFocus();
1233
+ viewport.lineUp();
1234
+ return true;
1235
+ }
1236
+ if (key.shift && key.name === 'down') {
1237
+ if (!this.editor.isEmpty)
1238
+ return false;
1239
+ clearTurnRailFocus();
1240
+ viewport.lineDown();
1241
+ return true;
1242
+ }
1243
+ if (key.alt && key.ctrl && key.name === 'u') {
1244
+ clearTurnRailFocus();
1245
+ viewport.halfPageUp();
1246
+ return true;
1247
+ }
1248
+ if (key.alt && key.ctrl && key.name === 'd') {
1249
+ clearTurnRailFocus();
1250
+ viewport.halfPageDown();
1251
+ return true;
1252
+ }
1253
+ const jumpViewport = (direction, kinds) => {
1254
+ clearTurnRailFocus();
1255
+ viewport.jump(direction, kinds);
1256
+ return true;
1257
+ };
1258
+ if (key.alt && key.name === ',')
1259
+ return jumpViewport(-1, ['step']);
1260
+ if (key.alt && key.name === '.')
1261
+ return jumpViewport(1, ['step']);
1262
+ if ((key.alt && key.name === '[') || (key.alt && key.name === '<'))
1263
+ return jumpViewport(-1, ['user']);
1264
+ if ((key.alt && key.name === ']') || (key.alt && key.name === '>'))
1265
+ return jumpViewport(1, ['user']);
1266
+ if (key.alt && key.name === 'u') {
1267
+ this.offerUndo();
1268
+ return true;
1269
+ }
1270
+ return false;
1271
+ }
1272
+ offerUndo() {
1273
+ const surface = this.surface;
1274
+ if (!surface)
1275
+ return;
1276
+ const width = surface.viewport.width;
1277
+ const marks = surface.transcript.markers(width).filter((m) => m.kind === 'checkpoint');
1278
+ if (marks.length === 0) {
1279
+ this.notice = 'no restore points in this session yet';
1280
+ return;
1281
+ }
1282
+ const top = surface.viewport.scrollTop;
1283
+ const bottom = top + surface.viewport.height;
1284
+ const onScreen = marks.filter((m) => m.row >= top && m.row < bottom);
1285
+ const above = marks.filter((m) => m.row < top);
1286
+ const mark = onScreen.length ? onScreen[onScreen.length - 1] : (above.pop() || marks[0]);
1287
+ const meta = mark?.meta || {};
1288
+ const where = meta.path ? this.sanitizeSingleLine(shortenHome(meta.path)) : 'files changed this task';
1289
+ const rawStep = meta.step == null ? '' : this.sanitizeSingleLine(meta.step);
1290
+ const step = rawStep ? ` at step ${rawStep}` : '';
1291
+ if (this.editor.isEmpty) {
1292
+ this.editor.setText('/undo');
1293
+ this.notice = `restore point${step} ${GLYPHS.dot} ${where} ${GLYPHS.dot} enter previews, --apply writes`;
1294
+ }
1295
+ else {
1296
+ this.notice = `restore point${step} ${GLYPHS.dot} ${where} ${GLYPHS.dot} run /undo to preview`;
1297
+ }
1298
+ }
1299
+ sanitizeSingleLine(value) {
1300
+ return value == null ? '' : safeDisplay(String(value)).replace(/\s+/g, ' ').trim();
1301
+ }
1302
+ cutSelection() {
1303
+ if (!this.editor.hasSelection)
1304
+ return false;
1305
+ const text = this.editor.getSelectedText();
1247
1306
  writeClipboardSync(text);
1248
1307
  this.editor.killRing = text;
1249
- this.notice = this.editor.hasSelection
1250
- ? `copied selection (${text.length} chars) to clipboard`
1251
- : 'copied input to clipboard';
1252
- } else {
1253
- this.notice = 'input is empty (nothing to copy)';
1254
- }
1255
- this.scheduleDraw();
1256
- return;
1257
- }
1258
- if (key.alt && key.name === 'v') return this.pasteClipboard();
1259
- if (key.alt && key.name === 'b') return this.editor.moveWordLeft();
1260
- if (key.alt && key.name === 'f') return this.editor.moveWordRight();
1261
- }
1262
-
1263
- /**
1264
- * Scroll the transcript viewport. Returns true when the key was ours.
1265
- *
1266
- * Only bound when a Stage is running: without one there is no viewport, the
1267
- * terminal's own scrollback is the viewport, and stealing pageup from it
1268
- * would be worse than useless.
1269
- *
1270
- * The choices, and why they are not opencode's:
1271
- *
1272
- * * pageup/pagedown move a full viewport MINUS ONE ROW of overlap, which is
1273
- * what every pager does and what lets the eye carry across the jump.
1274
- * opencode calls height/2 a "page" and height/4 a "half page" — both are
1275
- * half of what their names claim, and there is no reason to inherit that.
1276
- * * ctrl+u / ctrl+d are NOT scroll keys. They are kill-to-start and
1277
- * delete/exit, tests/chatSurface.test.js asserts it, and a chat where the
1278
- * key that deletes your line also scrolls is a trap. Half-page is on the
1279
- * alt-modified pair instead.
1280
- * * home/end stay with the editor, so top/bottom take the shifted pageup and
1281
- * pagedown rather than fighting for them.
1282
- */
1283
- handleScrollKey(key) {
1284
- const viewport = this.surface && this.surface.viewport;
1285
-
1286
- // A mouse report must be swallowed whether or not there is a viewport to
1287
- // act on. The bytes are already consumed by the decoder; letting the event
1288
- // fall through would put `mouse` or `wheel` into the switch below, where a
1289
- // future case could act on it by accident — and, worse, a terminal that
1290
- // kept reporting after a failed teardown would type into the user's line.
1291
- if (key.name === 'mouse') {
1292
- if (handleTurnRailMouse(key, this.surface, this)) return true;
1293
- if (this.messageActionLoop && isMouseMotion(key.sequence)) {
1294
- return handleMessageMouse(this, this.messageActionLoop, key);
1295
- }
1296
- if (handleScrollbarMouse(key, viewport, this.surface, this)) return true;
1297
- if (!this.layer && this.messageActionLoop) return handleMessageMouse(this, this.messageActionLoop, key);
1298
- return true;
1299
- }
1300
- if (key.name === 'wheel') {
1301
- if (!viewport || !key.wheel) return true;
1302
- // The reference timeline popover is itself scrollable when a dot
1303
- // represents more turns than can fit. Wheel input over the card must
1304
- // not move the chat viewport behind it.
1305
- const layout = this.surface?.turnRailLayout;
1306
- const card = layout?.cardRect;
1307
- const pointerX = key.wheel.x;
1308
- const pointerY = key.wheel.y;
1309
- const relativeY = pointerY - (Number.isFinite(layout?.stageTop) ? layout.stageTop : 0);
1310
- if (card && Array.isArray(card.groupTurns) &&
1311
- Number.isFinite(pointerX) && Number.isFinite(pointerY) &&
1312
- pointerX >= card.x && pointerX < card.x + card.width &&
1313
- relativeY >= card.y && relativeY < card.y + card.height &&
1314
- (key.wheel.direction === 'up' || key.wheel.direction === 'down')) {
1315
- const previous = Number.isFinite(this.surface.turnRailCardOffset)
1316
- ? this.surface.turnRailCardOffset : 0;
1317
- const maximum = Number.isFinite(card.maxOffset) ? Math.max(0, card.maxOffset) : 0;
1318
- const change = key.wheel.direction === 'up' ? -1 : 1;
1319
- const current = Math.max(0, Math.min(maximum, previous + change));
1320
- if (current !== previous) {
1321
- this.surface.turnRailCardOffset = current;
1322
- this.scheduleDraw();
1323
- }
1308
+ this.editor.deleteSelection();
1309
+ this.notice = `cut selection (${text.length} chars) to clipboard`;
1310
+ this.refreshCompletion();
1324
1311
  return true;
1325
- }
1326
- if (this.renderer?.scrollCodePanel?.(key, this.surface)) {
1327
- if (typeof this.scheduleDraw === 'function') this.scheduleDraw(); else this.draw();
1328
- return true;
1329
- }
1330
- if (this.renderer?.scrollThinkingPanel?.(key, this.surface)) {
1331
- if (typeof this.scheduleDraw === 'function') this.scheduleDraw(); else this.draw();
1332
- return true;
1333
- }
1334
-
1335
- return handleViewportWheel(key, viewport, this.surface, this);
1336
- }
1337
-
1338
- if (!viewport) return false;
1339
-
1340
- const clearTurnRailFocus = () => {
1341
- if (!this.surface) return;
1342
- this.surface.activeTurnIndex = null;
1343
- this.surface.hoveredTurnIndex = null;
1344
- this.surface.hoveredTurnAnchorY = null;
1345
- };
1346
-
1347
- if (key.name === 'pageup') {
1348
- clearTurnRailFocus();
1349
- if (key.shift) viewport.toTop(); else viewport.pageUp();
1350
- return true;
1351
- }
1352
- if (key.name === 'pagedown') {
1353
- clearTurnRailFocus();
1354
- // Shift+PgDn is the way back to following, and it is spelled out in the
1355
- // affordance the surface draws while the view is held away.
1356
- if (key.shift) viewport.toBottom(); else viewport.pageDown();
1357
- return true;
1358
- }
1359
- if (key.shift && key.name === 'up') {
1360
- if (!this.editor.isEmpty) return false;
1361
- clearTurnRailFocus();
1362
- viewport.lineUp();
1363
- return true;
1364
- }
1365
- if (key.shift && key.name === 'down') {
1366
- if (!this.editor.isEmpty) return false;
1367
- clearTurnRailFocus();
1368
- viewport.lineDown();
1369
- return true;
1370
- }
1371
- if (key.alt && key.ctrl && key.name === 'u') {
1372
- clearTurnRailFocus();
1373
- viewport.halfPageUp();
1374
- return true;
1375
- }
1376
- if (key.alt && key.ctrl && key.name === 'd') {
1377
- clearTurnRailFocus();
1378
- viewport.halfPageDown();
1379
- return true;
1380
- }
1381
-
1382
- // Jump by structure, not by rows. The transcript knows where each frame
1383
- // starts, so `,`/`.` step through tool calls and the shifted `<`/`>` on the
1384
- // same two physical keys step through exchanges — a bigger jump on the
1385
- // bigger key press.
1386
- //
1387
- // These are alt-modified because a bare bracket is a character the user is
1388
- // entitled to type; the plan's `[`/`]` could not be bound at all, and
1389
- // alt+[ is worse than unbound — ESC [ IS the CSI introducer, so it is
1390
- // indistinguishable from the start of an escape sequence.
1391
- const jumpViewport = (direction, kinds) => {
1392
- clearTurnRailFocus();
1393
- viewport.jump(direction, kinds);
1394
- return true;
1395
- };
1396
- if (key.alt && key.name === ',') return jumpViewport(-1, ['step']);
1397
- if (key.alt && key.name === '.') return jumpViewport(1, ['step']);
1398
- // Exchanges are marked by the USER's message, not by the turn footer. Both
1399
- // sit at almost the same seam — a footer is immediately followed by the next
1400
- // question — so accepting either made the jump land twice two rows apart
1401
- // instead of once per exchange.
1402
- if ((key.alt && key.name === '[') || (key.alt && key.name === '<')) return jumpViewport(-1, ['user']);
1403
- if ((key.alt && key.name === ']') || (key.alt && key.name === '>')) return jumpViewport(1, ['user']);
1404
-
1405
- if (key.alt && key.name === 'u') { this.offerUndo(); return true; }
1406
-
1407
- return false;
1408
- }
1409
-
1410
- /**
1411
- * OFFER the undo for the restore point you are looking at. Never perform it.
1412
- *
1413
- * The rail marks every restore point, which makes scrolling back a way of
1414
- * finding somewhere to roll back TO — and that is worth nothing if reaching it
1415
- * means remembering a command. This puts the command in the input line for
1416
- * review; it does not run it, and it does not overwrite a message you were
1417
- * part-way through typing.
1418
- *
1419
- * `/undo` is preview-by-default and needs `--apply` to write, so even the
1420
- * accidental path here is a read. That is deliberate: a single keystroke may
1421
- * not be able to overwrite a day's work.
1422
- *
1423
- * WHAT THIS IS NOT: undo for *exactly* that point. `/undo` takes a task, not a
1424
- * checkpoint id, so there is no way to ask for "the state at this marker"
1425
- * without changing restore semantics — which is not a terminal-UI change and
1426
- * is not being smuggled into one. The notice says which step the marker is, so
1427
- * the choice is at least informed.
1428
- */
1429
- offerUndo() {
1430
- const surface = this.surface;
1431
- if (!surface) return;
1432
- const width = surface.viewport.width;
1433
- const marks = surface.transcript.markers(width).filter((m) => m.kind === 'checkpoint');
1434
- if (marks.length === 0) {
1435
- this.notice = 'no restore points in this session yet';
1436
- return;
1437
- }
1438
-
1439
- const top = surface.viewport.scrollTop;
1440
- const bottom = top + surface.viewport.height;
1441
- const onScreen = marks.filter((m) => m.row >= top && m.row < bottom);
1442
- const above = marks.filter((m) => m.row < top);
1443
- const mark = onScreen.length ? onScreen[onScreen.length - 1] : (above.pop() || marks[0]);
1444
- const meta = mark.meta || {};
1445
-
1446
- const where = meta.path ? this.sanitizeSingleLine(shortenHome(meta.path)) : 'files changed this task';
1447
- const rawStep = meta.step == null ? '' : this.sanitizeSingleLine(meta.step);
1448
- const step = rawStep ? ` at step ${rawStep}` : '';
1449
-
1450
- if (this.editor.isEmpty) {
1451
- this.editor.setText('/undo');
1452
- this.notice = `restore point${step} ${GLYPHS.dot} ${where} ${GLYPHS.dot} enter previews, --apply writes`;
1453
- } else {
1454
- // Their draft is theirs. Say what is there and leave the line alone.
1455
- this.notice = `restore point${step} ${GLYPHS.dot} ${where} ${GLYPHS.dot} run /undo to preview`;
1456
- }
1457
- }
1458
-
1459
- sanitizeSingleLine(value) {
1460
- return value == null ? '' : safeDisplay(String(value)).replace(/\s+/g, ' ').trim();
1461
- }
1462
-
1463
- cutSelection() {
1464
- if (!this.editor.hasSelection) return false;
1465
- const text = this.editor.getSelectedText();
1466
- writeClipboardSync(text);
1467
- this.editor.killRing = text;
1468
- this.editor.deleteSelection();
1469
- this.notice = `cut selection (${text.length} chars) to clipboard`;
1470
- this.refreshCompletion();
1471
- return true;
1472
- }
1473
-
1474
- handleCtrlC() {
1475
- handlePromptCtrlC(
1476
- this,
1477
- () => [`${paint('warn', GLYPHS.cross)} ${dim('interrupted')}`],
1478
- CTRL_C_WINDOW_MS
1479
- );
1480
- }
1481
-
1482
- handleEscape() {
1483
- handlePromptEscape(
1484
- this,
1485
- () => [`${paint('warn', GLYPHS.cross)} ${dim('interrupted')}`]
1486
- );
1487
- }
1488
-
1489
- interrupt() {
1490
- triggerTurnInterrupt(
1491
- this,
1492
- () => [`${paint('warn', GLYPHS.cross)} ${dim('interrupted')}`]
1493
- );
1494
- }
1495
-
1496
- /** Show the last tool output in full, above the prompt. */
1497
- expand() {
1498
- this.erase();
1499
- this.onExpand();
1500
- this.notice = '';
1501
- }
1502
-
1503
- clearScreen() {
1504
- // On the Stage, ctrl+L means what it means in a terminal: the screen goes
1505
- // blank and your history is still behind you. Clearing the transcript alone
1506
- // would destroy the session record, so the surface prints it through into
1507
- // real scrollback first and then starts the band clean. It is also the
1508
- // escape hatch for getting a transcript out of the band without exiting.
1509
- if (this.surface) { this.surface.flushAndClear(); return; }
1510
-
1511
- this.erase();
1512
- // The one clear Causyne may perform: the user pressed ctrl+L and asked for it.
1513
- // UX-01 forbids clearing the terminal on the app's own initiative.
1514
- this.writeControl('\x1b[2J\x1b[H');
1515
- this.drawnRows = 0;
1516
- this.cursorRow = 0;
1517
- }
1518
-
1519
- historyOrMove(direction) {
1520
- // Inside a multi-line buffer the arrows move the cursor; history is only
1521
- // reachable from the edge, which is what every shell does.
1522
- if (direction === -1 && this.editor.line > 0) return this.editor.moveUp();
1523
- if (direction === 1 && this.editor.line < this.editor.lines.length - 1) return this.editor.moveDown();
1524
-
1525
- const text = direction === -1
1526
- ? this.history.previous(this.editor.getText())
1527
- : this.history.next();
1528
- if (text === null || text === undefined) return;
1529
- this.editor.setText(text);
1530
- }
1531
-
1532
- // -------------------------------------------------------------------------
1533
- // Completion
1534
- // -------------------------------------------------------------------------
1535
-
1536
- /** A completed scan must refresh the currently displayed @ picker. */
1537
- bindFileIndex(index) {
1538
- if (typeof this._unsubscribeFileIndex === 'function') this._unsubscribeFileIndex();
1539
- this._unsubscribeFileIndex = index.subscribe(() => {
1540
- // Ignore a late callback from a previous workspace or a dismissed prompt.
1541
- if (this.index !== index || !this.active) return;
1542
- const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
1543
- if (!trigger || trigger.kind !== 'file') return;
1544
- this.openCompletion(false);
1545
- if (index.truncated) this.notice = 'Workspace file index reached its safety limit; narrow the project root.';
1546
- else if (this.notice === 'Indexing workspace files…') this.notice = '';
1547
- this.scheduleDraw();
1548
- });
1549
- void index.ensure();
1550
- }
1551
-
1552
- /** Dynamically re-target the prompt root and optional focused subproject. */
1553
- setWorkingRoot(newRoot, focusDir = null) {
1554
- if (typeof this._unsubscribeFileIndex === 'function') this._unsubscribeFileIndex();
1555
- this.index?.dispose();
1556
- this.root = newRoot;
1557
- this.focusDir = focusDir;
1558
- this.index = new FileIndex(newRoot);
1559
- this.bindFileIndex(this.index);
1560
- const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
1561
- if (trigger?.kind === 'file') this.openCompletion(false);
1562
- }
1563
-
1564
- cursorOffset() {
1565
- // The editor stores Unicode code points; String.slice() in the completion
1566
- // provider expects UTF-16 code units. Count units at this API boundary.
1567
- const before = this.editor.lines.slice(0, this.editor.line)
1568
- .reduce((total, line) => total + line.join('').length + 1, 0);
1569
- return before + this.editor.lines[this.editor.line]
1570
- .slice(0, this.editor.col).join('').length;
1571
- }
1572
-
1573
- openCompletion(force = false) {
1574
- const text = this.editor.getText();
1575
- const result = suggest(text, this.cursorOffset(), {
1576
- root: this.root,
1577
- index: this.index,
1578
- focusDir: this.focusDir
1579
- });
1580
- if (!result) {
1581
- if (force) this.notice = 'nothing to complete here';
1582
- // Close a picker whose trigger has gone.
1583
- this.completion = null;
1584
- return;
1585
- }
1586
- this.completion = result;
1587
- this.selected = 0;
1588
- }
1589
-
1590
- /** Re-run completion after an edit; close it when the trigger is gone. */
1591
- refreshCompletion() {
1592
- if (!this.completion) {
1593
- const text = this.editor.getText();
1594
- const offset = this.cursorOffset();
1595
- const opens = Boolean(detectTrigger(text, offset));
1596
- if (opens) this.openCompletion(false);
1597
- return;
1598
- }
1599
- this.openCompletion(false);
1600
- if (this.completion) this.selected = Math.min(this.selected, this.completion.items.length - 1);
1601
- }
1602
-
1603
- /**
1604
- * Is the only suggestion the thing that is already typed?
1605
- *
1606
- * `/skill mine` offers exactly one completion — `mine` — which is what the
1607
- * user has already written. Accepting it changes nothing, refreshCompletion()
1608
- * immediately reopens the picker on the same text, and Enter becomes a key
1609
- * that can never submit. The command was unreachable.
1610
- *
1611
- * openclaw solves this with shouldSubmitExactArgumentCompletion
1612
- * (src/tui/commands.ts): when the sole completion equals the argument text,
1613
- * submit instead of completing. Same rule here, extended to a whole command
1614
- * so `/undo` submits on the first Enter rather than the second.
1615
- *
1616
- * Deliberately NOT applied to file completion: there, accepting a directory
1617
- * that matches exactly is how you drill into it.
1618
- */
1619
- completionIsExact() {
1620
- if (!this.completion || this.completion.items.length !== 1) return false;
1621
- const [item] = this.completion.items;
1622
- if (this.completion.kind === 'command-argument') return item.value === this.completion.query;
1623
- if (this.completion.kind === 'command') return item.value === this.editor.getText();
1624
- return false;
1625
- }
1626
-
1627
- handleCompletionKey(key) {
1628
- if (key.name === 'up') { this.moveSelection(-1); return true; }
1629
- if (key.name === 'down') { this.moveSelection(1); return true; }
1630
- // The wheel, PgUp and PgDn belong to the open picker. Letting them fall
1631
- // through scrolled the transcript behind a frozen menu.
1632
- if (key.name === 'wheel') {
1633
- const direction = key.wheel && key.wheel.direction;
1634
- if (direction === 'up') this.moveSelectionClamped(-1);
1635
- else if (direction === 'down') this.moveSelectionClamped(1);
1636
- this.scheduleDraw();
1637
- return true;
1638
- }
1639
- if (key.name === 'pageup' && !key.shift) {
1640
- this.moveSelectionClamped(-MAX_VISIBLE);
1641
- this.scheduleDraw();
1642
- return true;
1643
- }
1644
- if (key.name === 'pagedown' && !key.shift) {
1645
- this.moveSelectionClamped(MAX_VISIBLE);
1646
- this.scheduleDraw();
1647
- return true;
1648
- }
1649
- if (key.name === 'mouse') {
1650
- if (key.mouse && key.mouse.pressed && key.mouse.button === 0 && !isMouseMotion(key.sequence)) {
1651
- let item = null;
1652
- const hasZeroY = Number.isFinite(key.mouse.y);
1653
- const rawMouseRow = hasZeroY
1654
- ? Math.floor(key.mouse.y)
1655
- : (Number.isFinite(key.mouse.row) ? Math.floor(key.mouse.row) : NaN);
1656
- if (this.pickerLayout && Number.isFinite(rawMouseRow)) {
1657
- const stageHeight = this.surface?.stage?.height || this.out?.rows || process.stdout.rows || 24;
1658
- const termRows = Number.isFinite(this.out?.rows) && this.out.rows > 0
1659
- ? Math.floor(this.out.rows)
1660
- : stageHeight;
1661
- // KeyDecoder emits 0-based x/y screen coordinates; legacy unit tests pass 1-based row/col.
1662
- const promptTop = hasZeroY
1663
- ? Math.max(0, termRows - this.pickerLayout.totalPromptRows)
1664
- : Math.max(1, stageHeight - this.pickerLayout.totalPromptRows + 1);
1665
- const pickerTop = promptTop + this.pickerLayout.pickerStart;
1666
- const pickerBottom = pickerTop + this.pickerLayout.pickerCount - 1;
1667
- const mouseX = Number.isFinite(key.mouse.x) ? Math.floor(key.mouse.x) : NaN;
1668
- const mainW = this.surface
1669
- ? sessionMainWidth(this.surface.width, Boolean(this.surface.homeInfo), this.surface.env)
1670
- : Infinity;
1671
- const inMainColumn = !Number.isFinite(mouseX) || (mouseX >= 0 && mouseX < mainW);
1672
-
1673
- if (inMainColumn && rawMouseRow >= pickerTop && rawMouseRow <= pickerBottom) {
1674
- // The picker renders a scrolled window (renderPicker); a click maps
1675
- // to the item under the cursor, not to the first page of items.
1676
- const items = Array.isArray(this.completion.items) ? this.completion.items : [];
1677
- const total = items.length;
1678
- const windowStart = Math.max(0, Math.min(this.selected - MAX_VISIBLE + 1, total - MAX_VISIBLE));
1679
- const index = windowStart + (rawMouseRow - pickerTop);
1680
- if (index >= 0 && index < total) {
1681
- this.selected = index;
1682
- item = items[index];
1683
- }
1684
- } else {
1685
- // Click outside picker closes it
1312
+ }
1313
+ handleCtrlC() {
1314
+ handlePromptCtrlC(this, () => [`${paint('warn', GLYPHS.cross)} ${dim('interrupted')}`], CTRL_C_WINDOW_MS);
1315
+ }
1316
+ handleEscape() {
1317
+ handlePromptEscape(this, () => [`${paint('warn', GLYPHS.cross)} ${dim('interrupted')}`]);
1318
+ }
1319
+ interrupt() {
1320
+ triggerTurnInterrupt(this, () => [`${paint('warn', GLYPHS.cross)} ${dim('interrupted')}`]);
1321
+ }
1322
+ expand() {
1323
+ this.erase();
1324
+ this.onExpand();
1325
+ this.notice = '';
1326
+ }
1327
+ clearScreen() {
1328
+ if (this.surface) {
1329
+ this.surface.flushAndClear();
1330
+ return;
1331
+ }
1332
+ this.erase();
1333
+ // The one clear Causyne may perform: the user pressed ctrl+L and asked for it.
1334
+ // UX-01 forbids clearing the terminal on the app's own initiative.
1335
+ this.writeControl('\x1b[2J\x1b[H');
1336
+ this.drawnRows = 0;
1337
+ this.cursorRow = 0;
1338
+ }
1339
+ historyOrMove(direction) {
1340
+ if (direction === -1 && this.editor.line > 0) {
1341
+ this.editor.moveUp();
1342
+ return;
1343
+ }
1344
+ if (direction === 1 && this.editor.line < this.editor.lines.length - 1) {
1345
+ this.editor.moveDown();
1346
+ return;
1347
+ }
1348
+ const text = direction === -1
1349
+ ? this.history.previous(this.editor.getText())
1350
+ : this.history.next();
1351
+ if (text === null || text === undefined)
1352
+ return;
1353
+ this.editor.setText(text);
1354
+ }
1355
+ // -------------------------------------------------------------------------
1356
+ // Completion
1357
+ // -------------------------------------------------------------------------
1358
+ bindFileIndex(index) {
1359
+ if (typeof this._unsubscribeFileIndex === 'function')
1360
+ this._unsubscribeFileIndex();
1361
+ this._unsubscribeFileIndex = index.subscribe(() => {
1362
+ if (this.index !== index || !this.active)
1363
+ return;
1364
+ const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
1365
+ if (!trigger || trigger.kind !== 'file')
1366
+ return;
1367
+ this.openCompletion(false);
1368
+ if (index.truncated)
1369
+ this.notice = 'Workspace file index reached its safety limit; narrow the project root.';
1370
+ else if (this.notice === 'Indexing workspace files…')
1371
+ this.notice = '';
1372
+ this.scheduleDraw();
1373
+ });
1374
+ void index.ensure();
1375
+ }
1376
+ setWorkingRoot(newRoot, focusDir = null) {
1377
+ if (typeof this._unsubscribeFileIndex === 'function')
1378
+ this._unsubscribeFileIndex();
1379
+ this.index?.dispose();
1380
+ this.root = newRoot;
1381
+ this.focusDir = focusDir;
1382
+ this.index = new FileIndex(newRoot);
1383
+ this.bindFileIndex(this.index);
1384
+ const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
1385
+ if (trigger?.kind === 'file')
1386
+ this.openCompletion(false);
1387
+ }
1388
+ cursorOffset() {
1389
+ const before = this.editor.lines.slice(0, this.editor.line)
1390
+ .reduce((total, line) => total + line.join('').length + 1, 0);
1391
+ return before + (this.editor.lines[this.editor.line] ?? [])
1392
+ .slice(0, this.editor.col).join('').length;
1393
+ }
1394
+ openCompletion(force = false) {
1395
+ const text = this.editor.getText();
1396
+ const result = suggest(text, this.cursorOffset(), {
1397
+ root: this.root,
1398
+ index: this.index,
1399
+ focusDir: this.focusDir
1400
+ });
1401
+ if (!result) {
1402
+ if (force)
1403
+ this.notice = 'nothing to complete here';
1686
1404
  this.completion = null;
1405
+ return;
1406
+ }
1407
+ this.completion = result;
1408
+ this.selected = 0;
1409
+ }
1410
+ refreshCompletion() {
1411
+ if (!this.completion) {
1412
+ const text = this.editor.getText();
1413
+ const offset = this.cursorOffset();
1414
+ const opens = Boolean(detectTrigger(text, offset));
1415
+ if (opens)
1416
+ this.openCompletion(false);
1417
+ return;
1418
+ }
1419
+ this.openCompletion(false);
1420
+ if (this.completion)
1421
+ this.selected = Math.min(this.selected, this.completion.items.length - 1);
1422
+ }
1423
+ completionIsExact() {
1424
+ if (!this.completion || this.completion.items.length !== 1)
1425
+ return false;
1426
+ const item = this.completion.items[0];
1427
+ if (!item)
1428
+ return false;
1429
+ if (this.completion.kind === 'command-argument')
1430
+ return item.value === this.completion.query;
1431
+ if (this.completion.kind === 'command')
1432
+ return item.value === this.editor.getText();
1433
+ return false;
1434
+ }
1435
+ handleCompletionKey(key) {
1436
+ if (!this.completion)
1437
+ return false;
1438
+ if (key.name === 'up') {
1439
+ this.moveSelection(-1);
1440
+ return true;
1441
+ }
1442
+ if (key.name === 'down') {
1443
+ this.moveSelection(1);
1444
+ return true;
1445
+ }
1446
+ if (key.name === 'wheel') {
1447
+ const direction = key.wheel && key.wheel.direction;
1448
+ if (direction === 'up')
1449
+ this.moveSelectionClamped(-1);
1450
+ else if (direction === 'down')
1451
+ this.moveSelectionClamped(1);
1687
1452
  this.scheduleDraw();
1688
1453
  return true;
1689
- }
1690
- } else {
1691
- const items = Array.isArray(this.completion.items) ? this.completion.items : [];
1692
- item = items[this.selected];
1693
- }
1694
-
1695
- if (item) {
1696
- if (this.completion.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
1697
- const selectedCommand = this.completion.kind === 'command'
1698
- ? item.value : `/${this.completion.command} ${item.value}`;
1699
- this.runInlineSlashSelection(selectedCommand);
1454
+ }
1455
+ if (key.name === 'pageup' && !key.shift) {
1456
+ this.moveSelectionClamped(-MAX_VISIBLE);
1457
+ this.scheduleDraw();
1700
1458
  return true;
1701
- }
1702
- if (this.completion.kind === 'command') {
1703
- // A skill entry goes onto the line so the user can say what to do
1704
- // with it; clicking it used to invoke it immediately with no task.
1705
- if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
1706
- this.acceptCompletion();
1707
- return true;
1459
+ }
1460
+ if (key.name === 'pagedown' && !key.shift) {
1461
+ this.moveSelectionClamped(MAX_VISIBLE);
1462
+ this.scheduleDraw();
1463
+ return true;
1464
+ }
1465
+ if (key.name === 'mouse') {
1466
+ if (key.mouse && key.mouse.pressed && key.mouse.button === 0 && !isMouseMotion(key.sequence)) {
1467
+ let item = null;
1468
+ const hasZeroY = Number.isFinite(key.mouse.y);
1469
+ const rawMouseRow = hasZeroY
1470
+ ? Math.floor(key.mouse.y)
1471
+ : (Number.isFinite(key.mouse.row) ? Math.floor(key.mouse.row) : Number.NaN);
1472
+ if (this.pickerLayout && Number.isFinite(rawMouseRow)) {
1473
+ const stageHeight = this.surface?.stage?.height || this.out?.rows || process.stdout.rows || 24;
1474
+ const termRows = Number.isFinite(this.out?.rows) && this.out.rows > 0
1475
+ ? Math.floor(this.out.rows)
1476
+ : stageHeight;
1477
+ const promptTop = hasZeroY
1478
+ ? Math.max(0, termRows - this.pickerLayout.totalPromptRows)
1479
+ : Math.max(1, stageHeight - this.pickerLayout.totalPromptRows + 1);
1480
+ const pickerTop = promptTop + this.pickerLayout.pickerStart;
1481
+ const pickerBottom = pickerTop + this.pickerLayout.pickerCount - 1;
1482
+ const mouseX = Number.isFinite(key.mouse.x) ? Math.floor(key.mouse.x) : Number.NaN;
1483
+ const mainW = this.surface
1484
+ ? sessionMainWidth(this.surface.width, Boolean(this.surface.homeInfo), this.surface.env)
1485
+ : Infinity;
1486
+ const inMainColumn = !Number.isFinite(mouseX) || (mouseX >= 0 && mouseX < mainW);
1487
+ if (inMainColumn && rawMouseRow >= pickerTop && rawMouseRow <= pickerBottom) {
1488
+ const items = Array.isArray(this.completion.items) ? this.completion.items : [];
1489
+ const total = items.length;
1490
+ const windowStart = Math.max(0, Math.min(this.selected - MAX_VISIBLE + 1, total - MAX_VISIBLE));
1491
+ const index = windowStart + (rawMouseRow - pickerTop);
1492
+ if (index >= 0 && index < total) {
1493
+ this.selected = index;
1494
+ item = items[index];
1495
+ }
1496
+ }
1497
+ else {
1498
+ this.completion = null;
1499
+ this.scheduleDraw();
1500
+ return true;
1501
+ }
1502
+ }
1503
+ else {
1504
+ const items = Array.isArray(this.completion.items) ? this.completion.items : [];
1505
+ item = items[this.selected];
1506
+ }
1507
+ if (item) {
1508
+ if (this.completion.kind !== 'file' && this.completion.inline) {
1509
+ const selectedCommand = this.completion.kind === 'command'
1510
+ ? item.value : `/${this.completion.command} ${item.value}`;
1511
+ this.runInlineSlashSelection(selectedCommand);
1512
+ return true;
1513
+ }
1514
+ if (this.completion.kind === 'command') {
1515
+ if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
1516
+ this.acceptCompletion();
1517
+ return true;
1518
+ }
1519
+ this.submitPickedCommand(item.value);
1520
+ return true;
1521
+ }
1522
+ if (this.completion.kind === 'command-argument') {
1523
+ this.submitPickedCommand(`/${this.completion.command} ${item.value}`);
1524
+ return true;
1525
+ }
1526
+ this.acceptCompletion();
1527
+ return true;
1528
+ }
1708
1529
  }
1709
- this.submitPickedCommand(item.value);
1710
1530
  return true;
1711
- }
1712
- if (this.completion.kind === 'command-argument') {
1713
- this.submitPickedCommand(`/${this.completion.command} ${item.value}`);
1531
+ }
1532
+ if (key.name === 'enter' && !key.alt && !key.shift) {
1533
+ const item = this.completion.items && this.completion.items[this.selected];
1534
+ if (item && this.completion.kind !== 'file' && this.completion.inline) {
1535
+ const selectedCommand = this.completion.kind === 'command'
1536
+ ? item.value : `/${this.completion.command} ${item.value}`;
1537
+ this.runInlineSlashSelection(selectedCommand);
1538
+ return true;
1539
+ }
1540
+ if (this.completion.kind === 'command' && item) {
1541
+ if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
1542
+ this.acceptCompletion();
1543
+ return true;
1544
+ }
1545
+ this.submitPickedCommand(item.value);
1546
+ return true;
1547
+ }
1548
+ if (this.completionIsExact()) {
1549
+ this.completion = null;
1550
+ return false;
1551
+ }
1552
+ this.acceptCompletion();
1714
1553
  return true;
1715
- }
1716
- this.acceptCompletion();
1717
- return true;
1718
- }
1719
- }
1720
- return true;
1721
- }
1722
- if (key.name === 'enter' && !key.alt && !key.shift) {
1723
- const item = this.completion.items && this.completion.items[this.selected];
1724
- if (item && this.completion.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
1725
- const selectedCommand = this.completion.kind === 'command'
1726
- ? item.value : `/${this.completion.command} ${item.value}`;
1727
- this.runInlineSlashSelection(selectedCommand);
1728
- return true;
1729
- }
1730
- if (this.completion.kind === 'command' && item) {
1731
- if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
1732
- this.acceptCompletion();
1733
- return true;
1734
- }
1735
- // Instant execution on single Enter for any pure slash command
1736
- this.submitPickedCommand(item.value);
1737
- return true;
1738
- }
1739
- if (this.completionIsExact()) {
1740
- // Nothing left to complete. Close the picker and let the key through to
1741
- // submit, rather than re-offering what is already on the line.
1742
- this.completion = null;
1554
+ }
1555
+ if (key.name === 'tab') {
1556
+ if (this.completion.kind !== 'file' && this.completion.inline) {
1557
+ this.notice = 'Press Enter to run the selected command; your unsent draft is preserved.';
1558
+ this.scheduleDraw();
1559
+ return true;
1560
+ }
1561
+ this.acceptCompletion();
1562
+ return true;
1563
+ }
1564
+ if (key.name === 'escape') {
1565
+ const dismissed = this.completion;
1566
+ this.completion = null;
1567
+ if (!(dismissed.kind !== 'file' && dismissed.inline) && /^\s*\/[a-z0-9_?-]*$/i.test(this.editor.getText())) {
1568
+ this.editor.clear();
1569
+ }
1570
+ this.scheduleDraw();
1571
+ return true;
1572
+ }
1743
1573
  return false;
1744
- }
1745
- this.acceptCompletion();
1746
- return true;
1747
- }
1748
- if (key.name === 'tab') {
1749
- if (this.completion?.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
1750
- // Tab must never silently turn an unsent message into a local command.
1751
- this.notice = 'Press Enter to run the selected command; your unsent draft is preserved.';
1752
- this.scheduleDraw();
1753
- return true;
1754
- }
1755
- this.acceptCompletion();
1756
- return true;
1757
- }
1758
- if (key.name === 'escape') {
1759
- const dismissed = this.completion;
1760
- this.completion = null;
1761
- // Only discard a standalone leading command token. Never erase a
1762
- // longer draft just because its first character happens to be /.
1763
- if (!dismissed?.inline && /^\s*\/[a-z0-9_?-]*$/i.test(this.editor.getText())) {
1764
- this.editor.clear();
1765
- }
1766
- this.scheduleDraw();
1767
- return true;
1768
- }
1769
- return false;
1770
- }
1771
-
1772
- moveSelection(direction) {
1773
- const count = Array.isArray(this.completion?.items) ? this.completion.items.length : 0;
1774
- if (count === 0) return;
1775
- this.selected = (((this.selected + direction) % count) + count) % count;
1776
- }
1777
-
1778
- /** Move without wrapping: a wheel or page key stops at either end. */
1779
- moveSelectionClamped(delta) {
1780
- const count = Array.isArray(this.completion?.items) ? this.completion.items.length : 0;
1781
- if (count === 0) return;
1782
- this.selected = Math.max(0, Math.min(count - 1, this.selected + delta));
1783
- }
1784
-
1785
- /**
1786
- * Run a command chosen in the picker through the same path as typing it.
1787
- *
1788
- * deliver() bypassed submit(): during a running turn a picked `/stop` was
1789
- * queued behind the very turn it was meant to stop, and the command never
1790
- * reached input history.
1791
- */
1792
- submitPickedCommand(value) {
1793
- this.completion = null;
1794
- this.editor.setText(value);
1795
- this.submit();
1796
- }
1797
-
1798
- /**
1799
- * Execute an explicitly selected slash action from anywhere in a draft.
1800
- * Ordinary commands run through submit() with the unsent draft suspended;
1801
- * selecting a compiled skill applies it to the draft as its instruction.
1802
- * Neither path changes parseCommand() or interprets ambient prose as control.
1803
- */
1804
- runInlineSlashSelection(value) {
1805
- const trigger = this.completion;
1806
- if (!trigger?.inline || (trigger.kind !== 'command' && trigger.kind !== 'command-argument')) {
1807
- this.submitPickedCommand(value);
1808
- return;
1809
- }
1810
-
1811
- const currentText = this.editor.getText();
1812
- const currentCursor = this.cursorOffset();
1813
- let remaining;
1814
- try {
1815
- remaining = removeInlineSlashToken(currentText, currentCursor, trigger);
1816
- } catch (error) {
1817
- // The draft might have changed since the last render. Never execute a
1818
- // command selected against stale input or erase user-authored text.
1819
- this.notice = 'The command text changed. Reopen the / menu and select again.';
1820
- this.completion = null;
1821
- this.scheduleDraw();
1822
- return;
1823
- }
1824
-
1825
- const consumeDraft = isInlineSkillInvocation(value) && remaining.text.trim().length > 0;
1826
- const commandText = consumeDraft ? `${value} ${remaining.text.trim()}` : value;
1827
-
1828
- // submit() itself protects the queue, but return early here to avoid
1829
- // discarding the unfinished inline token when the command was not queued.
1830
- if (this.busy && this.queue.length >= 32 && !/^\/(?:stop|interrupt)$/i.test(commandText)) {
1831
- this.notice = '32 queued messages: command not submitted; your draft is unchanged.';
1832
- this.scheduleDraw();
1833
- return;
1834
- }
1835
-
1836
- this.completion = null;
1837
- try {
1838
- this.editor.setText(commandText);
1839
- this.submit(); // existing history, permission and command-dispatch boundary
1840
- } finally {
1841
- this.editor.setText(consumeDraft ? '' : remaining.text);
1842
- if (!consumeDraft) this.setCursorOffset(remaining.cursor);
1843
- this.completion = null;
1844
- this.scheduleDraw();
1845
- }
1846
- }
1847
-
1848
- acceptCompletion() {
1849
- const item = this.completion.items[this.selected];
1850
- if (!item) { this.completion = null; return; }
1851
- const applied = applyCompletion(
1852
- this.editor.getText(), this.cursorOffset(), this.completion, item
1853
- );
1854
- this.editor.setText(applied.text);
1855
- // setText parks the cursor at the end; put it back where the insert ended.
1856
- this.setCursorOffset(applied.cursor);
1857
- this.completion = null;
1858
- this.refreshCompletion();
1859
- }
1860
-
1861
- setCursorOffset(offset) {
1862
- // Convert completion's UTF-16 offset back into the editor's code-point
1863
- // column, never splitting a surrogate pair or moving to the wrong row.
1864
- let remaining = Math.max(0, Number.isFinite(offset) ? offset : 0);
1865
- for (let index = 0; index < this.editor.lines.length; index++) {
1866
- const line = this.editor.lines[index];
1867
- const units = line.join('').length;
1868
- if (remaining <= units || index === this.editor.lines.length - 1) {
1869
- let column = 0;
1870
- let consumed = 0;
1871
- while (column < line.length && consumed + line[column].length <= remaining) {
1872
- consumed += line[column].length;
1873
- column++;
1874
- }
1875
- this.editor.line = index;
1876
- this.editor.col = column;
1877
- return;
1878
- }
1879
- remaining -= units + 1;
1880
- }
1881
- }
1882
-
1883
- // -------------------------------------------------------------------------
1884
- // Drawing
1885
- // -------------------------------------------------------------------------
1886
-
1887
- /** Preview pending input without falsely adding unsent text to the transcript. */
1888
- queuedPreviewRows(width) {
1889
- if (this.queue.length === 0) return [];
1890
- const last = this.queue[this.queue.length - 1];
1891
- const text = typeof last === 'string' ? last
1892
- : last && typeof last.text === 'string' ? last.text : 'pending action';
1893
- const prefix = ` Queued (${this.queue.length}): `;
1894
- const available = Math.max(0, width - visibleWidth(prefix) - 2);
1895
- // Do not reformat megabyte-sized pastes on every running-turn redraw.
1896
- const preview = safeDisplay(text.slice(0, 160).replace(/\s+/g, ' ').trim());
1897
- return [dim(prefix + truncate(preview, available, GLYPHS.ellipsis))];
1898
- }
1899
-
1900
- /**
1901
- * Clamp every row so the terminal can never wrap one of them.
1902
- *
1903
- * THE invariant of the live region. erase() walks back up `cursorRow` rows and
1904
- * clears with \x1b[J, and both numbers are LOGICAL row counts. A row wider
1905
- * than the terminal occupies TWO physical rows, so the walk lands one row too
1906
- * low and \x1b[J then clears from the middle of the block — leaving the rows
1907
- * above it on screen as debris. That is the doubled hint row and the trail of
1908
- * half-drawn glyphs in the reported screenshot.
1909
- *
1910
- * Measuring correctly is necessary but not sufficient: every glyph in GLYPHS is
1911
- * East Asian Ambiguous (see text.js), so the measurement can legitimately
1912
- * disagree with the terminal by a column. Cutting to width - 1 makes a wrap
1913
- * impossible whatever the measurement says, and leaves the last column free so
1914
- * a row that lands exactly on the edge cannot trip the terminal's deferred-wrap
1915
- * state either.
1916
- *
1917
- * truncate() is escape-aware and closes an open SGR at the cut, so a clamped
1918
- * row cannot leak colour into the row below.
1919
- */
1920
- clampRows(rows, width) {
1921
- const limit = Math.max(1, width - 1);
1922
- return rows.map((row) => (visibleWidth(row) <= limit ? row : truncate(row, limit, '')));
1923
- }
1924
-
1925
- /** Remove everything this prompt drew, leaving the cursor where it started. */
1926
- erase() {
1927
- // Nothing of ours is on the terminal in stage mode — the band is painted by
1928
- // a diff and the previous frame is a row array, not screen state. Walking
1929
- // up and clearing here would erase rows the Stage owns and then paint over
1930
- // them, which is the collision this method exists to prevent.
1931
- if (this.surface) return;
1932
- if (this.drawnRows === 0) {
1933
- // Nothing of OURS is on screen — but the caret may still be sitting at a
1934
- // non-zero column, because whoever wrote last left it there. Writing the
1935
- // block from there puts its first row at that offset, which is how a
1936
- // second `▏` appeared beside the first on the same row. Returning to
1937
- // column 0 costs one byte and removes the whole class.
1938
- this.out.write('\r');
1939
- return;
1940
- }
1941
- if (this.cursorRow > 0) this.out.write(`\x1b[${this.cursorRow}A`);
1942
- this.out.write('\r\x1b[J');
1943
- this.drawnRows = 0;
1944
- this.cursorRow = 0;
1945
- }
1946
-
1947
- draw() {
1948
- if (this.resizeTimer) return;
1949
- if (!this.active) return;
1950
- this.erase();
1951
-
1952
- const width = this.width();
1953
- if (this.layer) return this.drawLayer(width);
1954
-
1955
- // The input is a BLOCK, not a line.
1956
- //
1957
- // It used to be a bare `▸ ` prefix, so the place the user types looked like
1958
- // one more row of shell output among all the others. opencode gives its
1959
- // prompt a left border in the agent's colour and a filled surface
1960
- // (component/prompt/index.tsx:1353), which is what makes the input read as a
1961
- // surface you are writing INTO. Every row of the block is inset by the same
1962
- // gutter, so the caret column is a constant rather than a special case for
1963
- // row 0 — which is also one fewer thing for erase() to get wrong.
1964
- // Reserve one editor cell for the caret. The left bar and gutter are
1965
- // consumed by barBlock; the remaining full-width body is not all editable.
1966
- // This prevents a full sentence from placing the cursor beyond the fill.
1967
- const { boxWidth, inset, editorWidth } = composerGeometry(
1968
- width, visibleWidth(GLYPHS.barHeavy || GLYPHS.bar), GUTTER
1969
- );
1970
- const inner = editorWidth;
1971
- const layout = this.editor.render(editorWidth, '');
1972
-
1973
- // Scroll the editor internally rather than growing without bound: keep a
1974
- // window of MAX_PROMPT_ROWS that always contains the caret.
1975
- const start = Math.max(0, Math.min(layout.cursorRow - MAX_PROMPT_ROWS + 1,
1976
- layout.rows.length - MAX_PROMPT_ROWS));
1977
- const top = Math.max(0, start);
1978
- const window = layout.rows.slice(top, top + MAX_PROMPT_ROWS);
1979
- const caretRow = layout.cursorRow - top;
1980
- let body = window.slice();
1981
-
1982
- if (!this.editor.isEmpty) {
1983
- body = body.map((line) => {
1984
- if (typeof line !== 'string' || !line.includes('[Image ')) return line;
1985
- return line.replace(/\[Image (\d+)\]/g, (_m, num) => {
1986
- return paint('warn', bold(`[Image ${num}]`));
1574
+ }
1575
+ moveSelection(direction) {
1576
+ const count = Array.isArray(this.completion?.items) ? this.completion.items.length : 0;
1577
+ if (count === 0)
1578
+ return;
1579
+ this.selected = (((this.selected + direction) % count) + count) % count;
1580
+ }
1581
+ moveSelectionClamped(delta) {
1582
+ const count = Array.isArray(this.completion?.items) ? this.completion.items.length : 0;
1583
+ if (count === 0)
1584
+ return;
1585
+ this.selected = Math.max(0, Math.min(count - 1, this.selected + delta));
1586
+ }
1587
+ submitPickedCommand(value) {
1588
+ this.completion = null;
1589
+ this.editor.setText(value);
1590
+ this.submit();
1591
+ }
1592
+ runInlineSlashSelection(value) {
1593
+ const trigger = this.completion;
1594
+ if (!trigger || trigger.kind === 'file' || !trigger.inline) {
1595
+ this.submitPickedCommand(value);
1596
+ return;
1597
+ }
1598
+ const currentText = this.editor.getText();
1599
+ const currentCursor = this.cursorOffset();
1600
+ let remaining;
1601
+ try {
1602
+ remaining = removeInlineSlashToken(currentText, currentCursor, trigger);
1603
+ }
1604
+ catch {
1605
+ this.notice = 'The command text changed. Reopen the / menu and select again.';
1606
+ this.completion = null;
1607
+ this.scheduleDraw();
1608
+ return;
1609
+ }
1610
+ const consumeDraft = isInlineSkillInvocation(value) && remaining.text.trim().length > 0;
1611
+ const commandText = consumeDraft ? `${value} ${remaining.text.trim()}` : value;
1612
+ if (this.busy && this.queue.length >= 32 && !/^\/(?:stop|interrupt)$/i.test(commandText)) {
1613
+ this.notice = '32 queued messages: command not submitted; your draft is unchanged.';
1614
+ this.scheduleDraw();
1615
+ return;
1616
+ }
1617
+ this.completion = null;
1618
+ try {
1619
+ this.editor.setText(commandText);
1620
+ this.submit();
1621
+ }
1622
+ finally {
1623
+ this.editor.setText(consumeDraft ? '' : remaining.text);
1624
+ if (!consumeDraft)
1625
+ this.setCursorOffset(remaining.cursor);
1626
+ this.completion = null;
1627
+ this.scheduleDraw();
1628
+ }
1629
+ }
1630
+ acceptCompletion() {
1631
+ if (!this.completion)
1632
+ return;
1633
+ const item = this.completion.items[this.selected];
1634
+ if (!item) {
1635
+ this.completion = null;
1636
+ return;
1637
+ }
1638
+ const applied = applyCompletion(this.editor.getText(), this.cursorOffset(), this.completion, item);
1639
+ this.editor.setText(applied.text);
1640
+ this.setCursorOffset(applied.cursor);
1641
+ this.completion = null;
1642
+ this.refreshCompletion();
1643
+ }
1644
+ setCursorOffset(offset) {
1645
+ let remaining = Math.max(0, Number.isFinite(offset) ? offset : 0);
1646
+ for (let index = 0; index < this.editor.lines.length; index++) {
1647
+ const line = this.editor.lines[index] ?? [];
1648
+ const units = line.join('').length;
1649
+ if (remaining <= units || index === this.editor.lines.length - 1) {
1650
+ let column = 0;
1651
+ let consumed = 0;
1652
+ while (column < line.length && consumed + (line[column]?.length ?? 0) <= remaining) {
1653
+ consumed += line[column]?.length ?? 0;
1654
+ column++;
1655
+ }
1656
+ this.editor.line = index;
1657
+ this.editor.col = column;
1658
+ return;
1659
+ }
1660
+ remaining -= units + 1;
1661
+ }
1662
+ }
1663
+ // -------------------------------------------------------------------------
1664
+ // Drawing
1665
+ // -------------------------------------------------------------------------
1666
+ queuedPreviewRows(width) {
1667
+ if (this.queue.length === 0)
1668
+ return [];
1669
+ const last = this.queue[this.queue.length - 1];
1670
+ const text = typeof last === 'string' ? last
1671
+ : last && typeof last.text === 'string' ? last.text : 'pending action';
1672
+ const prefix = ` Queued (${this.queue.length}): `;
1673
+ const available = Math.max(0, width - visibleWidth(prefix) - 2);
1674
+ const preview = safeDisplay(text.slice(0, 160).replace(/\s+/g, ' ').trim());
1675
+ return [dim(prefix + truncate(preview, available, GLYPHS.ellipsis))];
1676
+ }
1677
+ clampRows(rows, width) {
1678
+ const limit = Math.max(1, width - 1);
1679
+ return rows.map((row) => (visibleWidth(row) <= limit ? row : truncate(row, limit, '')));
1680
+ }
1681
+ erase() {
1682
+ if (this.surface)
1683
+ return;
1684
+ if (this.drawnRows === 0) {
1685
+ this.out.write('\r');
1686
+ return;
1687
+ }
1688
+ if (this.cursorRow > 0)
1689
+ this.out.write(`\x1b[${this.cursorRow}A`);
1690
+ this.out.write('\r\x1b[J');
1691
+ this.drawnRows = 0;
1692
+ this.cursorRow = 0;
1693
+ }
1694
+ draw() {
1695
+ if (this.resizeTimer)
1696
+ return;
1697
+ if (!this.active)
1698
+ return;
1699
+ this.erase();
1700
+ const width = this.width();
1701
+ if (this.layer) {
1702
+ this.drawLayer(width);
1703
+ return;
1704
+ }
1705
+ const { boxWidth, inset, editorWidth } = composerGeometry(width, visibleWidth(GLYPHS.barHeavy || GLYPHS.bar), GUTTER);
1706
+ const inner = editorWidth;
1707
+ const layout = this.editor.render(editorWidth, '');
1708
+ const start = Math.max(0, Math.min(layout.cursorRow - MAX_PROMPT_ROWS + 1, layout.rows.length - MAX_PROMPT_ROWS));
1709
+ const top = Math.max(0, start);
1710
+ const windowRows = layout.rows.slice(top, top + MAX_PROMPT_ROWS);
1711
+ const caretRow = layout.cursorRow - top;
1712
+ let body = windowRows.slice();
1713
+ if (!this.editor.isEmpty) {
1714
+ body = body.map((line) => {
1715
+ if (typeof line !== 'string' || !line.includes('[Image '))
1716
+ return line;
1717
+ return line.replace(/\[Image (\d+)\]/g, (_m, num) => {
1718
+ return paint('warn', bold(`[Image ${num}]`));
1719
+ });
1720
+ });
1721
+ }
1722
+ if (this.editor.isEmpty && !this.completion) {
1723
+ const idle = fitHints([`try "${this.example}"`, '/ commands', '@ files', '^V image'], Math.max(8, inner), 'ask anything');
1724
+ body = [dim(this.busy ? 'type to queue a message…' : idle)];
1725
+ }
1726
+ const agent = this.completion ? null : this.agentRow(inner);
1727
+ if (agent)
1728
+ body = body.concat(['', agent]);
1729
+ const rows = Number(this.out && this.out.rows);
1730
+ const roomy = !Number.isFinite(rows) || rows >= ROOMY_TERMINAL_ROWS;
1731
+ const padTop = (!Number.isFinite(rows) || rows >= CRAMPED_TERMINAL_ROWS) ? PROMPT_PAD_TOP : 0;
1732
+ const padBottom = roomy ? PROMPT_PAD_BOTTOM : 0;
1733
+ const padded = new Array(padTop).fill('')
1734
+ .concat(body, new Array(padBottom).fill(''));
1735
+ const boxRows = barBlock(padded, {
1736
+ width: boxWidth,
1737
+ role: this.busy ? 'accent' : 'user',
1738
+ filled: true,
1739
+ surface: 'surface',
1740
+ punctuate: false
1987
1741
  });
1988
- });
1989
- }
1990
-
1991
- if (this.editor.isEmpty && !this.completion) {
1992
- const idle = fitHints([`try "${this.example}"`, '/ commands', '@ files', '^V image'], Math.max(8, inner), 'ask anything');
1993
- body = [dim(this.busy ? 'type to queue a message…' : idle)];
1994
- }
1995
-
1996
- // The model line lives INSIDE the box, as its last row — except while a
1997
- // completion picker is open. The suggestions belong to the text being
1998
- // typed, and an ambient status row wedged between the two breaks that
1999
- // connection for no gain; opencode floats its autocomplete directly against
2000
- // the input for the same reason.
2001
- //
2002
- // A blank row separates the two. Without it the box is two lines of text
2003
- // touching, which reads as a list; the reference leaves a row of space and
2004
- // that is most of what makes it read as a surface you are typing into.
2005
- const agent = this.completion ? null : this.agentRow(inner);
2006
- if (agent) body = body.concat(['', agent]);
2007
-
2008
- // Air at the top of the surface and at the bottom, with the caret moved down
2009
- // to match. The box is the thing the user is about to type into; it earns
2010
- // the room.
2011
- const rows = Number(this.out && this.out.rows);
2012
- const roomy = !Number.isFinite(rows) || rows >= ROOMY_TERMINAL_ROWS;
2013
- const padTop = (!Number.isFinite(rows) || rows >= CRAMPED_TERMINAL_ROWS) ? PROMPT_PAD_TOP : 0;
2014
- const padBottom = roomy ? PROMPT_PAD_BOTTOM : 0;
2015
-
2016
- const padded = new Array(padTop).fill('')
2017
- .concat(body, new Array(padBottom).fill(''));
2018
- const boxRows = barBlock(padded, {
2019
- width: boxWidth,
2020
- role: this.busy ? 'accent' : 'user',
2021
- filled: true,
2022
- surface: 'surface',
2023
- punctuate: false
2024
- });
2025
-
2026
- const usageCardRows = this.usageCard ? renderUsageCardRows(this.usageCard, boxWidth)
2027
- : this.statusCard !== null ? this.statusCardRows(boxWidth) : [];
2028
- const planRows = this.planRows(width);
2029
- const pickerRows = this.completion ? this.pickerRows(width) : [];
2030
- this.pickerLayout = this.completion ? {
2031
- pickerStart: usageCardRows.length + planRows.length + boxRows.length,
2032
- pickerCount: pickerRows.length,
2033
- totalPromptRows: 0
2034
- } : null;
2035
- const queuedRows = this.queuedPreviewRows(width);
2036
- const cleanNotice = this.notice ? this.sanitizeSingleLine(this.notice) : '';
2037
- const noticeRows = cleanNotice ? [dim(` ${cleanNotice}`)] : [];
2038
-
2039
- // And a row of air between the box and the footer. The picker and a notice
2040
- // belong to the input and stay welded to it — opencode floats its
2041
- // autocomplete directly against the prompt for the same reason — so the gap
2042
- // goes after them, immediately above the status row.
2043
- const status = this.statusRow(width);
2044
- const gap = status.length > 0 ? new Array(FOOTER_GAP).fill('') : [];
2045
-
2046
- const all = this.clampRows(
2047
- usageCardRows.concat(planRows, boxRows, pickerRows, queuedRows, noticeRows, gap, status), width
2048
- );
2049
- if (this.pickerLayout) this.pickerLayout.totalPromptRows = all.length;
2050
-
2051
- // Park the cursor where the user is typing, not at the end of the picker.
2052
- const availableWidth = this.surface?.composeAvailableWidth
2053
- ? this.surface.composeAvailableWidth()
2054
- : sessionMainWidth(this.surface?.width || terminalWidth(), false, this.surface?.env);
2055
- const positioned = this.surface
2056
- ? (this.surface.homeInfo ? centerRows(all, this.surface.width) : sessionRows(all, availableWidth))
2057
- : { rows: all, inset: 0 };
2058
- this.present(positioned.rows, usageCardRows.length + planRows.length + caretRow + padTop, layout.cursorCol + inset + positioned.inset);
2059
- }
2060
-
2061
- /**
2062
- * Put the composed block on screen.
2063
- *
2064
- * The two draw paths used to end with the same eleven lines of cursor
2065
- * arithmetic; extracting it is what lets the Stage substitute itself for
2066
- * stdout without either path knowing. In stage mode the rows are handed to
2067
- * the surface, which stacks the transcript viewport above them and paints the
2068
- * whole band in one diff — so drawnRows/cursorRow stay at zero, because
2069
- * nothing of ours is on the terminal for erase() to walk back over.
2070
- */
2071
- present(all, caretRow, caretCol) {
2072
- const rows = Array.isArray(all) ? all : [];
2073
- const maxRow = Math.max(0, rows.length - 1);
2074
- const safeRow = Number.isFinite(caretRow) ? Math.max(0, Math.min(maxRow, Math.floor(caretRow))) : 0;
2075
- const safeCol = Number.isFinite(caretCol) ? Math.max(0, Math.floor(caretCol)) : 0;
2076
- const hideCursor = Boolean(this.busy && this.editor.isEmpty);
2077
- if (this.surface) {
2078
- this.drawnRows = 0;
2079
- this.cursorRow = 0;
2080
- this.surface.present(rows, { row: safeRow, col: safeCol, hideCursor,
2081
- modal: Boolean(this.layer), inline: Boolean(this.layer && !isStartupDialog(this.surface)) });
2082
- return;
2083
- }
2084
-
2085
- this.out.write(rows.join('\n'));
2086
- this.drawnRows = rows.length;
2087
-
2088
- const below = rows.length - 1 - safeRow;
2089
- if (below > 0) this.out.write(`\x1b[${below}A`);
2090
- this.cursorRow = safeRow;
2091
- this.out.write('\r');
2092
- if (safeCol > 0) this.out.write(`\x1b[${safeCol}C`);
2093
- if (hideCursor) {
2094
- this.out.write('\x1b[?25l');
2095
- } else {
2096
- this.out.write('\x1b[?25h');
2097
- }
2098
- }
2099
-
2100
- /**
2101
- * Attach a Stage surface. From here on the prompt composes rows and this
2102
- * decides where they land.
2103
- */
2104
- attachSurface(surface) {
2105
- this.surface = surface || null;
2106
- if (!surface) return;
2107
- surface.onDirty = () => this.scheduleDraw();
2108
- }
2109
-
2110
- /**
2111
- * Put a finished block into the transcript.
2112
- *
2113
- * `produce` must be a pure function of width — a stage frame is re-rendered
2114
- * on every resize, so anything it closes over must already be resolved. In
2115
- * scrollback mode it is called once, immediately, and printed.
2116
- */
2117
- commit(kind, produce) {
2118
- // clampRows() guarded the live region and nothing else, so a committed
2119
- // block could still be exactly terminal-width, wrap, and desynchronise the
2120
- // row count erase() walks back. The net belongs on both paths, not one.
2121
- const clamped = (width) => this.clampRows(produce(width), width);
2122
- if (this.surface) { this.surface.commit(kind, clamped); return; }
2123
- this.erase();
2124
- this.out.write(clamped(this.width()).join('\n') + '\n');
2125
- }
2126
-
2127
- /** The live region while a dialog is up: the panel, then the status row. */
2128
- drawLayer(width) {
2129
- const preferredHeight = typeof this.layer.preferredHeight === 'function'
2130
- ? this.layer.preferredHeight()
2131
- : 14;
2132
- if (this.layer.messageActions && this.surface?.presentMessageActions) {
2133
- const availableWidth = this.surface.composeAvailableWidth
2134
- ? this.surface.composeAvailableWidth()
2135
- : sessionMainWidth(this.surface.width, false, this.surface.env);
2136
- const requestedWidth = typeof this.layer.preferredWidth === 'function'
2137
- ? this.layer.preferredWidth(Math.max(8, availableWidth - 3))
2138
- : (this.layer.width || 64);
2139
- const panelWidth = dialogWidth(Math.max(8, availableWidth - 3), requestedWidth);
2140
- const panel = panelRows(this.layer, panelWidth, preferredHeight);
2141
- this.surface.presentMessageActions(panel, this.layer);
2142
- return;
2143
- }
2144
- if (isStartupDialog(this.surface)) {
2145
- const view = startupDialogView(this.layer, this.surface.width, this.surface.stage.maxHeight);
2146
- return this.present(view.rows, view.caretRow, view.caretCol);
2147
- }
2148
- const inline = this.surface && !this.surface.homeInfo;
2149
- const availableWidth = inline
2150
- ? (this.surface.composeAvailableWidth
2151
- ? this.surface.composeAvailableWidth()
2152
- : sessionMainWidth(this.surface.width, false, this.surface.env))
2153
- : width;
2154
- const panelWidth = dialogWidth(availableWidth, this.layer.width || 64);
2155
- const stageMax = this.surface?.stage?.maxHeight || this.out?.rows || 24;
2156
- const statusReserve = 2; // status row + margin
2157
- const availableDialogRows = Math.max(4, stageMax - statusReserve);
2158
- const maxHeight = dialogHeight(availableDialogRows, preferredHeight);
2159
- const panel = panelRows(this.layer, panelWidth, maxHeight);
2160
- const status = this.statusRow(width);
2161
- const all = this.clampRows(panel.concat(status), width);
2162
-
2163
- // panelRows() called body(), which is where a layer publishes its cursor.
2164
- const cursor = this.layer.cursor;
2165
- const centered = this.surface ? centerRows(all, availableWidth) : { rows: all, inset: 0 };
2166
- const stageHeight = this.surface?.stage?.height || this.out?.rows || all.length;
2167
- const outRows = Number.isFinite(this.out?.rows) && this.out.rows > 0
2168
- ? Math.floor(this.out.rows)
2169
- : stageHeight;
2170
- this.layer.panelGeometry = {
2171
- inset: centered.inset,
2172
- // Anchor at the panel's last body row above the bottom border and status rows (0-based screen row).
2173
- optionScreenRow: Math.max(0, outRows - status.length - 2)
2174
- };
2175
- this.present(centered.rows, cursor ? 1 + cursor.y : 0,
2176
- (cursor ? 2 + cursor.x : 0) + centered.inset);
2177
- }
2178
-
2179
- pickerRows(width) {
2180
- const rows = renderPicker(this.completion.items, this.selected, width);
2181
- const labelWidth = Math.min(
2182
- 36,
2183
- rows.reduce((max, row) => Math.max(max, visibleWidth(row.label)), 0)
2184
- );
2185
-
2186
- const drawn = rows.map((row) => {
2187
- const marker = row.selected ? paint('accent', GLYPHS.arrow) : ' ';
2188
- const label = truncate(row.label, labelWidth, GLYPHS.ellipsis);
2189
- const padded = label + ' '.repeat(Math.max(0, labelWidth - visibleWidth(label)));
2190
- const name = row.selected ? bold(paint('ink', padded)) : paint('ink', padded);
2191
- const description = row.description
2192
- ? dim(' ' + truncate(row.description, Math.max(0, width - labelWidth - 8), GLYPHS.ellipsis))
2193
- : '';
2194
- return ` ${marker} ${name}${description}`;
2195
- });
2196
-
2197
- // Count against everything that MATCHED, not against the capped array the
2198
- // picker happens to hold. Reporting the capped figure told the user there
2199
- // were 42 more entries when 107 were reachable by scrolling.
2200
- const matched = this.completion.total || this.completion.items.length;
2201
- const hidden = matched - drawn.length;
2202
- if (hidden > 0) drawn.push(dim(` ${GLYPHS.ellipsis} ${hidden} more`));
2203
- if (this.completion?.inline && (this.completion.kind === 'command' || this.completion.kind === 'command-argument')) {
2204
- drawn.push(dim(' ' + truncate('Enter run · Esc dismiss · draft protected', Math.max(0, width - 5))));
2205
- }
2206
- return drawn;
2207
- }
1742
+ const usageCardRows = this.usageCard ? renderUsageCardRows(this.usageCard, boxWidth)
1743
+ : this.statusCard !== null ? this.statusCardRows(boxWidth) : [];
1744
+ const planRows = this.planRows(width);
1745
+ const pickerRows = this.completion ? this.pickerRows(width) : [];
1746
+ this.pickerLayout = this.completion ? {
1747
+ pickerStart: usageCardRows.length + planRows.length + boxRows.length,
1748
+ pickerCount: pickerRows.length,
1749
+ totalPromptRows: 0
1750
+ } : null;
1751
+ const queuedRows = this.queuedPreviewRows(width);
1752
+ const cleanNotice = this.notice ? this.sanitizeSingleLine(this.notice) : '';
1753
+ const noticeRows = cleanNotice ? [dim(` ${cleanNotice}`)] : [];
1754
+ const status = this.statusRow(width);
1755
+ const gap = status.length > 0 ? new Array(FOOTER_GAP).fill('') : [];
1756
+ const all = this.clampRows(usageCardRows.concat(planRows, boxRows, pickerRows, queuedRows, noticeRows, gap, status), width);
1757
+ if (this.pickerLayout)
1758
+ this.pickerLayout.totalPromptRows = all.length;
1759
+ const availableWidth = this.surface?.composeAvailableWidth
1760
+ ? this.surface.composeAvailableWidth()
1761
+ : sessionMainWidth(this.surface?.width || terminalWidth(), false, this.surface?.env);
1762
+ const positioned = this.surface
1763
+ ? (this.surface.homeInfo ? centerRows(all, this.surface.width) : sessionRows(all, availableWidth))
1764
+ : { rows: all, inset: 0 };
1765
+ this.present(positioned.rows, usageCardRows.length + planRows.length + caretRow + padTop, layout.cursorCol + inset + positioned.inset);
1766
+ }
1767
+ present(all, caretRow, caretCol) {
1768
+ const rows = Array.isArray(all) ? all : [];
1769
+ const maxRow = Math.max(0, rows.length - 1);
1770
+ const safeRow = Number.isFinite(caretRow) ? Math.max(0, Math.min(maxRow, Math.floor(caretRow))) : 0;
1771
+ const safeCol = Number.isFinite(caretCol) ? Math.max(0, Math.floor(caretCol)) : 0;
1772
+ const hideCursor = Boolean(this.busy && this.editor.isEmpty);
1773
+ if (this.surface) {
1774
+ this.drawnRows = 0;
1775
+ this.cursorRow = 0;
1776
+ this.surface.present(rows, {
1777
+ row: safeRow,
1778
+ col: safeCol,
1779
+ hideCursor,
1780
+ modal: Boolean(this.layer),
1781
+ inline: Boolean(this.layer && !isStartupDialog(this.surface))
1782
+ });
1783
+ return;
1784
+ }
1785
+ this.out.write(rows.join('\n'));
1786
+ this.drawnRows = rows.length;
1787
+ const below = rows.length - 1 - safeRow;
1788
+ if (below > 0)
1789
+ this.out.write(`\x1b[${below}A`);
1790
+ this.cursorRow = safeRow;
1791
+ this.out.write('\r');
1792
+ if (safeCol > 0)
1793
+ this.out.write(`\x1b[${safeCol}C`);
1794
+ if (hideCursor) {
1795
+ this.out.write('\x1b[?25l');
1796
+ }
1797
+ else {
1798
+ this.out.write('\x1b[?25h');
1799
+ }
1800
+ }
1801
+ attachSurface(surface) {
1802
+ this.surface = surface || null;
1803
+ if (!surface)
1804
+ return;
1805
+ surface.onDirty = () => this.scheduleDraw();
1806
+ }
1807
+ commit(kind, produce) {
1808
+ const clamped = (width) => this.clampRows(produce(width), width);
1809
+ if (this.surface) {
1810
+ this.surface.commit(kind, clamped);
1811
+ return;
1812
+ }
1813
+ this.erase();
1814
+ this.out.write(clamped(this.width()).join('\n') + '\n');
1815
+ }
1816
+ drawLayer(width) {
1817
+ const preferredHeight = typeof this.layer.preferredHeight === 'function'
1818
+ ? this.layer.preferredHeight()
1819
+ : 14;
1820
+ if (this.layer.messageActions && this.surface?.presentMessageActions) {
1821
+ const availableWidth = this.surface.composeAvailableWidth
1822
+ ? this.surface.composeAvailableWidth()
1823
+ : sessionMainWidth(this.surface.width, false, this.surface.env);
1824
+ const requestedWidth = typeof this.layer.preferredWidth === 'function'
1825
+ ? this.layer.preferredWidth(Math.max(8, availableWidth - 3))
1826
+ : (this.layer.width || 64);
1827
+ const panelWidth = dialogWidth(Math.max(8, availableWidth - 3), requestedWidth);
1828
+ const panel = panelRows(this.layer, panelWidth, preferredHeight);
1829
+ this.surface.presentMessageActions(panel, this.layer);
1830
+ return;
1831
+ }
1832
+ if (isStartupDialog(this.surface)) {
1833
+ const view = startupDialogView(this.layer, this.surface.width, this.surface.stage.maxHeight);
1834
+ this.present(view.rows, view.caretRow, view.caretCol);
1835
+ return;
1836
+ }
1837
+ const inline = Boolean(this.surface && !this.surface.homeInfo);
1838
+ const availableWidth = inline
1839
+ ? (this.surface.composeAvailableWidth
1840
+ ? this.surface.composeAvailableWidth()
1841
+ : sessionMainWidth(this.surface.width, false, this.surface.env))
1842
+ : width;
1843
+ const panelWidth = dialogWidth(availableWidth, this.layer.width || 64);
1844
+ const stageMax = this.surface?.stage?.maxHeight || this.out?.rows || 24;
1845
+ const statusReserve = 2;
1846
+ const availableDialogRows = Math.max(4, stageMax - statusReserve);
1847
+ const maxHeight = dialogHeight(availableDialogRows, preferredHeight);
1848
+ const panel = panelRows(this.layer, panelWidth, maxHeight);
1849
+ const status = this.statusRow(width);
1850
+ const all = this.clampRows(panel.concat(status), width);
1851
+ const cursor = this.layer.cursor;
1852
+ const centered = this.surface ? centerRows(all, availableWidth) : { rows: all, inset: 0 };
1853
+ const stageHeight = this.surface?.stage?.height || this.out?.rows || all.length;
1854
+ const outRows = Number.isFinite(this.out?.rows) && this.out.rows > 0
1855
+ ? Math.floor(this.out.rows)
1856
+ : stageHeight;
1857
+ this.layer.panelGeometry = {
1858
+ inset: centered.inset,
1859
+ optionScreenRow: Math.max(0, outRows - status.length - 2)
1860
+ };
1861
+ this.present(centered.rows, cursor ? 1 + cursor.y : 0, (cursor ? 2 + cursor.x : 0) + centered.inset);
1862
+ }
1863
+ pickerRows(width) {
1864
+ if (!this.completion)
1865
+ return [];
1866
+ const rows = renderPicker(this.completion.items, this.selected, width);
1867
+ const labelWidth = Math.min(36, rows.reduce((max, row) => Math.max(max, visibleWidth(row.label)), 0));
1868
+ const drawn = rows.map((row) => {
1869
+ const marker = row.selected ? paint('accent', GLYPHS.arrow) : ' ';
1870
+ const label = truncate(row.label, labelWidth, GLYPHS.ellipsis);
1871
+ const padded = label + ' '.repeat(Math.max(0, labelWidth - visibleWidth(label)));
1872
+ const name = row.selected ? bold(paint('ink', padded)) : paint('ink', padded);
1873
+ const description = row.description
1874
+ ? dim(' ' + truncate(row.description, Math.max(0, width - labelWidth - 8), GLYPHS.ellipsis))
1875
+ : '';
1876
+ return ` ${marker} ${name}${description}`;
1877
+ });
1878
+ const matched = this.completion.total || this.completion.items.length;
1879
+ const hidden = matched - drawn.length;
1880
+ if (hidden > 0)
1881
+ drawn.push(dim(` ${GLYPHS.ellipsis} ${hidden} more`));
1882
+ if (this.completion.kind !== 'file' && this.completion.inline) {
1883
+ drawn.push(dim(' ' + truncate('Enter run · Esc dismiss · draft protected', Math.max(0, width - 5))));
1884
+ }
1885
+ return drawn;
1886
+ }
2208
1887
  }
2209
-
2210
- /**
2211
- * Hint line for the session header — the keys that are not discoverable.
2212
- *
2213
- * FITTED to the terminal. The full list is 140 columns; printed unconditionally
2214
- * it wrapped on any terminal narrower than that, which is how the very first
2215
- * thing a user sees ended up broken across two rows mid-word. Fragments are
2216
- * dropped from the right — least important first — rather than the line being
2217
- * truncated, because a hint clipped mid-key is worse than a missing one.
2218
- */
2219
1888
  export function keyHints(width = terminalWidth()) {
2220
- const parts = [
2221
- 'enter send', 'alt+enter newline', 'ctrl+p palette', '/ commands', '@ files',
2222
- '↑ history', 'tab complete', 'esc interrupt', 'ctrl+o expand'
2223
- ];
2224
- const separator = ` ${GLYPHS.dot} `;
2225
- const kept = parts.slice();
2226
- // Reserve a column, for the same reason every drawn row does: a line landing
2227
- // exactly on the margin trips the terminal's deferred wrap.
2228
- while (kept.length > 1 && visibleWidth(kept.join(separator)) > width - 1) kept.pop();
2229
- return HAS_COLOR
2230
- ? kept.map((part) => dim(part)).join(dim(separator))
2231
- : kept.join(separator);
1889
+ const parts = [
1890
+ 'enter send', 'alt+enter newline', 'ctrl+p palette', '/ commands', '@ files',
1891
+ '↑ history', 'tab complete', 'esc interrupt', 'ctrl+o expand'
1892
+ ];
1893
+ const separator = ` ${GLYPHS.dot} `;
1894
+ const kept = parts.slice();
1895
+ while (kept.length > 1 && visibleWidth(kept.join(separator)) > width - 1)
1896
+ kept.pop();
1897
+ return HAS_COLOR
1898
+ ? kept.map((part) => dim(part)).join(dim(separator))
1899
+ : kept.join(separator);
2232
1900
  }
2233
-
2234
1901
  export { MAX_VISIBLE };