@causyne/agent 1.20.122 → 1.20.124

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (518) hide show
  1. package/bin/causyne.js +38 -15
  2. package/docs/SECURITY_REVIEW.md +42 -6
  3. package/package.json +5 -5
  4. package/src/acp/agentCatalog.js +74 -50
  5. package/src/acp/agentCatalog.ts +82 -49
  6. package/src/acp/client.js +309 -86
  7. package/src/acp/client.ts +291 -84
  8. package/src/acp/protocol.js +147 -3
  9. package/src/acp/protocol.ts +162 -3
  10. package/src/acp/server.js +138 -39
  11. package/src/acp/server.ts +122 -41
  12. package/src/agent/errorClassifier.js +42 -6
  13. package/src/agent/errorClassifier.ts +44 -5
  14. package/src/agent/providerFailure.js +1 -1
  15. package/src/agent/providerFailure.ts +7 -1
  16. package/src/agent/toolArgValidator.js +38 -4
  17. package/src/agent/toolArgValidator.ts +39 -4
  18. package/src/agent/toolTurnIntegrity.js +28 -7
  19. package/src/agent/toolTurnIntegrity.ts +25 -6
  20. package/src/agent/workspaceBoundary.js +30 -4
  21. package/src/agent/workspaceBoundary.ts +32 -4
  22. package/src/agentLoop.js +598 -217
  23. package/src/agentLoop.ts +621 -215
  24. package/src/approvalPolicy.js +28 -1
  25. package/src/approvalPolicy.ts +28 -1
  26. package/src/auditLog.js +641 -48
  27. package/src/auditLog.ts +661 -0
  28. package/src/autoUpdate.js +32 -5
  29. package/src/autoUpdate.ts +27 -5
  30. package/src/backgroundTasks.js +328 -0
  31. package/src/backgroundTasks.ts +339 -0
  32. package/src/benchmarks/codingEval.js +558 -0
  33. package/src/benchmarks/codingEval.ts +628 -0
  34. package/src/benchmarks/planCache.js +115 -134
  35. package/src/benchmarks/planCache.ts +163 -0
  36. package/src/browser/browserRuntime.js +52 -0
  37. package/src/browser/browserRuntime.ts +55 -0
  38. package/src/browser/causyneBrowser.js +884 -10
  39. package/src/browser/causyneBrowser.ts +1042 -32
  40. package/src/browser/searchProviders.js +94 -6
  41. package/src/browser/searchProviders.ts +89 -6
  42. package/src/browser/urlPolicy.js +8 -1
  43. package/src/browser/urlPolicy.ts +7 -1
  44. package/src/browser/workspacePathSafety.js +6 -4
  45. package/src/browser/workspacePathSafety.ts +7 -4
  46. package/src/capabilities.js +18 -17
  47. package/src/capabilities.ts +38 -0
  48. package/src/checkpoints.js +1241 -1127
  49. package/src/checkpoints.ts +1377 -0
  50. package/src/cliMode.js +707 -755
  51. package/src/cliMode.ts +780 -0
  52. package/src/codebase/repoMap.js +656 -0
  53. package/src/codebase/repoMap.ts +664 -0
  54. package/src/commands.js +3651 -2514
  55. package/src/commands.ts +3985 -0
  56. package/src/compiledSkills.js +8052 -8054
  57. package/src/compiledSkills.ts +8078 -0
  58. package/src/config.js +103 -1
  59. package/src/config.ts +110 -1
  60. package/src/configVault.js +29 -2
  61. package/src/configVault.ts +26 -2
  62. package/src/contextManager.js +473 -557
  63. package/src/contextManager.ts +599 -0
  64. package/src/continuum/adapters/antigravity.js +8 -3
  65. package/src/continuum/adapters/antigravity.ts +8 -3
  66. package/src/continuum/sanitizer.js +23 -1
  67. package/src/continuum/sanitizer.ts +23 -1
  68. package/src/continuum/ui/continuumPicker.js +0 -2
  69. package/src/continuum/ui/continuumPicker.ts +0 -2
  70. package/src/continuum/ui/continuumPickerView.js +0 -2
  71. package/src/continuum/ui/continuumPickerView.ts +4 -20
  72. package/src/core/contextCompactor.js +88 -7
  73. package/src/core/contextCompactor.ts +87 -8
  74. package/src/creative/liveBridge.js +3 -2
  75. package/src/creative/liveBridge.ts +4 -2
  76. package/src/creative/studioScripts.js +1 -1
  77. package/src/creative/studioScripts.ts +1 -1
  78. package/src/decideTools.js +7 -2
  79. package/src/decideTools.ts +7 -2
  80. package/src/decisionPolicy.js +10 -2
  81. package/src/decisionPolicy.ts +10 -2
  82. package/src/designPalettes.js +72 -84
  83. package/src/designPalettes.ts +111 -0
  84. package/src/devMode.js +2 -2
  85. package/src/devMode.ts +6 -0
  86. package/src/diffReview.js +370 -0
  87. package/src/diffReview.ts +407 -0
  88. package/src/dynamicCatalogue.js +311 -11
  89. package/src/dynamicCatalogue.ts +331 -11
  90. package/src/embodimentSession.js +143 -154
  91. package/src/embodimentSession.ts +173 -0
  92. package/src/engines/installer.js +60 -29
  93. package/src/engines/installer.ts +73 -22
  94. package/src/enterprisePolicy.js +660 -0
  95. package/src/enterprisePolicy.ts +728 -0
  96. package/src/entrypoint.js +514 -268
  97. package/src/entrypoint.ts +607 -0
  98. package/src/gitSnapshot.js +417 -312
  99. package/src/gitSnapshot.ts +500 -0
  100. package/src/headlessCli.js +324 -13
  101. package/src/headlessCli.ts +321 -12
  102. package/src/hooks.js +247 -26
  103. package/src/hooks.ts +236 -26
  104. package/src/ignoreRules.js +297 -0
  105. package/src/ignoreRules.ts +308 -0
  106. package/src/implementationPlan.js +7 -6
  107. package/src/implementationPlan.ts +8 -6
  108. package/src/infra/atomicWriter.js +92 -19
  109. package/src/infra/atomicWriter.ts +108 -19
  110. package/src/launchIntent.js +13 -2
  111. package/src/launchIntent.ts +13 -2
  112. package/src/licensing/entitlements.js +553 -237
  113. package/src/licensing/entitlements.ts +590 -0
  114. package/src/licensing/policy.js +17 -1
  115. package/src/licensing/policy.ts +31 -0
  116. package/src/lsp/lspCatalog.js +398 -0
  117. package/src/lsp/lspCatalog.ts +452 -0
  118. package/src/lsp/lspClient.js +699 -0
  119. package/src/lsp/lspClient.ts +799 -0
  120. package/src/lsp/lspProtocol.js +121 -0
  121. package/src/lsp/lspProtocol.ts +140 -0
  122. package/src/mcp/mcpClient.js +69 -8
  123. package/src/mcp/mcpClient.ts +66 -9
  124. package/src/mcp/mcpRegistry.js +180 -7
  125. package/src/mcp/mcpRegistry.ts +171 -7
  126. package/src/mcp/mcpSecurity.js +6 -7
  127. package/src/mcp/mcpSecurity.ts +7 -6
  128. package/src/memory/episodicStore.js +2 -5
  129. package/src/memory/episodicStore.ts +2 -5
  130. package/src/memory.js +80 -32
  131. package/src/memory.ts +111 -0
  132. package/src/memoryManager.js +151 -143
  133. package/src/memoryManager.ts +182 -0
  134. package/src/modelCatalogue.js +172 -195
  135. package/src/modelCatalogue.ts +201 -0
  136. package/src/modelIds.js +8 -27
  137. package/src/modelIds.ts +33 -0
  138. package/src/modelVariants.js +600 -0
  139. package/src/modelVariants.ts +663 -0
  140. package/src/observer/evidence.js +5 -1
  141. package/src/observer/evidence.ts +5 -1
  142. package/src/osKeychain.js +17 -9
  143. package/src/osKeychain.ts +14 -9
  144. package/src/outputStore.js +210 -156
  145. package/src/outputStore.ts +321 -0
  146. package/src/planCache.js +3 -6
  147. package/src/planCache.ts +3 -6
  148. package/src/plugins/pluginManager.js +689 -461
  149. package/src/plugins/pluginManager.ts +807 -0
  150. package/src/plugins/pluginRunner.js +82 -37
  151. package/src/plugins/pluginRunner.ts +98 -0
  152. package/src/plugins/pluginSkills.js +47 -9
  153. package/src/plugins/pluginSkills.ts +46 -8
  154. package/src/pluginsFactory/discovery.js +0 -1
  155. package/src/pluginsFactory/discovery.ts +0 -1
  156. package/src/pluginsFactory/templates.js +17 -4
  157. package/src/pluginsFactory/templates.ts +17 -4
  158. package/src/prWorkflow.js +337 -0
  159. package/src/prWorkflow.ts +376 -0
  160. package/src/procSignal.js +1 -2
  161. package/src/procSignal.ts +1 -3
  162. package/src/projectInstructions.js +319 -0
  163. package/src/projectInstructions.ts +361 -0
  164. package/src/providers/acp.js +234 -49
  165. package/src/providers/acp.ts +240 -50
  166. package/src/providers/anthropic.js +152 -47
  167. package/src/providers/anthropic.ts +152 -45
  168. package/src/providers/antigravity.js +565 -354
  169. package/src/providers/antigravity.ts +555 -355
  170. package/src/providers/base.js +9 -2
  171. package/src/providers/base.ts +10 -2
  172. package/src/providers/byokHttp.js +127 -17
  173. package/src/providers/byokHttp.ts +175 -18
  174. package/src/providers/byokStream.js +162 -36
  175. package/src/providers/byokStream.ts +162 -55
  176. package/src/providers/dashscope-byok.js +29 -3
  177. package/src/providers/dashscope-byok.ts +30 -2
  178. package/src/providers/deepseek.js +12 -3
  179. package/src/providers/deepseek.ts +12 -3
  180. package/src/providers/factory.js +41 -0
  181. package/src/providers/factory.ts +42 -0
  182. package/src/providers/gemini.js +74 -22
  183. package/src/providers/gemini.ts +78 -26
  184. package/src/providers/moonshot.js +36 -3
  185. package/src/providers/moonshot.ts +32 -3
  186. package/src/providers/ollama.js +267 -21
  187. package/src/providers/ollama.ts +302 -29
  188. package/src/providers/openai-compatible.js +67 -11
  189. package/src/providers/openai-compatible.ts +78 -17
  190. package/src/providers/openai.js +25 -2
  191. package/src/providers/openai.ts +24 -2
  192. package/src/providers/openrouter.js +233 -66
  193. package/src/providers/openrouter.ts +226 -70
  194. package/src/providers/qwen-byok.js +29 -3
  195. package/src/providers/qwen-byok.ts +30 -2
  196. package/src/providers/wireNormalizer.js +66 -0
  197. package/src/providers/wireNormalizer.ts +64 -0
  198. package/src/providers/xai.js +10 -3
  199. package/src/providers/xai.ts +9 -3
  200. package/src/provisioning/capabilityConsent.js +29 -11
  201. package/src/provisioning/capabilityConsent.ts +42 -0
  202. package/src/provisioning/capabilityProvisioner.js +309 -197
  203. package/src/provisioning/capabilityProvisioner.ts +413 -0
  204. package/src/provisioning/capabilityTools.js +31 -17
  205. package/src/provisioning/capabilityTools.ts +43 -0
  206. package/src/provisioning/npmInstall.js +33 -5
  207. package/src/provisioning/npmInstall.ts +33 -5
  208. package/src/reporting.js +328 -326
  209. package/src/reporting.ts +482 -0
  210. package/src/sandbox.js +37 -0
  211. package/src/sandbox.ts +38 -0
  212. package/src/sessionJournal.js +24 -3
  213. package/src/sessionJournal.ts +18 -3
  214. package/src/sessionStore.js +1 -2
  215. package/src/sessionStore.ts +2 -0
  216. package/src/slopDetector.js +202 -265
  217. package/src/slopDetector.ts +279 -0
  218. package/src/smartToolsUse.js +10 -4
  219. package/src/smartToolsUse.ts +10 -4
  220. package/src/stallGuard.js +10 -3
  221. package/src/stallGuard.ts +9 -3
  222. package/src/taskBuffer.js +91 -40
  223. package/src/taskBuffer.ts +94 -0
  224. package/src/tokenTracker.js +78 -11
  225. package/src/tokenTracker.ts +69 -11
  226. package/src/toolPacks.js +5 -0
  227. package/src/toolPacks.ts +5 -0
  228. package/src/tools/applyPatch.js +610 -0
  229. package/src/tools/applyPatch.ts +661 -0
  230. package/src/tools/archive.js +135 -21
  231. package/src/tools/archive.ts +136 -21
  232. package/src/tools/astryxOracle.js +77 -72
  233. package/src/tools/astryxOracle.ts +95 -0
  234. package/src/tools/axSnapshot.js +127 -147
  235. package/src/tools/axSnapshot.ts +174 -0
  236. package/src/tools/backgroundTask.js +86 -0
  237. package/src/tools/backgroundTask.ts +121 -0
  238. package/src/tools/blenderAutomator.js +434 -390
  239. package/src/tools/blenderAutomator.ts +623 -0
  240. package/src/tools/checkSystemSpecs.js +54 -61
  241. package/src/tools/checkSystemSpecs.ts +73 -0
  242. package/src/tools/clipboard.js +42 -31
  243. package/src/tools/clipboard.ts +61 -0
  244. package/src/tools/codeSearchAst.js +359 -91
  245. package/src/tools/codeSearchAst.ts +399 -0
  246. package/src/tools/codeSearcher.js +179 -37
  247. package/src/tools/codeSearcher.ts +188 -33
  248. package/src/tools/codeTools.js +208 -245
  249. package/src/tools/codeTools.ts +271 -0
  250. package/src/tools/codebaseSearch.js +5 -0
  251. package/src/tools/codebaseSearch.ts +5 -0
  252. package/src/tools/desktopAct.js +185 -197
  253. package/src/tools/desktopAct.ts +257 -0
  254. package/src/tools/dynamicLoader.js +4 -40
  255. package/src/tools/dynamicLoader.ts +13 -0
  256. package/src/tools/executeProceduralMedia.js +117 -86
  257. package/src/tools/executeProceduralMedia.ts +135 -0
  258. package/src/tools/fileTracker.js +74 -0
  259. package/src/tools/fileTracker.ts +94 -0
  260. package/src/tools/fsDelete.js +57 -47
  261. package/src/tools/fsDelete.ts +80 -0
  262. package/src/tools/fsEdit.js +192 -74
  263. package/src/tools/fsEdit.ts +201 -72
  264. package/src/tools/fsMove.js +79 -52
  265. package/src/tools/fsMove.ts +108 -0
  266. package/src/tools/fsRead.js +54 -15
  267. package/src/tools/fsRead.ts +55 -15
  268. package/src/tools/fsSearch.js +5 -0
  269. package/src/tools/fsSearch.ts +5 -0
  270. package/src/tools/fsWrite.js +14 -6
  271. package/src/tools/fsWrite.ts +14 -6
  272. package/src/tools/gameAiBehaviorTree.js +74 -91
  273. package/src/tools/gameAiBehaviorTree.ts +219 -0
  274. package/src/tools/gameAnimationRig.js +128 -147
  275. package/src/tools/gameAnimationRig.ts +215 -0
  276. package/src/tools/gameAssetFetcher.js +403 -441
  277. package/src/tools/gameAssetFetcher.ts +477 -0
  278. package/src/tools/gameAssetHarvester.js +171 -200
  279. package/src/tools/gameAssetHarvester.ts +261 -0
  280. package/src/tools/gameAudioSynth.js +223 -259
  281. package/src/tools/gameAudioSynth.ts +255 -0
  282. package/src/tools/gameBuilder.js +100 -91
  283. package/src/tools/gameBuilder.ts +913 -0
  284. package/src/tools/gameCanvasAudit.js +138 -96
  285. package/src/tools/gameCanvasAudit.ts +157 -0
  286. package/src/tools/gameCinematicSequencer.js +93 -111
  287. package/src/tools/gameCinematicSequencer.ts +165 -0
  288. package/src/tools/gameDataForge.js +115 -118
  289. package/src/tools/gameDataForge.ts +151 -0
  290. package/src/tools/gameDialogueTreeGen.js +125 -156
  291. package/src/tools/gameDialogueTreeGen.ts +159 -0
  292. package/src/tools/gameEconomyBalancer.js +150 -153
  293. package/src/tools/gameEconomyBalancer.ts +186 -0
  294. package/src/tools/gameEntitySpawner.js +91 -108
  295. package/src/tools/gameEntitySpawner.ts +209 -0
  296. package/src/tools/gameLoreForge.js +125 -147
  297. package/src/tools/gameLoreForge.ts +162 -0
  298. package/src/tools/gameQuestArcBuilder.js +105 -144
  299. package/src/tools/gameQuestArcBuilder.ts +147 -0
  300. package/src/tools/gameSceneBuilder.js +143 -149
  301. package/src/tools/gameSceneBuilder.ts +196 -0
  302. package/src/tools/gameShaderForge.js +83 -101
  303. package/src/tools/gameShaderForge.ts +181 -0
  304. package/src/tools/gameTilemapGenerator.js +99 -129
  305. package/src/tools/gameTilemapGenerator.ts +158 -0
  306. package/src/tools/gameUiHudBuilder.js +109 -129
  307. package/src/tools/gameUiHudBuilder.ts +300 -0
  308. package/src/tools/gameVfxEmitterGen.js +86 -89
  309. package/src/tools/gameVfxEmitterGen.ts +133 -0
  310. package/src/tools/gameWebRuntimeInspector.js +153 -86
  311. package/src/tools/gameWebRuntimeInspector.ts +167 -0
  312. package/src/tools/generateMediaViaApi.js +53 -12
  313. package/src/tools/generateMediaViaApi.ts +52 -12
  314. package/src/tools/gitExec.js +133 -86
  315. package/src/tools/gitExec.ts +146 -0
  316. package/src/tools/gitWorktree.js +115 -0
  317. package/src/tools/gitWorktree.ts +150 -0
  318. package/src/tools/godotAutomator.js +417 -394
  319. package/src/tools/godotAutomator.ts +530 -0
  320. package/src/tools/lspCodeIntel.js +217 -0
  321. package/src/tools/lspCodeIntel.ts +260 -0
  322. package/src/tools/manageLocalAiDependencies.js +242 -206
  323. package/src/tools/manageLocalAiDependencies.ts +288 -0
  324. package/src/tools/multiEdit.js +16 -76
  325. package/src/tools/multiEdit.ts +20 -77
  326. package/src/tools/osSandbox.js +152 -15
  327. package/src/tools/osSandbox.ts +148 -15
  328. package/src/tools/palmierAutomator.js +147 -95
  329. package/src/tools/palmierAutomator.ts +171 -0
  330. package/src/tools/pdfReader.js +95 -104
  331. package/src/tools/pdfReader.ts +125 -0
  332. package/src/tools/persistentShell.js +267 -144
  333. package/src/tools/persistentShell.ts +314 -0
  334. package/src/tools/pluginManager.js +84 -72
  335. package/src/tools/pluginManager.ts +109 -0
  336. package/src/tools/printer.js +278 -296
  337. package/src/tools/printer.ts +326 -0
  338. package/src/tools/procTerm.js +96 -83
  339. package/src/tools/procTerm.ts +127 -0
  340. package/src/tools/processList.js +45 -48
  341. package/src/tools/processList.ts +73 -0
  342. package/src/tools/registry.js +298 -286
  343. package/src/tools/registry.ts +486 -0
  344. package/src/tools/repoMap.js +46 -0
  345. package/src/tools/repoMap.ts +66 -0
  346. package/src/tools/subagentOrchestrator.js +404 -348
  347. package/src/tools/subagentOrchestrator.ts +457 -0
  348. package/src/tools/sysRun.js +83 -26
  349. package/src/tools/sysRun.ts +80 -26
  350. package/src/tools/toolForge.js +84 -67
  351. package/src/tools/toolForge.ts +102 -0
  352. package/src/tools/toolPathSafety.js +262 -0
  353. package/src/tools/toolPathSafety.ts +308 -0
  354. package/src/tools/toolScanner.js +28 -0
  355. package/src/tools/toolScanner.ts +29 -0
  356. package/src/tools/toolSelfRepair.js +21 -6
  357. package/src/tools/toolSelfRepair.ts +26 -6
  358. package/src/tools/walkerSafety.ts +1 -0
  359. package/src/tools/webFetch.js +5 -2
  360. package/src/tools/webFetch.ts +5 -2
  361. package/src/toolsList.js +5 -0
  362. package/src/toolsList.ts +5 -0
  363. package/src/tui/ask.js +159 -168
  364. package/src/tui/ask.ts +259 -0
  365. package/src/tui/block.js +0 -1
  366. package/src/tui/block.ts +0 -1
  367. package/src/tui/chatRenderer.js +1193 -1441
  368. package/src/tui/chatRenderer.ts +1336 -0
  369. package/src/tui/clipboardImage.js +36 -12
  370. package/src/tui/clipboardImage.ts +39 -13
  371. package/src/tui/clipboardSync.js +34 -9
  372. package/src/tui/clipboardSync.ts +38 -9
  373. package/src/tui/codeProgress.js +0 -1
  374. package/src/tui/codeProgress.ts +0 -1
  375. package/src/tui/completion.js +395 -371
  376. package/src/tui/completion.ts +574 -0
  377. package/src/tui/composerControls.js +113 -19
  378. package/src/tui/composerControls.ts +124 -19
  379. package/src/tui/consoleGuard.js +27 -7
  380. package/src/tui/consoleGuard.ts +29 -7
  381. package/src/tui/dialogs.js +864 -717
  382. package/src/tui/dialogs.ts +984 -0
  383. package/src/tui/diff.js +205 -195
  384. package/src/tui/diff.ts +336 -0
  385. package/src/tui/history.js +143 -108
  386. package/src/tui/history.ts +167 -0
  387. package/src/tui/home.js +165 -161
  388. package/src/tui/home.ts +251 -0
  389. package/src/tui/invocation.js +58 -65
  390. package/src/tui/invocation.ts +117 -0
  391. package/src/tui/keys.js +437 -420
  392. package/src/tui/keys.ts +597 -0
  393. package/src/tui/lineEditor.js +477 -432
  394. package/src/tui/lineEditor.ts +542 -0
  395. package/src/tui/messageActionPlacement.js +0 -1
  396. package/src/tui/messageActionPlacement.ts +0 -1
  397. package/src/tui/messageInteraction.js +0 -2
  398. package/src/tui/messageInteraction.ts +0 -2
  399. package/src/tui/modelPicker.js +0 -3
  400. package/src/tui/modelPicker.ts +3 -6
  401. package/src/tui/observerPicker.js +0 -2
  402. package/src/tui/observerPicker.ts +0 -2
  403. package/src/tui/overlay.js +0 -1
  404. package/src/tui/overlay.ts +0 -1
  405. package/src/tui/prompt.js +1816 -2151
  406. package/src/tui/prompt.ts +1870 -0
  407. package/src/tui/runningLight.js +0 -1
  408. package/src/tui/runningLight.ts +0 -1
  409. package/src/tui/selectList.js +365 -337
  410. package/src/tui/selectList.ts +441 -0
  411. package/src/tui/sessionPicker.js +0 -1
  412. package/src/tui/sessionPicker.ts +0 -1
  413. package/src/tui/sessionPickerView.js +0 -2
  414. package/src/tui/sessionPickerView.ts +4 -21
  415. package/src/tui/sessionSidebar.js +3 -1
  416. package/src/tui/sessionSidebar.ts +4 -1
  417. package/src/tui/setup.js +17 -5
  418. package/src/tui/setup.ts +19 -5
  419. package/src/tui/skillAuthoring.js +0 -2
  420. package/src/tui/skillAuthoring.ts +0 -3
  421. package/src/tui/stageSurface.js +829 -909
  422. package/src/tui/stageSurface.ts +1003 -0
  423. package/src/tui/statusLine.js +7 -4
  424. package/src/tui/statusLine.ts +7 -3
  425. package/src/tui/terminalInputFramer.js +82 -69
  426. package/src/tui/terminalInputFramer.ts +116 -0
  427. package/src/tui/text.js +25 -10
  428. package/src/tui/text.ts +24 -10
  429. package/src/tui/textLayout.js +0 -1
  430. package/src/tui/textLayout.ts +0 -1
  431. package/src/tui/theme.js +245 -250
  432. package/src/tui/theme.ts +441 -0
  433. package/src/tui/thinkingBox.js +0 -1
  434. package/src/tui/thinkingBox.ts +0 -1
  435. package/src/tui/transcript.js +239 -216
  436. package/src/tui/transcript.ts +324 -0
  437. package/src/tui/turnRail.js +53 -54
  438. package/src/tui/turnRail.ts +51 -49
  439. package/src/tui/usageCard.js +0 -2
  440. package/src/tui/usageCard.ts +0 -2
  441. package/src/tui/workspaceSwitch.js +4 -2
  442. package/src/tui/workspaceSwitch.ts +5 -2
  443. package/src/types/contracts.ts +4 -1
  444. package/src/utils/browserOpen.js +107 -0
  445. package/src/utils/browserOpen.ts +129 -0
  446. package/src/utils/cli_ui.js +0 -0
  447. package/src/utils/cli_ui.ts +158 -0
  448. package/src/utils/winSpawn.js +248 -0
  449. package/src/utils/winSpawn.ts +275 -0
  450. package/src/verification/boundedExplorer.js +138 -107
  451. package/src/verification/boundedExplorer.ts +154 -0
  452. package/src/verification/byokSmokeProbe.js +193 -0
  453. package/src/verification/byokSmokeProbe.ts +234 -0
  454. package/src/verification/cliProbe.js +144 -110
  455. package/src/verification/cliProbe.ts +170 -0
  456. package/src/verification/featureMap.js +105 -75
  457. package/src/verification/featureMap.ts +124 -0
  458. package/src/verification/interactivePty.js +195 -100
  459. package/src/verification/interactivePty.ts +333 -0
  460. package/src/verification/propertyProbe.js +109 -101
  461. package/src/verification/propertyProbe.ts +159 -0
  462. package/src/verification/ptyProbe.js +168 -73
  463. package/src/verification/ptyProbe.ts +254 -0
  464. package/src/verification/skillCatalog.js +25 -25
  465. package/src/verification/skillCatalog.ts +66 -0
  466. package/src/verification/statechart.js +140 -127
  467. package/src/verification/statechart.ts +196 -0
  468. package/src/verification/uiRuntime.js +80 -49
  469. package/src/verification/uiRuntime.ts +88 -0
  470. package/src/version.js +37 -32
  471. package/src/version.ts +45 -0
  472. package/src/web/guiLauncher.js +89 -0
  473. package/src/web/guiLauncher.ts +119 -0
  474. package/src/web/skybridgeBrowserBridge.js +256 -0
  475. package/src/web/skybridgeBrowserBridge.ts +285 -0
  476. package/src/web/skybridgeBrowserMcp.js +730 -0
  477. package/src/web/skybridgeBrowserMcp.ts +813 -0
  478. package/src/web/skybridgeClientScript.js +3951 -0
  479. package/src/web/skybridgeClientScript.ts +3952 -0
  480. package/src/web/skybridgeServer.js +2622 -0
  481. package/src/web/skybridgeServer.ts +2787 -0
  482. package/src/web/skybridgeStyles.js +827 -0
  483. package/src/web/skybridgeStyles.ts +828 -0
  484. package/src/web/skybridgeUi.js +472 -0
  485. package/src/web/skybridgeUi.ts +485 -0
  486. package/src/worktreeManager.js +511 -0
  487. package/src/worktreeManager.ts +546 -0
  488. package/src/zeroCostFailover.js +168 -0
  489. package/src/zeroCostFailover.ts +198 -0
  490. package/src/zeroCostRouting.js +391 -0
  491. package/src/zeroCostRouting.ts +437 -0
  492. package/src/agentLoop.d.ts +0 -65
  493. package/src/auditLog.d.ts +0 -3
  494. package/src/checkpoints.d.ts +0 -4
  495. package/src/compiledSkills.d.ts +0 -5
  496. package/src/contextManager.d.ts +0 -14
  497. package/src/designPalettes.d.ts +0 -2
  498. package/src/devMode.d.ts +0 -1
  499. package/src/embodimentSession.d.ts +0 -2
  500. package/src/licensing/entitlements.d.ts +0 -14
  501. package/src/memory.d.ts +0 -13
  502. package/src/memoryManager.d.ts +0 -1
  503. package/src/modelCatalogue.d.ts +0 -6
  504. package/src/modelIds.d.ts +0 -2
  505. package/src/outputStore.d.ts +0 -4
  506. package/src/plugins/pluginManager.d.ts +0 -7
  507. package/src/providers/antigravity.d.ts +0 -19
  508. package/src/provisioning/capabilityProvisioner.d.ts +0 -12
  509. package/src/slopDetector.d.ts +0 -3
  510. package/src/taskBuffer.d.ts +0 -1
  511. package/src/tools/desktopAct.d.ts +0 -10
  512. package/src/tools/registry.d.ts +0 -5
  513. package/src/tui/chatRenderer.d.ts +0 -27
  514. package/src/tui/diff.d.ts +0 -3
  515. package/src/utils/cli_ui.d.ts +0 -19
  516. package/src/utils/paths.d.ts +0 -3
  517. package/src/verification/skillCatalog.d.ts +0 -1
  518. package/src/version.d.ts +0 -1
