@causyne/agent 1.20.122 → 1.20.124

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 (518) hide show
  1. package/bin/causyne.js +38 -15
  2. package/docs/SECURITY_REVIEW.md +42 -6
  3. package/package.json +5 -5
  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 +162 -3
  10. package/src/acp/server.js +138 -39
  11. package/src/acp/server.ts +122 -41
  12. package/src/agent/errorClassifier.js +42 -6
  13. package/src/agent/errorClassifier.ts +44 -5
  14. package/src/agent/providerFailure.js +1 -1
  15. package/src/agent/providerFailure.ts +7 -1
  16. package/src/agent/toolArgValidator.js +38 -4
  17. package/src/agent/toolArgValidator.ts +39 -4
  18. package/src/agent/toolTurnIntegrity.js +28 -7
  19. package/src/agent/toolTurnIntegrity.ts +25 -6
  20. package/src/agent/workspaceBoundary.js +30 -4
  21. package/src/agent/workspaceBoundary.ts +32 -4
  22. package/src/agentLoop.js +598 -217
  23. package/src/agentLoop.ts +621 -215
  24. package/src/approvalPolicy.js +28 -1
  25. package/src/approvalPolicy.ts +28 -1
  26. package/src/auditLog.js +641 -48
  27. package/src/auditLog.ts +661 -0
  28. package/src/autoUpdate.js +32 -5
  29. package/src/autoUpdate.ts +27 -5
  30. package/src/backgroundTasks.js +328 -0
  31. package/src/backgroundTasks.ts +339 -0
  32. package/src/benchmarks/codingEval.js +558 -0
  33. package/src/benchmarks/codingEval.ts +628 -0
  34. package/src/benchmarks/planCache.js +115 -134
  35. package/src/benchmarks/planCache.ts +163 -0
  36. package/src/browser/browserRuntime.js +52 -0
  37. package/src/browser/browserRuntime.ts +55 -0
  38. package/src/browser/causyneBrowser.js +884 -10
  39. package/src/browser/causyneBrowser.ts +1042 -32
  40. package/src/browser/searchProviders.js +94 -6
  41. package/src/browser/searchProviders.ts +89 -6
  42. package/src/browser/urlPolicy.js +8 -1
  43. package/src/browser/urlPolicy.ts +7 -1
  44. package/src/browser/workspacePathSafety.js +6 -4
  45. package/src/browser/workspacePathSafety.ts +7 -4
  46. package/src/capabilities.js +18 -17
  47. package/src/capabilities.ts +38 -0
  48. package/src/checkpoints.js +1241 -1127
  49. package/src/checkpoints.ts +1377 -0
  50. package/src/cliMode.js +707 -755
  51. package/src/cliMode.ts +780 -0
  52. package/src/codebase/repoMap.js +656 -0
  53. package/src/codebase/repoMap.ts +664 -0
  54. package/src/commands.js +3651 -2514
  55. package/src/commands.ts +3985 -0
  56. package/src/compiledSkills.js +8052 -8054
  57. package/src/compiledSkills.ts +8078 -0
  58. package/src/config.js +103 -1
  59. package/src/config.ts +110 -1
  60. package/src/configVault.js +29 -2
  61. package/src/configVault.ts +26 -2
  62. package/src/contextManager.js +473 -557
  63. package/src/contextManager.ts +599 -0
  64. package/src/continuum/adapters/antigravity.js +8 -3
  65. package/src/continuum/adapters/antigravity.ts +8 -3
  66. package/src/continuum/sanitizer.js +23 -1
  67. package/src/continuum/sanitizer.ts +23 -1
  68. package/src/continuum/ui/continuumPicker.js +0 -2
  69. package/src/continuum/ui/continuumPicker.ts +0 -2
  70. package/src/continuum/ui/continuumPickerView.js +0 -2
  71. package/src/continuum/ui/continuumPickerView.ts +4 -20
  72. package/src/core/contextCompactor.js +88 -7
  73. package/src/core/contextCompactor.ts +87 -8
  74. package/src/creative/liveBridge.js +3 -2
  75. package/src/creative/liveBridge.ts +4 -2
  76. package/src/creative/studioScripts.js +1 -1
  77. package/src/creative/studioScripts.ts +1 -1
  78. package/src/decideTools.js +7 -2
  79. package/src/decideTools.ts +7 -2
  80. package/src/decisionPolicy.js +10 -2
  81. package/src/decisionPolicy.ts +10 -2
  82. package/src/designPalettes.js +72 -84
  83. package/src/designPalettes.ts +111 -0
  84. package/src/devMode.js +2 -2
  85. package/src/devMode.ts +6 -0
  86. package/src/diffReview.js +370 -0
  87. package/src/diffReview.ts +407 -0
  88. package/src/dynamicCatalogue.js +311 -11
  89. package/src/dynamicCatalogue.ts +331 -11
  90. package/src/embodimentSession.js +143 -154
  91. package/src/embodimentSession.ts +173 -0
  92. package/src/engines/installer.js +60 -29
  93. package/src/engines/installer.ts +73 -22
  94. package/src/enterprisePolicy.js +660 -0
  95. package/src/enterprisePolicy.ts +728 -0
  96. package/src/entrypoint.js +514 -268
  97. package/src/entrypoint.ts +607 -0
  98. package/src/gitSnapshot.js +417 -312
  99. package/src/gitSnapshot.ts +500 -0
  100. package/src/headlessCli.js +324 -13
  101. package/src/headlessCli.ts +321 -12
  102. package/src/hooks.js +247 -26
  103. package/src/hooks.ts +236 -26
  104. package/src/ignoreRules.js +297 -0
  105. package/src/ignoreRules.ts +308 -0
  106. package/src/implementationPlan.js +7 -6
  107. package/src/implementationPlan.ts +8 -6
  108. package/src/infra/atomicWriter.js +92 -19
  109. package/src/infra/atomicWriter.ts +108 -19
  110. package/src/launchIntent.js +13 -2
  111. package/src/launchIntent.ts +13 -2
  112. package/src/licensing/entitlements.js +553 -237
  113. package/src/licensing/entitlements.ts +590 -0
  114. package/src/licensing/policy.js +17 -1
  115. package/src/licensing/policy.ts +31 -0
  116. package/src/lsp/lspCatalog.js +398 -0
  117. package/src/lsp/lspCatalog.ts +452 -0
  118. package/src/lsp/lspClient.js +699 -0
  119. package/src/lsp/lspClient.ts +799 -0
  120. package/src/lsp/lspProtocol.js +121 -0
  121. package/src/lsp/lspProtocol.ts +140 -0
  122. package/src/mcp/mcpClient.js +69 -8
  123. package/src/mcp/mcpClient.ts +66 -9
  124. package/src/mcp/mcpRegistry.js +180 -7
  125. package/src/mcp/mcpRegistry.ts +171 -7
  126. package/src/mcp/mcpSecurity.js +6 -7
  127. package/src/mcp/mcpSecurity.ts +7 -6
  128. package/src/memory/episodicStore.js +2 -5
  129. package/src/memory/episodicStore.ts +2 -5
  130. package/src/memory.js +80 -32
  131. package/src/memory.ts +111 -0
  132. package/src/memoryManager.js +151 -143
  133. package/src/memoryManager.ts +182 -0
  134. package/src/modelCatalogue.js +172 -195
  135. package/src/modelCatalogue.ts +201 -0
  136. package/src/modelIds.js +8 -27
  137. package/src/modelIds.ts +33 -0
  138. package/src/modelVariants.js +600 -0
  139. package/src/modelVariants.ts +663 -0
  140. package/src/observer/evidence.js +5 -1
  141. package/src/observer/evidence.ts +5 -1
  142. package/src/osKeychain.js +17 -9
  143. package/src/osKeychain.ts +14 -9
  144. package/src/outputStore.js +210 -156
  145. package/src/outputStore.ts +321 -0
  146. package/src/planCache.js +3 -6
  147. package/src/planCache.ts +3 -6
  148. package/src/plugins/pluginManager.js +689 -461
  149. package/src/plugins/pluginManager.ts +807 -0
  150. package/src/plugins/pluginRunner.js +82 -37
  151. package/src/plugins/pluginRunner.ts +98 -0
  152. package/src/plugins/pluginSkills.js +47 -9
  153. package/src/plugins/pluginSkills.ts +46 -8
  154. package/src/pluginsFactory/discovery.js +0 -1
  155. package/src/pluginsFactory/discovery.ts +0 -1
  156. package/src/pluginsFactory/templates.js +17 -4
  157. package/src/pluginsFactory/templates.ts +17 -4
  158. package/src/prWorkflow.js +337 -0
  159. package/src/prWorkflow.ts +376 -0
  160. package/src/procSignal.js +1 -2
  161. package/src/procSignal.ts +1 -3
  162. package/src/projectInstructions.js +319 -0
  163. package/src/projectInstructions.ts +361 -0
  164. package/src/providers/acp.js +234 -49
  165. package/src/providers/acp.ts +240 -50
  166. package/src/providers/anthropic.js +152 -47
  167. package/src/providers/anthropic.ts +152 -45
  168. package/src/providers/antigravity.js +565 -354
  169. package/src/providers/antigravity.ts +555 -355
  170. package/src/providers/base.js +9 -2
  171. package/src/providers/base.ts +10 -2
  172. package/src/providers/byokHttp.js +127 -17
  173. package/src/providers/byokHttp.ts +175 -18
  174. package/src/providers/byokStream.js +162 -36
  175. package/src/providers/byokStream.ts +162 -55
  176. package/src/providers/dashscope-byok.js +29 -3
  177. package/src/providers/dashscope-byok.ts +30 -2
  178. package/src/providers/deepseek.js +12 -3
  179. package/src/providers/deepseek.ts +12 -3
  180. package/src/providers/factory.js +41 -0
  181. package/src/providers/factory.ts +42 -0
  182. package/src/providers/gemini.js +74 -22
  183. package/src/providers/gemini.ts +78 -26
  184. package/src/providers/moonshot.js +36 -3
  185. package/src/providers/moonshot.ts +32 -3
  186. package/src/providers/ollama.js +267 -21
  187. package/src/providers/ollama.ts +302 -29
  188. package/src/providers/openai-compatible.js +67 -11
  189. package/src/providers/openai-compatible.ts +78 -17
  190. package/src/providers/openai.js +25 -2
  191. package/src/providers/openai.ts +24 -2
  192. package/src/providers/openrouter.js +233 -66
  193. package/src/providers/openrouter.ts +226 -70
  194. package/src/providers/qwen-byok.js +29 -3
  195. package/src/providers/qwen-byok.ts +30 -2
  196. package/src/providers/wireNormalizer.js +66 -0
  197. package/src/providers/wireNormalizer.ts +64 -0
  198. package/src/providers/xai.js +10 -3
  199. package/src/providers/xai.ts +9 -3
  200. package/src/provisioning/capabilityConsent.js +29 -11
  201. package/src/provisioning/capabilityConsent.ts +42 -0
  202. package/src/provisioning/capabilityProvisioner.js +309 -197
  203. package/src/provisioning/capabilityProvisioner.ts +413 -0
  204. package/src/provisioning/capabilityTools.js +31 -17
  205. package/src/provisioning/capabilityTools.ts +43 -0
  206. package/src/provisioning/npmInstall.js +33 -5
  207. package/src/provisioning/npmInstall.ts +33 -5
  208. package/src/reporting.js +328 -326
  209. package/src/reporting.ts +482 -0
  210. package/src/sandbox.js +37 -0
  211. package/src/sandbox.ts +38 -0
  212. package/src/sessionJournal.js +24 -3
  213. package/src/sessionJournal.ts +18 -3
  214. package/src/sessionStore.js +1 -2
  215. package/src/sessionStore.ts +2 -0
  216. package/src/slopDetector.js +202 -265
  217. package/src/slopDetector.ts +279 -0
  218. package/src/smartToolsUse.js +10 -4
  219. package/src/smartToolsUse.ts +10 -4
  220. package/src/stallGuard.js +10 -3
  221. package/src/stallGuard.ts +9 -3
  222. package/src/taskBuffer.js +91 -40
  223. package/src/taskBuffer.ts +94 -0
  224. package/src/tokenTracker.js +78 -11
  225. package/src/tokenTracker.ts +69 -11
  226. package/src/toolPacks.js +5 -0
  227. package/src/toolPacks.ts +5 -0
  228. package/src/tools/applyPatch.js +610 -0
  229. package/src/tools/applyPatch.ts +661 -0
  230. package/src/tools/archive.js +135 -21
  231. package/src/tools/archive.ts +136 -21
  232. package/src/tools/astryxOracle.js +77 -72
  233. package/src/tools/astryxOracle.ts +95 -0
  234. package/src/tools/axSnapshot.js +127 -147
  235. package/src/tools/axSnapshot.ts +174 -0
  236. package/src/tools/backgroundTask.js +86 -0
  237. package/src/tools/backgroundTask.ts +121 -0
  238. package/src/tools/blenderAutomator.js +434 -390
  239. package/src/tools/blenderAutomator.ts +623 -0
  240. package/src/tools/checkSystemSpecs.js +54 -61
  241. package/src/tools/checkSystemSpecs.ts +73 -0
  242. package/src/tools/clipboard.js +42 -31
  243. package/src/tools/clipboard.ts +61 -0
  244. package/src/tools/codeSearchAst.js +359 -91
  245. package/src/tools/codeSearchAst.ts +399 -0
  246. package/src/tools/codeSearcher.js +179 -37
  247. package/src/tools/codeSearcher.ts +188 -33
  248. package/src/tools/codeTools.js +208 -245
  249. package/src/tools/codeTools.ts +271 -0
  250. package/src/tools/codebaseSearch.js +5 -0
  251. package/src/tools/codebaseSearch.ts +5 -0
  252. package/src/tools/desktopAct.js +185 -197
  253. package/src/tools/desktopAct.ts +257 -0
  254. package/src/tools/dynamicLoader.js +4 -40
  255. package/src/tools/dynamicLoader.ts +13 -0
  256. package/src/tools/executeProceduralMedia.js +117 -86
  257. package/src/tools/executeProceduralMedia.ts +135 -0
  258. package/src/tools/fileTracker.js +74 -0
  259. package/src/tools/fileTracker.ts +94 -0
  260. package/src/tools/fsDelete.js +57 -47
  261. package/src/tools/fsDelete.ts +80 -0
  262. package/src/tools/fsEdit.js +192 -74
  263. package/src/tools/fsEdit.ts +201 -72
  264. package/src/tools/fsMove.js +79 -52
  265. package/src/tools/fsMove.ts +108 -0
  266. package/src/tools/fsRead.js +54 -15
  267. package/src/tools/fsRead.ts +55 -15
  268. package/src/tools/fsSearch.js +5 -0
  269. package/src/tools/fsSearch.ts +5 -0
  270. package/src/tools/fsWrite.js +14 -6
  271. package/src/tools/fsWrite.ts +14 -6
  272. package/src/tools/gameAiBehaviorTree.js +74 -91
  273. package/src/tools/gameAiBehaviorTree.ts +219 -0
  274. package/src/tools/gameAnimationRig.js +128 -147
  275. package/src/tools/gameAnimationRig.ts +215 -0
  276. package/src/tools/gameAssetFetcher.js +403 -441
  277. package/src/tools/gameAssetFetcher.ts +477 -0
  278. package/src/tools/gameAssetHarvester.js +171 -200
  279. package/src/tools/gameAssetHarvester.ts +261 -0
  280. package/src/tools/gameAudioSynth.js +223 -259
  281. package/src/tools/gameAudioSynth.ts +255 -0
  282. package/src/tools/gameBuilder.js +100 -91
  283. package/src/tools/gameBuilder.ts +913 -0
  284. package/src/tools/gameCanvasAudit.js +138 -96
  285. package/src/tools/gameCanvasAudit.ts +157 -0
  286. package/src/tools/gameCinematicSequencer.js +93 -111
  287. package/src/tools/gameCinematicSequencer.ts +165 -0
  288. package/src/tools/gameDataForge.js +115 -118
  289. package/src/tools/gameDataForge.ts +151 -0
  290. package/src/tools/gameDialogueTreeGen.js +125 -156
  291. package/src/tools/gameDialogueTreeGen.ts +159 -0
  292. package/src/tools/gameEconomyBalancer.js +150 -153
  293. package/src/tools/gameEconomyBalancer.ts +186 -0
  294. package/src/tools/gameEntitySpawner.js +91 -108
  295. package/src/tools/gameEntitySpawner.ts +209 -0
  296. package/src/tools/gameLoreForge.js +125 -147
  297. package/src/tools/gameLoreForge.ts +162 -0
  298. package/src/tools/gameQuestArcBuilder.js +105 -144
  299. package/src/tools/gameQuestArcBuilder.ts +147 -0
  300. package/src/tools/gameSceneBuilder.js +143 -149
  301. package/src/tools/gameSceneBuilder.ts +196 -0
  302. package/src/tools/gameShaderForge.js +83 -101
  303. package/src/tools/gameShaderForge.ts +181 -0
  304. package/src/tools/gameTilemapGenerator.js +99 -129
  305. package/src/tools/gameTilemapGenerator.ts +158 -0
  306. package/src/tools/gameUiHudBuilder.js +109 -129
  307. package/src/tools/gameUiHudBuilder.ts +300 -0
  308. package/src/tools/gameVfxEmitterGen.js +86 -89
  309. package/src/tools/gameVfxEmitterGen.ts +133 -0
  310. package/src/tools/gameWebRuntimeInspector.js +153 -86
  311. package/src/tools/gameWebRuntimeInspector.ts +167 -0
  312. package/src/tools/generateMediaViaApi.js +53 -12
  313. package/src/tools/generateMediaViaApi.ts +52 -12
  314. package/src/tools/gitExec.js +133 -86
  315. package/src/tools/gitExec.ts +146 -0
  316. package/src/tools/gitWorktree.js +115 -0
  317. package/src/tools/gitWorktree.ts +150 -0
  318. package/src/tools/godotAutomator.js +417 -394
  319. package/src/tools/godotAutomator.ts +530 -0
  320. package/src/tools/lspCodeIntel.js +217 -0
  321. package/src/tools/lspCodeIntel.ts +260 -0
  322. package/src/tools/manageLocalAiDependencies.js +242 -206
  323. package/src/tools/manageLocalAiDependencies.ts +288 -0
  324. package/src/tools/multiEdit.js +16 -76
  325. package/src/tools/multiEdit.ts +20 -77
  326. package/src/tools/osSandbox.js +152 -15
  327. package/src/tools/osSandbox.ts +148 -15
  328. package/src/tools/palmierAutomator.js +147 -95
  329. package/src/tools/palmierAutomator.ts +171 -0
  330. package/src/tools/pdfReader.js +95 -104
  331. package/src/tools/pdfReader.ts +125 -0
  332. package/src/tools/persistentShell.js +267 -144
  333. package/src/tools/persistentShell.ts +314 -0
  334. package/src/tools/pluginManager.js +84 -72
  335. package/src/tools/pluginManager.ts +109 -0
  336. package/src/tools/printer.js +278 -296
  337. package/src/tools/printer.ts +326 -0
  338. package/src/tools/procTerm.js +96 -83
  339. package/src/tools/procTerm.ts +127 -0
  340. package/src/tools/processList.js +45 -48
  341. package/src/tools/processList.ts +73 -0
  342. package/src/tools/registry.js +298 -286
  343. package/src/tools/registry.ts +486 -0
  344. package/src/tools/repoMap.js +46 -0
  345. package/src/tools/repoMap.ts +66 -0
  346. package/src/tools/subagentOrchestrator.js +404 -348
  347. package/src/tools/subagentOrchestrator.ts +457 -0
  348. package/src/tools/sysRun.js +83 -26
  349. package/src/tools/sysRun.ts +80 -26
  350. package/src/tools/toolForge.js +84 -67
  351. package/src/tools/toolForge.ts +102 -0
  352. package/src/tools/toolPathSafety.js +262 -0
  353. package/src/tools/toolPathSafety.ts +308 -0
  354. package/src/tools/toolScanner.js +28 -0
  355. package/src/tools/toolScanner.ts +29 -0
  356. package/src/tools/toolSelfRepair.js +21 -6
  357. package/src/tools/toolSelfRepair.ts +26 -6
  358. package/src/tools/walkerSafety.ts +1 -0
  359. package/src/tools/webFetch.js +5 -2
  360. package/src/tools/webFetch.ts +5 -2
  361. package/src/toolsList.js +5 -0
  362. package/src/toolsList.ts +5 -0
  363. package/src/tui/ask.js +159 -168
  364. package/src/tui/ask.ts +259 -0
  365. package/src/tui/block.js +0 -1
  366. package/src/tui/block.ts +0 -1
  367. package/src/tui/chatRenderer.js +1193 -1441
  368. package/src/tui/chatRenderer.ts +1336 -0
  369. package/src/tui/clipboardImage.js +36 -12
  370. package/src/tui/clipboardImage.ts +39 -13
  371. package/src/tui/clipboardSync.js +34 -9
  372. package/src/tui/clipboardSync.ts +38 -9
  373. package/src/tui/codeProgress.js +0 -1
  374. package/src/tui/codeProgress.ts +0 -1
  375. package/src/tui/completion.js +395 -371
  376. package/src/tui/completion.ts +574 -0
  377. package/src/tui/composerControls.js +113 -19
  378. package/src/tui/composerControls.ts +124 -19
  379. package/src/tui/consoleGuard.js +27 -7
  380. package/src/tui/consoleGuard.ts +29 -7
  381. package/src/tui/dialogs.js +864 -717
  382. package/src/tui/dialogs.ts +984 -0
  383. package/src/tui/diff.js +205 -195
  384. package/src/tui/diff.ts +336 -0
  385. package/src/tui/history.js +143 -108
  386. package/src/tui/history.ts +167 -0
  387. package/src/tui/home.js +165 -161
  388. package/src/tui/home.ts +251 -0
  389. package/src/tui/invocation.js +58 -65
  390. package/src/tui/invocation.ts +117 -0
  391. package/src/tui/keys.js +437 -420
  392. package/src/tui/keys.ts +597 -0
  393. package/src/tui/lineEditor.js +477 -432
  394. package/src/tui/lineEditor.ts +542 -0
  395. package/src/tui/messageActionPlacement.js +0 -1
  396. package/src/tui/messageActionPlacement.ts +0 -1
  397. package/src/tui/messageInteraction.js +0 -2
  398. package/src/tui/messageInteraction.ts +0 -2
  399. package/src/tui/modelPicker.js +0 -3
  400. package/src/tui/modelPicker.ts +3 -6
  401. package/src/tui/observerPicker.js +0 -2
  402. package/src/tui/observerPicker.ts +0 -2
  403. package/src/tui/overlay.js +0 -1
  404. package/src/tui/overlay.ts +0 -1
  405. package/src/tui/prompt.js +1816 -2151
  406. package/src/tui/prompt.ts +1870 -0
  407. package/src/tui/runningLight.js +0 -1
  408. package/src/tui/runningLight.ts +0 -1
  409. package/src/tui/selectList.js +365 -337
  410. package/src/tui/selectList.ts +441 -0
  411. package/src/tui/sessionPicker.js +0 -1
  412. package/src/tui/sessionPicker.ts +0 -1
  413. package/src/tui/sessionPickerView.js +0 -2
  414. package/src/tui/sessionPickerView.ts +4 -21
  415. package/src/tui/sessionSidebar.js +3 -1
  416. package/src/tui/sessionSidebar.ts +4 -1
  417. package/src/tui/setup.js +17 -5
  418. package/src/tui/setup.ts +19 -5
  419. package/src/tui/skillAuthoring.js +0 -2
  420. package/src/tui/skillAuthoring.ts +0 -3
  421. package/src/tui/stageSurface.js +829 -909
  422. package/src/tui/stageSurface.ts +1003 -0
  423. package/src/tui/statusLine.js +7 -4
  424. package/src/tui/statusLine.ts +7 -3
  425. package/src/tui/terminalInputFramer.js +82 -69
  426. package/src/tui/terminalInputFramer.ts +116 -0
  427. package/src/tui/text.js +25 -10
  428. package/src/tui/text.ts +24 -10
  429. package/src/tui/textLayout.js +0 -1
  430. package/src/tui/textLayout.ts +0 -1
  431. package/src/tui/theme.js +245 -250
  432. package/src/tui/theme.ts +441 -0
  433. package/src/tui/thinkingBox.js +0 -1
  434. package/src/tui/thinkingBox.ts +0 -1
  435. package/src/tui/transcript.js +239 -216
  436. package/src/tui/transcript.ts +324 -0
  437. package/src/tui/turnRail.js +53 -54
  438. package/src/tui/turnRail.ts +51 -49
  439. package/src/tui/usageCard.js +0 -2
  440. package/src/tui/usageCard.ts +0 -2
  441. package/src/tui/workspaceSwitch.js +4 -2
  442. package/src/tui/workspaceSwitch.ts +5 -2
  443. package/src/types/contracts.ts +4 -1
  444. package/src/utils/browserOpen.js +107 -0
  445. package/src/utils/browserOpen.ts +129 -0
  446. package/src/utils/cli_ui.js +0 -0
  447. package/src/utils/cli_ui.ts +158 -0
  448. package/src/utils/winSpawn.js +248 -0
  449. package/src/utils/winSpawn.ts +275 -0
  450. package/src/verification/boundedExplorer.js +138 -107
  451. package/src/verification/boundedExplorer.ts +154 -0
  452. package/src/verification/byokSmokeProbe.js +193 -0
  453. package/src/verification/byokSmokeProbe.ts +234 -0
  454. package/src/verification/cliProbe.js +144 -110
  455. package/src/verification/cliProbe.ts +170 -0
  456. package/src/verification/featureMap.js +105 -75
  457. package/src/verification/featureMap.ts +124 -0
  458. package/src/verification/interactivePty.js +195 -100
  459. package/src/verification/interactivePty.ts +333 -0
  460. package/src/verification/propertyProbe.js +109 -101
  461. package/src/verification/propertyProbe.ts +159 -0
  462. package/src/verification/ptyProbe.js +168 -73
  463. package/src/verification/ptyProbe.ts +254 -0
  464. package/src/verification/skillCatalog.js +25 -25
  465. package/src/verification/skillCatalog.ts +66 -0
  466. package/src/verification/statechart.js +140 -127
  467. package/src/verification/statechart.ts +196 -0
  468. package/src/verification/uiRuntime.js +80 -49
  469. package/src/verification/uiRuntime.ts +88 -0
  470. package/src/version.js +37 -32
  471. package/src/version.ts +45 -0
  472. package/src/web/guiLauncher.js +89 -0
  473. package/src/web/guiLauncher.ts +119 -0
  474. package/src/web/skybridgeBrowserBridge.js +256 -0
  475. package/src/web/skybridgeBrowserBridge.ts +285 -0
  476. package/src/web/skybridgeBrowserMcp.js +730 -0
  477. package/src/web/skybridgeBrowserMcp.ts +813 -0
  478. package/src/web/skybridgeClientScript.js +3951 -0
  479. package/src/web/skybridgeClientScript.ts +3952 -0
  480. package/src/web/skybridgeServer.js +2622 -0
  481. package/src/web/skybridgeServer.ts +2787 -0
  482. package/src/web/skybridgeStyles.js +827 -0
  483. package/src/web/skybridgeStyles.ts +828 -0
  484. package/src/web/skybridgeUi.js +472 -0
  485. package/src/web/skybridgeUi.ts +485 -0
  486. package/src/worktreeManager.js +511 -0
  487. package/src/worktreeManager.ts +546 -0
  488. package/src/zeroCostFailover.js +168 -0
  489. package/src/zeroCostFailover.ts +198 -0
  490. package/src/zeroCostRouting.js +391 -0
  491. package/src/zeroCostRouting.ts +437 -0
  492. package/src/agentLoop.d.ts +0 -65
  493. package/src/auditLog.d.ts +0 -3
  494. package/src/checkpoints.d.ts +0 -4
  495. package/src/compiledSkills.d.ts +0 -5
  496. package/src/contextManager.d.ts +0 -14
  497. package/src/designPalettes.d.ts +0 -2
  498. package/src/devMode.d.ts +0 -1
  499. package/src/embodimentSession.d.ts +0 -2
  500. package/src/licensing/entitlements.d.ts +0 -14
  501. package/src/memory.d.ts +0 -13
  502. package/src/memoryManager.d.ts +0 -1
  503. package/src/modelCatalogue.d.ts +0 -6
  504. package/src/modelIds.d.ts +0 -2
  505. package/src/outputStore.d.ts +0 -4
  506. package/src/plugins/pluginManager.d.ts +0 -7
  507. package/src/providers/antigravity.d.ts +0 -19
  508. package/src/provisioning/capabilityProvisioner.d.ts +0 -12
  509. package/src/slopDetector.d.ts +0 -3
  510. package/src/taskBuffer.d.ts +0 -1
  511. package/src/tools/desktopAct.d.ts +0 -10
  512. package/src/tools/registry.d.ts +0 -5
  513. package/src/tui/chatRenderer.d.ts +0 -27
  514. package/src/tui/diff.d.ts +0 -3
  515. package/src/utils/cli_ui.d.ts +0 -19
  516. package/src/utils/paths.d.ts +0 -3
  517. package/src/verification/skillCatalog.d.ts +0 -1
  518. package/src/version.d.ts +0 -1
