@causyne/agent 1.20.121 → 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 (640) hide show
  1. package/README.md +3 -3
  2. package/bin/causyne.js +38 -15
  3. package/docs/SECURITY_REVIEW.md +42 -6
  4. package/package.json +5 -5
  5. package/src/acp/agentCatalog.js +141 -62
  6. package/src/acp/agentCatalog.ts +142 -65
  7. package/src/acp/client.js +489 -109
  8. package/src/acp/client.ts +465 -108
  9. package/src/acp/peerProfiles.js +55 -22
  10. package/src/acp/peerProfiles.ts +51 -22
  11. package/src/acp/protocol.js +181 -8
  12. package/src/acp/protocol.ts +189 -8
  13. package/src/acp/server.js +250 -53
  14. package/src/acp/server.ts +234 -53
  15. package/src/agent/errorClassifier.js +48 -8
  16. package/src/agent/errorClassifier.ts +50 -7
  17. package/src/agent/providerFailure.js +1 -1
  18. package/src/agent/providerFailure.ts +7 -1
  19. package/src/agent/toolArgValidator.js +38 -4
  20. package/src/agent/toolArgValidator.ts +39 -4
  21. package/src/agent/toolTurnIntegrity.js +28 -7
  22. package/src/agent/toolTurnIntegrity.ts +25 -6
  23. package/src/agent/workspaceBoundary.js +30 -4
  24. package/src/agent/workspaceBoundary.ts +32 -4
  25. package/src/agentLoop.js +609 -222
  26. package/src/agentLoop.ts +632 -220
  27. package/src/approvalGrants.js +19 -7
  28. package/src/approvalGrants.ts +20 -7
  29. package/src/approvalPolicy.js +76 -16
  30. package/src/approvalPolicy.ts +74 -16
  31. package/src/auditLog.js +641 -48
  32. package/src/auditLog.ts +661 -0
  33. package/src/autoUpdate.js +37 -7
  34. package/src/autoUpdate.ts +32 -7
  35. package/src/backgroundTasks.js +328 -0
  36. package/src/backgroundTasks.ts +339 -0
  37. package/src/benchmarks/codingEval.js +558 -0
  38. package/src/benchmarks/codingEval.ts +628 -0
  39. package/src/benchmarks/planCache.js +115 -134
  40. package/src/benchmarks/planCache.ts +163 -0
  41. package/src/browser/browserRuntime.js +52 -0
  42. package/src/browser/browserRuntime.ts +55 -0
  43. package/src/browser/causyneBrowser.js +887 -12
  44. package/src/browser/causyneBrowser.ts +1045 -34
  45. package/src/browser/searchProviders.js +95 -7
  46. package/src/browser/searchProviders.ts +90 -7
  47. package/src/browser/urlPolicy.js +8 -1
  48. package/src/browser/urlPolicy.ts +7 -1
  49. package/src/browser/workspacePathSafety.js +6 -4
  50. package/src/browser/workspacePathSafety.ts +7 -4
  51. package/src/capabilities.js +18 -17
  52. package/src/capabilities.ts +38 -0
  53. package/src/checkpoints.js +1241 -1127
  54. package/src/checkpoints.ts +1377 -0
  55. package/src/cliMode.js +707 -755
  56. package/src/cliMode.ts +780 -0
  57. package/src/codebase/repoMap.js +656 -0
  58. package/src/codebase/repoMap.ts +664 -0
  59. package/src/commands.js +3651 -2514
  60. package/src/commands.ts +3985 -0
  61. package/src/compiledSkills.js +8052 -8054
  62. package/src/compiledSkills.ts +8078 -0
  63. package/src/config.js +389 -250
  64. package/src/config.ts +451 -0
  65. package/src/configVault.js +113 -19
  66. package/src/configVault.ts +103 -19
  67. package/src/contextManager.js +473 -557
  68. package/src/contextManager.ts +599 -0
  69. package/src/continuum/adapters/antigravity.js +8 -3
  70. package/src/continuum/adapters/antigravity.ts +8 -3
  71. package/src/continuum/compactor.js +2 -1
  72. package/src/continuum/compactor.ts +2 -1
  73. package/src/continuum/sanitizer.js +33 -4
  74. package/src/continuum/sanitizer.ts +32 -4
  75. package/src/continuum/ui/continuumPicker.js +0 -2
  76. package/src/continuum/ui/continuumPicker.ts +0 -2
  77. package/src/continuum/ui/continuumPickerView.js +3 -4
  78. package/src/continuum/ui/continuumPickerView.ts +7 -22
  79. package/src/core/contextCompactor.js +88 -7
  80. package/src/core/contextCompactor.ts +87 -8
  81. package/src/cortex/vectorDb.js +26 -15
  82. package/src/cortex/vectorDb.ts +26 -16
  83. package/src/creative/liveBridge.js +10 -7
  84. package/src/creative/liveBridge.ts +11 -7
  85. package/src/creative/studioScripts.js +17 -6
  86. package/src/creative/studioScripts.ts +15 -6
  87. package/src/decideTools.js +7 -2
  88. package/src/decideTools.ts +7 -2
  89. package/src/decisionPolicy.js +26 -6
  90. package/src/decisionPolicy.ts +24 -6
  91. package/src/designPalettes.js +72 -84
  92. package/src/designPalettes.ts +111 -0
  93. package/src/devMode.js +2 -2
  94. package/src/devMode.ts +6 -0
  95. package/src/diffReview.js +370 -0
  96. package/src/diffReview.ts +407 -0
  97. package/src/documentEngine/antiSlopAuditor.js +10 -5
  98. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  99. package/src/documentEngine/documentForge.js +47 -15
  100. package/src/documentEngine/documentForge.ts +43 -14
  101. package/src/dynamicCatalogue.js +311 -11
  102. package/src/dynamicCatalogue.ts +331 -11
  103. package/src/embodimentSession.js +143 -154
  104. package/src/embodimentSession.ts +173 -0
  105. package/src/engines/design.js +2 -1
  106. package/src/engines/design.ts +2 -1
  107. package/src/engines/film.js +4 -4
  108. package/src/engines/film.ts +2 -2
  109. package/src/engines/installer.js +60 -29
  110. package/src/engines/installer.ts +73 -22
  111. package/src/engines/light.js +2 -1
  112. package/src/engines/light.ts +2 -1
  113. package/src/engines/registry.js +1 -1
  114. package/src/engines/registry.ts +1 -1
  115. package/src/engines/reverseHarness.js +4 -3
  116. package/src/engines/reverseHarness.ts +4 -3
  117. package/src/enterprisePolicy.js +660 -0
  118. package/src/enterprisePolicy.ts +728 -0
  119. package/src/entrypoint.js +514 -268
  120. package/src/entrypoint.ts +607 -0
  121. package/src/gitSnapshot.js +417 -312
  122. package/src/gitSnapshot.ts +500 -0
  123. package/src/headlessCli.js +326 -14
  124. package/src/headlessCli.ts +323 -13
  125. package/src/historyPruner.js +3 -2
  126. package/src/historyPruner.ts +3 -2
  127. package/src/hooks.js +250 -26
  128. package/src/hooks.ts +239 -26
  129. package/src/ignoreRules.js +297 -0
  130. package/src/ignoreRules.ts +308 -0
  131. package/src/implementationPlan.js +28 -17
  132. package/src/implementationPlan.ts +29 -17
  133. package/src/infra/atomicWriter.js +96 -20
  134. package/src/infra/atomicWriter.ts +112 -20
  135. package/src/launchIntent.js +14 -3
  136. package/src/launchIntent.ts +14 -3
  137. package/src/licensing/entitlements.js +553 -237
  138. package/src/licensing/entitlements.ts +590 -0
  139. package/src/licensing/policy.js +17 -1
  140. package/src/licensing/policy.ts +31 -0
  141. package/src/lsp/lspCatalog.js +398 -0
  142. package/src/lsp/lspCatalog.ts +452 -0
  143. package/src/lsp/lspClient.js +699 -0
  144. package/src/lsp/lspClient.ts +799 -0
  145. package/src/lsp/lspProtocol.js +121 -0
  146. package/src/lsp/lspProtocol.ts +140 -0
  147. package/src/mcp/mcpClient.js +69 -8
  148. package/src/mcp/mcpClient.ts +66 -9
  149. package/src/mcp/mcpRegistry.js +180 -7
  150. package/src/mcp/mcpRegistry.ts +171 -7
  151. package/src/mcp/mcpSecurity.js +6 -7
  152. package/src/mcp/mcpSecurity.ts +7 -6
  153. package/src/memory/episodicStore.js +2 -5
  154. package/src/memory/episodicStore.ts +2 -5
  155. package/src/memory/scopedFacts.js +1 -1
  156. package/src/memory/scopedFacts.ts +1 -1
  157. package/src/memory/symbolFolder.js +1 -1
  158. package/src/memory/symbolFolder.ts +1 -1
  159. package/src/memory.js +80 -32
  160. package/src/memory.ts +111 -0
  161. package/src/memoryManager.js +151 -143
  162. package/src/memoryManager.ts +182 -0
  163. package/src/modelCatalogue.js +172 -195
  164. package/src/modelCatalogue.ts +201 -0
  165. package/src/modelIds.js +8 -27
  166. package/src/modelIds.ts +33 -0
  167. package/src/modelRouter.js +1 -1
  168. package/src/modelRouter.ts +1 -1
  169. package/src/modelVariants.js +600 -0
  170. package/src/modelVariants.ts +663 -0
  171. package/src/observer/evidence.js +15 -5
  172. package/src/observer/evidence.ts +15 -5
  173. package/src/osKeychain.js +79 -17
  174. package/src/osKeychain.ts +64 -17
  175. package/src/outputStore.js +210 -156
  176. package/src/outputStore.ts +321 -0
  177. package/src/perception.js +3 -2
  178. package/src/perception.ts +3 -2
  179. package/src/planCache.js +5 -8
  180. package/src/planCache.ts +5 -8
  181. package/src/plugins/pluginManager.js +689 -461
  182. package/src/plugins/pluginManager.ts +807 -0
  183. package/src/plugins/pluginRunner.js +82 -37
  184. package/src/plugins/pluginRunner.ts +98 -0
  185. package/src/plugins/pluginSkills.js +47 -9
  186. package/src/plugins/pluginSkills.ts +46 -8
  187. package/src/pluginsFactory/discovery.js +0 -1
  188. package/src/pluginsFactory/discovery.ts +0 -1
  189. package/src/pluginsFactory/pluginsFactory.js +19 -11
  190. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  191. package/src/pluginsFactory/templates.js +17 -4
  192. package/src/pluginsFactory/templates.ts +17 -4
  193. package/src/prWorkflow.js +337 -0
  194. package/src/prWorkflow.ts +376 -0
  195. package/src/procSignal.js +1 -2
  196. package/src/procSignal.ts +1 -3
  197. package/src/projectInstructions.js +319 -0
  198. package/src/projectInstructions.ts +361 -0
  199. package/src/promptMentions.js +2 -2
  200. package/src/promptMentions.ts +2 -2
  201. package/src/providers/acp.js +235 -50
  202. package/src/providers/acp.ts +241 -51
  203. package/src/providers/anthropic.js +431 -400
  204. package/src/providers/anthropic.ts +493 -0
  205. package/src/providers/antigravity.js +575 -358
  206. package/src/providers/antigravity.ts +565 -359
  207. package/src/providers/base.js +229 -320
  208. package/src/providers/base.ts +348 -0
  209. package/src/providers/byokHttp.js +183 -30
  210. package/src/providers/byokHttp.ts +232 -32
  211. package/src/providers/byokStream.js +287 -70
  212. package/src/providers/byokStream.ts +282 -71
  213. package/src/providers/dashscope-byok.js +123 -89
  214. package/src/providers/dashscope-byok.ts +142 -0
  215. package/src/providers/deepseek.js +82 -72
  216. package/src/providers/deepseek.ts +108 -0
  217. package/src/providers/factory.js +76 -28
  218. package/src/providers/factory.ts +82 -0
  219. package/src/providers/gemini.js +279 -278
  220. package/src/providers/gemini.ts +313 -0
  221. package/src/providers/loopGuard.js +9 -5
  222. package/src/providers/loopGuard.ts +10 -5
  223. package/src/providers/moonshot.js +103 -72
  224. package/src/providers/moonshot.ts +122 -0
  225. package/src/providers/muse.js +82 -152
  226. package/src/providers/muse.ts +122 -0
  227. package/src/providers/ollama.js +360 -106
  228. package/src/providers/ollama.ts +408 -0
  229. package/src/providers/openai-compatible.js +168 -95
  230. package/src/providers/openai-compatible.ts +200 -0
  231. package/src/providers/openai.js +45 -15
  232. package/src/providers/openai.ts +52 -0
  233. package/src/providers/openrouter.js +342 -113
  234. package/src/providers/openrouter.ts +333 -116
  235. package/src/providers/pi.js +6 -0
  236. package/src/providers/pi.ts +6 -0
  237. package/src/providers/qwen-byok.js +122 -87
  238. package/src/providers/qwen-byok.ts +141 -0
  239. package/src/providers/toolContracts.js +40 -14
  240. package/src/providers/toolContracts.ts +35 -14
  241. package/src/providers/wireNormalizer.js +144 -11
  242. package/src/providers/wireNormalizer.ts +132 -12
  243. package/src/providers/xai.js +80 -72
  244. package/src/providers/xai.ts +103 -0
  245. package/src/provisioning/capabilityConsent.js +29 -11
  246. package/src/provisioning/capabilityConsent.ts +42 -0
  247. package/src/provisioning/capabilityProvisioner.js +309 -197
  248. package/src/provisioning/capabilityProvisioner.ts +413 -0
  249. package/src/provisioning/capabilityTools.js +31 -17
  250. package/src/provisioning/capabilityTools.ts +43 -0
  251. package/src/provisioning/npmInstall.js +33 -5
  252. package/src/provisioning/npmInstall.ts +33 -5
  253. package/src/reliability/assetEvidence.js +4 -2
  254. package/src/reliability/assetEvidence.ts +4 -2
  255. package/src/reporting.js +328 -326
  256. package/src/reporting.ts +482 -0
  257. package/src/sandbox.js +526 -554
  258. package/src/sandbox.ts +590 -0
  259. package/src/sandboxPolicy.js +95 -16
  260. package/src/sandboxPolicy.ts +97 -16
  261. package/src/sessionJournal.js +32 -6
  262. package/src/sessionJournal.ts +27 -6
  263. package/src/sessionStore.js +1 -2
  264. package/src/sessionStore.ts +2 -0
  265. package/src/skills/skillResourceSafety.js +19 -8
  266. package/src/skills/skillResourceSafety.ts +16 -7
  267. package/src/skillsManager.js +3 -3
  268. package/src/skillsManager.ts +3 -3
  269. package/src/slopDetector.js +202 -265
  270. package/src/slopDetector.ts +279 -0
  271. package/src/smartToolsUse.js +38 -8
  272. package/src/smartToolsUse.ts +39 -11
  273. package/src/stallGuard.js +53 -23
  274. package/src/stallGuard.ts +53 -23
  275. package/src/subagentJournal.js +6 -4
  276. package/src/subagentJournal.ts +6 -4
  277. package/src/taskBuffer.js +91 -40
  278. package/src/taskBuffer.ts +94 -0
  279. package/src/textDiff.js +6 -1
  280. package/src/textDiff.ts +6 -1
  281. package/src/timeMachine.js +7 -1
  282. package/src/timeMachine.ts +7 -1
  283. package/src/tokenTracker.js +120 -38
  284. package/src/tokenTracker.ts +110 -38
  285. package/src/toolPacks.js +8 -1
  286. package/src/toolPacks.ts +8 -1
  287. package/src/tools/applyPatch.js +610 -0
  288. package/src/tools/applyPatch.ts +661 -0
  289. package/src/tools/archive.js +372 -48
  290. package/src/tools/archive.ts +372 -48
  291. package/src/tools/astryxOracle.js +77 -72
  292. package/src/tools/astryxOracle.ts +95 -0
  293. package/src/tools/axSnapshot.js +127 -147
  294. package/src/tools/axSnapshot.ts +174 -0
  295. package/src/tools/backgroundTask.js +86 -0
  296. package/src/tools/backgroundTask.ts +121 -0
  297. package/src/tools/blenderAutomator.js +434 -390
  298. package/src/tools/blenderAutomator.ts +623 -0
  299. package/src/tools/checkSystemSpecs.js +54 -61
  300. package/src/tools/checkSystemSpecs.ts +73 -0
  301. package/src/tools/clipboard.js +42 -31
  302. package/src/tools/clipboard.ts +61 -0
  303. package/src/tools/codeSearchAst.js +359 -91
  304. package/src/tools/codeSearchAst.ts +399 -0
  305. package/src/tools/codeSearcher.js +179 -37
  306. package/src/tools/codeSearcher.ts +188 -33
  307. package/src/tools/codeTools.js +208 -245
  308. package/src/tools/codeTools.ts +271 -0
  309. package/src/tools/codebaseSearch.js +5 -0
  310. package/src/tools/codebaseSearch.ts +5 -0
  311. package/src/tools/computerUse.js +7 -3
  312. package/src/tools/computerUse.ts +7 -3
  313. package/src/tools/creativeApps.js +13 -8
  314. package/src/tools/creativeApps.ts +22 -9
  315. package/src/tools/deferredMcpSearch.js +26 -14
  316. package/src/tools/deferredMcpSearch.ts +26 -14
  317. package/src/tools/desktopAct.js +185 -197
  318. package/src/tools/desktopAct.ts +257 -0
  319. package/src/tools/desktopOpen.js +69 -10
  320. package/src/tools/desktopOpen.ts +70 -11
  321. package/src/tools/documentForge.js +167 -82
  322. package/src/tools/documentForge.ts +169 -84
  323. package/src/tools/dynamicLoader.js +4 -40
  324. package/src/tools/dynamicLoader.ts +13 -0
  325. package/src/tools/executeProceduralMedia.js +117 -86
  326. package/src/tools/executeProceduralMedia.ts +135 -0
  327. package/src/tools/fileTracker.js +74 -0
  328. package/src/tools/fileTracker.ts +94 -0
  329. package/src/tools/fsDelete.js +57 -47
  330. package/src/tools/fsDelete.ts +80 -0
  331. package/src/tools/fsEdit.js +250 -61
  332. package/src/tools/fsEdit.ts +265 -63
  333. package/src/tools/fsFind.js +8 -5
  334. package/src/tools/fsFind.ts +7 -4
  335. package/src/tools/fsMove.js +79 -52
  336. package/src/tools/fsMove.ts +108 -0
  337. package/src/tools/fsRead.js +163 -18
  338. package/src/tools/fsRead.ts +169 -18
  339. package/src/tools/fsSearch.js +5 -0
  340. package/src/tools/fsSearch.ts +5 -0
  341. package/src/tools/fsWrite.js +31 -11
  342. package/src/tools/fsWrite.ts +31 -13
  343. package/src/tools/gameAiBehaviorTree.js +74 -91
  344. package/src/tools/gameAiBehaviorTree.ts +219 -0
  345. package/src/tools/gameAnimationRig.js +128 -147
  346. package/src/tools/gameAnimationRig.ts +215 -0
  347. package/src/tools/gameAssetFetcher.js +403 -441
  348. package/src/tools/gameAssetFetcher.ts +477 -0
  349. package/src/tools/gameAssetHarvester.js +171 -200
  350. package/src/tools/gameAssetHarvester.ts +261 -0
  351. package/src/tools/gameAudioSynth.js +223 -259
  352. package/src/tools/gameAudioSynth.ts +255 -0
  353. package/src/tools/gameBuilder.js +100 -91
  354. package/src/tools/gameBuilder.ts +913 -0
  355. package/src/tools/gameCanvasAudit.js +138 -96
  356. package/src/tools/gameCanvasAudit.ts +157 -0
  357. package/src/tools/gameCinematicSequencer.js +93 -111
  358. package/src/tools/gameCinematicSequencer.ts +165 -0
  359. package/src/tools/gameDataForge.js +115 -118
  360. package/src/tools/gameDataForge.ts +151 -0
  361. package/src/tools/gameDialogueTreeGen.js +125 -156
  362. package/src/tools/gameDialogueTreeGen.ts +159 -0
  363. package/src/tools/gameEconomyBalancer.js +150 -153
  364. package/src/tools/gameEconomyBalancer.ts +186 -0
  365. package/src/tools/gameEntitySpawner.js +91 -108
  366. package/src/tools/gameEntitySpawner.ts +209 -0
  367. package/src/tools/gameLoreForge.js +125 -147
  368. package/src/tools/gameLoreForge.ts +162 -0
  369. package/src/tools/gameQuestArcBuilder.js +105 -144
  370. package/src/tools/gameQuestArcBuilder.ts +147 -0
  371. package/src/tools/gameSceneBuilder.js +143 -149
  372. package/src/tools/gameSceneBuilder.ts +196 -0
  373. package/src/tools/gameShaderForge.js +83 -101
  374. package/src/tools/gameShaderForge.ts +181 -0
  375. package/src/tools/gameTilemapGenerator.js +99 -129
  376. package/src/tools/gameTilemapGenerator.ts +158 -0
  377. package/src/tools/gameUiHudBuilder.js +109 -129
  378. package/src/tools/gameUiHudBuilder.ts +300 -0
  379. package/src/tools/gameVfxEmitterGen.js +86 -89
  380. package/src/tools/gameVfxEmitterGen.ts +133 -0
  381. package/src/tools/gameWebRuntimeInspector.js +153 -86
  382. package/src/tools/gameWebRuntimeInspector.ts +167 -0
  383. package/src/tools/generateMediaViaApi.js +126 -22
  384. package/src/tools/generateMediaViaApi.ts +123 -22
  385. package/src/tools/gitExec.js +133 -86
  386. package/src/tools/gitExec.ts +146 -0
  387. package/src/tools/gitWorktree.js +115 -0
  388. package/src/tools/gitWorktree.ts +150 -0
  389. package/src/tools/godotAutomator.js +417 -394
  390. package/src/tools/godotAutomator.ts +530 -0
  391. package/src/tools/lspCodeIntel.js +217 -0
  392. package/src/tools/lspCodeIntel.ts +260 -0
  393. package/src/tools/manageLocalAiDependencies.js +242 -206
  394. package/src/tools/manageLocalAiDependencies.ts +288 -0
  395. package/src/tools/memoryRecall.js +62 -11
  396. package/src/tools/memoryRecall.ts +70 -13
  397. package/src/tools/memoryWrite.js +27 -14
  398. package/src/tools/memoryWrite.ts +30 -14
  399. package/src/tools/multiEdit.js +73 -63
  400. package/src/tools/multiEdit.ts +80 -65
  401. package/src/tools/nativeEngine.js +33 -18
  402. package/src/tools/nativeEngine.ts +31 -18
  403. package/src/tools/openSourceToolProvisioner.js +49 -14
  404. package/src/tools/openSourceToolProvisioner.ts +54 -15
  405. package/src/tools/osSandbox.js +202 -25
  406. package/src/tools/osSandbox.ts +192 -25
  407. package/src/tools/palmierAutomator.js +147 -95
  408. package/src/tools/palmierAutomator.ts +171 -0
  409. package/src/tools/payloadSanitizer.js +40 -8
  410. package/src/tools/payloadSanitizer.ts +39 -8
  411. package/src/tools/pdfReader.js +95 -104
  412. package/src/tools/pdfReader.ts +125 -0
  413. package/src/tools/peerAgent.js +96 -34
  414. package/src/tools/peerAgent.ts +114 -37
  415. package/src/tools/persistentShell.js +267 -144
  416. package/src/tools/persistentShell.ts +314 -0
  417. package/src/tools/pluginManager.js +84 -72
  418. package/src/tools/pluginManager.ts +109 -0
  419. package/src/tools/pluginsFactory.js +38 -6
  420. package/src/tools/pluginsFactory.ts +42 -6
  421. package/src/tools/printer.js +278 -296
  422. package/src/tools/printer.ts +326 -0
  423. package/src/tools/procTerm.js +96 -83
  424. package/src/tools/procTerm.ts +127 -0
  425. package/src/tools/processList.js +45 -48
  426. package/src/tools/processList.ts +73 -0
  427. package/src/tools/readNativeSkill.js +10 -8
  428. package/src/tools/readNativeSkill.ts +10 -8
  429. package/src/tools/registry.js +298 -286
  430. package/src/tools/registry.ts +486 -0
  431. package/src/tools/repoMap.js +46 -0
  432. package/src/tools/repoMap.ts +66 -0
  433. package/src/tools/requestDecision.js +10 -3
  434. package/src/tools/requestDecision.ts +10 -3
  435. package/src/tools/resolveAutomator.js +91 -17
  436. package/src/tools/resolveAutomator.ts +102 -17
  437. package/src/tools/reverseEngineering.js +168 -41
  438. package/src/tools/reverseEngineering.ts +161 -41
  439. package/src/tools/subagentOrchestrator.js +404 -348
  440. package/src/tools/subagentOrchestrator.ts +457 -0
  441. package/src/tools/sysRun.js +148 -51
  442. package/src/tools/sysRun.ts +142 -46
  443. package/src/tools/toolDispatch.js +24 -1
  444. package/src/tools/toolDispatch.ts +21 -1
  445. package/src/tools/toolForge.js +84 -67
  446. package/src/tools/toolForge.ts +102 -0
  447. package/src/tools/toolOutputStore.js +62 -23
  448. package/src/tools/toolOutputStore.ts +56 -23
  449. package/src/tools/toolPathSafety.js +262 -0
  450. package/src/tools/toolPathSafety.ts +308 -0
  451. package/src/tools/toolScanner.js +41 -10
  452. package/src/tools/toolScanner.ts +42 -10
  453. package/src/tools/toolSelfRepair.js +115 -34
  454. package/src/tools/toolSelfRepair.ts +122 -34
  455. package/src/tools/uiForge.js +71 -6
  456. package/src/tools/uiForge.ts +74 -6
  457. package/src/tools/viewImage.js +62 -17
  458. package/src/tools/viewImage.ts +57 -12
  459. package/src/tools/visionInspector.js +15 -3
  460. package/src/tools/visionInspector.ts +15 -3
  461. package/src/tools/walkerSafety.js +2 -0
  462. package/src/tools/walkerSafety.ts +2 -0
  463. package/src/tools/webFetch.js +110 -12
  464. package/src/tools/webFetch.ts +110 -13
  465. package/src/toolsList.js +5 -0
  466. package/src/toolsList.ts +5 -0
  467. package/src/tui/ask.js +159 -168
  468. package/src/tui/ask.ts +259 -0
  469. package/src/tui/banner.js +3 -2
  470. package/src/tui/banner.ts +3 -2
  471. package/src/tui/block.js +0 -1
  472. package/src/tui/block.ts +0 -1
  473. package/src/tui/chatRenderer.js +1193 -1441
  474. package/src/tui/chatRenderer.ts +1336 -0
  475. package/src/tui/clipboardImage.js +36 -12
  476. package/src/tui/clipboardImage.ts +39 -13
  477. package/src/tui/clipboardSync.js +34 -9
  478. package/src/tui/clipboardSync.ts +38 -9
  479. package/src/tui/codeProgress.js +0 -1
  480. package/src/tui/codeProgress.ts +0 -1
  481. package/src/tui/completion.js +395 -371
  482. package/src/tui/completion.ts +574 -0
  483. package/src/tui/composerControls.js +113 -19
  484. package/src/tui/composerControls.ts +124 -19
  485. package/src/tui/consoleGuard.js +39 -11
  486. package/src/tui/consoleGuard.ts +38 -11
  487. package/src/tui/dialogs.js +864 -717
  488. package/src/tui/dialogs.ts +984 -0
  489. package/src/tui/diff.js +205 -195
  490. package/src/tui/diff.ts +336 -0
  491. package/src/tui/history.js +143 -108
  492. package/src/tui/history.ts +167 -0
  493. package/src/tui/home.js +165 -161
  494. package/src/tui/home.ts +251 -0
  495. package/src/tui/invocation.js +58 -65
  496. package/src/tui/invocation.ts +117 -0
  497. package/src/tui/keys.js +437 -420
  498. package/src/tui/keys.ts +597 -0
  499. package/src/tui/lineEditor.js +477 -432
  500. package/src/tui/lineEditor.ts +542 -0
  501. package/src/tui/messageActionPlacement.js +0 -1
  502. package/src/tui/messageActionPlacement.ts +0 -1
  503. package/src/tui/messageInteraction.js +2 -5
  504. package/src/tui/messageInteraction.ts +2 -5
  505. package/src/tui/modelPicker.js +1 -3
  506. package/src/tui/modelPicker.ts +4 -6
  507. package/src/tui/observerPicker.js +0 -2
  508. package/src/tui/observerPicker.ts +0 -2
  509. package/src/tui/overlay.js +3 -2
  510. package/src/tui/overlay.ts +3 -2
  511. package/src/tui/prompt.js +1816 -2151
  512. package/src/tui/prompt.ts +1870 -0
  513. package/src/tui/runningLight.js +0 -1
  514. package/src/tui/runningLight.ts +0 -1
  515. package/src/tui/selectList.js +365 -337
  516. package/src/tui/selectList.ts +441 -0
  517. package/src/tui/sessionPicker.js +3 -3
  518. package/src/tui/sessionPicker.ts +3 -3
  519. package/src/tui/sessionPickerView.js +7 -3
  520. package/src/tui/sessionPickerView.ts +10 -22
  521. package/src/tui/sessionSidebar.js +3 -1
  522. package/src/tui/sessionSidebar.ts +4 -1
  523. package/src/tui/setup.js +17 -5
  524. package/src/tui/setup.ts +19 -5
  525. package/src/tui/skillAuthoring.js +0 -2
  526. package/src/tui/skillAuthoring.ts +0 -3
  527. package/src/tui/stageSurface.js +829 -909
  528. package/src/tui/stageSurface.ts +1003 -0
  529. package/src/tui/statusLine.js +7 -4
  530. package/src/tui/statusLine.ts +7 -3
  531. package/src/tui/terminalInputFramer.js +82 -69
  532. package/src/tui/terminalInputFramer.ts +116 -0
  533. package/src/tui/text.js +25 -10
  534. package/src/tui/text.ts +24 -10
  535. package/src/tui/textLayout.js +0 -1
  536. package/src/tui/textLayout.ts +0 -1
  537. package/src/tui/theme.js +245 -250
  538. package/src/tui/theme.ts +441 -0
  539. package/src/tui/thinkingBox.js +0 -1
  540. package/src/tui/thinkingBox.ts +0 -1
  541. package/src/tui/toolOutputNormalizer.js +2 -3
  542. package/src/tui/toolOutputNormalizer.ts +4 -3
  543. package/src/tui/transcript.js +239 -216
  544. package/src/tui/transcript.ts +324 -0
  545. package/src/tui/turnRail.js +53 -54
  546. package/src/tui/turnRail.ts +51 -49
  547. package/src/tui/usageCard.js +0 -2
  548. package/src/tui/usageCard.ts +0 -2
  549. package/src/tui/viewport.js +4 -4
  550. package/src/tui/viewport.ts +5 -5
  551. package/src/tui/workspaceIdentity.js +2 -1
  552. package/src/tui/workspaceIdentity.ts +2 -1
  553. package/src/tui/workspaceSwitch.js +4 -2
  554. package/src/tui/workspaceSwitch.ts +5 -2
  555. package/src/types/contracts.ts +4 -1
  556. package/src/uncertainty.js +8 -3
  557. package/src/uncertainty.ts +8 -3
  558. package/src/utils/browserOpen.js +107 -0
  559. package/src/utils/browserOpen.ts +129 -0
  560. package/src/utils/cli_ui.js +0 -0
  561. package/src/utils/cli_ui.ts +158 -0
  562. package/src/utils/paths.js +8 -5
  563. package/src/utils/paths.ts +9 -7
  564. package/src/utils/winSpawn.js +248 -0
  565. package/src/utils/winSpawn.ts +275 -0
  566. package/src/verification/boundedExplorer.js +138 -107
  567. package/src/verification/boundedExplorer.ts +154 -0
  568. package/src/verification/byokSmokeProbe.js +193 -0
  569. package/src/verification/byokSmokeProbe.ts +234 -0
  570. package/src/verification/cliProbe.js +144 -110
  571. package/src/verification/cliProbe.ts +170 -0
  572. package/src/verification/featureMap.js +105 -75
  573. package/src/verification/featureMap.ts +124 -0
  574. package/src/verification/interactivePty.js +195 -100
  575. package/src/verification/interactivePty.ts +333 -0
  576. package/src/verification/propertyProbe.js +109 -101
  577. package/src/verification/propertyProbe.ts +159 -0
  578. package/src/verification/ptyProbe.js +168 -73
  579. package/src/verification/ptyProbe.ts +254 -0
  580. package/src/verification/skillCatalog.js +25 -25
  581. package/src/verification/skillCatalog.ts +66 -0
  582. package/src/verification/statechart.js +140 -127
  583. package/src/verification/statechart.ts +196 -0
  584. package/src/verification/uiRuntime.js +80 -49
  585. package/src/verification/uiRuntime.ts +88 -0
  586. package/src/version.js +37 -32
  587. package/src/version.ts +45 -0
  588. package/src/vfeTracker.js +9 -3
  589. package/src/vfeTracker.ts +9 -3
  590. package/src/web/guiLauncher.js +89 -0
  591. package/src/web/guiLauncher.ts +119 -0
  592. package/src/web/skybridgeBrowserBridge.js +256 -0
  593. package/src/web/skybridgeBrowserBridge.ts +285 -0
  594. package/src/web/skybridgeBrowserMcp.js +730 -0
  595. package/src/web/skybridgeBrowserMcp.ts +813 -0
  596. package/src/web/skybridgeClientScript.js +3951 -0
  597. package/src/web/skybridgeClientScript.ts +3952 -0
  598. package/src/web/skybridgeServer.js +2622 -0
  599. package/src/web/skybridgeServer.ts +2787 -0
  600. package/src/web/skybridgeStyles.js +827 -0
  601. package/src/web/skybridgeStyles.ts +828 -0
  602. package/src/web/skybridgeUi.js +472 -0
  603. package/src/web/skybridgeUi.ts +485 -0
  604. package/src/worktreeManager.js +511 -0
  605. package/src/worktreeManager.ts +546 -0
  606. package/src/zeroCostFailover.js +168 -0
  607. package/src/zeroCostFailover.ts +198 -0
  608. package/src/zeroCostRouting.js +391 -0
  609. package/src/zeroCostRouting.ts +437 -0
  610. package/src/agentLoop.d.ts +0 -65
  611. package/src/auditLog.d.ts +0 -3
  612. package/src/checkpoints.d.ts +0 -4
  613. package/src/compiledSkills.d.ts +0 -5
  614. package/src/config.d.ts +0 -2
  615. package/src/contextManager.d.ts +0 -14
  616. package/src/designPalettes.d.ts +0 -2
  617. package/src/devMode.d.ts +0 -1
  618. package/src/embodimentSession.d.ts +0 -2
  619. package/src/licensing/entitlements.d.ts +0 -14
  620. package/src/memory.d.ts +0 -13
  621. package/src/memoryManager.d.ts +0 -1
  622. package/src/modelCatalogue.d.ts +0 -6
  623. package/src/modelIds.d.ts +0 -2
  624. package/src/outputStore.d.ts +0 -4
  625. package/src/plugins/pluginManager.d.ts +0 -7
  626. package/src/providers/antigravity.d.ts +0 -19
  627. package/src/providers/base.d.ts +0 -94
  628. package/src/providers/factory.d.ts +0 -1
  629. package/src/provisioning/capabilityProvisioner.d.ts +0 -12
  630. package/src/sandbox.d.ts +0 -1
  631. package/src/slopDetector.d.ts +0 -3
  632. package/src/taskBuffer.d.ts +0 -1
  633. package/src/tools/desktopAct.d.ts +0 -10
  634. package/src/tools/registry.d.ts +0 -5
  635. package/src/tui/chatRenderer.d.ts +0 -27
  636. package/src/tui/diff.d.ts +0 -3
  637. package/src/utils/cli_ui.d.ts +0 -19
  638. package/src/utils/paths.d.ts +0 -3
  639. package/src/verification/skillCatalog.d.ts +0 -1
  640. package/src/version.d.ts +0 -1
