@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
@@ -6,17 +6,11 @@
6
6
  // (so it degrades) and through text.safeDisplay (so untrusted tool output
7
7
  // cannot move the cursor or repaint the screen).
8
8
  //
9
- // Pure JS over ./theme.js and ./text.js. No dependency, no shell.
10
-
9
+ // Pure TypeScript over ./theme.js and ./text.js. No dependency, no shell.
11
10
  import readline from 'readline';
12
11
  import { compactSuccessfulToolResult } from './toolActivityPolicy.js';
13
- import {
14
- paint, bold, dim, badge, GLYPHS, terminalWidth, HAS_COLOR, fileLink,
15
- safeLink, HAS_HYPERLINKS
16
- } from './theme.js';
17
- import {
18
- visibleWidth, truncate, wrap, wrapBlock, padEnd, safeDisplay, shortenHome
19
- } from './text.js';
12
+ import { paint, bold, dim, badge, GLYPHS, terminalWidth, HAS_COLOR, fileLink, safeLink, HAS_HYPERLINKS } from './theme.js';
13
+ import { visibleWidth, truncate, wrap, wrapBlock, padEnd, safeDisplay, shortenHome } from './text.js';
20
14
  import { sessionBanner } from './banner.js';
21
15
  import { describeTool } from './toolDisplay.js';
22
16
  import { approvalDiff } from './diff.js';
@@ -30,1509 +24,1266 @@ import { cleanToolOutputPreview, normalizeHistoricalToolResult, normalizeHistori
30
24
  import { formatMarkdownMath } from './markdownMath.js';
31
25
  import { renderThinkingFrame } from './thinkingBox.js';
32
26
  import { measureMessages, resolveCharPool } from '../contextManager.js';
33
-
34
27
  // Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
35
- // minified output would otherwise become thousands of rows and lock the
36
- // terminal. (The failure openclaw's tool-execution component documents.)
28
+ // minified output would otherwise become thousands of rows and lock the terminal.
37
29
  const PREVIEW_LINES = 12;
38
-
39
30
  // Cut the SOURCE before sanitising it, not after.
40
- //
41
- // safeDisplay() runs sanitize() plus four redaction passes over whatever it is
42
- // given. Handing it a 900 KB tool result meant regex-scanning 900 KB to print
43
- // twelve lines. openclaw's tool-execution component bounds the source first for
44
- // exactly this reason; 256 columns per previewed line is far more than any
45
- // terminal shows and still bounds the work at a few KB.
46
31
  const PREVIEW_SOURCE_BUDGET = PREVIEW_LINES * 256;
47
-
48
- // How much of a model's chain of thought to show inline.
49
- //
50
- // Reasoning models emit thousands of tokens of it. Printed in full it buries
51
- // the answer it was reasoning towards, which is the opposite of useful — and on
52
- // the Stage it would push the reply off the viewport entirely. The frame keeps
53
- // the whole thing, so nothing is lost; this is only what is shown at rest.
54
- const REASONING_LINES = 12;
55
-
56
32
  // Column where the timing/status gutter starts, so tool rows line up.
57
33
  const STATUS_GUTTER = 10;
58
-
59
34
  function formatDuration(ms) {
60
- if (!Number.isFinite(ms) || ms <= 0) return '0ms';
61
- if (ms < 1000) return `${Math.round(ms)}ms`;
62
- if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
63
- const totalSeconds = Math.round(ms / 1000);
64
- return `${Math.floor(totalSeconds / 60)}m ${totalSeconds % 60}s`;
35
+ if (!Number.isFinite(ms) || ms <= 0)
36
+ return '0ms';
37
+ if (ms < 1000)
38
+ return `${Math.round(ms)}ms`;
39
+ if (ms < 60000)
40
+ return `${(ms / 1000).toFixed(1)}s`;
41
+ const totalSeconds = Math.round(ms / 1000);
42
+ return `${Math.floor(totalSeconds / 60)}m ${totalSeconds % 60}s`;
65
43
  }
66
-
67
- /**
68
- * Minimal markdown for a terminal.
69
- *
70
- * Agent replies are markdown; printing them raw means the user reads literal
71
- * `**bold**` and ``` fences. This is deliberately small — headings, emphasis,
72
- * inline code, fenced blocks and list bullets. Anything fancier belongs in a
73
- * pager, not a chat transcript.
74
- */
75
44
  function clampMarkdownIndent(raw, markerCols, targetWidth) {
76
- const maxLead = Math.max(0, Math.min(Math.floor(targetWidth / 3), targetWidth - markerCols - 8));
77
- const rawCols = visibleWidth(String(raw || '').replace(/\t/g, ' '));
78
- return ' '.repeat(Math.min(rawCols, maxLead));
45
+ const maxLead = Math.max(0, Math.min(Math.floor(targetWidth / 3), targetWidth - markerCols - 8));
46
+ const rawCols = visibleWidth(String(raw || '').replace(/\t/g, ' '));
47
+ return ' '.repeat(Math.min(rawCols, maxLead));
79
48
  }
80
-
81
49
  function renderMarkdown(text, width) {
82
- const safeWidth = Number.isFinite(width) && width > 0 ? Math.max(12, Math.floor(width)) : 80;
83
- const lines = [];
84
- let inFence = false;
85
-
86
- for (const rawLine of String(text).split('\n')) {
87
- const line = rawLine.replace(/\s+$/, '');
88
-
89
- if (/^\s*```/.test(line)) {
90
- inFence = !inFence;
91
- const language = line.replace(/^\s*```/, '').trim();
92
- const maxLabel = Math.max(0, safeWidth - 8);
93
- const safeLang = language.length > maxLabel ? language.slice(0, maxLabel) : language;
94
- const trail = Math.max(0, safeWidth - 3 - (safeLang ? safeLang.length + 2 : 1));
95
- lines.push(dim(`${GLYPHS.hLine.repeat(3)}${safeLang ? ' ' + safeLang + ' ' : ' '}${GLYPHS.hLine.repeat(trail)}`));
96
- continue;
50
+ const safeWidth = Number.isFinite(width) && width > 0 ? Math.max(12, Math.floor(width)) : 80;
51
+ const lines = [];
52
+ let inFence = false;
53
+ for (const rawLine of String(text).split('\n')) {
54
+ const line = rawLine.replace(/\s+$/, '');
55
+ if (/^\s*```/.test(line)) {
56
+ inFence = !inFence;
57
+ const language = line.replace(/^\s*```/, '').trim();
58
+ const maxLabel = Math.max(0, safeWidth - 8);
59
+ const safeLang = language.length > maxLabel ? language.slice(0, maxLabel) : language;
60
+ const trail = Math.max(0, safeWidth - 3 - (safeLang ? safeLang.length + 2 : 1));
61
+ lines.push(dim(`${GLYPHS.hLine.repeat(3)}${safeLang ? ' ' + safeLang + ' ' : ' '}${GLYPHS.hLine.repeat(trail)}`));
62
+ continue;
63
+ }
64
+ if (inFence) {
65
+ for (const codeRow of wrapBlock(' ' + line, Math.max(8, safeWidth), { hang: 0 })) {
66
+ lines.push(paint('accent', codeRow));
67
+ }
68
+ continue;
69
+ }
70
+ const heading = line.match(/^(#{1,6})\s+(.*)$/);
71
+ if (heading && heading[2] !== undefined) {
72
+ lines.push('');
73
+ for (const headingRow of wrap(heading[2], Math.max(8, safeWidth))) {
74
+ lines.push(bold(paint('ink', headingRow)));
75
+ }
76
+ continue;
77
+ }
78
+ if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
79
+ lines.push(dim(GLYPHS.hLine.repeat(Math.max(4, Math.min(safeWidth, 40)))));
80
+ continue;
81
+ }
82
+ const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/);
83
+ if (bullet && bullet[2] !== undefined) {
84
+ const indent = clampMarkdownIndent(bullet[1], 4, safeWidth) + ' ';
85
+ const wrapped = wrap(inline(bullet[2]), Math.max(8, safeWidth - indent.length - 2));
86
+ wrapped.forEach((part, index) => {
87
+ lines.push(index === 0 ? `${indent}${paint('muted', GLYPHS.bullet)} ${part}` : `${indent} ${part}`);
88
+ });
89
+ continue;
90
+ }
91
+ const numbered = line.match(/^(\s*)(\d+\.)\s+(.*)$/);
92
+ if (numbered && numbered[2] !== undefined && numbered[3] !== undefined) {
93
+ const markerCols = visibleWidth(numbered[2]) + 1;
94
+ const lead = clampMarkdownIndent(numbered[1], markerCols, safeWidth);
95
+ const prefix = `${lead}${bold(numbered[2])} `;
96
+ const indentCols = visibleWidth(lead) + markerCols;
97
+ const indent = ' '.repeat(indentCols);
98
+ const wrapped = wrap(inline(numbered[3]), Math.max(8, safeWidth - indentCols));
99
+ wrapped.forEach((part, index) => {
100
+ lines.push(index === 0 ? `${prefix}${part}` : `${indent}${part}`);
101
+ });
102
+ continue;
103
+ }
104
+ const quote = line.match(/^(\s*)>\s?(.*)$/);
105
+ if (quote && quote[2] !== undefined) {
106
+ const lead = clampMarkdownIndent(quote[1], 2, safeWidth);
107
+ const indent = lead + paint('muted', '│ ');
108
+ const wrapped = wrap(inline(quote[2]), Math.max(8, safeWidth - visibleWidth(lead) - 2));
109
+ wrapped.forEach((part) => {
110
+ lines.push(`${indent}${part}`);
111
+ });
112
+ continue;
113
+ }
114
+ if (/^\s*\|?(\s*:?-+:?\s*\|)+\s*$/.test(line)) {
115
+ lines.push(dim(' ' + GLYPHS.hLine.repeat(Math.max(4, Math.min(safeWidth - 4, 48)))));
116
+ continue;
117
+ }
118
+ const tableRow = line.match(/^\s*\|(.+)\|\s*$/);
119
+ if (tableRow && tableRow[1] !== undefined) {
120
+ const cells = tableRow[1].split('|').map(c => c.trim());
121
+ for (const tableLine of wrapBlock(' ' + cells.join(' │ '), Math.max(8, safeWidth), { hang: 0 })) {
122
+ lines.push(inline(tableLine));
123
+ }
124
+ continue;
125
+ }
126
+ const trimmed = line.trim();
127
+ if (trimmed === '') {
128
+ lines.push('');
129
+ continue;
130
+ }
131
+ if (trimmed === '[' || trimmed === ']')
132
+ continue;
133
+ for (const part of wrap(inline(line), safeWidth))
134
+ lines.push(part);
97
135
  }
98
136
  if (inFence) {
99
- for (const codeRow of wrapBlock(' ' + line, Math.max(8, safeWidth), { hang: 0 })) {
100
- lines.push(paint('accent', codeRow));
101
- }
102
- continue;
103
- }
104
-
105
- const heading = line.match(/^(#{1,6})\s+(.*)$/);
106
- if (heading) {
107
- lines.push('');
108
- for (const headingRow of wrap(heading[2], Math.max(8, safeWidth))) {
109
- lines.push(bold(paint('ink', headingRow)));
110
- }
111
- continue;
112
- }
113
-
114
- if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
115
- lines.push(dim(GLYPHS.hLine.repeat(Math.max(4, Math.min(safeWidth, 40)))));
116
- continue;
117
- }
118
-
119
- const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/);
120
- if (bullet) {
121
- const indent = clampMarkdownIndent(bullet[1], 4, safeWidth) + ' ';
122
- const wrapped = wrap(inline(bullet[2]), Math.max(8, safeWidth - indent.length - 2));
123
- wrapped.forEach((part, index) => {
124
- lines.push(index === 0 ? `${indent}${paint('muted', GLYPHS.bullet)} ${part}` : `${indent} ${part}`);
125
- });
126
- continue;
137
+ lines.push(dim(`${GLYPHS.hLine.repeat(3)} unclosed code block ${GLYPHS.hLine.repeat(Math.max(0, safeWidth - 24))}`));
127
138
  }
128
-
129
- const numbered = line.match(/^(\s*)(\d+\.)\s+(.*)$/);
130
- if (numbered) {
131
- const markerCols = visibleWidth(numbered[2]) + 1;
132
- const lead = clampMarkdownIndent(numbered[1], markerCols, safeWidth);
133
- const prefix = `${lead}${bold(numbered[2])} `;
134
- const indentCols = visibleWidth(lead) + markerCols;
135
- const indent = ' '.repeat(indentCols);
136
- const wrapped = wrap(inline(numbered[3]), Math.max(8, safeWidth - indentCols));
137
- wrapped.forEach((part, index) => {
138
- lines.push(index === 0 ? `${prefix}${part}` : `${indent}${part}`);
139
- });
140
- continue;
141
- }
142
-
143
- const quote = line.match(/^(\s*)>\s?(.*)$/);
144
- if (quote) {
145
- const lead = clampMarkdownIndent(quote[1], 2, safeWidth);
146
- const indent = lead + paint('muted', '│ ');
147
- const wrapped = wrap(inline(quote[2]), Math.max(8, safeWidth - visibleWidth(lead) - 2));
148
- wrapped.forEach((part) => {
149
- lines.push(`${indent}${part}`);
150
- });
151
- continue;
152
- }
153
-
154
- if (/^\s*\|?(\s*:?-+:?\s*\|)+\s*$/.test(line)) {
155
- lines.push(dim(' ' + GLYPHS.hLine.repeat(Math.max(4, Math.min(safeWidth - 4, 48)))));
156
- continue;
157
- }
158
-
159
- const tableRow = line.match(/^\s*\|(.+)\|\s*$/);
160
- if (tableRow) {
161
- const cells = tableRow[1].split('|').map(c => c.trim());
162
- for (const tableLine of wrapBlock(' ' + cells.join(' │ '), Math.max(8, safeWidth), { hang: 0 })) {
163
- lines.push(inline(tableLine));
164
- }
165
- continue;
166
- }
167
-
168
- const trimmed = line.trim();
169
- if (trimmed === '') { lines.push(''); continue; }
170
- if (trimmed === '[' || trimmed === ']') continue;
171
- for (const part of wrap(inline(line), safeWidth)) lines.push(part);
172
- }
173
-
174
- // A fence that never closed.
175
- //
176
- // `inFence` simply toggles, so an unbalanced ``` used to swallow every
177
- // remaining line into code styling and end without a closing rule — the block
178
- // read as still open, forever, with nothing saying so. The model does emit
179
- // these: a reply cut short by a token limit ends mid-fence, and reasoning
180
- // text quotes fences it never closes.
181
- //
182
- // This is also the invariant a streaming renderer would need, and it is the
183
- // one opencode's split-footer mode solves by holding an unstable markdown
184
- // block back until it closes (scrollback.surface.ts:278-307). It cannot hold
185
- // anything back here, because a frame is re-rendered rather than committed —
186
- // so it says what happened instead.
187
- if (inFence) {
188
- lines.push(dim(`${GLYPHS.hLine.repeat(3)} unclosed code block ${GLYPHS.hLine.repeat(Math.max(0, width - 24))}`));
189
- }
190
- return lines;
139
+ return lines;
191
140
  }
192
-
193
141
  // A bare URL, allowing one level of balanced parentheses so a link to
194
142
  // `.../URL_(disambiguation)` is not cut at the first `)`.