@@ -20,7 +20,6 @@
20
20
  // everything but cannot scroll; doing both is the entire point.
21
21
  //
22
22
  // Pure Node: no dependency, no shell.
23
-
24
23
  import { Stage, stageHeight } from './stage.js';
25
24
  import { Transcript } from './transcript.js';
26
25
  import { Viewport, ScrollAcceleration, DEFAULT_SCROLL_SPEED } from './viewport.js';
@@ -29,22 +28,19 @@ import { markHoveredMessage } from './messageInteraction.js';
29
28
  import { placeMessageActionPanel } from './messageActionPlacement.js';
30
29
  import { mouseTracking } from './keys.js';
31
30
  import { mouseHoverTracking } from './mouseHover.js';
32
- import { truncate, padEnd, visibleWidth, stripAnsi } from './text.js';
31
+ import { truncate, padEnd, visibleWidth, stripAnsi, safeDisplay } from './text.js';
33
32
  import { composerWidth } from './layout.js';
34
33
  import { placeHome, placeDialog } from './homeView.js';
35
34
  import { sidebarVisible, sessionSidebarWidth, sessionMainWidth, sessionComposerWidth, sessionSidebarRows, joinSessionSidebar } from './sessionSidebar.js';
36
35
  import { sessionStageHeight, alignTranscriptRows } from './sessionLayout.js';