package/src/acp/client.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { spawn } from 'node:child_process';
1
+ import { spawn, spawnSync } from 'node:child_process';
2
2
  import type { ChildProcessWithoutNullStreams } from 'node:child_process';
3
3
  import fsSync from 'node:fs';
4
4
  import fs from 'node:fs/promises';
@@ -7,16 +7,21 @@ import path from 'node:path';
7
7
  import { isPhysicalPathAllowed } from '../agent/workspaceBoundary.js';
8
8
  import { isCredentialPath } from '../sandbox.js';
9
9
  import { redactProviderSecrets } from '../providers/byokHttp.js';
10
+ import { resolveWindowsSpawnTarget } from '../utils/winSpawn.js';
10
11
  import {
11
12
  ACP_ERROR_CODES,
12
13
  ACP_METHODS,
13
14
  ACP_PROTOCOL_VERSION,
14
15
  extractAcpSessionModels,
16
+ extractAcpSessionVariants,
15
17
  isJsonRpcRequest,
16
- isJsonRpcResponse
18
+ isJsonRpcResponse,
19
+ isJsonRpcNotification,
20
+ normalizeAcpMcpServers
17
21
  } from './protocol.js';
18
22
  import type {
19
23
  AcpDiscoveredSessionModels,
24
+ AcpDiscoveredVariantOption,
20
25
  ContentBlock,
21
26
  InitializeRequest,
22
27
  InitializeResult,
@@ -89,6 +94,7 @@ export class AcpClient {
89
94
  private stderrTail = '';
90
95
  private readonly pending = new Map<string | number, PendingRequest>();
91
96
  private readonly openToolCalls = new Map<string, number>();
97
+ private activePermissionRequests = 0;
92
98
  private nextId = 1;
93
99
  private closed = false;
94
100
  private exitError: Error | null = null;
@@ -99,6 +105,8 @@ export class AcpClient {
99
105
  modelLabels: {},
100
106
  usesConfigOption: false
101
107
  };
108
+ private readonly sessionVariants = new Map<string, AcpDiscoveredVariantOption>();
109
+ private latestSessionVariants: AcpDiscoveredVariantOption | null = null;
102
110
 
103
111
  constructor(options: AcpClientOptions) {
104
112
  this.options = options;
@@ -143,6 +151,7 @@ export class AcpClient {
143
151
  configOptionId: state.configOptionId
144
152
  };
145
153
  }
154
+ if (sessionId !== undefined) return { availableModels: [], modelLabels: {}, usesConfigOption: false };
146
155
  return {
147
156
  currentModelId: this.latestSessionModels.currentModelId,
148
157
  availableModels: [...this.latestSessionModels.availableModels],
@@ -152,9 +161,39 @@ export class AcpClient {
152
161
  };
153
162
  }
154
163
 
164
+ getSessionVariants(sessionId?: string): AcpDiscoveredVariantOption | null {
165
+ const src = sessionId ? (this.sessionVariants.get(sessionId) ?? null) : this.latestSessionVariants;
166
+ if (!src) return null;
167
+ return {
168
+ configOptionId: src.configOptionId,
169
+ ...(src.currentValue ? { currentValue: src.currentValue } : {}),
170
+ options: src.options.map((o) => ({ ...o }))
171
+ };
172
+ }
173
+
155
174
  private recordSessionModels(sessionId: string, payload: unknown): void {
175
+ const extractedVariant = extractAcpSessionVariants(payload);
176
+ if (extractedVariant) {
177
+ const existingVar = this.sessionVariants.get(sessionId);
178
+ const mergedVar: AcpDiscoveredVariantOption = {
179
+ configOptionId: extractedVariant.configOptionId || existingVar?.configOptionId || 'thought_level',
180
+ ...(extractedVariant.currentValue
181
+ ? { currentValue: extractedVariant.currentValue }
182
+ : (existingVar?.currentValue ? { currentValue: existingVar.currentValue } : {})),
183
+ options: extractedVariant.options.length > 0
184
+ ? extractedVariant.options
185
+ : (existingVar?.options ?? [])
186
+ };
187
+ if (!this.sessionVariants.has(sessionId) && this.sessionVariants.size >= MAX_TRACKED_SESSIONS) {
188
+ const oldest = this.sessionVariants.keys().next().value;
189
+ if (oldest !== undefined) this.sessionVariants.delete(oldest);
190
+ }
191
+ this.sessionVariants.set(sessionId, mergedVar);
192
+ this.latestSessionVariants = mergedVar;
193
+ }
194
+
156
195
  const extracted = extractAcpSessionModels(payload);
157
- if (extracted.availableModels.length === 0 && !extracted.currentModelId) {
196
+ if (extracted.availableModels.length === 0 && !extracted.currentModelId && !extracted.usesConfigOption) {
158
197
  return;
159
198
  }
160
199
  const existing = this.sessionModels.get(sessionId);
@@ -167,6 +206,9 @@ export class AcpClient {
167
206
  usesConfigOption: extracted.usesConfigOption || Boolean(existing?.usesConfigOption),
168
207
  configOptionId: extracted.configOptionId ?? existing?.configOptionId
169
208
  };
209
+ for (const id of Object.keys(merged.modelLabels)) {
210
+ if (!merged.availableModels.includes(id)) delete merged.modelLabels[id];
211
+ }
170
212
  if (!this.sessionModels.has(sessionId) && this.sessionModels.size >= MAX_TRACKED_SESSIONS) {
171
213
  const oldest = this.sessionModels.keys().next().value;
172
214
  if (oldest !== undefined) this.sessionModels.delete(oldest);
@@ -177,35 +219,37 @@ export class AcpClient {
177
219
 
178
220
  async start(signal?: AbortSignal): Promise<InitializeResult> {
179
221
  if (signal?.aborted) throw createAbortError();
222
+ if (this.closed) throw new Error('ACP client is closed');
180
223
  if (this.child) throw new Error('client already started');
181
224
  const args = this.options.args ?? [];
182
- let childEnv: NodeJS.ProcessEnv;
183
- if (this.options.env) {
184
- childEnv = this.options.env;
185
- } else {
186
- childEnv = { ...process.env };
187
- delete childEnv.CAUSYNE_VAULT_KEY;
188
- delete childEnv.CAUSYNE_DEV_SECRET;
189
- }
190
- const child = spawn(this.options.command, args, {
225
+ const childEnv: NodeJS.ProcessEnv = this.options.env ? { ...this.options.env } : { ...process.env };
226
+ delete childEnv.CAUSYNE_VAULT_KEY;
227
+ delete childEnv.CAUSYNE_DEV_SECRET;
228
+ delete childEnv.CAUSYNE_DEV_TOKEN;
229
+ const isPosix = process.platform !== 'win32';
230
+ const spawnTarget = resolveWindowsSpawnTarget(this.options.command, args, { env: childEnv });
231
+ const child = spawn(spawnTarget.command, spawnTarget.args, {
191
232
  cwd: this.options.cwd,
192
233
  env: childEnv,
193
234
  stdio: ['pipe', 'pipe', 'pipe'],
235
+ detached: isPosix,
194
236
  windowsHide: true
195
237
  });
196
238
  this.child = child;
239
+ child.stdin.on('error', (error) => {
240
+ if (!this.closed) this.failAll(error);
241
+ });
197
242
 
198
243
  child.stdout.setEncoding('utf8');
199
244
  child.stdout.on('data', (chunk: string) => {
200
- if (this.closed) return;
245
+ if (this.closed || this.exitError) return;
201
246
  this.buffer += chunk;
202
- if (this.buffer.length > MAX_JSONRPC_BUFFER_BYTES) {
247
+ this.notifyPendingActivity();
248
+ void this.drain();
249
+ if (Buffer.byteLength(this.buffer, 'utf8') > MAX_JSONRPC_BUFFER_BYTES) {
203
250
  this.buffer = '';
204
251
  this.failAll(new Error('agent output frame exceeded maximum size'));
205
- return;
206
252
  }
207
- this.notifyPendingActivity();
208
- void this.drain();
209
253
  });
210
254
  child.stderr.setEncoding('utf8');
211
255
  child.stderr.on('data', (chunk: string) => {
@@ -213,7 +257,7 @@ export class AcpClient {
213
257
  this.notifyPendingActivity();
214
258
  });
215
259
  child.on('error', (error) => this.failAll(new Error(`agent process failed: ${error.message}`)));
216
- child.on('exit', (code, exitSignal) => {
260
+ child.on('close', (code, exitSignal) => {
217
261
  const cleanTail = redactProviderSecrets(this.stderrTail).trim();
218
262
  const detail = cleanTail || `exit code ${code ?? 'null'}${exitSignal ? ` signal ${exitSignal}` : ''}`;
219
263
  this.failAll(new Error(`agent process exited: ${detail}`));
@@ -227,14 +271,25 @@ export class AcpClient {
227
271
  clientCapabilities: {
228
272
  fs: { readTextFile: hasFsRead, writeTextFile: hasFsWrite },
229
273
  terminal: false,
230
- session: { notices: true }
274
+ _meta: { session: { notices: true } }
231
275
  },
232
276
  clientInfo: { name: 'Causyne Agent', version: this.options.clientVersion ?? '0.0.0' }
233
277
  };
234
278
 
235
- const result = await this.request<InitializeResult>(ACP_METHODS.INITIALIZE, params, 30_000, signal);
236
- this.initResult = result;
237
- return result;
279
+ try {
280
+ const result = await this.request<InitializeResult>(ACP_METHODS.INITIALIZE, params, 30_000, signal);
281
+ if (!result || result.protocolVersion !== ACP_PROTOCOL_VERSION) {
282
+ throw new Error('ACP peer negotiated an unsupported protocol version');
283
+ }
284
+ if (result.agentCapabilities !== undefined && (result.agentCapabilities === null || typeof result.agentCapabilities !== 'object' || Array.isArray(result.agentCapabilities))) {
285
+ throw new Error('ACP peer returned malformed agent capabilities');
286
+ }
287
+ this.initResult = result;
288
+ return result;
289
+ } catch (err) {
290
+ await this.close().catch(() => {});
291
+ throw err;
292
+ }
238
293
  }
239
294
 
240
295
  async newSession(cwd: string, mcpServers: unknown[] = [], signal?: AbortSignal): Promise<string> {
@@ -243,9 +298,9 @@ export class AcpClient {
243
298
  }
244
299
  const result = await this.request<{ sessionId?: unknown }>(ACP_METHODS.NEW_SESSION, {
245
300
  cwd,
246
- mcpServers
301
+ mcpServers: normalizeAcpMcpServers(mcpServers)
247
302
  }, 30_000, signal);
248
- if (!result || typeof result.sessionId !== 'string' || !result.sessionId) {
303
+ if (!result || typeof result.sessionId !== 'string' || !result.sessionId.trim() || result.sessionId.includes('\0')) {
249
304
  throw new Error('agent did not return a session id');
250
305
  }
251
306
  this.recordSessionModels(result.sessionId, result);
@@ -263,15 +318,15 @@ export class AcpClient {
263
318
  }
264
319
 
265
320
  async setSessionModel(sessionId: string, modelId: string, signal?: AbortSignal): Promise<void> {
266
- if (typeof sessionId !== 'string' || !sessionId.trim() || typeof modelId !== 'string' || !modelId.trim()) {
321
+ if (typeof sessionId !== 'string' || !sessionId.trim() || sessionId.includes('\0') || typeof modelId !== 'string' || !modelId.trim() || modelId.includes('\0')) {
267
322
  throw new Error('setSessionModel requires non-empty sessionId and modelId');
268
323
  }
269
- const state = this.sessionModels.get(sessionId) ?? this.latestSessionModels;
324
+ const state = this.getSessionModels(sessionId);
270
325
  try {
271
326
  const res = await this.request<unknown>(ACP_METHODS.SET_MODEL, {
272
327
  sessionId,
273
328
  modelId
274
- }, 5_000, signal);
329
+ }, 20_000, signal);
275
330
  this.recordSessionModels(sessionId, res);
276
331
  const updated = this.sessionModels.get(sessionId);
277
332
  if (updated) {
@@ -288,7 +343,7 @@ export class AcpClient {
288
343
  sessionId,
289
344
  configId: state.configOptionId || 'model',
290
345
  value: modelId
291
- }, 5_000, signal);
346
+ }, 20_000, signal);
292
347
  this.recordSessionModels(sessionId, res);
293
348
  return;
294
349
  }
@@ -296,8 +351,29 @@ export class AcpClient {
296
351
  }
297
352
  }
298
353
 
354
+ async setSessionConfigOption(sessionId: string, configId: string, value: string, signal?: AbortSignal): Promise<void> {
355
+ if (
356
+ typeof sessionId !== 'string' || !sessionId.trim() || sessionId.includes('\0')
357
+ || typeof configId !== 'string' || !configId.trim() || configId.includes('\0')
358
+ || typeof value !== 'string' || !value.trim() || value.includes('\0')
359
+ ) {
360
+ throw new Error('setSessionConfigOption requires non-empty sessionId, configId, and value');
361
+ }
362
+ const res = await this.request<unknown>(ACP_METHODS.SET_CONFIG_OPTION, {
363
+ sessionId,
364
+ configId: configId.trim(),
365
+ value: value.trim()
366
+ }, 20_000, signal);
367
+ this.recordSessionModels(sessionId, res);
368
+ const tracked = this.sessionVariants.get(sessionId);
369
+ if (tracked && tracked.configOptionId === configId.trim()) {
370
+ tracked.currentValue = value.trim();
371
+ this.latestSessionVariants = tracked;
372
+ }
373
+ }
374
+
299
375
  async setSessionMode(sessionId: string, modeId: string, signal?: AbortSignal): Promise<void> {
300
- if (typeof sessionId !== 'string' || !sessionId.trim() || typeof modeId !== 'string' || !modeId.trim()) {
376
+ if (typeof sessionId !== 'string' || !sessionId.trim() || sessionId.includes('\0') || typeof modeId !== 'string' || !modeId.trim() || modeId.includes('\0')) {
301
377
  throw new Error('setSessionMode requires non-empty sessionId and modeId');
302
378
  }
303
379
  await this.request<void>(ACP_METHODS.SET_MODE, {
@@ -307,9 +383,12 @@ export class AcpClient {
307
383
  }
308
384
 
309
385
  async loadSession(sessionId: string, cwd?: string, signal?: AbortSignal): Promise<unknown> {
310
- if (typeof sessionId !== 'string' || !sessionId.trim()) {
386
+ if (typeof sessionId !== 'string' || !sessionId.trim() || sessionId.includes('\0')) {
311
387
  throw new Error('loadSession requires a non-empty sessionId');
312
388
  }
389
+ if (cwd !== undefined && (typeof cwd !== 'string' || !cwd.trim() || cwd.includes('\0'))) {
390
+ throw new Error('loadSession requires a valid cwd');
391
+ }
313
392
  const res = await this.request<unknown>(ACP_METHODS.LOAD, {
314
393
  sessionId,
315
394
  cwd: cwd || this.options.cwd
@@ -320,6 +399,12 @@ export class AcpClient {
320
399
 
321
400
  async prompt(sessionId: string, input: string | ContentBlock[], signal?: AbortSignal): Promise<AcpPromptResult> {
322
401
  if (signal?.aborted) throw createAbortError();
402
+ if (typeof sessionId !== 'string' || !sessionId.trim() || sessionId.includes('\0')) throw new Error('ACP prompt requires a valid session ID');
403
+ if (this.promptActive) throw new Error('ACP client already has an active prompt');
404
+ this.promptActive = sessionId;
405
+ this.promptGeneration++;
406
+ // Diagnostic text from an earlier turn must not cancel this prompt.
407
+ this.stderrTail = '';
323
408
  const blocks: ContentBlock[] = typeof input === 'string' ? [{ type: 'text', text: input }] : input;
324
409
  let collected = '';
325
410
  const collector = (update: SessionUpdate): void => {
@@ -367,14 +452,18 @@ export class AcpClient {
367
452
  sessionId,
368
453
  inactivityTimeoutMs
369
454
  });
455
+ if (!response || !['end_turn', 'max_tokens', 'max_turn_requests', 'refusal', 'cancelled'].includes(response.stopReason)) {
456
+ throw new Error('ACP peer returned an invalid prompt stop reason');
457
+ }
370
458
  return {
371
- stopReason: response?.stopReason ?? 'end_turn',
459
+ stopReason: response.stopReason,
372
460
  ...(response?.usage ? { usage: response.usage } : {}),
373
461
  text: collected
374
462
  };
375
463
  } finally {
376
464
  signal?.removeEventListener('abort', onAbort);
377
465
  this.updateListeners.delete(listener);
466
+ this.promptActive = null;
378
467
  this.clearOpenToolCalls(sessionId);
379
468
  }
380
469
  }
@@ -395,7 +484,7 @@ export class AcpClient {
395
484
  const status = typeof record.status === 'string' ? record.status : '';
396
485
  if (status === 'completed' || status === 'failed' || status === 'cancelled') {
397
486
  this.openToolCalls.delete(key);
398
- } else if (record.sessionUpdate === 'tool_call' || status === 'pending' || status === 'in_progress') {
487
+ } else if (record.sessionUpdate === 'tool_call' || status === 'pending' || status === 'in_progress' || status === 'running') {
399
488
  if (!this.openToolCalls.has(key)) {
400
489
  if (this.openToolCalls.size >= MAX_OPEN_TOOL_CALLS) {
401
490
  const oldest = this.openToolCalls.keys().next().value;
@@ -413,11 +502,12 @@ export class AcpClient {
413
502
  }
414
503
  }
415
504
 
416
- private hasOpenToolCall(sessionId?: string): boolean {
505
+ private hasOpenToolCall(sessionId?: string, maxSilenceMs = 10 * 60 * 1000): boolean {
417
506
  if (!sessionId || !this.child || this.child.exitCode !== null || this.closed) return false;
418
507
  const prefix = `${sessionId}\u0000`;
419
- for (const key of this.openToolCalls.keys()) {
420
- if (key.startsWith(prefix)) return true;
508
+ const now = Date.now();
509
+ for (const [key, startedAt] of this.openToolCalls.entries()) {
510
+ if (key.startsWith(prefix) && now - startedAt < maxSilenceMs) return true;
421
511
  }
422
512
  return false;
423
513
  }
@@ -449,8 +539,23 @@ export class AcpClient {
449
539
  clearTimeout(timer);
450
540
  resolve();
451
541
  };
542
+ const terminateTree = (sig: 'SIGTERM' | 'SIGKILL'): void => {
543
+ const pid = child.pid;
544
+ if (process.platform === 'win32' && pid) {
545
+ try {
546
+ spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore', timeout: 2000, windowsHide: true });
547
+ return;
548
+ } catch { /* fallback to child.kill */ }
549
+ } else if (process.platform !== 'win32' && pid) {
550
+ try {
551
+ process.kill(-pid, sig);
552
+ return;
553
+ } catch { /* fallback to direct child.kill */ }
554
+ }
555
+ try { child.kill(sig); } catch { /* ignore */ }
556
+ };
452
557
  const timer = setTimeout(() => {
453
- try { child.kill('SIGKILL'); } catch { /* ignore */ }
558
+ terminateTree('SIGKILL');
454
559
  done();
455
560
  }, 250);
456
561
  if (typeof timer.unref === 'function') timer.unref();
@@ -463,33 +568,45 @@ export class AcpClient {
463
568
  // ignore stream destroy errors
464
569
  }
465
570
  try {
466
- child.kill('SIGTERM');
571
+ terminateTree('SIGTERM');
467
572
  } catch {
468
573
  done();
469
574
  }
470
575
  });
471
576
  }
472
577
 
578
+ private promptActive: string | null = null;
579
+ private promptGeneration = 0;
473
580
  private readonly updateListeners = new Set<(sessionId: string, update: SessionUpdate) => void>();
474
581
 
475
582
  private write(message: JsonRpcRequest<unknown> | JsonRpcResponse | JsonRpcNotification<unknown>): void {
476
- if (!this.child || this.closed) return;
583
+ if (!this.child || this.closed || this.exitError) return;
477
584
  try {
478
585
  this.child.stdin.write(`${JSON.stringify(message)}\n`);
479
- } catch {
480
- // A dead pipe surfaces through the exit handler.
586
+ } catch (error) {
587
+ this.failAll(error instanceof Error ? error : new Error(String(error)));
481
588
  }
482
589
  }
483
590
 
484
- private async drain(): Promise<void> {
591
+ private drain(): void {
485
592
  if (this.draining) return;
486
593
  this.draining = true;
487
594
  try {
488
595
  let index = this.buffer.indexOf('\n');
489
- while (index >= 0 && !this.closed) {
490
- const line = this.buffer.slice(0, index).replace(/^\uFEFF/, '').trim();
596
+ while (index >= 0 && !this.closed && !this.exitError) {
597
+ const rawLine = this.buffer.slice(0, index);
598
+ if (Buffer.byteLength(rawLine, 'utf8') > MAX_JSONRPC_BUFFER_BYTES) {
599
+ this.buffer = '';
600
+ this.failAll(new Error('agent output frame exceeded maximum size'));
601
+ break;
602
+ }
603
+ const line = rawLine.replace(/^\uFEFF/, '').trim();
491
604
  this.buffer = this.buffer.slice(index + 1);
492
- if (line) await this.handleLine(line);
605
+ if (line) {
606
+ try { this.handleLine(line); } catch (error) {
607
+ this.failAll(error instanceof Error ? error : new Error(String(error)));
608
+ }
609
+ }
493
610
  index = this.buffer.indexOf('\n');
494
611
  }
495
612
  } finally {
@@ -497,7 +614,7 @@ export class AcpClient {
497
614
  }
498
615
  }
499
616
 
500
- private async handleLine(line: string): Promise<void> {
617
+ private handleLine(line: string): void {
501
618
  let parsed: unknown;
502
619
  try {
503
620
  parsed = JSON.parse(line);
@@ -509,12 +626,15 @@ export class AcpClient {
509
626
  return;
510
627
  }
511
628
  if (isJsonRpcRequest(parsed)) {
512
- await this.handleServerRequest(parsed);
629
+ // Dispatch server requests concurrently so waiting on HITL permission or
630
+ // host I/O never head-of-line blocks subsequent updates or responses.
631
+ void this.handleServerRequest(parsed).catch(() => {});
513
632
  return;
514
633
  }
515
- const method = (parsed as { method?: unknown }).method;
634
+ if (!isJsonRpcNotification(parsed)) return;
635
+ const method = parsed.method;
516
636
  if (method === ACP_METHODS.UPDATE) {
517
- const params = (parsed as { params?: SessionNotification }).params;
637
+ const params = parsed.params as unknown as SessionNotification | undefined;
518
638
  if (
519
639
  params &&
520
640
  typeof params.sessionId === 'string' &&
@@ -522,6 +642,7 @@ export class AcpClient {
522
642
  typeof params.update === 'object' &&
523
643
  !Array.isArray(params.update)
524
644
  ) {
645
+ if (this.promptActive && params.sessionId !== this.promptActive) return;
525
646
  this.recordSessionModels(params.sessionId, params.update);
526
647
  this.trackToolCall(params.sessionId, params.update);
527
648
  for (const listener of [...this.updateListeners]) {
@@ -533,6 +654,11 @@ export class AcpClient {
533
654
  }
534
655
 
535
656
  private async handleServerRequest(request: JsonRpcRequest): Promise<void> {
657
+ if ((request.method === ACP_METHODS.READ_TEXT_FILE || request.method === ACP_METHODS.WRITE_TEXT_FILE)
658
+ && (!this.promptActive || (request.params as { sessionId?: unknown } | undefined)?.sessionId !== this.promptActive)) {
659
+ this.write({ jsonrpc: '2.0', id: request.id, error: { code: ACP_ERROR_CODES.INVALID_REQUEST, message: 'Host file request does not belong to the active session' } });
660
+ return;
661
+ }
536
662
  if (this.options.allowHostTools === false
537
663
  && (request.method === ACP_METHODS.READ_TEXT_FILE || request.method === ACP_METHODS.WRITE_TEXT_FILE)) {
538
664
  this.write({ jsonrpc: '2.0', id: request.id,
@@ -541,7 +667,7 @@ export class AcpClient {
541
667
  }
542
668
  if (request.method === ACP_METHODS.REQUEST_PERMISSION) {
543
669
  const handler = this.options.permissionHandler;
544
- if (!handler) {
670
+ if (!handler || !this.promptActive || (request.params as { sessionId?: unknown } | undefined)?.sessionId !== this.promptActive) {
545
671
  this.write({
546
672
  jsonrpc: '2.0',
547
673
  id: request.id,
@@ -549,15 +675,30 @@ export class AcpClient {
549
675
  });
550
676
  return;
551
677
  }
678
+ this.activePermissionRequests++;
552
679
  try {
553
- const rawOutcome = await handler(request.params as unknown as RequestPermissionRequest);
680
+ const permission = request.params as unknown as RequestPermissionRequest;
681
+ const activePrompt = this.promptActive;
682
+ const generation = this.promptGeneration;
683
+ const options = Array.isArray(permission.options) ? permission.options : [];
684
+ if (!permission.toolCall || typeof permission.toolCall.toolCallId !== 'string' || !permission.toolCall.toolCallId.trim() || !options.length) {
685
+ throw new Error('Invalid peer permission request');
686
+ }
687
+ const optionIds = new Set(options.map(option => option?.optionId));
688
+ if (optionIds.size !== options.length || options.some(option => !option || typeof option.optionId !== 'string' || !option.optionId.trim() || typeof option.name !== 'string' || !['allow_once', 'allow_always', 'reject_once', 'reject_always'].includes(option.kind))) {
689
+ throw new Error('Invalid peer permission choices');
690
+ }
691
+ const rawOutcome = await handler(permission);
554
692
  const validOutcome: RequestPermissionResponse['outcome'] =
555
- rawOutcome && typeof rawOutcome === 'object' && rawOutcome.outcome === 'selected' && typeof rawOutcome.optionId === 'string'
693
+ activePrompt !== null && this.promptActive === activePrompt && this.promptGeneration === generation && !this.closed && !this.exitError && rawOutcome && typeof rawOutcome === 'object' && rawOutcome.outcome === 'selected' && typeof rawOutcome.optionId === 'string' && optionIds.has(rawOutcome.optionId)
556
694
  ? { outcome: 'selected', optionId: rawOutcome.optionId }
557
695
  : { outcome: 'cancelled' };
558
696
  this.write({ jsonrpc: '2.0', id: request.id, result: { outcome: validOutcome } });
559
697
  } catch {
560
698
  this.write({ jsonrpc: '2.0', id: request.id, result: { outcome: { outcome: 'cancelled' } } });
699
+ } finally {
700
+ this.activePermissionRequests = Math.max(0, this.activePermissionRequests - 1);
701
+ this.notifyPendingActivity();
561
702
  }
562
703
  return;
563
704
  }
@@ -565,7 +706,9 @@ export class AcpClient {
565
706
  if (request.method === ACP_METHODS.READ_TEXT_FILE) {
566
707
  const params = request.params as unknown as ReadTextFileRequest | undefined;
567
708
  const targetPath = params?.path;
568
- if (!targetPath || typeof targetPath !== 'string') {
709
+ const generation = this.promptGeneration;
710
+ const activePrompt = this.promptActive;
711
+ if (!targetPath || typeof targetPath !== 'string' || !targetPath.trim() || targetPath.includes('\0')) {
569
712
  this.write({
570
713
  jsonrpc: '2.0',
571
714
  id: request.id,
@@ -574,6 +717,11 @@ export class AcpClient {
574
717
  return;
575
718
  }
576
719
 
720
+ if ([params?.line, params?.limit].some(value => value !== undefined && (!Number.isSafeInteger(value) || value < 1)) || (params?.limit !== undefined && !Number.isSafeInteger((params.line ?? 1) + (params.limit - 1)))) {
721
+ this.write({ jsonrpc: '2.0', id: request.id, error: { code: ACP_ERROR_CODES.INVALID_PARAMS, message: 'Invalid file line range' } });
722
+ return;
723
+ }
724
+
577
725
  try {
578
726
  let content: string;
579
727
  if (this.options.fsReadHandler) {
@@ -613,6 +761,15 @@ export class AcpClient {
613
761
  content = rawContent;
614
762
  }
615
763
  }
764
+ if (typeof content !== 'string') {
765
+ throw new Error('Host file read returned non-text content');
766
+ }
767
+ if (Buffer.byteLength(content, 'utf8') > MAX_HOST_FILE_BYTES) {
768
+ throw new Error(`File exceeds maximum readable size (${MAX_HOST_FILE_BYTES} bytes)`);
769
+ }
770
+ if (this.closed || this.exitError || this.promptActive !== activePrompt || this.promptGeneration !== generation) {
771
+ throw new Error('Host file read belongs to a retired prompt');
772
+ }
616
773
  this.write({
617
774
  jsonrpc: '2.0',
618
775
  id: request.id,
@@ -633,7 +790,14 @@ export class AcpClient {
633
790
  const params = request.params as unknown as WriteTextFileRequest | undefined;
634
791
  const targetPath = params?.path;
635
792
  const content = params?.content;
636
- if (!targetPath || typeof targetPath !== 'string' || typeof content !== 'string') {
793
+ const generation = this.promptGeneration;
794
+ const activePrompt = this.promptActive;
795
+ const assertActive = (): void => {
796
+ if (this.closed || this.exitError || this.promptActive !== activePrompt || this.promptGeneration !== generation) {
797
+ throw new Error('Host file write belongs to a retired prompt');
798
+ }
799
+ };
800
+ if (!targetPath || typeof targetPath !== 'string' || !targetPath.trim() || targetPath.includes('\0') || typeof content !== 'string') {
637
801
  this.write({
638
802
  jsonrpc: '2.0',
639
803
  id: request.id,
@@ -643,15 +807,15 @@ export class AcpClient {
643
807
  }
644
808
 
645
809
  try {
810
+ if (Buffer.byteLength(content, 'utf8') > MAX_HOST_FILE_BYTES) {
811
+ throw new Error(`File content exceeds maximum writable size (${MAX_HOST_FILE_BYTES} bytes)`);
812
+ }
646
813
  if (this.options.fsWriteHandler) {
647
814
  await this.options.fsWriteHandler(targetPath, content);
648
815
  } else {
649
816
  if (targetPath.includes('\0')) {
650
817
  throw new Error('File path contains invalid NUL byte');
651
818
  }
652
- if (Buffer.byteLength(content, 'utf8') > MAX_HOST_FILE_BYTES) {
653
- throw new Error(`File content exceeds maximum writable size (${MAX_HOST_FILE_BYTES} bytes)`);
654
- }
655
819
  const resolved = path.resolve(this.options.cwd, targetPath);
656
820
  if (!isPhysicalPathAllowed(resolved, [this.options.cwd], false)) {
657
821
  throw new Error('File path is outside the allowed workspace');
@@ -668,9 +832,12 @@ export class AcpClient {
668
832
  const code = typeof statErr === 'object' && statErr !== null && 'code' in statErr ? String(statErr.code) : '';
669
833
  if (code !== 'ENOENT') throw statErr;
670
834
  }
835
+ assertActive();
671
836
  await fs.mkdir(path.dirname(resolved), { recursive: true });
837
+ assertActive();
672
838
  await fs.writeFile(resolved, content, 'utf8');
673
839
  }
840
+ assertActive();
674
841
  this.write({
675
842
  jsonrpc: '2.0',
676
843
  id: request.id,
@@ -704,7 +871,30 @@ export class AcpClient {
704
871
  pending.cleanup?.();
705
872
  this.pending.delete(response.id);
706
873
  if (response.error) {
707
- const err = new Error(`${pending.method} failed: ${response.error.message}`);
874
+ let detail = redactProviderSecrets(String(response.error.message || 'Unknown ACP error')).trim();
875
+ const rawData = response.error.data;
876
+ if (rawData !== undefined && rawData !== null) {
877
+ const dataText = typeof rawData === 'string'
878
+ ? rawData.trim()
879
+ : (typeof rawData === 'object' && 'details' in rawData && typeof (rawData as { details?: unknown }).details === 'string'
880
+ ? (rawData as { details: string }).details.trim()
881
+ : (typeof rawData === 'object' && 'message' in rawData && typeof (rawData as { message?: unknown }).message === 'string'
882
+ ? (rawData as { message: string }).message.trim()
883
+ : (() => { try { return JSON.stringify(rawData); } catch { return ''; } })()));
884
+ const cleanData = redactProviderSecrets(dataText).slice(0, 600).trim();
885
+ if (cleanData && !detail.includes(cleanData)) {
886
+ detail = `${detail} (${cleanData})`;
887
+ }
888
+ }
889
+ const isGenericInternal = response.error.code === ACP_ERROR_CODES.INTERNAL_ERROR || /^internal error$/i.test(String(response.error.message || '').trim());
890
+ if (isGenericInternal && this.stderrTail.trim()) {
891
+ const tailLines = redactProviderSecrets(this.stderrTail).split(/\r?\n/).map(l => l.trim()).filter(Boolean);
892
+ const stderrSummary = tailLines.slice(-4).join(' | ').slice(0, 500);
893
+ if (stderrSummary && !detail.includes(stderrSummary)) {
894
+ detail = `${detail} — stderr: ${stderrSummary}`;
895
+ }
896
+ }
897
+ const err = new Error(`${pending.method} failed: ${detail}`);
708
898
  (err as unknown as { code?: number }).code = response.error.code;
709
899
  (err as unknown as { data?: unknown }).data = response.error.data;
710
900
  pending.reject(err);
@@ -719,33 +909,24 @@ export class AcpClient {
719
909
  }
720
910
  }
721
911
 
722
- inspectPeerDiagnostics(sessionId?: string, sinceEpochMs?: number): string | null {
912
+ inspectPeerDiagnostics(sessionId?: string, sinceEpochMs?: number, terminalOnly = false): string | null {
723
913
  if (this.exitError) {
724
- return this.exitError.message;
914
+ return redactProviderSecrets(this.exitError.message);
725
915
  }
726
916
  if (this.child && this.child.exitCode !== null) {
727
- const detail = this.stderrTail.trim() || `exit code ${this.child.exitCode}`;
917
+ const detail = redactProviderSecrets(this.stderrTail).trim() || `exit code ${this.child.exitCode}`;
728
918
  return `agent process exited: ${detail}`;
729
919
  }
730
920
  if (this.stderrTail) {
731
- const fatalPatterns = [
732
- /free usage limit reached/i,
733
- /ai_apicallerror/i,
734
- /ai_retryerror/i,
735
- /rate limit/i,
736
- /quota exceeded/i,
737
- /insufficient_quota/i,
738
- /unauthorized/i,
739
- /authentication failed/i,
740
- /invalid api key/i
741
- ];
742
- for (const pat of fatalPatterns) {
743
- if (pat.test(this.stderrTail)) {
744
- const match = this.stderrTail.split('\n').find(l => pat.test(l));
745
- if (match) return redactProviderSecrets(match).trim();
746
- }
747
- }
921
+ const terminal = /free usage limit reached|insufficient_quota|quota exceeded|invalid api key|authentication failed|credit balance is too low|unauthorized/i;
922
+ const diagnostic = /ai_apicallerror|ai_retryerror|rate limit|cannot connect to api|socket connection was closed/i;
923
+ const lines = this.stderrTail.split('\n').reverse();
924
+ const match = lines.find(line => terminal.test(line) || (!terminalOnly && diagnostic.test(line)));
925
+ if (match) return redactProviderSecrets(match).trim();
748
926
  }
927
+ // A shared log may contain recoverable or stale errors. Only inspect it
928
+ // for diagnostics after the normal prompt deadline, never to cancel live work.
929
+ if (terminalOnly) return null;
749
930
  const cmd = (this.options.command || '').toLowerCase();
750
931
  const isOpencode = cmd.includes('opencode')
751
932
  || (this.options.args && this.options.args.some(a => String(a).toLowerCase().includes('opencode')));
@@ -756,14 +937,24 @@ export class AcpClient {
756
937
  return null;
757
938
  }
758
939
 
940
+ private lastOpencodeLogSignature = '';
941
+ private lastOpencodeLogResult: string | null = null;
942
+
759
943
  private inspectOpencodeLog(sessionId?: string, sinceEpochMs?: number): string | null {
760
944
  try {
761
945
  const home = os.homedir();
762
946
  if (!home) return null;
763
- const logPath = path.join(home, '.local', 'share', 'opencode', 'log', 'opencode.log');
947
+ const xdgData = typeof process.env.XDG_DATA_HOME === 'string' && process.env.XDG_DATA_HOME.trim()
948
+ ? process.env.XDG_DATA_HOME.trim()
949
+ : path.join(home, '.local', 'share');
950
+ const logPath = path.join(xdgData, 'opencode', 'log', 'opencode.log');
764
951
  if (!fsSync.existsSync(logPath)) return null;
765
952
  const stat = fsSync.lstatSync(logPath);
766
953
  if (stat.isSymbolicLink() || !stat.isFile() || stat.size === 0) return null;
954
+ const sig = `${logPath}|${stat.mtimeMs}|${stat.size}|${sessionId || ''}|${sinceEpochMs ?? ''}`;
955
+ if (sig === this.lastOpencodeLogSignature) {
956
+ return this.lastOpencodeLogResult;
957
+ }
767
958
  const readBytes = Math.min(stat.size, 65536);
768
959
  const buffer = Buffer.alloc(readBytes);
769
960
  const fd = fsSync.openSync(logPath, 'r');
@@ -774,6 +965,7 @@ export class AcpClient {
774
965
  }
775
966
  const text = buffer.toString('utf8');
776
967
  const lines = text.split('\n').filter(Boolean);
968
+ let found: string | null = null;
777
969
  for (let i = lines.length - 1; i >= Math.max(0, lines.length - 60); i--) {
778
970
  const line = lines[i];
779
971
  if (!line) continue;
@@ -794,11 +986,16 @@ export class AcpClient {
794
986
  if (line.includes('level=ERROR') || line.includes('AI_APICallError') || line.includes('Free usage limit reached') || line.includes('AI_RetryError')) {
795
987
  const match = line.match(/error\.error="([^"]+)"/) || line.match(/message="([^"]+)"/);
796
988
  if (match && match[1]) {
797
- return redactProviderSecrets(match[1].replace(/\\n/g, ' ')).trim();
989
+ found = redactProviderSecrets(match[1].replace(/\\n/g, ' ')).trim();
990
+ } else {
991
+ found = redactProviderSecrets(line).trim();
798
992
  }
799
- return redactProviderSecrets(line).trim();
993
+ break;
800
994
  }
801
995
  }
996
+ this.lastOpencodeLogSignature = sig;
997
+ this.lastOpencodeLogResult = found;
998
+ return found;
802
999
  } catch {
803
1000
  // ignore log inspection errors
804
1001
  }
@@ -850,10 +1047,13 @@ export class AcpClient {
850
1047
  reject(error);
851
1048
  };
852
1049
  const onAbort = (): void => {
1050
+ if (options?.sessionId) this.exitError ??= createAbortError();
853
1051
  settleReject(createAbortError());
854
1052
  };
855
1053
  const timer = setTimeout(() => {
1054
+ if (options?.sessionId) this.notifyCancel(options.sessionId);
856
1055
  const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
1056
+ if (options?.sessionId) this.exitError ??= new Error(`${method} timed out; peer must reconnect`);
857
1057
  if (diag) {
858
1058
  settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
859
1059
  } else {
@@ -869,11 +1069,18 @@ export class AcpClient {
869
1069
  if (inactivityTimer) clearTimeout(inactivityTimer);
870
1070
  inactivityTimer = setTimeout(() => {
871
1071
  if (settled) return;
872
- if (this.hasOpenToolCall(options?.sessionId) && !this.inspectPeerDiagnostics(options?.sessionId, requestStartMs)) {
1072
+ if (this.activePermissionRequests > 0) {
1073
+ resetInactivity();
1074
+ return;
1075
+ }
1076
+ const maxToolSilenceMs = Math.min(10 * 60 * 1000, Math.max(timeoutMsInact * 3, 300_000));
1077
+ if (this.hasOpenToolCall(options?.sessionId, maxToolSilenceMs) && !this.inspectPeerDiagnostics(options?.sessionId, requestStartMs, true)) {
873
1078
  resetInactivity();
874
1079
  return;
875
1080
  }
1081
+ if (options?.sessionId) this.notifyCancel(options.sessionId);
876
1082
  const diag = this.inspectPeerDiagnostics(options?.sessionId, requestStartMs);
1083
+ this.exitError ??= new Error(`${method} stalled; peer must reconnect`);
877
1084
  if (diag) {
878
1085
  settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${diag}`));
879
1086
  } else {
@@ -889,10 +1096,10 @@ export class AcpClient {
889
1096
  if (sid) {
890
1097
  snifferInterval = setInterval(() => {
891
1098
  if (settled) return;
892
- const fatalDiag = this.inspectPeerDiagnostics(sid, requestStartMs);
1099
+ const fatalDiag = this.inspectPeerDiagnostics(sid, requestStartMs, true);
893
1100
  if (fatalDiag) {
894
1101
  try { this.notifyCancel(sid); } catch { /* ignore */ }
895
- settleReject(new Error(`ACP Peer Agent (${this.options.command}) Error: ${fatalDiag}`));
1102
+ this.failAll(new Error(`ACP Peer Agent (${this.options.command}) Error: ${fatalDiag}`));
896
1103
  }
897
1104
  }, 1500);
898
1105
  if (typeof snifferInterval.unref === 'function') snifferInterval.unref();
@@ -915,7 +1122,7 @@ export class AcpClient {
915
1122
  }
916
1123
 
917
1124
  private failAll(error: Error): void {
918
- this.exitError = error;
1125
+ this.exitError ??= error;
919
1126
  for (const [id, pending] of this.pending) {
920
1127
  clearTimeout(pending.timer);
921
1128
  if (pending.inactivityTimer) clearTimeout(pending.inactivityTimer);