195
- const BARE_URL = /https?:\/\/[^\s<>()\[\]"'`]+(?:\([^\s<>()"'`]*\)[^\s<>()\[\]"'`]*)*/g;
196
- const MD_LINK = /\[([^\]\n]{1,80})\]\(((?:https?|file):\/\/[^\s)]+(?:\([^\s)]*\)[^\s)]*)*)\)/g;
197
-
198
- // The longest label a link may show. Anything longer would reach wrap()'s
199
- // hard-split branch, which cuts a long unbroken token by column — and cutting
200
- // through an OSC 8 sequence leaves the link open across the break.
143
+ const BARE_URL = /https?:\/\/[^\s<>()\[\]"'`]{1,1024}(?:\([^\s<>()\[\]"'`]{0,128}\)[^\s<>()\[\]"'`]{0,256}){0,4}/g;
144
+ const MD_LINK = /\[([^\]\n]{1,80})\]\(((?:https?|file):\/\/[^\s()]{1,1024}(?:\([^\s()]{0,128}\)[^\s()]{0,256}){0,4})\)/g;
201
145
  const MAX_LINK_LABEL = 48;
202
-
146
+ const MAX_INLINE_FORMAT_CHARS = 16384;
147
+ const MAX_EXPAND_LINES = 2000;
203
148
  /** Trailing sentence punctuation belongs to the sentence, not to the URL. */
204
149
  function trimUrlPunctuation(url) {
205
- let depth = 0;
206
- for (let index = 0; index < url.length; index++) {
207
- const character = url[index];
208
- if (character === '(') depth++;
209
- else if (character === ')') {
210
- if (depth === 0) return trimUrlPunctuation(url.slice(0, index));
211
- depth--;
150
+ let depth = 0;
151
+ for (let index = 0; index < url.length; index++) {
152
+ const character = url[index];
153
+ if (character === '(')
154
+ depth++;
155
+ else if (character === ')') {
156
+ if (depth === 0)
157
+ return trimUrlPunctuation(url.slice(0, index));
158
+ depth--;
159
+ }
212
160
  }
213
- }
214
- return url.replace(/[?!.,:;*_~]+$/u, '');
161
+ return url.replace(/[?!.,:;*_~]+$/u, '');
215
162
  }
216
-
217
163
  /** `https://docs.example.com/a/very/long/path?x=1` → `docs.example.com/a/…`. */
218
164
  function compactUrlLabel(url) {
219
- let label = url.replace(/^(?:https?|file):\/\//, '').replace(/\/$/, '');
220
- if (label.length > MAX_LINK_LABEL) label = label.slice(0, MAX_LINK_LABEL - 1) + GLYPHS.ellipsis;
221
- return label;
165
+ let label = url.replace(/^(?:https?|file):\/\//, '').replace(/\/$/, '');
166
+ if (label.length > MAX_LINK_LABEL)
167
+ label = label.slice(0, MAX_LINK_LABEL - 1) + GLYPHS.ellipsis;
168
+ return label;
222
169
  }
223
-
224
- /**
225
- * Inline emphasis, code spans and links.
226
- *
227
- * Links are stashed as \u0000N\u0000 placeholders before the emphasis passes run
228
- * and substituted back afterwards, so an escape sequence can never be matched
229
- * by the code-span or bold regex. The placeholder is safe because this function
230
- * only ever sees text that has been through text.safeDisplay(), and sanitize()
231
- * strips \x00 — so a model cannot forge one.
232
- *
233
- * Every URL goes through theme.safeLink(), which re-serialises it from a parsed
234
- * URL object and refuses anything that is not plain http/https.
235
- */
236
170
  function inline(text) {
237
- const stashed = [];
238
- const stash = (rendered) => `\u0000${stashed.push(rendered) - 1}\u0000`;
239
-
240
- let out = String(text);
241
-
242
- if (HAS_HYPERLINKS) {
243
- out = out.replace(MD_LINK, (whole, label, url) => {
244
- const target = trimUrlPunctuation(url);
245
- const shown = label.length > MAX_LINK_LABEL
246
- ? label.slice(0, MAX_LINK_LABEL - 1) + GLYPHS.ellipsis
247
- : label;
248
- const rendered = safeLink(paint('accent', shown), target);
249
- return rendered === paint('accent', shown) ? whole : stash(rendered);
250
- });
251
- out = out.replace(BARE_URL, (whole) => {
252
- const target = trimUrlPunctuation(whole);
253
- const tail = whole.slice(target.length);
254
- const rendered = safeLink(paint('accent', compactUrlLabel(target)), target);
255
- // safeLink returns its input untouched when the URL does not clear the
256
- // bar; in that case leave the original text exactly as written.
257
- return rendered.includes('\x1b]8') ? stash(rendered) + tail : whole;
258
- });
259
- } else {
260
- // No OSC 8 here, so a markdown link must still show where it points.
261
- out = out.replace(MD_LINK, (whole, label, url) => {
262
- if (url.startsWith('file:')) return label;
263
- return `${label} (${url})`;
264
- });
265
- }
266
-
267
- out = out.replace(/`([^`]+)`/g, (_m, code) => stash(HAS_COLOR ? paint('accent', code) : code));
268
- out = formatMarkdownMath(out);
269
- out = HAS_COLOR
270
- ? out.replace(/\*\*\*([^*]+)\*\*\*/g, (_m, strong) => bold(paint('accent', strong)))
271
- : out.replace(/\*\*\*([^*]+)\*\*\*/g, '$1');
272
- out = HAS_COLOR
273
- ? out.replace(/\*\*([^*]+)\*\*/g, (_m, strong) => bold(strong))
274
- : out.replace(/\*\*([^*]+)\*\*/g, '$1');
275
- out = HAS_COLOR
276
- ? out.replace(/(?<=^|[\s(])\*([^*\s](?:[^*]*[^*\s])?)\*(?=[\s).,!?]|$)/g, (_m, italic) => `\x1b[3m${italic}\x1b[23m`)
277
- : out.replace(/(?<=^|[\s(])\*([^*\s](?:[^*]*[^*\s])?)\*(?=[\s).,!?]|$)/g, '$1');
278
- out = HAS_COLOR
279
- ? out.replace(/(?<=^|[\s(])_([^\s_](?:[^_]*[^\s_])?)_(?=[\s).,!?]|$)/g, (_m, italic) => `\x1b[3m${italic}\x1b[23m`)
280
- : out.replace(/(?<=^|[\s(])_([^\s_](?:[^_]*[^\s_])?)_(?=[\s).,!?]|$)/g, '$1');
281
- out = out.replace(/~~([^~]+)~~/g, HAS_COLOR ? '\x1b[9m$1\x1b[29m' : '$1');
282
-
283
- if (stashed.length > 0) {
284
- out = out.replace(/\u0000(\d+)\u0000/g, (m, index) => stashed[Number(index)] || '');
285
- }
286
- return out;
171
+ const stashed = [];
172
+ const stash = (rendered) => `\u0000${stashed.push(rendered) - 1}\u0000`;
173
+ let out = String(text);
174
+ if (out.length > MAX_INLINE_FORMAT_CHARS)
175
+ return out;
176
+ if (HAS_HYPERLINKS) {
177
+ out = out.replace(MD_LINK, (whole, label, url) => {
178
+ const target = trimUrlPunctuation(url);
179
+ const shown = label.length > MAX_LINK_LABEL
180
+ ? label.slice(0, MAX_LINK_LABEL - 1) + GLYPHS.ellipsis
181
+ : label;
182
+ const rendered = safeLink(paint('accent', shown), target);
183
+ return rendered === paint('accent', shown) ? whole : stash(rendered);
184
+ });
185
+ out = out.replace(BARE_URL, (whole) => {
186
+ const target = trimUrlPunctuation(whole);
187
+ const tail = whole.slice(target.length);
188
+ const rendered = safeLink(paint('accent', compactUrlLabel(target)), target);
189
+ return rendered.includes('\x1b]8') ? stash(rendered) + tail : whole;
190
+ });
191
+ }
192
+ else {
193
+ out = out.replace(MD_LINK, (_whole, label, url) => {
194
+ if (url.startsWith('file:'))
195
+ return label;
196
+ return `${label} (${url})`;
197
+ });
198
+ }
199
+ out = out.replace(/`([^`]+)`/g, (_m, code) => stash(HAS_COLOR ? paint('accent', code) : code));
200
+ out = formatMarkdownMath(out);
201
+ out = HAS_COLOR
202
+ ? out.replace(/\*\*\*([^*]+)\*\*\*/g, (_m, strong) => bold(paint('accent', strong)))
203
+ : out.replace(/\*\*\*([^*]+)\*\*\*/g, '$1');
204
+ out = HAS_COLOR
205
+ ? out.replace(/\*\*([^*]+)\*\*/g, (_m, strong) => bold(strong))
206
+ : out.replace(/\*\*([^*]+)\*\*/g, '$1');
207
+ out = HAS_COLOR
208
+ ? out.replace(/(?<=^|[\s(])\*([^*\s](?:[^*]*[^*\s])?)\*(?=[\s).,!?]|$)/g, (_m, italic) => `\x1b[3m${italic}\x1b[23m`)
209
+ : out.replace(/(?<=^|[\s(])\*([^*\s](?:[^*]*[^*\s])?)\*(?=[\s).,!?]|$)/g, '$1');
210
+ out = HAS_COLOR
211
+ ? out.replace(/(?<=^|[\s(])_([^\s_](?:[^_]*[^\s_])?)_(?=[\s).,!?]|$)/g, (_m, italic) => `\x1b[3m${italic}\x1b[23m`)
212
+ : out.replace(/(?<=^|[\s(])_([^\s_](?:[^_]*[^\s_])?)_(?=[\s).,!?]|$)/g, '$1');
213
+ out = out.replace(/~~([^~]+)~~/g, HAS_COLOR ? '\x1b[9m$1\x1b[29m' : '$1');
214
+ if (stashed.length > 0) {
215
+ out = out.replace(/\u0000(\d+)\u0000/g, (_m, index) => stashed[Number(index)] || '');
216
+ }
217
+ return out;
287
218
  }
288
-
289
219
  export class ChatRenderer {
290
- constructor(options = {}) {
291
- this.out = options.out || process.stdout;
292
- this.isTTY = Boolean(this.out.isTTY);
293
- this.stepCount = 0;
294
- this.stepStartedAt = null;
295
- this.spinnerTimer = null;
296
- this.spinnerIndex = 0;
297
- this.currentStatus = '';
298
- this.pendingApprovals = new Map();
299
- this.latestPlan = [];
300
- this.status = new StatusLine();
301
- this.turnStartedAt = null;
302
-
303
- // Full-screen mode owns both of these. The shell hands the renderer the
304
- // width of the transcript viewport (which is not the terminal width — a
305
- // border and a gutter come off it), and takes the status message for its
306
- // footer so no spinner is ever animated into the transcript itself.
307
- this.widthOf = typeof options.width === 'function' ? options.width : null;
308
- this.quietStatus = Boolean(options.quietStatus);
309
- this.onStatusChange = options.onStatusChange || null;
310
-
311
- // Stage mode. When a Transcript is attached the renderer stops being a
312
- // formatter into stdout and becomes a producer of re-renderable frames:
313
- // rows go into the model, and the Stage decides which of them are on
314
- // screen. Null keeps every byte on the path it has always taken.
315
- this.transcript = options.transcript || null;
316
- // Set only while a frame is being produced. write() collects into it
317
- // instead of reaching the terminal.
318
- this.rowSink = null;
319
- // Set only while a frame is being RE-produced at a width that is not the
320
- // terminal's — a reflow after a resize, or a measurement in a test.
321
- this.forcedWidth = 0;
322
- }
323
-
324
- write(line = '') {
325
- // Producing a frame: the rows belong to the model, not to the terminal.
326
- if (this.rowSink) { this.rowSink.push(line); return; }
327
-
328
- // Stage mode: a direct write is a caller that formatted its own rows —
329
- // /report, /mcp, the home status card. It cannot be allowed to reach stdout,
330
- // because the band occupies the bottom of the screen and a bare write lands
331
- // in the middle of it. Wrapped as a frame, it scrolls with everything else.
332
- //
333
- // The text is captured, not re-derived, so this is a pure producer: these
334
- // callers have already committed to a width and cannot be asked for another.
335
- if (this.transcript) {
336
- const text = String(line);
337
- this.transcript.append({ kind: 'notice', produce: () => text.split('\n') });
338
- return;
220
+ out;
221
+ isTTY;
222
+ stepCount;
223
+ stepStartedAt;
224
+ spinnerTimer;
225
+ spinnerIndex;
226
+ currentStatus;
227
+ pendingApprovals;
228
+ latestPlan;
229
+ status;
230
+ turnStartedAt;
231
+ widthOf;
232
+ quietStatus;
233
+ onStatusChange;
234
+ transcript;
235
+ rowSink;
236
+ forcedWidth;
237
+ onBeforeWrite;
238
+ onAfterWrite;
239
+ onPlanChange;
240
+ dialogWillAsk;
241
+ _activeAssistant;
242
+ _assistantStreamId = null;
243
+ _assistantSnapshot = '';
244
+ _assistantSegmentStart = 0;
245
+ _activeReasoning;
246
+ lastOutput;
247
+ constructor(options = {}) {
248
+ const opts = options && typeof options === 'object' ? options : {};
249
+ this.out = opts.out || process.stdout;
250
+ this.isTTY = Boolean(this.out.isTTY);
251
+ this.stepCount = 0;
252
+ this.stepStartedAt = null;
253
+ this.spinnerTimer = null;
254
+ this.spinnerIndex = 0;
255
+ this.currentStatus = '';
256
+ this.pendingApprovals = new Map();
257
+ this.latestPlan = [];
258
+ this.status = new StatusLine();
259
+ this.turnStartedAt = null;
260
+ this.widthOf = typeof opts.width === 'function' ? opts.width : null;
261
+ this.quietStatus = Boolean(opts.quietStatus);
262
+ this.onStatusChange = opts.onStatusChange || null;
263
+ this.transcript = opts.transcript || null;
264
+ this.rowSink = null;
265
+ this.forcedWidth = 0;
266
+ }
267
+ write(line = '') {
268
+ if (this.rowSink) {
269
+ this.rowSink.push(line);
270
+ return;
271
+ }
272
+ if (this.transcript) {
273
+ const text = String(line);
274
+ this.transcript.append({ kind: 'notice', produce: () => text.split('\n') });
275
+ return;
276
+ }
277
+ if (this.onBeforeWrite)
278
+ this.onBeforeWrite();
279
+ this.out.write(line + '\n');
280
+ if (this.onAfterWrite)
281
+ this.onAfterWrite();
282
+ }
283
+ frame(kind, produce, meta = null) {
284
+ if (kind !== 'assistant')
285
+ this._activeAssistant = false;
286
+ if (kind !== 'reasoning')
287
+ this._activeReasoning = false;
288
+ if (!this.transcript) {
289
+ produce();
290
+ return;
291
+ }
292
+ this.transcript.append({
293
+ kind,
294
+ meta,
295
+ produce: (width) => this.capture(width, produce)
296
+ });
297
+ }
298
+ updateTailFrame(kind, produce, meta = null) {
299
+ if (!this.transcript) {
300
+ produce();
301
+ return;
302
+ }
303
+ this.transcript.replaceTail({
304
+ kind,
305
+ meta,
306
+ produce: (width) => this.capture(width, produce)
307
+ });
339
308
  }
340
-
341
- // The prompt occupies the bottom rows of the terminal. It has to lift them
342
- // out of the way before the transcript prints and put them back after, or
343
- // the two writers interleave and leave debris on screen. Nothing is
344
- // attached in non-interactive mode, where both hooks stay undefined.
345
- if (this.onBeforeWrite) this.onBeforeWrite();
346
- this.out.write(line + '\n');
347
- if (this.onAfterWrite) this.onAfterWrite();
348
- }
349
-
350
- /**
351
- * Record one transcript frame, or print it — whichever mode we are in.
352
- *
353
- * `produce` must be a PURE function of width. Every value that depends on
354
- * wall-clock time or on renderer state (the step number, an elapsed
355
- * duration, the model name at the time) has to be resolved by the caller
356
- * before the closure is built, because the closure is called again on every
357
- * resize. That is why the handlers below mutate first and render second: it
358
- * is not style, it is the contract the Transcript rests on.
359
- *
360
- * In scrollback mode this is `produce()` and nothing else, so the byte
361
- * stream is identical to what it has always been.
362
- */
363
- frame(kind, produce, meta = null) {
364
- if (kind !== 'assistant') this._activeAssistant = false;
365
- if (kind !== 'reasoning') this._activeReasoning = false;
366
- if (!this.transcript) { produce(); return; }
367
- this.transcript.append({
368
- kind,
369
- meta,
370
- produce: (width) => this.capture(width, produce)
371
- });
372
- }
373
-
374
- updateTailFrame(kind, produce, meta = null) {
375
- if (!this.transcript) { produce(); return; }
376
- this.transcript.replaceTail({
377
- kind,
378
- meta,
379
- produce: (width) => this.capture(width, produce)
380
- });
381
- }
382
-
383
- /**
384
- * Run a producer with write() redirected and the width pinned.
385
- */
386
- capture(width, produce) {
387
- const sink = [];
388
- const previousSink = this.rowSink;
389
- const previousWidth = this.forcedWidth;
390
- this.rowSink = sink;
391
- this.forcedWidth = width;
392
- try {
393
- produce();
394
- } finally {
395
- this.rowSink = previousSink;
396
- this.forcedWidth = previousWidth;
309
+ capture(width, produce) {
310
+ const sink = [];
311
+ const previousSink = this.rowSink;
312
+ const previousWidth = this.forcedWidth;
313
+ this.rowSink = sink;
314
+ this.forcedWidth = width;
315
+ try {
316
+ produce();
317
+ }
318
+ finally {
319
+ this.rowSink = previousSink;
320
+ this.forcedWidth = previousWidth;
321
+ }
322
+ const maxAvailable = this.transcript?.surface?.composeAvailableWidth
323
+ ? this.transcript.surface.composeAvailableWidth()
324
+ : width;
325
+ const availableWidth = Math.min(width, maxAvailable);
326
+ return sessionRows(sink, availableWidth).rows;
397
327
  }
398
- const maxAvailable = this.transcript?.surface?.composeAvailableWidth
399
- ? this.transcript.surface.composeAvailableWidth()
400
- : width;
401
- const availableWidth = Math.min(width, maxAvailable);
402
- return sessionRows(sink, availableWidth).rows;
403
- }
404
-
405
- /**
406
- * Columns available on the stream this renderer actually writes to.
407
- *
408
- * This used to fall straight through to terminalWidth(), which reads the
409
- * global process.stdout.columns. That is right in production — `out` IS
410
- * stdout — but it means the renderer cannot be measured against anything
411
- * else, and every row it produces is sized from the wrong width the moment it
412
- * is pointed at another stream. ChatPrompt.width() already reasons this way
413
- * for exactly the same reason; the two now agree.
414
- */
415
- width() {
416
- // A reflow asks "what would this frame look like at 96 columns" about rows
417
- // that were produced when the terminal was 200 wide. The pinned width has
418
- // to win over every other source, or a resize re-renders at the old width
419
- // and the viewport silently misreports its own height.
420
- if (this.forcedWidth) return Math.max(40, this.forcedWidth);
421
- if (this.widthOf) return this.widthOf();
422
- const columns = this.out && this.out.columns;
423
- return Number.isFinite(columns) && columns > 0 ? Math.max(40, columns) : terminalWidth();
424
- }
425
-
426
- /** Prose follows the current conversation column with a small text inset. */
427
- measure() {
428
- return this.transcript ? sessionComposerWidth(this.width()) : chatProseWidth(this.width());
429
- }
430
-
431
- // -------------------------------------------------------------------------
432
- // Session framing
433
- // -------------------------------------------------------------------------
434
-
435
- /**
436
- * The context the CLI never showed. Which model is about to spend the user's
437
- * money, in which autonomy mode, over which paths.
438
- */
439
- /** Write the opening composition and report its companion composer width. */
440
- sessionHeader(info = {}) {
441
- // The status line shows the same facts during the turn, where the header
442
- // has already scrolled away. Mutation first: the closure below runs again
443
- // on every reflow and must not re-apply it.
444
- this.status.setSession(info);
445
-
446
- this.frame('session', () => this.renderSessionHeader(info));
447
- return composerWidth(this.width());
448
- }
449
-
450
- renderSessionHeader(info = {}) {
451
- const width = this.width();
452
-
453
- // ONE block: the wordmark with the session facts set beside it, then one
454
- // hint row. This used to be the art, a blank, a bordered panel of four
455
- // label/value rows, a command count, a blank and a separate key-hint row —
456
- // nineteen rows of chrome before the user could type. Both references open
457
- // in eight or fewer, with the identity and the facts as a single object.
458
- const rows = ['', ...sessionBanner(info, width, { height: this.out?.rows }), ''];
459
-
460
- const hints = [
461
- `${info.commandCount || 0} commands`, '/help', 'enter send',
462
- 'alt+enter newline', 'ctrl+p palette', 'esc interrupt', 'exit to leave'
463
- ];
464
- const separator = ` ${GLYPHS.dot} `;
465
- const kept = hints.slice();
466
- while (kept.length > 1 && visibleWidth(kept.join(separator)) > width - 1) kept.pop();
467
- rows.push(dim(kept.join(separator)), '');
468
- for (const row of openingRows(rows, width, Number(this.out?.rows))) this.write(row);
469
- }
470
-
471
- /**
472
- * Closing line for one turn: who answered, on what, in how long.
473
- *
474
- * The reference closes each exchange with `▪ Build · MiMo V2.5 Free · 5.8s`
475
- * (screenshot 15.02.21) — a filled marker, the agent, the model, the elapsed
476
- * time. It is the seam that says "this exchange is finished", which a list of
477
- * four dim hints never did.
478
- */
479
- turnFooter(durationMs) {
480
- // Resolved now, not inside the closure: by the time a resize re-renders
481
- // this frame the step counter has been reset and the model may have been
482
- // switched, and a turn footer that reports the CURRENT state instead of
483
- // the state it closed is a lie that only appears after a resize.
484
- const model = this.status.model;
485
- const steps = this.stepCount;
486
-
487
- this.frame('turn', () => {
488
- const parts = [];
489
- if (model) parts.push(paint('ink', safeDisplay(model)));
490
- parts.push(`${steps} step${steps === 1 ? '' : 's'}`);
491
- if (durationMs > 0) parts.push(formatDuration(durationMs));
492
-
493
- const separator = dim(` ${GLYPHS.dot} `);
494
- this.write();
495
- this.write(`${paint('accent', GLYPHS.step)} ${dim(parts.join(separator))}`);
496
- this.write(dim(` /usage for cost ${GLYPHS.dot} /undo to roll back`));
497
- this.write();
498
- }, { steps, durationMs });
499
- }
500
-
501
- resetTurn() {
502
- this.stepCount = 0;
503
- this.stepStartedAt = null;
504
- this.turnStartedAt = Date.now();
505
- this._activeAssistant = false;
506
- this._activeReasoning = false;
507
- this.status.reset();
508
- }
509
-
510
- // -------------------------------------------------------------------------
511
- // Spinner — only where it can be erased again
512
- // -------------------------------------------------------------------------
513
-
514
- startSpinner(message) {
515
- this.stopSpinner();
516
- this.currentStatus = safeDisplay(message);
517
-
518
- // In full-screen mode the status belongs to the footer, which repaints on
519
- // the shell's own frame clock. Animating here too would write a spinner
520
- // into the scrollback of a transcript that is already being repainted.
521
- if (this.quietStatus) {
522
- if (this.onStatusChange) this.onStatusChange(this.currentStatus);
523
- return;
328
+ width() {
329
+ if (this.forcedWidth)
330
+ return Math.max(40, this.forcedWidth);
331
+ if (this.widthOf)
332
+ return this.widthOf();
333
+ const columns = this.out && this.out.columns;
334
+ return Number.isFinite(columns) && columns > 0 ? Math.max(40, columns) : terminalWidth();
524
335
  }
525
-
526
- // A spinner needs cursor control. Piped into a file or a CI log there is no
527
- // cursor, and the animation becomes thousands of junk lines — so print the
528
- // status once instead.
529
- if (!this.isTTY) {
530
- this.write(paint('muted', this.status.renderStatic(this.currentStatus, this.width())));
531
- return;
336
+ measure() {
337
+ return this.transcript ? sessionComposerWidth(this.width()) : chatProseWidth(this.width());
532
338
  }
533
-
534
- // Elapsed is measured from the START OF THE TURN, not from this spinner.
535
- // A forty-step run restarts the spinner on every frame, so a per-spinner
536
- // clock would reset to 0.0s each time and never show the real wait.
537
- const since = this.turnStartedAt || Date.now();
538
-
539
- this.spinnerTimer = setInterval(() => {
540
- readline.cursorTo(this.out, 0);
541
- const frame = GLYPHS.spinner[this.spinnerIndex % GLYPHS.spinner.length];
542
- this.out.write(this.status.render({
543
- message: this.currentStatus,
544
- elapsedMs: Date.now() - since,
545
- steps: this.stepCount,
546
- width: this.width() - 1,
547
- spinnerFrame: frame,
548
- tick: this.spinnerIndex
549
- }));
550
- readline.clearLine(this.out, 1);
551
- this.spinnerIndex++;
552
- }, 125);
553
- }
554
-
555
- stopSpinner() {
556
- if (this.quietStatus) {
557
- this.currentStatus = '';
558
- if (this.onStatusChange) this.onStatusChange('');
559
- return;
339
+ sessionHeader(info = {}) {
340
+ this.status.setSession(info);
341
+ this.frame('session', () => this.renderSessionHeader(info));
342
+ return composerWidth(this.width());
560
343
  }
561
- if (!this.spinnerTimer) return;
562
- clearInterval(this.spinnerTimer);
563
- this.spinnerTimer = null;
564
- if (this.isTTY) {
565
- readline.clearLine(this.out, 0);
566
- readline.cursorTo(this.out, 0);
344
+ renderSessionHeader(info = {}) {
345
+ const width = this.width();
346
+ const rows = ['', ...sessionBanner(info, width, { height: this.out?.rows }), ''];
347
+ const hints = [
348
+ `${info.commandCount || 0} commands`, '/help', 'enter send',
349
+ 'alt+enter newline', 'ctrl+p palette', 'esc interrupt', 'exit to leave'
350
+ ];
351
+ const separator = ` ${GLYPHS.dot} `;
352
+ const kept = hints.slice();
353
+ while (kept.length > 1 && visibleWidth(kept.join(separator)) > width - 1)
354
+ kept.pop();
355
+ rows.push(dim(kept.join(separator)), '');
356
+ for (const row of openingRows(rows, width, Number(this.out?.rows)))
357
+ this.write(row);
567
358
  }
568
- }
569
-
570
- // -------------------------------------------------------------------------
571
- // Frames
572
- // -------------------------------------------------------------------------
573
-
574
- renderUserMessage(content) {
575
- const text = typeof content === 'string'
576
- ? content
577
- : (Array.isArray(content)
578
- ? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
579
- : String(content || ''));
580
- if (!text.trim()) return;
581
-
582
- this.frame('user', () => {
583
- const measured = this.width();
584
- const maxCaptureWidth = Math.max(8, Math.min(
585
- measured,
586
- this.transcript?.surface?.composeAvailableWidth?.() ?? measured
587
- ) - 4);
588
- const preferred = this.transcript
589
- ? (this.transcript.surface?.composeWidth?.() ?? sessionComposerWidth(measured))
590
- : composerWidth(this.measure());
591
- const blockWidth = this.transcript
592
- ? Math.max(8, Math.min(preferred, maxCaptureWidth))
593
- : Math.max(8, preferred);
594
- const innerWidth = Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - 1);
595
- const rows = barBlock(
596
- wrapBlock(safeDisplay(text), innerWidth, { hang: 0 }),
597
- { width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' }
598
- );
599
- this.write();
600
- for (const row of rows) {
601
- this.write(row);
602
- }
603
- this.write();
604
- }, { messageText: text });
605
- }
606
-
607
- renderAssistantMessage(content) {
608
- const text = typeof content === 'string'
609
- ? content
610
- : (Array.isArray(content)
611
- ? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
612
- : String(content || ''));
613
- if (!text.trim()) return;
614
-
615
- this.onAgentMessage({ content: text });
616
- }
617
-
618
- renderSessionDivider(info = {}) {
619
- this.transcript?.surface?.setSessionInfo?.(info);
620
- this.frame('session', () => {
621
- const width = Math.max(12, this.measure());
622
- const rawTitle = safeDisplay((info && info.title) || 'Session');
623
- const count = (info && info.messagesCount) ?? 0;
624
- const rawCount = count > 0 ? ` (${count} message${count === 1 ? '' : 's'})` : '';
625
- const countText = visibleWidth(rawCount) <= Math.max(0, width - 10) ? rawCount : '';
626
- const title = truncate(rawTitle, Math.max(4, width - visibleWidth(countText) - 6), GLYPHS.ellipsis);
627
- const badgeText = `${title}${countText}`;
628
- const remaining = Math.max(2, width - visibleWidth(badgeText) - 2);
629
- const leftRule = Math.max(1, Math.floor(remaining / 2));
630
- const rightRule = Math.max(1, remaining - leftRule);
631
- this.write();
632
- this.write(`${paint('rule', GLYPHS.hLine.repeat(leftRule))} ${bold(paint('accent', title))}${dim(countText)} ${paint('rule', GLYPHS.hLine.repeat(rightRule))}`);
633
- this.write();
634
- });
635
- }
636
-
637
- clearTranscript() {
638
- this._activeAssistant = false;
639
- this._activeReasoning = false;
640
- this.lastOutput = null;
641
- if (this.transcript && typeof this.transcript.clear === 'function') {
642
- this.transcript.clear();
359
+ turnFooter(durationMs = 0) {
360
+ const model = this.status.model;
361
+ const steps = this.stepCount;
362
+ this.frame('turn', () => {
363
+ const parts = [];
364
+ if (model)
365
+ parts.push(paint('ink', safeDisplay(model)));
366
+ parts.push(`${steps} step${steps === 1 ? '' : 's'}`);
367
+ if (durationMs > 0)
368
+ parts.push(formatDuration(durationMs));
369
+ const separator = dim(` ${GLYPHS.dot} `);
370
+ this.write();
371
+ this.write(`${paint('accent', GLYPHS.step)} ${dim(parts.join(separator))}`);
372
+ this.write(dim(` /usage for cost ${GLYPHS.dot} /undo to roll back`));
373
+ this.write();
374
+ }, { steps, durationMs });
643
375
  }
644
- }
645
-
646
- /**
647
- * Render conversation history frames from a selected or resumed session.
648
- * Mirrors OpenCode's session conversation loader so prior turns are visible in viewport.
649
- */
650
- renderSessionHistory(messages = [], sessionInfo = null) {
651
- const safeMessages = Array.isArray(messages) ? messages : [];
652
- const renderContent = () => {
653
- this.transcript?.surface?.leaveHome?.(true);
654
- this.clearTranscript();
655
- this.latestPlan = [];
656
- this.onPlanChange?.([]);
657
- this.resetTurn();
658
-
659
- const info = sessionInfo ? { ...sessionInfo } : {};
660
- if (info.messagesCount === undefined || info.messagesCount === null) {
661
- info.messagesCount = safeMessages.filter(m => m && m.role !== 'system').length;
662
- }
663
- const measuredChars = measureMessages(safeMessages);
664
- // Loading an empty session must clear usage from the previous chat.
665
- this.status.contextChars = measuredChars;
666
- info.contextChars = measuredChars;
667
-
668
- if (info.title || info.id) {
669
- this.renderSessionDivider(info);
670
- }
671
-
672
- // Index tool results by tool_call_id to pair them with assistant tool_calls
673
- const toolResultsById = new Map();
674
- for (const m of safeMessages) {
675
- if (m && m.role === 'tool' && m.tool_call_id) {
676
- toolResultsById.set(m.tool_call_id, m);
677
- }
678
- }
679
-
680
- const renderedToolMessages = new Set();
681
-
682
- for (let i = 0; i < safeMessages.length; i++) {
683
- const msg = safeMessages[i];
684
- if (!msg) continue;
685
- const role = String(msg.role || '').toLowerCase();
686
-
687
- if (role === 'user') {
688
- this.resetTurn();
689
- this.renderUserMessage(msg.content);
690
- } else if (role === 'assistant') {
691
- // 1. Restore reasoning content as an auto-minimized thinking box
692
- const reasoning = typeof msg.reasoning_content === 'string'
693
- ? msg.reasoning_content.trim()
694
- : (Array.isArray(msg.thinking_blocks)
695
- ? msg.thinking_blocks.map(b => (typeof b === 'string' ? b : b?.thinking || b?.text || '')).filter(Boolean).join('\n').trim()
696
- : '');
697
- if (reasoning) {
698
- const meta = {
699
- reasoning: true,
700
- done: true,
701
- streaming: false,
702
- collapsed: true,
703
- durationText: '',
704
- content: reasoning,
705
- scrollStart: 0
706
- };
707
- this.frame('reasoning', () => this.renderReasoning(meta.content, {
708
- streaming: false,
709
- durationText: '',
710
- collapsed: Boolean(meta.collapsed),
711
- startLine: 0
712
- }), meta);
376
+ resetTurn() {
377
+ this.stepCount = 0;
378
+ this.stepStartedAt = null;
379
+ this.turnStartedAt = Date.now();
380
+ this._activeAssistant = false;
381
+ this._assistantStreamId = null;
382
+ this._assistantSnapshot = '';
383
+ this._assistantSegmentStart = 0;
384
+ this._activeReasoning = false;
385
+ this.status.reset();
386
+ }
387
+ startSpinner(message) {
388
+ this.stopSpinner();
389
+ this.currentStatus = safeDisplay(String(message ?? ''));
390
+ if (this.quietStatus) {
391
+ if (this.onStatusChange)
392
+ this.onStatusChange(this.currentStatus);
393
+ return;
713
394
  }
714
-
715
- // 2. Restore external / native ACP tool executions
716
- if (Array.isArray(msg.external_actions) && msg.external_actions.length > 0) {
717
- for (const ext of msg.external_actions) {
718
- const { toolName, args, result } = normalizeHistoricalExternalAction(ext);
719
- this.onStepStart({ tool: toolName, args });
720
- this.onStepComplete({ tool: toolName, result, elapsed: '' });
721
- }
395
+ if (!this.isTTY) {
396
+ this.write(paint('muted', this.status.renderStatic(this.currentStatus, this.width())));
397
+ return;
722
398
  }
723
-
724
- // 3. If assistant invoked tool calls, render each tool step and pair with its result
725
- if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
726
- for (const call of msg.tool_calls) {
727
- if (!call || typeof call !== 'object') continue;
728
- const toolName = call.function?.name || call.name || 'tool';
729
- let args = {};
399
+ const since = this.turnStartedAt || Date.now();
400
+ this.spinnerTimer = setInterval(() => {
730
401
  try {
731
- args = typeof call.function?.arguments === 'string'
732
- ? JSON.parse(call.function.arguments)
733
- : (call.function?.arguments || {});
734
- } catch {
735
- args = {};
402
+ readline.cursorTo(this.out, 0);
403
+ const frame = GLYPHS.spinner[this.spinnerIndex % GLYPHS.spinner.length] ?? '*';
404
+ if (this.out && typeof this.out.write === 'function') {
405
+ this.out.write(this.status.render({
406
+ message: this.currentStatus,
407
+ elapsedMs: Date.now() - since,
408
+ steps: this.stepCount,
409
+ width: this.width() - 1,
410
+ spinnerFrame: frame,
411
+ tick: this.spinnerIndex
412
+ }));
413
+ }
414
+ readline.clearLine(this.out, 1);
415
+ this.spinnerIndex++;
736
416
  }
737
-
738
- // Restore active implementation plan if update_plan was called
739
- if (toolName === 'update_plan' && args && Array.isArray(args.plan)) {
740
- this.onAgentPlan({
741
- plan: args.plan.filter(Boolean).map(item => ({
742
- ...item,
743
- text: item.text || item.step || item.content || ''
744
- }))
745
- });
417
+ catch {
418
+ this.stopSpinner();
746
419
  }
747
-
748
- // Look up corresponding tool result before emitting step start so
749
- // internal synthesis checkpoints (which never emit steps live) can be skipped.
750
- const toolMsg = call.id ? toolResultsById.get(call.id) : null;
751
- if (toolMsg) {
752
- renderedToolMessages.add(toolMsg);
753
- const normalized = normalizeHistoricalToolResult(toolName, toolMsg);
754
- if (normalized.skipStep) {
755
- continue;
756
- }
757
- if (toolName === 'update_plan' && Array.isArray(normalized.plan)) {
758
- this.onAgentPlan({
759
- plan: normalized.plan.filter(Boolean).map(item => ({
760
- ...item,
761
- text: item.text || item.step || item.content || ''
762
- }))
420
+ }, 125);
421
+ this.spinnerTimer.unref?.();
422
+ }
423
+ stopSpinner() {
424
+ if (this.quietStatus) {
425
+ this.currentStatus = '';
426
+ if (this.onStatusChange)
427
+ this.onStatusChange('');
428
+ return;
429
+ }
430
+ if (!this.spinnerTimer)
431
+ return;
432
+ clearInterval(this.spinnerTimer);
433
+ this.spinnerTimer = null;
434
+ if (this.isTTY) {
435
+ readline.clearLine(this.out, 0);
436
+ readline.cursorTo(this.out, 0);
437
+ }
438
+ }
439
+ renderUserMessage(content) {
440
+ const text = typeof content === 'string'
441
+ ? content
442
+ : (Array.isArray(content)
443
+ ? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
444
+ : String(content || ''));
445
+ if (!text.trim())
446
+ return;
447
+ this.frame('user', () => {
448
+ const measured = this.width();
449
+ const maxCaptureWidth = Math.max(8, Math.min(measured, this.transcript?.surface?.composeAvailableWidth?.() ?? measured) - 4);
450
+ const preferred = this.transcript
451
+ ? (this.transcript.surface?.composeWidth?.() ?? sessionComposerWidth(measured))
452
+ : composerWidth(this.measure());
453
+ const blockWidth = this.transcript
454
+ ? Math.max(8, Math.min(preferred, maxCaptureWidth))
455
+ : Math.max(8, preferred);
456
+ const innerWidth = Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - 1);
457
+ const rows = barBlock(wrapBlock(safeDisplay(text), innerWidth, { hang: 0 }), { width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' });
458
+ this.write();
459
+ for (const row of rows) {
460
+ this.write(row);
461
+ }
462
+ this.write();
463
+ }, { messageText: text });
464
+ }
465
+ renderAssistantMessage(content) {
466
+ const text = typeof content === 'string'
467
+ ? content
468
+ : (Array.isArray(content)
469
+ ? content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
470
+ : String(content || ''));
471
+ if (!text.trim())
472
+ return;
473
+ this.onAgentMessage({ content: text });
474
+ }
475
+ renderSessionDivider(info = {}) {
476
+ this.transcript?.surface?.setSessionInfo?.(info);
477
+ this.frame('session', () => {
478
+ const width = Math.max(12, this.measure());
479
+ const rawTitle = safeDisplay((info && info.title) || 'Session');
480
+ const count = (info && info.messagesCount) ?? 0;
481
+ const rawCount = count > 0 ? ` (${count} message${count === 1 ? '' : 's'})` : '';
482
+ const countText = visibleWidth(rawCount) <= Math.max(0, width - 10) ? rawCount : '';
483
+ const title = truncate(rawTitle, Math.max(4, width - visibleWidth(countText) - 6), GLYPHS.ellipsis);
484
+ const badgeText = `${title}${countText}`;
485
+ const remaining = Math.max(2, width - visibleWidth(badgeText) - 2);
486
+ const leftRule = Math.max(1, Math.floor(remaining / 2));
487
+ const rightRule = Math.max(1, remaining - leftRule);
488
+ this.write();
489
+ this.write(`${paint('rule', GLYPHS.hLine.repeat(leftRule))} ${bold(paint('accent', title))}${dim(countText)} ${paint('rule', GLYPHS.hLine.repeat(rightRule))}`);
490
+ this.write();
491
+ });
492
+ }
493
+ clearTranscript() {
494
+ this._activeAssistant = false;
495
+ this._assistantStreamId = null;
496
+ this._assistantSnapshot = '';
497
+ this._assistantSegmentStart = 0;
498
+ this._activeReasoning = false;
499
+ this.lastOutput = null;
500
+ if (this.transcript && typeof this.transcript.clear === 'function') {
501
+ this.transcript.clear();
502
+ }
503
+ }
504
+ renderSessionHistory(messages = [], sessionInfo = null) {
505
+ const safeMessages = Array.isArray(messages) ? messages : [];
506
+ const renderContent = () => {
507
+ this.transcript?.surface?.leaveHome?.(true);
508
+ this.clearTranscript();
509
+ this.latestPlan = [];
510
+ this.onPlanChange?.([]);
511
+ this.resetTurn();
512
+ const info = sessionInfo ? { ...sessionInfo } : {};
513
+ if (info.messagesCount === undefined || info.messagesCount === null) {
514
+ info.messagesCount = safeMessages.filter(m => m && m.role !== 'system').length;
515
+ }
516
+ const measuredChars = measureMessages(safeMessages);
517
+ this.status.contextChars = measuredChars;
518
+ info.contextChars = measuredChars;
519
+ if (info.title || info.id) {
520
+ this.renderSessionDivider(info);
521
+ }
522
+ const toolResultsById = new Map();
523
+ for (const m of safeMessages) {
524
+ if (m && m.role === 'tool' && m.tool_call_id) {
525
+ toolResultsById.set(m.tool_call_id, m);
526
+ }
527
+ }
528
+ const renderedToolMessages = new Set();
529
+ for (let i = 0; i < safeMessages.length; i++) {
530
+ const msg = safeMessages[i];
531
+ if (!msg)
532
+ continue;
533
+ const role = String(msg.role || '').toLowerCase();
534
+ if (role === 'user') {
535
+ this.resetTurn();
536
+ this.renderUserMessage(msg.content);
537
+ }
538
+ else if (role === 'assistant') {
539
+ const reasoning = typeof msg.reasoning_content === 'string'
540
+ ? msg.reasoning_content.trim()
541
+ : (Array.isArray(msg.thinking_blocks)
542
+ ? msg.thinking_blocks.map((b) => (typeof b === 'string' ? b : b?.thinking || b?.text || '')).filter(Boolean).join('\n').trim()
543
+ : '');
544
+ if (reasoning) {
545
+ const meta = {
546
+ reasoning: true,
547
+ done: true,
548
+ streaming: false,
549
+ collapsed: true,
550
+ durationText: '',
551
+ content: reasoning,
552
+ scrollStart: 0
553
+ };
554
+ this.frame('reasoning', () => this.renderReasoning(meta.content, {
555
+ streaming: false,
556
+ durationText: '',
557
+ collapsed: Boolean(meta.collapsed),
558
+ startLine: 0
559
+ }), meta);
560
+ }
561
+ if (Array.isArray(msg.external_actions) && msg.external_actions.length > 0) {
562
+ for (const ext of msg.external_actions) {
563
+ const { toolName, args, result } = normalizeHistoricalExternalAction(ext);
564
+ this.onStepStart({ tool: toolName, args });
565
+ this.onStepComplete({ tool: toolName, result, elapsed: '' });
566
+ }
567
+ }
568
+ if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
569
+ for (const call of msg.tool_calls) {
570
+ if (!call || typeof call !== 'object')
571
+ continue;
572
+ const toolName = call.function?.name || call.name || 'tool';
573
+ let args = {};
574
+ try {
575
+ args = typeof call.function?.arguments === 'string'
576
+ ? JSON.parse(call.function.arguments)
577
+ : (call.function?.arguments || {});
578
+ }
579
+ catch {
580
+ args = {};
581
+ }
582
+ if (toolName === 'update_plan' && args && Array.isArray(args.plan)) {
583
+ this.onAgentPlan({
584
+ plan: args.plan.filter(Boolean).map((item) => ({
585
+ ...item,
586
+ text: item.text || item.step || item.content || ''
587
+ }))
588
+ });
589
+ }
590
+ const toolMsg = call.id ? toolResultsById.get(call.id) : null;
591
+ if (toolMsg) {
592
+ renderedToolMessages.add(toolMsg);
593
+ const normalized = normalizeHistoricalToolResult(toolName, toolMsg);
594
+ if (normalized.skipStep) {
595
+ continue;
596
+ }
597
+ if (toolName === 'update_plan' && Array.isArray(normalized.plan)) {
598
+ this.onAgentPlan({
599
+ plan: normalized.plan.filter(Boolean).map((item) => ({
600
+ ...item,
601
+ text: item.text || item.step || item.content || ''
602
+ }))
603
+ });
604
+ }
605
+ this.onStepStart({ tool: toolName, args });
606
+ this.onStepComplete({ tool: toolName, result: normalized.result, elapsed: '' });
607
+ }
608
+ else {
609
+ this.onStepStart({ tool: toolName, args });
610
+ }
611
+ }
612
+ }
613
+ const text = typeof msg.content === 'string'
614
+ ? msg.content
615
+ : (Array.isArray(msg.content)
616
+ ? msg.content.map((p) => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
617
+ : (msg.content == null ? '' : String(msg.content)));
618
+ const syntheticNoFinal = msg.causyne_synthetic_no_final === true
619
+ || (text.trim() === 'No final response was provided.'
620
+ && (!Array.isArray(msg.tool_calls) || msg.tool_calls.length === 0));
621
+ if (syntheticNoFinal) {
622
+ const isLatestTurn = !safeMessages.slice(i + 1).some(next => next && (next.role === 'assistant' || next.role === 'user'));
623
+ if (isLatestTurn) {
624
+ this.frame('notice', () => {
625
+ this.write(`${paint('warn', GLYPHS.warnMark)} ${dim('Provider returned no final answer; task completion is unverified.')}`);
626
+ }, { syntheticNoFinal: true });
627
+ }
628
+ }
629
+ else if (text.trim()) {
630
+ this.renderAssistantMessage(text);
631
+ }
632
+ }
633
+ else if (role === 'tool') {
634
+ if (!renderedToolMessages.has(msg)) {
635
+ renderedToolMessages.add(msg);
636
+ const toolName = msg.name || 'tool';
637
+ const normalized = normalizeHistoricalToolResult(toolName, msg, { unpaired: true });
638
+ if (normalized.skipStep) {
639
+ continue;
640
+ }
641
+ this.onStepStart({ tool: toolName, args: {} });
642
+ this.onStepComplete({ tool: toolName, result: normalized.result, elapsed: '' });
643
+ }
644
+ }
645
+ else if (role === 'system') {
646
+ const text = typeof msg.content === 'string' ? msg.content : '';
647
+ if (text.startsWith('[Continuum Context')) {
648
+ this.frame('notice', () => {
649
+ const firstLine = text.split('\n')[0] || '[Continuum Context]';
650
+ this.write(`${paint('accent', GLYPHS.bullet)} ${dim(firstLine)}`);
651
+ });
652
+ }
653
+ }
654
+ }
655
+ const finalMeasured = measureMessages(safeMessages);
656
+ if (finalMeasured > 0) {
657
+ this.status.contextChars = finalMeasured;
658
+ }
659
+ if (!this.status.contextLimit) {
660
+ this.status.contextLimit = resolveCharPool(this.status.tier, undefined, {
661
+ provider: sessionInfo?.provider || this.status.provider,
662
+ model: sessionInfo?.model || this.status.model
763
663
  });
764
- }
765
- this.onStepStart({ tool: toolName, args });
766
- this.onStepComplete({ tool: toolName, result: normalized.result, elapsed: '' });
767
- } else {
768
- this.onStepStart({ tool: toolName, args });
769
664
  }
770
- }
665
+ if (sessionInfo) {
666
+ this.status.setSession({
667
+ ...sessionInfo,
668
+ contextChars: this.status.contextChars || finalMeasured,
669
+ contextLimit: sessionInfo.contextLimit || this.status.contextLimit
670
+ });
671
+ }
672
+ if (this.transcript?.surface?.viewport) {
673
+ this.transcript.surface.viewport.manual = false;
674
+ this.transcript.surface.viewport.unseen = 0;
675
+ this.transcript.surface.viewport.toBottom();
676
+ }
677
+ };
678
+ if (this.transcript && typeof this.transcript.batch === 'function') {
679
+ this.transcript.batch(renderContent);
771
680
  }
772
-
773
- // 4. If assistant has textual content, render it
774
- const text = typeof msg.content === 'string'
775
- ? msg.content
776
- : (Array.isArray(msg.content)
777
- ? msg.content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
778
- : (msg.content == null ? '' : String(msg.content)));
779
- // The agent loop stores a protocol placeholder when a peer emits no
780
- // final reply. Restoring it as a Causyne message falsely implies an
781
- // answer was given. Older histories have the literal but no marker.
782
- const syntheticNoFinal = msg.causyne_synthetic_no_final === true
783
- || (text.trim() === 'No final response was provided.'
784
- && (!Array.isArray(msg.tool_calls) || msg.tool_calls.length === 0));
785
- if (syntheticNoFinal) {
786
- const isLatestTurn = !safeMessages.slice(i + 1).some(next =>
787
- next && (next.role === 'assistant' || next.role === 'user'));
788
- if (isLatestTurn) {
789
- this.frame('notice', () => {
790
- this.write(`${paint('warn', GLYPHS.warnMark)} ${dim('Provider returned no final answer; task completion is unverified.')}`);
791
- }, { syntheticNoFinal: true });
792
- }
793
- } else if (text.trim()) {
794
- this.renderAssistantMessage(text);
681
+ else {
682
+ renderContent();
795
683
  }
796
- } else if (role === 'tool') {
797
- // Standalone or un-paired tool message (e.g. from compacted session turns)
798
- if (!renderedToolMessages.has(msg)) {
799
- renderedToolMessages.add(msg);
800
- const toolName = msg.name || 'tool';
801
- const normalized = normalizeHistoricalToolResult(toolName, msg, { unpaired: true });
802
- if (normalized.skipStep) {
803
- continue;
804
- }
805
-
806
- this.onStepStart({ tool: toolName, args: {} });
807
- this.onStepComplete({ tool: toolName, result: normalized.result, elapsed: '' });
684
+ }
685
+ onAgentMessage(msg) {
686
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
687
+ let content = safeDisplay(safeMsg.content || '');
688
+ const isStreaming = Boolean(safeMsg.streaming);
689
+ const tailIsAssistant = !this.transcript
690
+ || this.transcript.frames?.at(-1)?.meta?.assistant === true;
691
+ if (this._activeAssistant && !tailIsAssistant) {
692
+ this._activeAssistant = false;
808
693
  }
809
- } else if (role === 'system') {
810
- const text = typeof msg.content === 'string' ? msg.content : '';
811
- if (text.startsWith('[Continuum Context')) {
812
- this.frame('notice', () => {
813
- const firstLine = text.split('\n')[0] || '[Continuum Context]';
814
- this.write(`${paint('accent', GLYPHS.bullet)} ${dim(firstLine)}`);
815
- });
694
+ // Each live event contains a cumulative model snapshot. Native tool frames
695
+ // may separate assistant segments, so render only the newly observed suffix.
696
+ if (this.transcript && (typeof safeMsg.streamId === 'number' || typeof safeMsg.streamId === 'string')) {
697
+ const streamKey = String(safeMsg.taskId ?? '') + ':' + String(safeMsg.streamId);
698
+ if (streamKey !== this._assistantStreamId) {
699
+ this._activeAssistant = false;
700
+ this._assistantStreamId = streamKey;
701
+ this._assistantSnapshot = '';
702
+ this._assistantSegmentStart = 0;
703
+ }
704
+ if (content.startsWith(this._assistantSnapshot)) {
705
+ if (!this._activeAssistant)
706
+ this._assistantSegmentStart = this._assistantSnapshot.length;
707
+ }
708
+ else if (this._assistantSegmentStart > content.length || !content.startsWith(this._assistantSnapshot.slice(0, this._assistantSegmentStart))) {
709
+ this._assistantSegmentStart = 0;
710
+ }
711
+ this._assistantSnapshot = content;
712
+ content = content.slice(this._assistantSegmentStart);
713
+ if (!content.trim() && !this._activeAssistant)
714
+ return;
715
+ }
716
+ else {
717
+ this._assistantStreamId = null;
718
+ this._assistantSnapshot = '';
719
+ this._assistantSegmentStart = 0;
720
+ }
721
+ if (isStreaming) {
722
+ if (!this._activeAssistant) {
723
+ this._activeAssistant = true;
724
+ this.frame('assistant', () => this.formatAssistantMessage(content, { streaming: true }), { assistant: true, messageText: content });
725
+ }
726
+ else {
727
+ this.updateTailFrame('assistant', () => this.formatAssistantMessage(content, { streaming: true }), { assistant: true, messageText: content });
728
+ }
729
+ return;
730
+ }
731
+ if (this._activeAssistant) {
732
+ this._activeAssistant = false;
733
+ this.updateTailFrame('assistant', () => this.formatAssistantMessage(content, { streaming: false }), { assistant: true, messageText: content });
734
+ }
735
+ else {
736
+ this.frame('assistant', () => this.formatAssistantMessage(content, { streaming: false }), { assistant: true, messageText: content });
816
737
  }
817
- }
818
738
  }
819
-
820
- const finalMeasured = measureMessages(safeMessages);
821
- if (finalMeasured > 0) {
822
- this.status.contextChars = finalMeasured;
739
+ formatAssistantMessage(content, { streaming = false } = {}) {
740
+ const width = this.measure();
741
+ this.write(`${paint('agent', GLYPHS.arrow)} ${bold(paint('agent', 'Causyne'))}${streaming ? ' ' + dim('…') : ''}`);
742
+ for (const line of renderMarkdown(content, Math.max(8, width - 4))) {
743
+ this.write(line ? ' ' + line : '');
744
+ }
745
+ this.write();
823
746
  }
824
- if (!this.status.contextLimit) {
825
- this.status.contextLimit = resolveCharPool(this.status.tier, undefined, {
826
- provider: sessionInfo?.provider || this.status.provider,
827
- model: sessionInfo?.model || this.status.model
828
- });
747
+ onAgentReasoning(msg) {
748
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
749
+ const content = safeDisplay(safeMsg.content || '');
750
+ const isStreaming = Boolean(safeMsg.streaming);
751
+ const elapsedMs = Number(safeMsg.elapsedMs) || 0;
752
+ const durationText = elapsedMs > 0 ? formatDuration(elapsedMs) : '';
753
+ const activity = typeof safeMsg.activity === 'string' ? safeMsg.activity : '';
754
+ const title = typeof safeMsg.title === 'string' ? safeMsg.title : '';
755
+ const completedTitle = typeof safeMsg.completedTitle === 'string' ? safeMsg.completedTitle : '';
756
+ const tailFrame = this.transcript?.frames?.at(-1);
757
+ const tailIsReasoning = !this.transcript
758
+ || tailFrame?.meta?.reasoning === true;
759
+ if (this._activeReasoning && !tailIsReasoning) {
760
+ this._activeReasoning = false;
761
+ }
762
+ if (isStreaming) {
763
+ if (!this._activeReasoning) {
764
+ this._activeReasoning = true;
765
+ const meta = {
766
+ reasoning: true,
767
+ collapsed: false,
768
+ streaming: true,
769
+ durationText,
770
+ content,
771
+ activity,
772
+ title,
773
+ completedTitle,
774
+ scrollStart: 0
775
+ };
776
+ this.frame('reasoning', () => this.renderReasoning(meta.content, {
777
+ streaming: Boolean(meta.streaming),
778
+ durationText: meta.durationText,
779
+ collapsed: Boolean(meta.collapsed),
780
+ startLine: Number(meta.scrollStart) || 0,
781
+ activity: meta.activity,
782
+ title: meta.title,
783
+ completedTitle: meta.completedTitle
784
+ }), meta);
785
+ }
786
+ else {
787
+ const meta = tailFrame?.meta || { reasoning: true };
788
+ meta.streaming = true;
789
+ meta.durationText = durationText;
790
+ meta.content = content;
791
+ if (activity)
792
+ meta.activity = activity;
793
+ if (title)
794
+ meta.title = title;
795
+ if (completedTitle)
796
+ meta.completedTitle = completedTitle;
797
+ if (meta.collapsed === undefined)
798
+ meta.collapsed = false;
799
+ if (meta.scrollStart === undefined)
800
+ meta.scrollStart = 0;
801
+ this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
802
+ streaming: Boolean(meta.streaming),
803
+ durationText: meta.durationText,
804
+ collapsed: Boolean(meta.collapsed),
805
+ startLine: Number(meta.scrollStart) || 0,
806
+ activity: meta.activity,
807
+ title: meta.title,
808
+ completedTitle: meta.completedTitle
809
+ }), meta);
810
+ }
811
+ return;
812
+ }
813
+ if (this._activeReasoning) {
814
+ this._activeReasoning = false;
815
+ const meta = tailFrame?.meta || { reasoning: true };
816
+ meta.streaming = false;
817
+ meta.done = true;
818
+ meta.durationText = durationText;
819
+ meta.content = content;
820
+ if (activity)
821
+ meta.activity = activity;
822
+ if (title)
823
+ meta.title = title;
824
+ if (completedTitle)
825
+ meta.completedTitle = completedTitle;
826
+ if (meta.collapsed === undefined)
827
+ meta.collapsed = Boolean(safeMsg.collapsed);
828
+ if (meta.scrollStart === undefined)
829
+ meta.scrollStart = 0;
830
+ this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
831
+ streaming: Boolean(meta.streaming),
832
+ durationText: meta.durationText,
833
+ collapsed: Boolean(meta.collapsed),
834
+ startLine: Number(meta.scrollStart) || 0,
835
+ activity: meta.activity,
836
+ title: meta.title,
837
+ completedTitle: meta.completedTitle
838
+ }), meta);
839
+ }
840
+ else if (content.trim()) {
841
+ const meta = {
842
+ reasoning: true,
843
+ done: true,
844
+ streaming: false,
845
+ durationText,
846
+ content,
847
+ activity,
848
+ title,
849
+ completedTitle,
850
+ collapsed: Boolean(safeMsg.collapsed),
851
+ scrollStart: 0
852
+ };
853
+ this.frame('reasoning', () => this.renderReasoning(meta.content, {
854
+ streaming: Boolean(meta.streaming),
855
+ durationText: meta.durationText,
856
+ collapsed: Boolean(meta.collapsed),
857
+ startLine: Number(meta.scrollStart) || 0,
858
+ activity: meta.activity,
859
+ title: meta.title,
860
+ completedTitle: meta.completedTitle
861
+ }), meta);
862
+ }
863
+ }
864
+ renderReasoning(content, { streaming = false, durationText = '', collapsed = false, startLine = 0, activity = '', title = '', completedTitle = '' } = {}) {
865
+ const width = this.measure();
866
+ const rows = renderThinkingFrame(content, {
867
+ width,
868
+ streaming,
869
+ durationText,
870
+ collapsed,
871
+ startLine: Number(startLine) || 0,
872
+ activity,
873
+ title,
874
+ completedTitle
875
+ });
876
+ if (rows.length === 0)
877
+ return;
878
+ this.write();
879
+ for (const row of rows) {
880
+ this.write(row);
881
+ }
882
+ this.write();
829
883
  }
830
- if (sessionInfo) {
831
- this.status.setSession({
832
- ...sessionInfo,
833
- contextChars: this.status.contextChars || finalMeasured,
834
- contextLimit: sessionInfo.contextLimit || this.status.contextLimit
835
- });
884
+ scrollThinkingPanel(_key, _surface) {
885
+ return false;
836
886
  }
837
-
838
- if (this.transcript?.surface?.viewport) {
839
- this.transcript.surface.viewport.manual = false;
840
- this.transcript.surface.viewport.unseen = 0;
841
- this.transcript.surface.viewport.toBottom();
842
- }
843
- };
844
-
845
- if (this.transcript && typeof this.transcript.batch === 'function') {
846
- this.transcript.batch(renderContent);
847
- } else {
848
- renderContent();
887
+ onAgentActivity(msg) {
888
+ if (!msg || typeof msg !== 'object')
889
+ return;
890
+ const text = String(msg.activity || msg.message || '').trim();
891
+ if (!text)
892
+ return;
893
+ this.frame('notice', () => {
894
+ const prefix = `${GLYPHS.arrow || '▸'} `;
895
+ for (const [index, row] of activityRows(text, this.width(), prefix).entries()) {
896
+ if (index === 0) {
897
+ const body = row.startsWith(prefix) ? row.slice(prefix.length) : row;
898
+ this.write(`${paint('accent', GLYPHS.arrow || '▸')} ${dim(body)}`);
899
+ }
900
+ else {
901
+ this.write(dim(row));
902
+ }
903
+ }
904
+ }, { activity: true });
849
905
  }
850
- }
851
-
852
- onAgentMessage(msg) {
853
- const content = safeDisplay(msg.content || '');
854
- const isStreaming = Boolean(msg.streaming);
855
-
856
- const tailIsAssistant = !this.transcript
857
- || this.transcript.frames?.at(-1)?.meta?.assistant === true;
858
- if (this._activeAssistant && !tailIsAssistant) {
859
- this._activeAssistant = false;
906
+ onAgentPlan(msg) {
907
+ if (!msg || !Array.isArray(msg.plan) || msg.plan.length === 0)
908
+ return;
909
+ const plan = msg.plan.slice();
910
+ this.latestPlan = plan;
911
+ const placement = this.onPlanChange?.(plan);
912
+ if (placement === 'sidebar')
913
+ return;
914
+ this.frame('plan', () => this.renderPlan(plan), { items: plan.length });
860
915
  }
861
-
862
- if (isStreaming) {
863
- if (!this._activeAssistant) {
864
- this._activeAssistant = true;
865
- this.frame('assistant', () => this.formatAssistantMessage(content, { streaming: true }), { assistant: true, messageText: String(msg.content || '') });
866
- } else {
867
- this.updateTailFrame('assistant', () => this.formatAssistantMessage(content, { streaming: true }), { assistant: true, messageText: String(msg.content || '') });
868
- }
869
- return;
916
+ onDecisionRequest(msg) {
917
+ if (this.dialogWillAsk)
918
+ return;
919
+ const request = (msg && msg.request) || {};
920
+ this.frame('approval', () => {
921
+ this.write();
922
+ this.write(`${paint('accent', GLYPHS.arrow)} ${bold(safeDisplay(request.header || 'decision required'))}`);
923
+ for (const row of wrapBlock(safeDisplay(request.question || ''), Math.max(20, this.width() - 4), { hang: 0 }))
924
+ this.write(` ${row}`);
925
+ this.write();
926
+ }, { kind: request.kind || 'other' });
870
927
  }
871
-
872
- if (this._activeAssistant) {
873
- this._activeAssistant = false;
874
- this.updateTailFrame('assistant', () => this.formatAssistantMessage(content, { streaming: false }), { assistant: true, messageText: String(msg.content || '') });
875
- } else {
876
- this.frame('assistant', () => this.formatAssistantMessage(content, { streaming: false }), { assistant: true, messageText: String(msg.content || '') });
928
+ onDecisionResult(msg) {
929
+ const request = (msg && msg.request) || {};
930
+ const answer = msg && msg.answer;
931
+ this.frame('approval', () => {
932
+ if (!answer) {
933
+ this.write(` ${paint('muted', 'decision dismissed')} ${safeDisplay(request.header || '')}`);
934
+ return;
935
+ }
936
+ this.write(` ${paint('success', GLYPHS.check)} ${bold(safeDisplay(answer.label || ''))}${answer.custom ? dim(' custom choice') : ''}`);
937
+ }, { kind: request.kind || 'other', answered: Boolean(answer) });
938
+ }
939
+ renderPlan(plan) {
940
+ if (!Array.isArray(plan) || plan.length === 0)
941
+ return;
942
+ const width = this.width();
943
+ this.write();
944
+ this.write(paint('muted', 'plan'));
945
+ for (const item of plan) {
946
+ if (!item || typeof item !== 'object')
947
+ continue;
948
+ const done = item.status === 'completed';
949
+ const active = item.status === 'in_progress';
950
+ const mark = done ? paint('success', GLYPHS.check)
951
+ : active ? paint('accent', GLYPHS.arrow)
952
+ : paint('muted', GLYPHS.dot);
953
+ const text = item.text || item.step || item.content || '';
954
+ const label = done ? dim(safeDisplay(text)) : paint('ink', safeDisplay(text));
955
+ this.write(` ${mark} ${truncate(label, Math.max(8, width - 5), GLYPHS.ellipsis)}`);
956
+ }
957
+ this.write();
877
958
  }
878
- }
879
-
880
- formatAssistantMessage(content, { streaming = false } = {}) {
881
- const width = this.measure();
882
- // The frame already ends with a blank separator. A leading blank row on the
883
- // first assistant response leaves a visible void in compact chat view.
884
- this.write(`${paint('agent', GLYPHS.arrow)} ${bold(paint('agent', 'Causyne'))}${streaming ? ' ' + dim('…') : ''}`);
885
- // Reserve the transcript's three-column inset and final safety cell.
886
- for (const line of renderMarkdown(content, Math.max(8, width - 4))) {
887
- this.write(line ? ' ' + line : '');
959
+ onStepStart(msg) {
960
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
961
+ this.stepStartedAt = Date.now();
962
+ this.stepCount++;
963
+ const toolLabel = safeDisplay(safeMsg.tool || 'tool') || 'tool';
964
+ const { verb, detail } = describeTool(safeMsg.tool, safeMsg.args);
965
+ const step = this.stepCount;
966
+ this.frame('step', () => {
967
+ const width = this.width();
968
+ const index = paint('muted', String(step).padStart(2, '0'));
969
+ const displayVerb = verb || toolLabel;
970
+ const name = paint('accent', padEnd(displayVerb, STATUS_GUTTER));
971
+ const used = 2 + 2 + 1 + Math.max(visibleWidth(displayVerb), STATUS_GUTTER) + 1;
972
+ const detailText = detail ? paint('ink', truncate(detail, Math.max(10, width - used - 12), GLYPHS.ellipsis)) : '';
973
+ this.write(`${paint('muted', GLYPHS.arrow)} ${index} ${name} ${detailText}`);
974
+ }, { step, tool: safeMsg.tool, verb: verb || toolLabel, detail });
888
975
  }
889
- this.write();
890
- }
891
-
892
- /**
893
- * The chain of thought the user paid for.
894
- *
895
- * This frame was emitted by the loop (agentLoop.js:1113) and handled by
896
- * NOBODY — not here, not in the Android app. openai-compatible.js was fixed
897
- * to stop discarding `reasoning_content` because "the reasoning the user paid
898
- * for never reached them", and then it was discarded one layer further down.
899
- *
900
- * It is rendered subordinate to the answer on purpose: a dim rule and a cap.
901
- * Reasoning that shouts as loudly as the reply trains the user to read
902
- * neither, and the reply is the part they asked for.
903
- */
904
- /**
905
- * The chain of thought the user requested: streamed live directly into the
906
- * chat transcript, with real-time updates and clear elapsed time.
907
- */
908
- onAgentReasoning(msg) {
909
- const content = safeDisplay(msg.content || '');
910
- const isStreaming = Boolean(msg.streaming);
911
- const elapsedMs = Number(msg.elapsedMs) || 0;
912
- const durationText = elapsedMs > 0 ? formatDuration(elapsedMs) : '';
913
- const activity = typeof msg.activity === 'string' ? msg.activity : '';
914
- const title = typeof msg.title === 'string' ? msg.title : '';
915
- const completedTitle = typeof msg.completedTitle === 'string' ? msg.completedTitle : '';
916
-
917
- const tailFrame = this.transcript?.frames?.at(-1);
918
- const tailIsReasoning = !this.transcript
919
- || tailFrame?.meta?.reasoning === true;
920
- if (this._activeReasoning && !tailIsReasoning) {
921
- this._activeReasoning = false;
976
+ onStepComplete(msg) {
977
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
978
+ const elapsed = typeof safeMsg.elapsed === 'string'
979
+ ? safeMsg.elapsed
980
+ : (this.stepStartedAt ? formatDuration(Date.now() - this.stepStartedAt) : '');
981
+ const result = safeMsg.result || {};
982
+ this.captureLastOutput(result);
983
+ const tail = this.transcript?.frames?.at(-1);
984
+ if (compactSuccessfulToolResult(this.stepCount, result, tail, safeMsg.tool) && tail?.meta) {
985
+ const { step, verb, detail, tool } = tail.meta;
986
+ const completedElapsed = elapsed;
987
+ this.updateTailFrame('step', () => {
988
+ const width = this.width();
989
+ const index = paint('muted', String(step).padStart(2, '0'));
990
+ const name = paint('accent', padEnd(verb || tool, STATUS_GUTTER));
991
+ const used = 2 + 2 + 1 + Math.max(visibleWidth(verb || tool), STATUS_GUTTER) + 1;
992
+ const tailText = completedElapsed ? ` ${dim(completedElapsed)}` : '';
993
+ const detailWidth = Math.max(5, width - used - visibleWidth(tailText) - 10);
994
+ const detailText = detail ? paint('ink', truncate(detail, detailWidth, GLYPHS.ellipsis)) : '';
995
+ this.write(`${paint('success', GLYPHS.check)} ${index} ${name} ${detailText}${tailText}`);
996
+ }, { ...tail.meta, success: true, elapsed: completedElapsed });
997
+ return;
998
+ }
999
+ this.frame('result', () => {
1000
+ if (result.success) {
1001
+ const elapsedText = elapsed ? ` ${dim(elapsed)}` : '';
1002
+ this.write(` ${paint('success', GLYPHS.check)}${elapsedText}`);
1003
+ this.renderOutputPreview(result, safeMsg.tool || '');
1004
+ return;
1005
+ }
1006
+ const detail = `${safeDisplay(result.error || 'failed')}${elapsed ? ` · ${elapsed}` : ''}`;
1007
+ for (const row of wrappedChatRows(detail, this.width(), ` ${paint('danger', GLYPHS.cross)} `, 'danger'))
1008
+ this.write(row);
1009
+ }, { success: Boolean(result.success) });
922
1010
  }
923
-
924
- if (isStreaming) {
925
- if (!this._activeReasoning) {
926
- this._activeReasoning = true;
927
- const meta = {
928
- reasoning: true,
929
- collapsed: false,
930
- streaming: true,
931
- durationText,
932
- content,
933
- activity,
934
- title,
935
- completedTitle,
936
- scrollStart: 0
937
- };
938
- this.frame('reasoning', () => this.renderReasoning(meta.content, {
939
- streaming: Boolean(meta.streaming),
940
- durationText: meta.durationText,
941
- collapsed: Boolean(meta.collapsed),
942
- startLine: Number(meta.scrollStart) || 0,
943
- activity: meta.activity,
944
- title: meta.title,
945
- completedTitle: meta.completedTitle
946
- }), meta);
947
- } else {
948
- const meta = tailFrame?.meta || { reasoning: true };
949
- meta.streaming = true;
950
- meta.durationText = durationText;
951
- meta.content = content;
952
- if (activity) meta.activity = activity;
953
- if (title) meta.title = title;
954
- if (completedTitle) meta.completedTitle = completedTitle;
955
- if (meta.collapsed === undefined) meta.collapsed = false;
956
- if (meta.scrollStart === undefined) meta.scrollStart = 0;
957
- this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
958
- streaming: Boolean(meta.streaming),
959
- durationText: meta.durationText,
960
- collapsed: Boolean(meta.collapsed),
961
- startLine: Number(meta.scrollStart) || 0,
962
- activity: meta.activity,
963
- title: meta.title,
964
- completedTitle: meta.completedTitle
965
- }), meta);
966
- }
967
- return;
1011
+ expandLastOutput() {
1012
+ if (!this.lastOutput || !this.lastOutput.text) {
1013
+ this.frame('notice', () => this.write(dim(' nothing to expand')));
1014
+ return false;
1015
+ }
1016
+ const output = this.lastOutput;
1017
+ this.frame('result', () => {
1018
+ const width = Math.max(8, this.width() - 7);
1019
+ this.write('');
1020
+ let emitted = 0;
1021
+ let truncatedExpanded = false;
1022
+ for (const line of String(output.text).split('\n')) {
1023
+ for (const part of wrap(safeDisplay(line), width)) {
1024
+ if (emitted >= MAX_EXPAND_LINES) {
1025
+ truncatedExpanded = true;
1026
+ break;
1027
+ }
1028
+ this.write(` ${paint('rule', GLYPHS.vLine)} ${dim(part)}`);
1029
+ emitted++;
1030
+ }
1031
+ if (truncatedExpanded)
1032
+ break;
1033
+ }
1034
+ if (truncatedExpanded) {
1035
+ this.write(` ${paint('rule', GLYPHS.corner)} ${dim(`${GLYPHS.ellipsis} expanded view capped at ${MAX_EXPAND_LINES} lines`)}`);
1036
+ }
1037
+ if (output.spillPath) {
1038
+ this.write(this.clipHint(output.spillPath));
1039
+ }
1040
+ this.write('');
1041
+ }, { expanded: true });
1042
+ return true;
968
1043
  }
969
-
970
- if (this._activeReasoning) {
971
- this._activeReasoning = false;
972
- const meta = tailFrame?.meta || { reasoning: true };
973
- meta.streaming = false;
974
- meta.done = true;
975
- meta.durationText = durationText;
976
- meta.content = content;
977
- if (activity) meta.activity = activity;
978
- if (title) meta.title = title;
979
- if (completedTitle) meta.completedTitle = completedTitle;
980
- if (meta.collapsed === undefined) meta.collapsed = Boolean(msg.collapsed);
981
- if (meta.scrollStart === undefined) meta.scrollStart = 0;
982
- this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
983
- streaming: Boolean(meta.streaming),
984
- durationText: meta.durationText,
985
- collapsed: Boolean(meta.collapsed),
986
- startLine: Number(meta.scrollStart) || 0,
987
- activity: meta.activity,
988
- title: meta.title,
989
- completedTitle: meta.completedTitle
990
- }), meta);
991
- } else if (content.trim()) {
992
- const meta = {
993
- reasoning: true,
994
- done: true,
995
- streaming: false,
996
- durationText,
997
- content,
998
- activity,
999
- title,
1000
- completedTitle,
1001
- collapsed: Boolean(msg.collapsed),
1002
- scrollStart: 0
1003
- };
1004
- this.frame('reasoning', () => this.renderReasoning(meta.content, {
1005
- streaming: Boolean(meta.streaming),
1006
- durationText: meta.durationText,
1007
- collapsed: Boolean(meta.collapsed),
1008
- startLine: Number(meta.scrollStart) || 0,
1009
- activity: meta.activity,
1010
- title: meta.title,
1011
- completedTitle: meta.completedTitle
1012
- }), meta);
1044
+ captureLastOutput(result) {
1045
+ if (!result || typeof result !== 'object')
1046
+ return;
1047
+ const payload = typeof result.output === 'string' ? result.output
1048
+ : typeof result.log === 'string' ? result.log
1049
+ : '';
1050
+ if (!payload)
1051
+ return;
1052
+ this.lastOutput = { text: payload, spillPath: result.spillPath || null };
1013
1053
  }
1014
- }
1015
-
1016
- renderReasoning(content, { streaming = false, durationText = '', collapsed = false, startLine = 0, activity = '', title = '', completedTitle = '' } = {}) {
1017
- const width = this.measure();
1018
- const rows = renderThinkingFrame(content, {
1019
- width,
1020
- streaming,
1021
- durationText,
1022
- collapsed,
1023
- startLine: Number(startLine) || 0,
1024
- activity,
1025
- title,
1026
- completedTitle
1027
- });
1028
-
1029
- if (rows.length === 0) return;
1030
-
1031
- this.write();
1032
- for (const row of rows) {
1033
- this.write(row);
1054
+ renderOutputPreview(result, toolName = '') {
1055
+ if (!result || typeof result !== 'object')
1056
+ return;
1057
+ const rawPayload = typeof result.output === 'string' ? result.output
1058
+ : typeof result.log === 'string' ? result.log
1059
+ : '';
1060
+ const payload = cleanToolOutputPreview(rawPayload, toolName);
1061
+ if (!payload)
1062
+ return;
1063
+ const source = payload.length > PREVIEW_SOURCE_BUDGET
1064
+ ? payload.slice(0, PREVIEW_SOURCE_BUDGET)
1065
+ : payload;
1066
+ if (!source.trim())
1067
+ return;
1068
+ const width = Math.max(8, this.width() - 7);
1069
+ const cleaned = safeDisplay(source).replace(/\n{3,}/g, '\n\n').trim();
1070
+ const wrapped = [];
1071
+ for (const rawLine of cleaned.split('\n')) {
1072
+ const line = rawLine.replace(/\r/g, '').trimEnd();
1073
+ if (/^\s*(?:% Total\b|Dload\s+Upload\b|\d+\s+\d+\s+\d+\s+.*--:--:--)/i.test(line))
1074
+ continue;
1075
+ for (const part of wrap(line, width)) {
1076
+ wrapped.push(part);
1077
+ if (wrapped.length > PREVIEW_LINES + 1)
1078
+ break;
1079
+ }
1080
+ if (wrapped.length > PREVIEW_LINES + 1)
1081
+ break;
1082
+ }
1083
+ const previewLimit = this.stepCount >= 12 ? 5 : PREVIEW_LINES;
1084
+ for (const line of wrapped.slice(0, previewLimit)) {
1085
+ this.write(` ${paint('rule', GLYPHS.vLine)} ${dim(line)}`);
1086
+ }
1087
+ const clipped = wrapped.length > previewLimit || source.length < payload.length;
1088
+ if (clipped)
1089
+ this.write(this.clipHint(result.spillPath));
1034
1090
  }
1035
- this.write();
1036
- }
1037
-
1038
- scrollThinkingPanel(key, surface) {
1039
- return false;
1040
- }
1041
-
1042
- onAgentActivity(msg) {
1043
- if (!msg || typeof msg !== 'object') return;
1044
- const text = String(msg.activity || msg.message || '').trim();
1045
- if (!text) return;
1046
- this.frame('notice', () => {
1047
- const prefix = `${GLYPHS.arrow || '▸'} `;
1048
- for (const [index, row] of activityRows(text, this.width(), prefix).entries()) {
1049
- if (index === 0) {
1050
- const body = row.startsWith(prefix) ? row.slice(prefix.length) : row;
1051
- this.write(`${paint('accent', GLYPHS.arrow || '▸')} ${dim(body)}`);
1052
- } else {
1053
- this.write(dim(row));
1091
+ clipHint(spillPath) {
1092
+ const corner = paint('rule', GLYPHS.corner);
1093
+ const room = Math.max(12, this.width() - 8);
1094
+ if (spillPath) {
1095
+ const label = truncate(shortenHome(spillPath), Math.max(8, room - 13), GLYPHS.ellipsis);
1096
+ return ` ${corner} ${dim(`full output: ${fileLink(label, spillPath)}`)}`;
1054
1097
  }
1055
- }
1056
- }, { activity: true });
1057
- }
1058
-
1059
- onAgentPlan(msg) {
1060
- if (!msg || !Array.isArray(msg.plan) || msg.plan.length === 0) return;
1061
- const plan = msg.plan.slice();
1062
- this.latestPlan = plan;
1063
- const placement = this.onPlanChange?.(plan);
1064
- if (placement === 'sidebar') return;
1065
- this.frame('plan', () => this.renderPlan(plan), { items: plan.length });
1066
- }
1067
-
1068
- onDecisionRequest(msg) {
1069
- if (this.dialogWillAsk) return;
1070
- const request = (msg && msg.request) || {};
1071
- this.frame('approval', () => {
1072
- this.write();
1073
- this.write(`${paint('accent', GLYPHS.arrow)} ${bold(safeDisplay(request.header || 'decision required'))}`);
1074
- for (const row of wrapBlock(safeDisplay(request.question || ''), Math.max(20, this.width() - 4), { hang: 0 })) this.write(` ${row}`);
1075
- this.write();
1076
- }, { kind: request.kind || 'other' });
1077
- }
1078
-
1079
- onDecisionResult(msg) {
1080
- const request = (msg && msg.request) || {};
1081
- const answer = msg && msg.answer;
1082
- this.frame('approval', () => {
1083
- if (!answer) {
1084
- this.write(` ${paint('muted', 'decision dismissed')} ${safeDisplay(request.header || '')}`);
1085
- return;
1086
- }
1087
- this.write(` ${paint('success', GLYPHS.check)} ${bold(safeDisplay(answer.label || ''))}${answer.custom ? dim(' custom choice') : ''}`);
1088
- }, { kind: request.kind || 'other', answered: Boolean(answer) });
1089
- }
1090
-
1091
- renderPlan(plan) {
1092
- if (!Array.isArray(plan) || plan.length === 0) return;
1093
- const width = this.width();
1094
- this.write();
1095
- this.write(paint('muted', 'plan'));
1096
- for (const item of plan) {
1097
- if (!item || typeof item !== 'object') continue;
1098
- const done = item.status === 'completed';
1099
- const active = item.status === 'in_progress';
1100
- const mark = done ? paint('success', GLYPHS.check)
1101
- : active ? paint('accent', GLYPHS.arrow)
1102
- : paint('muted', GLYPHS.dot);
1103
- const text = item.text || item.step || item.content || '';
1104
- const label = done ? dim(safeDisplay(text)) : paint('ink', safeDisplay(text));
1105
- this.write(` ${mark} ${truncate(label, Math.max(8, width - 5), GLYPHS.ellipsis)}`);
1098
+ const full = `${GLYPHS.ellipsis} output truncated — ctrl+o to expand`;
1099
+ const short = `${GLYPHS.ellipsis} truncated — ctrl+o`;
1100
+ const hint = visibleWidth(full) <= room ? full
1101
+ : visibleWidth(short) <= room ? short
1102
+ : truncate(full, room, GLYPHS.ellipsis);
1103
+ return ` ${corner} ${dim(hint)}`;
1106
1104
  }
1107
- this.write();
1108
- }
1109
-
1110
- onStepStart(msg) {
1111
- const safeMsg = msg && typeof msg === 'object' ? msg : {};
1112
- this.stepStartedAt = Date.now();
1113
- this.stepCount++;
1114
-
1115
- const toolLabel = safeDisplay(safeMsg.tool || 'tool') || 'tool';
1116
- const { verb, detail } = describeTool(safeMsg.tool, safeMsg.args);
1117
- const step = this.stepCount;
1118
-
1119
- this.frame('step', () => {
1120
- const width = this.width();
1121
- const index = paint('muted', String(step).padStart(2, '0'));
1122
- const displayVerb = verb || toolLabel;
1123
- const name = paint('accent', padEnd(displayVerb, STATUS_GUTTER));
1124
-
1125
- const used = 2 + 2 + 1 + Math.max(visibleWidth(displayVerb), STATUS_GUTTER) + 1;
1126
- const detailText = detail ? paint('ink', truncate(detail, Math.max(10, width - used - 12), GLYPHS.ellipsis)) : '';
1127
-
1128
- this.write(`${paint('muted', GLYPHS.arrow)} ${index} ${name} ${detailText}`);
1129
- }, { step, tool: safeMsg.tool, verb: verb || toolLabel, detail });
1130
- }
1131
-
1132
- onStepComplete(msg) {
1133
- const safeMsg = msg && typeof msg === 'object' ? msg : {};
1134
- const elapsed = typeof safeMsg.elapsed === 'string'
1135
- ? safeMsg.elapsed
1136
- : (this.stepStartedAt ? formatDuration(Date.now() - this.stepStartedAt) : '');
1137
- const result = safeMsg.result || {};
1138
-
1139
- // Kept so Ctrl+O can show the whole thing, and set here rather than inside
1140
- // the closure — a reflow must not re-point "the last output" at a tool
1141
- // result the user finished with ten turns ago.
1142
- this.captureLastOutput(result);
1143
-
1144
- const tail = this.transcript?.frames?.at(-1);
1145
- if (compactSuccessfulToolResult(this.stepCount, result, tail, msg?.tool)) {
1146
- const { step, verb, detail, tool } = tail.meta;
1147
- const completedElapsed = elapsed;
1148
- this.updateTailFrame('step', () => {
1149
- const width = this.width();
1150
- const index = paint('muted', String(step).padStart(2, '0'));
1151
- const name = paint('accent', padEnd(verb || tool, STATUS_GUTTER));
1152
- const used = 2 + 2 + 1 + Math.max(visibleWidth(verb || tool), STATUS_GUTTER) + 1;
1153
- const tailText = completedElapsed ? ` ${dim(completedElapsed)}` : '';
1154
- const detailWidth = Math.max(5, width - used - visibleWidth(tailText) - 10);
1155
- const detailText = detail ? paint('ink', truncate(detail, detailWidth, GLYPHS.ellipsis)) : '';
1156
- this.write(`${paint('success', GLYPHS.check)} ${index} ${name} ${detailText}${tailText}`);
1157
- }, { ...tail.meta, success: true, elapsed: completedElapsed });
1158
- return;
1105
+ onCheckpoint(msg) {
1106
+ if (!msg || typeof msg !== 'object')
1107
+ return;
1108
+ const where = typeof msg.path === 'string' ? safeDisplay(shortenHome(msg.path)) : '';
1109
+ const count = Number(msg.count) || 1;
1110
+ this.frame('checkpoint', () => {
1111
+ const label = where
1112
+ ? `restore point ${GLYPHS.dot} ${where}`
1113
+ : `restore point ${GLYPHS.dot} ${count} file${count === 1 ? '' : 's'}`;
1114
+ this.write(` ${paint('muted', GLYPHS.dot)} ${dim(truncate(label, Math.max(10, this.width() - 8), GLYPHS.ellipsis))}`);
1115
+ }, { tool: msg.tool, path: msg.path || null, step: msg.step ?? null, taskId: msg.taskId || null });
1159
1116
  }
1160
-
1161
- this.frame('result', () => {
1162
- if (result.success) {
1163
- const elapsedText = elapsed ? ` ${dim(elapsed)}` : '';
1164
- this.write(` ${paint('success', GLYPHS.check)}${elapsedText}`);
1165
- this.renderOutputPreview(result, msg?.tool || '');
1166
- return;
1167
- }
1168
- const detail = `${safeDisplay(result.error || 'failed')}${elapsed ? ` · ${elapsed}` : ''}`;
1169
- for (const row of wrappedChatRows(detail, this.width(), ` ${paint('danger', GLYPHS.cross)} `, 'danger')) this.write(row);
1170
- }, { success: Boolean(result.success) });
1171
- }
1172
-
1173
- /**
1174
- * A bounded look at what the tool actually returned.
1175
- *
1176
- * The old renderer printed only a tick, so the user never saw any tool output
1177
- * at all — they were approving and trusting blind.
1178
- */
1179
- /**
1180
- * Print the last tool output in full — bound to Ctrl+O.
1181
- *
1182
- * The preview is deliberately twelve lines, which is right until it is not.
1183
- * Before this the cut was permanent and the only recovery was re-running the
1184
- * tool, which costs tokens to see something already fetched.
1185
- */
1186
- expandLastOutput() {
1187
- if (!this.lastOutput || !this.lastOutput.text) {
1188
- this.frame('notice', () => this.write(dim(' nothing to expand')));
1189
- return false;
1117
+ onStepError(msg) {
1118
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1119
+ const label = safeDisplay(`${safeMsg.tool || ''}`.trim());
1120
+ const rawError = safeMsg.error || (safeMsg.result && (safeMsg.result.error || safeMsg.result.message)) || '';
1121
+ const detail = safeDisplay(`${rawError}`.trim());
1122
+ const head = label && detail ? `${label} ${detail}` : (detail || label || 'failed');
1123
+ this.frame('error', () => {
1124
+ const rows = wrapBlock(head, Math.max(20, this.width() - 7), { hang: 0 });
1125
+ this.write(` ${paint('danger', GLYPHS.cross)} ${paint('danger', rows[0] || '')}`);
1126
+ for (const row of rows.slice(1))
1127
+ this.write(` ${dim(row)}`);
1128
+ }, { tool: safeMsg.tool });
1190
1129
  }
1191
- // Bound to the output as it is NOW. Ctrl+O twice, ten turns apart, must
1192
- // leave two frames showing two different outputs, not one shown twice.
1193
- const output = this.lastOutput;
1194
- this.frame('result', () => {
1195
- const width = Math.max(8, this.width() - 7);
1196
- this.write('');
1197
- for (const line of String(output.text).split('\n')) {
1198
- for (const part of wrap(safeDisplay(line), width)) {
1199
- this.write(` ${paint('rule', GLYPHS.vLine)} ${dim(part)}`);
1130
+ onApprovalRequest(msg) {
1131
+ if (!msg || typeof msg !== 'object')
1132
+ return;
1133
+ if (msg.toolCallId)
1134
+ this.pendingApprovals.set(msg.toolCallId, msg);
1135
+ if (this.dialogWillAsk)
1136
+ return;
1137
+ const diff = approvalDiff(msg.tool, msg.args, { width: this.width() });
1138
+ this.frame('approval', () => this.renderApprovalRequest(msg, diff), {
1139
+ tool: msg.tool,
1140
+ risk: String(msg.risk || 'unknown').toUpperCase()
1141
+ });
1142
+ }
1143
+ renderApprovalRequest(msg, diff = undefined) {
1144
+ if (!msg || typeof msg !== 'object')
1145
+ return;
1146
+ const risk = String(msg.risk || 'unknown').toUpperCase();
1147
+ const role = risk === 'EXTREME' ? 'danger' : risk === 'DANGEROUS' ? 'warn' : 'accent';
1148
+ const { verb, detail } = describeTool(msg.tool, msg.args);
1149
+ this.write();
1150
+ this.write(`${paint(role, GLYPHS.warnMark)} ${paint('ink', 'permission required')} ${bold(safeDisplay(msg.tool || ''))}${verb ? dim(` ${verb}`) : ''}`);
1151
+ if (detail) {
1152
+ this.write(` ${paint('ink', truncate(detail, Math.max(8, this.width() - 4), GLYPHS.ellipsis))}`);
1153
+ }
1154
+ const resolvedDiff = diff === undefined ? approvalDiff(msg.tool, msg.args, { width: this.width() }) : diff;
1155
+ if (resolvedDiff) {
1156
+ const stat = [
1157
+ resolvedDiff.added ? paint('success', `+${resolvedDiff.added}`) : '',
1158
+ resolvedDiff.removed ? paint('danger', `-${resolvedDiff.removed}`) : ''
1159
+ ].filter(Boolean).join(' ');
1160
+ const note = resolvedDiff.note ? dim(` ${GLYPHS.dot} ${resolvedDiff.note}`) : '';
1161
+ const where = detail ? '' : `${dim(resolvedDiff.path)} `;
1162
+ this.write(` ${where}${stat}${note}`);
1163
+ this.write();
1164
+ for (const row of resolvedDiff.rows)
1165
+ this.write(row);
1166
+ if (resolvedDiff.clipped) {
1167
+ this.write(` ${paint('rule', GLYPHS.corner)} ${dim(`${GLYPHS.ellipsis} diff truncated`)}`);
1168
+ }
1169
+ this.write();
1200
1170
  }
1201
- }
1202
- if (output.spillPath) {
1203
- this.write(this.clipHint(output.spillPath));
1204
- }
1205
- this.write('');
1206
- }, { expanded: true });
1207
- return true;
1208
- }
1209
-
1210
- /**
1211
- * Remember the payload Ctrl+O expands. Separate from rendering it, because
1212
- * rendering runs again on every reflow and this must not.
1213
- */
1214
- captureLastOutput(result) {
1215
- if (!result || typeof result !== 'object') return;
1216
- const payload = typeof result.output === 'string' ? result.output
1217
- : typeof result.log === 'string' ? result.log
1218
- : '';
1219
- if (!payload) return;
1220
- this.lastOutput = { text: payload, spillPath: result.spillPath || null };
1221
- }
1222
-
1223
- renderOutputPreview(result, toolName = '') {
1224
- if (!result || typeof result !== 'object') return;
1225
- const rawPayload = typeof result.output === 'string' ? result.output
1226
- : typeof result.log === 'string' ? result.log
1227
- : '';
1228
- const payload = cleanToolOutputPreview(rawPayload, toolName);
1229
- if (!payload) return;
1230
-
1231
- const source = payload.length > PREVIEW_SOURCE_BUDGET
1232
- ? payload.slice(0, PREVIEW_SOURCE_BUDGET)
1233
- : payload;
1234
- if (!source.trim()) return;
1235
-
1236
- const width = Math.max(8, this.width() - 7);
1237
- const cleaned = safeDisplay(source).replace(/\n{3,}/g, '\n\n').trim();
1238
-
1239
- // Wrap first, THEN cut — bounding by source newlines lets a single long
1240
- // line through as thousands of wrapped rows. Filter out transient curl progress noise.
1241
- const wrapped = [];
1242
- for (const rawLine of cleaned.split('\n')) {
1243
- const line = rawLine.replace(/\r/g, '').trimEnd();
1244
- if (/^\s*(?:% Total\b|Dload\s+Upload\b|\d+\s+\d+\s+\d+\s+.*--:--:--)/i.test(line)) continue;
1245
- for (const part of wrap(line, width)) {
1246
- wrapped.push(part);
1247
- if (wrapped.length > PREVIEW_LINES + 1) break;
1248
- }
1249
- if (wrapped.length > PREVIEW_LINES + 1) break;
1250
1171
  }
1251
-
1252
- // A long tool-heavy run needs a concise preview. Full output remains
1253
- // available through the existing Ctrl+O expansion path and spill files.
1254
- const previewLimit = this.stepCount >= 12 ? 5 : PREVIEW_LINES;
1255
- for (const line of wrapped.slice(0, previewLimit)) {
1256
- this.write(` ${paint('rule', GLYPHS.vLine)} ${dim(line)}`);
1172
+ renderApprovalDecision(msg, approved, scope = 'once') {
1173
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1174
+ const verdict = !approved
1175
+ ? paint('danger', 'rejected')
1176
+ : scope === 'always'
1177
+ ? paint('warn', 'allowed always')
1178
+ : paint('success', 'allowed once');
1179
+ const { verb } = describeTool(safeMsg.tool, safeMsg.args);
1180
+ this.frame('approval', () => {
1181
+ this.write(` ${verdict} ${bold(safeDisplay(safeMsg.tool || ''))}${verb ? dim(` ${verb}`) : ''}`);
1182
+ }, { tool: safeMsg.tool, approved: Boolean(approved), scope });
1183
+ }
1184
+ onError(msg) {
1185
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1186
+ const message = safeDisplay(safeMsg.message || '');
1187
+ this.frame('error', () => {
1188
+ this.write();
1189
+ for (const row of wrappedChatRows(message, this.width(), `${badge('danger', 'ERROR')} `, 'danger'))
1190
+ this.write(row);
1191
+ this.write();
1192
+ });
1257
1193
  }
1258
- const clipped = wrapped.length > previewLimit || source.length < payload.length;
1259
- if (clipped) this.write(this.clipHint(result.spillPath));
1260
- }
1261
-
1262
- /**
1263
- * The "there is more than this" footer, fitted to the terminal.
1264
- *
1265
- * It was a fixed string. At 40 columns it came back six columns too wide and
1266
- * wrapped — which in scrollback is merely ugly, and inside the Stage's band is
1267
- * the exact failure the width clamp exists to prevent. Found by sweeping the
1268
- * clamp at stage geometry, not by anyone looking at a narrow terminal.
1269
- *
1270
- * A path is shortened BEFORE it is made into a link, never after: truncate()
1271
- * is escape-aware, but cutting a finished OSC 8 sequence in half leaves the
1272
- * hyperlink open across the break.
1273
- */
1274
- clipHint(spillPath) {
1275
- const corner = paint('rule', GLYPHS.corner);
1276
- // Five spaces of gutter, the corner, and the space after it.
1277
- const room = Math.max(12, this.width() - 8);
1278
-
1279
- if (spillPath) {
1280
- const label = truncate(shortenHome(spillPath), Math.max(8, room - 13), GLYPHS.ellipsis);
1281
- return ` ${corner} ${dim(`full output: ${fileLink(label, spillPath)}`)}`;
1194
+ onBudgetWarning(msg) {
1195
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1196
+ const message = safeDisplay(safeMsg.message || '');
1197
+ this.frame('notice', () => {
1198
+ for (const row of wrappedChatRows(message, this.width(), `${badge('warn', 'BUDGET')} `, 'warn'))
1199
+ this.write(row);
1200
+ }, { tone: 'warn' });
1282
1201
  }
1283
-
1284
- // Say the shorter true thing rather than the longer half-cut one.
1285
- const full = `${GLYPHS.ellipsis} output truncated — ctrl+o to expand`;
1286
- const short = `${GLYPHS.ellipsis} truncated — ctrl+o`;
1287
- const hint = visibleWidth(full) <= room ? full
1288
- : visibleWidth(short) <= room ? short
1289
- : truncate(full, room, GLYPHS.ellipsis);
1290
- return ` ${corner} ${dim(hint)}`;
1291
- }
1292
-
1293
- /**
1294
- * A restore point was taken before a tool changed a file.
1295
- *
1296
- * Emitted between the step row and its result, and indented to the result
1297
- * gutter so it reads as part of that step rather than as a new event. Quiet
1298
- * on purpose: it happens on every mutating call, and an aside that shouts as
1299
- * loudly as the work trains the user to read neither.
1300
- */
1301
- onCheckpoint(msg) {
1302
- if (!msg || typeof msg !== 'object') return;
1303
- const where = typeof msg.path === 'string' ? safeDisplay(shortenHome(msg.path)) : '';
1304
- const count = Number(msg.count) || 1;
1305
- this.frame('checkpoint', () => {
1306
- const label = where
1307
- ? `restore point ${GLYPHS.dot} ${where}`
1308
- : `restore point ${GLYPHS.dot} ${count} file${count === 1 ? '' : 's'}`;
1309
- this.write(` ${paint('muted', GLYPHS.dot)} ${dim(truncate(label, Math.max(10, this.width() - 8), GLYPHS.ellipsis))}`);
1310
- }, { tool: msg.tool, path: msg.path || null, step: msg.step ?? null, taskId: msg.taskId || null });
1311
- }
1312
-
1313
- onStepError(msg) {
1314
- const safeMsg = msg && typeof msg === 'object' ? msg : {};
1315
- // Wrapped and hanging-indented, not written as one long string.
1316
- //
1317
- // Loop-level failures now carry a real explanation across several lines —
1318
- // what could not be reached, why, and what to check. Emitting that as a
1319
- // single write put the continuation lines at column 0, under a marker
1320
- // indented five columns, so the whole block read as unrelated fragments.
1321
- const label = safeDisplay(`${safeMsg.tool || ''}`.trim());
1322
- const rawError = safeMsg.error || (safeMsg.result && (safeMsg.result.error || safeMsg.result.message)) || '';
1323
- const detail = safeDisplay(`${rawError}`.trim());
1324
- const head = label && detail ? `${label} ${detail}` : (detail || label || 'failed');
1325
-
1326
- this.frame('error', () => {
1327
- const rows = wrapBlock(head, Math.max(20, this.width() - 7), { hang: 0 });
1328
- this.write(` ${paint('danger', GLYPHS.cross)} ${paint('danger', rows[0] || '')}`);
1329
- for (const row of rows.slice(1)) this.write(` ${dim(row)}`);
1330
- }, { tool: safeMsg.tool });
1331
- }
1332
-
1333
- /**
1334
- * Keep the approval detail so the prompt can name what is being approved.
1335
- * L6 in the local-path audit: a bare "Proceed?" is not human-in-the-loop.
1336
- */
1337
- onApprovalRequest(msg) {
1338
- if (!msg || typeof msg !== 'object') return;
1339
- if (msg.toolCallId) this.pendingApprovals.set(msg.toolCallId, msg);
1340
-
1341
- // When an interactive dialog will ask the question, DO NOT also print the
1342
- // whole request into the transcript. It shipped doing both: the same risk
1343
- // badge, command and diff appeared once in the scrollback and again inside
1344
- // the modal, so the user read the same alarming block twice and the panel
1345
- // looked like a duplicate of a thing that had already happened.
1346
- //
1347
- // The transcript still gets a record — see renderApprovalDecision(), which
1348
- // writes ONE line after the user answers. That is the audit trail; the
1349
- // panel is the question. Printing the question twice is not an audit trail.
1350
- if (this.dialogWillAsk) return;
1351
-
1352
- // The diff is resolved ONCE, here, and closed over.
1353
- //
1354
- // approvalDiff() reads the file from disk. If it ran from inside the
1355
- // producer, a resize would re-read the file — and by then the write has
1356
- // been approved and applied, so the transcript would show the user a diff
1357
- // of the change against itself. A record of what someone consented to may
1358
- // not be re-derived from the world after they consented.
1359
- const diff = approvalDiff(msg.tool, msg.args, { width: this.width() });
1360
-
1361
- this.frame('approval', () => this.renderApprovalRequest(msg, diff), {
1362
- tool: msg.tool,
1363
- risk: String(msg.risk || 'unknown').toUpperCase()
1364
- });
1365
- }
1366
-
1367
- renderApprovalRequest(msg, diff = undefined) {
1368
- if (!msg || typeof msg !== 'object') return;
1369
- // Colour carries the tier; the word never reaches the user. See the note
1370
- // in dialogs.js ApprovalLayer — 'DANGEROUS' printed at somebody installing a
1371
- // package teaches them to stop reading these.
1372
- const risk = String(msg.risk || 'unknown').toUpperCase();
1373
- const role = risk === 'EXTREME' ? 'danger' : risk === 'DANGEROUS' ? 'warn' : 'accent';
1374
- const { verb, detail } = describeTool(msg.tool, msg.args);
1375
-
1376
- this.write();
1377
- this.write(`${paint(role, GLYPHS.warnMark)} ${paint('ink', 'permission required')} ${bold(safeDisplay(msg.tool || ''))}${verb ? dim(` ${verb}`) : ''}`);
1378
- if (detail) {
1379
- this.write(` ${paint('ink', truncate(detail, Math.max(8, this.width() - 4), GLYPHS.ellipsis))}`);
1202
+ onStatus(msg) {
1203
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1204
+ this.startSpinner(safeMsg.message || '');
1380
1205
  }
1381
-
1382
- // What the user is actually consenting to. Without this the approval gate
1383
- // asks a human to authorise a file mutation they have never seen — which is
1384
- // consent in form only. null for every tool that does not change a file.
1385
- //
1386
- // Resolved by the caller so it is computed once, at the moment consent was
1387
- // asked for; a direct caller that passes nothing still gets the live read.
1388
- if (diff === undefined) diff = approvalDiff(msg.tool, msg.args, { width: this.width() });
1389
- if (diff) {
1390
- const stat = [
1391
- diff.added ? paint('success', `+${diff.added}`) : '',
1392
- diff.removed ? paint('danger', `-${diff.removed}`) : ''
1393
- ].filter(Boolean).join(' ');
1394
- const note = diff.note ? dim(` ${GLYPHS.dot} ${diff.note}`) : '';
1395
- // The detail row above already names the file; repeating it here just
1396
- // prints the same path twice. Only fall back to the diff's own path when
1397
- // the tool had no readable detail to show.
1398
- const where = detail ? '' : `${dim(diff.path)} `;
1399
- this.write(` ${where}${stat}${note}`);
1400
- this.write();
1401
- for (const row of diff.rows) this.write(row);
1402
- if (diff.clipped) {
1403
- this.write(` ${paint('rule', GLYPHS.corner)} ${dim(`${GLYPHS.ellipsis} diff truncated`)}`);
1404
- }
1405
- this.write();
1206
+ skillInvoked(id, instruction) {
1207
+ this.frame('skill', () => {
1208
+ const width = this.width();
1209
+ const head = `${paint('accent', GLYPHS.step)} ${bold(paint('ink', 'skill'))}`
1210
+ + `${dim(` ${GLYPHS.dot} `)}${paint('agent', safeDisplay(String(id ?? '')))}`;
1211
+ this.write();
1212
+ this.write(truncate(head, Math.max(8, width - 1), GLYPHS.ellipsis));
1213
+ if (instruction) {
1214
+ for (const line of wrapBlock(safeDisplay(String(instruction)), Math.max(8, width - 4), { hang: 0 })) {
1215
+ this.write(dim(` ${line}`));
1216
+ }
1217
+ }
1218
+ }, { skill: String(id || '') });
1219
+ }
1220
+ onNotice(msg) {
1221
+ const safeMsg = msg && typeof msg === 'object' ? msg : {};
1222
+ const tone = ['accent', 'success', 'warn', 'muted'].includes(safeMsg.tone) ? String(safeMsg.tone) : 'muted';
1223
+ const message = safeDisplay(safeMsg.message || '');
1224
+ this.frame('notice', () => {
1225
+ const width = this.measure();
1226
+ const marker = paint(tone === 'muted' ? 'rule' : tone, GLYPHS.vLine);
1227
+ for (const line of wrapBlock(message, Math.max(8, width - 2), { hang: 0 })) {
1228
+ this.write(`${marker} ${dim(line)}`);
1229
+ }
1230
+ }, { tone });
1406
1231
  }
1407
- }
1408
-
1409
- /**
1410
- * One line recording what the user actually decided.
1411
- *
1412
- * Written AFTER the answer, so the scrollback reads as history rather than
1413
- * as a second copy of the prompt. Only used when a dialog asked the
1414
- * question; the non-interactive path still prints the full block, because
1415
- * there the scrollback IS the only place the request was ever shown.
1416
- */
1417
- renderApprovalDecision(msg, approved, scope = 'once') {
1418
- // A standing grant must be VISIBLE in the transcript. Someone who lifts the
1419
- // gate for a whole session should be able to scroll back and see that they
1420
- // did, and `/approvals` tells them how to take it back.
1421
- const verdict = !approved
1422
- ? paint('danger', 'rejected')
1423
- : scope === 'always'
1424
- ? paint('warn', 'allowed always')
1425
- : paint('success', 'allowed once');
1426
- const { verb } = describeTool(msg.tool, msg.args);
1427
- this.frame('approval', () => {
1428
- this.write(` ${verdict} ${bold(safeDisplay(msg.tool || ''))}${verb ? dim(` ${verb}`) : ''}`);
1429
- }, { tool: msg.tool, approved: Boolean(approved), scope });
1430
- }
1431
-
1432
- onError(msg) {
1433
- const safeMsg = msg && typeof msg === 'object' ? msg : {};
1434
- const message = safeDisplay(safeMsg.message || '');
1435
- this.frame('error', () => {
1436
- this.write();
1437
- for (const row of wrappedChatRows(message, this.width(), `${badge('danger', 'ERROR')} `, 'danger')) this.write(row);
1438
- this.write();
1439
- });
1440
- }
1441
-
1442
- onBudgetWarning(msg) {
1443
- const safeMsg = msg && typeof msg === 'object' ? msg : {};
1444
- const message = safeDisplay(safeMsg.message || '');
1445
- this.frame('notice', () => {
1446
- for (const row of wrappedChatRows(message, this.width(), `${badge('warn', 'BUDGET')} `, 'warn')) this.write(row);
1447
- }, { tone: 'warn' });
1448
- }
1449
-
1450
- onStatus(msg) {
1451
- const safeMsg = msg && typeof msg === 'object' ? msg : {};
1452
- this.startSpinner(safeMsg.message || '');
1453
- }
1454
-
1455
- /**
1456
- * A skill was invoked — say so in one line, do not print the skill.
1457
- *
1458
- * The reported behaviour: invoking a skill dumped the whole SKILL.md into the
1459
- * terminal, frontmatter and all, and that was the ENTIRE effect. None of the
1460
- * references do that — a skill is a working method the model follows, not a
1461
- * document it reads back at you. The body now goes into the request; what the
1462
- * user sees here is a marker that it was picked up, in the same shape as a
1463
- * step row.
1464
- */
1465
- skillInvoked(id, instruction) {
1466
- this.frame('skill', () => {
1467
- const width = this.width();
1468
- const head = `${paint('accent', GLYPHS.step)} ${bold(paint('ink', 'skill'))}`
1469
- + `${dim(` ${GLYPHS.dot} `)}${paint('agent', safeDisplay(id))}`;
1470
- this.write();
1471
- this.write(truncate(head, Math.max(8, width - 1), GLYPHS.ellipsis));
1472
- if (instruction) {
1473
- for (const line of wrapBlock(safeDisplay(instruction), Math.max(8, width - 4), { hang: 0 })) {
1474
- this.write(dim(` ${line}`));
1232
+ handle(msg) {
1233
+ if (!msg || typeof msg.type !== 'string')
1234
+ return false;
1235
+ if (msg.type !== 'status')
1236
+ this.stopSpinner();
1237
+ switch (msg.type) {
1238
+ case 'status':
1239
+ this.onStatus(msg);
1240
+ return true;
1241
+ case 'agent_activity':
1242
+ this.onAgentActivity(msg);
1243
+ return true;
1244
+ case 'agent_message':
1245
+ this.onAgentMessage(msg);
1246
+ return true;
1247
+ case 'agent_reasoning':
1248
+ this.onAgentReasoning(msg);
1249
+ return true;
1250
+ case 'agent_plan':
1251
+ this.onAgentPlan(msg);
1252
+ return true;
1253
+ case 'step_start':
1254
+ this.onStepStart(msg);
1255
+ return true;
1256
+ case 'step_complete':
1257
+ this.onStepComplete(msg);
1258
+ return true;
1259
+ case 'step_error':
1260
+ this.onStepError(msg);
1261
+ return true;
1262
+ case 'checkpoint':
1263
+ this.onCheckpoint(msg);
1264
+ return true;
1265
+ case 'approval_request':
1266
+ this.onApprovalRequest(msg);
1267
+ return true;
1268
+ case 'decision_request':
1269
+ this.onDecisionRequest(msg);
1270
+ return true;
1271
+ case 'decision_result':
1272
+ this.onDecisionResult(msg);
1273
+ return true;
1274
+ case 'error':
1275
+ this.onError(msg);
1276
+ return true;
1277
+ case 'budget_warning':
1278
+ this.onBudgetWarning(msg);
1279
+ return true;
1280
+ case 'notice':
1281
+ this.onNotice(msg);
1282
+ return true;
1283
+ case 'usage_update':
1284
+ this.status.onUsage(msg);
1285
+ return true;
1286
+ default: return false;
1475
1287
  }
1476
- }
1477
- }, { skill: String(id || '') });
1478
- }
1479
-
1480
- /**
1481
- * A one-line aside from the loop: tier, packs, compaction, a cache hit.
1482
- *
1483
- * These were bare console.log calls in agentLoop.js — a second writer to a
1484
- * terminal whose bottom rows the prompt repaints in place, which is why they
1485
- * left debris. Routed here they pass through write(), so the live region is
1486
- * lifted out of the way first and put back after, and they inherit the theme
1487
- * instead of carrying a hardcoded \x1b[1m\x1b[36m that ignored NO_COLOR.
1488
- *
1489
- * Deliberately quiet: a dim marker and one wrapped line. An aside that shouts
1490
- * as loudly as the agent's answer trains the user to stop reading both.
1491
- */
1492
- onNotice(msg) {
1493
- const safeMsg = msg && typeof msg === 'object' ? msg : {};
1494
- const tone = ['accent', 'success', 'warn', 'muted'].includes(safeMsg.tone) ? safeMsg.tone : 'muted';
1495
- const message = safeDisplay(safeMsg.message || '');
1496
- this.frame('notice', () => {
1497
- const width = this.measure();
1498
- const marker = paint(tone === 'muted' ? 'rule' : tone, GLYPHS.vLine);
1499
- for (const line of wrapBlock(message, Math.max(8, width - 2), { hang: 0 })) {
1500
- this.write(`${marker} ${dim(line)}`);
1501
- }
1502
- }, { tone });
1503
- }
1504
-
1505
- /**
1506
- * Route one frame. Returns true when handled.
1507
- *
1508
- * Unknown frame types are ignored rather than printed raw — the loop emits
1509
- * several the terminal has no business showing (usage_update, task_complete).
1510
- */
1511
- handle(msg) {
1512
- if (!msg || typeof msg.type !== 'string') return false;
1513
- if (msg.type !== 'status') this.stopSpinner();
1514
-
1515
- switch (msg.type) {
1516
- case 'status': this.onStatus(msg); return true;
1517
- case 'agent_activity': this.onAgentActivity(msg); return true;
1518
- case 'agent_message': this.onAgentMessage(msg); return true;
1519
- case 'agent_reasoning': this.onAgentReasoning(msg); return true;
1520
- case 'agent_plan': this.onAgentPlan(msg); return true;
1521
- case 'step_start': this.onStepStart(msg); return true;
1522
- case 'step_complete': this.onStepComplete(msg); return true;
1523
- case 'step_error': this.onStepError(msg); return true;
1524
- case 'checkpoint': this.onCheckpoint(msg); return true;
1525
- case 'approval_request': this.onApprovalRequest(msg); return true;
1526
- case 'decision_request': this.onDecisionRequest(msg); return true;
1527
- case 'decision_result': this.onDecisionResult(msg); return true;
1528
- case 'error': this.onError(msg); return true;
1529
- case 'budget_warning': this.onBudgetWarning(msg); return true;
1530
- case 'notice': this.onNotice(msg); return true;
1531
- // Not printed — it feeds the live status line, which is where a running
1532
- // token and cost total belongs. Printing it would interleave a counter
1533
- // into the transcript on every single model response.
1534
- case 'usage_update': this.status.onUsage(msg); return true;
1535
- default: return false;
1536
1288
  }
1537
- }
1538
1289
  }