@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,971 @@
1
+ // Concrete TUI modal dialogs built over SelectList and scrolling Layer panes.
2
+ // ApprovalLayer keeps the risk badge, tool, arguments, and scrollable diff in
3
+ // one focused modal frame instead of losing them in terminal scrollback.
4
+ // Pure Node over ./selectList.js, ./overlay.js, ./theme.js, ./text.js.
5
+
6
+ import { Layer, dialogHint, type LayerOptions } from './overlay.js';
7
+ import { SelectList, type SelectListItem } from './selectList.js';
8
+ import { LineEditor } from './lineEditor.js';
9
+ import { paint, bold, dim, badge, GLYPHS } from './theme.js';
10
+ import { truncate, wrap, visibleWidth, safeDisplay, shortenHome } from './text.js';
11
+ import { approvalDiff, type ApprovalDiffResult } from './diff.js';
12
+ import { isChar, isMouseMotion } from './keys.js';
13
+ import { readClipboardSync } from './clipboardSync.js';
14
+
15
+ export interface SelectLayerOptions extends LayerOptions {
16
+ items?: readonly (SelectListItem | null | undefined)[] | undefined;
17
+ placeholder?: string | undefined;
18
+ emptyText?: string | undefined;
19
+ showFilter?: boolean | undefined;
20
+ onPick?: ((item: any) => any) | null | undefined;
21
+ [key: string]: any;
22
+ }
23
+
24
+ export interface InputLayerOptions extends LayerOptions {
25
+ value?: unknown;
26
+ lines?: readonly unknown[] | undefined;
27
+ mask?: boolean | undefined;
28
+ placeholder?: string | undefined;
29
+ onSubmit?: ((value: string) => void) | null | undefined;
30
+ onCancel?: (() => void) | null | undefined;
31
+ [key: string]: any;
32
+ }
33
+
34
+ export interface HomeLayerItem {
35
+ id?: string | undefined;
36
+ label?: string | undefined;
37
+ hint?: string | undefined;
38
+ action?: unknown;
39
+ [key: string]: any;
40
+ }
41
+
42
+ export interface HomeLayerOptions extends LayerOptions {
43
+ items?: readonly HomeLayerItem[] | undefined;
44
+ onPick?: ((item: any) => any) | null | undefined;
45
+ [key: string]: any;
46
+ }
47
+
48
+ export interface TextLayerOptions extends LayerOptions {
49
+ lines?: readonly unknown[] | undefined;
50
+ text?: unknown;
51
+ [key: string]: any;
52
+ }
53
+
54
+ export interface ApprovalOption {
55
+ id: string;
56
+ label: string;
57
+ answer: boolean;
58
+ }
59
+
60
+ export interface ApprovalOptionBound {
61
+ index: number;
62
+ option: ApprovalOption;
63
+ startCol: number;
64
+ endCol: number;
65
+ }
66
+
67
+ export interface ApprovalLayerOptions extends LayerOptions {
68
+ request?: Record<string, any> | undefined;
69
+ detail?: string | undefined;
70
+ verb?: string | undefined;
71
+ onAnswer?: ((approved: boolean, scope: string) => void) | null | undefined;
72
+ [key: string]: any;
73
+ }
74
+
75
+ export interface DecisionOption {
76
+ id?: string | undefined;
77
+ label?: string | undefined;
78
+ description?: string | undefined;
79
+ }
80
+
81
+ export interface DecisionLayerOptions extends LayerOptions {
82
+ request?: Record<string, any> | undefined;
83
+ onAnswer?: ((answer: any) => void) | null | undefined;
84
+ [key: string]: any;
85
+ }
86
+
87
+ export interface ConfirmLayerOptions extends LayerOptions {
88
+ message?: string | undefined;
89
+ defaultAnswer?: boolean | undefined;
90
+ onAnswer?: ((approved: boolean) => void) | null | undefined;
91
+ [key: string]: any;
92
+ }
93
+
94
+ const MAX_DIALOG_PASTE_CHARS = 65536;
95
+
96
+ const cleanDialogText = (value: unknown): string => (
97
+ value == null ? '' : safeDisplay(String(value)).replace(/\s+/g, ' ').trim()
98
+ );
99
+
100
+ function safeJsonPreview(value: unknown): string {
101
+ try {
102
+ const serialized = JSON.stringify(value);
103
+ return serialized === undefined ? String(value) : serialized;
104
+ } catch {
105
+ return String(value);
106
+ }
107
+ }
108
+
109
+ /**
110
+ * A picker. `items` are SelectList items; `onPick(item)` fires on enter.
111
+ *
112
+ * onPick may return 'keep' to leave the dialog open — which is what a theme
113
+ * picker wants, so the user can see each theme applied before committing.
114
+ */
115
+ export class SelectLayer<T extends SelectListItem = SelectListItem> extends Layer {
116
+ list: SelectList<T>;
117
+ onPick: ((item: any) => any) | null;
118
+ settled: boolean;
119
+
120
+ constructor(options: SelectLayerOptions = {}) {
121
+ const opts = options && typeof options === 'object' ? options : {};
122
+ super({ width: opts.width || 68, height: opts.height || 18, ...opts });
123
+ this.list = new SelectList<T>((opts.items || []) as readonly (T | null | undefined)[], {
124
+ placeholder: opts.placeholder,
125
+ emptyText: opts.emptyText,
126
+ showFilter: opts.showFilter
127
+ });
128
+ this.onPick = opts.onPick || null;
129
+ this.settled = false;
130
+ this.footer = opts.footer || dialogHint();
131
+ }
132
+
133
+ /** Dismissal must resolve pending picker flows, just like text inputs. */
134
+ answer(): void {
135
+ if (this.settled) return;
136
+ this.settled = true;
137
+ if (this.onPick) this.onPick(null);
138
+ }
139
+
140
+ override preferredHeight(): number {
141
+ // filter row + rule + one row per item (+ its category header) + frame.
142
+ const categories = new Set(this.list.filtered.map((entry) => entry.item.category).filter(Boolean));
143
+ return 2 + this.list.filtered.length + categories.size + 2;
144
+ }
145
+
146
+ override body(width = 64, height = 16): string[] {
147
+ const { rows } = this.list.render(width, height);
148
+ this.cursor = { x: this.list.cursorColumn(), y: 0 };
149
+ return rows;
150
+ }
151
+
152
+ override key(event: any): string | null {
153
+ // Scroll by the budget the RENDERER used, not by one derived from the
154
+ // layer's configured height. The panel gives the body
155
+ // `min(preferredHeight, maxHeight) - 2` rows and the list then spends two
156
+ // more on the filter and its rule and one on the position counter — so this
157
+ // used to move the selection by 17 rows through a list that was drawing 15.
158
+ // The list publishes what it actually budgeted on its last render; before
159
+ // the first render there is nothing to disagree with, so the estimate stands.
160
+ const visibleRows = this.list.lastItemRows || Math.max(1, this.height - 5);
161
+ const action = this.list.handleKey(event, visibleRows);
162
+
163
+ if (action === 'select') {
164
+ const item = this.list.current;
165
+ this.settled = true;
166
+ const result = this.onPick ? this.onPick(item) : null;
167
+ if (result === 'keep' || result === 'handled') {
168
+ this.settled = false;
169
+ return 'handled';
170
+ }
171
+ return 'close';
172
+ }
173
+ if (action === 'cancel') return 'close';
174
+ return action ? 'handled' : null;
175
+ }
176
+ }
177
+
178
+ export class InputLayer extends Layer {
179
+ editor: LineEditor;
180
+ lines: unknown[];
181
+ mask: boolean;
182
+ placeholder: string;
183
+ onSubmit: ((value: string) => void) | null;
184
+ onCancel: (() => void) | null;
185
+ settled: boolean;
186
+
187
+ constructor(options: InputLayerOptions = {}) {
188
+ const opts = options && typeof options === 'object' ? options : {};
189
+ super({ width: opts.width || 68, height: opts.height || 10, ...opts });
190
+ this.mask = opts.mask === true;
191
+ this.editor = new LineEditor(String(opts.value == null ? '' : opts.value), { disableClipboard: this.mask });
192
+ this.lines = Array.isArray(opts.lines) ? [...opts.lines] : [];
193
+ this.placeholder = opts.placeholder || '';
194
+ this.onSubmit = opts.onSubmit || null;
195
+ this.onCancel = opts.onCancel || null;
196
+ this.footer = opts.footer || `enter accept ${GLYPHS.dot} esc cancel`;
197
+ this.settled = false;
198
+ }
199
+
200
+ // Blurb rows + a blank + the input row, inside the frame.
201
+ override preferredHeight(): number { return this.lines.length + (this.lines.length ? 1 : 0) + 1 + 2; }
202
+
203
+ /** Dismissal is a cancel, so the caller's promise can never hang. */
204
+ answer(): void {
205
+ if (this.settled) return;
206
+ this.settled = true;
207
+ if (this.onCancel) this.onCancel();
208
+ }
209
+
210
+ override body(width = 64): string[] {
211
+ const safeWidth = Number.isFinite(width) && width > 0 ? Math.floor(width) : 8;
212
+ const rows = this.lines.map((line) => truncate(cleanDialogText(line), safeWidth, GLYPHS.ellipsis));
213
+ if (rows.length) rows.push('');
214
+
215
+ const raw = this.editor.getText();
216
+ const shown = this.mask ? GLYPHS.bullet.repeat(Array.from(raw).length) : cleanDialogText(raw);
217
+ const cleanPlaceholder = cleanDialogText(this.placeholder);
218
+ const text = shown.length === 0 && cleanPlaceholder ? dim(cleanPlaceholder) : shown;
219
+
220
+ const prefix = paint('accent', `${GLYPHS.arrow} `);
221
+ rows.push(truncate(prefix + text, safeWidth, GLYPHS.ellipsis));
222
+
223
+ // Park the caret after what is displayed — which for a masked field is the
224
+ // dot count, not the character count, or the caret drifts off the value —
225
+ // using code-point slicing (never UTF-16 `.slice()`) so emoji never shift
226
+ // the caret off the visible glyph boundary.
227
+ const beforeCodePoints = Array.from(raw).slice(0, this.editor.col);
228
+ const before = this.mask
229
+ ? beforeCodePoints.length
230
+ : visibleWidth(cleanDialogText(beforeCodePoints.join('')));
231
+ const maxCol = Math.max(0, safeWidth - 1);
232
+ this.cursor = { x: Math.min(maxCol, 2 + before), y: rows.length - 1 };
233
+ return rows;
234
+ }
235
+
236
+ override key(event: any): string | null {
237
+ if (!event) return null;
238
+
239
+ switch (event.name) {
240
+ case 'escape':
241
+ return 'close';
242
+ case 'enter':
243
+ case 'return': {
244
+ if (this.settled) return 'close';
245
+ this.settled = true;
246
+ const value = this.editor.getText();
247
+ if (this.onSubmit) this.onSubmit(value);
248
+ return 'close';
249
+ }
250
+ case 'backspace':
251
+ if (event.alt) this.editor.killWordLeft(); else this.editor.backspace();
252
+ return 'handled';
253
+ case 'delete': this.editor.deleteForward(); return 'handled';
254
+ case 'left': this.editor.moveLeft(); return 'handled';
255
+ case 'right': this.editor.moveRight(); return 'handled';
256
+ case 'home': this.editor.moveHome(); return 'handled';
257
+ case 'end': this.editor.moveEnd(); return 'handled';
258
+ case 'char': this.editor.insert(event.text); return 'handled';
259
+ case 'paste': {
260
+ // eslint-disable-next-line no-control-regex
261
+ const clean = String(event.text || '').replace(/[\x00-\x1f\x7f]+/g, '').trim().slice(0, MAX_DIALOG_PASTE_CHARS);
262
+ if (clean) this.editor.insert(clean);
263
+ return 'handled';
264
+ }
265
+ default: break;
266
+ }
267
+
268
+ if (event.ctrl) {
269
+ switch (event.name) {
270
+ case 'a': this.editor.moveHome(); return 'handled';
271
+ case 'e': this.editor.moveEnd(); return 'handled';
272
+ case 'k': this.editor.killToEnd(); return 'handled';
273
+ case 'u': this.editor.killToStart(); return 'handled';
274
+ case 'w': this.editor.killWordLeft(); return 'handled';
275
+ case 'v': {
276
+ let text = '';
277
+ try { text = readClipboardSync() || ''; } catch { text = ''; }
278
+ if (text) {
279
+ // eslint-disable-next-line no-control-regex
280
+ const clean = String(text).replace(/[\x00-\x1f\x7f]+/g, '').trim().slice(0, MAX_DIALOG_PASTE_CHARS);
281
+ if (clean) this.editor.insert(clean);
282
+ }
283
+ return 'handled';
284
+ }
285
+ default: break;
286
+ }
287
+ }
288
+
289
+ // Stay modal for anything unrecognised: a stray key must not reach the
290
+ // input line behind a question that is still open.
291
+ return 'handled';
292
+ }
293
+ }
294
+
295
+ /**
296
+ * The home menu: the action list that sits above the input line.
297
+ *
298
+ * This is deliberately NOT a SelectLayer. A SelectLayer owns the keyboard and
299
+ * filters on every keystroke, which is exactly wrong here — home shows the menu
300
+ * and the chat input in ONE frame, so `↑↓` must pick an action while typing must
301
+ * reach the input line underneath. A filter row would also be a lie: there is
302
+ * nothing to type into it.
303
+ *
304
+ * So this layer claims four keys and hands everything else back:
305
+ *
306
+ * ↑ ↓ move the selection → 'handled'
307
+ * enter run the selected action → 'close' (onPick fires first)
308
+ * esc put the menu away → 'close'
309
+ * else not mine → 'dismiss' for a printable character,
310
+ * 'passthrough' for anything else
311
+ *
312
+ * 'dismiss' tears the menu down AND lets the key through, so the first character
313
+ * you type both closes the menu and appears in the input — one keystroke, not
314
+ * two. 'passthrough' leaves the menu up, so ctrl+c, ctrl+p and friends keep
315
+ * working while it is open. Every other Layer returns null and stays modal; the
316
+ * invariant is unchanged for them.
317
+ */
318
+ export class HomeLayer extends Layer {
319
+ items: HomeLayerItem[];
320
+ index: number;
321
+ onPick: ((item: any) => any) | null;
322
+
323
+ constructor(options: HomeLayerOptions = {}) {
324
+ const opts = options && typeof options === 'object' ? options : {};
325
+ super({ width: opts.width || 66, height: opts.height || 14, ...opts });
326
+ this.items = Array.isArray(opts.items) ? [...opts.items] : [];
327
+ this.index = 0;
328
+ this.onPick = opts.onPick || null;
329
+ this.title = opts.title || 'what would you like to do?';
330
+ this.footer = opts.footer || `↑↓ pick ${GLYPHS.dot} enter run ${GLYPHS.dot} esc menu off ${GLYPHS.dot} or just start typing`;
331
+ }
332
+
333
+ // No filter row and no rule — one row per item, plus the frame.
334
+ override preferredHeight(): number { return this.items.length + 2; }
335
+
336
+ get current(): HomeLayerItem | null { return this.items[this.index] || null; }
337
+
338
+ override body(width = 64): string[] {
339
+ // The hint column is right-padded from the widest label so the two columns
340
+ // line up, but it is computed from the ACTUAL labels rather than a constant:
341
+ // a hardcoded inset is what makes a menu look off by one at some widths.
342
+ const cleanItems = this.items.map((item) => ({
343
+ label: cleanDialogText(item?.label || ''),
344
+ hint: cleanDialogText(item?.hint || '')
345
+ }));
346
+ const labelWidth = cleanItems.reduce((max, item) => Math.max(max, visibleWidth(item.label)), 0);
347
+ return cleanItems.map((item, i) => {
348
+ const selected = i === this.index;
349
+ const marker = selected ? paint('accent', GLYPHS.arrow) : ' ';
350
+ const label = selected ? bold(paint('accent', item.label)) : item.label;
351
+ const pad = ' '.repeat(Math.max(0, labelWidth - visibleWidth(item.label)));
352
+ const hint = item.hint ? dim(item.hint) : '';
353
+ // truncate() is ANSI-aware, so styling the label first is safe. The row is
354
+ // clamped to the panel, never to the terminal — the panel is narrower.
355
+ return truncate(` ${marker} ${label}${pad} ${hint}`, width);
356
+ });
357
+ }
358
+
359
+ override key(event: any): string | null {
360
+ if (!event) return null;
361
+
362
+ switch (event.name) {
363
+ case 'up':
364
+ if (this.items.length === 0) return 'handled';
365
+ this.index = (this.index - 1 + this.items.length) % this.items.length;
366
+ return 'handled';
367
+ case 'down':
368
+ if (this.items.length === 0) return 'handled';
369
+ this.index = (this.index + 1) % this.items.length;
370
+ return 'handled';
371
+ case 'enter':
372
+ case 'return': {
373
+ const item = this.current;
374
+ if (!item) return 'close';
375
+ const result = this.onPick ? this.onPick(item) : null;
376
+ return result === 'keep' ? 'handled' : 'close';
377
+ }
378
+ case 'escape': return 'close';
379
+ default: break;
380
+ }
381
+
382
+ // A printable character is the user starting a sentence. Put the menu away
383
+ // and let the character land in the input line in the same keystroke.
384
+ if (event.name === 'char' || event.name === 'paste') return 'dismiss';
385
+
386
+ // Anything else — ctrl chords, tab, backspace on an empty line — belongs to
387
+ // the prompt, and the menu has no opinion about it.
388
+ return 'passthrough';
389
+ }
390
+ }
391
+
392
+ /**
393
+ * A scrolling text pane — help, usage, an expanded tool output, an error.
394
+ *
395
+ * Takes already-styled rows and scrolls them. It exists so that "show me the
396
+ * whole thing" never again means dumping 900 lines into the transcript.
397
+ */
398
+ export class TextLayer extends Layer {
399
+ lines: unknown[];
400
+ scroll: number;
401
+ viewHeight?: number;
402
+
403
+ constructor(options: TextLayerOptions = {}) {
404
+ const opts = options && typeof options === 'object' ? options : {};
405
+ super({ width: opts.width || 76, height: opts.height || 20, ...opts });
406
+ this.lines = Array.isArray(opts.lines) ? [...opts.lines] : String(opts.text || '').split('\n');
407
+ this.scroll = 0;
408
+ this.footer = opts.footer || `↑↓ scroll ${GLYPHS.dot} esc close`;
409
+ }
410
+
411
+ override preferredHeight(): number { return this.lines.length + 2; }
412
+
413
+ override body(width = 72, height = 18): string[] {
414
+ const safeWidth = Number.isFinite(width) && width > 0 ? Math.floor(width) : 8;
415
+ const safeHeight = Number.isFinite(height) && height > 0 ? Math.floor(height) : 1;
416
+ this.viewHeight = safeHeight;
417
+ const maximum = Math.max(0, this.lines.length - safeHeight);
418
+ this.scroll = Math.max(0, Math.min(this.scroll, maximum));
419
+
420
+ const windowLines = this.lines.slice(this.scroll, this.scroll + safeHeight)
421
+ .map((line) => truncate(line == null ? '' : safeDisplay(String(line)), safeWidth, GLYPHS.ellipsis));
422
+
423
+ if (this.lines.length > safeHeight) {
424
+ const position = `${this.scroll + 1}-${Math.min(this.lines.length, this.scroll + safeHeight)}/${this.lines.length}`;
425
+ while (windowLines.length < safeHeight) windowLines.push('');
426
+ windowLines[safeHeight - 1] = dim(position.padStart(safeWidth));
427
+ }
428
+ this.cursor = null;
429
+ return windowLines;
430
+ }
431
+
432
+ override key(event: any): string | null {
433
+ if (!event) return null;
434
+ const page = Math.max(1, (this.viewHeight || this.height) - 1);
435
+ switch (event.name) {
436
+ case 'escape':
437
+ case 'q': return 'close';
438
+ case 'wheel':
439
+ if (event.wheel?.direction === 'up') this.scroll = Math.max(0, this.scroll - 1);
440
+ else if (event.wheel?.direction === 'down') this.scroll++;
441
+ return 'handled';
442
+ case 'up': this.scroll = Math.max(0, this.scroll - 1); return 'handled';
443
+ case 'down': this.scroll++; return 'handled';
444
+ case 'pageup': this.scroll = Math.max(0, this.scroll - page); return 'handled';
445
+ case 'pagedown': this.scroll += page; return 'handled';
446
+ case 'home': this.scroll = 0; return 'handled';
447
+ case 'end': this.scroll = this.lines.length; return 'handled';
448
+ case 'enter':
449
+ case 'return': return 'close';
450
+ default: return 'handled';
451
+ }
452
+ }
453
+ }
454
+
455
+ /**
456
+ * The approval modal.
457
+ *
458
+ * Answers three questions in one frame, none of which the old prompt answered:
459
+ * how dangerous is this, what exactly will it do, and what will change on disk.
460
+ * The diff scrolls, so a 400-line rewrite is inspectable rather than truncated.
461
+ *
462
+ * The highlighted default is Reject. `y` and `n` remain explicit shortcuts;
463
+ * arrows choose a visible option and Enter commits it. A reflex Enter therefore
464
+ * denies, while an intentional move to either Allow option works consistently.
465
+ */
466
+ export class ApprovalLayer extends Layer {
467
+ request: Record<string, any>;
468
+ detail: string;
469
+ verb: string;
470
+ onAnswer: ((approved: boolean, scope: string) => void) | null;
471
+ scroll: number;
472
+ risk: string;
473
+ role: string;
474
+ capabilityGrant: boolean;
475
+ options: ApprovalOption[];
476
+ selected: number;
477
+ diff: ApprovalDiffResult | null;
478
+ optionBounds?: ApprovalOptionBound[];
479
+ panelGeometry?: { inset?: number; optionScreenRow?: number };
480
+ viewHeight?: number;
481
+ answered?: boolean;
482
+
483
+ constructor(options: ApprovalLayerOptions = {}) {
484
+ const opts = options && typeof options === 'object' ? options : {};
485
+ super({ width: opts.width || 84, height: opts.height || 22, ...opts });
486
+ this.request = opts.request || {};
487
+ this.detail = opts.detail || '';
488
+ this.verb = opts.verb || '';
489
+ this.onAnswer = opts.onAnswer || null;
490
+ this.scroll = 0;
491
+
492
+ // The risk TIER is kept for colour and for the audit trail; it is never
493
+ // shown as a word. Printing 'DANGEROUS' at someone who asked to install a
494
+ // package does not make them careful, it makes them numb — and a gate people
495
+ // are numb to is not a gate. opencode shows a warning triangle and the tool,
496
+ // and that is the whole signal: being asked at all IS the warning.
497
+ const risk = String(this.request.risk || 'unknown').toUpperCase();
498
+ this.risk = risk;
499
+ this.role = risk === 'EXTREME' ? 'danger' : risk === 'DANGEROUS' ? 'warn' : 'accent';
500
+ this.title = 'permission required';
501
+
502
+ // Selectable options, modelled on opencode's permission prompt: a row of
503
+ // chips moved with ←/→ and committed with enter. Typing y/n still answers
504
+ // directly, so the fast path stays one keystroke rather than two.
505
+ // grant_capability stores consent for the named capability group itself.
506
+ // A standing grant for the *manager tool* would also authorize unrelated
507
+ // package and MCP operations, and adds a redundant second confirmation.
508
+ this.capabilityGrant = this.request.tool === 'manage_local_dependencies'
509
+ && this.request.args?.action === 'grant_capability';
510
+ this.options = [
511
+ { id: 'once', label: 'Allow once', answer: true },
512
+ // Standing approval for the rest of the PROCESS — never written to disk.
513
+ // Seven developers in ten would rather grant this than be asked again,
514
+ // and a gate people hammer through is worse than one they chose to lift.
515
+ // It is not the default and it is confirmed a second time before it takes
516
+ // effect; see makeApprovalHandler in cliMode.js.
517
+ ...(!this.capabilityGrant ? [{ id: 'always', label: 'Allow always', answer: true }] : []),
518
+ { id: 'reject', label: 'Reject', answer: false }
519
+ ];
520
+
521
+ // THE DEFAULT IS DENY, AND THAT IS DELIBERATE.
522
+ //
523
+ // opencode starts on its approving option, which suits a coding session
524
+ // where the worst case is an unwanted file edit. Causyne's approval gate
525
+ // also stands in front of `sysRun` and `desktop_act` — arbitrary shell and
526
+ // full control of the user's mouse and keyboard. Enter is the key people
527
+ // press without reading, so it must not be the one that says yes.
528
+ //
529
+ // Approving is still a single keystroke (`y`); it is just not the REFLEX
530
+ // keystroke. Set the highlight to Approve here and one careless enter
531
+ // authorises anything the agent asks for.
532
+ this.selected = this.options.findIndex(option => option.id === 'reject');
533
+
534
+ this.footer = `←→ choose ${GLYPHS.dot} enter confirm ${GLYPHS.dot} ${this.capabilityGrant ? 'y/n' : 'y/a/n'} direct ${GLYPHS.dot} ↑↓ scroll ${GLYPHS.dot} esc reject`;
535
+
536
+ this.diff = approvalDiff(this.request.tool, this.request.args, { width: this.width - 6, maxLines: 400 });
537
+ }
538
+
539
+ override preferredHeight(): number {
540
+ const detailRows = this.detail ? 1 : 0;
541
+ // A diff costs a blank, a stat row and a rule on top of its own rows.
542
+ const diffRows = this.diff ? this.diff.rows.length + 3 : Object.keys(this.request.args || {}).length + 1;
543
+ // +2 for the blank line and the option row that always sit at the bottom.
544
+ return 1 + detailRows + diffRows + 2 + 2;
545
+ }
546
+
547
+ /** The chip row: the selected option is filled, the rest are dimmed. */
548
+ optionRow(): string {
549
+ let col = 0;
550
+ this.optionBounds = [];
551
+ const parts = this.options.map((option, index) => {
552
+ const rendered = index === this.selected
553
+ ? badge(option.id === 'reject' ? 'danger' : 'success', option.label)
554
+ : dim(` ${option.label} `);
555
+ const width = visibleWidth(rendered);
556
+ this.optionBounds!.push({ index, option, startCol: col, endCol: col + width - 1 });
557
+ col += width + 1;
558
+ return rendered;
559
+ });
560
+ return parts.join(' ');
561
+ }
562
+
563
+ override body(width = 80, fullHeight = 20): string[] {
564
+ // Two rows are reserved at the bottom for the blank line and the option
565
+ // chips, so the diff never grows into the controls and push them off-panel.
566
+ const height = Math.max(1, fullHeight - 2);
567
+ const rows: string[] = [];
568
+ const cleanVerb = this.verb ? cleanDialogText(this.verb) : '';
569
+ rows.push(`${paint(this.role, GLYPHS.warnMark)} ${bold(safeDisplay(this.request.tool || ''))}${cleanVerb ? dim(` ${cleanVerb}`) : ''}`);
570
+
571
+ if (this.detail) {
572
+ for (const line of wrap(paint('ink', cleanDialogText(this.detail)), width).slice(0, 2)) rows.push(line);
573
+ }
574
+
575
+ if (this.diff) {
576
+ const stat = [
577
+ this.diff.added ? paint('success', `+${this.diff.added}`) : '',
578
+ this.diff.removed ? paint('danger', `-${this.diff.removed}`) : ''
579
+ ].filter(Boolean).join(' ');
580
+ const note = this.diff.note ? dim(` ${GLYPHS.dot} ${cleanDialogText(this.diff.note)}`) : '';
581
+ // The detail row above already names the file; printing the path again
582
+ // here just spends a row saying the same thing twice.
583
+ const where = this.detail ? '' : `${dim(cleanDialogText(this.diff.path))} `;
584
+ rows.push('');
585
+ rows.push(`${where}${stat}${note}`);
586
+ rows.push(paint('rule', GLYPHS.hLine.repeat(width)));
587
+
588
+ // Only spend a row on the scroll indicator when there is actually
589
+ // something out of view. Reserving it unconditionally cost one diff row
590
+ // on every dialog that fit perfectly.
591
+ const available = Math.max(1, height - rows.length);
592
+ const needsIndicator = this.diff.rows.length > available;
593
+ const room = needsIndicator ? Math.max(1, available - 1) : available;
594
+ this.viewHeight = room;
595
+ const maximum = Math.max(0, this.diff.rows.length - room);
596
+ this.scroll = Math.max(0, Math.min(this.scroll, maximum));
597
+
598
+ for (const line of this.diff.rows.slice(this.scroll, this.scroll + room)) {
599
+ rows.push(truncate(line, width, GLYPHS.ellipsis));
600
+ }
601
+ if (this.diff.rows.length > room) {
602
+ rows.push(dim(`${this.scroll + 1}-${Math.min(this.diff.rows.length, this.scroll + room)}/${this.diff.rows.length}`.padStart(width)));
603
+ }
604
+ } else if (this.request.args) {
605
+ rows.push('');
606
+ // No diff means this is not a file mutation; show the arguments instead,
607
+ // because "approve sysRun" with the command hidden is not consent either.
608
+ for (const [key, value] of Object.entries(this.request.args).slice(0, 8)) {
609
+ const shown = typeof value === 'string' ? shortenHome(value) : safeJsonPreview(value);
610
+ for (const line of wrap(`${paint('muted', key)} ${paint('ink', safeDisplay(String(shown)))}`, width).slice(0, 4)) {
611
+ rows.push(line);
612
+ if (rows.length >= height) break;
613
+ }
614
+ if (rows.length >= height) break;
615
+ }
616
+ }
617
+
618
+ while (rows.length < height) rows.push('');
619
+ rows.push('');
620
+ rows.push(this.optionRow());
621
+
622
+ this.cursor = null;
623
+ return rows.slice(0, fullHeight);
624
+ }
625
+
626
+ override key(event: any): string | null {
627
+ if (!event) return null;
628
+ const page = Math.max(1, (this.viewHeight || 8) - 1);
629
+
630
+ // isChar(), NOT event.name. A printable key decodes to {name:'char',
631
+ // text:'y'} — only MODIFIED letters carry the letter as a name. Testing
632
+ // event.name === 'y' here matched ctrl+y and never matched y, so this
633
+ // dialog could not be approved at all; escape worked, which made it look
634
+ // responsive. See src/tui/keys.js isChar().
635
+ if (isChar(event, 'y')) { this.answer(true, 'once'); return 'close'; }
636
+ if (!this.capabilityGrant && isChar(event, 'a')) { this.answer(true, 'always'); return 'close'; }
637
+ if (isChar(event, 'n')) { this.answer(false, 'reject'); return 'close'; }
638
+ if (event.name === 'escape') { this.answer(false, 'reject'); return 'close'; }
639
+
640
+ // ←/→ move the highlight, enter commits it — opencode's permission model,
641
+ // which is the one people already have muscle memory for. `h`/`l` come
642
+ // along for the same reason opencode binds them: a vim user reaches for
643
+ // them without thinking, and they cost nothing here.
644
+ const move = (delta: number): string => {
645
+ this.selected = (this.selected + delta + this.options.length) % this.options.length;
646
+ return 'handled';
647
+ };
648
+ if (event.name === 'left' || isChar(event, 'h')) return move(-1);
649
+ if (event.name === 'right' || isChar(event, 'l')) return move(1);
650
+ if (event.name === 'enter' || event.name === 'return') {
651
+ const choice = this.options[this.selected];
652
+ this.answer(Boolean(choice && choice.answer), choice ? choice.id : 'reject');
653
+ return 'close';
654
+ }
655
+
656
+ if (event.name === 'mouse' && event.mouse && event.mouse.pressed && event.mouse.button === 0 && !isMouseMotion(event.sequence)) {
657
+ if (!Array.isArray(this.optionBounds) || this.optionBounds.length === 0) {
658
+ this.optionRow();
659
+ }
660
+ const geom = this.panelGeometry;
661
+ const hasZeroRow = Number.isFinite(event.mouse.y);
662
+ const rawRow = hasZeroRow
663
+ ? Math.floor(event.mouse.y)
664
+ : (Number.isFinite(event.mouse.row) ? Math.floor(event.mouse.row) : Number.NaN);
665
+ if (geom && Number.isFinite(rawRow) && typeof geom.optionScreenRow === 'number' && Number.isFinite(geom.optionScreenRow)) {
666
+ // drawLayer() computes 0-based screen rows; legacy synthetic callers send 1-based row.
667
+ const zeroBasedRow = hasZeroRow ? rawRow : rawRow - 1;
668
+ if (Math.abs(zeroBasedRow - geom.optionScreenRow) > 1) return 'handled';
669
+ }
670
+ const hasZeroCol = Number.isFinite(event.mouse.x);
671
+ const rawCol = hasZeroCol
672
+ ? Math.floor(event.mouse.x)
673
+ : (Number.isFinite(event.mouse.col) ? Math.floor(event.mouse.col) : -1);
674
+ const bodyCol = geom
675
+ ? rawCol - (hasZeroCol ? 0 : 1) - (geom.inset || 0) - 2
676
+ : rawCol;
677
+ const hit = (this.optionBounds || []).find(b => bodyCol >= b.startCol && bodyCol <= b.endCol);
678
+ if (hit) {
679
+ this.selected = hit.index;
680
+ this.answer(Boolean(hit.option.answer), hit.option.id);
681
+ return 'close';
682
+ }
683
+ return 'handled';
684
+ }
685
+
686
+ if (event.name === 'wheel') {
687
+ if (event.wheel?.direction === 'up') this.scroll = Math.max(0, this.scroll - 1);
688
+ else if (event.wheel?.direction === 'down') this.scroll++;
689
+ return 'handled';
690
+ }
691
+
692
+ switch (event.name) {
693
+ case 'up': this.scroll = Math.max(0, this.scroll - 1); return 'handled';
694
+ case 'down': this.scroll++; return 'handled';
695
+ case 'pageup': this.scroll = Math.max(0, this.scroll - page); return 'handled';
696
+ case 'pagedown': this.scroll += page; return 'handled';
697
+ case 'home': this.scroll = 0; return 'handled';
698
+ case 'end': this.scroll = this.diff ? this.diff.rows.length : 0; return 'handled';
699
+ default: return 'handled';
700
+ }
701
+ }
702
+
703
+ /**
704
+ * Deliver the decision exactly once.
705
+ *
706
+ * `scope` says WHICH option produced it — 'once', 'always' or 'reject'.
707
+ * closeLayer() calls this with no arguments when a dialog is torn down from
708
+ * outside, and the defaults make that a rejection, which is the safe reading
709
+ * of a question nobody answered.
710
+ */
711
+ answer(approved = false, scope = 'reject'): void {
712
+ if (this.answered) return;
713
+ this.answered = true;
714
+ if (this.onAnswer) this.onAnswer(approved, scope);
715
+ }
716
+ }
717
+
718
+ /** A structured product or architecture choice, separate from permissions. */
719
+ export class DecisionLayer extends Layer {
720
+ request: Record<string, any>;
721
+ onAnswer: ((answer: any) => void) | null;
722
+ options: DecisionOption[];
723
+ selected: number;
724
+ customIndex: number;
725
+ customMode: boolean;
726
+ editor: LineEditor;
727
+ answered: boolean;
728
+
729
+ constructor(options: DecisionLayerOptions = {}) {
730
+ const opts = options && typeof options === 'object' ? options : {};
731
+ super({ width: opts.width || 82, height: opts.height || 24, ...opts });
732
+ this.request = opts.request || {};
733
+ this.onAnswer = opts.onAnswer || null;
734
+ this.options = Array.isArray(this.request.options) ? this.request.options.slice(0, 4) : [];
735
+ this.selected = 0;
736
+ this.customIndex = this.options.length;
737
+ this.customMode = false;
738
+ this.editor = new LineEditor();
739
+ this.answered = false;
740
+ this.title = safeDisplay(this.request.header || 'decision required');
741
+ this.footer = `↑↓ choose ${GLYPHS.dot} enter select ${GLYPHS.dot} esc cancel`;
742
+ }
743
+
744
+ override preferredHeight(): number {
745
+ const questionRows = wrap(safeDisplay(this.request.question || ''), Math.max(20, this.width - 6)).length;
746
+ const reasonRows = wrap(safeDisplay(this.request.reason || ''), Math.max(20, this.width - 6)).length;
747
+ return Math.min(this.height, questionRows + reasonRows + (this.options.length * 2) + 7);
748
+ }
749
+
750
+ override body(width = 78, height = 22): string[] {
751
+ const rows: string[] = [];
752
+ rows.push(...wrap(bold(safeDisplay(this.request.question || 'Choose a direction')), width).slice(0, 4));
753
+ if (this.request.reason) rows.push(...wrap(dim(safeDisplay(this.request.reason)), width).slice(0, 3));
754
+ rows.push('');
755
+
756
+ for (const [index, option] of this.options.entries()) {
757
+ const selected = index === this.selected;
758
+ const marker = selected ? paint('accent', GLYPHS.arrow) : paint('muted', GLYPHS.dot);
759
+ rows.push(`${marker} ${selected ? bold(safeDisplay(option.label || '')) : safeDisplay(option.label || '')}`);
760
+ if (option.description) rows.push(` ${dim(truncate(safeDisplay(option.description), Math.max(1, width - 2), GLYPHS.ellipsis))}`);
761
+ }
762
+
763
+ const safeWidth = Number.isFinite(width) && width > 0 ? Math.floor(width) : 8;
764
+ const safeHeight = Number.isFinite(height) && height > 0 ? Math.floor(height) : rows.length + 2;
765
+ const customSelected = this.selected === this.customIndex;
766
+ rows.push(`${customSelected ? paint('accent', GLYPHS.arrow) : paint('muted', GLYPHS.dot)} ${customSelected ? bold('Type your own answer') : 'Type your own answer'}`);
767
+ if (this.customMode) {
768
+ const raw = this.editor.getText();
769
+ const value = cleanDialogText(raw);
770
+ rows.push(truncate(`${paint('accent', `${GLYPHS.arrow} `)}${value || dim('Describe the direction you want')}`, safeWidth, GLYPHS.ellipsis));
771
+ const rendered = rows.length > safeHeight ? rows.slice(rows.length - safeHeight) : rows;
772
+ const before = visibleWidth(cleanDialogText(raw.slice(0, this.editor.col)));
773
+ this.cursor = {
774
+ x: Math.min(Math.max(0, safeWidth - 1), 2 + before),
775
+ y: Math.max(0, rendered.length - 1)
776
+ };
777
+ this.footer = `enter submit ${GLYPHS.dot} esc choices`;
778
+ return rendered;
779
+ } else {
780
+ this.cursor = null;
781
+ this.footer = `↑↓ choose ${GLYPHS.dot} enter select ${GLYPHS.dot} esc cancel`;
782
+ }
783
+ return rows.slice(0, safeHeight);
784
+ }
785
+
786
+ override key(event: any): string | null {
787
+ if (!event) return null;
788
+ if (this.customMode) {
789
+ if (event.name === 'escape') { this.customMode = false; return 'handled'; }
790
+ if (event.name === 'enter' || event.name === 'return') {
791
+ const label = this.editor.getText().replace(/\s+/g, ' ').trim();
792
+ if (!label) return 'handled';
793
+ this.answer({ requestId: this.request.id, optionId: null, label, custom: true });
794
+ return 'close';
795
+ }
796
+ if (event.name === 'backspace') { this.editor.backspace(); return 'handled'; }
797
+ if (event.name === 'delete') { this.editor.deleteForward(); return 'handled'; }
798
+ if (event.name === 'left') { this.editor.moveLeft(); return 'handled'; }
799
+ if (event.name === 'right') { this.editor.moveRight(); return 'handled'; }
800
+ if (event.name === 'home') { this.editor.moveHome(); return 'handled'; }
801
+ if (event.name === 'end') { this.editor.moveEnd(); return 'handled'; }
802
+ if (event.name === 'paste') {
803
+ const clean = safeDisplay(String(event.text || '')).replace(/[\r\n]+/g, ' ').slice(0, MAX_DIALOG_PASTE_CHARS);
804
+ if (clean) this.editor.insert(clean);
805
+ return 'handled';
806
+ }
807
+ if (event.name === 'char') { this.editor.insert(event.text); return 'handled'; }
808
+ return 'handled';
809
+ }
810
+
811
+ if (event.name === 'escape') { this.answer(null); return 'close'; }
812
+ const count = this.options.length + 1;
813
+ if (event.name === 'up') { this.selected = (this.selected - 1 + count) % count; return 'handled'; }
814
+ if (event.name === 'down') { this.selected = (this.selected + 1) % count; return 'handled'; }
815
+ if (event.name === 'enter' || event.name === 'return') {
816
+ if (this.selected === this.customIndex) { this.customMode = true; return 'handled'; }
817
+ const option = this.options[this.selected];
818
+ if (!option) return 'handled';
819
+ this.answer({ requestId: this.request.id, optionId: option.id, label: option.label, custom: false });
820
+ return 'close';
821
+ }
822
+ return 'handled';
823
+ }
824
+
825
+ answer(value: unknown = null): void {
826
+ if (this.answered) return;
827
+ this.answered = true;
828
+ if (this.onAnswer) this.onAnswer(value);
829
+ }
830
+ }
831
+
832
+ /** A yes/no confirm, for destructive commands that are not tool approvals. */
833
+ export class ConfirmLayer extends Layer {
834
+ message: string;
835
+ onAnswer: ((approved: boolean) => void) | null;
836
+ defaultAnswer: boolean;
837
+ settled: boolean;
838
+
839
+ constructor(options: ConfirmLayerOptions = {}) {
840
+ const opts = options && typeof options === 'object' ? options : {};
841
+ super({ width: opts.width || 60, height: opts.height || 8, ...opts });
842
+ this.message = opts.message || 'Are you sure?';
843
+ this.onAnswer = opts.onAnswer || null;
844
+ this.defaultAnswer = opts.defaultAnswer === true;
845
+ this.footer = this.defaultAnswer
846
+ ? `enter confirm ${GLYPHS.dot} y yes ${GLYPHS.dot} n no ${GLYPHS.dot} esc cancel`
847
+ : `enter cancel ${GLYPHS.dot} y yes ${GLYPHS.dot} n no ${GLYPHS.dot} esc cancel`;
848
+ this.settled = false;
849
+ }
850
+
851
+ /**
852
+ * Dismissal is an ANSWER, and the safe answer is no.
853
+ *
854
+ * ChatPrompt.closeLayer() calls this on any layer that defines it. Without it
855
+ * a confirm torn down from outside — an interrupt, a resize teardown, the
856
+ * host stopping — left its promise pending forever and hung the caller
857
+ * mid-approval. The `settled` guard is what makes the y/n path and this path
858
+ * safe to both fire.
859
+ */
860
+ answer(value = false): void {
861
+ if (this.settled) return;
862
+ this.settled = true;
863
+ if (this.onAnswer) this.onAnswer(Boolean(value));
864
+ }
865
+
866
+ override preferredHeight(): number { return 6; }
867
+
868
+ override body(width = 56): string[] {
869
+ this.cursor = null;
870
+ return ['', ...wrap(paint('ink', safeDisplay(this.message)), width)];
871
+ }
872
+
873
+ override key(event: any): string | null {
874
+ if (!event) return null;
875
+ // `y` is always an explicit approval. Enter follows the default selected by
876
+ // the caller: false for ordinary destructive confirmations, true only for
877
+ // the second step after the user has already selected Allow always.
878
+ if (isChar(event, 'y')) { this.answer(true); return 'close'; }
879
+ if (isChar(event, 'n') || event.name === 'escape') { this.answer(false); return 'close'; }
880
+ if (event.name === 'enter' || event.name === 'return') {
881
+ this.answer(this.defaultAnswer);
882
+ return 'close';
883
+ }
884
+ return 'handled';
885
+ }
886
+ }
887
+
888
+ /** The command palette — every command in the app, fuzzy-searchable. */
889
+ export function commandPalette(commands: readonly any[] | null | undefined, onRun?: ((command: any) => void) | null): SelectLayer {
890
+ const safeCommands = Array.isArray(commands) ? commands.filter(Boolean) : [];
891
+ return new SelectLayer({
892
+ title: 'commands',
893
+ placeholder: 'search commands',
894
+ emptyText: 'no command matches',
895
+ width: 72,
896
+ height: 20,
897
+ items: safeCommands.map((command) => ({
898
+ label: cleanDialogText(command.name || ''),
899
+ description: cleanDialogText(command.description || ''),
900
+ category: cleanDialogText(command.category || ''),
901
+ hint: cleanDialogText(command.hint || ''),
902
+ searchText: cleanDialogText(command.description || ''),
903
+ value: command
904
+ })),
905
+ onPick: (item) => { if (item && onRun) onRun(item.value); }
906
+ });
907
+ }
908
+
909
+ /**
910
+ * The skill browser: 100 skills, fuzzy-searchable, grouped by domain.
911
+ *
912
+ * `/skills` used to print every skill as one unwrapped line. At five skills that
913
+ * was merely ugly — descriptions reached 195 columns on a 102-column terminal
914
+ * and the terminal broke them mid-word at column 0. At 100 it would be a wall of
915
+ * text nobody reads. Both references browse skills in a picker instead
916
+ * (opencode's dialog-skill.tsx), and the picker truncates each description to
917
+ * the pane rather than to the terminal, so overflow is structurally impossible.
918
+ */
919
+ export function skillPicker(skills: readonly any[] | null | undefined, onOpen?: ((skill: any) => void) | null): SelectLayer {
920
+ const safeSkills = Array.isArray(skills) ? skills.filter(Boolean) : [];
921
+ return new SelectLayer({
922
+ title: `skills (${safeSkills.length})`,
923
+ placeholder: 'search skills',
924
+ emptyText: 'no skill matches',
925
+ width: 76,
926
+ height: 22,
927
+ items: safeSkills.map((skill) => ({
928
+ label: `${cleanDialogText(skill.domain || '')}/${cleanDialogText(skill.id || '')}`,
929
+ description: cleanDialogText(skill.description || ''),
930
+ category: cleanDialogText(skill.domain || ''),
931
+ searchText: cleanDialogText(`${skill.name || ''} ${skill.description || ''}`),
932
+ value: skill
933
+ })),
934
+ onPick: (item) => { if (item && onOpen) onOpen(item.value); }
935
+ });
936
+ }
937
+
938
+ /** Help: the keys, grouped, in a scrolling pane. */
939
+ export function helpLayer(sections: readonly any[] | null | undefined): TextLayer {
940
+ const safeSections = Array.isArray(sections) ? sections.filter(Boolean) : [];
941
+ const lines: string[] = [];
942
+ for (const section of safeSections) {
943
+ lines.push(bold(paint('ink', cleanDialogText(section.title || ''))));
944
+ const rows = Array.isArray(section.rows) ? section.rows : [];
945
+ for (const pair of rows) {
946
+ if (!Array.isArray(pair)) continue;
947
+ const keys = cleanDialogText(pair[0] || '');
948
+ const what = cleanDialogText(pair[1] || '');
949
+ lines.push(` ${paint('accent', keys.padEnd(18))}${dim(what)}`);
950
+ }
951
+ lines.push('');
952
+ }
953
+ return new TextLayer({ title: 'keys', lines, width: 62, height: Math.min(24, lines.length + 3) });
954
+ }
955
+
956
+ /** A status pane: session facts that would otherwise need a scrollback hunt. */
957
+ export function statusLayer(rows: readonly any[] | null | undefined): TextLayer {
958
+ const safeRows = (Array.isArray(rows) ? rows : []).filter((row): row is unknown[] => Array.isArray(row));
959
+ const labels = safeRows.map(row => cleanDialogText(row[0] == null ? '' : String(row[0])));
960
+ const width = labels.reduce((max, label) => Math.max(max, label.length), 0);
961
+ const lines = safeRows.map((row, index) => {
962
+ const label = labels[index] ?? '';
963
+ const value = cleanDialogText(row[1] == null ? '' : String(row[1]));
964
+ return label === ''
965
+ ? ''
966
+ : `${paint('muted', label.padEnd(width + 2))}${paint('ink', value)}`;
967
+ });
968
+ return new TextLayer({ title: 'session', lines, width: 74, height: Math.min(24, lines.length + 3) });
969
+ }
970
+
971
+ export { visibleWidth };