package/src/agentLoop.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { clearSysRunCache } from './tools/sysRun.js';
2
+ import { sanitizeSubprocessEnv } from './tools/subprocessEnv.js';
2
3
  import { NetworkHostGuard } from './reliability/networkHostGuard.js';
3
4
  import { inspectRequestedImageAssets } from './reliability/assetEvidence.js';
4
5
  import { inspect3DVisualEvidence } from './reliability/visualEvidence.js';
@@ -19,10 +20,14 @@ import {
19
20
  isMidTaskProgressText
20
21
  } from './agent/promptIntent.js';
21
22
  import { validateAndNormalizeToolArgs } from './agent/toolArgValidator.js';
23
+ import { physicalPath, isWithinPhysicalPath } from './agent/workspaceBoundary.js';
22
24
  import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime, DEFAULT_AGY_TASK_TOKENS } from './budget/budgetPolicy.js';
23
25
  import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
24
- import type { RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
26
+ import type { McpServer, RequestPermissionRequest, RequestPermissionResponse } from './acp/protocol.js';
27
+ import { isAcpProvider } from './providers/acp.js';
28
+ import { causyneBrowser, type LiveBrowserAwarenessContext } from './browser/causyneBrowser.js';
25
29
  import { createHash, randomUUID } from 'crypto';
30
+ import { fileURLToPath } from 'node:url';
26
31
  import { execFileSync } from 'node:child_process';
27
32
  import { processApprovalScope, createApprovalScope } from './approvalGrants.js';
28
33
  import { pruneSessions as pruneEmbodimentSessions, describeSession } from './embodimentSession.js';
@@ -36,7 +41,7 @@ import { validateToolArguments } from './tools/argumentValidation.js';
36
41
  import { Sandbox } from './sandbox.js';
37
42
  import { auditLog } from './auditLog.js';
38
43
  import { hasMatchingHook, runConfiguredHooks } from './hooks.js';
39
- import { loadConfig } from './config.js';
44
+ import { loadConfig, applyProviderOverrides } from './config.js';
40
45
  import { isDevEmulator } from './devMode.js';
41
46
  import { TokenTracker } from './tokenTracker.js';
42
47
 
@@ -45,7 +50,7 @@ import { MemoryManager } from './memoryManager.js';
45
50
  import { cortexDb, isSearchablePrompt } from './cortex/vectorDb.js';
46
51
  import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
47
52
  import { episodicStore, compileToolObservation } from './memory/episodicStore.js';
48
- import { buildCodexStyleSummary, compactSessionMessages, autoCompactIfUnderPressure } from './core/contextCompactor.js';
53
+ import { buildCodexStyleSummary, compactSessionMessages, autoCompactIfUnderPressure, findSafeCompactionSplitIndex } from './core/contextCompactor.js';
49
54
  import { analyzeTask, buildTaskBrief } from './taskShape.js';
50
55
  import {
51
56
  lookupPlan,
@@ -62,7 +67,14 @@ import { routedConfig } from './modelRouter.js';
62
67
  import { assessStep, isThrashing } from './uncertainty.js';
63
68
  import { assessDecisionRequirement, isMutatingToolCall, requiresImplementationPlan } from './decisionPolicy.js';
64
69
  import { normalizePeerPlanEntries, extractLivePlanFromText, stripToolCallMarkup, stripThinkBlocks, extractToolCallJsonObjects, resolveToolCallEnvelopeArguments } from './implementationPlan.js';
65
- import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
70
+ import { isWholeFileDeletion, requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
71
+ import { evaluateEnterprisePolicy } from './enterprisePolicy.js';
72
+ import {
73
+ isZeroCostFailoverEligible,
74
+ normalizeZeroCostId,
75
+ selectNextZeroCostRoute
76
+ } from './zeroCostFailover.js';
77
+ import { formatProjectInstructionsPrompt, loadProjectInstructions } from './projectInstructions.js';
66
78
  import { AGENT_USER_POLICY } from './agentPolicy.js';
67
79
  import { VFETracker } from './vfeTracker.js';
68
80
  import { coldObserver } from './observer/coldObserver.js';
@@ -112,12 +124,14 @@ import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from '.
112
124
  import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
113
125
  import { ToolOutputStore, defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
114
126
  import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
127
+ import { extractPatchTargetPaths } from './tools/applyPatch.js';
115
128
  import fsSync from 'fs';
116
129
  import os from 'os';
117
130
  import path from 'path';
118
131
  import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js';
119
132
  import { suggestMovements, formatMovementBrief } from './designPalettes.js';
120
133
  import { createProvider } from './providers/factory.js';
134
+ import { redactProviderSecrets } from './providers/byokHttp.js';
121
135
  import { isNativeMutation } from './providers/antigravity.js';
122
136
  import { resolveMentionedContext } from './promptMentions.js';
123
137
  import { isLaunchOnlyPrompt, launchScopeError, isNoExecutionPrompt, isReadOnlyOrExplanatoryPrompt, readOnlyScopeError } from './launchIntent.js';
@@ -188,9 +202,12 @@ export interface AgentLoopApprovalScope {
188
202
  export interface AgentLoopOptions {
189
203
  workspaceRoot?: string;
190
204
  memorySessionId?: string | null;
205
+ ephemeralSession?: boolean;
191
206
  approvalScope?: AgentLoopApprovalScope;
192
207
  provider?: string;
193
208
  model?: string;
209
+ variant?: string;
210
+ peerMcpServers?: McpServer[] | undefined;
194
211
  }
195
212
 
196
213
  export {
@@ -208,7 +225,7 @@ export {
208
225
  function readMacDesktopPictures(): string | null {
209
226
  try {
210
227
  return execFileSync('osascript', ['-e', 'tell application "System Events" to get picture of every desktop'], {
211
- encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore']
228
+ encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, env: sanitizeSubprocessEnv(process.env)
212
229
  }).trim() || null;
213
230
  } catch {
214
231
  return null;
@@ -219,63 +236,22 @@ const SYSTEM_PROMPT = `You are Causyne Agent, an autonomous local AI agent. Your
219
236
 
220
237
  ${PEER_COLLABORATION_POLICY}
221
238
 
222
- # Your Capabilities
223
- Use only tools actually present and permitted in this session. Read each tool result before reporting an outcome. A user message that only asks a question or greets you may be answered directly without calling a tool.
224
-
225
239
  ${AGENT_USER_POLICY}
226
240
 
227
- # Project Conventions
228
- Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
229
-
230
- # Repository Structure, Project Docs & Existing Codebases First
231
- - When working inside an existing repository or project (indicated by Workspace Context key files, docs, build scripts, or subprojects), ALWAYS inspect the relevant project documentation (docs/, README.md), build scripts (scripts/, Makefile, package.json), and actual directory structure BEFORE modifying files or choosing a build/release command.
232
- - Do NOT blindly initialize template web files (index.html, style.css, app.js) or assume a task is a greenfield web app unless the user explicitly requested a new web project from scratch AND the target directory has no matching existing build/architecture.
233
- - Only skip root exploration when creating an explicitly requested brand-new greenfield project inside a dedicated new/empty directory.
234
-
235
- # Operational Guidelines & Communication
236
- - **Strict Mandatory English Only Directive**: Operate, reason, plan, and communicate STRICTLY and EXCLUSIVELY in the English language across all thoughts, plan steps, and responses, regardless of the language used in the user's prompt. The use of non-English languages (including Indonesian) is strictly and permanently forbidden anywhere in agent responses, plans, or thoughts.
237
- - **Ruthless Conciseness**: Answer concisely with fewer than 4 lines unless detail is requested. No preambles ("Okay, I will now...") or postambles ("I have finished..."). One-word answers are best for simple questions.
238
- - **Evidence-Based Recovery Reports**: State only observed tool results and checks. Never claim a failed task was fixed without a passing check. Keep failure reports brief; if the user requests a detailed report, write it to a Markdown file in their selected workspace and give its path instead of dumping it into chat.
239
- - **Status Updates**: For substantial work, give brief progress notes while using tools. Use a tool when it contributes to the task, and report what it actually returned.
240
- - **Clarify Only When Needed**: Make routine implementation choices yourself. Ask when an unresolved choice or missing user-only input genuinely blocks progress; continue independent work while waiting.
241
- - **No Chitchat**: Tools are for actions, text output is *only* for communication. Do not add explanatory comments within tool calls or code blocks.
242
- - **File Paths**: ALWAYS output the absolute path of any file you create, modify, or generate so the user knows exactly where it is.
243
-
244
- # Task Management & Planning
245
- - Use update_plan to create a visible implementation checklist before complex implementation. Create atomic, verb-led, verifiable steps in English and keep exactly one step in progress.
246
- - Return known tool calls together when their arguments are already available. Calls execute in order: a checklist update, file write, and readback of that path can share one response. Wait for results before choosing arguments that depend on their contents.
247
- - Check off completed TODOs immediately before reporting progress. Do not batch up multiple task completions.
248
- - Reconcile and close the todo list when all goal tasks are done. If the user asks you to implement, do not output a separate text-based plan. Just build and display the todo list.
249
-
250
- # Durable Decisions
251
- - Use request_decision when multiple materially different architecture, product, data, security, or workflow directions are valid. Give 2-4 concrete options with consequences; the UI adds a custom-answer choice.
252
- - A decision is separate from permission. Do not ask for routine implementation details that can be resolved from the repository. Even in Mode C, pause for an unresolved durable architecture decision before changing the system.
253
-
254
- # Efficient Tool Use
255
- - Batch independent searches and reads when useful. Keep edits, dependent operations, approvals, and verification in a safe order. Never run conflicting writes concurrently.
256
-
257
- # Context Understanding & Searching
258
- - Semantic search (or grep) is your MAIN exploration tool. Start with a broad, high-level query.
259
- - Batch independent searches when the task needs them. Gather enough evidence to choose the next useful action; avoid repeating unchanged probes.
260
- - Expand research when uncertainty or a failed check justifies it. Keep exploration proportional to the user's goal.
261
-
262
- # Making Code Changes & Execution
263
- - **No Blind Patching**: Base edits on observed current file contents. Read again when the file changed or the observation is stale; reuse an unchanged verified observation across loop steps.
264
- - **Verification Loop**: NEVER assume code works. After making code changes, execute the project-specific build, linting, and type-checking commands (e.g., 'tsc', 'npm run lint', 'pytest'). Identify these commands by examining 'README' files or 'package.json'.
265
- - **Code Quality**: Write HIGH-VERBOSITY code. Optimize for clarity. Use meaningful variable names (no 1-letter names like 'n'). Use guard clauses/early returns. Avoid deep nesting.
266
- - **No TODOs/Comments**: Do not add comments for trivial code. NEVER use inline comments. Avoid TODO comments—implement the logic instead.
267
- - **Runnable Code**: Ensure generated code can be run immediately. Add all necessary imports, dependencies, and scaffolding (e.g. requirements.txt) if building from scratch.
268
-
269
- # Git Workflow & Best Practices
270
- - When asked to commit changes, use strictly a plain, ultra-short single-word or minimal tag (e.g. 'fix', 'update', 'build'). Never write descriptive sentences, feature narratives, bullet points, or commentary in git commit messages or push sections.
271
- - Zero feature explanations or commentary on commit subject lines.
272
-
273
- # Security & Constraints (Causyne Architecture)
274
- - **Token Budgeting**: You must respect the user's BYOK (Bring Your Own Key) limits. Be highly token-efficient.
275
- - **Explain Critical Commands**: Before executing destructive shell commands, provide a brief explanation of the impact.
276
- - **Interactive Commands**: Avoid shell commands that require user interaction (e.g., \`git rebase -i\`). Use non-interactive flags (e.g., \`-y\`).
277
- - **Sandboxing**: Keep workspace checks and hard safety blocks active. In Mode C, ordinary in-scope edits and tool calls do not need approval; deleting an entire file or directory does. Removing or replacing lines while editing a file is not whole-file deletion.
278
- - **SSRF Protection**: Do not fetch cloud metadata services (169.254.169.254, metadata.google.internal) or private LAN ranges. Local development servers on loopback (localhost, 127.0.0.1, ::1) are authorized for local web/app verification.
241
+ # Operational Guidelines & Engineering Discipline
242
+ - **Language & Communication**: Communicate clearly in the user's language by default unless repository instructions (such as \`AGENTS.md\` or \`CAUSYNE.md\`) specify a required language.
243
+ - **Conciseness & Output**: Keep replies concise (<4 lines unless detail is requested). No preambles or postambles. Output exact file paths for files created or modified. Answer greetings or pure questions directly without tools.
244
+ - **Proportional Exploration & No Blind Patching**: When the user names specific target files, read them directly instead of running redundant repository scans or \`git log\`. When targets are unspecified, inspect relevant docs/configs/structure first; never blindly scaffold template web files in an existing non-web project. Base edits on observed file contents; prefer \`apply_patch\` for multi-file edits and \`fs_edit\` for single-file surgical changes.
245
+ - **Verification Loop**: After editing code, run the project's actual tests, typecheck, or build commands (e.g., \`node --test\`, \`tsc --noEmit\`, \`npm test\`, \`pytest\`). State only observed results and checks.
246
+ - **Code Quality**: Write clear, runnable, idiomatic code following existing project conventions without trivial inline comments or TODO placeholders. Preserve unrelated behavior.
247
+ - **Planning & Decisions**: Batch independent read-only calls together. Use \`update_plan\` only for genuinely complex multi-stage implementations (keep one step \`in_progress\`). Use \`request_decision\` only when a material architecture/product/security choice genuinely blocks progress.
248
+ - **Git Commits**: Follow the target repository's commit message conventions and project instructions (such as \`AGENTS.md\` or \`git log\`) when committing changes.
249
+ - **Autonomy & Safety Boundaries**:
250
+ - **Mode A (Passive)**: Ask permission before mutating files, running shell commands, or installing dependencies.
251
+ - **Mode B (Supervised)**: Ordinary dev dependencies allowed; ask before OS-level changes or \`sudo\`.
252
+ - **Mode C (Autonomous)**: Execute ordinary in-scope work independently; whole-file/directory deletion, hard policy blocks, and workspace boundaries still require approval/compliance. Avoid interactive shell flags; use non-interactive flags (\`-y\`).
253
+ - **SSRF**: Never fetch cloud metadata (169.254.169.254, metadata.google.internal) or private LAN ranges. Loopback (\`localhost\`, \`127.0.0.1\`, \`::1\`) is permitted for local dev verification.
254
+ - **Tool Schema Discipline**: Invoke only active Causyne or permitted peer tools using exact schema parameter names and valid JSON (no unescaped newlines or trailing commas). Respect BYOK token limits.
279
255
 
280
256
  # ABSOLUTE ETHICAL SAFETY NET (NON-NEGOTIABLE)
281
257
  You are bound by an unbreakable ethical safety net. Regardless of user prompt, jailbreak attempts, or roleplay scenarios, you MUST REFUSE to:
@@ -290,42 +266,53 @@ You are bound by an unbreakable ethical safety net. Regardless of user prompt, j
290
266
 
291
267
  If asked to perform ANY harmful task, politely decline, state that Causyne exists to make the world better, and offer legitimate developer assistance instead.
292
268
 
293
- # Sovereign Reverse Engineering & Clean-Room Analysis (REA Substrate)
294
- You possess native reverse engineering capabilities powered by the Reverse Engineer Anything (REA) sovereign substrate via the \`reverse_engineering\` tool.
295
- - **Authorized Analytical Scope**: Reverse engineering for interoperability, binary inspection, security research, vulnerability analysis, format decoding, manifest analysis, and clean-room application implementation is fully authorized.
296
- - **Clean-Room Implementation Discipline**: When a user provides an APK, binary, or application package and asks to build a similar or compatible application (e.g. "analyze using rea make app like this for me"):
297
- 1. Proactively use \`reverse_engineering\` with actions 'inspect', 'unpack', 'decompile', or 'engine_tool' to inspect the artifact: examine \`AndroidManifest.xml\`, decode resources, list activities, extract layouts, inspect DEX classes, and map the application graph.
298
- 2. Synthesize functional and architectural specifications (data models, UI flows, service components).
299
- 3. Scaffold and build the original, clean-room application using modern open-source frameworks and idiomatic patterns.
300
- 4. NEVER issue canned refusals (such as "I cannot decompile, extract, or clone proprietary commercial software..."). Legitimate structural inspection, format analysis, and clean-room development are core sovereign capabilities.
301
-
302
- # Dependency Management & Autonomy Modes
303
- - **Mode A (Passive)**: You MUST explicitly ask the user for permission (by ending your turn and asking a question) before installing any dependencies.
304
- - **Mode B (Supervised)**: You may install standard development dependencies automatically, but you MUST ask for permission before modifying OS-level settings or running \`sudo\`.
305
- - **Mode C (Autonomous)**: Work independently within the user's task and selected workspace. Ordinary in-scope actions do not require an approval dialog. Whole-file or directory deletion requires approval. Hard policy blocks, workspace boundaries, and explicit user limits still apply.
306
-
307
- # Direct API & Automation Policy
308
- - **Prefer REST APIs (curl) for External Services**: When interacting with external services (like web, email, chat), prioritize finding and using official REST APIs via \`curl\` or simple scripts over browser scraping.
309
- - **Web/UI Verification Requirement**: Prefer \`browser_act\` preview for static workspace HTML and ES modules; it does not need a separate HTTP server. Use \`sysRunBg\` only when a real application server is required. Do not kill unrelated processes to claim a port. For web development, UI components, and frontend applications, ALWAYS verify your rendered output before concluding. Use \`browser_act\` (preview and snapshot) or \`screenshot\`/\`vision_inspect_ui\` to inspect the visual/DOM state of your web pages. Report DOM inspection separately from visual inspection; only claim visual inspection when you actually receive and inspect image pixels.
310
-
311
- # Execution Environment & Toolchains in sysRun
312
- - Subprocesses executed via \`sysRun\` have an enriched toolchain environment automatically configured:
313
- 1. **Android SDK**: \`ANDROID_HOME\`, \`ANDROID_SDK_ROOT\`, \`platform-tools\` (\`adb\`), \`cmdline-tools\`, \`emulator\`, and \`build-tools\` are already pre-configured in \`PATH\`. You do NOT need to prepend \`export PATH=...\`.
314
- 2. **Java JDK**: \`JAVA_HOME\` and JDK bin directories are automatically discovered and set in the environment. You do NOT need to prepend \`export JAVA_HOME=...\`.
315
- 3. **Local Binaries & Package Managers**: \`~/.local/bin\` (where official CLIs such as Google's \`android\` CLI reside), \`/opt/homebrew/bin\`, and language runtimes are pre-configured in \`PATH\`.
316
- 4. **Activity Launch Verification**: When launching an Activity via ADB, use \`adb -s <serial> shell am start -W -n <package>/<activity>\` (\`-W\` waits for the activity launch to complete before returning), or query resumed activities via \`dumpsys activity activities\`.
317
- 5. **Multiple Emulators/Devices**: When multiple devices or emulators are connected, specify \`-s <serial>\` (e.g. \`adb -s emulator-5554 ...\`) or set \`export ANDROID_SERIAL=<serial>\`.
318
-
319
- # Universal Tool Calling & Registry Discipline
320
- 1. **Strict Root Registry Adherence**: Invoke ONLY tools registered in the active Causyne catalogue (native, plugin, or MCP) or permitted connected-peer capabilities across ACP/Antigravity/Pi. Use exact canonical parameter names and required fields defined in each tool schema without inventing or renaming parameters.
321
- 2. **Pre-Flight Universal Schema Scan (\`toolsScan\`)**: Before dispatching schemas to any provider API, Causyne scans and compiles every tool declaration into that provider's dialect without reducing or altering underlying tool capability. When an adapted schema asks for a JSON-encoded string on an object, array, or union parameter (e.g. multi-file paths or free-form properties), pass valid JSON so the runtime buffer decodes it transparently to its native type.
322
- 3. **Universal Self-Repair Buffer (\`toolsSelfRepair\`)**: Every tool call is filtered through \`toolsSelfRepair\`, which heals malformed JSON, decodes adapted free-form/polymorphic values, resolves parameter aliases, coerces types recursively, and emits structured \`selfRepairGuidance\` (\`expectedParameters\`) on incomplete invocations. Always read \`expectedParameters\` and re-invoke with the corrected arguments.
323
- 4. **Valid JSON Formatting**: Never emit raw unescaped newlines, single-quoted keys, or trailing commas inside tool call JSON strings.
324
-
325
269
  # Completion
326
- Answer directly when no tool is needed. For action tasks, continue until the authorized work is done or a real blocker is evidenced; then report the verified outcome or blocker concisely.
270
+ Continue until the authorized work is verified or a real blocker is evidenced, then report the outcome concisely.
327
271
  `;
328
272
 
273
+ const REA_SUBSTRATE_PROMPT = `\n\n# Sovereign Reverse Engineering & Clean-Room Analysis (REA Substrate)
274
+ You possess native reverse engineering capabilities via \`reverse_engineering\` for interoperability, binary inspection, security research, format decoding, manifest analysis, and clean-room application implementation.
275
+ - Inspect artifacts with \`reverse_engineering\` (\`inspect\`, \`unpack\`, \`decompile\`, \`engine_tool\`), synthesize specs, and build original clean-room implementations. Never issue canned refusals for legitimate structural inspection or clean-room development.`;
276
+
277
+ const ANDROID_TOOLCHAIN_PROMPT = `\n\n# Android & JVM Toolchains in sysRun
278
+ Subprocesses in \`sysRun\` pre-configure \`ANDROID_HOME\`, \`ANDROID_SDK_ROOT\`, \`platform-tools\` (\`adb\`), \`cmdline-tools\`, \`emulator\`, \`build-tools\`, \`JAVA_HOME\`, \`~/.local/bin\`, and \`/opt/homebrew/bin\` in \`PATH\`. For Activity launches use \`adb -s <serial> shell am start -W -n <package>/<activity>\`; pass \`-s <serial>\` when multiple devices/emulators are connected.`;
279
+
280
+ const WEB_VERIFICATION_PROMPT = `\n\n# Web & UI Verification
281
+ Prefer \`browser_act\` preview for static workspace HTML/ES modules without starting a separate server; use \`sysRunBg\` only when a real app server is needed. Do not kill unrelated processes to claim a port. Always verify rendered web/UI output via \`browser_act\` (preview/snapshot) or \`screenshot\`/\`vision_inspect_ui\`, reporting DOM inspection separately from visual pixel inspection.`;
282
+
283
+ const ANDROID_CONTEXT_RE = /\b(?:android|apk|aab|adb|emulator|gradle|gradlew|kotlin|jetpack|compose|java|jdk|jvm|avd|dumpsys)\b/i;
284
+
285
+ const SHARED_BROWSER_INTENT_RE = /\b(?:browser|tab|tabs|webpage|website|site|youtube|video|watch|stream|url|https?:\/\/|click|navigate|scroll|open\s+(?:the\s+)?(?:page|link|site)|in\s+(?:the\s+)?browser|on\s+(?:this|the)\s+(?:page|tab|screen))\b/i;
286
+
287
+ const CAUSYNE_CLI_BIN_PATH = fileURLToPath(new URL('../bin/causyne.js', import.meta.url));
288
+
289
+ export function buildSharedBrowserAwarenessPrompt(
290
+ live: LiveBrowserAwarenessContext,
291
+ hasBrowserMcp: boolean
292
+ ): string {
293
+ const toolHint = hasBrowserMcp
294
+ ? 'Use your attached `causyne-browser` MCP tools (`browser_tabs`, `browser_read_page`, `browser_screenshot`, `browser_navigate`, `browser_interact`, `browser_extract`) directly as native tools (or `browser_act` if needed).'
295
+ : 'Use `browser_act` directly (actions: `snapshot`, `extract`, `screenshot`, `click`, `type`, `scroll`, `navigate`, `listTabs`).';
296
+ if (!live.active) {
297
+ return `\n\n◆ SHARED WORKSPACE BROWSER (IDLE — built-in live browser shared with the user beside chat): Causyne includes a real shared browser that both you and the user can operate together. ${toolHint} Opening or navigating a URL launches it automatically in the user's live Browser Panel.`;
298
+ }
299
+ const modeLabel = live.visible ? 'visible native OS window' : 'embedded live Browser Panel';
300
+ const engineLabel = live.engine || 'browser';
301
+ const tabLines = live.tabs.slice(0, 8).map((tab, idx) => {
302
+ const marker = tab.active ? ' [ACTIVE]' : '';
303
+ const titlePart = tab.title ? `"${tab.title.slice(0, 90)}" — ` : '';
304
+ return ` ${idx + 1}. (${tab.tabId})${marker} ${titlePart}${tab.url || 'about:blank'}`;
305
+ });
306
+ return [
307
+ `\n\n◆ SHARED WORKSPACE BROWSER (LIVE — shared directly with the user beside this chat):`,
308
+ `- Runtime: ${engineLabel} (${modeLabel}, viewport ${live.viewport.width}x${live.viewport.height})`,
309
+ `- Active tab: ${live.title ? `"${live.title.slice(0, 120)}" — ` : ''}${live.url || 'about:blank'} (tabId=${live.activeTabId || 'active'})`,
310
+ ...(tabLines.length > 0 ? [`- Open tabs (${live.tabs.length}):`, ...tabLines] : []),
311
+ `- Both you and the user see and operate this exact live browser. When the user refers to "the browser", "this page", "this tab", "this video", or asks to analyze/inspect/control what is currently open, inspect it immediately. ${toolHint}`,
312
+ `- To visually inspect layout, images, or video/motion in the open tab, call \`browser_screenshot\` (supports \`frames: 2..4\` for sequential motion/video frames) alongside \`browser_read_page\`. Never run dummy shell \`echo\` probes or claim you cannot see the browser.`
313
+ ].join('\n');
314
+ }
315
+
329
316
  function getProviderSpecificPrompt(provider: string = '') {
330
317
  const p = provider.toLowerCase();
331
318
 
@@ -458,12 +445,13 @@ export function skillSystemMessage(skill: any) {
458
445
 
459
446
 
460
447
  export function explainNetworkError(error: any, config: any = {}) {
448
+ const safeConfig = config && typeof config === 'object' ? config : {};
461
449
  const cause = error && error.cause;
462
- const code = (cause && (cause.code || cause.errno)) || '';
450
+ const code = String((cause && (cause.code || cause.errno)) || error?.code || error?.errno || '');
463
451
 
464
452
  let host = '';
465
453
  try {
466
- const raw = config.baseUrl && String(config.baseUrl).trim();
454
+ const raw = safeConfig.baseUrl && String(safeConfig.baseUrl).trim();
467
455
  if (raw) host = new URL(raw).host;
468
456
  } catch (e: any) { /* a malformed base URL is itself worth reporting, below */ }
469
457
 
@@ -478,15 +466,18 @@ export function explainNetworkError(error: any, config: any = {}) {
478
466
  EHOSTUNREACH: 'that host is unreachable from this network',
479
467
  ENETUNREACH: 'this machine has no route to the network',
480
468
  EPIPE: 'the connection closed mid-request',
469
+ UND_ERR_SOCKET: 'the upstream socket closed unexpectedly',
470
+ ECONNABORTED: 'the connection was aborted mid-request',
471
+ UND_ERR_BODY_TIMEOUT: 'the server response body stalled',
481
472
  CERT_HAS_EXPIRED: 'the TLS certificate has expired',
482
473
  DEPTH_ZERO_SELF_SIGNED_CERT: 'the TLS certificate is self-signed — a proxy may be intercepting',
483
474
  UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'the TLS certificate could not be verified — a proxy may be intercepting',
484
475
  SELF_SIGNED_CERT_IN_CHAIN: 'a self-signed certificate is in the chain — a proxy may be intercepting'
485
476
  };
486
477
 
487
- const reason = REASONS[code] || (code ? `the connection failed (${code})` : 'the connection failed');
478
+ const reason = (Object.hasOwn(REASONS, code) ? REASONS[code] : undefined) || (code ? `the connection failed (${code})` : 'the connection failed');
488
479
  const where = host ? ` reaching ${host}` : '';
489
- const provider = config.provider ? ` via ${config.provider}` : '';
480
+ const provider = safeConfig.provider ? ` via ${safeConfig.provider}` : '';
490
481
 
491
482
  const checks = [];
492
483
  if (code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'ENETUNREACH') {
@@ -514,6 +505,17 @@ class RetryConsentCheckpoint extends Error {
514
505
  constructor() { super('Peer paused after three failed attempts; explicit retry approval is required.'); }
515
506
  }
516
507
 
508
+ export function resolveToolsCatalogPromptBlock(
509
+ provider: unknown,
510
+ fullToolsListText: string
511
+ ): string {
512
+ const norm = String(provider || '').trim().toLowerCase();
513
+ if (norm === 'ollama') {
514
+ return 'Additional specialized tools are available on demand via tool_search(query).';
515
+ }
516
+ return fullToolsListText;
517
+ }
518
+
517
519
  export class AgentLoop {
518
520
  // Task state is assembled across the constructor and helpers below. This
519
521
  // signature keeps those reads and writes explicitly dynamic while each field
@@ -545,13 +547,21 @@ export class AgentLoop {
545
547
  this.modelOverride = typeof options.model === 'string' && options.model.trim()
546
548
  ? options.model.trim()
547
549
  : null;
550
+ this.variantOverride = typeof options.variant === 'string' && options.variant.trim()
551
+ ? options.variant.trim().toLowerCase()
552
+ : null;
548
553
  this.approvalScope = options.approvalScope && typeof options.approvalScope.isAlwaysAllowed === 'function'
549
554
  ? options.approvalScope
550
555
  : processApprovalScope;
556
+ this.peerMcpServers = Array.isArray(options.peerMcpServers)
557
+ ? [...options.peerMcpServers]
558
+ : [];
551
559
 
552
560
  this.config = loadConfig();
553
- if (this.providerOverride) this.config.provider = this.providerOverride;
554
- if (this.modelOverride) this.config.model = this.modelOverride;
561
+ applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
562
+ if (this.variantOverride) {
563
+ this.config.reasoningEffort = this.variantOverride;
564
+ }
555
565
  this.sandbox = new Sandbox({ workspaceRoot: this.workspaceRoot });
556
566
 
557
567
  // Retire spilled tool outputs past their retention window. Fire-and-forget
@@ -571,7 +581,9 @@ export class AgentLoop {
571
581
  this.tokenTracker = new TokenTracker();
572
582
 
573
583
  this.llm = this.initializeProvider();
574
- this.memoryManager = new MemoryManager(this.workspaceRoot, options.memorySessionId || null);
584
+ this.memoryManager = new MemoryManager(this.workspaceRoot, options.memorySessionId || null, {
585
+ ephemeral: options.ephemeralSession === true
586
+ });
575
587
  this.messages = this.memoryManager.loadHistory(); // Persistent context window
576
588
  this.stepsCompleted = 0;
577
589
  this.consecutiveCommands = 0;
@@ -600,7 +612,10 @@ export class AgentLoop {
600
612
  this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
601
613
  this.recentActionSignatures = [];
602
614
  this.consecutiveReadOnlySteps = 0;
603
- this.stallGuard = new StallGuardController();
615
+ this.stallGuard = new StallGuardController({
616
+ hardStopEnabled: true,
617
+ identicalCallHaltAfter: TIME_MACHINE_MAX_ATTEMPTS + 1
618
+ });
604
619
  this.smartToolsGovernor = new SmartToolsGovernor(4);
605
620
  this._smartToolsNudge = null;
606
621
  this.activeFreeFormPaths = new Map<string, string[][]>();
@@ -692,6 +707,9 @@ export class AgentLoop {
692
707
  this.approvalScope = createApprovalScope();
693
708
  this.autonomyOverride = null;
694
709
  this.circuitBreakerUnlocked = false;
710
+ for (const toolCallId of [...this.pendingApprovals.keys()]) {
711
+ this.handleApprovalResponse(toolCallId, false);
712
+ }
695
713
  this.pendingApprovals.clear();
696
714
  }
697
715
 
@@ -847,7 +865,7 @@ export class AgentLoop {
847
865
  }
848
866
 
849
867
  recordWebArtifact(candidate: unknown): void {
850
- if (typeof candidate !== 'string' || !isScannableFile(candidate)) return;
868
+ if (typeof candidate !== 'string' || candidate.length === 0 || candidate.length > 4096 || candidate.includes('\0') || !isScannableFile(candidate)) return;
851
869
  const lower = candidate.toLowerCase();
852
870
  // Exclude test files, spec files, python scripts, and backend code from invalidating web verification
853
871
  if (/\b(?:test|spec|bench|unittest)\b/i.test(lower) || /\.(py|sh|rb|go|rs|json|ya?ml|md|sql)$/i.test(lower)) {
@@ -866,8 +884,9 @@ export class AgentLoop {
866
884
  }
867
885
 
868
886
  recordInspectedWebFile(candidate: unknown): void {
869
- if (typeof candidate !== 'string' || !candidate.trim()) return;
870
- const matches = candidate.match(/[\w./-]+\.(?:html?|css|jsx|tsx|vue|svelte)\b/gi) || [candidate];
887
+ if (typeof candidate !== 'string' || !candidate.trim() || candidate.includes('\0')) return;
888
+ const scanText = candidate.length > 32768 ? candidate.slice(0, 32768) : candidate;
889
+ const matches = scanText.match(/[\w./-]+\.(?:html?|css|jsx|tsx|vue|svelte)\b/gi) || [scanText];
871
890
  for (const rawMatch of matches) {
872
891
  if (!isScannableFile(rawMatch)) continue;
873
892
  const expanded = rawMatch.startsWith('~/')
@@ -1001,7 +1020,14 @@ export class AgentLoop {
1001
1020
  this.debugLog(`episodic context build skipped: ${e.message}`);
1002
1021
  }
1003
1022
 
1004
- return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext };
1023
+ let projectInstructions = '';
1024
+ try {
1025
+ projectInstructions = formatProjectInstructionsPrompt(loadProjectInstructions(this.workspaceRoot));
1026
+ } catch (e: any) {
1027
+ this.debugLog(`project instructions load skipped: ${e.message}`);
1028
+ }
1029
+
1030
+ return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext, projectInstructions };
1005
1031
  }
1006
1032
 
1007
1033
 
@@ -1012,17 +1038,21 @@ export class AgentLoop {
1012
1038
  abort() {
1013
1039
  this.stopRequested = true;
1014
1040
  if (this.abortController) {
1015
- this.abortController.abort();
1041
+ try {
1042
+ this.abortController.abort();
1043
+ } catch {
1044
+ // An abort listener error must not prevent provider/approval teardown.
1045
+ }
1016
1046
  }
1017
1047
  if (this.llm && typeof (this.llm as any).abort === 'function') {
1018
1048
  try {
1019
- (this.llm as any).abort();
1049
+ void Promise.resolve((this.llm as any).abort()).catch(() => {});
1020
1050
  } catch {
1021
1051
  // ignore provider abort errors
1022
1052
  }
1023
1053
  } else if (this.llm && typeof (this.llm as any).close === 'function') {
1024
1054
  try {
1025
- void (this.llm as any).close();
1055
+ void Promise.resolve((this.llm as any).close()).catch(() => {});
1026
1056
  } catch {
1027
1057
  // ignore provider close errors
1028
1058
  }
@@ -1078,7 +1108,9 @@ export class AgentLoop {
1078
1108
 
1079
1109
  initializeProvider() {
1080
1110
  if (!this.config?.provider) return null;
1081
- return createProvider(this.config);
1111
+ const provider = createProvider(this.config);
1112
+ this._factoryLlmRef = provider;
1113
+ return provider;
1082
1114
  }
1083
1115
 
1084
1116
  /**
@@ -1149,6 +1181,17 @@ export class AgentLoop {
1149
1181
  }
1150
1182
  if (!validation || validation.allowed === false || validation.risk !== 'safe') continue;
1151
1183
 
1184
+ try {
1185
+ const enterpriseDecision = evaluateEnterprisePolicy({
1186
+ tool: functionName,
1187
+ args,
1188
+ workspaceRoot: this.workspaceRoot
1189
+ });
1190
+ if (enterpriseDecision.effect === 'deny' || enterpriseDecision.effect === 'ask') continue;
1191
+ } catch {
1192
+ continue;
1193
+ }
1194
+
1152
1195
  const tool = resolveTool(functionName);
1153
1196
  if (!tool || typeof tool.execute !== 'function') continue;
1154
1197
 
@@ -1191,6 +1234,9 @@ export class AgentLoop {
1191
1234
 
1192
1235
  /** Apply host policy to an ACP operation without disabling the peer itself. */
1193
1236
  private resolvePeerFilePath(file: string): string {
1237
+ if (typeof file !== 'string' || !file.trim() || file.includes('\0')) {
1238
+ throw new Error('ACP path was not authorized');
1239
+ }
1194
1240
  const target = path.resolve(this.workspaceRoot, file);
1195
1241
  let ancestor = target;
1196
1242
  while (true) {
@@ -1217,16 +1263,33 @@ export class AgentLoop {
1217
1263
  if (this.stopRequested || this.abortController.signal.aborted) return false;
1218
1264
  const validation = this.sandbox.validate(tool, args);
1219
1265
  if (!validation.allowed) return false;
1266
+ const enterpriseDecision = evaluateEnterprisePolicy({
1267
+ tool,
1268
+ args,
1269
+ workspaceRoot: this.workspaceRoot
1270
+ });
1271
+ if (enterpriseDecision.effect === 'deny') {
1272
+ auditLog.log({
1273
+ event: 'peer_operation_policy_denied',
1274
+ taskId: this.taskId,
1275
+ tool,
1276
+ rule: enterpriseDecision.matchedRule,
1277
+ dimension: enterpriseDecision.matchedDimension
1278
+ });
1279
+ return false;
1280
+ }
1220
1281
  const hook = await this.runPreToolUse(tool, args, id);
1221
1282
  if (hook?.denied) return false;
1222
1283
  const assessment = await coldObserver.evaluateMutation(tool, args, { workspaceRoot: this.workspaceRoot });
1223
1284
  if (assessment.veto) return false;
1224
1285
  const isModeC = (this.config.autonomyMode || 'C') === 'C';
1225
- const needsApproval = (!isModeC && uncertain) || requiresToolApproval({
1226
- mode: this.config.autonomyMode || 'C', tool, args,
1227
- risk: assessment.requiresConfirmation ? 'dangerous' : validation.risk,
1228
- heavyDownload: false, standingApproval: this.isAlwaysAllowed(tool)
1229
- });
1286
+ const needsApproval = enterpriseDecision.effect === 'ask'
1287
+ || (!isModeC && uncertain)
1288
+ || requiresToolApproval({
1289
+ mode: this.config.autonomyMode || 'C', tool, args,
1290
+ risk: assessment.requiresConfirmation ? 'dangerous' : validation.risk,
1291
+ heavyDownload: false, standingApproval: this.isAlwaysAllowed(tool)
1292
+ });
1230
1293
  if (needsApproval) {
1231
1294
  this.emitEvent({ type: 'approval_request', toolCallId: id, tool, args, risk: validation.risk });
1232
1295
  if (!await this.waitForApproval(id)) return false;
@@ -1237,14 +1300,28 @@ export class AgentLoop {
1237
1300
  }
1238
1301
 
1239
1302
  async requestPeerPermission(request: RequestPermissionRequest): Promise<RequestPermissionResponse['outcome']> {
1240
- const call = request.toolCall;
1303
+ const options = Array.isArray(request?.options) ? request.options : [];
1304
+ const allowOption = options.find(item => item?.kind === 'allow_once');
1305
+ const rejectOption = options.find(item => item?.kind === 'reject_once')
1306
+ ?? options.find(item => item?.kind === 'reject_always');
1307
+ const denyOutcome = (): RequestPermissionResponse['outcome'] => {
1308
+ if (this.stopRequested || this.abortController.signal.aborted) {
1309
+ return { outcome: 'cancelled' };
1310
+ }
1311
+ return rejectOption?.optionId
1312
+ ? { outcome: 'selected', optionId: rejectOption.optionId }
1313
+ : { outcome: 'cancelled' };
1314
+ };
1315
+
1316
+ const call = request?.toolCall;
1317
+ if (!call || typeof call !== 'object' || typeof call.toolCallId !== 'string' || !call.toolCallId.trim()) return denyOutcome();
1241
1318
  const raw = call.rawInput && typeof call.rawInput === 'object' && !Array.isArray(call.rawInput)
1242
1319
  ? call.rawInput as Record<string, unknown> : {};
1243
1320
  const args = { ...raw };
1244
1321
  if (!args.path && call.locations?.[0]?.path) args.path = call.locations[0].path;
1245
1322
  for (const field of ['path', 'file_path', 'filePath', 'filepath', 'absolutePath', 'cwd', 'source', 'destination', 'directory', 'targetFile', 'outputFile', 'outputPath']) {
1246
1323
  if (typeof args[field] === 'string') {
1247
- try { args[field] = this.resolvePeerFilePath(args[field] as string); } catch { return { outcome: 'cancelled' }; }
1324
+ try { args[field] = this.resolvePeerFilePath(args[field] as string); } catch { return denyOutcome(); }
1248
1325
  }
1249
1326
  }
1250
1327
  args.path ??= args.file_path ?? args.filePath ?? args.filepath ?? args.absolutePath;
@@ -1254,29 +1331,40 @@ export class AgentLoop {
1254
1331
  if (tool === 'sysRun' && !args.command && typeof args.cmd === 'string') args.command = args.cmd;
1255
1332
  const uncertain = !['read', 'search', 'fetch', 'think'].includes(call.kind || '')
1256
1333
  && (tool === 'peer_native' || (tool === 'sysRun' ? !args.command : !args.path));
1257
- const option = request.options.find(item => item.kind === 'allow_once');
1258
1334
  // Never propagate a standing peer grant across sessions or forks.
1259
- if (!option || !await this.authorizePeerOperation(tool, { ...args, peerTitle: call.title }, `peer:${call.toolCallId}`, uncertain)) {
1260
- return { outcome: 'cancelled' };
1335
+ if (!allowOption || !await this.authorizePeerOperation(tool, { ...args, peerTitle: call.title }, `peer:${call.toolCallId}`, uncertain)) {
1336
+ return denyOutcome();
1261
1337
  }
1262
- return { outcome: 'selected', optionId: option.optionId };
1338
+ return { outcome: 'selected', optionId: allowOption.optionId };
1263
1339
  }
1264
1340
 
1265
1341
  async executePeerFile(tool: 'fs_read' | 'fs_write', file: string, content?: string, options?: { line?: number; limit?: number }): Promise<string> {
1266
1342
  const target = this.resolvePeerFilePath(file);
1267
1343
  if (options?.line !== undefined && (!Number.isSafeInteger(options.line) || options.line < 1)) throw new Error('ACP line must be a positive integer');
1268
1344
  if (options?.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 1)) throw new Error('ACP limit must be a positive integer');
1345
+ if (options?.limit !== undefined && !Number.isSafeInteger((options.line || 1) + (options.limit - 1))) throw new Error('ACP line range exceeds the safe integer limit');
1269
1346
  const args = { path: target, ...(tool === 'fs_write' ? { content } : {}),
1270
1347
  ...(options?.line !== undefined ? { startLine: options.line } : {}),
1271
- ...(options?.limit !== undefined ? { endLine: (options.line || 1) + options.limit - 1 } : {}) };
1348
+ ...(options?.limit !== undefined ? { endLine: (options.line || 1) + (options.limit - 1) } : {}) };
1272
1349
  const id = `peer-file:${randomUUID()}:${tool}`;
1273
1350
  if (!await this.authorizePeerOperation(tool, args, id)) throw new Error('The requested ACP file operation was not authorized');
1351
+ this.resolvePeerFilePath(target);
1274
1352
  if (tool === 'fs_write') captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
1275
1353
  let result: { success: boolean; error?: string; output?: string };
1276
1354
  if (tool === 'fs_read') {
1277
1355
  // ACP expects the actual requested text, not the host tool's paging
1278
1356
  // warning appended to a silently shortened file.
1357
+ const lstat = fsSync.lstatSync(target);
1358
+ if (lstat.isSymbolicLink() && !this.sandbox.grantAllAccess) {
1359
+ const realTarget = physicalPath(target);
1360
+ const stillAllowed = realTarget !== null && this.sandbox.workspacePaths.some((root: string) => {
1361
+ const realRoot = physicalPath(root);
1362
+ return realRoot !== null && isWithinPhysicalPath(realTarget, realRoot);
1363
+ });
1364
+ if (!stillAllowed) throw new Error('ACP symlink target was not authorized by the selected workspace');
1365
+ }
1279
1366
  const stat = fsSync.statSync(target);
1367
+ if (!stat.isFile()) throw new Error('ACP read_text_file requires a regular file');
1280
1368
  if (stat.size > 4 * 1024 * 1024) throw new Error('ACP text file exceeds the 4 MiB client transfer limit');
1281
1369
  const bytes = fsSync.readFileSync(target);
1282
1370
  if (bytes.includes(0)) throw new Error('ACP read_text_file requires a text file');
@@ -1314,7 +1402,13 @@ export class AgentLoop {
1314
1402
  }
1315
1403
  }
1316
1404
  if (this.eventSink && this.eventSink.readyState === 1) {
1317
- this.eventSink.send(JSON.stringify({ taskId: this.taskId, ...messageObj }));
1405
+ let serialized: string;
1406
+ try {
1407
+ serialized = JSON.stringify({ taskId: this.taskId, ...messageObj });
1408
+ } catch {
1409
+ serialized = JSON.stringify({ taskId: this.taskId, type: String(messageObj?.type || 'notice') });
1410
+ }
1411
+ this.eventSink.send(serialized);
1318
1412
  }
1319
1413
  }
1320
1414
 
@@ -1339,15 +1433,17 @@ export class AgentLoop {
1339
1433
  */
1340
1434
  debugLog(message: string) {
1341
1435
  if (process.env.CAUSYNE_DEBUG !== '1') return;
1342
- process.stderr.write(`[causyne] ${message}\n`);
1436
+ // eslint-disable-next-line no-control-regex
1437
+ const clean = redactProviderSecrets(String(message ?? '')).replace(/[\x00-\x1f\x7f]+/g, ' ').slice(0, 4096);
1438
+ process.stderr.write(`[causyne] ${clean}\n`);
1343
1439
  }
1344
1440
 
1345
1441
 
1346
1442
  handleApprovalResponse(toolCallId: string, approved: boolean) {
1347
1443
  if (this.pendingApprovals.has(toolCallId)) {
1348
1444
  const resolve = this.pendingApprovals.get(toolCallId);
1349
- resolve(approved);
1350
1445
  this.pendingApprovals.delete(toolCallId);
1446
+ if (typeof resolve === 'function') resolve(approved === true);
1351
1447
  }
1352
1448
  }
1353
1449
 
@@ -1355,10 +1451,19 @@ export class AgentLoop {
1355
1451
  // A malformed provider plan is not permission to replace a valid plan or
1356
1452
  // crash an active run. Empty arrays remain valid and can clear the plan.
1357
1453
  if (!update || !Array.isArray(update.plan)) return;
1358
- const nextPlan = update.plan.map((item: any) => ({ ...item }));
1454
+ const nextPlan = update.plan
1455
+ .filter((item: unknown): item is Record<string, any> => Boolean(item) && typeof item === 'object')
1456
+ .map((item: Record<string, any>) => ({ ...item }));
1359
1457
  const prevText = this._implementationPlan.map((item: any) => item.step).join('\n');
1360
- const prevKey = JSON.stringify(this._implementationPlan.map((item: any) => ({ id: item.id, step: item.step, status: item.status })));
1361
- const nextKey = JSON.stringify(nextPlan.map((item: any) => ({ id: item.id, step: item.step, status: item.status })));
1458
+ const planKey = (entries: any[]): string => {
1459
+ try {
1460
+ return JSON.stringify(entries.map((item: any) => ({ id: item?.id, step: item?.step, status: item?.status })));
1461
+ } catch {
1462
+ return String(entries.length);
1463
+ }
1464
+ };
1465
+ const prevKey = planKey(this._implementationPlan);
1466
+ const nextKey = planKey(nextPlan);
1362
1467
  this._implementationPlan = nextPlan;
1363
1468
  if (options.seeded !== undefined) {
1364
1469
  this._implementationPlanSeeded = Boolean(options.seeded);
@@ -1509,15 +1614,21 @@ export class AgentLoop {
1509
1614
  }
1510
1615
 
1511
1616
  async requestDecision(request: any) {
1617
+ if (!request || typeof request !== 'object') return null;
1512
1618
  if (this.stopRequested || this.abortController?.signal?.aborted) return null;
1513
- const fingerprint = createHash('sha256')
1514
- .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option: any) => option.id) }))
1515
- .digest('hex');
1619
+ const safeOptions = Array.isArray(request.options) ? request.options : [];
1620
+ let fingerprintInput: string;
1621
+ try {
1622
+ fingerprintInput = JSON.stringify({ kind: request.kind, question: request.question, options: safeOptions.map((option: any) => option?.id ?? null) });
1623
+ } catch {
1624
+ fingerprintInput = `${String(request.kind || '')}:${String(request.question || '')}`;
1625
+ }
1626
+ const fingerprint = createHash('sha256').update(fingerprintInput).digest('hex');
1516
1627
  const remembered = request.ephemeral === true ? null : this._decisionAnswers.get(fingerprint);
1517
1628
  if (remembered) return remembered;
1518
1629
 
1519
1630
  this.emitEvent({ type: 'decision_request', request });
1520
- auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount: request.options.length });
1631
+ auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount: safeOptions.length });
1521
1632
  // CAUSYNE_ENTITLEMENT_V1: unresolved durable decisions do not consume fresh leases.
1522
1633
  this._entitlementGate?.pause();
1523
1634
  let answer: any;
@@ -1560,8 +1671,10 @@ export class AgentLoop {
1560
1671
  updateTierLimits() {
1561
1672
  this.config = loadConfig();
1562
1673
  if (this.autonomyOverride) this.config.autonomyMode = this.autonomyOverride;
1563
- if (this.providerOverride) this.config.provider = this.providerOverride;
1564
- if (this.modelOverride) this.config.model = this.modelOverride;
1674
+ applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
1675
+ if (this.variantOverride) {
1676
+ this.config.reasoningEffort = this.variantOverride;
1677
+ }
1565
1678
  if (typeof this.initializeProvider === 'function') {
1566
1679
  const nextProvider = this.initializeProvider();
1567
1680
  if (nextProvider) {
@@ -1991,14 +2104,56 @@ export class AgentLoop {
1991
2104
  });
1992
2105
  }
1993
2106
  } else if (att.type === 'document') {
2107
+ if (typeof att.name !== 'string' || typeof att.base64 !== 'string' || !att.base64.trim()) {
2108
+ this.notice('skipped malformed document attachment', 'warn');
2109
+ continue;
2110
+ }
1994
2111
  const fs = await import('fs');
1995
2112
  const path = await import('path');
1996
2113
  // Ensure unique name to prevent overwriting
1997
- const safeName = att.name.replace(/[^a-zA-Z0-9.\-_]/g, '_');
1998
- const writePath = path.join(this.workspaceRoot, safeName);
1999
- fs.writeFileSync(writePath, Buffer.from(att.base64, 'base64'));
2114
+ const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024;
2115
+ if (att.base64.length > Math.ceil(MAX_ATTACHMENT_BYTES * 4 / 3) + 64) {
2116
+ this.notice('skipped oversized document attachment (exceeds 16 MiB limit)', 'warn');
2117
+ continue;
2118
+ }
2119
+ const decodedBytes = Buffer.from(att.base64, 'base64');
2120
+ if (decodedBytes.length > MAX_ATTACHMENT_BYTES) {
2121
+ this.notice('skipped oversized document attachment (exceeds 16 MiB limit)', 'warn');
2122
+ continue;
2123
+ }
2124
+ const baseName = path.basename(att.name).replace(/[^a-zA-Z0-9.\-_]/g, '_').replace(/^\.+/, '');
2125
+ const safeName = (!baseName || baseName === '.' || baseName === '..') ? 'attachment.bin' : baseName.slice(0, 128);
2126
+ const realWorkspaceRoot = physicalPath(this.workspaceRoot);
2127
+ if (!realWorkspaceRoot) {
2128
+ this.notice('skipped document attachment: workspace root could not be resolved', 'warn');
2129
+ continue;
2130
+ }
2131
+ const ext = path.extname(safeName);
2132
+ const stem = ext ? safeName.slice(0, -ext.length) : safeName;
2133
+ let finalName = safeName;
2134
+ let writePath = '';
2135
+ let saved = false;
2136
+ for (let attempt = 0; attempt < 100; attempt++) {
2137
+ finalName = attempt === 0 ? safeName : `${stem}-${attempt}${ext}`;
2138
+ const candidatePath = path.join(realWorkspaceRoot, finalName);
2139
+ const resolvedCandidate = physicalPath(candidatePath);
2140
+ if (!resolvedCandidate || !isWithinPhysicalPath(resolvedCandidate, realWorkspaceRoot)) break;
2141
+ try {
2142
+ fs.writeFileSync(candidatePath, decodedBytes, { flag: 'wx', mode: 0o600 });
2143
+ writePath = candidatePath;
2144
+ saved = true;
2145
+ break;
2146
+ } catch (writeErr: unknown) {
2147
+ if ((writeErr as NodeJS.ErrnoException)?.code === 'EEXIST') continue;
2148
+ throw writeErr;
2149
+ }
2150
+ }
2151
+ if (!saved) {
2152
+ this.notice(`could not save attached document '${safeName}' safely without overwriting`, 'warn');
2153
+ continue;
2154
+ }
2000
2155
 
2001
- contentArray[0].text += `\n\n[SYSTEM NOTIFICATION: The user attached a document named '${safeName}'. It has been saved to your workspace at ./${safeName}. Please use your file reading tools to examine its contents.]`;
2156
+ contentArray[0].text += `\n\n[SYSTEM NOTIFICATION: The user attached a document named '${finalName}'. It has been saved to your workspace at ./${finalName}. Please use your file reading tools to examine its contents.]`;
2002
2157
  this.notice(`saved attached document to ${writePath}`);
2003
2158
  }
2004
2159
  }
@@ -2102,18 +2257,26 @@ export class AgentLoop {
2102
2257
  // replaced by a summary, so memory, disk and CPU all stay bounded.
2103
2258
 
2104
2259
  const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
2105
- const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool, {
2260
+ const rawCharPool = resolveCharPool(activeTier, this.config.maxCharPool, {
2106
2261
  provider: this.config.provider,
2107
2262
  model: this.config.model,
2108
2263
  overrideTokens: this.config.contextTokens || this.config.maxContextTokens
2109
2264
  });
2265
+ // Keep MAX_CHAR_POOL as the true model context ceiling for accurate usage reporting,
2266
+ // while reserving 25% compaction headroom for system prompt, tool schemas, and output tokens.
2267
+ const MAX_CHAR_POOL = rawCharPool;
2268
+ const COMPACTION_CHAR_POOL = this.config.maxCharPool
2269
+ ? MAX_CHAR_POOL
2270
+ : Math.max(24_000, Math.floor(MAX_CHAR_POOL * 0.75));
2110
2271
 
2111
2272
  // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
2112
- // Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
2113
- // Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
2273
+ // Under low context pressure (<25% of pool), keep more recent small file reads
2274
+ // verbatim so models do not lose a 1-2 KB source file after four tool calls.
2275
+ const currentMessageChars = measureMessages(this.messages);
2276
+ const lowContextPressure = currentMessageChars < COMPACTION_CHAR_POOL * 0.25;
2114
2277
  const observationPrune = pruneStaleToolObservations(this.messages, {
2115
- keepRecent: this.config.keepRecentToolResults ?? 4,
2116
- minChars: 600,
2278
+ keepRecent: this.config.keepRecentToolResults ?? (lowContextPressure ? 12 : 4),
2279
+ minChars: lowContextPressure ? 2400 : 600,
2117
2280
  taskId: this.taskId
2118
2281
  });
2119
2282
  const argumentPrune = pruneExecutedToolArguments(this.messages, { taskId: this.taskId });
@@ -2124,7 +2287,7 @@ export class AgentLoop {
2124
2287
  for (const message of this.messages) {
2125
2288
  if (typeof message.spillPath === 'string') recoveryPaths.add(path.resolve(message.spillPath));
2126
2289
  }
2127
- const compaction = applyProgressiveCompaction(this.messages, MAX_CHAR_POOL, {
2290
+ const compaction = applyProgressiveCompaction(this.messages, COMPACTION_CHAR_POOL, {
2128
2291
  // historyPruner preserves full output before eliding it. The legacy
2129
2292
  // decay path cannot promise that recovery, so keep it disabled here.
2130
2293
  enableEphemeralDecay: false,
@@ -2153,7 +2316,7 @@ export class AgentLoop {
2153
2316
  });
2154
2317
  }
2155
2318
 
2156
- const { window: slidingWindow, splitIndex } = buildWindow(this.messages, MAX_CHAR_POOL);
2319
+ const { window: slidingWindow, splitIndex } = buildWindow(this.messages, COMPACTION_CHAR_POOL);
2157
2320
 
2158
2321
  // What the context window actually holds right now.
2159
2322
  //
@@ -2169,19 +2332,19 @@ export class AgentLoop {
2169
2332
  this._contextChars = measureMessages(slidingWindow);
2170
2333
  this._contextLimitChars = MAX_CHAR_POOL;
2171
2334
 
2172
- // Real compaction: physically collapse the amputated range so the array
2173
- // stops growing. Index 0 (the Root Anchor / original user intent) is
2174
- // never compacted away.
2335
+ // Real compaction: physically collapse the amputated range at a turn-safe
2336
+ // boundary so role=tool results are never orphaned from their tool_calls.
2175
2337
  if (splitIndex >= 1) {
2176
- const dropped = this.messages.slice(1, splitIndex + 1);
2177
- if (dropped.length > 0) {
2338
+ const safeSplit = findSafeCompactionSplitIndex(this.messages, splitIndex);
2339
+ const dropped = safeSplit >= 1 ? this.messages.slice(1, safeSplit + 1) : [];
2340
+ if (dropped.length > 0 && safeSplit >= 1) {
2178
2341
  const compactSummary = buildRecoverableDroppedSummary(
2179
2342
  dropped,
2180
2343
  buildCodexStyleSummary(dropped, this.currentTaskPrompt || this.userPrompt)
2181
2344
  || buildStructuralSummary(dropped)
2182
2345
  || describeDroppedMessages(dropped)
2183
2346
  );
2184
- const removed = compactInPlace(this.messages, splitIndex, compactSummary);
2347
+ const removed = compactInPlace(this.messages, safeSplit, compactSummary);
2185
2348
  this._lastCompactionIndex = null;
2186
2349
  this.debugLog(`compacted ${removed} messages out of the live context`);
2187
2350
  auditLog.log({
@@ -2217,8 +2380,15 @@ export class AgentLoop {
2217
2380
  deniedTools: this.config.deniedTools
2218
2381
  });
2219
2382
  await this.ensureToolsList(eligibleTools);
2383
+ const promptForDomain = this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '';
2384
+ const liveBrowserAwareness = causyneBrowser({ workspace: this.workspaceRoot }).getLiveAwarenessContext();
2385
+ const sharedBrowserRelevant = liveBrowserAwareness.active || SHARED_BROWSER_INTENT_RE.test(promptForDomain);
2386
+ if (sharedBrowserRelevant) {
2387
+ this.savedTools.admitTool('browser_act');
2388
+ }
2220
2389
  const permittedTools = this.toolScope instanceof Set && this.toolScope.size > 0
2221
- ? eligibleTools.filter((tool: { name: string }) => this.toolScope.has(tool.name)) : eligibleTools;
2390
+ ? eligibleTools.filter((tool: { name: string }) => this.toolScope.has(tool.name) || (sharedBrowserRelevant && tool.name === 'browser_act'))
2391
+ : eligibleTools;
2222
2392
  const dynamicTools = this.smartTools.schemas(permittedTools, this.unlockedTools, this.unlockedPacks,
2223
2393
  this.config.grantAllTools === true);
2224
2394
  const dynamicToolNames = dynamicTools.map((t: any) => t.name);
@@ -2245,20 +2415,27 @@ export class AgentLoop {
2245
2415
  ? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
2246
2416
  : (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
2247
2417
  const baseProviderPrompt = getProviderSpecificPrompt(this.config.provider);
2248
- const sensoryAwareness = this.llm.supportsVision
2249
- ? `\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE
2250
- You have native multimodal vision perception. You can perceive rendered images, screenshots, and visual outputs directly.
2251
- - For Web, UI, 3D, and visual design tasks: You MUST visually verify your work (using browser_act snapshot/screenshot or view_image) and actively cross-reference visual output against the codebase.
2252
- - If visual rendering reveals visual bugs, layout misalignment, or runtime glitches, you must fix the code and re-verify before claiming completion.`
2253
- : `\n# SENSORY PROFILE: TEXT & CODE ENGINE (VISION INACTIVE)
2254
- You are operating in a text-and-code modality without direct image pixel rendering.
2255
- - For Web, UI, 3D, and visual tasks: Do NOT attempt raw visual inspection expecting image perception. Instead, verify programmatically:
2256
- 1. Inspect the rendered DOM structure, computed hierarchy, and elements via browser_act (scrape / snapshot).
2257
- 2. Check for JavaScript console and runtime errors (browser_act runtimeErrors).
2258
- 3. Validate syntax and runtime integrity with code_verify_syntax and unit tests.
2259
- 4. Perform thorough code inspection of generated math, physics, and canvas render loops to ensure zero defects.
2260
- - For non-visual tasks (backend, CLI, algorithms): Verify using standard test suites and execution logs.`;
2261
- const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}`;
2418
+ const domainArchetype = determineToolScope(promptForDomain, this.taskShape).archetype;
2419
+ const isVisualOrWebTask = isWebIntent(promptForDomain)
2420
+ || this.hasWebSurfaceArtifacts()
2421
+ || domainArchetype === 'web_engineering'
2422
+ || domainArchetype === 'game_development'
2423
+ || domainArchetype === 'media_3d_generation';
2424
+ const sensoryAwareness = isVisualOrWebTask
2425
+ ? (this.llm.supportsVision
2426
+ ? `\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE
2427
+ You have native multimodal vision perception. Visually verify Web, UI, and 3D work (via browser_act snapshot/screenshot or view_image), fix any visual/layout/runtime defects, and re-verify before concluding.`
2428
+ : `\n# SENSORY PROFILE: TEXT & CODE ENGINE (VISION INACTIVE)
2429
+ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeErrors), code_verify_syntax, and unit tests.`)
2430
+ : (this.llm.supportsVision
2431
+ ? '\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE'
2432
+ : '\n# SENSORY PROFILE: TEXT & CODE ENGINE — verify changes via project tests, typechecks, and execution logs.');
2433
+ const domainPrompts = [
2434
+ (this.unlockedPacks.has('reverse_engineering') || domainArchetype === 'reverse_engineering') ? REA_SUBSTRATE_PROMPT : '',
2435
+ (ANDROID_CONTEXT_RE.test(promptForDomain) || ANDROID_CONTEXT_RE.test(String(this.workspaceContext?.projectType || ''))) ? ANDROID_TOOLCHAIN_PROMPT : '',
2436
+ isVisualOrWebTask ? WEB_VERIFICATION_PROMPT : ''
2437
+ ].join('');
2438
+ const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}${domainPrompts}`;
2262
2439
  const memoryContext = getMemoryContextString({ workspaceRoot: this.workspaceRoot });
2263
2440
 
2264
2441
  // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
@@ -2270,7 +2447,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2270
2447
  if (!this.staticContext) {
2271
2448
  this.staticContext = await this.buildStaticContext();
2272
2449
  }
2273
- const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext } = this.staticContext;
2450
+ const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext, projectInstructions } = this.staticContext;
2274
2451
 
2275
2452
  // --- WORKSPACE AWARENESS ---
2276
2453
  // perception.buildContext() output used to be computed and discarded,
@@ -2373,6 +2550,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
2373
2550
  this.debugLog(`uncertainty gate skipped: ${e.message}`);
2374
2551
  }
2375
2552
 
2553
+ const effectivePeerMcpServers: McpServer[] = Array.isArray(this.peerMcpServers)
2554
+ ? [...this.peerMcpServers]
2555
+ : [];
2556
+ const hasConfiguredBrowserMcp = effectivePeerMcpServers.some((srv) => srv?.name === 'causyne-browser');
2557
+ if (!hasConfiguredBrowserMcp && isAcpProvider(this.config?.provider) && !process.env.NODE_TEST_CONTEXT) {
2558
+ effectivePeerMcpServers.push({
2559
+ name: 'causyne-browser',
2560
+ command: process.execPath,
2561
+ args: [CAUSYNE_CLI_BIN_PATH, 'browser-mcp', '--workspace', this.workspaceRoot],
2562
+ env: []
2563
+ });
2564
+ }
2565
+ const hasBrowserMcpAttached = effectivePeerMcpServers.some((srv) => srv?.name === 'causyne-browser');
2566
+ const sharedBrowserPrompt = buildSharedBrowserAwarenessPrompt(liveBrowserAwareness, hasBrowserMcpAttached);
2567
+
2568
+ const isLocalOllama = String(this.config?.provider || '').trim().toLowerCase() === 'ollama';
2569
+ const effectiveToolsListText = resolveToolsCatalogPromptBlock(
2570
+ this.config?.provider,
2571
+ this.toolsListText || renderToolsList(buildToolsList())
2572
+ );
2376
2573
  const systemMessages = [
2377
2574
  // [1] stable for the entire task — the primary cache anchor.
2378
2575
  { role: 'system', content: SYSTEM_PROMPT, cacheAnchor: true },
@@ -2380,7 +2577,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2380
2577
  // is stable within a task and gets its own breakpoint.
2381
2578
  {
2382
2579
  role: 'system',
2383
- content: `${taskBrief ? taskBrief + '\n\n' : ''}${this.toolsListText || renderToolsList(buildToolsList())}${activePlaybooks ? '\n\n' + activePlaybooks : ''}`,
2580
+ content: `${taskBrief ? taskBrief + '\n\n' : ''}${effectiveToolsListText}${activePlaybooks ? '\n\n' + activePlaybooks : ''}`,
2384
2581
  cacheAnchor: true
2385
2582
  },
2386
2583
  // [3] per-task STATIC context — provider activation, detected design,
@@ -2389,7 +2586,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2389
2586
  // is byte-identical every step; cached.
2390
2587
  {
2391
2588
  role: 'system',
2392
- content: `${providerPrompt}${designContext}${workspaceSummary}${lessonsLearned}${episodicContext ? '\n\n' + episodicContext : ''}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}\n${universalSkillsContext}`,
2589
+ content: `${providerPrompt}${designContext}${workspaceSummary}${projectInstructions || ''}${lessonsLearned}${!isLocalOllama && episodicContext ? '\n\n' + episodicContext : ''}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}${!isLocalOllama && universalSkillsContext ? '\n' + universalSkillsContext : ''}`,
2393
2590
  cacheAnchor: true
2394
2591
  },
2395
2592
  // [4] THE INVOKED SKILL, when the user named one.
@@ -2406,12 +2603,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
2406
2603
  // so it anchors too.
2407
2604
  ...(skillSystemMessage(this.activeSkill) || []),
2408
2605
  // [5] VOLATILE tail — the only bytes that may differ between steps:
2409
- // autonomy/workspace paths (change via config) and persistent memory
2410
- // (grows via memory_write mid-task). Kept LAST and UNcached so a change
2411
- // here never invalidates the cached prefix in [1]-[3].
2606
+ // autonomy/workspace paths (change via config), live shared browser
2607
+ // state, and persistent memory (grows via memory_write mid-task).
2608
+ // Kept LAST and UNcached so a change here never invalidates [1]-[3].
2412
2609
  {
2413
2610
  role: 'system',
2414
- content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)${memoryContext ? `\n\n◆ PERSISTENT MEMORY (workspace-relevant notes — actual repository files and docs on disk always override memory if anything conflicts):\n${memoryContext}` : ''}`
2611
+ content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)${sharedBrowserPrompt}${memoryContext ? `\n\n◆ PERSISTENT MEMORY (workspace-relevant notes — actual repository files and docs on disk always override memory if anything conflicts):\n${memoryContext}` : ''}`
2415
2612
  }
2416
2613
  ];
2417
2614
 
@@ -2559,6 +2756,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2559
2756
  const response = await this.llm.chat(prunedMessages, {
2560
2757
  taskId: this.taskId,
2561
2758
  conversationId: this.memoryManager?.sessionId || this.taskId,
2759
+ cacheKey: `causyne_${createHash('sha256').update(`${this.workspaceRoot}:${this.memoryManager?.sessionId || this.taskId}`).digest('hex').slice(0, 32)}`,
2562
2760
  taskIntent: isLaunchOnlyPrompt(this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
2563
2761
  taskArchetype: determineToolScope(this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
2564
2762
  hardBudget: hardBudget,
@@ -2578,6 +2776,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2578
2776
  ? remainingBudget : undefined,
2579
2777
  taskDeadlineMs: this._taskWallDeadlineAt ?? undefined,
2580
2778
  workspaceRoot: this.workspaceRoot,
2779
+ ...(effectivePeerMcpServers.length > 0 ? { peerMcpServers: effectivePeerMcpServers } : {}),
2581
2780
  onPeerPermission: (request: RequestPermissionRequest) => this.requestPeerPermission(request),
2582
2781
  onPeerFileRead: (file: string, options?: { line?: number; limit?: number }) => this.executePeerFile('fs_read', file, undefined, options),
2583
2782
  onPeerFileWrite: async (file: string, content: string) => { await this.executePeerFile('fs_write', file, content); },
@@ -2639,6 +2838,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2639
2838
  if (cleanProse && !cleanProse.startsWith('```')) {
2640
2839
  this.emitEvent({
2641
2840
  type: 'agent_message',
2841
+ streamId: invocation,
2642
2842
  content: cleanProse,
2643
2843
  delta: _chunk,
2644
2844
  streaming: true
@@ -2795,7 +2995,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
2795
2995
  });
2796
2996
  } else if (action.status === 'failed') {
2797
2997
  this.emitEvent({ type: 'status', message: '' });
2798
- this.emitEvent({ type: 'warning', message: `${this.config.provider || 'Provider'} could not ${action.name}${detail}` });
2998
+ this.emitEvent({
2999
+ type: 'warning',
3000
+ nativeStep: true,
3001
+ nativeFailed: true,
3002
+ actionName: action.name,
3003
+ detail: action.detail,
3004
+ message: `${this.config.provider || 'Provider'} could not ${action.name}${detail}`
3005
+ });
2799
3006
  }
2800
3007
  }
2801
3008
  }).catch((error: unknown) => {
@@ -2902,6 +3109,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2902
3109
  // the project's own CHAR_POOLS convention, instead of comparing a token
2903
3110
  // count to a character limit.
2904
3111
  const reportedPromptTokens = Number(response.usage?.promptTokens || 0);
3112
+ const reportedCompletionTokens = Number(response.usage?.completionTokens || 0);
2905
3113
  if (response.usage?.measurement === 'provider_reported'
2906
3114
  && response.usage?.measurementScope !== 'cumulative'
2907
3115
  && Number.isFinite(reportedPromptTokens)
@@ -2925,9 +3133,22 @@ You are operating in a text-and-code modality without direct image pixel renderi
2925
3133
  lifetimeCostUsd: tracking.lifetimeCostUsd || 0,
2926
3134
  contextChars: this._contextChars || 0,
2927
3135
  contextLimitChars: this._contextLimitChars || 0,
2928
- cachedTokens
3136
+ cachedTokens,
3137
+ inputTokens: Number.isFinite(reportedPromptTokens) && reportedPromptTokens > 0 ? reportedPromptTokens : 0,
3138
+ outputTokens: Number.isFinite(reportedCompletionTokens) && reportedCompletionTokens > 0 ? reportedCompletionTokens : 0
2929
3139
  });
2930
3140
 
3141
+ const taskCostCap = typeof (this as any).taskCostLimitUsd === 'number' && Number.isFinite((this as any).taskCostLimitUsd) && (this as any).taskCostLimitUsd > 0
3142
+ ? (this as any).taskCostLimitUsd as number
3143
+ : null;
3144
+ if (taskCostCap !== null && (tracking.taskCostUsd || 0) >= taskCostCap) {
3145
+ this.emitEvent({
3146
+ type: 'error',
3147
+ message: `Task USD budget limit reached ($${(tracking.taskCostUsd || 0).toFixed(4)} >= $${taskCostCap.toFixed(4)}).`
3148
+ });
3149
+ break;
3150
+ }
3151
+
2931
3152
  if (!tracking.allowed) {
2932
3153
  this.emitEvent({ type: 'error', message: tracking.reason });
2933
3154
  break;
@@ -3317,7 +3538,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3317
3538
  if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations < 3) {
3318
3539
  incompleteTurnContinuations++;
3319
3540
  if (response.content) {
3320
- this.emitEvent({ type: 'agent_message', content: response.content });
3541
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: response.content });
3321
3542
  }
3322
3543
  const blockedNote = failedExternalActions.length > 0
3323
3544
  ? ` Note: ${failedExternalActions.map((a: any) => `${a.name}${a.detail ? ` (${a.detail})` : ''}`).join(', ')} failed. Use their actual error results to choose the next step; honor user denials and the configured workspace policy without assuming a path-related cause.`
@@ -3337,7 +3558,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3337
3558
  if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations === 3) {
3338
3559
  incompleteTurnContinuations++;
3339
3560
  if (response.content) {
3340
- this.emitEvent({ type: 'agent_message', content: response.content });
3561
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: response.content });
3341
3562
  }
3342
3563
  this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
3343
3564
  this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
@@ -3362,7 +3583,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3362
3583
  .replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
3363
3584
  .trim();
3364
3585
  if (partial.length >= 20) {
3365
- this.emitEvent({ type: 'agent_message', content: partial });
3586
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: partial });
3366
3587
  }
3367
3588
  this.emitEvent({ type: 'error', message:
3368
3589
  'The peer ended with an incomplete or progress-only turn. ' +
@@ -3399,10 +3620,17 @@ You are operating in a text-and-code modality without direct image pixel renderi
3399
3620
  if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
3400
3621
  if (this.stepsCompleted > 0 && incompleteTurnContinuations < 2 && failedExternalActions.length === 0) {
3401
3622
  incompleteTurnContinuations++;
3402
- this.emitEvent({ type: 'status', message: 'Requesting the missing final response…' });
3403
- this.messages.push({ role: 'system', content:
3404
- '[FINAL RESPONSE REQUIRED] Report actual completed and incomplete work from tool results. ' +
3405
- 'Do not call plan steps or file writes proof of verification.' });
3623
+ if (isActionable && taskMutationCount === 0 && !isLaunchOnlyPrompt(taskPrompt) && !isPlanningOnlyRequest(taskPrompt)) {
3624
+ this.emitEvent({ type: 'status', message: 'Continuing execution after reasoning-only turn…' });
3625
+ this.messages.push({ role: 'system', content:
3626
+ '[CONTINUE EXECUTION] Your previous turn produced reasoning without invoking a tool or applying the requested changes. ' +
3627
+ 'Continue immediately by calling the appropriate tool (such as fs_edit, apply_patch, fs_write, or sysRun) to implement and verify the task.' });
3628
+ } else {
3629
+ this.emitEvent({ type: 'status', message: 'Requesting the missing final response…' });
3630
+ this.messages.push({ role: 'system', content:
3631
+ '[FINAL RESPONSE REQUIRED] Report actual completed and incomplete work from tool results. ' +
3632
+ 'Do not call plan steps or file writes proof of verification.' });
3633
+ }
3406
3634
  this.memoryManager.saveHistory(this.messages);
3407
3635
  continue;
3408
3636
  }
@@ -3777,6 +4005,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
3777
4005
  const finalToolOutcomes = coldObserver.getToolOutcomes(this.taskId);
3778
4006
  const finalToolOutcome = finalToolOutcomes[finalToolOutcomes.length - 1];
3779
4007
  if (this.stepsCompleted > 0 && finalToolOutcome && !finalToolOutcome.success) {
4008
+ const blockerExplanation = typeof response.content === 'string'
4009
+ ? response.content
4010
+ .replace(/^Antigravity executed:[^\n]*\n*/i, '')
4011
+ .replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
4012
+ .trim()
4013
+ : '';
4014
+ if (blockerExplanation.length >= 20) {
4015
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: blockerExplanation });
4016
+ }
3780
4017
  this.emitEvent({ type: 'error', message:
3781
4018
  `The last observed tool action failed (${finalToolOutcome.tool}). ` +
3782
4019
  'Resolve the error or report partial work; no success has been recorded.' });
@@ -3789,12 +4026,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
3789
4026
  const outcomes = coldObserver.getToolOutcomes(this.taskId);
3790
4027
  const hasCodeOrWorkspaceMutation = this.webArtifacts.size > 0 || outcomes.some((o: any) =>
3791
4028
  o.success !== false && [
3792
- 'fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit', 'multi_edit',
4029
+ 'fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit', 'multi_edit', 'apply_patch',
3793
4030
  'ui_forge', 'write_file', 'write_to_file', 'edit_file', 'replace_file_content',
3794
4031
  'multi_replace_file_content', 'native_engine', 'update_plan'
3795
4032
  ].includes(String(o.tool || ''))
3796
4033
  );
3797
- if (!hasCodeOrWorkspaceMutation && completedNativeActionIds.size === 0) {
4034
+ const rawReply = typeof response.content === 'string' ? response.content.trim() : '';
4035
+ const hasVerifiedFailureBlocker = outcomes.some((o: any) => o.success === false)
4036
+ && rawReply.length >= 25
4037
+ && /\b(?:blocked|cannot|unable|missing|permission denied|not installed|failed|error)\b/i.test(rawReply);
4038
+ if (!hasCodeOrWorkspaceMutation && completedNativeActionIds.size === 0 && !hasVerifiedFailureBlocker) {
3798
4039
  if (this._nonMutationNudges === undefined) this._nonMutationNudges = 0;
3799
4040
  if (this._nonMutationNudges < 2) {
3800
4041
  this._nonMutationNudges++;
@@ -3825,7 +4066,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3825
4066
 
3826
4067
  const substantiveTerminalContent = cleanTerminalContent(response.content);
3827
4068
  if (substantiveTerminalContent.length >= 20) {
3828
- this.emitEvent({ type: 'agent_message', content: substantiveTerminalContent });
4069
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: substantiveTerminalContent });
3829
4070
  } else {
3830
4071
  const recentSubstantive = [...this.messages].reverse().find(m =>
3831
4072
  m.role === 'assistant'
@@ -3849,7 +4090,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3849
4090
  content: `Task completed successfully.${planSummary}`
3850
4091
  });
3851
4092
  } else if (response.content) {
3852
- this.emitEvent({ type: 'agent_message', content: response.content });
4093
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: response.content });
3853
4094
  }
3854
4095
  }
3855
4096
  if (this.stepsCompleted > 0) {
@@ -4044,7 +4285,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4044
4285
  let actionSig = `${functionName}:${JSON.stringify(args || {})}`;
4045
4286
  if (functionName === 'sysRun' || functionName === 'sysRunBg') {
4046
4287
  const rawCmd = String(args?.command || '').trim();
4047
- if (/python[0-9.]*\s+.*import\s+numpy/i.test(rawCmd)) {
4288
+ if (/\bpython[0-9.]*\s/i.test(rawCmd) && /\bimport\s+numpy\b/i.test(rawCmd)) {
4048
4289
  actionSig = 'sysRun:probe:numpy';
4049
4290
  } else if (/python[0-9.]*\s+(--version|-V|-c\s+['"]print)/i.test(rawCmd)) {
4050
4291
  actionSig = 'sysRun:probe:python';
@@ -4329,21 +4570,84 @@ You are operating in a text-and-code modality without direct image pixel renderi
4329
4570
  // Cold observer mutation assessment fail-open
4330
4571
  }
4331
4572
 
4573
+ // Declarative enterprise policy (`causyne.policy.json`): deterministic
4574
+ // allow / ask / deny gate outside the model. Runs after Sandbox and Cold
4575
+ // Observer so it can never weaken workspace isolation or observer vetoes.
4576
+ const enterpriseDecision = evaluateEnterprisePolicy({
4577
+ tool: functionName,
4578
+ args,
4579
+ workspaceRoot: this.workspaceRoot
4580
+ });
4581
+ if (enterpriseDecision.effect === 'deny') {
4582
+ this.emitEvent({
4583
+ type: 'status',
4584
+ message: `Enterprise Policy Denied: ${enterpriseDecision.reason}`
4585
+ });
4586
+ auditLog.log({
4587
+ event: 'enterprise_policy_denied',
4588
+ taskId: this.taskId,
4589
+ tool: functionName,
4590
+ dimension: enterpriseDecision.matchedDimension,
4591
+ rule: enterpriseDecision.matchedRule,
4592
+ reason: enterpriseDecision.reason
4593
+ });
4594
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, {
4595
+ success: false,
4596
+ error: `[ENTERPRISE POLICY DENIED]: ${enterpriseDecision.reason}`
4597
+ });
4598
+ this.messages.push({
4599
+ role: 'tool',
4600
+ tool_call_id: toolCall.id,
4601
+ name: functionName,
4602
+ content: JSON.stringify({
4603
+ success: false,
4604
+ error: `[ENTERPRISE POLICY DENIED]: ${enterpriseDecision.reason}`
4605
+ })
4606
+ });
4607
+ continue;
4608
+ }
4609
+
4332
4610
  // A standing grant can avoid repeat prompts in supervised modes.
4333
4611
  // Mode C is autonomous for in-scope work. Whole-file deletion asks
4334
4612
  // unless this session explicitly granted the fs_delete tool; a broad
4335
4613
  // shell grant cannot authorize deletion. Sandbox denials and observer
4336
4614
  // vetoes have already run and are never lifted by prompt policy.
4337
4615
  const standingApproval = this.isAlwaysAllowed(functionName);
4338
- const needsToolApproval = requiresToolApproval({
4616
+ let needsToolApproval = requiresToolApproval({
4339
4617
  mode: this.config.autonomyMode || 'C',
4340
4618
  tool: functionName,
4341
4619
  args,
4342
4620
  risk: validation.risk,
4343
4621
  heavyDownload: isHeavyAiDownload,
4622
+ reason: validation.reason,
4344
4623
  standingApproval
4345
4624
  });
4346
- if (standingApproval && !needsToolApproval && this.config.autonomyMode !== 'C') {
4625
+ if (enterpriseDecision.effect === 'ask') {
4626
+ needsToolApproval = true;
4627
+ auditLog.log({
4628
+ event: 'enterprise_policy_ask',
4629
+ taskId: this.taskId,
4630
+ tool: functionName,
4631
+ dimension: enterpriseDecision.matchedDimension,
4632
+ rule: enterpriseDecision.matchedRule,
4633
+ reason: enterpriseDecision.reason
4634
+ });
4635
+ } else if (
4636
+ enterpriseDecision.effect === 'allow'
4637
+ && !isWholeFileDeletion(functionName, args)
4638
+ && !isHeavyAiDownload
4639
+ ) {
4640
+ needsToolApproval = false;
4641
+ auditLog.log({
4642
+ event: 'enterprise_policy_allowed',
4643
+ taskId: this.taskId,
4644
+ tool: functionName,
4645
+ dimension: enterpriseDecision.matchedDimension,
4646
+ rule: enterpriseDecision.matchedRule,
4647
+ reason: enterpriseDecision.reason
4648
+ });
4649
+ }
4650
+ if (standingApproval && !needsToolApproval && this.config.autonomyMode !== 'C' && enterpriseDecision.effect !== 'allow') {
4347
4651
  auditLog.log({
4348
4652
  event: 'approval_auto_granted', taskId: this.taskId,
4349
4653
  tool: functionName, risk: validation.risk, reason: 'allow_always'
@@ -4497,8 +4801,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
4497
4801
 
4498
4802
  this._networkHostGuard.after(functionName, args, result);
4499
4803
 
4500
- if (result && result.success !== false && !result.error && ['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
4501
- this.recordWebArtifact(args.path || args.file_path);
4804
+ if (result && result.success !== false && !result.error) {
4805
+ if (['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
4806
+ this.recordWebArtifact(args.path || args.file_path);
4807
+ } else if (functionName === 'apply_patch' && typeof args.patch === 'string') {
4808
+ for (const patchPath of extractPatchTargetPaths(args.patch).paths) {
4809
+ this.recordWebArtifact(patchPath);
4810
+ }
4811
+ }
4502
4812
  }
4503
4813
 
4504
4814
  if (result && result.success !== false && !result.error && ['fs_read', 'view_file', 'read_file'].includes(functionName)) {
@@ -4533,7 +4843,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4533
4843
  }
4534
4844
  }
4535
4845
 
4536
- if (result?.success === true && ['fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit'].includes(functionName)) clearSysRunCache();
4846
+ if (result?.success === true && ['fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit', 'apply_patch'].includes(functionName)) clearSysRunCache();
4537
4847
 
4538
4848
  // The journal is the observer's own record of what actually ran. It
4539
4849
  // is written only after post-hook review, so a formatter that rejects
@@ -4621,7 +4931,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4621
4931
 
4622
4932
  // Active Inference: Record step prediction error into VFE rolling tracker
4623
4933
  if (this.vfeTracker) {
4624
- const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool), functionName);
4934
+ const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool));
4625
4935
  const vfeOutcome = this.vfeTracker.recordStep({
4626
4936
  tool: functionName,
4627
4937
  success: stepSuccess,
@@ -4814,22 +5124,31 @@ You are operating in a text-and-code modality without direct image pixel renderi
4814
5124
  }
4815
5125
  }
4816
5126
 
4817
- // Fold identical bytes without treating them as proof of external state.
5127
+ // Fold identical bytes only when the earlier full observation is still
5128
+ // verbatim in active context (never blindfold a re-read of a decayed result).
4818
5129
  const OBSERVATION_FOLD_FLOOR = 600;
4819
5130
  if (resultString.length >= OBSERVATION_FOLD_FLOOR) {
4820
5131
  const digest = originalFingerprint;
4821
- const seenAt = this._observationDigests.get(digest);
4822
- if (seenAt !== undefined) {
5132
+ const seenRecord = this._observationDigests.get(digest) as { step: number; toolCallId: string } | undefined;
5133
+ const earlierStillVerbatim = Boolean(
5134
+ seenRecord && this.messages.some((msg: any) =>
5135
+ msg?.role === 'tool'
5136
+ && msg?.tool_call_id === seenRecord.toolCallId
5137
+ && typeof msg.content === 'string'
5138
+ && !msg.content.startsWith('[decayed]')
5139
+ )
5140
+ );
5141
+ if (seenRecord !== undefined && earlierStillVerbatim) {
4823
5142
  resultString = JSON.stringify({
4824
5143
  ...(result && typeof result.success === 'boolean' ? { success: result.success } : {}),
4825
5144
  identicalResult: true,
4826
- output: `The serialized tool response matches step ${seenAt}. This does not prove external state is unchanged. `
5145
+ output: `The serialized tool response matches step ${seenRecord.step}. This does not prove external state is unchanged. `
4827
5146
  + (spill
4828
5147
  ? `Full output is saved at ${spill.path}; read a relevant range if needed.`
4829
- : 'The earlier response may have left the active context; make a targeted read if its details are needed.')
5148
+ : 'The earlier response is still present in active context.')
4830
5149
  });
4831
5150
  } else {
4832
- this._observationDigests.set(digest, this.stepsCompleted + 1);
5151
+ this._observationDigests.set(digest, { step: this.stepsCompleted + 1, toolCallId: toolCall.id });
4833
5152
  }
4834
5153
  }
4835
5154
 
@@ -4894,16 +5213,19 @@ You are operating in a text-and-code modality without direct image pixel renderi
4894
5213
  // wall-clock limits, before deciding whether recovery is possible.
4895
5214
  if (e?.partialUsage) {
4896
5215
  const usage = e.partialUsage;
4897
- if (usage.promptTokens + usage.completionTokens > 0) {
5216
+ const promptTokens = Number.isFinite(Number(usage.promptTokens)) ? Math.max(0, Number(usage.promptTokens)) : 0;
5217
+ const completionTokens = Number.isFinite(Number(usage.completionTokens)) ? Math.max(0, Number(usage.completionTokens)) : 0;
5218
+ const cachedPromptTokens = Number.isFinite(Number(usage.cachedPromptTokens)) ? Math.max(0, Number(usage.cachedPromptTokens)) : 0;
5219
+ if (promptTokens + completionTokens > 0) {
4898
5220
  await this.tokenTracker.trackUsage(
4899
- usage.promptTokens, usage.completionTokens,
5221
+ promptTokens, completionTokens,
4900
5222
  (message: string) => this.emitEvent({ type: 'budget_warning', message }), usage
4901
5223
  );
4902
5224
  auditLog.log({
4903
5225
  event: 'model_usage', scope: 'agent_loop_primary', taskId: this.taskId,
4904
5226
  step: this.stepsCompleted, provider: this.config.provider || 'unknown',
4905
- promptTokens: usage.promptTokens, completionTokens: usage.completionTokens,
4906
- cachedPromptTokens: usage.cachedPromptTokens || 0,
5227
+ promptTokens, completionTokens,
5228
+ cachedPromptTokens,
4907
5229
  measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
4908
5230
  });
4909
5231
  }
@@ -4971,6 +5293,18 @@ You are operating in a text-and-code modality without direct image pixel renderi
4971
5293
  : 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
4972
5294
  break;
4973
5295
  }
5296
+ if (e?.code === 'ACP_PARTIAL_TURN') {
5297
+ const completed = Number.isSafeInteger(e.completedNativeActions) && e.completedNativeActions >= 0 ? e.completedNativeActions : 0;
5298
+ const unfinished = Number.isSafeInteger(e.unfinishedNativeActions) && e.unfinishedNativeActions >= 0 ? e.unfinishedNativeActions : 0;
5299
+ const partialText = typeof e.partialText === 'string' ? redactProviderSecrets(e.partialText).slice(0, 4000).trim() : '';
5300
+ if (partialText) this.messages.push({ role: 'assistant', content: partialText });
5301
+ this.messages.push({ role: 'system', content:
5302
+ `[Unfinished ACP task checkpoint] The peer connection ended after partial progress. Observed completed native actions in the interrupted turn: ${completed}; non-completed native actions: ${unfinished}. Prior assistant prose is not evidence of successful execution. Workspace effects may already exist. Reinspect affected files and verify outstanding work before any further mutations. Do not replay the interrupted turn or claim completion from this checkpoint.` });
5303
+ this.memoryManager.saveHistory(this.messages);
5304
+ this.emitEvent({ type: 'error', message: e.message });
5305
+ auditLog.log({ event: 'acp_partial_turn_checkpoint', taskId: this.taskId, completedNativeActions: completed, unfinishedNativeActions: unfinished, outcome: 'unverified' });
5306
+ break;
5307
+ }
4974
5308
  if (e?.code === 'PROVIDER_EMPTY_RESPONSE'
4975
5309
  || (typeof e?.message === 'string' && e.message.includes('returned no response'))) {
4976
5310
  if (emptyResponseRecoveries++ < 5) {
@@ -5024,15 +5358,34 @@ You are operating in a text-and-code modality without direct image pixel renderi
5024
5358
  // "Thinking" and the only signal was `network_error: fetch failed`
5025
5359
  // repeated in red. From the outside it is indistinguishable from
5026
5360
  // working, and it burns the user's step budget doing nothing.
5027
- const repeated = this.lastFailureType === errorType;
5028
- this.consecutiveFailures = repeated ? this.consecutiveFailures + 1 : 1;
5361
+ // Changing error classes is not successful progress.
5362
+ this.consecutiveFailures++;
5029
5363
  this.lastFailureType = errorType;
5030
5364
 
5365
+ const isContextOverflow = errorType === 'context_overflow';
5366
+ if (isContextOverflow) {
5367
+ const compactRes = compactSessionMessages(this.messages, {
5368
+ keepRecentTurns: Math.max(2, 6 - this.consecutiveFailures * 2),
5369
+ taskId: this.taskId,
5370
+ originalPrompt: this.currentTaskPrompt || this.userPrompt
5371
+ });
5372
+ if (compactRes.compacted) {
5373
+ this.notice(`Context limit exceeded — auto-compacted ${compactRes.removedCount} earlier messages (~${compactRes.reclaimedTokens} tokens reclaimed) and retrying.`);
5374
+ }
5375
+ }
5376
+
5031
5377
  const isNetwork = errorType === NETWORK_ERROR_TYPE;
5378
+ const isRateLimit = errorType === 'rate_limit';
5379
+ const maxAttempts = isRateLimit ? 5 : AgentLoop.MAX_CONSECUTIVE_FAILURES;
5032
5380
  const detail = isNetwork ? explainNetworkError(e, this.config) : e.message;
5033
5381
  auditLog.log({ event: 'loop_error_recovered', taskId: this.taskId, error: e.message, errorType });
5034
5382
 
5035
- if (this.consecutiveFailures >= AgentLoop.MAX_CONSECUTIVE_FAILURES) {
5383
+ const exceededCeiling = isRateLimit
5384
+ ? this.consecutiveFailures >= maxAttempts
5385
+ : this.consecutiveFailures >= AgentLoop.MAX_CONSECUTIVE_FAILURES;
5386
+ if (exceededCeiling) {
5387
+ if (await this.tryZeroCostFailover(isNetwork, isRateLimit, errorType)) continue;
5388
+
5036
5389
  // Nothing is changing between attempts. Stop and say why, rather
5037
5390
  // than spinning until the budget is gone.
5038
5391
  this.emitEvent({
@@ -5048,23 +5401,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
5048
5401
  type: 'step_error',
5049
5402
  tool: 'agent_loop',
5050
5403
  error: `${detail}\n retrying (${this.consecutiveFailures} of `
5051
- + `${AgentLoop.MAX_CONSECUTIVE_FAILURES})`
5404
+ + `${maxAttempts})`
5052
5405
  });
5053
5406
 
5054
- // Back off before trying again. Hammering a failing endpoint as fast
5055
- // as the loop can spin turns a one-second blip into a burst of
5056
- // failures and gives the endpoint no chance to recover.
5057
- await this.backoff(this.consecutiveFailures);
5407
+ // Back off before trying again. Honor provider Retry-After / X-RateLimit-Reset
5408
+ // when present so free-tier 429 limits recover cleanly without hammering.
5409
+ const retryAfterMs = typeof e?.retryAfterMs === 'number' && Number.isFinite(e.retryAfterMs)
5410
+ ? e.retryAfterMs
5411
+ : undefined;
5412
+ await this.backoff(this.consecutiveFailures, retryAfterMs);
5058
5413
 
5059
5414
  // Only tell the MODEL about errors the model can act on. It cannot
5060
- // fix DNS or a firewall, and a system message per attempt grows the
5061
- // context — and the bill — for nothing.
5415
+ // fix DNS, firewalls, HTTP 429 rate limits, or context overflow (already compacted).
5062
5416
  if (!isNetwork) {
5063
- this.messages.push({
5064
- role: 'system',
5065
- content: `[SYSTEM ERROR RECOVERED: A ${errorType} error occurred: "${e.message}". `
5066
- + 'The loop has recovered. You may continue or try a different approach.]'
5067
- });
5417
+ if (!isRateLimit && !isContextOverflow) {
5418
+ this.messages.push({
5419
+ role: 'system',
5420
+ content: `[SYSTEM ERROR RECOVERED: A ${errorType} error occurred: "${e.message}". `
5421
+ + 'The loop has recovered. You may continue or try a different approach.]'
5422
+ });
5423
+ }
5068
5424
  }
5069
5425
  }
5070
5426
  }
@@ -5077,7 +5433,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
5077
5433
 
5078
5434
  async waitForApproval(toolCallId: string): Promise<boolean> {
5079
5435
  const signal = this.abortController?.signal;
5080
- if (this.stopRequested || signal?.aborted) return false;
5436
+ if (this.stopRequested || signal?.aborted || typeof toolCallId !== 'string' || !toolCallId.trim() || this.pendingApprovals.has(toolCallId)) return false;
5081
5437
  this._entitlementGate?.pause();
5082
5438
  try {
5083
5439
  return await new Promise<boolean>((resolve) => {
@@ -5108,8 +5464,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
5108
5464
  * Exponential, capped. Without the abort check a user pressing esc during a
5109
5465
  * backoff would wait out the full delay before anything responded.
5110
5466
  */
5111
- async backoff(attempt: number) {
5112
- const delay = Math.min(8000, 500 * Math.pow(2, Math.max(0, attempt - 1)));
5467
+ async backoff(attempt: number, retryAfterMs?: number) {
5468
+ let delay: number;
5469
+ if (typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
5470
+ const jitter = Math.min(250, Math.floor(retryAfterMs * 0.1));
5471
+ delay = Math.min(60_000, Math.max(50, Math.round(retryAfterMs) + jitter));
5472
+ } else {
5473
+ delay = Math.min(8000, 500 * Math.pow(2, Math.max(0, attempt - 1)));
5474
+ }
5113
5475
  await waitForAbortableDelay(delay, this.abortController?.signal);
5114
5476
  }
5115
5477
 
@@ -5151,4 +5513,54 @@ You are operating in a text-and-code modality without direct image pixel renderi
5151
5513
  validateToolArgs(toolName: string, args: any) {
5152
5514
  return validateAndNormalizeToolArgs(toolName, args, this.workspaceRoot || process.cwd());
5153
5515
  }
5516
+
5517
+ private async tryZeroCostFailover(isNetwork: boolean, isRateLimit: boolean, errorType: string): Promise<boolean> {
5518
+ const canAttemptZeroCostFailover = (isRateLimit || isNetwork)
5519
+ && isZeroCostFailoverEligible(this.config?.provider, this.config?.model)
5520
+ && (this.config?.zeroCostFailover === true || (this._factoryLlmRef != null && this._factoryLlmRef === this.llm));
5521
+ if (!canAttemptZeroCostFailover) return false;
5522
+
5523
+ const triedSet: Set<string> = ((this as any)._zeroCostTriedProviders ||= new Set<string>());
5524
+ triedSet.add(normalizeZeroCostId(this.config?.provider));
5525
+ const nextRoute = await selectNextZeroCostRoute({
5526
+ currentProvider: String(this.config?.provider || ''),
5527
+ currentModel: String(this.config?.model || ''),
5528
+ triedProviders: triedSet,
5529
+ config: this.config,
5530
+ reason: isNetwork ? 'network_error' : 'rate_limit',
5531
+ ...(Array.isArray((this as any).zeroCostFailoverCandidates)
5532
+ ? { candidates: (this as any).zeroCostFailoverCandidates }
5533
+ : {})
5534
+ });
5535
+ if (!nextRoute) return false;
5536
+
5537
+ const prevProvider = String(this.config?.provider || '');
5538
+ triedSet.add(normalizeZeroCostId(nextRoute.provider));
5539
+ this.config = {
5540
+ ...this.config,
5541
+ provider: nextRoute.provider,
5542
+ model: nextRoute.model,
5543
+ apiKey: nextRoute.apiKey
5544
+ };
5545
+ delete this.config.baseUrl;
5546
+ this.llm = this.initializeProvider();
5547
+ this._utilityLlm = null;
5548
+ this.consecutiveFailures = 0;
5549
+ this.lastFailureType = null;
5550
+ auditLog.log({
5551
+ event: 'zero_cost_failover',
5552
+ taskId: this.taskId,
5553
+ fromProvider: prevProvider,
5554
+ toProvider: nextRoute.provider,
5555
+ toModel: nextRoute.model,
5556
+ costTier: nextRoute.costTier,
5557
+ reason: errorType
5558
+ });
5559
+ this.notice(
5560
+ `Zero-cost failover ($0): switched from ${prevProvider} to ${nextRoute.provider}`
5561
+ + (nextRoute.model ? ` (${nextRoute.model})` : '')
5562
+ + ` after ${errorType}.`
5563
+ );
5564
+ return true;
5565
+ }
5154
5566
  }