37
36
  import { hasSessionTurns, collectSessionTurns, buildTurnRailCells, renderTurnPreviewCard, overlayTurnPreviewCard, resolveActiveTurnIndex, formatPreviewCardMarkdown } from './turnRail.js';
38
37
  import { registerStageConsoleGuard, setStageConsoleGuardActive, runWithStageWrite } from './consoleGuard.js';
39
-
40
38
  // Rows of evicted transcript held for the exit log. Eviction only happens after
41
39
  // MAX_FRAMES, so this is a bound on a pathological session, not a working limit.
42
40
  const MAX_EVICTED_ROWS = 40000;
43
-
44
41
  // Below this the prompt block gets the whole band and the transcript is not
45
42
  // shown at all — which is a broken screen, so the prompt is trimmed instead.
46
43
  const MIN_VIEWPORT_ROWS = 2;
47
-
48
44
  // The rail costs a column plus a column of air. On a narrow terminal those two
49
45
  // are worth more as text, so it turns itself off rather than crowding the
50
46
  // transcript it exists to help you navigate.
@@ -59,983 +55,907 @@ const RAIL_WIDTH = 2;
59
55
  const RAIL_BUDGET = RAIL_WIDTH + 1;
60
56
  // The interactive turn rail takes three columns at the left of each row.
61
57
  const TURN_RAIL_BUDGET = 3;
62
-
63
58
  // Count a prefix of terminal control sequences with a deterministic scan.
64
59
  // This preserves CSI, OSC (BEL/ST), and two-byte ESC codes without regex
65
60
  // backtracking on long or malformed terminal output.
66
61
  export function leadingAnsiControlEnd(row) {
67
- if (typeof row !== 'string') return 0;
68
- let index = 0;
69
- while (row.charCodeAt(index) === 27) {
70
- let cursor = index + 1;
71
- const kind = row.charCodeAt(cursor);
72
- if (kind === 91) { // ESC [
73
- cursor++;
74
- while (row.charCodeAt(cursor) >= 48 && row.charCodeAt(cursor) <= 63) cursor++;
75
- while (row.charCodeAt(cursor) >= 32 && row.charCodeAt(cursor) <= 47) cursor++;
76
- const final = row.charCodeAt(cursor);
77
- if (final >= 64 && final <= 126) {
78
- index = cursor + 1;
79
- continue;
80
- }
81
- } else if (kind === 93) { // ESC ] ... BEL or ESC backslash
82
- cursor++;
83
- while (cursor < row.length && row.charCodeAt(cursor) !== 7 && row.charCodeAt(cursor) !== 27) cursor++;
84
- if (row.charCodeAt(cursor) === 7) {
85
- index = cursor + 1;
86
- continue;
87
- }
88
- if (row.charCodeAt(cursor) === 27 && row.charCodeAt(cursor + 1) === 92) {
89
- index = cursor + 2;
90
- continue;
91
- }
92
- } else if ((kind >= 64 && kind <= 90) || (kind >= 92 && kind <= 95)) {
93
- index = cursor + 1;
94
- continue;
62
+ if (typeof row !== 'string')
63
+ return 0;
64
+ let index = 0;
65
+ while (row.charCodeAt(index) === 27) {
66
+ let cursor = index + 1;
67
+ const kind = row.charCodeAt(cursor);
68
+ if (kind === 91) { // ESC [
69
+ cursor++;
70
+ while (row.charCodeAt(cursor) >= 48 && row.charCodeAt(cursor) <= 63)
71
+ cursor++;
72
+ while (row.charCodeAt(cursor) >= 32 && row.charCodeAt(cursor) <= 47)
73
+ cursor++;
74
+ const final = row.charCodeAt(cursor);
75
+ if (final >= 64 && final <= 126) {
76
+ index = cursor + 1;
77
+ continue;
78
+ }
79
+ }
80
+ else if (kind === 93) { // ESC ] ... BEL or ESC backslash
81
+ cursor++;
82
+ while (cursor < row.length && row.charCodeAt(cursor) !== 7 && row.charCodeAt(cursor) !== 27)
83
+ cursor++;
84
+ if (row.charCodeAt(cursor) === 7) {
85
+ index = cursor + 1;
86
+ continue;
87
+ }
88
+ if (row.charCodeAt(cursor) === 27 && row.charCodeAt(cursor + 1) === 92) {
89
+ index = cursor + 2;
90
+ continue;
91
+ }
92
+ }
93
+ else if ((kind >= 64 && kind <= 90) || (kind >= 92 && kind <= 95)) {
94
+ index = cursor + 1;
95
+ continue;
96
+ }
97
+ break;
95
98
  }
96
- break;
97
- }
98
- return index;
99
+ return index;
99
100
  }
100
-
101
101
  // Which marker wins when several frames fall in the same rail row. A proportional
102
102
  // rail on a long session compresses dozens of frames per row, and what you want
103
103
  // to see at a glance is the thing that went wrong or the thing you can roll back
104
104
  // to — not the forty step rows around them.
105
105
  // Inside the thumb, only a marker this loud overrides the position indicator.
106
- //
107
- // Two passes to get this right. The first draft let ANY marker win, and a dense
108
- // session put a marker in every slot — so the thumb, the one thing on the rail
109
- // that says WHERE YOU ARE, was invisible exactly when the rail mattered most.
110
- // The second draft set the bar at checkpoints, and a real session on a pty
111
- // showed why that is still wrong: a restore point is taken on every file write,
112
- // so the thumb came out as `▌▌▪▪▪▌` — shredded by the most routine event there
113
- // is. Only what is rare AND urgent is worth a row of position: an error, or an
114
- // approval waiting on the user.
115
106
  const RAIL_THUMB_YIELD = 80;
116
-
117
107
  const RAIL_PRIORITY = {
118
- error: 90, approval: 80, checkpoint: 70, turn: 60, user: 50,
119
- assistant: 40, reasoning: 30, skill: 25, plan: 20,
120
- session: 15, step: 10, result: 5, notice: 1
108
+ error: 90, approval: 80, checkpoint: 70, turn: 60, user: 50,
109
+ assistant: 40, reasoning: 30, skill: 25, plan: 20,
110
+ session: 15, step: 10, result: 5, notice: 1
111
+ };
112
+ const SIGNAL_EXIT_CODES = {
113
+ SIGINT: 2,
114
+ SIGTERM: 15,
115
+ SIGHUP: 1
121
116
  };
122
-
117
+ function railPriority(kind) {
118
+ if (!kind || !Object.hasOwn(RAIL_PRIORITY, kind))
119
+ return 0;
120
+ return RAIL_PRIORITY[kind] ?? 0;
121
+ }
123
122
  /**
124
123
  * One row of the position indicator: a continuous rule with ONE dot at its
125
124
  * middle. Line, dot, line — the same motif the input box carries.
126
125
  *
127
- * Alternating every other row was the first attempt and it was wrong: over a
128
- * thumb of any length it reads as a long dashed line, which is the thing it was
129
- * supposed to stop looking like. One dot at the centre makes even a full-track
130
- * thumb read as a single object rather than as a run of broken marks.
131
- *
132
126
  * `│` is used by no marker, which is what lets a test find the thumb at all.
133
127
  */
134
128
  function thumbGlyph(offsetInThumb, thumbLength) {
135
- const middle = thumbLength >= 3 ? Math.floor(thumbLength / 2) : -1;
136
- return offsetInThumb === middle ? GLYPHS.dot : GLYPHS.vLine;
129
+ const middle = thumbLength >= 3 ? Math.floor(thumbLength / 2) : -1;
130
+ return offsetInThumb === middle ? GLYPHS.dot : GLYPHS.vLine;
137
131
  }
138
-
139
132
  /**
140
133
  * One rail cell. Every glyph is an existing GLYPH — the ambiguous-width set is
141
134
  * already accounted for by visibleWidth(), and a new character here would be a
142
135
  * new way for a row to measure one column and render two.
143
136
  */
144
137
  function railGlyph(kind) {
145
- switch (kind) {
146
- case 'error': return paint('danger', GLYPHS.cross);
147
- case 'approval': return paint('warn', GLYPHS.step);
148
- case 'checkpoint': return paint('success', GLYPHS.step);
149
- case 'turn': return paint('rule', GLYPHS.hLine);
150
- case 'user': return paint('user', GLYPHS.arrow);
151
- case 'assistant': return paint('agent', GLYPHS.arrow);
152
- case 'reasoning': return paint('muted', GLYPHS.dot);
153
- default: return paint('rule', GLYPHS.dot);
154
- }
138
+ switch (kind) {
139
+ case 'error': return paint('danger', GLYPHS.cross);
140
+ case 'approval': return paint('warn', GLYPHS.step);
141
+ case 'checkpoint': return paint('success', GLYPHS.step);
142
+ case 'turn': return paint('rule', GLYPHS.hLine);
143
+ case 'user': return paint('user', GLYPHS.arrow);
144
+ case 'assistant': return paint('agent', GLYPHS.arrow);
145
+ case 'reasoning': return paint('muted', GLYPHS.dot);
146
+ default: return paint('rule', GLYPHS.dot);
147
+ }
155
148
  }
156
-
157
149
  /**
158
150
  * Wheel tuning, from the environment first and the saved config second.
159
- *
160
- * Env wins because every other Stage switch is an env var (CAUSYNE_STAGE,
161
- * CAUSYNE_MOUSE, CAUSYNE_RAIL) and a user debugging a terminal wants one place to
162
- * turn things off. The config file is where a preference lives once it is
163
- * settled.
164
151
  */
165
152
  export function scrollSettings(env = process.env, config = null) {
166
- const safeEnv = env && typeof env === 'object' ? env : {};
167
- const tui = (config && typeof config === 'object' && config.tui) || {};
168
-
169
- let speed = Number(safeEnv.CAUSYNE_SCROLL_SPEED);
170
- if (!Number.isFinite(speed) || speed <= 0) speed = Number(tui.scrollSpeed);
171
- if (!Number.isFinite(speed) || speed <= 0) speed = DEFAULT_SCROLL_SPEED;
172
- // A wheel that moves half the screen per notch is not a preference, it is a
173
- // misconfiguration; clamp rather than obey it.
174
- speed = Math.min(speed, 20);
175
-
176
- const raw = safeEnv.CAUSYNE_SCROLL_ACCEL;
177
- const accelerate = raw !== undefined && raw !== ''
178
- ? raw === '1' || raw === 'true'
179
- : Boolean(tui.scrollAcceleration);
180
-
181
- return { speed, accelerate };
153
+ const safeEnv = env && typeof env === 'object' ? env : {};
154
+ const tui = (config && typeof config === 'object' && config.tui) || {};
155
+ let speed = Number(safeEnv.CAUSYNE_SCROLL_SPEED);
156
+ if (!Number.isFinite(speed) || speed <= 0)
157
+ speed = Number(tui.scrollSpeed);
158
+ if (!Number.isFinite(speed) || speed <= 0)
159
+ speed = DEFAULT_SCROLL_SPEED;
160
+ // A wheel that moves half the screen per notch is not a preference, it is a
161
+ // misconfiguration; clamp rather than obey it.
162
+ speed = Math.min(speed, 20);
163
+ const raw = safeEnv.CAUSYNE_SCROLL_ACCEL;
164
+ const accelerate = raw !== undefined && raw !== ''
165
+ ? raw === '1' || raw === 'true'
166
+ : Boolean(tui.scrollAcceleration);
167
+ return { speed, accelerate };
182
168
  }
183
-
184
-
185
169
  /**
186
170
  * A rail dot represents a *time-ordered group* when a long conversation is
187
- * compressed into fewer terminal rows. The video reference shows a titled
188
- * history list with timestamps, not a single-turn assistant-summary card.
189
- * This function never changes transcript geometry or user content.
171
+ * compressed into fewer terminal rows.
190
172
  */
191
173
  export function renderTurnTimelineCard(turns, maxCardWidth = 52, maxHeight = 16, offset = 0) {
192
- if (!Array.isArray(turns) || turns.length === 0) {
193
- return { rows: [], entries: [], entryStart: 4, maxOffset: 0 };
194
- }
195
- const width = Number.isFinite(maxCardWidth) ? Math.max(24, Math.min(52, Math.floor(maxCardWidth))) : 52;
196
- const inner = width - 4;
197
- const viewHeight = Number.isFinite(maxHeight) ? Math.max(6, Math.floor(maxHeight)) : 16;
198
- const count = Math.max(1, Math.min(10, turns.length, viewHeight - 5));
199
- const maxOffset = Math.max(0, turns.length - count);
200
- const start = Number.isFinite(offset) ? Math.max(0, Math.min(maxOffset, Math.floor(offset))) : 0;
201
- const entries = turns.slice(start, start + count);
202
- const bg = '\x1b[48;2;28;28;32m';
203
- const border = bg + '\x1b[38;2;75;75;82m';
204
- const reset = '\x1b[0m';
205
- const top = border + '╭' + '─'.repeat(width - 2) + '╮' + reset;
206
- const bottom = border + '╰' + '─'.repeat(width - 2) + '╯' + reset;
207
- const blank = border + '│' + bg + ' '.repeat(inner + 2) + border + '│' + reset;
208
- const line = (value, style = '') => {
209
- const text = truncate(formatPreviewCardMarkdown(String(value || '')), inner, '…');
210
- return border + '│' + bg + ' ' + style + padEnd(text, inner) + border + ' │' + reset;
211
- };
212
- const shortTime = turn => {
213
- const ts = Number(turn?.timestamp);
214
- return Number.isFinite(ts) && ts > 0
215
- ? new Date(ts).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })
216
- : '';
217
- };
218
- const first = turns[0];
219
- const last = turns[turns.length - 1];
220
- const title = first?.userPrompt || 'Conversation history';
221
- const range = shortTime(first) + (turns.length > 1 ? ' – ' + shortTime(last) : '');
222
- const header = range.trim() + ' · ' + turns.length + (turns.length === 1 ? ' turn' : ' turns');
223
- const rows = [
224
- top,
225
- line(title, '\x1b[1m\x1b[38;2;235;235;242m'),
226
- line(header, '\x1b[38;2;145;145;155m'),
227
- blank
228
- ];
229
- for (const turn of entries) {
230
- const when = shortTime(turn);
231
- const prompt = turn?.userPrompt || 'Turn ' + String(turn?.turnIndex ?? '');
232
- rows.push(line((when ? when + ' ' : '') + prompt, '\x1b[38;2;185;185;193m'));
233
- }
234
- rows.push(bottom);
235
- return { rows, entries, entryStart: 4, maxOffset };
174
+ if (!Array.isArray(turns) || turns.length === 0) {
175
+ return { rows: [], entries: [], entryStart: 4, maxOffset: 0 };
176
+ }
177
+ const width = Number.isFinite(maxCardWidth) ? Math.max(24, Math.min(52, Math.floor(maxCardWidth))) : 52;
178
+ const inner = width - 4;
179
+ const viewHeight = Number.isFinite(maxHeight) ? Math.max(6, Math.floor(maxHeight)) : 16;
180
+ const count = Math.max(1, Math.min(10, turns.length, viewHeight - 5));
181
+ const maxOffset = Math.max(0, turns.length - count);
182
+ const start = Number.isFinite(offset) ? Math.max(0, Math.min(maxOffset, Math.floor(offset))) : 0;
183
+ const entries = turns.slice(start, start + count);
184
+ const bg = '\x1b[48;2;28;28;32m';
185
+ const border = bg + '\x1b[38;2;75;75;82m';
186
+ const reset = '\x1b[0m';
187
+ const top = border + '╭' + '─'.repeat(width - 2) + '╮' + reset;
188
+ const bottom = border + '╰' + '─'.repeat(width - 2) + '╯' + reset;
189
+ const blank = border + '│' + bg + ' '.repeat(inner + 2) + border + '│' + reset;
190
+ const line = (value, style = '') => {
191
+ const text = truncate(formatPreviewCardMarkdown(safeDisplay(String(value || ''))), inner, '…');
192
+ return border + '│' + bg + ' ' + style + padEnd(text, inner) + border + ' │' + reset;
193
+ };
194
+ const shortTime = (turn) => {
195
+ const ts = Number(turn?.timestamp);
196
+ return Number.isFinite(ts) && ts > 0
197
+ ? new Date(ts).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })
198
+ : '';
199
+ };
200
+ const first = turns[0];
201
+ const last = turns[turns.length - 1];
202
+ const title = first?.userPrompt || 'Conversation history';
203
+ const range = shortTime(first) + (turns.length > 1 ? ' – ' + shortTime(last) : '');
204
+ const header = range.trim() + ' · ' + turns.length + (turns.length === 1 ? ' turn' : ' turns');
205
+ const rows = [
206
+ top,
207
+ line(title, '\x1b[1m\x1b[38;2;235;235;242m'),
208
+ line(header, '\x1b[38;2;145;145;155m'),
209
+ blank
210
+ ];
211
+ for (const turn of entries) {
212
+ const when = shortTime(turn);
213
+ const prompt = turn?.userPrompt || 'Turn ' + String(turn?.turnIndex ?? '');
214
+ rows.push(line((when ? when + ' ' : '') + prompt, '\x1b[38;2;185;185;193m'));
215
+ }
216
+ rows.push(bottom);
217
+ return { rows, entries, entryStart: 4, maxOffset };
236
218
  }
