@causyne/agent 1.20.122 → 1.20.127

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