@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
@@ -0,0 +1,1870 @@
1
+ // The chat prompt: raw keyboard, live redraw, completion, history, queueing.
2
+ //
3
+ // This is what replaces `inquirer.prompt({ type: 'input' })`. inquirer answered
4
+ // one question at a time and owned the terminal while it did, which is why the
5
+ // chat could not offer history, could not complete a command, could not accept
6
+ // a paragraph, and went deaf the moment the agent started working.
7
+ //
8
+ // Three behaviours here are the ones a user actually feels:
9
+ //
10
+ // * TYPE WHILE BUSY — keystrokes during a turn are kept and sent when it ends,
11
+ // instead of being swallowed by a terminal nobody is reading.
12
+ // * ESC INTERRUPTS — wired to the AgentLoop.abort() that already existed and
13
+ // was only reachable by typing /stop after the turn had finished.
14
+ // * FAIL OPEN — if raw mode is unavailable (piped stdin, a CI runner, an
15
+ // unusual terminal) the caller falls back to plain readline. A fancy editor must
16
+ // never be the reason chat does not start.
17
+ //
18
+ // Pure Node. No dependency, no shell.
19
+
20
+ import { KeyDecoder, bracketedPaste } from './keys.js';
21
+ import { TerminalInputFramer, INPUT_PREFIX_TIMEOUT_MS, shouldTreatAsAtomicPaste } from './terminalInputFramer.js';
22
+ import { LineEditor } from './lineEditor.js';
23
+ import { PromptHistory } from './history.js';
24
+ import { FileIndex, suggest, applyCompletion, detectTrigger, renderPicker, MAX_VISIBLE, type CompletionSuggestion } from './completion.js';
25
+ import { removeInlineSlashToken, isInlineSkillInvocation } from './inlineSlash.js';
26
+ import { paint, dim, bold, GLYPHS, terminalWidth, HAS_COLOR } from './theme.js';
27
+ import { barBlock, GUTTER } from './block.js';
28
+ import { composerGeometry } from './composerGeometry.js';
29
+ import { visibleWidth, truncate, wrapBlock, shortenHome, safeDisplay } from './text.js';
30
+ import { pickExample, fitHints } from './banner.js';
31
+ import { panelRows } from './overlay.js';
32
+ import { renderUsageCardRows, renderStatusCardRows, collectUsageCardData, type UsageCardData } from './usageCard.js';
33
+ import { buildStatusText } from '../reporting.js';
34
+ import { commandPalette, skillPicker, ApprovalLayer, DecisionLayer, ConfirmLayer, HomeLayer, TextLayer } from './dialogs.js';
35
+ import { describeTool } from './toolDisplay.js';
36
+ import { writeClipboardSync } from './clipboardSync.js';
37
+ import { pasteIntoChatbox } from './chatboxClipboard.js';
38
+ import { handleViewportWheel, handleScrollbarMouse } from './scrollInteraction.js';
39
+ import { centerRows, sessionRows, dialogWidth, dialogHeight } from './layout.js';
40
+ import { settleStageResize } from './resizeRecovery.js';
41
+ import { sidebarVisible, sessionMainWidth } from './sessionSidebar.js';
42
+ import { isStartupDialog, startupDialogView } from './homeView.js';
43
+ import { handleMessageMouse, handleMessageActionMenuMouse, isMouseMotion } from './messageInteraction.js';
44
+ import { handleTurnRailMouse } from './turnRail.js';
45
+ import { runWithStageWrite } from './consoleGuard.js';
46
+ import {
47
+ resetTurnInterruptState,
48
+ shouldAcceptStatusUpdate,
49
+ triggerTurnInterrupt,
50
+ handlePromptCtrlC,
51
+ handlePromptEscape
52
+ } from './composerControls.js';
53
+
54
+ export interface ChatPromptOptions {
55
+ out?: any;
56
+ input?: any;
57
+ root?: string;
58
+ focusDir?: string | null;
59
+ onInterrupt?: () => void;
60
+ surface?: any;
61
+ onExit?: () => void;
62
+ onExpand?: () => void;
63
+ onOpenMode?: (() => unknown) | null;
64
+ onCycleMode?: (() => unknown) | null;
65
+ onOpenModel?: (() => unknown) | null;
66
+ onOpenVariant?: (() => unknown) | null;
67
+ onOpenVariantList?: (() => unknown) | null;
68
+ messageActionLoop?: any;
69
+ getMode?: () => string;
70
+ history?: PromptHistory;
71
+ renderer?: any;
72
+ commands?: any[];
73
+ isCommand?: (text: string) => boolean;
74
+ }
75
+
76
+ export interface PickerLayout {
77
+ pickerStart: number;
78
+ pickerCount: number;
79
+ totalPromptRows: number;
80
+ }
81
+
82
+ const CTRL_C_WINDOW_MS = 2000;
83
+
84
+ // Rows the editor may occupy before it starts scrolling internally.
85
+ const MAX_PROMPT_ROWS = 8;
86
+
87
+ // How long to wait for a resize gesture to settle before repainting.
88
+ const RESIZE_SETTLE_MS = 60;
89
+
90
+ const PROMPT_PAD_TOP = 1;
91
+ const PROMPT_PAD_BOTTOM = 1;
92
+ const FOOTER_GAP = 1;
93
+
94
+ const ROOMY_TERMINAL_ROWS = 20;
95
+ const CRAMPED_TERMINAL_ROWS = 18;
96
+
97
+ /** Can this process own the keyboard? */
98
+ export function isInteractive(): boolean {
99
+ if (process.env.CAUSYNE_SIMPLE_INPUT === '1') return false;
100
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
101
+ }
102
+
103
+ export class ChatPrompt {
104
+ out: any;
105
+ input: any;
106
+ root: string;
107
+ focusDir: string | null;
108
+ onInterrupt: () => void;
109
+ surface: any;
110
+ onExit: () => void;
111
+ onExpand: () => void;
112
+ onOpenMode: (() => unknown) | null;
113
+ onCycleMode: (() => unknown) | null;
114
+ onOpenModel: (() => unknown) | null;
115
+ onOpenVariant: (() => unknown) | null;
116
+ onOpenVariantList: (() => unknown) | null;
117
+ messageActionLoop: any;
118
+ getMode: () => string;
119
+ editor: LineEditor;
120
+ history: PromptHistory;
121
+ index: FileIndex;
122
+ _unsubscribeFileIndex: (() => void) | null;
123
+ decoder: KeyDecoder;
124
+ inputFramer: TerminalInputFramer;
125
+ inputFrameTimer: ReturnType<typeof setTimeout> | null;
126
+ decoderRecoveryTimer: ReturnType<typeof setTimeout> | null;
127
+ busy: boolean;
128
+ active: boolean;
129
+ exitHook: (() => void) | null;
130
+ drawnRows: number;
131
+ usageCard: UsageCardData | null;
132
+ usageCardLoading: boolean;
133
+ statusCard: string | null;
134
+ statusCardUsage: UsageCardData | null;
135
+ infoPanelVersion: number;
136
+ usageRefreshPending: boolean;
137
+ cursorRow: number;
138
+ renderer: any;
139
+ statusMessage: string;
140
+ tick: number;
141
+ tickTimer: ReturnType<typeof setInterval> | null;
142
+ example: string;
143
+ commands: any[];
144
+ isCommand: (text: string) => boolean;
145
+ layer: any;
146
+ queue: any[];
147
+ waiter: ((value: any) => void) | null;
148
+ currentSubmissionAttachments: any[] | null;
149
+ completion: CompletionSuggestion | null;
150
+ selected: number;
151
+ lastCtrlC: number;
152
+ interruptedTurn: boolean;
153
+ notice: string;
154
+ redrawScheduled: boolean;
155
+ resizeTimer: ReturnType<typeof setTimeout> | null;
156
+ suspendedSurface: any;
157
+ pendingAttachments: any[];
158
+ pickerLayout: PickerLayout | null;
159
+
160
+ constructor(options: ChatPromptOptions = {}) {
161
+ const opts = options && typeof options === 'object' ? options : {};
162
+ this.out = opts.out || process.stdout;
163
+ this.input = opts.input || process.stdin;
164
+ this.root = opts.root || process.cwd();
165
+ this.focusDir = opts.focusDir || null;
166
+ this.onInterrupt = opts.onInterrupt || (() => {});
167
+
168
+ this.surface = opts.surface || null;
169
+ this.onExit = opts.onExit || (() => process.exit(0));
170
+ this.onExpand = opts.onExpand || (() => {});
171
+ this.onOpenMode = opts.onOpenMode || null;
172
+ this.onCycleMode = opts.onCycleMode || null;
173
+ this.onOpenModel = opts.onOpenModel || null;
174
+ this.onOpenVariant = opts.onOpenVariant || null;
175
+ this.onOpenVariantList = opts.onOpenVariantList || null;
176
+ this.messageActionLoop = opts.messageActionLoop || null;
177
+ this.getMode = opts.getMode || (() => 'B');
178
+
179
+ this.editor = new LineEditor();
180
+ this.history = opts.history || new PromptHistory();
181
+ this.index = new FileIndex(this.root);
182
+ this._unsubscribeFileIndex = null;
183
+ this.bindFileIndex(this.index);
184
+ this.decoder = new KeyDecoder();
185
+ this.inputFramer = new TerminalInputFramer();
186
+ this.inputFrameTimer = null;
187
+ this.decoderRecoveryTimer = null;
188
+
189
+ this.busy = false;
190
+ this.active = false;
191
+ this.exitHook = null;
192
+ this.drawnRows = 0;
193
+ this.usageCard = null;
194
+ this.usageCardLoading = false;
195
+ this.statusCard = null;
196
+ this.statusCardUsage = null;
197
+ this.infoPanelVersion = 0;
198
+ this.usageRefreshPending = false;
199
+ this.cursorRow = 0;
200
+
201
+ this.renderer = opts.renderer || null;
202
+ this.statusMessage = '';
203
+ this.tick = 0;
204
+ this.tickTimer = null;
205
+
206
+ this.example = pickExample();
207
+ this.commands = opts.commands || [];
208
+ this.isCommand = typeof opts.isCommand === 'function' ? opts.isCommand : () => false;
209
+ this.layer = null;
210
+ this.queue = [];
211
+ this.waiter = null;
212
+ this.currentSubmissionAttachments = null;
213
+ this.completion = null;
214
+ this.selected = 0;
215
+ this.lastCtrlC = 0;
216
+ this.interruptedTurn = false;
217
+ this.notice = '';
218
+ this.redrawScheduled = false;
219
+ this.resizeTimer = null;
220
+ this.suspendedSurface = null;
221
+ this.pendingAttachments = [];
222
+ this.pickerLayout = null;
223
+ }
224
+
225
+ // -------------------------------------------------------------------------
226
+ // Lifecycle
227
+ // -------------------------------------------------------------------------
228
+
229
+ writeControl(sequence: string): void {
230
+ if (!sequence) return;
231
+ runWithStageWrite(() => {
232
+ this.out.write(sequence);
233
+ });
234
+ }
235
+
236
+ start(): void {
237
+ if (this.active) return;
238
+ this.active = true;
239
+ this.inputFramer.clear();
240
+ this.input.setRawMode(true);
241
+ this.input.resume();
242
+ this.input.on('data', this.handleData);
243
+ this.writeControl(bracketedPaste(true));
244
+ this.exitHook = () => {
245
+ try { this.writeControl(bracketedPaste(false)); } catch { /* terminal already closed */ }
246
+ try { this.input.setRawMode(false); } catch { /* stdin already closed */ }
247
+ };
248
+ process.once('exit', this.exitHook);
249
+ if (typeof this.out.on === 'function') this.out.on('resize', this.handleResize);
250
+ }
251
+
252
+ stop(): void {
253
+ if (!this.active) {
254
+ if (this.waiter) {
255
+ const resolve = this.waiter;
256
+ this.waiter = null;
257
+ resolve(null);
258
+ }
259
+ return;
260
+ }
261
+ this.active = false;
262
+ if (this.layer) {
263
+ const layer = this.layer;
264
+ this.layer = null;
265
+ if (typeof layer.answer === 'function') layer.answer(false);
266
+ }
267
+ if (this.waiter) {
268
+ const resolve = this.waiter;
269
+ this.waiter = null;
270
+ resolve(null);
271
+ }
272
+ if (typeof this._unsubscribeFileIndex === 'function') {
273
+ this._unsubscribeFileIndex();
274
+ this._unsubscribeFileIndex = null;
275
+ }
276
+ this.index?.dispose();
277
+ this.stopTick();
278
+ if (this.inputFrameTimer) { clearTimeout(this.inputFrameTimer); this.inputFrameTimer = null; }
279
+ if (this.decoderRecoveryTimer) { clearTimeout(this.decoderRecoveryTimer); this.decoderRecoveryTimer = null; }
280
+ this.inputFramer.clear();
281
+ this.decoder.pending = Buffer.alloc(0);
282
+ if (this.resizeTimer) { clearTimeout(this.resizeTimer); this.resizeTimer = null; }
283
+ this.erase();
284
+ if (this.surface) this.surface.close();
285
+ this.writeControl(bracketedPaste(false));
286
+ if (typeof this.out.removeListener === 'function') this.out.removeListener('resize', this.handleResize);
287
+ this.input.off('data', this.handleData);
288
+ try { this.input.setRawMode(false); } catch { /* already closed */ }
289
+ this.input.pause();
290
+ if (this.exitHook) {
291
+ process.removeListener('exit', this.exitHook);
292
+ this.exitHook = null;
293
+ }
294
+ }
295
+
296
+ handleResize = (): void => {
297
+ if (!this.resizeTimer) this.erase();
298
+ if (this.resizeTimer) clearTimeout(this.resizeTimer);
299
+ this.resizeTimer = setTimeout(() => {
300
+ this.resizeTimer = null;
301
+ this.drawnRows = 0;
302
+ this.cursorRow = 0;
303
+ const settled = settleStageResize(this.surface, this.suspendedSurface);
304
+ this.surface = settled.current;
305
+ this.suspendedSurface = settled.suspended;
306
+ if (settled.restored) this.attachSurface(settled.current);
307
+ this.draw();
308
+ }, RESIZE_SETTLE_MS);
309
+ if (this.resizeTimer.unref) this.resizeTimer.unref();
310
+ };
311
+
312
+ handleData = (chunk: Buffer | string): void => {
313
+ const frames = this.inputFramer.push(chunk);
314
+ for (const frame of frames) this.handleFramedData(frame);
315
+ if (this.inputFrameTimer) { clearTimeout(this.inputFrameTimer); this.inputFrameTimer = null; }
316
+ if (this.inputFramer.hasPending) {
317
+ this.inputFrameTimer = setTimeout(() => {
318
+ this.inputFrameTimer = null;
319
+ for (const frame of this.inputFramer.flush()) this.handleFramedData(frame);
320
+ }, INPUT_PREFIX_TIMEOUT_MS);
321
+ this.inputFrameTimer.unref?.();
322
+ }
323
+ };
324
+
325
+ flushCharBatch(charBatch: string): string {
326
+ if (!charBatch) return '';
327
+ this.prepareKeyboardState(true);
328
+ this.editor.insert(charBatch);
329
+ if (charBatch.length < 60 && !charBatch.includes('\n')) {
330
+ this.refreshCompletion();
331
+ } else {
332
+ this.completion = null;
333
+ }
334
+ return '';
335
+ }
336
+
337
+ prepareKeyboardState(clearNotice: boolean): void {
338
+ if (clearNotice && this.notice && !this.layer) this.notice = '';
339
+ if (this.surface && typeof this.surface.captureMouse === 'function') {
340
+ if (this.surface.captureMouse() && typeof this.notice === 'string' && this.notice.startsWith('top of this view')) {
341
+ this.notice = '';
342
+ }
343
+ }
344
+ if (this.surface) {
345
+ this.surface.turnRailHoverSuppressed = false;
346
+ if (this.surface.hoveredTurnIndex !== null && this.surface.hoveredTurnIndex !== undefined) {
347
+ this.surface.hoveredTurnIndex = null;
348
+ this.surface.hoveredTurnAnchorY = null;
349
+ this.scheduleDraw();
350
+ }
351
+ }
352
+ }
353
+
354
+ handleFramedData = (chunk: Buffer | string): void => {
355
+ let motionOnly = true;
356
+ const str = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString('utf8') : '';
357
+ if (!this.layer && shouldTreatAsAtomicPaste(chunk, this.decoder)) {
358
+ try {
359
+ this.handleKey({ name: 'paste', text: str, sequence: '' });
360
+ } catch (error: unknown) {
361
+ this.notice = `paste failed: ${this.sanitizeSingleLine(error instanceof Error ? error.message : String(error))}`;
362
+ this.scheduleDraw();
363
+ }
364
+ this.draw();
365
+ return;
366
+ }
367
+
368
+ const keys = this.decoder.decode(chunk);
369
+ if (this.decoderRecoveryTimer) clearTimeout(this.decoderRecoveryTimer);
370
+ this.decoderRecoveryTimer = null;
371
+ if (!this.decoder.inPaste && this.decoder.pending.length > 0) {
372
+ this.decoderRecoveryTimer = setTimeout(() => {
373
+ this.decoderRecoveryTimer = null;
374
+ const recovered = this.decoder.drainIncomplete();
375
+ for (const event of recovered) this.handleKey(event);
376
+ if (recovered.length) this.scheduleDraw();
377
+ }, 180);
378
+ this.decoderRecoveryTimer.unref?.();
379
+ }
380
+ let charBatch = '';
381
+
382
+ for (let i = 0; i < keys.length; i++) {
383
+ const key = keys[i];
384
+ if (!key) continue;
385
+ if (!this.layer && key.name === 'char' && typeof key.text === 'string' && !key.alt && !key.ctrl) {
386
+ charBatch += key.text;
387
+ motionOnly = false;
388
+ continue;
389
+ }
390
+ if (charBatch.length > 0) {
391
+ charBatch = this.flushCharBatch(charBatch);
392
+ }
393
+ if (key.name !== 'mouse' || !isMouseMotion(key.sequence)) motionOnly = false;
394
+ try {
395
+ this.handleKey(key);
396
+ } catch (e: unknown) {
397
+ this.notice = `input error: ${this.sanitizeSingleLine(e instanceof Error ? e.message : String(e))}`;
398
+ this.scheduleDraw();
399
+ }
400
+ }
401
+
402
+ if (charBatch.length > 0) {
403
+ charBatch = this.flushCharBatch(charBatch);
404
+ }
405
+
406
+ if (!motionOnly) this.draw();
407
+ };
408
+
409
+ attach(renderer: any): void {
410
+ renderer.onBeforeWrite = () => this.erase();
411
+ renderer.onAfterWrite = () => this.scheduleDraw();
412
+
413
+ this.renderer = renderer;
414
+ if (this.surface) this.surface.sidebarStatus = renderer.status;
415
+ renderer.quietStatus = true;
416
+ renderer.onStatusChange = (message: string) => {
417
+ if (!shouldAcceptStatusUpdate(this)) return;
418
+ this.statusMessage = message;
419
+ this.scheduleDraw();
420
+ };
421
+ renderer.onPlanChange = (plan: any[]) => {
422
+ if (this.surface) this.surface.sidebarPlan = plan;
423
+ this.scheduleDraw();
424
+ return this.surface && sidebarVisible(this.surface.width, false, this.surface.env) ? 'sidebar' : undefined;
425
+ };
426
+ }
427
+
428
+ statusRow(width: number): string[] {
429
+ if (!this.renderer || !this.renderer.status) return [];
430
+ const status = this.renderer.status;
431
+
432
+ if (!this.busy) {
433
+ return [status.renderIdle({
434
+ width: Math.max(10, width),
435
+ hint: this.commands.length > 0 ? 'ctrl+p commands' : ''
436
+ })];
437
+ }
438
+
439
+ const frame = GLYPHS.spinner[this.tick % GLYPHS.spinner.length] ?? '*';
440
+ const since = this.renderer.turnStartedAt;
441
+ return [status.render({
442
+ message: this.statusMessage || 'working',
443
+ elapsedMs: since ? Date.now() - since : 0,
444
+ steps: this.renderer.stepCount || 0,
445
+ width: Math.max(10, width - 1),
446
+ spinnerFrame: frame,
447
+ tick: this.tick
448
+ })];
449
+ }
450
+
451
+ agentRow(width: number): string | null {
452
+ const status = this.renderer && this.renderer.status;
453
+ if (!status) return null;
454
+
455
+ const mode = `${this.busy ? 'Working' : 'Build'} ${this.getMode()}`;
456
+ const parts = [bold(paint('accent', mode))];
457
+ if (status.model) parts.push(bold(paint('ink', status.model)));
458
+ if (status.variant) parts.push(paint('accent', `[${status.variant}]`));
459
+ const line = parts.join(dim(` ${GLYPHS.dot} `));
460
+ const trailing = [status.provider, status.tier].filter(Boolean).join(' ');
461
+ const base = trailing ? `${line} ${dim(trailing)}` : line;
462
+ const details: string[] = [];
463
+ if (this.queue.length) details.push(`${this.queue.length} queued`);
464
+ if (this.editor.lines.length > 1) details.push(`${this.editor.lines.length} lines`);
465
+ const extra = details.length ? dim(` ${GLYPHS.dot} ${details.join(' · ')}`) : '';
466
+ const withMeta = visibleWidth(base) + visibleWidth(extra) <= width ? base + extra : base;
467
+ const hints = dim(' Ctrl+G/⇧Tab mode · Alt+M model · Ctrl+T variant');
468
+ const full = visibleWidth(withMeta) + visibleWidth(hints) <= width ? withMeta + hints : withMeta;
469
+ return visibleWidth(full) > width ? truncate(full, width, GLYPHS.ellipsis) : full;
470
+ }
471
+
472
+ planRows(width: number): string[] {
473
+ if (this.surface && sidebarVisible(this.surface.width, false, this.surface.env)) return [];
474
+ const plan: any[] = this.renderer && Array.isArray(this.renderer.latestPlan) ? this.renderer.latestPlan : [];
475
+ if (plan.length === 0) return [];
476
+ const completed = plan.filter(item => item.status === 'completed').length;
477
+ const stageMax = this.surface?.stage?.maxHeight || this.out?.rows || 24;
478
+ if (stageMax < 22) {
479
+ const activeStep = plan.find(item => item.status === 'in_progress') || plan.find(item => item.status !== 'completed') || plan[0];
480
+ const stepText = activeStep ? (activeStep.text || activeStep.step || '') : '';
481
+ const summary = `${paint('accent', GLYPHS.skill || '✦')} ${bold('plan')} ${dim(`(${completed}/${plan.length})`)} ${dim('·')} ${truncate(safeDisplay(stepText), Math.max(8, width - 24), GLYPHS.ellipsis)}`;
482
+ return [summary, ''];
483
+ }
484
+ const rows = [`${bold(paint('accent', 'implementation plan'))} ${dim(`${completed}/${plan.length}`)}`];
485
+ const limit = Math.min(plan.length, 5);
486
+ const active = plan.findIndex(item => item.status === 'in_progress');
487
+ const pending = plan.findIndex(item => item.status !== 'completed');
488
+ const focus = active >= 0 ? active : pending >= 0 ? pending : plan.length - 1;
489
+ const start = Math.max(0, Math.min(focus - 1, plan.length - limit));
490
+ if (start > 0) rows.push(` ${dim(`${GLYPHS.ellipsis} ${start} earlier`)}`);
491
+ for (const item of plan.slice(start, start + limit)) {
492
+ const mark = item.status === 'completed'
493
+ ? paint('success', GLYPHS.check)
494
+ : item.status === 'in_progress'
495
+ ? paint('accent', GLYPHS.arrow)
496
+ : paint('muted', GLYPHS.dot);
497
+ rows.push(` ${mark} ${truncate(safeDisplay(item.text || item.step || ''), Math.max(8, width - 5), GLYPHS.ellipsis)}`);
498
+ }
499
+ const remaining = plan.length - start - limit;
500
+ if (remaining > 0) rows.push(` ${dim(`${GLYPHS.ellipsis} ${remaining} later`)}`);
501
+ rows.push('');
502
+ return rows;
503
+ }
504
+
505
+ startTick(): void {
506
+ if (this.tickTimer) return;
507
+ this.tickTimer = setInterval(() => {
508
+ this.tick++;
509
+ if (this.busy) this.scheduleDraw();
510
+ if (this.busy && (this.usageCard || this.statusCard !== null) && this.tick % 32 === 0) {
511
+ this.refreshPinnedPanels();
512
+ }
513
+ }, 125);
514
+ if (this.tickTimer.unref) this.tickTimer.unref();
515
+ }
516
+
517
+ stopTick(): void {
518
+ if (!this.tickTimer) return;
519
+ clearInterval(this.tickTimer);
520
+ this.tickTimer = null;
521
+ }
522
+
523
+ openLayer<T>(layer: T): T {
524
+ this.closeLayer();
525
+ this.layer = layer;
526
+ if (this.surface?.stage) this.surface.stage.invalidate();
527
+ this.draw();
528
+ return layer;
529
+ }
530
+
531
+ closeLayer(): void {
532
+ const layer = this.layer;
533
+ if (!layer) return;
534
+ this.layer = null;
535
+ if (typeof layer.answer === 'function') layer.answer(false);
536
+ if (this.surface?.stage) this.surface.stage.invalidate();
537
+ this.draw();
538
+ }
539
+
540
+ openPalette(): void {
541
+ if (this.commands.length === 0) {
542
+ this.notice = 'no commands available';
543
+ return;
544
+ }
545
+ this.openLayer(commandPalette(this.commands, (command) => {
546
+ this.editor.setText(`/${command.name}`);
547
+ this.layer = null;
548
+ this.submit();
549
+ }));
550
+ }
551
+
552
+ openHome(items: any[], onPick?: ((item: any) => any) | null): HomeLayer | null {
553
+ if (!Array.isArray(items) || items.length === 0) {
554
+ this.notice = 'no actions available';
555
+ this.scheduleDraw();
556
+ return null;
557
+ }
558
+ return this.openLayer(new HomeLayer({
559
+ items,
560
+ onPick: (item) => {
561
+ this.layer = null;
562
+ return onPick ? onPick(item) : null;
563
+ }
564
+ }));
565
+ }
566
+
567
+ setText(text: unknown): void {
568
+ this.editor.setText(String(text == null ? '' : text));
569
+ this.completion = null;
570
+ this.scheduleDraw();
571
+ }
572
+
573
+ updateModel(provider?: unknown, model?: unknown, variant?: unknown): void {
574
+ const nextProvider = provider ? String(provider) : '';
575
+ const nextModel = model ? String(model) : '';
576
+ const sessionUpdate: Record<string, string> = {
577
+ provider: nextProvider,
578
+ model: nextModel
579
+ };
580
+ if (variant !== undefined) {
581
+ sessionUpdate.variant = variant ? String(variant) : '';
582
+ }
583
+ if (this.renderer && this.renderer.status) {
584
+ this.renderer.status.setSession(sessionUpdate);
585
+ }
586
+ if (this.surface && typeof this.surface.setSessionInfo === 'function') {
587
+ this.surface.setSessionInfo(sessionUpdate);
588
+ }
589
+ this.scheduleDraw();
590
+ }
591
+
592
+ browseSkills(skills: any[], onOpen?: ((skill: any) => void) | null): void {
593
+ if (!Array.isArray(skills) || skills.length === 0) {
594
+ this.notice = 'no skills are compiled into this build';
595
+ this.scheduleDraw();
596
+ return;
597
+ }
598
+ this.openLayer(skillPicker(skills, (skill) => {
599
+ this.layer = null;
600
+ if (onOpen) onOpen(skill);
601
+ }));
602
+ }
603
+
604
+ showText(title: unknown, text: unknown, options: { width?: number; height?: number; danger?: boolean } = {}): TextLayer {
605
+ const opts = options && typeof options === 'object' ? options : {};
606
+ const panelWidth = dialogWidth(this.width(), opts.width || 76);
607
+ const contentWidth = Math.max(12, panelWidth - 4);
608
+ let lines = wrapBlock(safeDisplay(String(text == null ? '' : text)), contentWidth, { hang: 0 });
609
+ if (lines.length > 0 && (lines[0] ?? '').trim().toLowerCase() === String(title || '').trim().toLowerCase()) {
610
+ lines = lines.slice(1);
611
+ if (lines.length > 0 && /^[-─═_]+$/.test((lines[0] ?? '').trim())) {
612
+ lines = lines.slice(1);
613
+ }
614
+ }
615
+ return this.openLayer(new TextLayer({
616
+ title: String(title || 'Details'),
617
+ lines: opts.danger ? lines.map((line) => paint('danger', line)) : lines,
618
+ width: panelWidth,
619
+ height: opts.height || 20
620
+ }));
621
+ }
622
+
623
+ async toggleUsageCard(loop: any = null): Promise<boolean> {
624
+ if (this.usageCard || this.usageCardLoading) {
625
+ this.closeUsageCard();
626
+ return false;
627
+ }
628
+ const version = ++this.infoPanelVersion;
629
+ this.statusCard = null;
630
+ this.statusCardUsage = null;
631
+ this.usageCardLoading = true;
632
+ try {
633
+ const data = await collectUsageCardData(loop || this.messageActionLoop);
634
+ if (version !== this.infoPanelVersion || !this.usageCardLoading) return false;
635
+ this.usageCard = data;
636
+ this.usageCardLoading = false;
637
+ this.scheduleDraw();
638
+ return true;
639
+ } catch (error: unknown) {
640
+ if (version === this.infoPanelVersion) {
641
+ this.usageCardLoading = false;
642
+ this.notice = this.sanitizeSingleLine(error instanceof Error ? error.message : String(error));
643
+ this.scheduleDraw();
644
+ }
645
+ return false;
646
+ }
647
+ }
648
+
649
+ showUsageCard(loop: any = null): Promise<boolean> {
650
+ return this.toggleUsageCard(loop);
651
+ }
652
+
653
+ closeUsageCard(): boolean {
654
+ if (!this.usageCard && !this.usageCardLoading) return false;
655
+ ++this.infoPanelVersion;
656
+ this.usageCard = null;
657
+ this.usageCardLoading = false;
658
+ this.scheduleDraw();
659
+ return true;
660
+ }
661
+
662
+ async refreshUsageCard(loop: any = null): Promise<boolean> {
663
+ if (!this.usageCard || this.usageRefreshPending) return false;
664
+ const version = this.infoPanelVersion;
665
+ this.usageRefreshPending = true;
666
+ try {
667
+ const data = await collectUsageCardData(loop || this.messageActionLoop);
668
+ if (version !== this.infoPanelVersion || !this.usageCard) return false;
669
+ this.usageCard = data;
670
+ this.scheduleDraw();
671
+ return true;
672
+ } catch {
673
+ return false;
674
+ } finally {
675
+ this.usageRefreshPending = false;
676
+ }
677
+ }
678
+
679
+ toggleStatusCard(loop: any = null): boolean {
680
+ if (this.statusCard !== null) {
681
+ this.closeStatusCard();
682
+ return false;
683
+ }
684
+ const targetLoop = loop || this.messageActionLoop;
685
+ ++this.infoPanelVersion;
686
+ this.usageCard = null;
687
+ this.usageCardLoading = false;
688
+ this.statusCardUsage = null;
689
+ this.statusCard = buildStatusText({ loop: targetLoop });
690
+ this.scheduleDraw();
691
+ void this.refreshStatusCardMeta(targetLoop);
692
+ return true;
693
+ }
694
+
695
+ closeStatusCard(): boolean {
696
+ if (this.statusCard === null) return false;
697
+ ++this.infoPanelVersion;
698
+ this.statusCard = null;
699
+ this.statusCardUsage = null;
700
+ this.scheduleDraw();
701
+ return true;
702
+ }
703
+
704
+ async refreshStatusCardMeta(loop: any = null): Promise<boolean> {
705
+ if (this.statusCard === null) return false;
706
+ const version = this.infoPanelVersion;
707
+ try {
708
+ const data = await collectUsageCardData(loop || this.messageActionLoop);
709
+ if (version !== this.infoPanelVersion || this.statusCard === null) return false;
710
+ this.statusCardUsage = data;
711
+ this.scheduleDraw();
712
+ return true;
713
+ } catch {
714
+ return false;
715
+ }
716
+ }
717
+
718
+ refreshPinnedPanels(loop: any = null): void {
719
+ const targetLoop = loop || this.messageActionLoop;
720
+ if (this.usageCard) void this.refreshUsageCard(targetLoop);
721
+ if (this.statusCard !== null) {
722
+ this.statusCard = buildStatusText({ loop: targetLoop });
723
+ this.scheduleDraw();
724
+ void this.refreshStatusCardMeta(targetLoop);
725
+ }
726
+ }
727
+
728
+ statusCardRows(width: number): string[] {
729
+ if (this.statusCard === null) return [];
730
+ return renderStatusCardRows(this.statusCard, this.statusCardUsage, width);
731
+ }
732
+
733
+ approve(request: Record<string, any> = {}): Promise<{ approved: boolean; scope: string }> {
734
+ return new Promise((resolve) => {
735
+ const { verb } = describeTool(request.tool, request.args || {});
736
+ this.openLayer(new ApprovalLayer({
737
+ request,
738
+ verb,
739
+ onAnswer: (approved, scope) => resolve({ approved, scope: scope || (approved ? 'once' : 'reject') })
740
+ }));
741
+ });
742
+ }
743
+
744
+ decide(request: Record<string, any> = {}): Promise<any> {
745
+ return new Promise((resolve) => {
746
+ this.openLayer(new DecisionLayer({ request, onAnswer: resolve }));
747
+ });
748
+ }
749
+
750
+ confirm(message: string, options: { defaultAnswer?: boolean } = {}): Promise<boolean> {
751
+ const opts = options && typeof options === 'object' ? options : {};
752
+ return new Promise((resolve) => {
753
+ let settled = false;
754
+ const settle = (answer: unknown): void => { if (!settled) { settled = true; resolve(Boolean(answer)); } };
755
+ const layer = new ConfirmLayer({
756
+ message,
757
+ defaultAnswer: opts.defaultAnswer === true,
758
+ onAnswer: settle
759
+ });
760
+ this.openLayer(layer);
761
+ });
762
+ }
763
+
764
+ width(): number {
765
+ if (this.surface && typeof this.surface.composeWidth === 'function') {
766
+ const asked = this.surface.composeWidth();
767
+ if (Number.isFinite(asked) && asked > 0) return Math.max(20, asked);
768
+ }
769
+
770
+ const columns = this.out && this.out.columns;
771
+ return Number.isFinite(columns) && columns > 0
772
+ ? Math.max(20, columns)
773
+ : terminalWidth();
774
+ }
775
+
776
+ scheduleDraw(): void {
777
+ if (this.redrawScheduled || !this.active) return;
778
+ this.redrawScheduled = true;
779
+ setImmediate(() => {
780
+ this.redrawScheduled = false;
781
+ this.draw();
782
+ });
783
+ }
784
+
785
+ renderSubmittedUserMessage(text: string): void {
786
+ if (this.surface?.homeInfo) this.surface.leaveHome();
787
+ if (this.renderer?.renderUserMessage) this.renderer.renderUserMessage(text);
788
+ else this.commit('user', (width) => {
789
+ const blockWidth = Math.max(8, width);
790
+ return barBlock(
791
+ wrapBlock(safeDisplay(text), Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - GUTTER), { hang: 0 }),
792
+ { width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' }
793
+ );
794
+ });
795
+ }
796
+
797
+ restoreUnconsumedAttachments(): void {
798
+ if (Array.isArray(this.currentSubmissionAttachments) && this.currentSubmissionAttachments.length) {
799
+ this.pendingAttachments = this.currentSubmissionAttachments.concat(this.pendingAttachments);
800
+ }
801
+ this.currentSubmissionAttachments = null;
802
+ }
803
+
804
+ takeSubmissionAttachments(): any[] {
805
+ const attachments = Array.isArray(this.pendingAttachments) ? this.pendingAttachments : [];
806
+ this.pendingAttachments = [];
807
+ return attachments;
808
+ }
809
+
810
+ enqueueSubmission(text: string, { rendered = false }: { rendered?: boolean } = {}): void {
811
+ if (!Array.isArray(this.queue)) this.queue = [];
812
+ if (this.isCommand(text)) {
813
+ this.queue.push(text);
814
+ } else {
815
+ this.queue.push({ kind: 'chat-submission', text, attachments: this.takeSubmissionAttachments(), rendered });
816
+ }
817
+ }
818
+
819
+ read(): Promise<any> {
820
+ this.restoreUnconsumedAttachments();
821
+ if (this.queue.length > 0) {
822
+ const entry = this.queue.shift();
823
+ const submission = Boolean(entry && typeof entry === 'object' && entry.kind === 'chat-submission');
824
+ const text = submission ? entry.text : entry;
825
+ if (submission) this.currentSubmissionAttachments = entry.attachments;
826
+ if (typeof text === 'string' && !this.isCommand(text) && !(submission && entry.rendered)) {
827
+ this.renderSubmittedUserMessage(text);
828
+ }
829
+ this.scheduleDraw();
830
+ return Promise.resolve(text);
831
+ }
832
+ return new Promise((resolve) => { this.waiter = resolve; });
833
+ }
834
+
835
+ deliver(value: unknown): boolean {
836
+ if (this.waiter) {
837
+ const resolve = this.waiter;
838
+ this.waiter = null;
839
+ resolve(value);
840
+ return true;
841
+ }
842
+ this.queue.push(value);
843
+ return false;
844
+ }
845
+
846
+ consumeAttachments(): any[] {
847
+ if (this.currentSubmissionAttachments !== null) {
848
+ const attachments = this.currentSubmissionAttachments;
849
+ this.currentSubmissionAttachments = null;
850
+ return Array.isArray(attachments) ? attachments : [];
851
+ }
852
+ return this.takeSubmissionAttachments();
853
+ }
854
+
855
+ pasteClipboard(): void {
856
+ pasteIntoChatbox(this);
857
+ }
858
+
859
+ setBusy(busy: boolean): void {
860
+ this.busy = busy;
861
+ resetTurnInterruptState(this, busy);
862
+ if (busy) this.startTick(); else this.stopTick();
863
+ if (!busy && this.usageCard) void this.refreshUsageCard();
864
+ if (this.statusCard !== null) {
865
+ this.statusCard = buildStatusText({ loop: this.messageActionLoop });
866
+ if (!busy) void this.refreshStatusCardMeta(this.messageActionLoop);
867
+ }
868
+ if (this.surface?.stage) this.surface.stage.invalidate();
869
+ this.draw();
870
+ }
871
+
872
+ submit(): void {
873
+ const text = this.editor.getText();
874
+ if (!text.trim()) return;
875
+ if (!Array.isArray(this.queue)) this.queue = [];
876
+ if ((this.busy || !this.waiter) && this.queue.length >= 32
877
+ && !/^\/(?:stop|interrupt)$/i.test(text.trim())) {
878
+ this.notice = '32 queued messages: wait for a turn to complete before adding another';
879
+ this.scheduleDraw();
880
+ return;
881
+ }
882
+
883
+ this.erase();
884
+ this.history.add(text);
885
+ this.editor.clear();
886
+ this.completion = null;
887
+ const trimmedLower = text.trim().toLowerCase();
888
+ if ((trimmedLower === '/usage' || trimmedLower === '/cost')
889
+ && typeof this.toggleUsageCard === 'function') {
890
+ void this.toggleUsageCard();
891
+ return;
892
+ }
893
+ if (trimmedLower === '/status' && typeof this.toggleStatusCard === 'function') {
894
+ this.toggleStatusCard();
895
+ return;
896
+ }
897
+
898
+ if (trimmedLower === '/observer' || trimmedLower === '/observer status') {
899
+ import('./observerPicker.js').then(({ runInteractiveObserverPicker }) => {
900
+ void runInteractiveObserverPicker(this);
901
+ }).catch((err: unknown) => {
902
+ this.notice = this.sanitizeSingleLine(err instanceof Error ? err.message : String(err));
903
+ this.scheduleDraw();
904
+ });
905
+ return;
906
+ }
907
+
908
+ const commandToken = (trimmedLower.split(/\s+/, 1)[0] ?? '').toLowerCase();
909
+ const isControlCommand = this.isCommand(text) && new Set([
910
+ '/stop', '/interrupt', '/new', '/model', '/models',
911
+ '/variant', '/effort', '/reasoning', '/cortex',
912
+ '/gui', '/web', '/studio',
913
+ '/session', '/sessions', '/continuum', '/clear'
914
+ ]).has(commandToken);
915
+
916
+ if ((trimmedLower === '/stop' || trimmedLower === '/interrupt') && this.busy) {
917
+ this.interrupt();
918
+ this.notice = 'Interrupted';
919
+ this.scheduleDraw();
920
+ return;
921
+ }
922
+
923
+ if (isControlCommand && this.busy) {
924
+ this.interrupt();
925
+ }
926
+
927
+ if (this.busy) {
928
+ if (this.isCommand(text)) {
929
+ this.notice = `Command ${this.sanitizeSingleLine(text)} queued — will execute when current turn completes`;
930
+ } else {
931
+ this.notice = `queued (${this.queue.length + 1}) — sends when this turn ends`;
932
+ }
933
+ this.enqueueSubmission(text);
934
+ this.scheduleDraw();
935
+ return;
936
+ }
937
+
938
+ if (this.isCommand(text)) {
939
+ const settle = this.waiter;
940
+ this.waiter = null;
941
+ if (settle) settle(text);
942
+ else {
943
+ this.enqueueSubmission(text);
944
+ this.notice = `queued (${this.queue.length}) — sends when ready`;
945
+ this.scheduleDraw?.();
946
+ }
947
+ return;
948
+ }
949
+
950
+ const resolve = this.waiter;
951
+ this.waiter = null;
952
+ if (resolve) {
953
+ this.restoreUnconsumedAttachments();
954
+ this.currentSubmissionAttachments = this.takeSubmissionAttachments();
955
+ this.renderSubmittedUserMessage(text);
956
+ resolve(text);
957
+ } else {
958
+ this.renderSubmittedUserMessage(text);
959
+ this.enqueueSubmission(text, { rendered: true });
960
+ this.notice = `queued (${this.queue.length}) — sends when ready`;
961
+ this.scheduleDraw?.();
962
+ }
963
+ }
964
+
965
+ // -------------------------------------------------------------------------
966
+ // Keys
967
+ // -------------------------------------------------------------------------
968
+
969
+ handleKey(key: any): any {
970
+ const clearNotice = key.name === 'char' || key.name === 'paste' || key.name === 'backspace' || key.name === 'delete';
971
+ if (clearNotice && this.notice && !this.layer) {
972
+ this.notice = '';
973
+ }
974
+
975
+ if (key.name !== 'wheel' && key.name !== 'mouse') {
976
+ this.prepareKeyboardState(false);
977
+ }
978
+
979
+ if (key.ctrl && key.name === 'c') {
980
+ if (this.layer) { this.closeLayer(); return; }
981
+ if (this.editor.hasSelection) {
982
+ const text = this.editor.getSelectedText();
983
+ try { writeClipboardSync(text); } catch { /* clipboard unavailable */ }
984
+ this.editor.killRing = text;
985
+ this.notice = `copied selection (${text.length} chars) to clipboard`;
986
+ this.scheduleDraw();
987
+ return;
988
+ }
989
+ return this.handleCtrlC();
990
+ }
991
+ if (key.ctrl && key.name === 'd' && this.editor.isEmpty) return this.onExit();
992
+
993
+ if (this.layer) {
994
+ const previousSelection = this.layer.messageActions ? this.layer.list?.selected : null;
995
+ const action = key.name === 'mouse' && this.layer.messageActions
996
+ ? handleMessageActionMenuMouse(this.layer, key)
997
+ : this.layer.key(key);
998
+ if (this.layer?.messageActions && isMouseMotion(key.sequence)
999
+ && previousSelection !== this.layer.list?.selected) this.scheduleDraw();
1000
+ if (action === 'close') { this.closeLayer(); return; }
1001
+ if (action === 'dismiss') this.closeLayer();
1002
+ else if (action !== 'passthrough') return;
1003
+ }
1004
+
1005
+ if (key.name === 'paste-too-large') {
1006
+ this.notice = 'Paste exceeds 2 MiB; input unchanged. Attach a file or reduce the selection.';
1007
+ this.scheduleDraw();
1008
+ return;
1009
+ }
1010
+
1011
+ if (key.name === 'paste') {
1012
+ if (this.surface && typeof this.surface.captureMouse === 'function') {
1013
+ this.surface.captureMouse();
1014
+ }
1015
+ pasteIntoChatbox(this, key.text);
1016
+ return;
1017
+ }
1018
+
1019
+ if (this.completion && this.handleCompletionKey(key)) return;
1020
+ if (this.handleScrollKey(key)) return;
1021
+
1022
+ const isModeControl = Boolean((key.ctrl && key.name === 'g') || (key.shift && key.name === 'tab' && this.onCycleMode));
1023
+ const control = (key.ctrl && key.name === 'g') ? this.onOpenMode
1024
+ : (key.shift && key.name === 'tab' && this.onCycleMode) ? this.onCycleMode
1025
+ : key.alt && key.name === 'm' ? this.onOpenModel
1026
+ : key.ctrl && key.name === 't' ? this.onOpenVariant
1027
+ : key.alt && key.name === 't' ? (this.onOpenVariantList || this.onOpenVariant) : null;
1028
+ if (control) {
1029
+ if (this.busy && !isModeControl) {
1030
+ this.notice = 'Finish or interrupt the current turn before switching controls';
1031
+ this.scheduleDraw();
1032
+ } else {
1033
+ Promise.resolve(control()).catch((error: unknown) => {
1034
+ this.notice = this.sanitizeSingleLine(error instanceof Error ? error.message : String(error));
1035
+ this.scheduleDraw();
1036
+ });
1037
+ }
1038
+ return;
1039
+ }
1040
+
1041
+ switch (key.name) {
1042
+ case 'escape': return this.handleEscape();
1043
+ case 'enter':
1044
+ if (key.alt || key.shift) { this.editor.newline(); return this.refreshCompletion(); }
1045
+ return this.submit();
1046
+ case 'tab':
1047
+ if (key.shift) return;
1048
+ return this.openCompletion(true);
1049
+ case 'backspace':
1050
+ if (key.alt) this.editor.killWordLeft(); else this.editor.backspace();
1051
+ return this.refreshCompletion();
1052
+ case 'delete': this.editor.deleteForward(); return this.refreshCompletion();
1053
+ case 'left': return (key.ctrl || key.alt) ? this.editor.moveWordLeft(Boolean(key.shift)) : this.editor.moveLeft(Boolean(key.shift));
1054
+ case 'right': return (key.ctrl || key.alt) ? this.editor.moveWordRight(Boolean(key.shift)) : this.editor.moveRight(Boolean(key.shift));
1055
+ case 'home': return this.editor.moveHome(Boolean(key.shift));
1056
+ case 'end': return this.editor.moveEnd(Boolean(key.shift));
1057
+ case 'up':
1058
+ if (key.shift) return this.editor.moveUp(true);
1059
+ return this.historyOrMove(-1);
1060
+ case 'down':
1061
+ if (key.shift) return this.editor.moveDown(true);
1062
+ return this.historyOrMove(1);
1063
+ case 'pageup':
1064
+ if (key.shift) { this.editor.moveHome(true); this.editor.line = 0; return; }
1065
+ break;
1066
+ case 'pagedown':
1067
+ if (key.shift) { this.editor.moveEnd(true); this.editor.line = this.editor.lines.length - 1; return; }
1068
+ break;
1069
+ case 'char': this.editor.insert(key.text); return this.refreshCompletion();
1070
+ default: break;
1071
+ }
1072
+
1073
+ if (key.ctrl) {
1074
+ switch (key.name) {
1075
+ case 'a': return this.editor.moveHome();
1076
+ case 'e': return this.editor.moveEnd();
1077
+ case 'k': this.editor.killToEnd(); return this.refreshCompletion();
1078
+ case 'u': this.editor.killToStart(); return this.refreshCompletion();
1079
+ case 'w': this.editor.killWordLeft(); return this.refreshCompletion();
1080
+ case 'y': this.editor.yank(); return this.refreshCompletion();
1081
+ case 'x': {
1082
+ if (this.cutSelection()) return;
1083
+ break;
1084
+ }
1085
+ case 'p': return this.openPalette();
1086
+ case 'l': return this.clearScreen();
1087
+ case 'o': return this.expand();
1088
+ case 'v': return this.pasteClipboard();
1089
+ default: break;
1090
+ }
1091
+ }
1092
+ if (key.alt && key.name === 'a') {
1093
+ this.editor.selectAll();
1094
+ this.notice = 'selected all input text';
1095
+ this.scheduleDraw();
1096
+ return;
1097
+ }
1098
+ if (key.alt && key.name === 'x') {
1099
+ if (this.cutSelection()) return;
1100
+ }
1101
+ if (key.alt && (key.name === 'c' || key.name === 'w')) {
1102
+ const text = this.editor.hasSelection
1103
+ ? this.editor.getSelectedText()
1104
+ : this.editor.getText();
1105
+ if (text) {
1106
+ writeClipboardSync(text);
1107
+ this.editor.killRing = text;
1108
+ this.notice = this.editor.hasSelection
1109
+ ? `copied selection (${text.length} chars) to clipboard`
1110
+ : 'copied input to clipboard';
1111
+ } else {
1112
+ this.notice = 'input is empty (nothing to copy)';
1113
+ }
1114
+ this.scheduleDraw();
1115
+ return;
1116
+ }
1117
+ if (key.alt && key.name === 'v') return this.pasteClipboard();
1118
+ if (key.alt && key.name === 'b') return this.editor.moveWordLeft();
1119
+ if (key.alt && key.name === 'f') return this.editor.moveWordRight();
1120
+ }
1121
+
1122
+ handleScrollKey(key: any): boolean {
1123
+ const viewport = this.surface && this.surface.viewport;
1124
+
1125
+ if (key.name === 'mouse') {
1126
+ if (handleTurnRailMouse(key, this.surface, this)) return true;
1127
+ if (this.messageActionLoop && isMouseMotion(key.sequence)) {
1128
+ return handleMessageMouse(this, this.messageActionLoop, key);
1129
+ }
1130
+ if (handleScrollbarMouse(key, viewport, this.surface, this)) return true;
1131
+ if (!this.layer && this.messageActionLoop) return handleMessageMouse(this, this.messageActionLoop, key);
1132
+ return true;
1133
+ }
1134
+ if (key.name === 'wheel') {
1135
+ if (!viewport || !key.wheel) return true;
1136
+ const layout = this.surface?.turnRailLayout;
1137
+ const card = layout?.cardRect;
1138
+ const pointerX = key.wheel.x;
1139
+ const pointerY = key.wheel.y;
1140
+ const relativeY = pointerY - (Number.isFinite(layout?.stageTop) ? layout.stageTop : 0);
1141
+ if (card && Array.isArray(card.groupTurns) &&
1142
+ Number.isFinite(pointerX) && Number.isFinite(pointerY) &&
1143
+ pointerX >= card.x && pointerX < card.x + card.width &&
1144
+ relativeY >= card.y && relativeY < card.y + card.height &&
1145
+ (key.wheel.direction === 'up' || key.wheel.direction === 'down')) {
1146
+ const previous = Number.isFinite(this.surface.turnRailCardOffset)
1147
+ ? this.surface.turnRailCardOffset : 0;
1148
+ const maximum = Number.isFinite(card.maxOffset) ? Math.max(0, card.maxOffset) : 0;
1149
+ const change = key.wheel.direction === 'up' ? -1 : 1;
1150
+ const current = Math.max(0, Math.min(maximum, previous + change));
1151
+ if (current !== previous) {
1152
+ this.surface.turnRailCardOffset = current;
1153
+ this.scheduleDraw();
1154
+ }
1155
+ return true;
1156
+ }
1157
+ if (this.renderer?.scrollCodePanel?.(key, this.surface)) {
1158
+ if (typeof this.scheduleDraw === 'function') this.scheduleDraw(); else this.draw();
1159
+ return true;
1160
+ }
1161
+ if (this.renderer?.scrollThinkingPanel?.(key, this.surface)) {
1162
+ if (typeof this.scheduleDraw === 'function') this.scheduleDraw(); else this.draw();
1163
+ return true;
1164
+ }
1165
+
1166
+ return handleViewportWheel(key, viewport, this.surface, this);
1167
+ }
1168
+
1169
+ if (!viewport) return false;
1170
+
1171
+ const clearTurnRailFocus = (): void => {
1172
+ if (!this.surface) return;
1173
+ this.surface.activeTurnIndex = null;
1174
+ this.surface.hoveredTurnIndex = null;
1175
+ this.surface.hoveredTurnAnchorY = null;
1176
+ };
1177
+
1178
+ if (key.name === 'pageup') {
1179
+ clearTurnRailFocus();
1180
+ if (key.shift) viewport.toTop(); else viewport.pageUp();
1181
+ return true;
1182
+ }
1183
+ if (key.name === 'pagedown') {
1184
+ clearTurnRailFocus();
1185
+ if (key.shift) viewport.toBottom(); else viewport.pageDown();
1186
+ return true;
1187
+ }
1188
+ if (key.shift && key.name === 'up') {
1189
+ if (!this.editor.isEmpty) return false;
1190
+ clearTurnRailFocus();
1191
+ viewport.lineUp();
1192
+ return true;
1193
+ }
1194
+ if (key.shift && key.name === 'down') {
1195
+ if (!this.editor.isEmpty) return false;
1196
+ clearTurnRailFocus();
1197
+ viewport.lineDown();
1198
+ return true;
1199
+ }
1200
+ if (key.alt && key.ctrl && key.name === 'u') {
1201
+ clearTurnRailFocus();
1202
+ viewport.halfPageUp();
1203
+ return true;
1204
+ }
1205
+ if (key.alt && key.ctrl && key.name === 'd') {
1206
+ clearTurnRailFocus();
1207
+ viewport.halfPageDown();
1208
+ return true;
1209
+ }
1210
+
1211
+ const jumpViewport = (direction: number, kinds: string[]): boolean => {
1212
+ clearTurnRailFocus();
1213
+ viewport.jump(direction, kinds);
1214
+ return true;
1215
+ };
1216
+ if (key.alt && key.name === ',') return jumpViewport(-1, ['step']);
1217
+ if (key.alt && key.name === '.') return jumpViewport(1, ['step']);
1218
+ if ((key.alt && key.name === '[') || (key.alt && key.name === '<')) return jumpViewport(-1, ['user']);
1219
+ if ((key.alt && key.name === ']') || (key.alt && key.name === '>')) return jumpViewport(1, ['user']);
1220
+
1221
+ if (key.alt && key.name === 'u') { this.offerUndo(); return true; }
1222
+
1223
+ return false;
1224
+ }
1225
+
1226
+ offerUndo(): void {
1227
+ const surface = this.surface;
1228
+ if (!surface) return;
1229
+ const width = surface.viewport.width;
1230
+ const marks: any[] = surface.transcript.markers(width).filter((m: any) => m.kind === 'checkpoint');
1231
+ if (marks.length === 0) {
1232
+ this.notice = 'no restore points in this session yet';
1233
+ return;
1234
+ }
1235
+
1236
+ const top = surface.viewport.scrollTop;
1237
+ const bottom = top + surface.viewport.height;
1238
+ const onScreen = marks.filter((m) => m.row >= top && m.row < bottom);
1239
+ const above = marks.filter((m) => m.row < top);
1240
+ const mark = onScreen.length ? onScreen[onScreen.length - 1] : (above.pop() || marks[0]);
1241
+ const meta = mark?.meta || {};
1242
+
1243
+ const where = meta.path ? this.sanitizeSingleLine(shortenHome(meta.path)) : 'files changed this task';
1244
+ const rawStep = meta.step == null ? '' : this.sanitizeSingleLine(meta.step);
1245
+ const step = rawStep ? ` at step ${rawStep}` : '';
1246
+
1247
+ if (this.editor.isEmpty) {
1248
+ this.editor.setText('/undo');
1249
+ this.notice = `restore point${step} ${GLYPHS.dot} ${where} ${GLYPHS.dot} enter previews, --apply writes`;
1250
+ } else {
1251
+ this.notice = `restore point${step} ${GLYPHS.dot} ${where} ${GLYPHS.dot} run /undo to preview`;
1252
+ }
1253
+ }
1254
+
1255
+ sanitizeSingleLine(value: unknown): string {
1256
+ return value == null ? '' : safeDisplay(String(value)).replace(/\s+/g, ' ').trim();
1257
+ }
1258
+
1259
+ cutSelection(): boolean {
1260
+ if (!this.editor.hasSelection) return false;
1261
+ const text = this.editor.getSelectedText();
1262
+ writeClipboardSync(text);
1263
+ this.editor.killRing = text;
1264
+ this.editor.deleteSelection();
1265
+ this.notice = `cut selection (${text.length} chars) to clipboard`;
1266
+ this.refreshCompletion();
1267
+ return true;
1268
+ }
1269
+
1270
+ handleCtrlC(): void {
1271
+ handlePromptCtrlC(
1272
+ this,
1273
+ () => [`${paint('warn', GLYPHS.cross)} ${dim('interrupted')}`],
1274
+ CTRL_C_WINDOW_MS
1275
+ );
1276
+ }
1277
+
1278
+ handleEscape(): void {
1279
+ handlePromptEscape(
1280
+ this,
1281
+ () => [`${paint('warn', GLYPHS.cross)} ${dim('interrupted')}`]
1282
+ );
1283
+ }
1284
+
1285
+ interrupt(): void {
1286
+ triggerTurnInterrupt(
1287
+ this,
1288
+ () => [`${paint('warn', GLYPHS.cross)} ${dim('interrupted')}`]
1289
+ );
1290
+ }
1291
+
1292
+ expand(): void {
1293
+ this.erase();
1294
+ this.onExpand();
1295
+ this.notice = '';
1296
+ }
1297
+
1298
+ clearScreen(): void {
1299
+ if (this.surface) { this.surface.flushAndClear(); return; }
1300
+
1301
+ this.erase();
1302
+ // The one clear Causyne may perform: the user pressed ctrl+L and asked for it.
1303
+ // UX-01 forbids clearing the terminal on the app's own initiative.
1304
+ this.writeControl('\x1b[2J\x1b[H');
1305
+ this.drawnRows = 0;
1306
+ this.cursorRow = 0;
1307
+ }
1308
+
1309
+ historyOrMove(direction: -1 | 1): void {
1310
+ if (direction === -1 && this.editor.line > 0) { this.editor.moveUp(); return; }
1311
+ if (direction === 1 && this.editor.line < this.editor.lines.length - 1) { this.editor.moveDown(); return; }
1312
+
1313
+ const text = direction === -1
1314
+ ? this.history.previous(this.editor.getText())
1315
+ : this.history.next();
1316
+ if (text === null || text === undefined) return;
1317
+ this.editor.setText(text);
1318
+ }
1319
+
1320
+ // -------------------------------------------------------------------------
1321
+ // Completion
1322
+ // -------------------------------------------------------------------------
1323
+
1324
+ bindFileIndex(index: FileIndex): void {
1325
+ if (typeof this._unsubscribeFileIndex === 'function') this._unsubscribeFileIndex();
1326
+ this._unsubscribeFileIndex = index.subscribe(() => {
1327
+ if (this.index !== index || !this.active) return;
1328
+ const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
1329
+ if (!trigger || trigger.kind !== 'file') return;
1330
+ this.openCompletion(false);
1331
+ if (index.truncated) this.notice = 'Workspace file index reached its safety limit; narrow the project root.';
1332
+ else if (this.notice === 'Indexing workspace files…') this.notice = '';
1333
+ this.scheduleDraw();
1334
+ });
1335
+ void index.ensure();
1336
+ }
1337
+
1338
+ setWorkingRoot(newRoot: string, focusDir: string | null = null): void {
1339
+ if (typeof this._unsubscribeFileIndex === 'function') this._unsubscribeFileIndex();
1340
+ this.index?.dispose();
1341
+ this.root = newRoot;
1342
+ this.focusDir = focusDir;
1343
+ this.index = new FileIndex(newRoot);
1344
+ this.bindFileIndex(this.index);
1345
+ const trigger = detectTrigger(this.editor.getText(), this.cursorOffset());
1346
+ if (trigger?.kind === 'file') this.openCompletion(false);
1347
+ }
1348
+
1349
+ cursorOffset(): number {
1350
+ const before = this.editor.lines.slice(0, this.editor.line)
1351
+ .reduce((total, line) => total + line.join('').length + 1, 0);
1352
+ return before + (this.editor.lines[this.editor.line] ?? [])
1353
+ .slice(0, this.editor.col).join('').length;
1354
+ }
1355
+
1356
+ openCompletion(force = false): void {
1357
+ const text = this.editor.getText();
1358
+ const result = suggest(text, this.cursorOffset(), {
1359
+ root: this.root,
1360
+ index: this.index,
1361
+ focusDir: this.focusDir
1362
+ });
1363
+ if (!result) {
1364
+ if (force) this.notice = 'nothing to complete here';
1365
+ this.completion = null;
1366
+ return;
1367
+ }
1368
+ this.completion = result;
1369
+ this.selected = 0;
1370
+ }
1371
+
1372
+ refreshCompletion(): void {
1373
+ if (!this.completion) {
1374
+ const text = this.editor.getText();
1375
+ const offset = this.cursorOffset();
1376
+ const opens = Boolean(detectTrigger(text, offset));
1377
+ if (opens) this.openCompletion(false);
1378
+ return;
1379
+ }
1380
+ this.openCompletion(false);
1381
+ if (this.completion) this.selected = Math.min(this.selected, this.completion.items.length - 1);
1382
+ }
1383
+
1384
+ completionIsExact(): boolean {
1385
+ if (!this.completion || this.completion.items.length !== 1) return false;
1386
+ const item = this.completion.items[0];
1387
+ if (!item) return false;
1388
+ if (this.completion.kind === 'command-argument') return item.value === this.completion.query;
1389
+ if (this.completion.kind === 'command') return item.value === this.editor.getText();
1390
+ return false;
1391
+ }
1392
+
1393
+ handleCompletionKey(key: any): boolean {
1394
+ if (!this.completion) return false;
1395
+ if (key.name === 'up') { this.moveSelection(-1); return true; }
1396
+ if (key.name === 'down') { this.moveSelection(1); return true; }
1397
+ if (key.name === 'wheel') {
1398
+ const direction = key.wheel && key.wheel.direction;
1399
+ if (direction === 'up') this.moveSelectionClamped(-1);
1400
+ else if (direction === 'down') this.moveSelectionClamped(1);
1401
+ this.scheduleDraw();
1402
+ return true;
1403
+ }
1404
+ if (key.name === 'pageup' && !key.shift) {
1405
+ this.moveSelectionClamped(-MAX_VISIBLE);
1406
+ this.scheduleDraw();
1407
+ return true;
1408
+ }
1409
+ if (key.name === 'pagedown' && !key.shift) {
1410
+ this.moveSelectionClamped(MAX_VISIBLE);
1411
+ this.scheduleDraw();
1412
+ return true;
1413
+ }
1414
+ if (key.name === 'mouse') {
1415
+ if (key.mouse && key.mouse.pressed && key.mouse.button === 0 && !isMouseMotion(key.sequence)) {
1416
+ let item: any = null;
1417
+ const hasZeroY = Number.isFinite(key.mouse.y);
1418
+ const rawMouseRow = hasZeroY
1419
+ ? Math.floor(key.mouse.y)
1420
+ : (Number.isFinite(key.mouse.row) ? Math.floor(key.mouse.row) : Number.NaN);
1421
+ if (this.pickerLayout && Number.isFinite(rawMouseRow)) {
1422
+ const stageHeight = this.surface?.stage?.height || this.out?.rows || process.stdout.rows || 24;
1423
+ const termRows = Number.isFinite(this.out?.rows) && this.out.rows > 0
1424
+ ? Math.floor(this.out.rows)
1425
+ : stageHeight;
1426
+ const promptTop = hasZeroY
1427
+ ? Math.max(0, termRows - this.pickerLayout.totalPromptRows)
1428
+ : Math.max(1, stageHeight - this.pickerLayout.totalPromptRows + 1);
1429
+ const pickerTop = promptTop + this.pickerLayout.pickerStart;
1430
+ const pickerBottom = pickerTop + this.pickerLayout.pickerCount - 1;
1431
+ const mouseX = Number.isFinite(key.mouse.x) ? Math.floor(key.mouse.x) : Number.NaN;
1432
+ const mainW = this.surface
1433
+ ? sessionMainWidth(this.surface.width, Boolean(this.surface.homeInfo), this.surface.env)
1434
+ : Infinity;
1435
+ const inMainColumn = !Number.isFinite(mouseX) || (mouseX >= 0 && mouseX < mainW);
1436
+
1437
+ if (inMainColumn && rawMouseRow >= pickerTop && rawMouseRow <= pickerBottom) {
1438
+ const items = Array.isArray(this.completion.items) ? this.completion.items : [];
1439
+ const total = items.length;
1440
+ const windowStart = Math.max(0, Math.min(this.selected - MAX_VISIBLE + 1, total - MAX_VISIBLE));
1441
+ const index = windowStart + (rawMouseRow - pickerTop);
1442
+ if (index >= 0 && index < total) {
1443
+ this.selected = index;
1444
+ item = items[index];
1445
+ }
1446
+ } else {
1447
+ this.completion = null;
1448
+ this.scheduleDraw();
1449
+ return true;
1450
+ }
1451
+ } else {
1452
+ const items = Array.isArray(this.completion.items) ? this.completion.items : [];
1453
+ item = items[this.selected];
1454
+ }
1455
+
1456
+ if (item) {
1457
+ if (this.completion.kind !== 'file' && this.completion.inline) {
1458
+ const selectedCommand = this.completion.kind === 'command'
1459
+ ? item.value : `/${this.completion.command} ${item.value}`;
1460
+ this.runInlineSlashSelection(selectedCommand);
1461
+ return true;
1462
+ }
1463
+ if (this.completion.kind === 'command') {
1464
+ if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
1465
+ this.acceptCompletion();
1466
+ return true;
1467
+ }
1468
+ this.submitPickedCommand(item.value);
1469
+ return true;
1470
+ }
1471
+ if (this.completion.kind === 'command-argument') {
1472
+ this.submitPickedCommand(`/${this.completion.command} ${item.value}`);
1473
+ return true;
1474
+ }
1475
+ this.acceptCompletion();
1476
+ return true;
1477
+ }
1478
+ }
1479
+ return true;
1480
+ }
1481
+ if (key.name === 'enter' && !key.alt && !key.shift) {
1482
+ const item = this.completion.items && this.completion.items[this.selected];
1483
+ if (item && this.completion.kind !== 'file' && this.completion.inline) {
1484
+ const selectedCommand = this.completion.kind === 'command'
1485
+ ? item.value : `/${this.completion.command} ${item.value}`;
1486
+ this.runInlineSlashSelection(selectedCommand);
1487
+ return true;
1488
+ }
1489
+ if (this.completion.kind === 'command' && item) {
1490
+ if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
1491
+ this.acceptCompletion();
1492
+ return true;
1493
+ }
1494
+ this.submitPickedCommand(item.value);
1495
+ return true;
1496
+ }
1497
+ if (this.completionIsExact()) {
1498
+ this.completion = null;
1499
+ return false;
1500
+ }
1501
+ this.acceptCompletion();
1502
+ return true;
1503
+ }
1504
+ if (key.name === 'tab') {
1505
+ if (this.completion.kind !== 'file' && this.completion.inline) {
1506
+ this.notice = 'Press Enter to run the selected command; your unsent draft is preserved.';
1507
+ this.scheduleDraw();
1508
+ return true;
1509
+ }
1510
+ this.acceptCompletion();
1511
+ return true;
1512
+ }
1513
+ if (key.name === 'escape') {
1514
+ const dismissed = this.completion;
1515
+ this.completion = null;
1516
+ if (!(dismissed.kind !== 'file' && dismissed.inline) && /^\s*\/[a-z0-9_?-]*$/i.test(this.editor.getText())) {
1517
+ this.editor.clear();
1518
+ }
1519
+ this.scheduleDraw();
1520
+ return true;
1521
+ }
1522
+ return false;
1523
+ }
1524
+
1525
+ moveSelection(direction: number): void {
1526
+ const count = Array.isArray(this.completion?.items) ? this.completion.items.length : 0;
1527
+ if (count === 0) return;
1528
+ this.selected = (((this.selected + direction) % count) + count) % count;
1529
+ }
1530
+
1531
+ moveSelectionClamped(delta: number): void {
1532
+ const count = Array.isArray(this.completion?.items) ? this.completion.items.length : 0;
1533
+ if (count === 0) return;
1534
+ this.selected = Math.max(0, Math.min(count - 1, this.selected + delta));
1535
+ }
1536
+
1537
+ submitPickedCommand(value: string): void {
1538
+ this.completion = null;
1539
+ this.editor.setText(value);
1540
+ this.submit();
1541
+ }
1542
+
1543
+ runInlineSlashSelection(value: string): void {
1544
+ const trigger = this.completion;
1545
+ if (!trigger || trigger.kind === 'file' || !trigger.inline) {
1546
+ this.submitPickedCommand(value);
1547
+ return;
1548
+ }
1549
+
1550
+ const currentText = this.editor.getText();
1551
+ const currentCursor = this.cursorOffset();
1552
+ let remaining: { text: string; cursor: number };
1553
+ try {
1554
+ remaining = removeInlineSlashToken(currentText, currentCursor, trigger);
1555
+ } catch {
1556
+ this.notice = 'The command text changed. Reopen the / menu and select again.';
1557
+ this.completion = null;
1558
+ this.scheduleDraw();
1559
+ return;
1560
+ }
1561
+
1562
+ const consumeDraft = isInlineSkillInvocation(value) && remaining.text.trim().length > 0;
1563
+ const commandText = consumeDraft ? `${value} ${remaining.text.trim()}` : value;
1564
+
1565
+ if (this.busy && this.queue.length >= 32 && !/^\/(?:stop|interrupt)$/i.test(commandText)) {
1566
+ this.notice = '32 queued messages: command not submitted; your draft is unchanged.';
1567
+ this.scheduleDraw();
1568
+ return;
1569
+ }
1570
+
1571
+ this.completion = null;
1572
+ try {
1573
+ this.editor.setText(commandText);
1574
+ this.submit();
1575
+ } finally {
1576
+ this.editor.setText(consumeDraft ? '' : remaining.text);
1577
+ if (!consumeDraft) this.setCursorOffset(remaining.cursor);
1578
+ this.completion = null;
1579
+ this.scheduleDraw();
1580
+ }
1581
+ }
1582
+
1583
+ acceptCompletion(): void {
1584
+ if (!this.completion) return;
1585
+ const item = this.completion.items[this.selected];
1586
+ if (!item) { this.completion = null; return; }
1587
+ const applied = applyCompletion(
1588
+ this.editor.getText(), this.cursorOffset(), this.completion, item
1589
+ );
1590
+ this.editor.setText(applied.text);
1591
+ this.setCursorOffset(applied.cursor);
1592
+ this.completion = null;
1593
+ this.refreshCompletion();
1594
+ }
1595
+
1596
+ setCursorOffset(offset: number): void {
1597
+ let remaining = Math.max(0, Number.isFinite(offset) ? offset : 0);
1598
+ for (let index = 0; index < this.editor.lines.length; index++) {
1599
+ const line = this.editor.lines[index] ?? [];
1600
+ const units = line.join('').length;
1601
+ if (remaining <= units || index === this.editor.lines.length - 1) {
1602
+ let column = 0;
1603
+ let consumed = 0;
1604
+ while (column < line.length && consumed + (line[column]?.length ?? 0) <= remaining) {
1605
+ consumed += line[column]?.length ?? 0;
1606
+ column++;
1607
+ }
1608
+ this.editor.line = index;
1609
+ this.editor.col = column;
1610
+ return;
1611
+ }
1612
+ remaining -= units + 1;
1613
+ }
1614
+ }
1615
+
1616
+ // -------------------------------------------------------------------------
1617
+ // Drawing
1618
+ // -------------------------------------------------------------------------
1619
+
1620
+ queuedPreviewRows(width: number): string[] {
1621
+ if (this.queue.length === 0) return [];
1622
+ const last = this.queue[this.queue.length - 1];
1623
+ const text = typeof last === 'string' ? last
1624
+ : last && typeof last.text === 'string' ? last.text : 'pending action';
1625
+ const prefix = ` Queued (${this.queue.length}): `;
1626
+ const available = Math.max(0, width - visibleWidth(prefix) - 2);
1627
+ const preview = safeDisplay(text.slice(0, 160).replace(/\s+/g, ' ').trim());
1628
+ return [dim(prefix + truncate(preview, available, GLYPHS.ellipsis))];
1629
+ }
1630
+
1631
+ clampRows(rows: readonly string[], width: number): string[] {
1632
+ const limit = Math.max(1, width - 1);
1633
+ return rows.map((row) => (visibleWidth(row) <= limit ? row : truncate(row, limit, '')));
1634
+ }
1635
+
1636
+ erase(): void {
1637
+ if (this.surface) return;
1638
+ if (this.drawnRows === 0) {
1639
+ this.out.write('\r');
1640
+ return;
1641
+ }
1642
+ if (this.cursorRow > 0) this.out.write(`\x1b[${this.cursorRow}A`);
1643
+ this.out.write('\r\x1b[J');
1644
+ this.drawnRows = 0;
1645
+ this.cursorRow = 0;
1646
+ }
1647
+
1648
+ draw(): void {
1649
+ if (this.resizeTimer) return;
1650
+ if (!this.active) return;
1651
+ this.erase();
1652
+
1653
+ const width = this.width();
1654
+ if (this.layer) { this.drawLayer(width); return; }
1655
+
1656
+ const { boxWidth, inset, editorWidth } = composerGeometry(
1657
+ width, visibleWidth(GLYPHS.barHeavy || GLYPHS.bar), GUTTER
1658
+ );
1659
+ const inner = editorWidth;
1660
+ const layout = this.editor.render(editorWidth, '');
1661
+
1662
+ const start = Math.max(0, Math.min(layout.cursorRow - MAX_PROMPT_ROWS + 1,
1663
+ layout.rows.length - MAX_PROMPT_ROWS));
1664
+ const top = Math.max(0, start);
1665
+ const windowRows = layout.rows.slice(top, top + MAX_PROMPT_ROWS);
1666
+ const caretRow = layout.cursorRow - top;
1667
+ let body = windowRows.slice();
1668
+
1669
+ if (!this.editor.isEmpty) {
1670
+ body = body.map((line) => {
1671
+ if (typeof line !== 'string' || !line.includes('[Image ')) return line;
1672
+ return line.replace(/\[Image (\d+)\]/g, (_m, num: string) => {
1673
+ return paint('warn', bold(`[Image ${num}]`));
1674
+ });
1675
+ });
1676
+ }
1677
+
1678
+ if (this.editor.isEmpty && !this.completion) {
1679
+ const idle = fitHints([`try "${this.example}"`, '/ commands', '@ files', '^V image'], Math.max(8, inner), 'ask anything');
1680
+ body = [dim(this.busy ? 'type to queue a message…' : idle)];
1681
+ }
1682
+
1683
+ const agent = this.completion ? null : this.agentRow(inner);
1684
+ if (agent) body = body.concat(['', agent]);
1685
+
1686
+ const rows = Number(this.out && this.out.rows);
1687
+ const roomy = !Number.isFinite(rows) || rows >= ROOMY_TERMINAL_ROWS;
1688
+ const padTop = (!Number.isFinite(rows) || rows >= CRAMPED_TERMINAL_ROWS) ? PROMPT_PAD_TOP : 0;
1689
+ const padBottom = roomy ? PROMPT_PAD_BOTTOM : 0;
1690
+
1691
+ const padded = new Array<string>(padTop).fill('')
1692
+ .concat(body, new Array<string>(padBottom).fill(''));
1693
+ const boxRows = barBlock(padded, {
1694
+ width: boxWidth,
1695
+ role: this.busy ? 'accent' : 'user',
1696
+ filled: true,
1697
+ surface: 'surface',
1698
+ punctuate: false
1699
+ });
1700
+
1701
+ const usageCardRows = this.usageCard ? renderUsageCardRows(this.usageCard, boxWidth)
1702
+ : this.statusCard !== null ? this.statusCardRows(boxWidth) : [];
1703
+ const planRows = this.planRows(width);
1704
+ const pickerRows = this.completion ? this.pickerRows(width) : [];
1705
+ this.pickerLayout = this.completion ? {
1706
+ pickerStart: usageCardRows.length + planRows.length + boxRows.length,
1707
+ pickerCount: pickerRows.length,
1708
+ totalPromptRows: 0
1709
+ } : null;
1710
+ const queuedRows = this.queuedPreviewRows(width);
1711
+ const cleanNotice = this.notice ? this.sanitizeSingleLine(this.notice) : '';
1712
+ const noticeRows = cleanNotice ? [dim(` ${cleanNotice}`)] : [];
1713
+
1714
+ const status = this.statusRow(width);
1715
+ const gap = status.length > 0 ? new Array<string>(FOOTER_GAP).fill('') : [];
1716
+
1717
+ const all = this.clampRows(
1718
+ usageCardRows.concat(planRows, boxRows, pickerRows, queuedRows, noticeRows, gap, status), width
1719
+ );
1720
+ if (this.pickerLayout) this.pickerLayout.totalPromptRows = all.length;
1721
+
1722
+ const availableWidth = this.surface?.composeAvailableWidth
1723
+ ? this.surface.composeAvailableWidth()
1724
+ : sessionMainWidth(this.surface?.width || terminalWidth(), false, this.surface?.env);
1725
+ const positioned = this.surface
1726
+ ? (this.surface.homeInfo ? centerRows(all, this.surface.width) : sessionRows(all, availableWidth))
1727
+ : { rows: all, inset: 0 };
1728
+ this.present(positioned.rows, usageCardRows.length + planRows.length + caretRow + padTop, layout.cursorCol + inset + positioned.inset);
1729
+ }
1730
+
1731
+ present(all: string[], caretRow: number, caretCol: number): void {
1732
+ const rows = Array.isArray(all) ? all : [];
1733
+ const maxRow = Math.max(0, rows.length - 1);
1734
+ const safeRow = Number.isFinite(caretRow) ? Math.max(0, Math.min(maxRow, Math.floor(caretRow))) : 0;
1735
+ const safeCol = Number.isFinite(caretCol) ? Math.max(0, Math.floor(caretCol)) : 0;
1736
+ const hideCursor = Boolean(this.busy && this.editor.isEmpty);
1737
+ if (this.surface) {
1738
+ this.drawnRows = 0;
1739
+ this.cursorRow = 0;
1740
+ this.surface.present(rows, {
1741
+ row: safeRow,
1742
+ col: safeCol,
1743
+ hideCursor,
1744
+ modal: Boolean(this.layer),
1745
+ inline: Boolean(this.layer && !isStartupDialog(this.surface))
1746
+ });
1747
+ return;
1748
+ }
1749
+
1750
+ this.out.write(rows.join('\n'));
1751
+ this.drawnRows = rows.length;
1752
+
1753
+ const below = rows.length - 1 - safeRow;
1754
+ if (below > 0) this.out.write(`\x1b[${below}A`);
1755
+ this.cursorRow = safeRow;
1756
+ this.out.write('\r');
1757
+ if (safeCol > 0) this.out.write(`\x1b[${safeCol}C`);
1758
+ if (hideCursor) {
1759
+ this.out.write('\x1b[?25l');
1760
+ } else {
1761
+ this.out.write('\x1b[?25h');
1762
+ }
1763
+ }
1764
+
1765
+ attachSurface(surface: any): void {
1766
+ this.surface = surface || null;
1767
+ if (!surface) return;
1768
+ surface.onDirty = () => this.scheduleDraw();
1769
+ }
1770
+
1771
+ commit(kind: string, produce: (width: number) => string[]): void {
1772
+ const clamped = (width: number): string[] => this.clampRows(produce(width), width);
1773
+ if (this.surface) { this.surface.commit(kind, clamped); return; }
1774
+ this.erase();
1775
+ this.out.write(clamped(this.width()).join('\n') + '\n');
1776
+ }
1777
+
1778
+ drawLayer(width: number): void {
1779
+ const preferredHeight = typeof this.layer.preferredHeight === 'function'
1780
+ ? this.layer.preferredHeight()
1781
+ : 14;
1782
+ if (this.layer.messageActions && this.surface?.presentMessageActions) {
1783
+ const availableWidth = this.surface.composeAvailableWidth
1784
+ ? this.surface.composeAvailableWidth()
1785
+ : sessionMainWidth(this.surface.width, false, this.surface.env);
1786
+ const requestedWidth = typeof this.layer.preferredWidth === 'function'
1787
+ ? this.layer.preferredWidth(Math.max(8, availableWidth - 3))
1788
+ : (this.layer.width || 64);
1789
+ const panelWidth = dialogWidth(Math.max(8, availableWidth - 3), requestedWidth);
1790
+ const panel = panelRows(this.layer, panelWidth, preferredHeight);
1791
+ this.surface.presentMessageActions(panel, this.layer);
1792
+ return;
1793
+ }
1794
+ if (isStartupDialog(this.surface)) {
1795
+ const view = startupDialogView(this.layer, this.surface.width, this.surface.stage.maxHeight);
1796
+ this.present(view.rows, view.caretRow, view.caretCol);
1797
+ return;
1798
+ }
1799
+ const inline = Boolean(this.surface && !this.surface.homeInfo);
1800
+ const availableWidth = inline
1801
+ ? (this.surface.composeAvailableWidth
1802
+ ? this.surface.composeAvailableWidth()
1803
+ : sessionMainWidth(this.surface.width, false, this.surface.env))
1804
+ : width;
1805
+ const panelWidth = dialogWidth(availableWidth, this.layer.width || 64);
1806
+ const stageMax = this.surface?.stage?.maxHeight || this.out?.rows || 24;
1807
+ const statusReserve = 2;
1808
+ const availableDialogRows = Math.max(4, stageMax - statusReserve);
1809
+ const maxHeight = dialogHeight(availableDialogRows, preferredHeight);
1810
+ const panel = panelRows(this.layer, panelWidth, maxHeight);
1811
+ const status = this.statusRow(width);
1812
+ const all = this.clampRows(panel.concat(status), width);
1813
+
1814
+ const cursor = this.layer.cursor;
1815
+ const centered = this.surface ? centerRows(all, availableWidth) : { rows: all, inset: 0 };
1816
+ const stageHeight = this.surface?.stage?.height || this.out?.rows || all.length;
1817
+ const outRows = Number.isFinite(this.out?.rows) && this.out.rows > 0
1818
+ ? Math.floor(this.out.rows)
1819
+ : stageHeight;
1820
+ this.layer.panelGeometry = {
1821
+ inset: centered.inset,
1822
+ optionScreenRow: Math.max(0, outRows - status.length - 2)
1823
+ };
1824
+ this.present(centered.rows, cursor ? 1 + cursor.y : 0,
1825
+ (cursor ? 2 + cursor.x : 0) + centered.inset);
1826
+ }
1827
+
1828
+ pickerRows(width: number): string[] {
1829
+ if (!this.completion) return [];
1830
+ const rows = renderPicker(this.completion.items, this.selected, width);
1831
+ const labelWidth = Math.min(
1832
+ 36,
1833
+ rows.reduce((max, row) => Math.max(max, visibleWidth(row.label)), 0)
1834
+ );
1835
+
1836
+ const drawn = rows.map((row) => {
1837
+ const marker = row.selected ? paint('accent', GLYPHS.arrow) : ' ';
1838
+ const label = truncate(row.label, labelWidth, GLYPHS.ellipsis);
1839
+ const padded = label + ' '.repeat(Math.max(0, labelWidth - visibleWidth(label)));
1840
+ const name = row.selected ? bold(paint('ink', padded)) : paint('ink', padded);
1841
+ const description = row.description
1842
+ ? dim(' ' + truncate(row.description, Math.max(0, width - labelWidth - 8), GLYPHS.ellipsis))
1843
+ : '';
1844
+ return ` ${marker} ${name}${description}`;
1845
+ });
1846
+
1847
+ const matched = this.completion.total || this.completion.items.length;
1848
+ const hidden = matched - drawn.length;
1849
+ if (hidden > 0) drawn.push(dim(` ${GLYPHS.ellipsis} ${hidden} more`));
1850
+ if (this.completion.kind !== 'file' && this.completion.inline) {
1851
+ drawn.push(dim(' ' + truncate('Enter run · Esc dismiss · draft protected', Math.max(0, width - 5))));
1852
+ }
1853
+ return drawn;
1854
+ }
1855
+ }
1856
+
1857
+ export function keyHints(width: number = terminalWidth()): string {
1858
+ const parts = [
1859
+ 'enter send', 'alt+enter newline', 'ctrl+p palette', '/ commands', '@ files',
1860
+ '↑ history', 'tab complete', 'esc interrupt', 'ctrl+o expand'
1861
+ ];
1862
+ const separator = ` ${GLYPHS.dot} `;
1863
+ const kept = parts.slice();
1864
+ while (kept.length > 1 && visibleWidth(kept.join(separator)) > width - 1) kept.pop();
1865
+ return HAS_COLOR
1866
+ ? kept.map((part) => dim(part)).join(dim(separator))
1867
+ : kept.join(separator);
1868
+ }
1869
+
1870
+ export { MAX_VISIBLE };