237
-
238
219
  export class StageSurface {
239
- constructor({ out = process.stdout, env = process.env, config = null, speed, accelerate, openingWidth = 0 } = {}) {
240
- this.out = out;
241
- this.env = env;
242
-
243
- this.stage = new Stage({ out, env });
244
- this.lastColumns = this.stage.width();
245
- this.transcript = new Transcript({
246
- onEvict: (rows) => this.absorbEvicted(rows),
247
- onChange: () => this.handleChange()
248
- });
249
- this.transcript.surface = this;
250
- const tuning = scrollSettings(env, config);
251
- this.viewport = new Viewport({
252
- transcript: this.transcript,
253
- height: Math.max(MIN_VIEWPORT_ROWS, this.stage.height - 2),
254
- width: this.stage.width(),
255
- speed: speed !== undefined ? speed : tuning.speed,
256
- acceleration: (accelerate !== undefined ? accelerate : tuning.accelerate)
257
- ? new ScrollAcceleration()
258
- : null
259
- });
260
-
261
- // Rows that fell out of the model. Not shown, not lost: they are printed
262
- // ahead of the transcript on the way out.
263
- this.evicted = [];
264
- this.lastHeight = 0;
265
- // Set by ChatPrompt.attachSurface.
266
- this.onDirty = null;
267
- this.exitHook = null;
268
- this.signalHooks = [];
269
- // UX-02: opt out entirely, for anyone whose terminal or workflow this gets
270
- // in the way of.
271
- this.mouseWanted = String(env.CAUSYNE_MOUSE ?? '1') !== '0';
272
- this.mouseOn = false;
273
- this.mouseCaptured = false;
274
- this.mouseMotionOn = false;
275
- this.detached = false;
276
-
277
- // Retained for callers that pass a measured header width. The composer now
278
- // uses a stable readable width even after the first transcript entry.
279
- this.openingWidth = Number.isFinite(openingWidth) && openingWidth > 0
280
- ? Math.floor(openingWidth)
281
- : 0;
282
-
283
- // Tracks whether this session has ever received transcript content.
284
- this.opened = false;
285
- this.homeInfo = null;
286
- this.homeSessionSelected = false;
287
- this.sessionInfo = null;
288
- this.sidebarStatus = null;
289
- this.sidebarPlan = [];
290
- this.fullSession = false;
291
- this.lastPromptRows = [];
292
- this.lastPromptCaret = null;
293
- this.messageActionOverlay = null;
294
- this.unregisterConsoleGuard = null;
295
- this.wasModal = false;
296
- this.lastBlockLength = 0;
297
- this.lastUserTurnCount = 0;
298
- }
299
-
300
- get width() {
301
- return this.stage.width();
302
- }
303
-
304
- composeAvailableWidth() {
305
- if (this.homeInfo) return this.width;
306
- return sessionMainWidth(this.width, false, this.env);
307
- }
308
-
309
- /** Home is compact; a session uses its full conversation column. */
310
- composeWidth() {
311
- if (this.homeInfo) return composerWidth(this.width);
312
- const mainWidth = sessionMainWidth(this.width, false, this.env);
313
- return sessionComposerWidth(mainWidth);
314
- }
315
-
316
- /** Keep Home distinct from a selected or newly started conversation. */
317
- enterHome(info) {
318
- this.homeInfo = info;
319
- this.disableMouse();
320
- this.homeSessionSelected = false;
321
- this.sessionInfo = { title: 'Untitled', cwd: info?.cwd, provider: info?.provider, model: info?.model };
322
- this.fullSession = true;
323
- this.stage.invalidate();
324
- }
325
-
326
- leaveHome(sessionSelected = false) {
327
- if (this.homeInfo) this.stage.invalidate();
328
- this.homeInfo = null;
329
- this.enableMouse();
330
- if (sessionSelected) this.homeSessionSelected = true;
331
- }
332
-
333
- setSessionInfo(info) {
334
- const changedSession = info?.id && this.sessionInfo?.id && info.id !== this.sessionInfo.id;
335
- if (changedSession) {
336
- // Sidebar plans and turn hover coordinates belong to the previous chat.
337
- this.sidebarPlan = [];
338
- this.hoveredTurnIndex = null;
339
- this.hoveredTurnAnchorY = null;
340
- this.activeTurnIndex = null;
341
- this.hoveredMessageFrameId = null;
342
- this.turnRailLayout = null;
220
+ out;
221
+ env;
222
+ stage;
223
+ lastColumns;
224
+ transcript;
225
+ viewport;
226
+ evicted;
227
+ lastHeight;
228
+ onDirty;
229
+ exitHook;
230
+ signalHooks;
231
+ mouseWanted;
232
+ mouseOn;
233
+ mouseCaptured;
234
+ mouseMotionOn;
235
+ detached;
236
+ openingWidth;
237
+ opened;
238
+ homeInfo;
239
+ homeSessionSelected;
240
+ sessionInfo;
241
+ sidebarStatus;
242
+ sidebarPlan;
243
+ fullSession;
244
+ lastPromptRows;
245
+ lastPromptCaret;
246
+ messageActionOverlay;
247
+ unregisterConsoleGuard;
248
+ wasModal;
249
+ lastBlockLength;
250
+ lastUserTurnCount;
251
+ hoveredTurnIndex;
252
+ hoveredTurnAnchorY;
253
+ activeTurnIndex;
254
+ hoveredMessageFrameId;
255
+ turnRailLayout;
256
+ turnRailCardOffset;
257
+ turnRailHoverSuppressed;
258
+ constructor({ out = process.stdout, env = process.env, config = null, speed, accelerate, openingWidth = 0 } = {}) {
259
+ this.out = out;
260
+ this.env = env && typeof env === 'object' ? env : {};
261
+ this.stage = new Stage({ out, env: this.env });
262
+ this.lastColumns = this.stage.width();
263
+ this.transcript = new Transcript({
264
+ onEvict: (rows) => this.absorbEvicted(rows),
265
+ onChange: () => this.handleChange()
266
+ });
267
+ this.transcript.surface = this;
268
+ const tuning = scrollSettings(this.env, config);
269
+ this.viewport = new Viewport({
270
+ transcript: this.transcript,
271
+ height: Math.max(MIN_VIEWPORT_ROWS, this.stage.height - 2),
272
+ width: this.stage.width(),
273
+ speed: speed !== undefined ? speed : tuning.speed,
274
+ acceleration: (accelerate !== undefined ? accelerate : tuning.accelerate)
275
+ ? new ScrollAcceleration()
276
+ : null
277
+ });
278
+ // Rows that fell out of the model. Not shown, not lost: they are printed
279
+ // ahead of the transcript on the way out.
280
+ this.evicted = [];
281
+ this.lastHeight = 0;
282
+ // Set by ChatPrompt.attachSurface.
283
+ this.onDirty = null;
284
+ this.exitHook = null;
285
+ this.signalHooks = [];
286
+ // UX-02: opt out entirely, for anyone whose terminal or workflow this gets
287
+ // in the way of.
288
+ this.mouseWanted = String(this.env.CAUSYNE_MOUSE ?? '1') !== '0';
289
+ this.mouseOn = false;
290
+ this.mouseCaptured = false;
291
+ this.mouseMotionOn = false;
292
+ this.detached = false;
293
+ // Retained for callers that pass a measured header width. The composer now
294
+ // uses a stable readable width even after the first transcript entry.
295
+ this.openingWidth = Number.isFinite(openingWidth) && openingWidth > 0
296
+ ? Math.floor(openingWidth)
297
+ : 0;
298
+ // Tracks whether this session has ever received transcript content.
299
+ this.opened = false;
300
+ this.homeInfo = null;
301
+ this.homeSessionSelected = false;
302
+ this.sessionInfo = null;
303
+ this.sidebarStatus = null;
304
+ this.sidebarPlan = [];
305
+ this.fullSession = false;
306
+ this.lastPromptRows = [];
307
+ this.lastPromptCaret = null;
308
+ this.messageActionOverlay = null;
309
+ this.unregisterConsoleGuard = null;
310
+ this.wasModal = false;
311
+ this.lastBlockLength = 0;
312
+ this.lastUserTurnCount = 0;
343
313
  }
344
- this.sessionInfo = changedSession
345
- ? { ...this.sessionInfo, activeSkill: null, contextChars: 0, ...info }
346
- : { ...this.sessionInfo, ...info };
347
- this.stage.invalidate();
348
- }
349
-
350
- /**
351
- * Claim the band and arm the exit safety net.
352
- *
353
- * The hook matters: if the process dies without going through stop(), the
354
- * band's rows are ordinary terminal text and nothing is corrupted, but the
355
- * session would not reach scrollback. A synchronous exit handler is enough
356
- * because collapse and print-through are plain writes.
357
- */
358
- open() {
359
- // ONE row, not the whole screen.
360
- //
361
- // The band used to be born at `rows - 1` regardless of what it had to show.
362
- // Measured at 156x78: the banner's 12 rows plus a 77-row band came to 89 on
363
- // a 78-row screen, so the wordmark was scrolled 11 rows out of sight before
364
- // the user had typed anything, and 73 of the 77 claimed rows were empty.
365
- // present() grows it to fit what there actually is.
366
- if (!this.stage.reserve(1)) return false;
367
- this.unregisterConsoleGuard?.();
368
- this.unregisterConsoleGuard = registerStageConsoleGuard(this);
369
- if (this.out === process.stdout) setStageConsoleGuardActive(true);
370
- if (!this.homeInfo) this.enableMouse();
371
- this.armTeardown();
372
- return true;
373
- }
374
-
375
- writeModeControl(sequence) {
376
- if (!sequence) return;
377
- runWithStageWrite(() => {
378
- this.out.write(sequence);
379
- });
380
- }
381
-
382
- syncTurnRailMotion(railHasTurns) {
383
- if (!this.mouseOn || !this.mouseCaptured || !this.stage.reserved) return;
384
- const preference = String(this.env?.CAUSYNE_MOUSE_HOVER ?? '').trim();
385
- // Hover needs 1003, not just 1000. Limit default motion tracking to
386
- // visible turn rails; preserve explicit opt-in and opt-out preferences.
387
- const wantMotion = preference === '1' || (preference !== '0' && railHasTurns);
388
- if (this.mouseMotionOn === wantMotion) return;
389
- this.writeModeControl(mouseHoverTracking(wantMotion, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
390
- this.mouseMotionOn = wantMotion;
391
- if (!wantMotion) {
392
- // 1003 can replace 1000 in terminal tracking-mode state. When it is
393
- // removed, explicitly restore 1000 or the wheel scrolls the shell.
394
- this.writeModeControl(mouseTracking(true));
314
+ get width() {
315
+ return this.stage.width();
395
316
  }
396
- }
397
-
398
- enableMouse() {
399
- if (this.homeInfo || !this.mouseWanted || this.mouseOn || !this.stage.reserved) return false;
400
- this.writeModeControl(mouseTracking(true));
401
- this.writeModeControl(mouseHoverTracking(true, this.env));
402
- this.mouseCaptured = true;
403
- this.mouseOn = true;
404
- this.mouseMotionOn = String(this.env?.CAUSYNE_MOUSE_HOVER ?? '') === '1';
405
- return true;
406
- }
407
-
408
- disableMouse(force = false) {
409
- if (!force && !this.mouseOn && !this.mouseCaptured) return false;
410
- // Restore terminal motion modes, including stale tracking from an interrupted turn.
411
- this.writeModeControl(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
412
- this.writeModeControl(mouseTracking(false));
413
- this.mouseCaptured = false;
414
- this.mouseOn = false;
415
- this.mouseMotionOn = false;
416
- this.detached = false;
417
- return true;
418
- }
419
-
420
-
421
- armTeardown() {
422
- if (this.signalHooks.length > 0 || this.exitHook) this.disarmTeardown();
423
- this.exitHook = () => { try { this.close(); } catch { /* nothing left to do */ } };
424
- process.once('exit', this.exitHook);
425
-
426
- for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
427
- const handler = () => {
428
- try { this.close(); } catch { /* keep going: the exit matters more */ }
429
- // Re-raise the conventional status so a caller waiting on us still sees
430
- // that we were signalled rather than that we exited cleanly.
431
- process.exit(128 + { SIGINT: 2, SIGTERM: 15, SIGHUP: 1 }[signal]);
432
- };
433
- process.on(signal, handler);
434
- this.signalHooks.push([signal, handler]);
317
+ composeAvailableWidth() {
318
+ if (this.homeInfo)
319
+ return this.width;
320
+ return sessionMainWidth(this.width, false, this.env);
435
321
  }
436
- }
437
-
438
- disarmTeardown() {
439
- if (this.exitHook) {
440
- process.removeListener('exit', this.exitHook);
441
- this.exitHook = null;
322
+ /** Home is compact; a session uses its full conversation column. */
323
+ composeWidth() {
324
+ if (this.homeInfo)
325
+ return composerWidth(this.width);
326
+ const mainWidth = sessionMainWidth(this.width, false, this.env);
327
+ return sessionComposerWidth(mainWidth);
442
328
  }
443
- for (const [signal, handler] of this.signalHooks) process.removeListener(signal, handler);
444
- this.signalHooks = [];
445
- }
446
-
447
- close() {
448
- // Force the terminal to release tracking, even if internal flags were stale.
449
- this.disableMouse(true);
450
- if (this.unregisterConsoleGuard) {
451
- this.unregisterConsoleGuard();
452
- this.unregisterConsoleGuard = null;
453
- if (this.out === process.stdout) setStageConsoleGuardActive(false);
329
+ /** Keep Home distinct from a selected or newly started conversation. */
330
+ enterHome(info) {
331
+ this.homeInfo = info;
332
+ this.disableMouse();
333
+ this.homeSessionSelected = false;
334
+ this.sessionInfo = { title: 'Untitled', cwd: info?.cwd, provider: info?.provider, model: info?.model };
335
+ this.fullSession = true;
336
+ this.stage.invalidate();
454
337
  }
455
- if (!this.stage.reserved) { this.disarmTeardown(); return false; }
456
- const rows = this.snapshot();
457
- this.stage.collapse();
458
- this.stage.printThrough(rows);
459
- this.disarmTeardown();
460
- return true;
461
- }
462
-
463
- /**
464
- * Hand the terminal back to something that is about to write to it directly,
465
- * then take it again.
466
- *
467
- * Anything spawned with stdio: 'inherit' writes straight into the band and
468
- * the diff has no idea it happened. Causyne has four such call sites today
469
- * (autoUpdate's two npm installs, the cortex provisioner, the capability
470
- * provisioner); none of them is wired to this yet, and that is recorded as an
471
- * open item rather than left to be discovered.
472
- */
473
- suspend() {
474
- if (!this.stage.reserved) return false;
475
- this.disableMouse();
476
- if (this.unregisterConsoleGuard) {
477
- this.unregisterConsoleGuard();
478
- this.unregisterConsoleGuard = null;
479
- if (this.out === process.stdout) setStageConsoleGuardActive(false);
338
+ leaveHome(sessionSelected = false) {
339
+ if (this.homeInfo)
340
+ this.stage.invalidate();
341
+ this.homeInfo = null;
342
+ this.enableMouse();
343
+ if (sessionSelected)
344
+ this.homeSessionSelected = true;
480
345
  }
481
- this.stage.collapse();
482
- return true;
483
- }
484
-
485
- resume() {
486
- if (this.stage.reserved) return false;
487
- if (!this.stage.reserve()) return false;
488
- this.unregisterConsoleGuard?.();
489
- this.unregisterConsoleGuard = registerStageConsoleGuard(this);
490
- if (this.out === process.stdout) setStageConsoleGuardActive(true);
491
- this.stage.invalidate();
492
- this.enableMouse();
493
- return true;
494
- }
495
-
496
- /** Everything the session produced, oldest first. */
497
- snapshot() {
498
- return this.evicted.concat(this.transcript.snapshot(this.width));
499
- }
500
-
501
- absorbEvicted(rows) {
502
- for (const row of rows) this.evicted.push(row);
503
- if (this.evicted.length > MAX_EVICTED_ROWS) {
504
- this.evicted.splice(0, this.evicted.length - MAX_EVICTED_ROWS);
346
+ setSessionInfo(info) {
347
+ const changedSession = Boolean(info?.id && this.sessionInfo?.id && info.id !== this.sessionInfo.id);
348
+ if (changedSession) {
349
+ // Sidebar plans and turn hover coordinates belong to the previous chat.
350
+ this.sidebarPlan = [];
351
+ this.hoveredTurnIndex = null;
352
+ this.hoveredTurnAnchorY = null;
353
+ this.activeTurnIndex = null;
354
+ this.hoveredMessageFrameId = null;
355
+ this.turnRailLayout = null;
356
+ }
357
+ this.sessionInfo = changedSession
358
+ ? { ...this.sessionInfo, activeSkill: null, contextChars: 0, ...info }
359
+ : { ...this.sessionInfo, ...info };
360
+ this.stage.invalidate();
505
361
  }
506
- }
507
-
508
- handleChange() {
509
- if (!this.transcript.isEmpty()) this.opened = true;
510
- let userTurns = 0;
511
- for (const frame of this.transcript.frames) {
512
- if (frame && frame.kind === 'user') userTurns++;
362
+ /**
363
+ * Claim the band and arm the exit safety net.
364
+ */
365
+ open() {
366
+ if (!this.stage.reserve(1))
367
+ return false;
368
+ this.unregisterConsoleGuard?.();
369
+ this.unregisterConsoleGuard = registerStageConsoleGuard(this);
370
+ if (this.out === process.stdout)
371
+ setStageConsoleGuardActive(true);
372
+ if (!this.homeInfo)
373
+ this.enableMouse();
374
+ this.armTeardown();
375
+ return true;
513
376
  }
514
- if (userTurns > this.lastUserTurnCount) {
515
- this.activeTurnIndex = null;
516
- this.hoveredTurnIndex = null;
517
- this.hoveredTurnAnchorY = null;
377
+ writeModeControl(sequence) {
378
+ if (!sequence || !this.out || typeof this.out.write !== 'function')
379
+ return;
380
+ runWithStageWrite(() => {
381
+ this.out.write(sequence);
382
+ });
518
383
  }
519
- this.lastUserTurnCount = userTurns;
520
- const before = this.lastHeight;
521
- const mainWidth = sessionMainWidth(this.width, false, this.env);
522
- const contentWidth = this.railEnabled(mainWidth)
523
- ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
524
- : mainWidth;
525
- const after = this.transcript.height(contentWidth);
526
- this.lastHeight = after;
527
- // Growth is what drives auto-scroll. Handing the delta over is also what
528
- // lets the "N new below" affordance count only what arrived while the user
529
- // was reading somewhere else.
530
- this.viewport.refresh(Math.max(0, after - before));
531
- if (this.onDirty) this.onDirty();
532
- }
533
-
534
- // -------------------------------------------------------------------------
535
- // The interface ChatPrompt calls
536
- // -------------------------------------------------------------------------
537
-
538
- /**
539
- * Append a permanent frame. `produce` must be a pure function of width — see
540
- * the contract in transcript.js.
541
- */
542
- commit(kind, produce, meta = null) {
543
- return this.transcript.append({ kind, produce, meta });
544
- }
545
-
546
- /**
547
- * Paint the band: viewport on top, the prompt's own rows underneath.
548
- */
549
- present(promptRows, caret = null) {
550
- if (!this.stage.reserved) return 0;
551
-
552
- if (!this.messageActionOverlay) {
553
- this.lastPromptRows = promptRows;
554
- this.lastPromptCaret = caret;
384
+ syncTurnRailMotion(railHasTurns) {
385
+ if (!this.mouseOn || !this.mouseCaptured || !this.stage.reserved)
386
+ return;
387
+ const preference = String(this.env?.CAUSYNE_MOUSE_HOVER ?? '').trim();
388
+ // Hover needs 1003, not just 1000. Limit default motion tracking to
389
+ // visible turn rails; preserve explicit opt-in and opt-out preferences.
390
+ const wantMotion = preference === '1' || (preference !== '0' && railHasTurns);
391
+ if (this.mouseMotionOn === wantMotion)
392
+ return;
393
+ this.writeModeControl(mouseHoverTracking(wantMotion, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
394
+ this.mouseMotionOn = wantMotion;
395
+ if (!wantMotion) {
396
+ // 1003 can replace 1000 in terminal tracking-mode state. When it is
397
+ // removed, explicitly restore 1000 or the wheel scrolls the shell.
398
+ this.writeModeControl(mouseTracking(true));
399
+ }
555
400
  }
556
-
557
- // Do not grow, resize, or invalidate the band while the terminal owns
558
- // scrollback; otherwise stage.grow emits newlines that shift the user's
559
- // scroll position before the detached repaint guard below.
560
- if (this.detached) return false;
561
-
562
- const isModal = Boolean(caret?.modal);
563
- if (isModal !== this.wasModal) {
564
- this.wasModal = isModal;
565
- this.stage.invalidate();
401
+ enableMouse() {
402
+ if (this.homeInfo || !this.mouseWanted || this.mouseOn || !this.stage.reserved)
403
+ return false;
404
+ this.writeModeControl(mouseTracking(true));
405
+ this.writeModeControl(mouseHoverTracking(true, this.env));
406
+ this.mouseCaptured = true;
407
+ this.mouseOn = true;
408
+ this.mouseMotionOn = String(this.env?.CAUSYNE_MOUSE_HOVER ?? '') === '1';
409
+ return true;
566
410
  }
567
-
568
- if (this.homeInfo || (caret?.modal && !caret?.inline)) {
569
- this.syncTurnRailMotion(false);
570
- this.turnRailLayout = null;
571
- this.hoveredTurnIndex = null;
572
- this.hoveredTurnAnchorY = null;
573
- if (this.stage.height < this.stage.maxHeight) {
574
- this.stage.grow(this.stage.maxHeight - this.stage.height);
575
- }
576
- const view = caret?.modal
577
- ? placeDialog(promptRows, this.width, this.stage.height, caret?.row ?? 0, caret?.col ?? 0)
578
- : placeHome(this.homeInfo, promptRows, this.width, this.stage.height, caret?.row ?? 0, caret?.col ?? 0);
579
- return this.stage.paint(view.rows, { row: view.caretRow, col: view.caretCol, hideCursor: caret?.hideCursor });
411
+ disableMouse(force = false) {
412
+ if (!force && !this.mouseOn && !this.mouseCaptured)
413
+ return false;
414
+ // Restore terminal motion modes, including stale tracking from an interrupted turn.
415
+ this.writeModeControl(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
416
+ this.writeModeControl(mouseTracking(false));
417
+ this.mouseCaptured = false;
418
+ this.mouseOn = false;
419
+ this.mouseMotionOn = false;
420
+ this.detached = false;
421
+ return true;
580
422
  }
581
-
582
- const width = this.width;
583
- const sidebar = sidebarVisible(width, false, this.env);
584
- const mainWidth = sessionMainWidth(width, false, this.env);
585
- const rail = this.railEnabled(mainWidth);
586
- const contentWidth = rail
587
- ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
588
- : mainWidth;
589
-
590
- let block = Array.isArray(promptRows) && promptRows.length > 0 ? promptRows : [''];
591
- let caretRow = caret && Number.isFinite(caret.row) ? caret.row : Math.max(0, block.length - 1);
592
- let caretCol = caret ? caret.col : 0;
593
-
594
- // Grow the band to what there is to show, before deciding anything else.
595
- //
596
- // Direct chat keeps its printed header and grows with content. A session
597
- // entered from Home occupies the available height at every terminal width.
598
- // Its short transcript is placed next to the input below.
599
- const contentRows = this.transcript.height(contentWidth);
600
- const minFloor = contentRows > 0 ? MIN_VIEWPORT_ROWS : 0;
601
- const neededWithFloor = Math.min(this.stage.maxHeight, block.length + minFloor);
602
- const desired = Math.max(
603
- sessionStageHeight(this.stage.maxHeight, block.length, contentRows, this.fullSession || caret?.inline),
604
- neededWithFloor
605
- );
606
- if (desired > this.stage.height) this.stage.grow(desired - this.stage.height);
607
-
608
- const height = this.stage.height;
609
-
610
- // The prompt may not eat the whole band — but only once there is a
611
- // transcript for it to eat. Trim from the TOP when it would: the status
612
- // footer and the caret row are the last rows and the ones worth keeping,
613
- // and an input box that has scrolled its own oldest row off is a smaller lie
614
- // than a transcript that has vanished.
615
- const floor = contentRows > 0 ? MIN_VIEWPORT_ROWS : 0;
616
- const maxBlock = Math.max(1, height - floor);
617
- if (block.length > maxBlock) {
618
- const cut = block.length - maxBlock;
619
- block = block.slice(cut);
620
- caretRow = Math.max(0, caretRow - cut);
423
+ armTeardown() {
424
+ if (this.signalHooks.length > 0 || this.exitHook)
425
+ this.disarmTeardown();
426
+ this.exitHook = () => { try {
427
+ this.close();
428
+ }
429
+ catch { /* nothing left to do */ } };
430
+ process.once('exit', this.exitHook);
431
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
432
+ const handler = () => {
433
+ try {
434
+ this.close();
435
+ }
436
+ catch { /* keep going: the exit matters more */ }
437
+ // Re-raise the conventional status so a caller waiting on us still sees
438
+ // that we were signalled rather than that we exited cleanly.
439
+ process.exit(128 + SIGNAL_EXIT_CODES[signal]);
440
+ };
441
+ process.on(signal, handler);
442
+ this.signalHooks.push([signal, handler]);
443
+ }
621
444
  }
622
- caretRow = Math.max(0, Math.min(block.length - 1, Math.floor(caretRow)));
623
-
624
- if (this.lastBlockLength > 0 && this.lastBlockLength !== block.length) {
625
- this.stage.invalidate();
445
+ disarmTeardown() {
446
+ if (this.exitHook) {
447
+ process.removeListener('exit', this.exitHook);
448
+ this.exitHook = null;
449
+ }
450
+ for (const [signal, handler] of this.signalHooks)
451
+ process.removeListener(signal, handler);
452
+ this.signalHooks = [];
626
453
  }
627
- this.lastBlockLength = block.length;
628
-
629
- const budget = Math.max(0, height - block.length);
630
- this.syncTurnRailMotion(rail && budget > 0 && hasSessionTurns(this.transcript));
631
- let rows = [];
632
- if (budget > 0) {
633
- this.viewport.resize({ height: budget, width: contentWidth });
634
- rows = alignTranscriptRows(this.viewport.rows(), contentRows);
635
- // In follow mode, the viewport can land on the blank separator between
636
- // two assistant frames after enough replies to fill the band. Show a
637
- // subtle boundary marker in that same row instead of a visible void.
638
- // Do not shift row indices: rails, hover targets and reading anchors
639
- // are keyed to the original transcript row positions.
640
- if (this.viewport.following && this.viewport.maxScrollTop() > 0
641
- && rows.length > 0 && stripAnsi(rows[0] || '').trim() === ''
642
- && rows.some(row => stripAnsi(row).trim() !== '')) {
643
- rows[0] = paint('rule', ` ${GLYPHS.dot} `);
644
- }
645
- this.decorate(rows, contentWidth);
646
- markHoveredMessage(rows, this, contentWidth);
647
- if (rail) {
648
- this.attachRail(rows, contentWidth);
649
- } else {
650
- this.turnRailLayout = null;
651
- this.hoveredTurnIndex = null;
652
- this.hoveredTurnAnchorY = null;
653
- }
654
- if (this.hoveredTurnIndex && this.turnRailLayout?.turns?.length) {
655
- const hoveredTurn = this.turnRailLayout.turns.find(t => t.turnIndex === this.hoveredTurnIndex);
656
- if (hoveredTurn) {
657
- const groupRow = this.turnRailLayout?.dotRows?.get(hoveredTurn.turnIndex);
658
- const group = this.turnRailLayout?.rowToTurns?.get(groupRow) || [hoveredTurn];
659
- const timeline = group.length > 1
660
- ? renderTurnTimelineCard(group, Math.min(52, mainWidth - 5), rows.length, this.turnRailCardOffset || 0)
661
- : null;
662
- const card = timeline?.rows || renderTurnPreviewCard(hoveredTurn, 52);
663
- const anchorY = this.hoveredTurnAnchorY ?? Math.floor(rows.length / 2);
664
- rows = overlayTurnPreviewCard(rows, card, anchorY, this.turnRailLayout?.railX ?? 1, mainWidth);
665
- if (this.turnRailLayout) {
666
- const cardWidth = visibleWidth(card[0] || '') || 52;
667
- const railX = this.turnRailLayout.railX ?? 1;
668
- const safeAnchorY = Number.isFinite(anchorY) ? Math.floor(anchorY) : Math.floor(rows.length / 2);
669
- let cardX = railX - cardWidth - 1;
670
- if (railX <= 4 && railX + 2 < mainWidth) {
671
- cardX = railX + 2;
672
- } else if (cardX < 0) {
673
- cardX = Math.max(0, Math.min(mainWidth - cardWidth - 1, railX + 2));
674
- }
675
- const effectiveCardWidth = Math.max(1, Math.min(cardWidth, Math.max(1, mainWidth - cardX)));
676
- const startY = Math.max(0, Math.min(rows.length - card.length, safeAnchorY - Math.floor(card.length / 2)));
677
- const visibleCardHeight = Math.min(card.length, Math.max(0, rows.length - startY));
678
- this.turnRailLayout.cardRect = {
679
- x: cardX, y: startY, width: effectiveCardWidth, height: visibleCardHeight,
680
- turnIndex: hoveredTurn.turnIndex,
681
- entries: timeline?.entries || null,
682
- entryStart: timeline?.entryStart ?? null,
683
- groupTurns: group.length > 1 ? group : null,
684
- maxOffset: timeline?.maxOffset || 0
685
- };
686
- }
454
+ close() {
455
+ // Force the terminal to release tracking, even if internal flags were stale.
456
+ this.disableMouse(true);
457
+ if (this.unregisterConsoleGuard) {
458
+ this.unregisterConsoleGuard();
459
+ this.unregisterConsoleGuard = null;
460
+ if (this.out === process.stdout)
461
+ setStageConsoleGuardActive(false);
687
462
  }
688
- } else if (this.turnRailLayout) {
689
- this.turnRailLayout.cardRect = null;
690
- }
691
- if (this.messageActionOverlay) {
692
- const overlay = this.messageActionOverlay;
693
- const overlayWidth = rail ? Math.max(contentWidth, mainWidth - RAIL_BUDGET) : contentWidth;
694
- const placed = placeMessageActionPanel(rows, overlay.panel, overlayWidth,
695
- Math.max(0, (this.out.rows || height) - height), overlay.layer.anchorY,
696
- overlay.layer.items.length, {
697
- messageBounds: overlay.layer.messageBounds,
698
- dimBackdrop: true
699
- });
700
- rows = placed.rows;
701
- overlay.layer.actionLayout = placed.layout;
702
- }
703
- } else {
704
- this.turnRailLayout = null;
705
- this.hoveredTurnIndex = null;
706
- this.hoveredTurnAnchorY = null;
463
+ if (!this.stage.reserved) {
464
+ this.disarmTeardown();
465
+ return false;
466
+ }
467
+ const rows = this.snapshot();
468
+ this.stage.collapse();
469
+ this.stage.printThrough(rows);
470
+ this.disarmTeardown();
471
+ return true;
707
472
  }
708
-
709
- const mainRows = rows.concat(block);
710
- const panelWidth = sidebar ? sessionSidebarWidth(width, false, this.env) : 0;
711
- const panelRows = sidebar ? sessionSidebarRows({
712
- ...this.sessionInfo,
713
- cwd: this.sidebarStatus?.cwd || this.sessionInfo?.cwd,
714
- provider: this.sidebarStatus?.provider || this.sessionInfo?.provider,
715
- model: this.sidebarStatus?.model || this.sessionInfo?.model,
716
- contextChars: this.sidebarStatus?.contextChars ?? this.sessionInfo?.contextChars,
717
- contextLimit: this.sidebarStatus?.contextLimit ?? this.sessionInfo?.contextLimit,
718
- plan: this.sidebarPlan,
719
- activeSkill: this.sessionInfo?.activeSkill
720
- }, mainRows.length, panelWidth) : [];
721
- const painted = sidebar ? joinSessionSidebar(mainRows, panelRows, mainWidth, panelWidth) : mainRows;
722
- return this.stage.paint(painted, {
723
- row: rows.length + caretRow,
724
- // The composer may never put its caret into the sidebar or the reserved
725
- // right margin, even if layout measurements differ after a resize.
726
- col: Math.max(0, Math.min(mainWidth - 2, Number.isFinite(caretCol) ? Math.floor(caretCol) : 0)),
727
- hideCursor: caret?.hideCursor
728
- });
729
- }
730
-
731
- /** Draw message actions over the transcript while retaining the live composer. */
732
- presentMessageActions(panel, layer) {
733
- this.messageActionOverlay = { panel, layer };
734
- try {
735
- return this.present(this.lastPromptRows, this.lastPromptCaret);
736
- } finally {
737
- this.messageActionOverlay = null;
473
+ suspend() {
474
+ if (!this.stage.reserved)
475
+ return false;
476
+ this.disableMouse();
477
+ if (this.unregisterConsoleGuard) {
478
+ this.unregisterConsoleGuard();
479
+ this.unregisterConsoleGuard = null;
480
+ if (this.out === process.stdout)
481
+ setStageConsoleGuardActive(false);
482
+ }
483
+ this.stage.collapse();
484
+ return true;
738
485
  }
739
- }
740
-
741
- /**
742
- * The one thing on screen that opencode does not have: while the view is held
743
- * away from the bottom, say so and say how much arrived.
744
- *
745
- * Without it, un-following is invisible — the transcript simply stops moving
746
- * and the user cannot tell whether the agent stalled or they scrolled.
747
- */
748
- decorate(rows, width) {
749
- const state = this.viewport.state();
750
- if (state.following) return rows;
751
-
752
- const count = state.unseen;
753
- const label = count > 0
754
- ? `${GLYPHS.arrow} ${count} new below`
755
- : `${GLYPHS.arrow} scrolled up`;
756
- const hint = `${label} ${GLYPHS.dot} shift+pgdn to follow`;
757
- rows[rows.length - 1] = paint('accent', truncate(hint, Math.max(8, width - 1), GLYPHS.ellipsis));
758
- return rows;
759
- }
760
-
761
- /**
762
- * Ctrl+L: flush what is on the stage into real scrollback, then start clean.
763
- *
764
- * In a terminal, ctrl+L clears the screen and your history is still in
765
- * scrollback. Clearing the transcript alone would destroy the session record,
766
- * which is not what the key means — so print it through first. This is also
767
- * the escape hatch for getting a transcript into the terminal without exiting.
768
- */
769
- flushAndClear() {
770
- const rows = this.snapshot();
771
- this.stage.collapse();
772
- this.stage.printThrough(rows);
773
- this.evicted = [];
774
- this.transcript.clear();
775
- this.lastHeight = 0;
776
- this.stage.reserve();
777
- this.stage.invalidate();
778
- this.viewport.toBottom();
779
- return rows.length;
780
- }
781
-
782
- /** Clear the transcript without printing through to scrollback (for session switching). */
783
- clearTranscript() {
784
- this.evicted = [];
785
- this.transcript.clear();
786
- this.lastHeight = 0;
787
- this.lastUserTurnCount = 0;
788
- this.activeTurnIndex = null;
789
- this.hoveredTurnIndex = null;
790
- this.hoveredTurnAnchorY = null;
791
- this.turnRailLayout = null;
792
- this.stage.invalidate();
793
- if (this.viewport) {
794
- this.viewport.manual = false;
795
- this.viewport.unseen = 0;
796
- this.viewport.toBottom();
486
+ resume() {
487
+ if (this.stage.reserved)
488
+ return false;
489
+ if (!this.stage.reserve())
490
+ return false;
491
+ this.unregisterConsoleGuard?.();
492
+ this.unregisterConsoleGuard = registerStageConsoleGuard(this);
493
+ if (this.out === process.stdout)
494
+ setStageConsoleGuardActive(true);
495
+ this.stage.invalidate();
496
+ this.enableMouse();
497
+ return true;
797
498
  }
798
- }
799
-
800
- /**
801
- * The terminal changed size. Callers must debounce — ChatPrompt already
802
- * settles resize at RESIZE_SETTLE_MS.
803
- */
804
- resize() {
805
- const next = stageHeight(this.out, this.env);
806
- if (next < 1) {
807
- // The terminal became too short to hold a stage. Give the band back and
808
- // let the caller fall through to the scrollback renderer rather than
809
- // painting into a region that cannot hold a viewport.
810
- this.close();
811
- return false;
499
+ /** Everything the session produced, oldest first. */
500
+ snapshot() {
501
+ return this.evicted.concat(this.transcript.snapshot(this.width));
812
502
  }
813
- // A width-only resize must not collapse and re-claim the whole session.
814
- // Claiming fresh lines on every drag scrolls the transcript and leaves
815
- // obsolete sidebar columns behind during the 160-column breakpoint.
816
- // The existing rows are already reserved: repaint them in place with
817
- // their new width, clearing trailing cells through Stage.paint().
818
- const columns = this.stage.width();
819
- if (columns !== this.lastColumns || next !== this.stage.maxHeight) {
820
- this.hoveredTurnIndex = null;
821
- this.hoveredTurnAnchorY = null;
503
+ absorbEvicted(rows) {
504
+ for (const row of rows)
505
+ this.evicted.push(row);
506
+ if (this.evicted.length > MAX_EVICTED_ROWS) {
507
+ this.evicted.splice(0, this.evicted.length - MAX_EVICTED_ROWS);
508
+ }
822
509
  }
823
- if (!this.stage.reserved || next !== this.stage.maxHeight) {
824
- this.stage.resize(next, 1);
825
- } else if (columns !== this.lastColumns && !this.detached) {
826
- // macOS Terminal may physically reflow rows when the sidebar appears
827
- // or disappears. The old caret row is then no longer a reliable anchor.
828
- this.stage.reanchor();
510
+ handleChange() {
511
+ if (!this.transcript.isEmpty())
512
+ this.opened = true;
513
+ let userTurns = 0;
514
+ for (const frame of this.transcript.frames) {
515
+ if (frame && frame.kind === 'user')
516
+ userTurns++;
517
+ }
518
+ if (userTurns > this.lastUserTurnCount) {
519
+ this.activeTurnIndex = null;
520
+ this.hoveredTurnIndex = null;
521
+ this.hoveredTurnAnchorY = null;
522
+ }
523
+ this.lastUserTurnCount = userTurns;
524
+ const before = this.lastHeight;
525
+ const mainWidth = sessionMainWidth(this.width, false, this.env);
526
+ const contentWidth = this.railEnabled(mainWidth)
527
+ ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
528
+ : mainWidth;
529
+ const after = this.transcript.height(contentWidth);
530
+ this.lastHeight = after;
531
+ // Growth is what drives auto-scroll. Handing the delta over is also what
532
+ // lets the "N new below" affordance count only what arrived while the user
533
+ // was reading somewhere else.
534
+ this.viewport.refresh(Math.max(0, after - before));
535
+ if (this.onDirty)
536
+ this.onDirty();
829
537
  }
830
- this.lastColumns = columns;
831
- this.stage.invalidate();
832
- // Re-derive from the new geometry: growing the viewport lowers maxScrollTop,
833
- // and leaving scrollTop above it would read as "the user scrolled away".
834
- const mainWidth = sessionMainWidth(this.width, false, this.env);
835
- const contentWidth = this.railEnabled(mainWidth)
836
- ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
837
- : mainWidth;
838
- this.viewport.resize({ height: Math.max(MIN_VIEWPORT_ROWS, this.stage.height - 2), width: contentWidth });
839
- this.lastHeight = this.transcript.height(contentWidth);
840
- return this.stage.reserved;
841
- }
842
-
843
- /**
844
- * Does this terminal get a rail?
845
- */
846
- railEnabled(width) {
847
- if (String(this.env.CAUSYNE_RAIL ?? '1') === '0') return false;
848
- return width >= RAIL_MIN_WIDTH;
849
- }
850
-
851
- /**
852
- * The rail: the WHOLE session compressed into one column, plus where you are
853
- * in it.
854
- *
855
- * Proportional, not per-row. A per-row gutter would only mark what is already
856
- * on screen, which tells you nothing you cannot see; mapping the entire
857
- * transcript onto the column means a glance answers "how far in am I, and is
858
- * there anything back there worth going to". opencode has no equivalent —
859
- * its scrollbar reports position and nothing about content.
860
- *
861
- * Returns `height` single-column strings.
862
- */
863
- buildRail(height, contentWidth) {
864
- const flat = typeof this.transcript.flatten === 'function' ? this.transcript.flatten(contentWidth) : null;
865
- const flatRows = Array.isArray(flat?.rows) ? flat.rows : [];
866
- const markers = Array.isArray(flat?.markers) ? flat.markers : this.transcript.markers(contentWidth);
867
- const rawTotal = Math.max(0, flat ? flatRows.length : this.transcript.height(contentWidth));
868
- const total = Math.max(1, rawTotal);
869
- const padding = rawTotal <= height ? Math.max(0, height - rawTotal) : 0;
870
- const slotOf = (row) => (rawTotal <= height
871
- ? Math.max(0, Math.min(height - 1, padding + row))
872
- : Math.max(0, Math.min(height - 1, Math.floor((row / total) * height))));
873
-
874
- const kinds = new Array(height).fill(null);
875
- for (let mIdx = 0; mIdx < markers.length; mIdx++) {
876
- const marker = markers[mIdx];
877
- // Suppress repetitive step/result/reasoning noise on the overview rail.
878
- // Checkpoints, user turns, approvals, and errors remain discoverable.
879
- if ((RAIL_PRIORITY[marker.kind] || 0) < 50) continue;
880
- let markerRow = marker.row;
881
- if (marker.kind === 'user' && flatRows.length > 0) {
882
- const nextRow = mIdx + 1 < markers.length ? markers[mIdx + 1].row : flatRows.length;
883
- if (markerRow + 1 < nextRow && markerRow + 1 < flatRows.length) {
884
- const firstLine = stripAnsi(String(flatRows[markerRow] ?? '')).trim();
885
- const secondLine = stripAnsi(String(flatRows[markerRow + 1] ?? '')).trim();
886
- if (firstLine === '' && secondLine !== '') markerRow += 1;
538
+ // -------------------------------------------------------------------------
539
+ // The interface ChatPrompt calls
540
+ // -------------------------------------------------------------------------
541
+ /**
542
+ * Append a permanent frame. `produce` must be a pure function of width — see
543
+ * the contract in transcript.js.
544
+ */
545
+ commit(kind, produce, meta = null) {
546
+ return this.transcript.append({ kind, produce, meta });
547
+ }
548
+ /**
549
+ * Paint the band: viewport on top, the prompt's own rows underneath.
550
+ */
551
+ present(promptRows, caret = null) {
552
+ if (!this.stage.reserved)
553
+ return 0;
554
+ const safePromptRows = Array.isArray(promptRows) ? promptRows : [];
555
+ promptRows = safePromptRows;
556
+ if (!this.messageActionOverlay) {
557
+ this.lastPromptRows = promptRows;
558
+ this.lastPromptCaret = caret;
559
+ }
560
+ // Do not grow, resize, or invalidate the band while the terminal owns
561
+ // scrollback; otherwise stage.grow emits newlines that shift the user's
562
+ // scroll position before the detached repaint guard below.
563
+ if (this.detached)
564
+ return false;
565
+ const isModal = Boolean(caret?.modal);
566
+ if (isModal !== this.wasModal) {
567
+ this.wasModal = isModal;
568
+ this.stage.invalidate();
569
+ }
570
+ if (this.homeInfo || (caret?.modal && !caret?.inline)) {
571
+ this.syncTurnRailMotion(false);
572
+ this.turnRailLayout = null;
573
+ this.hoveredTurnIndex = null;
574
+ this.hoveredTurnAnchorY = null;
575
+ if (this.stage.height < this.stage.maxHeight) {
576
+ this.stage.grow(this.stage.maxHeight - this.stage.height);
577
+ }
578
+ const view = caret?.modal
579
+ ? placeDialog(promptRows, this.width, this.stage.height, caret?.row ?? 0, caret?.col ?? 0)
580
+ : placeHome(this.homeInfo || {}, promptRows, this.width, this.stage.height, caret?.row ?? 0, caret?.col ?? 0);
581
+ return this.stage.paint(view.rows, {
582
+ row: view.caretRow,
583
+ col: view.caretCol,
584
+ ...(caret?.hideCursor !== undefined ? { hideCursor: caret.hideCursor } : {})
585
+ });
887
586
  }
888
- }
889
- const slot = slotOf(markerRow);
890
- const held = kinds[slot];
891
- if (!held || (RAIL_PRIORITY[marker.kind] || 0) > (RAIL_PRIORITY[held] || 0)) {
892
- kinds[slot] = marker.kind;
893
- }
587
+ const width = this.width;
588
+ const sidebar = sidebarVisible(width, false, this.env);
589
+ const mainWidth = sessionMainWidth(width, false, this.env);
590
+ const rail = this.railEnabled(mainWidth);
591
+ const contentWidth = rail
592
+ ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
593
+ : mainWidth;
594
+ let block = Array.isArray(promptRows) && promptRows.length > 0 ? promptRows : [''];
595
+ let caretRow = caret && typeof caret.row === 'number' && Number.isFinite(caret.row) ? caret.row : Math.max(0, block.length - 1);
596
+ const caretCol = caret && typeof caret.col === 'number' ? caret.col : 0;
597
+ const contentRows = this.transcript.height(contentWidth);
598
+ const minFloor = contentRows > 0 ? MIN_VIEWPORT_ROWS : 0;
599
+ const neededWithFloor = Math.min(this.stage.maxHeight, block.length + minFloor);
600
+ const desired = Math.max(sessionStageHeight(this.stage.maxHeight, block.length, contentRows, Boolean(this.fullSession || caret?.inline)), neededWithFloor);
601
+ if (desired > this.stage.height)
602
+ this.stage.grow(desired - this.stage.height);
603
+ const height = this.stage.height;
604
+ const floor = contentRows > 0 ? MIN_VIEWPORT_ROWS : 0;
605
+ const maxBlock = Math.max(1, height - floor);
606
+ if (block.length > maxBlock) {
607
+ const cut = block.length - maxBlock;
608
+ block = block.slice(cut);
609
+ caretRow = Math.max(0, caretRow - cut);
610
+ }
611
+ caretRow = Math.max(0, Math.min(block.length - 1, Math.floor(caretRow)));
612
+ if (this.lastBlockLength > 0 && this.lastBlockLength !== block.length) {
613
+ this.stage.invalidate();
614
+ }
615
+ this.lastBlockLength = block.length;
616
+ const budget = Math.max(0, height - block.length);
617
+ this.syncTurnRailMotion(rail && budget > 0 && hasSessionTurns(this.transcript));
618
+ let rows = [];
619
+ if (budget > 0) {
620
+ this.viewport.resize({ height: budget, width: contentWidth });
621
+ rows = alignTranscriptRows(this.viewport.rows(), contentRows);
622
+ if (this.viewport.following && this.viewport.maxScrollTop() > 0
623
+ && rows.length > 0 && stripAnsi(rows[0] || '').trim() === ''
624
+ && rows.some(row => stripAnsi(row).trim() !== '')) {
625
+ rows[0] = paint('rule', ` ${GLYPHS.dot} `);
626
+ }
627
+ this.decorate(rows, contentWidth);
628
+ markHoveredMessage(rows, this, contentWidth);
629
+ if (rail) {
630
+ this.attachRail(rows, contentWidth);
631
+ }
632
+ else {
633
+ this.turnRailLayout = null;
634
+ this.hoveredTurnIndex = null;
635
+ this.hoveredTurnAnchorY = null;
636
+ }
637
+ if (this.hoveredTurnIndex && this.turnRailLayout?.turns?.length) {
638
+ const hoveredTurn = this.turnRailLayout.turns.find((t) => t.turnIndex === this.hoveredTurnIndex);
639
+ if (hoveredTurn) {
640
+ const groupRow = this.turnRailLayout?.dotRows?.get(hoveredTurn.turnIndex);
641
+ const group = this.turnRailLayout?.rowToTurns?.get(groupRow) || [hoveredTurn];
642
+ const timeline = group.length > 1
643
+ ? renderTurnTimelineCard(group, Math.min(52, mainWidth - 5), rows.length, this.turnRailCardOffset || 0)
644
+ : null;
645
+ const card = timeline?.rows || renderTurnPreviewCard(hoveredTurn, 52);
646
+ const anchorY = this.hoveredTurnAnchorY ?? Math.floor(rows.length / 2);
647
+ rows = overlayTurnPreviewCard(rows, card, anchorY, this.turnRailLayout?.railX ?? 1, mainWidth);
648
+ if (this.turnRailLayout) {
649
+ const cardWidth = visibleWidth(card[0] || '') || 52;
650
+ const railX = this.turnRailLayout.railX ?? 1;
651
+ const safeAnchorY = Number.isFinite(anchorY) ? Math.floor(anchorY) : Math.floor(rows.length / 2);
652
+ let cardX = railX - cardWidth - 1;
653
+ if (railX <= 4 && railX + 2 < mainWidth) {
654
+ cardX = railX + 2;
655
+ }
656
+ else if (cardX < 0) {
657
+ cardX = Math.max(0, Math.min(mainWidth - cardWidth - 1, railX + 2));
658
+ }
659
+ const effectiveCardWidth = Math.max(1, Math.min(cardWidth, Math.max(1, mainWidth - cardX)));
660
+ const startY = Math.max(0, Math.min(rows.length - card.length, safeAnchorY - Math.floor(card.length / 2)));
661
+ const visibleCardHeight = Math.min(card.length, Math.max(0, rows.length - startY));
662
+ this.turnRailLayout.cardRect = {
663
+ x: cardX, y: startY, width: effectiveCardWidth, height: visibleCardHeight,
664
+ turnIndex: hoveredTurn.turnIndex,
665
+ entries: timeline?.entries || null,
666
+ entryStart: timeline?.entryStart ?? null,
667
+ groupTurns: group.length > 1 ? group : null,
668
+ maxOffset: timeline?.maxOffset || 0
669
+ };
670
+ }
671
+ }
672
+ }
673
+ else if (this.turnRailLayout) {
674
+ this.turnRailLayout.cardRect = null;
675
+ }
676
+ if (this.messageActionOverlay) {
677
+ const overlay = this.messageActionOverlay;
678
+ const overlayWidth = rail ? Math.max(contentWidth, mainWidth - RAIL_BUDGET) : contentWidth;
679
+ const placed = placeMessageActionPanel(rows, overlay.panel, overlayWidth, Math.max(0, (this.out.rows || height) - height), overlay.layer.anchorY, overlay.layer.items.length, {
680
+ messageBounds: overlay.layer.messageBounds,
681
+ dimBackdrop: true
682
+ });
683
+ rows = placed.rows;
684
+ overlay.layer.actionLayout = placed.layout;
685
+ }
686
+ }
687
+ else {
688
+ this.turnRailLayout = null;
689
+ this.hoveredTurnIndex = null;
690
+ this.hoveredTurnAnchorY = null;
691
+ }
692
+ const mainRows = rows.concat(block);
693
+ const panelWidth = sidebar ? sessionSidebarWidth(width, false, this.env) : 0;
694
+ const panelRows = sidebar ? sessionSidebarRows({
695
+ ...this.sessionInfo,
696
+ cwd: this.sidebarStatus?.cwd || this.sessionInfo?.cwd,
697
+ provider: this.sidebarStatus?.provider || this.sessionInfo?.provider,
698
+ model: this.sidebarStatus?.model || this.sessionInfo?.model,
699
+ contextChars: this.sidebarStatus?.contextChars ?? this.sessionInfo?.contextChars,
700
+ contextLimit: this.sidebarStatus?.contextLimit ?? this.sessionInfo?.contextLimit,
701
+ plan: this.sidebarPlan,
702
+ activeSkill: this.sessionInfo?.activeSkill
703
+ }, mainRows.length, panelWidth) : [];
704
+ const painted = sidebar ? joinSessionSidebar(mainRows, panelRows, mainWidth, panelWidth) : mainRows;
705
+ return this.stage.paint(painted, {
706
+ row: rows.length + caretRow,
707
+ // The composer may never put its caret into the sidebar or the reserved
708
+ // right margin, even if layout measurements differ after a resize.
709
+ col: Math.max(0, Math.min(mainWidth - 2, Number.isFinite(caretCol) ? Math.floor(caretCol) : 0)),
710
+ ...(caret?.hideCursor !== undefined ? { hideCursor: caret.hideCursor } : {})
711
+ });
894
712
  }
895
-
896
- const state = this.viewport.state();
897
- // Nothing to scroll, no thumb. A scrollbar whose track is full says the same
898
- // thing as no scrollbar at all, and on an empty session it filled the whole
899
- // column with position indicator for a position that could not change —
900
- // noise where the rail is supposed to be information.
901
- const scrollable = state.max > 0;
902
- const from = scrollable ? slotOf(state.scrollTop) : -1;
903
- const to = scrollable ? slotOf(Math.max(state.scrollTop, state.scrollTop + state.height - 1)) : -2;
904
-
905
- const cells = new Array(height);
906
- for (let i = 0; i < height; i++) {
907
- const inThumb = i >= from && i <= to;
908
- const kind = kinds[i];
909
- const loud = kind && (RAIL_PRIORITY[kind] || 0) >= RAIL_THUMB_YIELD;
910
- if (kind && (!inThumb || loud)) cells[i] = railGlyph(kind);
911
- else if (inThumb) cells[i] = paint('scroll', thumbGlyph(i - from, to - from + 1));
912
- else cells[i] = ' ';
713
+ /** Draw message actions over the transcript while retaining the live composer. */
714
+ presentMessageActions(panel, layer) {
715
+ this.messageActionOverlay = { panel, layer };
716
+ try {
717
+ return this.present(this.lastPromptRows, this.lastPromptCaret);
718
+ }
719
+ finally {
720
+ this.messageActionOverlay = null;
721
+ }
913
722
  }
914
- return cells;
915
- }
916
-
917
- /**
918
- * Lay the rail beside the viewport rows.
919
- *
920
- * The rows were rendered at contentWidth, so padding them out to it is what
921
- * keeps the rail in one column instead of ragged against the text.
922
- */
923
- attachRail(rows, contentWidth) {
924
- const turns = collectSessionTurns(this.transcript, contentWidth);
925
- const hasTurns = turns.length > 0;
926
- const isAtBottom = typeof this.viewport?.atBottom === 'function' ? this.viewport.atBottom() : false;
927
- const scrollTop = this.viewport.state().scrollTop;
928
- const activeTurn = this.activeTurnIndex || resolveActiveTurnIndex(turns, scrollTop, rows.length, isAtBottom);
929
- const railResult = hasTurns
930
- ? buildTurnRailCells(turns, rows.length, activeTurn, this.hoveredTurnIndex, scrollTop)
931
- : null;
932
-
933
- // Keep the original sparse rail. Cluster every turn behind the nearest
934
- // *visible* dot so no unseen history becomes impossible to reach.
935
- const rowToTurns = new Map();
936
- const dotRows = [...(railResult?.layout?.rowToTurn?.keys() || [])].sort((a, b) => a - b);
937
- for (const turn of turns) {
938
- const rawRow = railResult?.layout?.dotRows?.get(turn.turnIndex);
939
- if (!Number.isFinite(rawRow) || dotRows.length === 0) continue;
940
- let nearest = dotRows[0];
941
- let distance = Math.abs(rawRow - nearest);
942
- for (const dotRow of dotRows) {
943
- const delta = Math.abs(rawRow - dotRow);
944
- if (delta < distance) {
945
- nearest = dotRow;
946
- distance = delta;
723
+ decorate(rows, width) {
724
+ const state = this.viewport.state();
725
+ if (state.following)
726
+ return rows;
727
+ const count = state.unseen;
728
+ const label = count > 0
729
+ ? `${GLYPHS.arrow} ${count} new below`
730
+ : `${GLYPHS.arrow} scrolled up`;
731
+ const hint = `${label} ${GLYPHS.dot} shift+pgdn to follow`;
732
+ if (rows.length > 0) {
733
+ rows[rows.length - 1] = paint('accent', truncate(hint, Math.max(8, width - 1), GLYPHS.ellipsis));
947
734
  }
948
- }
949
- if (!rowToTurns.has(nearest)) rowToTurns.set(nearest, []);
950
- rowToTurns.get(nearest).push(turn);
735
+ return rows;
951
736
  }
952
- this.turnRailLayout = {
953
- railX: hasTurns ? 1 : contentWidth + 1,
954
- rowToTurns,
955
- stageTop: Math.max(0, (this.out.rows || this.stage.height) - this.stage.height),
956
- viewportHeight: rows.length,
957
- dotRows: railResult?.layout?.dotRows || new Map(),
958
- rowToTurn: railResult?.layout?.rowToTurn || new Map(),
959
- turns
960
- };
961
-
962
- const rail = this.buildRail(rows.length, contentWidth);
963
- for (let i = 0; i < rows.length; i++) {
964
- const rightCell = rail[i] || ' ';
965
- let row = rows[i] || '';
966
- if (hasTurns && railResult) {
967
- const leftCell = railResult.cells[i] || ' ';
968
- const leadEnd = leadingAnsiControlEnd(row);
969
- if (row.slice(leadEnd, leadEnd + 3) === ' ') {
970
- const leadEscapes = row.slice(0, leadEnd);
971
- row = `${leadEscapes} ${leftCell} ${row.slice(leadEnd + 3)}`;
972
- } else if (stripAnsi(row).length === 0) {
973
- row = leftCell !== ' ' ? ` ${leftCell} ` : '';
974
- } else {
975
- row = ` ${leftCell} ${row}`;
737
+ flushAndClear() {
738
+ const rows = this.snapshot();
739
+ this.stage.collapse();
740
+ this.stage.printThrough(rows);
741
+ this.evicted = [];
742
+ this.transcript.clear();
743
+ this.lastHeight = 0;
744
+ this.stage.reserve();
745
+ this.stage.invalidate();
746
+ this.viewport.toBottom();
747
+ return rows.length;
748
+ }
749
+ /** Clear the transcript without printing through to scrollback (for session switching). */
750
+ clearTranscript() {
751
+ this.evicted = [];
752
+ this.transcript.clear();
753
+ this.lastHeight = 0;
754
+ this.lastUserTurnCount = 0;
755
+ this.activeTurnIndex = null;
756
+ this.hoveredTurnIndex = null;
757
+ this.hoveredTurnAnchorY = null;
758
+ this.turnRailLayout = null;
759
+ this.stage.invalidate();
760
+ if (this.viewport) {
761
+ this.viewport.manual = false;
762
+ this.viewport.unseen = 0;
763
+ this.viewport.toBottom();
764
+ }
765
+ }
766
+ resize() {
767
+ const next = stageHeight(this.out, this.env);
768
+ if (next < 1) {
769
+ this.close();
770
+ return false;
771
+ }
772
+ const columns = this.stage.width();
773
+ if (columns !== this.lastColumns || next !== this.stage.maxHeight) {
774
+ this.hoveredTurnIndex = null;
775
+ this.hoveredTurnAnchorY = null;
776
+ }
777
+ if (!this.stage.reserved || next !== this.stage.maxHeight) {
778
+ this.stage.resize(next, 1);
779
+ }
780
+ else if (columns !== this.lastColumns && !this.detached) {
781
+ this.stage.reanchor();
782
+ }
783
+ this.lastColumns = columns;
784
+ this.stage.invalidate();
785
+ const mainWidth = sessionMainWidth(this.width, false, this.env);
786
+ const contentWidth = this.railEnabled(mainWidth)
787
+ ? Math.max(20, mainWidth - RAIL_BUDGET - (hasSessionTurns(this.transcript) ? TURN_RAIL_BUDGET : 0))
788
+ : mainWidth;
789
+ this.viewport.resize({ height: Math.max(MIN_VIEWPORT_ROWS, this.stage.height - 2), width: contentWidth });
790
+ this.lastHeight = this.transcript.height(contentWidth);
791
+ return this.stage.reserved;
792
+ }
793
+ railEnabled(width) {
794
+ if (String(this.env.CAUSYNE_RAIL ?? '1') === '0')
795
+ return false;
796
+ return width >= RAIL_MIN_WIDTH;
797
+ }
798
+ buildRail(height, contentWidth) {
799
+ const flat = typeof this.transcript.flatten === 'function' ? this.transcript.flatten(contentWidth) : null;
800
+ const flatRows = Array.isArray(flat?.rows) ? flat.rows : [];
801
+ const markers = Array.isArray(flat?.markers) ? flat.markers : this.transcript.markers(contentWidth);
802
+ const rawTotal = Math.max(0, flat ? flatRows.length : this.transcript.height(contentWidth));
803
+ const total = Math.max(1, rawTotal);
804
+ const padding = rawTotal <= height ? Math.max(0, height - rawTotal) : 0;
805
+ const slotOf = (row) => (rawTotal <= height
806
+ ? Math.max(0, Math.min(height - 1, padding + row))
807
+ : Math.max(0, Math.min(height - 1, Math.floor((row / total) * height))));
808
+ const kinds = new Array(height).fill(null);
809
+ for (let mIdx = 0; mIdx < markers.length; mIdx++) {
810
+ const marker = markers[mIdx];
811
+ if (!marker)
812
+ continue;
813
+ if (railPriority(marker.kind) < 50)
814
+ continue;
815
+ let markerRow = marker.row;
816
+ if (marker.kind === 'user' && flatRows.length > 0) {
817
+ const nextRow = mIdx + 1 < markers.length ? (markers[mIdx + 1]?.row ?? flatRows.length) : flatRows.length;
818
+ if (markerRow + 1 < nextRow && markerRow + 1 < flatRows.length) {
819
+ const firstLine = stripAnsi(String(flatRows[markerRow] ?? '')).trim();
820
+ const secondLine = stripAnsi(String(flatRows[markerRow + 1] ?? '')).trim();
821
+ if (firstLine === '' && secondLine !== '')
822
+ markerRow += 1;
823
+ }
824
+ }
825
+ const slot = slotOf(markerRow);
826
+ const held = kinds[slot];
827
+ if (!held || railPriority(marker.kind) > railPriority(held)) {
828
+ kinds[slot] = marker.kind;
829
+ }
976
830
  }
977
- }
978
- // Turn markers consume their own three-column lane. Preserve ALL
979
- // previously rendered command text instead of clipping its last cells.
980
- const rowWidth = contentWidth + (hasTurns ? TURN_RAIL_BUDGET : 0);
981
- const paddedRow = padEnd(truncate(row, rowWidth, ''), rowWidth);
982
- const railReset = paddedRow.includes('\x1b[') ? '\x1b[0m' : '';
983
- rows[i] = `${paddedRow}${railReset} ${rightCell}`;
831
+ const state = this.viewport.state();
832
+ const scrollable = state.max > 0;
833
+ const from = scrollable ? slotOf(state.scrollTop) : -1;
834
+ const to = scrollable ? slotOf(Math.max(state.scrollTop, state.scrollTop + state.height - 1)) : -2;
835
+ const cells = new Array(height);
836
+ for (let i = 0; i < height; i++) {
837
+ const inThumb = i >= from && i <= to;
838
+ const kind = kinds[i];
839
+ const loud = Boolean(kind) && railPriority(kind) >= RAIL_THUMB_YIELD;
840
+ if (kind && (!inThumb || loud))
841
+ cells[i] = railGlyph(kind);
842
+ else if (inThumb)
843
+ cells[i] = paint('scroll', thumbGlyph(i - from, to - from + 1));
844
+ else
845
+ cells[i] = ' ';
846
+ }
847
+ return cells;
848
+ }
849
+ attachRail(rows, contentWidth) {
850
+ const turns = collectSessionTurns(this.transcript, contentWidth);
851
+ const hasTurns = turns.length > 0;
852
+ const isAtBottom = typeof this.viewport?.atBottom === 'function' ? this.viewport.atBottom() : false;
853
+ const scrollTop = this.viewport.state().scrollTop;
854
+ const activeTurn = this.activeTurnIndex || resolveActiveTurnIndex(turns, scrollTop, rows.length, isAtBottom);
855
+ const railResult = hasTurns
856
+ ? buildTurnRailCells(turns, rows.length, activeTurn, this.hoveredTurnIndex ?? null, scrollTop)
857
+ : null;
858
+ const rowToTurns = new Map();
859
+ const dotRows = [...(railResult?.layout?.rowToTurn?.keys() || [])].sort((a, b) => a - b);
860
+ for (const turn of turns) {
861
+ const rawRow = railResult?.layout?.dotRows?.get(turn.turnIndex);
862
+ if (rawRow === undefined || !Number.isFinite(rawRow) || dotRows.length === 0)
863
+ continue;
864
+ let nearest = dotRows[0] ?? 0;
865
+ let distance = Math.abs(rawRow - nearest);
866
+ for (const dotRow of dotRows) {
867
+ const delta = Math.abs(rawRow - dotRow);
868
+ if (delta < distance) {
869
+ nearest = dotRow;
870
+ distance = delta;
871
+ }
872
+ }
873
+ const bucket = rowToTurns.get(nearest) ?? [];
874
+ bucket.push(turn);
875
+ rowToTurns.set(nearest, bucket);
876
+ }
877
+ this.turnRailLayout = {
878
+ railX: hasTurns ? 1 : contentWidth + 1,
879
+ rowToTurns,
880
+ stageTop: Math.max(0, (this.out.rows || this.stage.height) - this.stage.height),
881
+ viewportHeight: rows.length,
882
+ dotRows: railResult?.layout?.dotRows || new Map(),
883
+ rowToTurn: railResult?.layout?.rowToTurn || new Map(),
884
+ turns
885
+ };
886
+ const rail = this.buildRail(rows.length, contentWidth);
887
+ for (let i = 0; i < rows.length; i++) {
888
+ const rightCell = rail[i] || ' ';
889
+ let row = rows[i] || '';
890
+ if (hasTurns && railResult) {
891
+ const leftCell = railResult.cells[i] || ' ';
892
+ const leadEnd = leadingAnsiControlEnd(row);
893
+ if (row.slice(leadEnd, leadEnd + 3) === ' ') {
894
+ const leadEscapes = row.slice(0, leadEnd);
895
+ row = `${leadEscapes} ${leftCell} ${row.slice(leadEnd + 3)}`;
896
+ }
897
+ else if (stripAnsi(row).length === 0) {
898
+ row = leftCell !== ' ' ? ` ${leftCell} ` : '';
899
+ }
900
+ else {
901
+ row = ` ${leftCell} ${row}`;
902
+ }
903
+ }
904
+ const rowWidth = contentWidth + (hasTurns ? TURN_RAIL_BUDGET : 0);
905
+ const paddedRow = padEnd(truncate(row, rowWidth, ''), rowWidth);
906
+ const railReset = paddedRow.includes('\x1b[') ? '\x1b[0m' : '';
907
+ rows[i] = `${paddedRow}${railReset} ${rightCell}`;
908
+ }
909
+ return rows;
910
+ }
911
+ releaseMouse() {
912
+ if (!this.mouseCaptured)
913
+ return false;
914
+ // Auto-enabled rail hover must be disarmed even without env opt-in.
915
+ this.writeModeControl(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
916
+ this.writeModeControl(mouseTracking(false));
917
+ this.mouseCaptured = false;
918
+ this.mouseMotionOn = false;
919
+ this.detached = true;
920
+ return true;
921
+ }
922
+ /** Take it back, once the user is driving the band again. */
923
+ captureMouse() {
924
+ // Home and suspended stages must not arm modes their teardown cannot observe.
925
+ if (!this.mouseWanted || !this.mouseOn || !this.stage.reserved || this.mouseCaptured)
926
+ return false;
927
+ this.writeModeControl(mouseTracking(true));
928
+ this.writeModeControl(mouseHoverTracking(true, this.env));
929
+ this.mouseCaptured = true;
930
+ this.mouseMotionOn = String(this.env?.CAUSYNE_MOUSE_HOVER ?? '') === '1';
931
+ this.detached = false;
932
+ // After native scrollback, the former physical cursor location is unknown.
933
+ // Return to the screen bottom before repainting any transcript rows.
934
+ this.stage.reanchor();
935
+ return true;
984
936
  }
985
- return rows;
986
- }
987
-
988
- /**
989
- * Hand the wheel back to the terminal.
990
- *
991
- * THE SEAM THIS EXISTS FOR. Two things scroll: this band's viewport, and the
992
- * terminal's own scrollback above it, which holds everything already flushed.
993
- * With ?1000 on, the app receives every wheel report and the terminal receives
994
- * none — so once the viewport reached its top, scrolling further did nothing
995
- * at all and the earlier conversation was unreachable by wheel. Releasing at
996
- * the boundary is what makes the two halves feel like one scroll.
997
- */
998
- releaseMouse() {
999
- if (!this.mouseCaptured) return false;
1000
- // Auto-enabled rail hover must be disarmed even without env opt-in.
1001
- this.writeModeControl(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
1002
- this.writeModeControl(mouseTracking(false));
1003
- this.mouseCaptured = false;
1004
- this.mouseMotionOn = false;
1005
- this.detached = true;
1006
- return true;
1007
- }
1008
-
1009
- /** Take it back, once the user is driving the band again. */
1010
- captureMouse() {
1011
- // Home and suspended stages must not arm modes their teardown cannot observe.
1012
- if (!this.mouseWanted || !this.mouseOn || !this.stage.reserved || this.mouseCaptured) return false;
1013
- this.writeModeControl(mouseTracking(true));
1014
- this.writeModeControl(mouseHoverTracking(true, this.env));
1015
- this.mouseCaptured = true;
1016
- this.mouseMotionOn = String(this.env?.CAUSYNE_MOUSE_HOVER ?? '') === '1';
1017
- this.detached = false;
1018
- // After native scrollback, the former physical cursor location is unknown.
1019
- // Return to the screen bottom before repainting any transcript rows.
1020
- this.stage.reanchor();
1021
- return true;
1022
- }
1023
937
  }
1024
-
1025
938
  /**
1026
939
  * Build a surface, or null when this terminal should keep the scrollback
1027
940
  * renderer. Every null here is a reason the region could not be repainted
1028
941
  * safely, and the fallback is the behaviour Causyne has always had.
1029
942
  */
1030
943
  export function createStageSurface({ out = process.stdout, env = process.env, config = null, speed, openingWidth = 0 } = {}) {
1031
- if (!out || !out.isTTY) return null;
1032
- if (String(env.TERM || '') === 'dumb') return null;
1033
- if (env.CAUSYNE_SIMPLE_INPUT === '1') return null;
1034
- if (stageHeight(out, env) < 1) return null;
1035
-
1036
- // Terminal-wide motion tracking is opt-in, never silently enabled by the TUI.
1037
- const surface = new StageSurface({ out, env, config, speed, openingWidth });
1038
- if (!surface.open()) return null;
1039
- return surface;
944
+ const safeEnv = env && typeof env === 'object' ? env : {};
945
+ if (!out || !out.isTTY)
946
+ return null;
947
+ if (String(safeEnv.TERM || '') === 'dumb')
948
+ return null;
949
+ if (safeEnv.CAUSYNE_SIMPLE_INPUT === '1')
950
+ return null;
951
+ if (stageHeight(out, safeEnv) < 1)
952
+ return null;
953
+ // Terminal-wide motion tracking is opt-in, never silently enabled by the TUI.
954
+ const opts = { out, env: safeEnv, config, openingWidth };
955
+ if (speed !== undefined)
956
+ opts.speed = speed;
957
+ const surface = new StageSurface(opts);
958
+ if (!surface.open())
959
+ return null;
960
+ return surface;
1040
961
  }
1041
-