@causyne/agent 1.20.122 → 1.20.127

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (641) hide show
  1. package/bin/causyne.js +38 -15
  2. package/docs/SECURITY_REVIEW.md +42 -6
  3. package/package.json +7 -7
  4. package/src/acp/agentCatalog.js +74 -50
  5. package/src/acp/agentCatalog.ts +82 -49
  6. package/src/acp/client.js +309 -86
  7. package/src/acp/client.ts +291 -84
  8. package/src/acp/protocol.js +147 -3
  9. package/src/acp/protocol.ts +181 -4
  10. package/src/acp/server.js +418 -45
  11. package/src/acp/server.ts +404 -47
  12. package/src/agent/abortableDelay.js +2 -2
  13. package/src/agent/abortableDelay.ts +2 -2
  14. package/src/agent/errorClassifier.js +51 -7
  15. package/src/agent/errorClassifier.ts +52 -6
  16. package/src/agent/providerFailure.js +1 -1
  17. package/src/agent/providerFailure.ts +7 -1
  18. package/src/agent/toolArgValidator.js +38 -4
  19. package/src/agent/toolArgValidator.ts +39 -4
  20. package/src/agent/toolTurnIntegrity.js +28 -7
  21. package/src/agent/toolTurnIntegrity.ts +25 -6
  22. package/src/agent/workspaceBoundary.js +30 -4
  23. package/src/agent/workspaceBoundary.ts +32 -4
  24. package/src/agentLoop.js +673 -236
  25. package/src/agentLoop.ts +705 -233
  26. package/src/approvalPolicy.js +61 -10
  27. package/src/approvalPolicy.ts +69 -11
  28. package/src/auditLog.js +641 -48
  29. package/src/auditLog.ts +661 -0
  30. package/src/autoUpdate.js +32 -5
  31. package/src/autoUpdate.ts +27 -5
  32. package/src/backgroundTasks.js +328 -0
  33. package/src/backgroundTasks.ts +339 -0
  34. package/src/benchmarks/codingEval.js +558 -0
  35. package/src/benchmarks/codingEval.ts +628 -0
  36. package/src/benchmarks/planCache.js +115 -134
  37. package/src/benchmarks/planCache.ts +163 -0
  38. package/src/browser/browserRuntime.js +52 -0
  39. package/src/browser/browserRuntime.ts +55 -0
  40. package/src/browser/causyneBrowser.js +914 -13
  41. package/src/browser/causyneBrowser.ts +1075 -35
  42. package/src/browser/searchProviders.js +94 -6
  43. package/src/browser/searchProviders.ts +89 -6
  44. package/src/browser/urlPolicy.js +22 -2
  45. package/src/browser/urlPolicy.ts +19 -2
  46. package/src/browser/workspacePathSafety.js +6 -4
  47. package/src/browser/workspacePathSafety.ts +7 -4
  48. package/src/capabilities.js +18 -17
  49. package/src/capabilities.ts +38 -0
  50. package/src/checkpoints.js +1241 -1127
  51. package/src/checkpoints.ts +1377 -0
  52. package/src/cliMode.js +718 -754
  53. package/src/cliMode.ts +792 -0
  54. package/src/codebase/repoMap.js +656 -0
  55. package/src/codebase/repoMap.ts +664 -0
  56. package/src/commands.js +3806 -2513
  57. package/src/commands.ts +4162 -0
  58. package/src/compiledSkills.js +8052 -8054
  59. package/src/compiledSkills.ts +8078 -0
  60. package/src/config.js +118 -1
  61. package/src/config.ts +124 -1
  62. package/src/configVault.js +29 -2
  63. package/src/configVault.ts +26 -2
  64. package/src/contextManager.js +473 -557
  65. package/src/contextManager.ts +599 -0
  66. package/src/continuum/adapters/antigravity.js +8 -3
  67. package/src/continuum/adapters/antigravity.ts +8 -3
  68. package/src/continuum/sanitizer.js +23 -1
  69. package/src/continuum/sanitizer.ts +23 -1
  70. package/src/continuum/ui/continuumPicker.js +0 -2
  71. package/src/continuum/ui/continuumPicker.ts +0 -2
  72. package/src/continuum/ui/continuumPickerView.js +0 -2
  73. package/src/continuum/ui/continuumPickerView.ts +4 -20
  74. package/src/core/contextCompactor.js +142 -14
  75. package/src/core/contextCompactor.ts +150 -15
  76. package/src/core/goalLoop.js +257 -0
  77. package/src/core/goalLoop.ts +310 -0
  78. package/src/creative/liveBridge.js +3 -2
  79. package/src/creative/liveBridge.ts +4 -2
  80. package/src/creative/studioScripts.js +1 -1
  81. package/src/creative/studioScripts.ts +1 -1
  82. package/src/decideTools.js +7 -2
  83. package/src/decideTools.ts +7 -2
  84. package/src/decisionPolicy.js +10 -2
  85. package/src/decisionPolicy.ts +10 -2
  86. package/src/designPalettes.js +72 -84
  87. package/src/designPalettes.ts +111 -0
  88. package/src/devMode.js +2 -2
  89. package/src/devMode.ts +6 -0
  90. package/src/diffReview.js +370 -0
  91. package/src/diffReview.ts +407 -0
  92. package/src/dynamicCatalogue.js +311 -11
  93. package/src/dynamicCatalogue.ts +331 -11
  94. package/src/embodimentSession.js +143 -154
  95. package/src/embodimentSession.ts +173 -0
  96. package/src/engines/installer.js +60 -29
  97. package/src/engines/installer.ts +73 -22
  98. package/src/enterprisePolicy.js +660 -0
  99. package/src/enterprisePolicy.ts +728 -0
  100. package/src/entrypoint.js +646 -268
  101. package/src/entrypoint.ts +740 -0
  102. package/src/game/causyneCoreBridge.js +686 -0
  103. package/src/game/causyneCoreBridge.ts +702 -0
  104. package/src/game/gameLauncher.js +287 -0
  105. package/src/game/gameLauncher.ts +352 -0
  106. package/src/game/gameProvisioner.js +425 -0
  107. package/src/game/gameProvisioner.ts +488 -0
  108. package/src/gitSnapshot.js +417 -312
  109. package/src/gitSnapshot.ts +500 -0
  110. package/src/headlessCli.js +343 -25
  111. package/src/headlessCli.ts +343 -20
  112. package/src/hooks.js +247 -26
  113. package/src/hooks.ts +236 -26
  114. package/src/ignoreRules.js +297 -0
  115. package/src/ignoreRules.ts +308 -0
  116. package/src/implementationPlan.js +7 -6
  117. package/src/implementationPlan.ts +8 -6
  118. package/src/infra/atomicWriter.js +127 -18
  119. package/src/infra/atomicWriter.ts +141 -20
  120. package/src/launchIntent.js +85 -4
  121. package/src/launchIntent.ts +88 -4
  122. package/src/licensing/entitlements.js +553 -237
  123. package/src/licensing/entitlements.ts +590 -0
  124. package/src/licensing/policy.js +17 -1
  125. package/src/licensing/policy.ts +31 -0
  126. package/src/lsp/lspCatalog.js +398 -0
  127. package/src/lsp/lspCatalog.ts +452 -0
  128. package/src/lsp/lspClient.js +770 -0
  129. package/src/lsp/lspClient.ts +862 -0
  130. package/src/lsp/lspProtocol.js +121 -0
  131. package/src/lsp/lspProtocol.ts +140 -0
  132. package/src/mcp/mcpClient.js +69 -8
  133. package/src/mcp/mcpClient.ts +66 -9
  134. package/src/mcp/mcpRegistry.js +255 -15
  135. package/src/mcp/mcpRegistry.ts +241 -14
  136. package/src/mcp/mcpSecurity.js +6 -7
  137. package/src/mcp/mcpSecurity.ts +7 -6
  138. package/src/memory/contextBudget.js +2 -0
  139. package/src/memory/contextBudget.ts +1 -0
  140. package/src/memory/episodicStore.js +2 -5
  141. package/src/memory/episodicStore.ts +2 -5
  142. package/src/memory.js +80 -32
  143. package/src/memory.ts +111 -0
  144. package/src/memoryManager.js +151 -143
  145. package/src/memoryManager.ts +182 -0
  146. package/src/modelCatalogue.js +172 -195
  147. package/src/modelCatalogue.ts +201 -0
  148. package/src/modelIds.js +8 -27
  149. package/src/modelIds.ts +33 -0
  150. package/src/modelVariants.js +645 -0
  151. package/src/modelVariants.ts +717 -0
  152. package/src/observer/evidence.js +5 -1
  153. package/src/observer/evidence.ts +5 -1
  154. package/src/osKeychain.js +17 -9
  155. package/src/osKeychain.ts +14 -9
  156. package/src/outputRecovery.js +3 -2
  157. package/src/outputRecovery.ts +4 -2
  158. package/src/outputStore.js +210 -156
  159. package/src/outputStore.ts +321 -0
  160. package/src/permissionPresets.js +327 -0
  161. package/src/permissionPresets.ts +361 -0
  162. package/src/planCache.js +3 -6
  163. package/src/planCache.ts +3 -6
  164. package/src/plugins/pluginManager.js +689 -461
  165. package/src/plugins/pluginManager.ts +807 -0
  166. package/src/plugins/pluginRunner.js +82 -37
  167. package/src/plugins/pluginRunner.ts +98 -0
  168. package/src/plugins/pluginSkills.js +47 -9
  169. package/src/plugins/pluginSkills.ts +46 -8
  170. package/src/pluginsFactory/discovery.js +0 -1
  171. package/src/pluginsFactory/discovery.ts +0 -1
  172. package/src/pluginsFactory/templates.js +17 -4
  173. package/src/pluginsFactory/templates.ts +17 -4
  174. package/src/prWorkflow.js +337 -0
  175. package/src/prWorkflow.ts +376 -0
  176. package/src/procSignal.js +1 -2
  177. package/src/procSignal.ts +1 -3
  178. package/src/projectInstructions.js +319 -0
  179. package/src/projectInstructions.ts +361 -0
  180. package/src/providers/acp.js +234 -49
  181. package/src/providers/acp.ts +240 -50
  182. package/src/providers/anthropic.js +152 -47
  183. package/src/providers/anthropic.ts +152 -45
  184. package/src/providers/antigravity.js +620 -356
  185. package/src/providers/antigravity.ts +621 -357
  186. package/src/providers/base.js +9 -2
  187. package/src/providers/base.ts +10 -2
  188. package/src/providers/byokHttp.js +134 -18
  189. package/src/providers/byokHttp.ts +181 -19
  190. package/src/providers/byokStream.js +183 -44
  191. package/src/providers/byokStream.ts +179 -62
  192. package/src/providers/dashscope-byok.js +50 -8
  193. package/src/providers/dashscope-byok.ts +59 -13
  194. package/src/providers/deepseek.js +12 -3
  195. package/src/providers/deepseek.ts +12 -3
  196. package/src/providers/factory.js +41 -0
  197. package/src/providers/factory.ts +42 -0
  198. package/src/providers/gemini.js +74 -22
  199. package/src/providers/gemini.ts +78 -26
  200. package/src/providers/moonshot.js +60 -8
  201. package/src/providers/moonshot.ts +64 -14
  202. package/src/providers/muse.js +6 -0
  203. package/src/providers/muse.ts +8 -0
  204. package/src/providers/ollama.js +299 -21
  205. package/src/providers/ollama.ts +331 -29
  206. package/src/providers/openai-compatible.js +81 -12
  207. package/src/providers/openai-compatible.ts +89 -18
  208. package/src/providers/openai.js +87 -6
  209. package/src/providers/openai.ts +74 -6
  210. package/src/providers/openrouter.js +248 -66
  211. package/src/providers/openrouter.ts +243 -70
  212. package/src/providers/qwen-byok.js +50 -8
  213. package/src/providers/qwen-byok.ts +59 -13
  214. package/src/providers/wireNormalizer.js +66 -0
  215. package/src/providers/wireNormalizer.ts +64 -0
  216. package/src/providers/xai.js +31 -8
  217. package/src/providers/xai.ts +38 -14
  218. package/src/provisioning/capabilityConsent.js +29 -11
  219. package/src/provisioning/capabilityConsent.ts +42 -0
  220. package/src/provisioning/capabilityProvisioner.js +309 -197
  221. package/src/provisioning/capabilityProvisioner.ts +413 -0
  222. package/src/provisioning/capabilityTools.js +31 -17
  223. package/src/provisioning/capabilityTools.ts +43 -0
  224. package/src/provisioning/npmInstall.js +33 -5
  225. package/src/provisioning/npmInstall.ts +33 -5
  226. package/src/reporting.js +330 -326
  227. package/src/reporting.ts +484 -0
  228. package/src/sandbox.js +71 -0
  229. package/src/sandbox.ts +81 -0
  230. package/src/scheduler/scheduler.js +372 -0
  231. package/src/scheduler/scheduler.ts +433 -0
  232. package/src/sessionJournal.js +24 -3
  233. package/src/sessionJournal.ts +18 -3
  234. package/src/sessionSearchIndex.js +267 -0
  235. package/src/sessionSearchIndex.ts +311 -0
  236. package/src/sessionStore.js +1 -2
  237. package/src/sessionStore.ts +2 -0
  238. package/src/skillsManager.js +2 -3
  239. package/src/skillsManager.ts +2 -3
  240. package/src/slopDetector.js +202 -265
  241. package/src/slopDetector.ts +279 -0
  242. package/src/smartToolsUse.js +10 -4
  243. package/src/smartToolsUse.ts +10 -4
  244. package/src/stallGuard.js +10 -3
  245. package/src/stallGuard.ts +9 -3
  246. package/src/taskBuffer.js +91 -40
  247. package/src/taskBuffer.ts +94 -0
  248. package/src/tokenTracker.js +78 -11
  249. package/src/tokenTracker.ts +69 -11
  250. package/src/toolPacks.js +11 -0
  251. package/src/toolPacks.ts +11 -0
  252. package/src/tools/applyPatch.js +610 -0
  253. package/src/tools/applyPatch.ts +661 -0
  254. package/src/tools/archive.js +135 -21
  255. package/src/tools/archive.ts +136 -21
  256. package/src/tools/astryxOracle.js +77 -72
  257. package/src/tools/astryxOracle.ts +95 -0
  258. package/src/tools/axSnapshot.js +127 -147
  259. package/src/tools/axSnapshot.ts +174 -0
  260. package/src/tools/backgroundTask.js +86 -0
  261. package/src/tools/backgroundTask.ts +121 -0
  262. package/src/tools/blenderAutomator.js +434 -390
  263. package/src/tools/blenderAutomator.ts +623 -0
  264. package/src/tools/checkSystemSpecs.js +54 -61
  265. package/src/tools/checkSystemSpecs.ts +73 -0
  266. package/src/tools/clipboard.js +42 -31
  267. package/src/tools/clipboard.ts +61 -0
  268. package/src/tools/codeSearchAst.js +359 -91
  269. package/src/tools/codeSearchAst.ts +399 -0
  270. package/src/tools/codeSearcher.js +179 -37
  271. package/src/tools/codeSearcher.ts +188 -33
  272. package/src/tools/codeTools.js +208 -245
  273. package/src/tools/codeTools.ts +271 -0
  274. package/src/tools/codebaseSearch.js +5 -0
  275. package/src/tools/codebaseSearch.ts +5 -0
  276. package/src/tools/desktopAct.js +185 -197
  277. package/src/tools/desktopAct.ts +257 -0
  278. package/src/tools/dynamicLoader.js +4 -40
  279. package/src/tools/dynamicLoader.ts +13 -0
  280. package/src/tools/executeProceduralMedia.js +117 -86
  281. package/src/tools/executeProceduralMedia.ts +135 -0
  282. package/src/tools/fileTracker.js +74 -0
  283. package/src/tools/fileTracker.ts +94 -0
  284. package/src/tools/fsDelete.js +57 -47
  285. package/src/tools/fsDelete.ts +80 -0
  286. package/src/tools/fsEdit.js +192 -74
  287. package/src/tools/fsEdit.ts +201 -72
  288. package/src/tools/fsMove.js +79 -52
  289. package/src/tools/fsMove.ts +108 -0
  290. package/src/tools/fsRead.js +54 -15
  291. package/src/tools/fsRead.ts +55 -15
  292. package/src/tools/fsSearch.js +5 -0
  293. package/src/tools/fsSearch.ts +5 -0
  294. package/src/tools/fsWrite.js +14 -6
  295. package/src/tools/fsWrite.ts +14 -6
  296. package/src/tools/gameAiBehaviorTree.js +74 -91
  297. package/src/tools/gameAiBehaviorTree.ts +219 -0
  298. package/src/tools/gameAnimationRig.js +128 -147
  299. package/src/tools/gameAnimationRig.ts +215 -0
  300. package/src/tools/gameAssetFetcher.js +403 -441
  301. package/src/tools/gameAssetFetcher.ts +477 -0
  302. package/src/tools/gameAssetHarvester.js +171 -200
  303. package/src/tools/gameAssetHarvester.ts +261 -0
  304. package/src/tools/gameAudioSynth.js +223 -259
  305. package/src/tools/gameAudioSynth.ts +255 -0
  306. package/src/tools/gameBuilder.js +100 -91
  307. package/src/tools/gameBuilder.ts +913 -0
  308. package/src/tools/gameCanvasAudit.js +138 -96
  309. package/src/tools/gameCanvasAudit.ts +157 -0
  310. package/src/tools/gameCinematicSequencer.js +93 -111
  311. package/src/tools/gameCinematicSequencer.ts +165 -0
  312. package/src/tools/gameDataForge.js +115 -118
  313. package/src/tools/gameDataForge.ts +151 -0
  314. package/src/tools/gameDialogueTreeGen.js +125 -156
  315. package/src/tools/gameDialogueTreeGen.ts +159 -0
  316. package/src/tools/gameEconomyBalancer.js +150 -153
  317. package/src/tools/gameEconomyBalancer.ts +186 -0
  318. package/src/tools/gameEntitySpawner.js +91 -108
  319. package/src/tools/gameEntitySpawner.ts +209 -0
  320. package/src/tools/gameLoreForge.js +125 -147
  321. package/src/tools/gameLoreForge.ts +162 -0
  322. package/src/tools/gameQuestArcBuilder.js +105 -144
  323. package/src/tools/gameQuestArcBuilder.ts +147 -0
  324. package/src/tools/gameSceneBuilder.js +143 -149
  325. package/src/tools/gameSceneBuilder.ts +196 -0
  326. package/src/tools/gameShaderForge.js +83 -101
  327. package/src/tools/gameShaderForge.ts +181 -0
  328. package/src/tools/gameTilemapGenerator.js +99 -129
  329. package/src/tools/gameTilemapGenerator.ts +158 -0
  330. package/src/tools/gameUiHudBuilder.js +109 -129
  331. package/src/tools/gameUiHudBuilder.ts +300 -0
  332. package/src/tools/gameVfxEmitterGen.js +86 -89
  333. package/src/tools/gameVfxEmitterGen.ts +133 -0
  334. package/src/tools/gameWebRuntimeInspector.js +153 -86
  335. package/src/tools/gameWebRuntimeInspector.ts +167 -0
  336. package/src/tools/generateMediaViaApi.js +57 -15
  337. package/src/tools/generateMediaViaApi.ts +56 -15
  338. package/src/tools/gitExec.js +133 -86
  339. package/src/tools/gitExec.ts +146 -0
  340. package/src/tools/gitWorktree.js +115 -0
  341. package/src/tools/gitWorktree.ts +150 -0
  342. package/src/tools/godotAutomator.js +417 -394
  343. package/src/tools/godotAutomator.ts +530 -0
  344. package/src/tools/lspCodeIntel.js +217 -0
  345. package/src/tools/lspCodeIntel.ts +260 -0
  346. package/src/tools/manageLocalAiDependencies.js +242 -206
  347. package/src/tools/manageLocalAiDependencies.ts +288 -0
  348. package/src/tools/multiEdit.js +16 -76
  349. package/src/tools/multiEdit.ts +20 -77
  350. package/src/tools/nativeEngine.js +2 -2
  351. package/src/tools/nativeEngine.ts +2 -2
  352. package/src/tools/openSourceToolProvisioner.js +2 -2
  353. package/src/tools/openSourceToolProvisioner.ts +2 -2
  354. package/src/tools/osSandbox.js +152 -15
  355. package/src/tools/osSandbox.ts +148 -15
  356. package/src/tools/palmierAutomator.js +147 -95
  357. package/src/tools/palmierAutomator.ts +171 -0
  358. package/src/tools/payloadSanitizer.js +0 -1
  359. package/src/tools/payloadSanitizer.ts +0 -1
  360. package/src/tools/pdfReader.js +197 -104
  361. package/src/tools/pdfReader.ts +216 -0
  362. package/src/tools/persistentShell.js +267 -144
  363. package/src/tools/persistentShell.ts +314 -0
  364. package/src/tools/pluginManager.js +84 -72
  365. package/src/tools/pluginManager.ts +109 -0
  366. package/src/tools/presentDeliverable.js +103 -0
  367. package/src/tools/presentDeliverable.ts +127 -0
  368. package/src/tools/printer.js +278 -296
  369. package/src/tools/printer.ts +326 -0
  370. package/src/tools/procTerm.js +96 -83
  371. package/src/tools/procTerm.ts +127 -0
  372. package/src/tools/processList.js +45 -48
  373. package/src/tools/processList.ts +73 -0
  374. package/src/tools/ptcRuntime.js +444 -0
  375. package/src/tools/ptcRuntime.ts +490 -0
  376. package/src/tools/ptyTerminal.js +1096 -0
  377. package/src/tools/ptyTerminal.ts +1231 -0
  378. package/src/tools/registry.js +308 -287
  379. package/src/tools/registry.ts +495 -0
  380. package/src/tools/repoMap.js +46 -0
  381. package/src/tools/repoMap.ts +66 -0
  382. package/src/tools/subagentOrchestrator.js +404 -348
  383. package/src/tools/subagentOrchestrator.ts +457 -0
  384. package/src/tools/sysRun.js +83 -26
  385. package/src/tools/sysRun.ts +80 -26
  386. package/src/tools/toolForge.js +84 -67
  387. package/src/tools/toolForge.ts +102 -0
  388. package/src/tools/toolOutputStore.js +26 -4
  389. package/src/tools/toolOutputStore.ts +22 -4
  390. package/src/tools/toolPathSafety.js +262 -0
  391. package/src/tools/toolPathSafety.ts +308 -0
  392. package/src/tools/toolScanner.js +28 -0
  393. package/src/tools/toolScanner.ts +29 -0
  394. package/src/tools/toolSelfRepair.js +21 -6
  395. package/src/tools/toolSelfRepair.ts +26 -6
  396. package/src/tools/walkerSafety.ts +1 -0
  397. package/src/tools/webFetch.js +163 -13
  398. package/src/tools/webFetch.ts +150 -13
  399. package/src/tools/webSearch.js +123 -36
  400. package/src/tools/webSearch.ts +124 -33
  401. package/src/toolsList.js +5 -0
  402. package/src/toolsList.ts +5 -0
  403. package/src/tui/ask.js +159 -168
  404. package/src/tui/ask.ts +259 -0
  405. package/src/tui/banner.js +5 -1
  406. package/src/tui/banner.ts +6 -1
  407. package/src/tui/block.js +0 -1
  408. package/src/tui/block.ts +0 -1
  409. package/src/tui/chatRenderer.js +1194 -1443
  410. package/src/tui/chatRenderer.ts +1335 -0
  411. package/src/tui/clipboardImage.js +36 -12
  412. package/src/tui/clipboardImage.ts +39 -13
  413. package/src/tui/clipboardSync.js +34 -9
  414. package/src/tui/clipboardSync.ts +38 -9
  415. package/src/tui/codeProgress.js +0 -1
  416. package/src/tui/codeProgress.ts +0 -1
  417. package/src/tui/completion.js +396 -371
  418. package/src/tui/completion.ts +575 -0
  419. package/src/tui/composerControls.js +212 -34
  420. package/src/tui/composerControls.ts +235 -34
  421. package/src/tui/consoleGuard.js +27 -7
  422. package/src/tui/consoleGuard.ts +29 -7
  423. package/src/tui/dialogs.js +867 -733
  424. package/src/tui/dialogs.ts +971 -0
  425. package/src/tui/diff.js +205 -195
  426. package/src/tui/diff.ts +336 -0
  427. package/src/tui/history.js +143 -108
  428. package/src/tui/history.ts +167 -0
  429. package/src/tui/home.js +166 -161
  430. package/src/tui/home.ts +252 -0
  431. package/src/tui/invocation.js +59 -67
  432. package/src/tui/invocation.ts +116 -0
  433. package/src/tui/keys.js +437 -420
  434. package/src/tui/keys.ts +597 -0
  435. package/src/tui/lineEditor.js +477 -432
  436. package/src/tui/lineEditor.ts +542 -0
  437. package/src/tui/messageActionPlacement.js +0 -1
  438. package/src/tui/messageActionPlacement.ts +0 -1
  439. package/src/tui/messageInteraction.js +0 -2
  440. package/src/tui/messageInteraction.ts +0 -2
  441. package/src/tui/modelPicker.js +22 -15
  442. package/src/tui/modelPicker.ts +25 -18
  443. package/src/tui/observerPicker.js +0 -2
  444. package/src/tui/observerPicker.ts +0 -2
  445. package/src/tui/overlay.js +2 -6
  446. package/src/tui/overlay.ts +2 -6
  447. package/src/tui/prompt.js +1818 -2151
  448. package/src/tui/prompt.ts +1872 -0
  449. package/src/tui/runningLight.js +0 -1
  450. package/src/tui/runningLight.ts +0 -1
  451. package/src/tui/selectList.js +369 -349
  452. package/src/tui/selectList.ts +433 -0
  453. package/src/tui/sessionPicker.js +0 -1
  454. package/src/tui/sessionPicker.ts +0 -1
  455. package/src/tui/sessionPickerView.js +0 -2
  456. package/src/tui/sessionPickerView.ts +4 -21
  457. package/src/tui/sessionSidebar.js +3 -1
  458. package/src/tui/sessionSidebar.ts +4 -1
  459. package/src/tui/setup.js +39 -14
  460. package/src/tui/setup.ts +45 -14
  461. package/src/tui/skillAuthoring.js +0 -2
  462. package/src/tui/skillAuthoring.ts +0 -3
  463. package/src/tui/stageSurface.js +829 -909
  464. package/src/tui/stageSurface.ts +1003 -0
  465. package/src/tui/statusLine.js +7 -4
  466. package/src/tui/statusLine.ts +9 -3
  467. package/src/tui/terminalInputFramer.js +82 -69
  468. package/src/tui/terminalInputFramer.ts +116 -0
  469. package/src/tui/text.js +25 -10
  470. package/src/tui/text.ts +24 -10
  471. package/src/tui/textLayout.js +0 -1
  472. package/src/tui/textLayout.ts +0 -1
  473. package/src/tui/theme.js +245 -250
  474. package/src/tui/theme.ts +441 -0
  475. package/src/tui/thinkingBox.js +0 -1
  476. package/src/tui/thinkingBox.ts +0 -1
  477. package/src/tui/transcript.js +239 -216
  478. package/src/tui/transcript.ts +324 -0
  479. package/src/tui/turnRail.js +53 -54
  480. package/src/tui/turnRail.ts +51 -49
  481. package/src/tui/usageCard.js +0 -2
  482. package/src/tui/usageCard.ts +0 -2
  483. package/src/tui/workspaceSwitch.js +4 -2
  484. package/src/tui/workspaceSwitch.ts +5 -2
  485. package/src/types/contracts.ts +4 -1
  486. package/src/utils/browserOpen.js +107 -0
  487. package/src/utils/browserOpen.ts +129 -0
  488. package/src/utils/cli_ui.js +0 -0
  489. package/src/utils/cli_ui.ts +158 -0
  490. package/src/utils/winSpawn.js +248 -0
  491. package/src/utils/winSpawn.ts +275 -0
  492. package/src/verification/boundedExplorer.js +138 -107
  493. package/src/verification/boundedExplorer.ts +154 -0
  494. package/src/verification/byokSmokeProbe.js +193 -0
  495. package/src/verification/byokSmokeProbe.ts +234 -0
  496. package/src/verification/cliProbe.js +144 -110
  497. package/src/verification/cliProbe.ts +170 -0
  498. package/src/verification/featureMap.js +105 -75
  499. package/src/verification/featureMap.ts +124 -0
  500. package/src/verification/interactivePty.js +195 -100
  501. package/src/verification/interactivePty.ts +333 -0
  502. package/src/verification/propertyProbe.js +109 -101
  503. package/src/verification/propertyProbe.ts +159 -0
  504. package/src/verification/ptyProbe.js +168 -73
  505. package/src/verification/ptyProbe.ts +254 -0
  506. package/src/verification/skillCatalog.js +25 -25
  507. package/src/verification/skillCatalog.ts +66 -0
  508. package/src/verification/statechart.js +140 -127
  509. package/src/verification/statechart.ts +196 -0
  510. package/src/verification/uiRuntime.js +80 -49
  511. package/src/verification/uiRuntime.ts +88 -0
  512. package/src/version.js +37 -32
  513. package/src/version.ts +45 -0
  514. package/src/web/client/browserPanel.js +702 -0
  515. package/src/web/client/browserPanel.ts +663 -0
  516. package/src/web/client/chatStream.js +309 -0
  517. package/src/web/client/chatStream.ts +289 -0
  518. package/src/web/client/cliPanel.js +165 -0
  519. package/src/web/client/cliPanel.ts +171 -0
  520. package/src/web/client/composer.js +204 -0
  521. package/src/web/client/composer.ts +209 -0
  522. package/src/web/client/diffPanel.js +176 -0
  523. package/src/web/client/diffPanel.ts +203 -0
  524. package/src/web/client/dom.js +220 -0
  525. package/src/web/client/dom.ts +221 -0
  526. package/src/web/client/filesAndCanvas.js +231 -0
  527. package/src/web/client/filesAndCanvas.ts +238 -0
  528. package/src/web/client/gameLauncherUi.js +78 -0
  529. package/src/web/client/gameLauncherUi.ts +78 -0
  530. package/src/web/client/main.js +301 -0
  531. package/src/web/client/main.ts +368 -0
  532. package/src/web/client/markdown.js +364 -0
  533. package/src/web/client/markdown.ts +373 -0
  534. package/src/web/client/modelPicker.js +455 -0
  535. package/src/web/client/modelPicker.ts +451 -0
  536. package/src/web/client/permissionPresetsUi.js +307 -0
  537. package/src/web/client/permissionPresetsUi.ts +333 -0
  538. package/src/web/client/sessions.js +353 -0
  539. package/src/web/client/sessions.ts +372 -0
  540. package/src/web/client/settingsModal.js +191 -0
  541. package/src/web/client/settingsModal.ts +176 -0
  542. package/src/web/client/state.js +250 -0
  543. package/src/web/client/state.ts +233 -0
  544. package/src/web/client/streamSmoother.js +127 -0
  545. package/src/web/client/streamSmoother.ts +119 -0
  546. package/src/web/client/studioLayout.js +54 -0
  547. package/src/web/client/studioLayout.ts +60 -0
  548. package/src/web/client/studioShell.js +327 -0
  549. package/src/web/client/studioShell.ts +340 -0
  550. package/src/web/client/studioStart.js +77 -0
  551. package/src/web/client/studioStart.ts +89 -0
  552. package/src/web/client/terminalPanel.js +357 -0
  553. package/src/web/client/terminalPanel.ts +345 -0
  554. package/src/web/client/turnView.js +934 -0
  555. package/src/web/client/turnView.ts +981 -0
  556. package/src/web/client/types.js +1 -0
  557. package/src/web/client/types.ts +319 -0
  558. package/src/web/client/validators.js +106 -0
  559. package/src/web/client/validators.ts +96 -0
  560. package/src/web/guiLauncher.js +89 -0
  561. package/src/web/guiLauncher.ts +119 -0
  562. package/src/web/server/activeRuns.js +152 -0
  563. package/src/web/server/activeRuns.ts +171 -0
  564. package/src/web/server/routesBrowser.js +355 -0
  565. package/src/web/server/routesBrowser.ts +386 -0
  566. package/src/web/server/routesChat.js +304 -0
  567. package/src/web/server/routesChat.ts +347 -0
  568. package/src/web/server/routesCore.js +472 -0
  569. package/src/web/server/routesCore.ts +522 -0
  570. package/src/web/server/routesTerminal.js +162 -0
  571. package/src/web/server/routesTerminal.ts +182 -0
  572. package/src/web/server/routesWorkspace.js +510 -0
  573. package/src/web/server/routesWorkspace.ts +546 -0
  574. package/src/web/server/security.js +98 -0
  575. package/src/web/server/security.ts +108 -0
  576. package/src/web/server/sessionTranscript.js +586 -0
  577. package/src/web/server/sessionTranscript.ts +566 -0
  578. package/src/web/server/staticAssets.js +80 -0
  579. package/src/web/server/staticAssets.ts +91 -0
  580. package/src/web/server/types.js +1 -0
  581. package/src/web/server/types.ts +135 -0
  582. package/src/web/server/workspaceFiles.js +368 -0
  583. package/src/web/server/workspaceFiles.ts +363 -0
  584. package/src/web/skybridgeBrowserBridge.js +256 -0
  585. package/src/web/skybridgeBrowserBridge.ts +285 -0
  586. package/src/web/skybridgeBrowserMcp.js +730 -0
  587. package/src/web/skybridgeBrowserMcp.ts +813 -0
  588. package/src/web/skybridgeServer.js +249 -0
  589. package/src/web/skybridgeServer.ts +305 -0
  590. package/src/web/skybridgeUi.js +38 -0
  591. package/src/web/skybridgeUi.ts +47 -0
  592. package/src/web/styles/agent.css +380 -0
  593. package/src/web/styles/composer.css +193 -0
  594. package/src/web/styles/overlays.css +436 -0
  595. package/src/web/styles/shell.css +387 -0
  596. package/src/web/styles/studio.css +723 -0
  597. package/src/web/styles/thread.css +221 -0
  598. package/src/web/styles/tokens.css +94 -0
  599. package/src/web/ui/brandMark.js +73 -0
  600. package/src/web/ui/brandMark.ts +82 -0
  601. package/src/web/ui/modalsTemplate.js +139 -0
  602. package/src/web/ui/modalsTemplate.ts +139 -0
  603. package/src/web/ui/sidebarTemplate.js +63 -0
  604. package/src/web/ui/sidebarTemplate.ts +64 -0
  605. package/src/web/ui/studioTemplate.js +258 -0
  606. package/src/web/ui/studioTemplate.ts +258 -0
  607. package/src/web/ui/workspaceTemplate.js +72 -0
  608. package/src/web/ui/workspaceTemplate.ts +73 -0
  609. package/src/worktreeManager.js +526 -0
  610. package/src/worktreeManager.ts +567 -0
  611. package/src/zeroCostFailover.js +168 -0
  612. package/src/zeroCostFailover.ts +198 -0
  613. package/src/zeroCostRouting.js +391 -0
  614. package/src/zeroCostRouting.ts +437 -0
  615. package/src/agentLoop.d.ts +0 -65
  616. package/src/auditLog.d.ts +0 -3
  617. package/src/checkpoints.d.ts +0 -4
  618. package/src/compiledSkills.d.ts +0 -5
  619. package/src/contextManager.d.ts +0 -14
  620. package/src/designPalettes.d.ts +0 -2
  621. package/src/devMode.d.ts +0 -1
  622. package/src/embodimentSession.d.ts +0 -2
  623. package/src/licensing/entitlements.d.ts +0 -14
  624. package/src/memory.d.ts +0 -13
  625. package/src/memoryManager.d.ts +0 -1
  626. package/src/modelCatalogue.d.ts +0 -6
  627. package/src/modelIds.d.ts +0 -2
  628. package/src/outputStore.d.ts +0 -4
  629. package/src/plugins/pluginManager.d.ts +0 -7
  630. package/src/providers/antigravity.d.ts +0 -19
  631. package/src/provisioning/capabilityProvisioner.d.ts +0 -12
  632. package/src/slopDetector.d.ts +0 -3
  633. package/src/taskBuffer.d.ts +0 -1
  634. package/src/tools/desktopAct.d.ts +0 -10
  635. package/src/tools/registry.d.ts +0 -5
  636. package/src/tui/chatRenderer.d.ts +0 -27
  637. package/src/tui/diff.d.ts +0 -3
  638. package/src/utils/cli_ui.d.ts +0 -19
  639. package/src/utils/paths.d.ts +0 -3
  640. package/src/verification/skillCatalog.d.ts +0 -1
  641. package/src/version.d.ts +0 -1
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';
@@ -125,6 +139,15 @@ import { StreamingCodePreview, NativeCodeObserver, codeProgressFromAction } from
125
139
  import { StallGuardController, type StallGuardDecision, type IdenticalCallObservation } from './stallGuard.js';
126
140
  import { buildRecoverableDroppedSummary, pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments } from './historyPruner.js';
127
141
  import { isOutputRecoveryRead } from './outputRecovery.js';
142
+ import {
143
+ autonomyModeToPreset,
144
+ getPermissionPresetDescriptor,
145
+ normalizePermissionPreset,
146
+ presetToAutonomyMode,
147
+ renderPermissionPolicyContext,
148
+ resolveConfigPermissionPreset,
149
+ type PermissionPresetId
150
+ } from './permissionPresets.js';
128
151
  import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.js';
129
152
  export function noncachedTokens(usage: any): number {
130
153
  if (!usage) return 0;
@@ -188,9 +211,13 @@ export interface AgentLoopApprovalScope {
188
211
  export interface AgentLoopOptions {
189
212
  workspaceRoot?: string;
190
213
  memorySessionId?: string | null;
214
+ ephemeralSession?: boolean;
191
215
  approvalScope?: AgentLoopApprovalScope;
192
216
  provider?: string;
193
217
  model?: string;
218
+ variant?: string;
219
+ hostSystemInstructions?: string | undefined;
220
+ peerMcpServers?: McpServer[] | undefined;
194
221
  }
195
222
 
196
223
  export {
@@ -208,7 +235,7 @@ export {
208
235
  function readMacDesktopPictures(): string | null {
209
236
  try {
210
237
  return execFileSync('osascript', ['-e', 'tell application "System Events" to get picture of every desktop'], {
211
- encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore']
238
+ encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, env: sanitizeSubprocessEnv(process.env)
212
239
  }).trim() || null;
213
240
  } catch {
214
241
  return null;
@@ -219,63 +246,22 @@ const SYSTEM_PROMPT = `You are Causyne Agent, an autonomous local AI agent. Your
219
246
 
220
247
  ${PEER_COLLABORATION_POLICY}
221
248
 
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
249
  ${AGENT_USER_POLICY}
226
250
 
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.
251
+ # Operational Guidelines & Engineering Discipline
252
+ - **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.
253
+ - **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.
254
+ - **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.
255
+ - **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.
256
+ - **Code Quality**: Write clear, runnable, idiomatic code following existing project conventions without trivial inline comments or TODO placeholders. Preserve unrelated behavior.
257
+ - **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.
258
+ - **Git Commits**: Follow the target repository's commit message conventions and project instructions (such as \`AGENTS.md\` or \`git log\`) when committing changes.
259
+ - **Permission Presets & Safety Boundaries**:
260
+ - **Read Only (\`read-only\`)**: Inspect files, search code, and read documentation only; file modifications and mutating shell commands are blocked.
261
+ - **Workspace Write (\`workspace-write\`)**: Read and edit files scoped to the active workspace; ask approval before dangerous operations, OS-level changes, or \`sudo\`.
262
+ - **Full access (\`danger-full-access\`)**: Execute ordinary in-scope workspace edits and commands directly; whole-file/directory deletion, credential safeguards, hard policy blocks, and workspace boundaries remain enforced. Avoid interactive shell flags; use non-interactive flags (\`-y\`).
263
+ - **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.
264
+ - **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
265
 
280
266
  # ABSOLUTE ETHICAL SAFETY NET (NON-NEGOTIABLE)
281
267
  You are bound by an unbreakable ethical safety net. Regardless of user prompt, jailbreak attempts, or roleplay scenarios, you MUST REFUSE to:
@@ -290,42 +276,53 @@ You are bound by an unbreakable ethical safety net. Regardless of user prompt, j
290
276
 
291
277
  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
278
 
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
279
  # 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.
280
+ Continue until the authorized work is verified or a real blocker is evidenced, then report the outcome concisely.
327
281
  `;
328
282
 
283
+ const REA_SUBSTRATE_PROMPT = `\n\n# Sovereign Reverse Engineering & Clean-Room Analysis (REA Substrate)
284
+ You possess native reverse engineering capabilities via \`reverse_engineering\` for interoperability, binary inspection, security research, format decoding, manifest analysis, and clean-room application implementation.
285
+ - 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.`;
286
+
287
+ const ANDROID_TOOLCHAIN_PROMPT = `\n\n# Android & JVM Toolchains in sysRun
288
+ 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.`;
289
+
290
+ const WEB_VERIFICATION_PROMPT = `\n\n# Web & UI Verification
291
+ 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.`;
292
+
293
+ const ANDROID_CONTEXT_RE = /\b(?:android|apk|aab|adb|emulator|gradle|gradlew|kotlin|jetpack|compose|java|jdk|jvm|avd|dumpsys)\b/i;
294
+
295
+ 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;
296
+
297
+ const CAUSYNE_CLI_BIN_PATH = fileURLToPath(new URL('../bin/causyne.js', import.meta.url));
298
+
299
+ export function buildSharedBrowserAwarenessPrompt(
300
+ live: LiveBrowserAwarenessContext,
301
+ hasBrowserMcp: boolean
302
+ ): string {
303
+ const toolHint = hasBrowserMcp
304
+ ? '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).'
305
+ : 'Use `browser_act` directly (actions: `snapshot`, `extract`, `screenshot`, `click`, `type`, `scroll`, `navigate`, `listTabs`).';
306
+ if (!live.active) {
307
+ 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.`;
308
+ }
309
+ const modeLabel = live.visible ? 'visible native OS window' : 'embedded live Browser Panel';
310
+ const engineLabel = live.engine || 'browser';
311
+ const tabLines = live.tabs.slice(0, 8).map((tab, idx) => {
312
+ const marker = tab.active ? ' [ACTIVE]' : '';
313
+ const titlePart = tab.title ? `"${tab.title.slice(0, 90)}" — ` : '';
314
+ return ` ${idx + 1}. (${tab.tabId})${marker} ${titlePart}${tab.url || 'about:blank'}`;
315
+ });
316
+ return [
317
+ `\n\n◆ SHARED WORKSPACE BROWSER (LIVE — shared directly with the user beside this chat):`,
318
+ `- Runtime: ${engineLabel} (${modeLabel}, viewport ${live.viewport.width}x${live.viewport.height})`,
319
+ `- Active tab: ${live.title ? `"${live.title.slice(0, 120)}" — ` : ''}${live.url || 'about:blank'} (tabId=${live.activeTabId || 'active'})`,
320
+ ...(tabLines.length > 0 ? [`- Open tabs (${live.tabs.length}):`, ...tabLines] : []),
321
+ `- 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}`,
322
+ `- 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.`
323
+ ].join('\n');
324
+ }
325
+
329
326
  function getProviderSpecificPrompt(provider: string = '') {
330
327
  const p = provider.toLowerCase();
331
328
 
@@ -458,12 +455,13 @@ export function skillSystemMessage(skill: any) {
458
455
 
459
456
 
460
457
  export function explainNetworkError(error: any, config: any = {}) {
458
+ const safeConfig = config && typeof config === 'object' ? config : {};
461
459
  const cause = error && error.cause;
462
- const code = (cause && (cause.code || cause.errno)) || '';
460
+ const code = String((cause && (cause.code || cause.errno)) || error?.code || error?.errno || '');
463
461
 
464
462
  let host = '';
465
463
  try {
466
- const raw = config.baseUrl && String(config.baseUrl).trim();
464
+ const raw = safeConfig.baseUrl && String(safeConfig.baseUrl).trim();
467
465
  if (raw) host = new URL(raw).host;
468
466
  } catch (e: any) { /* a malformed base URL is itself worth reporting, below */ }
469
467
 
@@ -478,15 +476,18 @@ export function explainNetworkError(error: any, config: any = {}) {
478
476
  EHOSTUNREACH: 'that host is unreachable from this network',
479
477
  ENETUNREACH: 'this machine has no route to the network',
480
478
  EPIPE: 'the connection closed mid-request',
479
+ UND_ERR_SOCKET: 'the upstream socket closed unexpectedly',
480
+ ECONNABORTED: 'the connection was aborted mid-request',
481
+ UND_ERR_BODY_TIMEOUT: 'the server response body stalled',
481
482
  CERT_HAS_EXPIRED: 'the TLS certificate has expired',
482
483
  DEPTH_ZERO_SELF_SIGNED_CERT: 'the TLS certificate is self-signed — a proxy may be intercepting',
483
484
  UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'the TLS certificate could not be verified — a proxy may be intercepting',
484
485
  SELF_SIGNED_CERT_IN_CHAIN: 'a self-signed certificate is in the chain — a proxy may be intercepting'
485
486
  };
486
487
 
487
- const reason = REASONS[code] || (code ? `the connection failed (${code})` : 'the connection failed');
488
+ const reason = (Object.hasOwn(REASONS, code) ? REASONS[code] : undefined) || (code ? `the connection failed (${code})` : 'the connection failed');
488
489
  const where = host ? ` reaching ${host}` : '';
489
- const provider = config.provider ? ` via ${config.provider}` : '';
490
+ const provider = safeConfig.provider ? ` via ${safeConfig.provider}` : '';
490
491
 
491
492
  const checks = [];
492
493
  if (code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'ENETUNREACH') {
@@ -514,6 +515,17 @@ class RetryConsentCheckpoint extends Error {
514
515
  constructor() { super('Peer paused after three failed attempts; explicit retry approval is required.'); }
515
516
  }
516
517
 
518
+ export function resolveToolsCatalogPromptBlock(
519
+ provider: unknown,
520
+ fullToolsListText: string
521
+ ): string {
522
+ const norm = String(provider || '').trim().toLowerCase();
523
+ if (norm === 'ollama') {
524
+ return 'Additional specialized tools are available on demand via tool_search(query).';
525
+ }
526
+ return fullToolsListText;
527
+ }
528
+
517
529
  export class AgentLoop {
518
530
  // Task state is assembled across the constructor and helpers below. This
519
531
  // signature keeps those reads and writes explicitly dynamic while each field
@@ -545,13 +557,24 @@ export class AgentLoop {
545
557
  this.modelOverride = typeof options.model === 'string' && options.model.trim()
546
558
  ? options.model.trim()
547
559
  : null;
560
+ this.variantOverride = typeof options.variant === 'string' && options.variant.trim()
561
+ ? options.variant.trim().toLowerCase()
562
+ : null;
548
563
  this.approvalScope = options.approvalScope && typeof options.approvalScope.isAlwaysAllowed === 'function'
549
564
  ? options.approvalScope
550
565
  : processApprovalScope;
566
+ this.peerMcpServers = Array.isArray(options.peerMcpServers)
567
+ ? [...options.peerMcpServers]
568
+ : [];
569
+ this.hostSystemInstructions = typeof options.hostSystemInstructions === 'string' && options.hostSystemInstructions.trim()
570
+ ? options.hostSystemInstructions.trim()
571
+ : null;
551
572
 
552
573
  this.config = loadConfig();
553
- if (this.providerOverride) this.config.provider = this.providerOverride;
554
- if (this.modelOverride) this.config.model = this.modelOverride;
574
+ applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
575
+ if (this.variantOverride) {
576
+ this.config.reasoningEffort = this.variantOverride;
577
+ }
555
578
  this.sandbox = new Sandbox({ workspaceRoot: this.workspaceRoot });
556
579
 
557
580
  // Retire spilled tool outputs past their retention window. Fire-and-forget
@@ -571,7 +594,9 @@ export class AgentLoop {
571
594
  this.tokenTracker = new TokenTracker();
572
595
 
573
596
  this.llm = this.initializeProvider();
574
- this.memoryManager = new MemoryManager(this.workspaceRoot, options.memorySessionId || null);
597
+ this.memoryManager = new MemoryManager(this.workspaceRoot, options.memorySessionId || null, {
598
+ ephemeral: options.ephemeralSession === true
599
+ });
575
600
  this.messages = this.memoryManager.loadHistory(); // Persistent context window
576
601
  this.stepsCompleted = 0;
577
602
  this.consecutiveCommands = 0;
@@ -600,7 +625,10 @@ export class AgentLoop {
600
625
  this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
601
626
  this.recentActionSignatures = [];
602
627
  this.consecutiveReadOnlySteps = 0;
603
- this.stallGuard = new StallGuardController();
628
+ this.stallGuard = new StallGuardController({
629
+ hardStopEnabled: true,
630
+ identicalCallHaltAfter: TIME_MACHINE_MAX_ATTEMPTS + 1
631
+ });
604
632
  this.smartToolsGovernor = new SmartToolsGovernor(4);
605
633
  this._smartToolsNudge = null;
606
634
  this.activeFreeFormPaths = new Map<string, string[][]>();
@@ -850,7 +878,7 @@ export class AgentLoop {
850
878
  }
851
879
 
852
880
  recordWebArtifact(candidate: unknown): void {
853
- if (typeof candidate !== 'string' || !isScannableFile(candidate)) return;
881
+ if (typeof candidate !== 'string' || candidate.length === 0 || candidate.length > 4096 || candidate.includes('\0') || !isScannableFile(candidate)) return;
854
882
  const lower = candidate.toLowerCase();
855
883
  // Exclude test files, spec files, python scripts, and backend code from invalidating web verification
856
884
  if (/\b(?:test|spec|bench|unittest)\b/i.test(lower) || /\.(py|sh|rb|go|rs|json|ya?ml|md|sql)$/i.test(lower)) {
@@ -869,8 +897,9 @@ export class AgentLoop {
869
897
  }
870
898
 
871
899
  recordInspectedWebFile(candidate: unknown): void {
872
- if (typeof candidate !== 'string' || !candidate.trim()) return;
873
- const matches = candidate.match(/[\w./-]+\.(?:html?|css|jsx|tsx|vue|svelte)\b/gi) || [candidate];
900
+ if (typeof candidate !== 'string' || !candidate.trim() || candidate.includes('\0')) return;
901
+ const scanText = candidate.length > 32768 ? candidate.slice(0, 32768) : candidate;
902
+ const matches = scanText.match(/[\w./-]+\.(?:html?|css|jsx|tsx|vue|svelte)\b/gi) || [scanText];
874
903
  for (const rawMatch of matches) {
875
904
  if (!isScannableFile(rawMatch)) continue;
876
905
  const expanded = rawMatch.startsWith('~/')
@@ -1004,7 +1033,14 @@ export class AgentLoop {
1004
1033
  this.debugLog(`episodic context build skipped: ${e.message}`);
1005
1034
  }
1006
1035
 
1007
- return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext };
1036
+ let projectInstructions = '';
1037
+ try {
1038
+ projectInstructions = formatProjectInstructionsPrompt(loadProjectInstructions(this.workspaceRoot));
1039
+ } catch (e: any) {
1040
+ this.debugLog(`project instructions load skipped: ${e.message}`);
1041
+ }
1042
+
1043
+ return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext, projectInstructions };
1008
1044
  }
1009
1045
 
1010
1046
 
@@ -1015,17 +1051,21 @@ export class AgentLoop {
1015
1051
  abort() {
1016
1052
  this.stopRequested = true;
1017
1053
  if (this.abortController) {
1018
- this.abortController.abort();
1054
+ try {
1055
+ this.abortController.abort();
1056
+ } catch {
1057
+ // An abort listener error must not prevent provider/approval teardown.
1058
+ }
1019
1059
  }
1020
1060
  if (this.llm && typeof (this.llm as any).abort === 'function') {
1021
1061
  try {
1022
- (this.llm as any).abort();
1062
+ void Promise.resolve((this.llm as any).abort()).catch(() => {});
1023
1063
  } catch {
1024
1064
  // ignore provider abort errors
1025
1065
  }
1026
1066
  } else if (this.llm && typeof (this.llm as any).close === 'function') {
1027
1067
  try {
1028
- void (this.llm as any).close();
1068
+ void Promise.resolve((this.llm as any).close()).catch(() => {});
1029
1069
  } catch {
1030
1070
  // ignore provider close errors
1031
1071
  }
@@ -1037,13 +1077,41 @@ export class AgentLoop {
1037
1077
  }
1038
1078
  }
1039
1079
 
1080
+ activePermissionPreset(): PermissionPresetId {
1081
+ const fromOverride = normalizePermissionPreset(this.autonomyOverride);
1082
+ if (fromOverride) return fromOverride;
1083
+ return resolveConfigPermissionPreset(this.config, 'danger-full-access');
1084
+ }
1085
+
1040
1086
  setAutonomyMode(mode: string) {
1041
- const normalized = String(mode || '').trim().toUpperCase();
1042
- if (!['A', 'B', 'C'].includes(normalized)) {
1043
- throw new Error('autonomy mode must be A, B, or C');
1087
+ const preset = normalizePermissionPreset(mode);
1088
+ if (!preset) {
1089
+ throw new Error('permission preset must be read-only, workspace-write, or danger-full-access (or A, B, C)');
1044
1090
  }
1091
+ const normalized = presetToAutonomyMode(preset);
1045
1092
  this.autonomyOverride = normalized;
1046
1093
  this.config.autonomyMode = normalized;
1094
+ this.config.permissionPreset = preset;
1095
+ if (this.sandbox) {
1096
+ this.sandbox.autonomyMode = normalized;
1097
+ this.sandbox.permissionPreset = preset;
1098
+ }
1099
+ }
1100
+
1101
+ setPermissionPreset(rawPreset: string): PermissionPresetId {
1102
+ const preset = normalizePermissionPreset(rawPreset);
1103
+ if (!preset) {
1104
+ throw new Error('permission preset must be read-only, workspace-write, or danger-full-access');
1105
+ }
1106
+ const mode = presetToAutonomyMode(preset);
1107
+ this.autonomyOverride = mode;
1108
+ this.config.autonomyMode = mode;
1109
+ this.config.permissionPreset = preset;
1110
+ if (this.sandbox) {
1111
+ this.sandbox.autonomyMode = mode;
1112
+ this.sandbox.permissionPreset = preset;
1113
+ }
1114
+ return preset;
1047
1115
  }
1048
1116
 
1049
1117
  /**
@@ -1081,7 +1149,9 @@ export class AgentLoop {
1081
1149
 
1082
1150
  initializeProvider() {
1083
1151
  if (!this.config?.provider) return null;
1084
- return createProvider(this.config);
1152
+ const provider = createProvider(this.config);
1153
+ this._factoryLlmRef = provider;
1154
+ return provider;
1085
1155
  }
1086
1156
 
1087
1157
  /**
@@ -1114,9 +1184,9 @@ export class AgentLoop {
1114
1184
  const prefetched = new Map();
1115
1185
  if (!Array.isArray(toolCalls) || toolCalls.length < 2) return prefetched;
1116
1186
 
1117
- // Mode A promises approval before every tool, including reads. Starting a
1187
+ // Read Only promises approval before every tool, including reads. Starting a
1118
1188
  // read here would execute it before the serial approval and hook gates.
1119
- if ((this.config.autonomyMode || 'C') === 'A') return prefetched;
1189
+ if (this.activePermissionPreset() === 'read-only') return prefetched;
1120
1190
 
1121
1191
  const eligible: any[] = [];
1122
1192
  for (const toolCall of toolCalls) {
@@ -1152,6 +1222,17 @@ export class AgentLoop {
1152
1222
  }
1153
1223
  if (!validation || validation.allowed === false || validation.risk !== 'safe') continue;
1154
1224
 
1225
+ try {
1226
+ const enterpriseDecision = evaluateEnterprisePolicy({
1227
+ tool: functionName,
1228
+ args,
1229
+ workspaceRoot: this.workspaceRoot
1230
+ });
1231
+ if (enterpriseDecision.effect === 'deny' || enterpriseDecision.effect === 'ask') continue;
1232
+ } catch {
1233
+ continue;
1234
+ }
1235
+
1155
1236
  const tool = resolveTool(functionName);
1156
1237
  if (!tool || typeof tool.execute !== 'function') continue;
1157
1238
 
@@ -1194,6 +1275,9 @@ export class AgentLoop {
1194
1275
 
1195
1276
  /** Apply host policy to an ACP operation without disabling the peer itself. */
1196
1277
  private resolvePeerFilePath(file: string): string {
1278
+ if (typeof file !== 'string' || !file.trim() || file.includes('\0')) {
1279
+ throw new Error('ACP path was not authorized');
1280
+ }
1197
1281
  const target = path.resolve(this.workspaceRoot, file);
1198
1282
  let ancestor = target;
1199
1283
  while (true) {
@@ -1220,16 +1304,35 @@ export class AgentLoop {
1220
1304
  if (this.stopRequested || this.abortController.signal.aborted) return false;
1221
1305
  const validation = this.sandbox.validate(tool, args);
1222
1306
  if (!validation.allowed) return false;
1307
+ const enterpriseDecision = evaluateEnterprisePolicy({
1308
+ tool,
1309
+ args,
1310
+ workspaceRoot: this.workspaceRoot
1311
+ });
1312
+ if (enterpriseDecision.effect === 'deny') {
1313
+ auditLog.log({
1314
+ event: 'peer_operation_policy_denied',
1315
+ taskId: this.taskId,
1316
+ tool,
1317
+ rule: enterpriseDecision.matchedRule,
1318
+ dimension: enterpriseDecision.matchedDimension
1319
+ });
1320
+ return false;
1321
+ }
1223
1322
  const hook = await this.runPreToolUse(tool, args, id);
1224
1323
  if (hook?.denied) return false;
1225
1324
  const assessment = await coldObserver.evaluateMutation(tool, args, { workspaceRoot: this.workspaceRoot });
1226
1325
  if (assessment.veto) return false;
1227
- const isModeC = (this.config.autonomyMode || 'C') === 'C';
1228
- const needsApproval = (!isModeC && uncertain) || requiresToolApproval({
1229
- mode: this.config.autonomyMode || 'C', tool, args,
1230
- risk: assessment.requiresConfirmation ? 'dangerous' : validation.risk,
1231
- heavyDownload: false, standingApproval: this.isAlwaysAllowed(tool)
1232
- });
1326
+ const activePreset = this.activePermissionPreset();
1327
+ const isFullAccess = activePreset === 'danger-full-access';
1328
+ const needsApproval = enterpriseDecision.effect === 'ask'
1329
+ || (!isFullAccess && uncertain)
1330
+ || requiresToolApproval({
1331
+ permissionPreset: activePreset,
1332
+ mode: presetToAutonomyMode(activePreset), tool, args,
1333
+ risk: assessment.requiresConfirmation ? 'dangerous' : validation.risk,
1334
+ heavyDownload: false, standingApproval: this.isAlwaysAllowed(tool)
1335
+ });
1233
1336
  if (needsApproval) {
1234
1337
  this.emitEvent({ type: 'approval_request', toolCallId: id, tool, args, risk: validation.risk });
1235
1338
  if (!await this.waitForApproval(id)) return false;
@@ -1240,14 +1343,28 @@ export class AgentLoop {
1240
1343
  }
1241
1344
 
1242
1345
  async requestPeerPermission(request: RequestPermissionRequest): Promise<RequestPermissionResponse['outcome']> {
1243
- const call = request.toolCall;
1346
+ const options = Array.isArray(request?.options) ? request.options : [];
1347
+ const allowOption = options.find(item => item?.kind === 'allow_once');
1348
+ const rejectOption = options.find(item => item?.kind === 'reject_once')
1349
+ ?? options.find(item => item?.kind === 'reject_always');
1350
+ const denyOutcome = (): RequestPermissionResponse['outcome'] => {
1351
+ if (this.stopRequested || this.abortController.signal.aborted) {
1352
+ return { outcome: 'cancelled' };
1353
+ }
1354
+ return rejectOption?.optionId
1355
+ ? { outcome: 'selected', optionId: rejectOption.optionId }
1356
+ : { outcome: 'cancelled' };
1357
+ };
1358
+
1359
+ const call = request?.toolCall;
1360
+ if (!call || typeof call !== 'object' || typeof call.toolCallId !== 'string' || !call.toolCallId.trim()) return denyOutcome();
1244
1361
  const raw = call.rawInput && typeof call.rawInput === 'object' && !Array.isArray(call.rawInput)
1245
1362
  ? call.rawInput as Record<string, unknown> : {};
1246
1363
  const args = { ...raw };
1247
1364
  if (!args.path && call.locations?.[0]?.path) args.path = call.locations[0].path;
1248
1365
  for (const field of ['path', 'file_path', 'filePath', 'filepath', 'absolutePath', 'cwd', 'source', 'destination', 'directory', 'targetFile', 'outputFile', 'outputPath']) {
1249
1366
  if (typeof args[field] === 'string') {
1250
- try { args[field] = this.resolvePeerFilePath(args[field] as string); } catch { return { outcome: 'cancelled' }; }
1367
+ try { args[field] = this.resolvePeerFilePath(args[field] as string); } catch { return denyOutcome(); }
1251
1368
  }
1252
1369
  }
1253
1370
  args.path ??= args.file_path ?? args.filePath ?? args.filepath ?? args.absolutePath;
@@ -1257,29 +1374,40 @@ export class AgentLoop {
1257
1374
  if (tool === 'sysRun' && !args.command && typeof args.cmd === 'string') args.command = args.cmd;
1258
1375
  const uncertain = !['read', 'search', 'fetch', 'think'].includes(call.kind || '')
1259
1376
  && (tool === 'peer_native' || (tool === 'sysRun' ? !args.command : !args.path));
1260
- const option = request.options.find(item => item.kind === 'allow_once');
1261
1377
  // Never propagate a standing peer grant across sessions or forks.
1262
- if (!option || !await this.authorizePeerOperation(tool, { ...args, peerTitle: call.title }, `peer:${call.toolCallId}`, uncertain)) {
1263
- return { outcome: 'cancelled' };
1378
+ if (!allowOption || !await this.authorizePeerOperation(tool, { ...args, peerTitle: call.title }, `peer:${call.toolCallId}`, uncertain)) {
1379
+ return denyOutcome();
1264
1380
  }
1265
- return { outcome: 'selected', optionId: option.optionId };
1381
+ return { outcome: 'selected', optionId: allowOption.optionId };
1266
1382
  }
1267
1383
 
1268
1384
  async executePeerFile(tool: 'fs_read' | 'fs_write', file: string, content?: string, options?: { line?: number; limit?: number }): Promise<string> {
1269
1385
  const target = this.resolvePeerFilePath(file);
1270
1386
  if (options?.line !== undefined && (!Number.isSafeInteger(options.line) || options.line < 1)) throw new Error('ACP line must be a positive integer');
1271
1387
  if (options?.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 1)) throw new Error('ACP limit must be a positive integer');
1388
+ if (options?.limit !== undefined && !Number.isSafeInteger((options.line || 1) + (options.limit - 1))) throw new Error('ACP line range exceeds the safe integer limit');
1272
1389
  const args = { path: target, ...(tool === 'fs_write' ? { content } : {}),
1273
1390
  ...(options?.line !== undefined ? { startLine: options.line } : {}),
1274
- ...(options?.limit !== undefined ? { endLine: (options.line || 1) + options.limit - 1 } : {}) };
1391
+ ...(options?.limit !== undefined ? { endLine: (options.line || 1) + (options.limit - 1) } : {}) };
1275
1392
  const id = `peer-file:${randomUUID()}:${tool}`;
1276
1393
  if (!await this.authorizePeerOperation(tool, args, id)) throw new Error('The requested ACP file operation was not authorized');
1394
+ this.resolvePeerFilePath(target);
1277
1395
  if (tool === 'fs_write') captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
1278
1396
  let result: { success: boolean; error?: string; output?: string };
1279
1397
  if (tool === 'fs_read') {
1280
1398
  // ACP expects the actual requested text, not the host tool's paging
1281
1399
  // warning appended to a silently shortened file.
1400
+ const lstat = fsSync.lstatSync(target);
1401
+ if (lstat.isSymbolicLink() && !this.sandbox.grantAllAccess) {
1402
+ const realTarget = physicalPath(target);
1403
+ const stillAllowed = realTarget !== null && this.sandbox.workspacePaths.some((root: string) => {
1404
+ const realRoot = physicalPath(root);
1405
+ return realRoot !== null && isWithinPhysicalPath(realTarget, realRoot);
1406
+ });
1407
+ if (!stillAllowed) throw new Error('ACP symlink target was not authorized by the selected workspace');
1408
+ }
1282
1409
  const stat = fsSync.statSync(target);
1410
+ if (!stat.isFile()) throw new Error('ACP read_text_file requires a regular file');
1283
1411
  if (stat.size > 4 * 1024 * 1024) throw new Error('ACP text file exceeds the 4 MiB client transfer limit');
1284
1412
  const bytes = fsSync.readFileSync(target);
1285
1413
  if (bytes.includes(0)) throw new Error('ACP read_text_file requires a text file');
@@ -1317,7 +1445,13 @@ export class AgentLoop {
1317
1445
  }
1318
1446
  }
1319
1447
  if (this.eventSink && this.eventSink.readyState === 1) {
1320
- this.eventSink.send(JSON.stringify({ taskId: this.taskId, ...messageObj }));
1448
+ let serialized: string;
1449
+ try {
1450
+ serialized = JSON.stringify({ taskId: this.taskId, ...messageObj });
1451
+ } catch {
1452
+ serialized = JSON.stringify({ taskId: this.taskId, type: String(messageObj?.type || 'notice') });
1453
+ }
1454
+ this.eventSink.send(serialized);
1321
1455
  }
1322
1456
  }
1323
1457
 
@@ -1342,15 +1476,17 @@ export class AgentLoop {
1342
1476
  */
1343
1477
  debugLog(message: string) {
1344
1478
  if (process.env.CAUSYNE_DEBUG !== '1') return;
1345
- process.stderr.write(`[causyne] ${message}\n`);
1479
+ // eslint-disable-next-line no-control-regex
1480
+ const clean = redactProviderSecrets(String(message ?? '')).replace(/[\x00-\x1f\x7f]+/g, ' ').slice(0, 4096);
1481
+ process.stderr.write(`[causyne] ${clean}\n`);
1346
1482
  }
1347
1483
 
1348
1484
 
1349
1485
  handleApprovalResponse(toolCallId: string, approved: boolean) {
1350
1486
  if (this.pendingApprovals.has(toolCallId)) {
1351
1487
  const resolve = this.pendingApprovals.get(toolCallId);
1352
- resolve(approved);
1353
1488
  this.pendingApprovals.delete(toolCallId);
1489
+ if (typeof resolve === 'function') resolve(approved === true);
1354
1490
  }
1355
1491
  }
1356
1492
 
@@ -1358,10 +1494,19 @@ export class AgentLoop {
1358
1494
  // A malformed provider plan is not permission to replace a valid plan or
1359
1495
  // crash an active run. Empty arrays remain valid and can clear the plan.
1360
1496
  if (!update || !Array.isArray(update.plan)) return;
1361
- const nextPlan = update.plan.map((item: any) => ({ ...item }));
1497
+ const nextPlan = update.plan
1498
+ .filter((item: unknown): item is Record<string, any> => Boolean(item) && typeof item === 'object')
1499
+ .map((item: Record<string, any>) => ({ ...item }));
1362
1500
  const prevText = this._implementationPlan.map((item: any) => item.step).join('\n');
1363
- const prevKey = JSON.stringify(this._implementationPlan.map((item: any) => ({ id: item.id, step: item.step, status: item.status })));
1364
- const nextKey = JSON.stringify(nextPlan.map((item: any) => ({ id: item.id, step: item.step, status: item.status })));
1501
+ const planKey = (entries: any[]): string => {
1502
+ try {
1503
+ return JSON.stringify(entries.map((item: any) => ({ id: item?.id, step: item?.step, status: item?.status })));
1504
+ } catch {
1505
+ return String(entries.length);
1506
+ }
1507
+ };
1508
+ const prevKey = planKey(this._implementationPlan);
1509
+ const nextKey = planKey(nextPlan);
1365
1510
  this._implementationPlan = nextPlan;
1366
1511
  if (options.seeded !== undefined) {
1367
1512
  this._implementationPlanSeeded = Boolean(options.seeded);
@@ -1512,15 +1657,21 @@ export class AgentLoop {
1512
1657
  }
1513
1658
 
1514
1659
  async requestDecision(request: any) {
1660
+ if (!request || typeof request !== 'object') return null;
1515
1661
  if (this.stopRequested || this.abortController?.signal?.aborted) return null;
1516
- const fingerprint = createHash('sha256')
1517
- .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option: any) => option.id) }))
1518
- .digest('hex');
1662
+ const safeOptions = Array.isArray(request.options) ? request.options : [];
1663
+ let fingerprintInput: string;
1664
+ try {
1665
+ fingerprintInput = JSON.stringify({ kind: request.kind, question: request.question, options: safeOptions.map((option: any) => option?.id ?? null) });
1666
+ } catch {
1667
+ fingerprintInput = `${String(request.kind || '')}:${String(request.question || '')}`;
1668
+ }
1669
+ const fingerprint = createHash('sha256').update(fingerprintInput).digest('hex');
1519
1670
  const remembered = request.ephemeral === true ? null : this._decisionAnswers.get(fingerprint);
1520
1671
  if (remembered) return remembered;
1521
1672
 
1522
1673
  this.emitEvent({ type: 'decision_request', request });
1523
- auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount: request.options.length });
1674
+ auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount: safeOptions.length });
1524
1675
  // CAUSYNE_ENTITLEMENT_V1: unresolved durable decisions do not consume fresh leases.
1525
1676
  this._entitlementGate?.pause();
1526
1677
  let answer: any;
@@ -1562,9 +1713,25 @@ export class AgentLoop {
1562
1713
 
1563
1714
  updateTierLimits() {
1564
1715
  this.config = loadConfig();
1565
- if (this.autonomyOverride) this.config.autonomyMode = this.autonomyOverride;
1566
- if (this.providerOverride) this.config.provider = this.providerOverride;
1567
- if (this.modelOverride) this.config.model = this.modelOverride;
1716
+ if (this.autonomyOverride) {
1717
+ const overridePreset = normalizePermissionPreset(this.autonomyOverride);
1718
+ if (overridePreset) {
1719
+ this.config.permissionPreset = overridePreset;
1720
+ this.config.autonomyMode = presetToAutonomyMode(overridePreset);
1721
+ } else {
1722
+ this.config.autonomyMode = this.autonomyOverride;
1723
+ }
1724
+ }
1725
+ const syncedPreset = resolveConfigPermissionPreset(this.config, 'workspace-write');
1726
+ this.config.permissionPreset = syncedPreset;
1727
+ if (this.sandbox) {
1728
+ this.sandbox.permissionPreset = syncedPreset;
1729
+ this.sandbox.autonomyMode = presetToAutonomyMode(syncedPreset);
1730
+ }
1731
+ applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
1732
+ if (this.variantOverride) {
1733
+ this.config.reasoningEffort = this.variantOverride;
1734
+ }
1568
1735
  if (typeof this.initializeProvider === 'function') {
1569
1736
  const nextProvider = this.initializeProvider();
1570
1737
  if (nextProvider) {
@@ -1994,14 +2161,56 @@ export class AgentLoop {
1994
2161
  });
1995
2162
  }
1996
2163
  } else if (att.type === 'document') {
2164
+ if (typeof att.name !== 'string' || typeof att.base64 !== 'string' || !att.base64.trim()) {
2165
+ this.notice('skipped malformed document attachment', 'warn');
2166
+ continue;
2167
+ }
1997
2168
  const fs = await import('fs');
1998
2169
  const path = await import('path');
1999
2170
  // Ensure unique name to prevent overwriting
2000
- const safeName = att.name.replace(/[^a-zA-Z0-9.\-_]/g, '_');
2001
- const writePath = path.join(this.workspaceRoot, safeName);
2002
- fs.writeFileSync(writePath, Buffer.from(att.base64, 'base64'));
2171
+ const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024;
2172
+ if (att.base64.length > Math.ceil(MAX_ATTACHMENT_BYTES * 4 / 3) + 64) {
2173
+ this.notice('skipped oversized document attachment (exceeds 16 MiB limit)', 'warn');
2174
+ continue;
2175
+ }
2176
+ const decodedBytes = Buffer.from(att.base64, 'base64');
2177
+ if (decodedBytes.length > MAX_ATTACHMENT_BYTES) {
2178
+ this.notice('skipped oversized document attachment (exceeds 16 MiB limit)', 'warn');
2179
+ continue;
2180
+ }
2181
+ const baseName = path.basename(att.name).replace(/[^a-zA-Z0-9.\-_]/g, '_').replace(/^\.+/, '');
2182
+ const safeName = (!baseName || baseName === '.' || baseName === '..') ? 'attachment.bin' : baseName.slice(0, 128);
2183
+ const realWorkspaceRoot = physicalPath(this.workspaceRoot);
2184
+ if (!realWorkspaceRoot) {
2185
+ this.notice('skipped document attachment: workspace root could not be resolved', 'warn');
2186
+ continue;
2187
+ }
2188
+ const ext = path.extname(safeName);
2189
+ const stem = ext ? safeName.slice(0, -ext.length) : safeName;
2190
+ let finalName = safeName;
2191
+ let writePath = '';
2192
+ let saved = false;
2193
+ for (let attempt = 0; attempt < 100; attempt++) {
2194
+ finalName = attempt === 0 ? safeName : `${stem}-${attempt}${ext}`;
2195
+ const candidatePath = path.join(realWorkspaceRoot, finalName);
2196
+ const resolvedCandidate = physicalPath(candidatePath);
2197
+ if (!resolvedCandidate || !isWithinPhysicalPath(resolvedCandidate, realWorkspaceRoot)) break;
2198
+ try {
2199
+ fs.writeFileSync(candidatePath, decodedBytes, { flag: 'wx', mode: 0o600 });
2200
+ writePath = candidatePath;
2201
+ saved = true;
2202
+ break;
2203
+ } catch (writeErr: unknown) {
2204
+ if ((writeErr as NodeJS.ErrnoException)?.code === 'EEXIST') continue;
2205
+ throw writeErr;
2206
+ }
2207
+ }
2208
+ if (!saved) {
2209
+ this.notice(`could not save attached document '${safeName}' safely without overwriting`, 'warn');
2210
+ continue;
2211
+ }
2003
2212
 
2004
- 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.]`;
2213
+ 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.]`;
2005
2214
  this.notice(`saved attached document to ${writePath}`);
2006
2215
  }
2007
2216
  }
@@ -2050,7 +2259,7 @@ export class AgentLoop {
2050
2259
  if (!this.currentTaskPrompt && this.userPrompt) {
2051
2260
  this.currentTaskPrompt = this.userPrompt;
2052
2261
  }
2053
- const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
2262
+ const isAutonomousMode = this.activePermissionPreset() === 'danger-full-access';
2054
2263
  const recoveryPaths = new Set<string>();
2055
2264
  let modelCallIndex = 0;
2056
2265
  let softUsageNoticeIssued = false;
@@ -2105,18 +2314,26 @@ export class AgentLoop {
2105
2314
  // replaced by a summary, so memory, disk and CPU all stay bounded.
2106
2315
 
2107
2316
  const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
2108
- const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool, {
2317
+ const rawCharPool = resolveCharPool(activeTier, this.config.maxCharPool, {
2109
2318
  provider: this.config.provider,
2110
2319
  model: this.config.model,
2111
2320
  overrideTokens: this.config.contextTokens || this.config.maxContextTokens
2112
2321
  });
2322
+ // Keep MAX_CHAR_POOL as the true model context ceiling for accurate usage reporting,
2323
+ // while reserving 25% compaction headroom for system prompt, tool schemas, and output tokens.
2324
+ const MAX_CHAR_POOL = rawCharPool;
2325
+ const COMPACTION_CHAR_POOL = this.config.maxCharPool
2326
+ ? MAX_CHAR_POOL
2327
+ : Math.max(24_000, Math.floor(MAX_CHAR_POOL * 0.75));
2113
2328
 
2114
2329
  // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
2115
- // Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
2116
- // Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
2330
+ // Under low context pressure (<25% of pool), keep more recent small file reads
2331
+ // verbatim so models do not lose a 1-2 KB source file after four tool calls.
2332
+ const currentMessageChars = measureMessages(this.messages);
2333
+ const lowContextPressure = currentMessageChars < COMPACTION_CHAR_POOL * 0.25;
2117
2334
  const observationPrune = pruneStaleToolObservations(this.messages, {
2118
- keepRecent: this.config.keepRecentToolResults ?? 4,
2119
- minChars: 600,
2335
+ keepRecent: this.config.keepRecentToolResults ?? (lowContextPressure ? 12 : 4),
2336
+ minChars: lowContextPressure ? 2400 : 600,
2120
2337
  taskId: this.taskId
2121
2338
  });
2122
2339
  const argumentPrune = pruneExecutedToolArguments(this.messages, { taskId: this.taskId });
@@ -2127,7 +2344,7 @@ export class AgentLoop {
2127
2344
  for (const message of this.messages) {
2128
2345
  if (typeof message.spillPath === 'string') recoveryPaths.add(path.resolve(message.spillPath));
2129
2346
  }
2130
- const compaction = applyProgressiveCompaction(this.messages, MAX_CHAR_POOL, {
2347
+ const compaction = applyProgressiveCompaction(this.messages, COMPACTION_CHAR_POOL, {
2131
2348
  // historyPruner preserves full output before eliding it. The legacy
2132
2349
  // decay path cannot promise that recovery, so keep it disabled here.
2133
2350
  enableEphemeralDecay: false,
@@ -2156,7 +2373,7 @@ export class AgentLoop {
2156
2373
  });
2157
2374
  }
2158
2375
 
2159
- const { window: slidingWindow, splitIndex } = buildWindow(this.messages, MAX_CHAR_POOL);
2376
+ const { window: slidingWindow, splitIndex } = buildWindow(this.messages, COMPACTION_CHAR_POOL);
2160
2377
 
2161
2378
  // What the context window actually holds right now.
2162
2379
  //
@@ -2172,19 +2389,19 @@ export class AgentLoop {
2172
2389
  this._contextChars = measureMessages(slidingWindow);
2173
2390
  this._contextLimitChars = MAX_CHAR_POOL;
2174
2391
 
2175
- // Real compaction: physically collapse the amputated range so the array
2176
- // stops growing. Index 0 (the Root Anchor / original user intent) is
2177
- // never compacted away.
2392
+ // Real compaction: physically collapse the amputated range at a turn-safe
2393
+ // boundary so role=tool results are never orphaned from their tool_calls.
2178
2394
  if (splitIndex >= 1) {
2179
- const dropped = this.messages.slice(1, splitIndex + 1);
2180
- if (dropped.length > 0) {
2395
+ const safeSplit = findSafeCompactionSplitIndex(this.messages, splitIndex);
2396
+ const dropped = safeSplit >= 1 ? this.messages.slice(1, safeSplit + 1) : [];
2397
+ if (dropped.length > 0 && safeSplit >= 1) {
2181
2398
  const compactSummary = buildRecoverableDroppedSummary(
2182
2399
  dropped,
2183
2400
  buildCodexStyleSummary(dropped, this.currentTaskPrompt || this.userPrompt)
2184
2401
  || buildStructuralSummary(dropped)
2185
2402
  || describeDroppedMessages(dropped)
2186
2403
  );
2187
- const removed = compactInPlace(this.messages, splitIndex, compactSummary);
2404
+ const removed = compactInPlace(this.messages, safeSplit, compactSummary);
2188
2405
  this._lastCompactionIndex = null;
2189
2406
  this.debugLog(`compacted ${removed} messages out of the live context`);
2190
2407
  auditLog.log({
@@ -2214,14 +2431,22 @@ export class AgentLoop {
2214
2431
  // All transports receive the same compact catalog and selected host
2215
2432
  // schemas. Peer-native tools and native schema deferral remain provider
2216
2433
  // features; neither changes host authorization or schema selection.
2217
- const eligibleTools = await getDynamicTools(this.config.autonomyMode, this.llm.supportsVision, {
2434
+ const activePreset = this.activePermissionPreset();
2435
+ const eligibleTools = await getDynamicTools(activePreset, this.llm.supportsVision, {
2218
2436
  grantAllTools: true,
2219
2437
  allowedTools: this.sandbox.allowedTools,
2220
2438
  deniedTools: this.config.deniedTools
2221
2439
  });
2222
2440
  await this.ensureToolsList(eligibleTools);
2441
+ const promptForDomain = this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '';
2442
+ const liveBrowserAwareness = causyneBrowser({ workspace: this.workspaceRoot }).getLiveAwarenessContext();
2443
+ const sharedBrowserRelevant = liveBrowserAwareness.active || SHARED_BROWSER_INTENT_RE.test(promptForDomain);
2444
+ if (sharedBrowserRelevant) {
2445
+ this.savedTools.admitTool('browser_act');
2446
+ }
2223
2447
  const permittedTools = this.toolScope instanceof Set && this.toolScope.size > 0
2224
- ? eligibleTools.filter((tool: { name: string }) => this.toolScope.has(tool.name)) : eligibleTools;
2448
+ ? eligibleTools.filter((tool: { name: string }) => this.toolScope.has(tool.name) || (sharedBrowserRelevant && tool.name === 'browser_act'))
2449
+ : eligibleTools;
2225
2450
  const dynamicTools = this.smartTools.schemas(permittedTools, this.unlockedTools, this.unlockedPacks,
2226
2451
  this.config.grantAllTools === true);
2227
2452
  const dynamicToolNames = dynamicTools.map((t: any) => t.name);
@@ -2243,25 +2468,33 @@ export class AgentLoop {
2243
2468
  }
2244
2469
 
2245
2470
  // Dynamically inject the absolute latest System context
2246
- const autonomyMode = this.config.autonomyMode || 'C';
2471
+ const activePresetDesc = getPermissionPresetDescriptor(activePreset);
2472
+ const permissionPolicyLine = renderPermissionPolicyContext(activePreset, this.workspaceRoot);
2247
2473
  const allowedPaths = this.sandbox.grantAllAccess
2248
2474
  ? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
2249
2475
  : (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
2250
2476
  const baseProviderPrompt = getProviderSpecificPrompt(this.config.provider);
2251
- const sensoryAwareness = this.llm.supportsVision
2252
- ? `\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE
2253
- You have native multimodal vision perception. You can perceive rendered images, screenshots, and visual outputs directly.
2254
- - 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.
2255
- - If visual rendering reveals visual bugs, layout misalignment, or runtime glitches, you must fix the code and re-verify before claiming completion.`
2256
- : `\n# SENSORY PROFILE: TEXT & CODE ENGINE (VISION INACTIVE)
2257
- You are operating in a text-and-code modality without direct image pixel rendering.
2258
- - For Web, UI, 3D, and visual tasks: Do NOT attempt raw visual inspection expecting image perception. Instead, verify programmatically:
2259
- 1. Inspect the rendered DOM structure, computed hierarchy, and elements via browser_act (scrape / snapshot).
2260
- 2. Check for JavaScript console and runtime errors (browser_act runtimeErrors).
2261
- 3. Validate syntax and runtime integrity with code_verify_syntax and unit tests.
2262
- 4. Perform thorough code inspection of generated math, physics, and canvas render loops to ensure zero defects.
2263
- - For non-visual tasks (backend, CLI, algorithms): Verify using standard test suites and execution logs.`;
2264
- const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}`;
2477
+ const domainArchetype = determineToolScope(promptForDomain, this.taskShape).archetype;
2478
+ const isVisualOrWebTask = isWebIntent(promptForDomain)
2479
+ || this.hasWebSurfaceArtifacts()
2480
+ || domainArchetype === 'web_engineering'
2481
+ || domainArchetype === 'game_development'
2482
+ || domainArchetype === 'media_3d_generation';
2483
+ const sensoryAwareness = isVisualOrWebTask
2484
+ ? (this.llm.supportsVision
2485
+ ? `\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE
2486
+ 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.`
2487
+ : `\n# SENSORY PROFILE: TEXT & CODE ENGINE (VISION INACTIVE)
2488
+ Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeErrors), code_verify_syntax, and unit tests.`)
2489
+ : (this.llm.supportsVision
2490
+ ? '\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE'
2491
+ : '\n# SENSORY PROFILE: TEXT & CODE ENGINE — verify changes via project tests, typechecks, and execution logs.');
2492
+ const domainPrompts = [
2493
+ (this.unlockedPacks.has('reverse_engineering') || domainArchetype === 'reverse_engineering') ? REA_SUBSTRATE_PROMPT : '',
2494
+ (ANDROID_CONTEXT_RE.test(promptForDomain) || ANDROID_CONTEXT_RE.test(String(this.workspaceContext?.projectType || ''))) ? ANDROID_TOOLCHAIN_PROMPT : '',
2495
+ isVisualOrWebTask ? WEB_VERIFICATION_PROMPT : ''
2496
+ ].join('');
2497
+ const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}${domainPrompts}`;
2265
2498
  const memoryContext = getMemoryContextString({ workspaceRoot: this.workspaceRoot });
2266
2499
 
2267
2500
  // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
@@ -2273,7 +2506,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2273
2506
  if (!this.staticContext) {
2274
2507
  this.staticContext = await this.buildStaticContext();
2275
2508
  }
2276
- const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext } = this.staticContext;
2509
+ const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext, projectInstructions } = this.staticContext;
2277
2510
 
2278
2511
  // --- WORKSPACE AWARENESS ---
2279
2512
  // perception.buildContext() output used to be computed and discarded,
@@ -2376,6 +2609,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
2376
2609
  this.debugLog(`uncertainty gate skipped: ${e.message}`);
2377
2610
  }
2378
2611
 
2612
+ const effectivePeerMcpServers: McpServer[] = Array.isArray(this.peerMcpServers)
2613
+ ? [...this.peerMcpServers]
2614
+ : [];
2615
+ const hasConfiguredBrowserMcp = effectivePeerMcpServers.some((srv) => srv?.name === 'causyne-browser');
2616
+ if (!hasConfiguredBrowserMcp && isAcpProvider(this.config?.provider) && !process.env.NODE_TEST_CONTEXT) {
2617
+ effectivePeerMcpServers.push({
2618
+ name: 'causyne-browser',
2619
+ command: process.execPath,
2620
+ args: [CAUSYNE_CLI_BIN_PATH, 'browser-mcp', '--workspace', this.workspaceRoot],
2621
+ env: []
2622
+ });
2623
+ }
2624
+ const hasBrowserMcpAttached = effectivePeerMcpServers.some((srv) => srv?.name === 'causyne-browser');
2625
+ const sharedBrowserPrompt = buildSharedBrowserAwarenessPrompt(liveBrowserAwareness, hasBrowserMcpAttached);
2626
+
2627
+ const isLocalOllama = String(this.config?.provider || '').trim().toLowerCase() === 'ollama';
2628
+ const effectiveToolsListText = resolveToolsCatalogPromptBlock(
2629
+ this.config?.provider,
2630
+ this.toolsListText || renderToolsList(buildToolsList())
2631
+ );
2379
2632
  const systemMessages = [
2380
2633
  // [1] stable for the entire task — the primary cache anchor.
2381
2634
  { role: 'system', content: SYSTEM_PROMPT, cacheAnchor: true },
@@ -2383,7 +2636,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2383
2636
  // is stable within a task and gets its own breakpoint.
2384
2637
  {
2385
2638
  role: 'system',
2386
- content: `${taskBrief ? taskBrief + '\n\n' : ''}${this.toolsListText || renderToolsList(buildToolsList())}${activePlaybooks ? '\n\n' + activePlaybooks : ''}`,
2639
+ content: `${taskBrief ? taskBrief + '\n\n' : ''}${effectiveToolsListText}${activePlaybooks ? '\n\n' + activePlaybooks : ''}`,
2387
2640
  cacheAnchor: true
2388
2641
  },
2389
2642
  // [3] per-task STATIC context — provider activation, detected design,
@@ -2392,7 +2645,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2392
2645
  // is byte-identical every step; cached.
2393
2646
  {
2394
2647
  role: 'system',
2395
- content: `${providerPrompt}${designContext}${workspaceSummary}${lessonsLearned}${episodicContext ? '\n\n' + episodicContext : ''}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}\n${universalSkillsContext}`,
2648
+ content: `${providerPrompt}${designContext}${workspaceSummary}${projectInstructions || ''}${lessonsLearned}${!isLocalOllama && episodicContext ? '\n\n' + episodicContext : ''}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}${!isLocalOllama && universalSkillsContext ? '\n' + universalSkillsContext : ''}`,
2396
2649
  cacheAnchor: true
2397
2650
  },
2398
2651
  // [4] THE INVOKED SKILL, when the user named one.
@@ -2408,13 +2661,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
2408
2661
  // time a different skill is invoked. This one is stable for the task,
2409
2662
  // so it anchors too.
2410
2663
  ...(skillSystemMessage(this.activeSkill) || []),
2664
+ ...(this.hostSystemInstructions ? [{ role: 'system', content: this.hostSystemInstructions }] : []),
2411
2665
  // [5] VOLATILE tail — the only bytes that may differ between steps:
2412
- // autonomy/workspace paths (change via config) and persistent memory
2413
- // (grows via memory_write mid-task). Kept LAST and UNcached so a change
2414
- // here never invalidates the cached prefix in [1]-[3].
2666
+ // autonomy/workspace paths (change via config), live shared browser
2667
+ // state, and persistent memory (grows via memory_write mid-task).
2668
+ // Kept LAST and UNcached so a change here never invalidates [1]-[3].
2415
2669
  {
2416
2670
  role: 'system',
2417
- 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}` : ''}`
2671
+ content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}PERMISSION PRESET: ${activePresetDesc.label} (${activePreset})\n${permissionPolicyLine}\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}` : ''}`
2418
2672
  }
2419
2673
  ];
2420
2674
 
@@ -2562,6 +2816,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2562
2816
  const response = await this.llm.chat(prunedMessages, {
2563
2817
  taskId: this.taskId,
2564
2818
  conversationId: this.memoryManager?.sessionId || this.taskId,
2819
+ cacheKey: `causyne_${createHash('sha256').update(`${this.workspaceRoot}:${this.memoryManager?.sessionId || this.taskId}`).digest('hex').slice(0, 32)}`,
2565
2820
  taskIntent: isLaunchOnlyPrompt(this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
2566
2821
  taskArchetype: determineToolScope(this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
2567
2822
  hardBudget: hardBudget,
@@ -2581,6 +2836,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2581
2836
  ? remainingBudget : undefined,
2582
2837
  taskDeadlineMs: this._taskWallDeadlineAt ?? undefined,
2583
2838
  workspaceRoot: this.workspaceRoot,
2839
+ ...(effectivePeerMcpServers.length > 0 ? { peerMcpServers: effectivePeerMcpServers } : {}),
2584
2840
  onPeerPermission: (request: RequestPermissionRequest) => this.requestPeerPermission(request),
2585
2841
  onPeerFileRead: (file: string, options?: { line?: number; limit?: number }) => this.executePeerFile('fs_read', file, undefined, options),
2586
2842
  onPeerFileWrite: async (file: string, content: string) => { await this.executePeerFile('fs_write', file, content); },
@@ -2642,6 +2898,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2642
2898
  if (cleanProse && !cleanProse.startsWith('```')) {
2643
2899
  this.emitEvent({
2644
2900
  type: 'agent_message',
2901
+ streamId: invocation,
2645
2902
  content: cleanProse,
2646
2903
  delta: _chunk,
2647
2904
  streaming: true
@@ -2798,7 +3055,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
2798
3055
  });
2799
3056
  } else if (action.status === 'failed') {
2800
3057
  this.emitEvent({ type: 'status', message: '' });
2801
- this.emitEvent({ type: 'warning', message: `${this.config.provider || 'Provider'} could not ${action.name}${detail}` });
3058
+ this.emitEvent({
3059
+ type: 'warning',
3060
+ nativeStep: true,
3061
+ nativeFailed: true,
3062
+ actionName: action.name,
3063
+ detail: action.detail,
3064
+ message: `${this.config.provider || 'Provider'} could not ${action.name}${detail}`
3065
+ });
2802
3066
  }
2803
3067
  }
2804
3068
  }).catch((error: unknown) => {
@@ -2905,6 +3169,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2905
3169
  // the project's own CHAR_POOLS convention, instead of comparing a token
2906
3170
  // count to a character limit.
2907
3171
  const reportedPromptTokens = Number(response.usage?.promptTokens || 0);
3172
+ const reportedCompletionTokens = Number(response.usage?.completionTokens || 0);
2908
3173
  if (response.usage?.measurement === 'provider_reported'
2909
3174
  && response.usage?.measurementScope !== 'cumulative'
2910
3175
  && Number.isFinite(reportedPromptTokens)
@@ -2928,9 +3193,22 @@ You are operating in a text-and-code modality without direct image pixel renderi
2928
3193
  lifetimeCostUsd: tracking.lifetimeCostUsd || 0,
2929
3194
  contextChars: this._contextChars || 0,
2930
3195
  contextLimitChars: this._contextLimitChars || 0,
2931
- cachedTokens
3196
+ cachedTokens,
3197
+ inputTokens: Number.isFinite(reportedPromptTokens) && reportedPromptTokens > 0 ? reportedPromptTokens : 0,
3198
+ outputTokens: Number.isFinite(reportedCompletionTokens) && reportedCompletionTokens > 0 ? reportedCompletionTokens : 0
2932
3199
  });
2933
3200
 
3201
+ const taskCostCap = typeof (this as any).taskCostLimitUsd === 'number' && Number.isFinite((this as any).taskCostLimitUsd) && (this as any).taskCostLimitUsd > 0
3202
+ ? (this as any).taskCostLimitUsd as number
3203
+ : null;
3204
+ if (taskCostCap !== null && (tracking.taskCostUsd || 0) >= taskCostCap) {
3205
+ this.emitEvent({
3206
+ type: 'error',
3207
+ message: `Task USD budget limit reached ($${(tracking.taskCostUsd || 0).toFixed(4)} >= $${taskCostCap.toFixed(4)}).`
3208
+ });
3209
+ break;
3210
+ }
3211
+
2934
3212
  if (!tracking.allowed) {
2935
3213
  this.emitEvent({ type: 'error', message: tracking.reason });
2936
3214
  break;
@@ -3320,7 +3598,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3320
3598
  if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations < 3) {
3321
3599
  incompleteTurnContinuations++;
3322
3600
  if (response.content) {
3323
- this.emitEvent({ type: 'agent_message', content: response.content });
3601
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: response.content });
3324
3602
  }
3325
3603
  const blockedNote = failedExternalActions.length > 0
3326
3604
  ? ` 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.`
@@ -3340,7 +3618,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3340
3618
  if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations === 3) {
3341
3619
  incompleteTurnContinuations++;
3342
3620
  if (response.content) {
3343
- this.emitEvent({ type: 'agent_message', content: response.content });
3621
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: response.content });
3344
3622
  }
3345
3623
  this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
3346
3624
  this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
@@ -3365,7 +3643,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3365
3643
  .replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
3366
3644
  .trim();
3367
3645
  if (partial.length >= 20) {
3368
- this.emitEvent({ type: 'agent_message', content: partial });
3646
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: partial });
3369
3647
  }
3370
3648
  this.emitEvent({ type: 'error', message:
3371
3649
  'The peer ended with an incomplete or progress-only turn. ' +
@@ -3402,10 +3680,17 @@ You are operating in a text-and-code modality without direct image pixel renderi
3402
3680
  if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
3403
3681
  if (this.stepsCompleted > 0 && incompleteTurnContinuations < 2 && failedExternalActions.length === 0) {
3404
3682
  incompleteTurnContinuations++;
3405
- this.emitEvent({ type: 'status', message: 'Requesting the missing final response…' });
3406
- this.messages.push({ role: 'system', content:
3407
- '[FINAL RESPONSE REQUIRED] Report actual completed and incomplete work from tool results. ' +
3408
- 'Do not call plan steps or file writes proof of verification.' });
3683
+ if (isActionable && taskMutationCount === 0 && !isLaunchOnlyPrompt(taskPrompt) && !isPlanningOnlyRequest(taskPrompt)) {
3684
+ this.emitEvent({ type: 'status', message: 'Continuing execution after reasoning-only turn…' });
3685
+ this.messages.push({ role: 'system', content:
3686
+ '[CONTINUE EXECUTION] Your previous turn produced reasoning without invoking a tool or applying the requested changes. ' +
3687
+ 'Continue immediately by calling the appropriate tool (such as fs_edit, apply_patch, fs_write, or sysRun) to implement and verify the task.' });
3688
+ } else {
3689
+ this.emitEvent({ type: 'status', message: 'Requesting the missing final response…' });
3690
+ this.messages.push({ role: 'system', content:
3691
+ '[FINAL RESPONSE REQUIRED] Report actual completed and incomplete work from tool results. ' +
3692
+ 'Do not call plan steps or file writes proof of verification.' });
3693
+ }
3409
3694
  this.memoryManager.saveHistory(this.messages);
3410
3695
  continue;
3411
3696
  }
@@ -3780,6 +4065,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
3780
4065
  const finalToolOutcomes = coldObserver.getToolOutcomes(this.taskId);
3781
4066
  const finalToolOutcome = finalToolOutcomes[finalToolOutcomes.length - 1];
3782
4067
  if (this.stepsCompleted > 0 && finalToolOutcome && !finalToolOutcome.success) {
4068
+ const blockerExplanation = typeof response.content === 'string'
4069
+ ? response.content
4070
+ .replace(/^Antigravity executed:[^\n]*\n*/i, '')
4071
+ .replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
4072
+ .trim()
4073
+ : '';
4074
+ if (blockerExplanation.length >= 20) {
4075
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: blockerExplanation });
4076
+ }
3783
4077
  this.emitEvent({ type: 'error', message:
3784
4078
  `The last observed tool action failed (${finalToolOutcome.tool}). ` +
3785
4079
  'Resolve the error or report partial work; no success has been recorded.' });
@@ -3792,12 +4086,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
3792
4086
  const outcomes = coldObserver.getToolOutcomes(this.taskId);
3793
4087
  const hasCodeOrWorkspaceMutation = this.webArtifacts.size > 0 || outcomes.some((o: any) =>
3794
4088
  o.success !== false && [
3795
- 'fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit', 'multi_edit',
4089
+ 'fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit', 'multi_edit', 'apply_patch',
3796
4090
  'ui_forge', 'write_file', 'write_to_file', 'edit_file', 'replace_file_content',
3797
4091
  'multi_replace_file_content', 'native_engine', 'update_plan'
3798
4092
  ].includes(String(o.tool || ''))
3799
4093
  );
3800
- if (!hasCodeOrWorkspaceMutation && completedNativeActionIds.size === 0) {
4094
+ const rawReply = typeof response.content === 'string' ? response.content.trim() : '';
4095
+ const hasVerifiedFailureBlocker = outcomes.some((o: any) => o.success === false)
4096
+ && rawReply.length >= 25
4097
+ && /\b(?:blocked|cannot|unable|missing|permission denied|not installed|failed|error)\b/i.test(rawReply);
4098
+ if (!hasCodeOrWorkspaceMutation && completedNativeActionIds.size === 0 && !hasVerifiedFailureBlocker) {
3801
4099
  if (this._nonMutationNudges === undefined) this._nonMutationNudges = 0;
3802
4100
  if (this._nonMutationNudges < 2) {
3803
4101
  this._nonMutationNudges++;
@@ -3828,7 +4126,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3828
4126
 
3829
4127
  const substantiveTerminalContent = cleanTerminalContent(response.content);
3830
4128
  if (substantiveTerminalContent.length >= 20) {
3831
- this.emitEvent({ type: 'agent_message', content: substantiveTerminalContent });
4129
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: substantiveTerminalContent });
3832
4130
  } else {
3833
4131
  const recentSubstantive = [...this.messages].reverse().find(m =>
3834
4132
  m.role === 'assistant'
@@ -3852,7 +4150,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
3852
4150
  content: `Task completed successfully.${planSummary}`
3853
4151
  });
3854
4152
  } else if (response.content) {
3855
- this.emitEvent({ type: 'agent_message', content: response.content });
4153
+ this.emitEvent({ type: 'agent_message', streamId: invocation, content: response.content });
3856
4154
  }
3857
4155
  }
3858
4156
  if (this.stepsCompleted > 0) {
@@ -4047,7 +4345,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4047
4345
  let actionSig = `${functionName}:${JSON.stringify(args || {})}`;
4048
4346
  if (functionName === 'sysRun' || functionName === 'sysRunBg') {
4049
4347
  const rawCmd = String(args?.command || '').trim();
4050
- if (/python[0-9.]*\s+.*import\s+numpy/i.test(rawCmd)) {
4348
+ if (/\bpython[0-9.]*\s/i.test(rawCmd) && /\bimport\s+numpy\b/i.test(rawCmd)) {
4051
4349
  actionSig = 'sysRun:probe:numpy';
4052
4350
  } else if (/python[0-9.]*\s+(--version|-V|-c\s+['"]print)/i.test(rawCmd)) {
4053
4351
  actionSig = 'sysRun:probe:python';
@@ -4160,8 +4458,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
4160
4458
  // 4-Layer Security Sandbox Validation
4161
4459
  // 2. Sandbox Security Validation (CRITICAL FIX: Prevent Infinite Loop on Block)
4162
4460
  let validation = this.sandbox.validate(functionName, args);
4461
+ const recoveryCandidatePath = args.path ?? args.file_path ?? args.target ?? args.dir;
4163
4462
  if (!validation.allowed && /^Path outside allowed workspace:/.test(validation.reason || '')
4164
- && isOutputRecoveryRead(functionName, args.path, recoveryPaths)) {
4463
+ && isOutputRecoveryRead(functionName, recoveryCandidatePath, recoveryPaths)) {
4165
4464
  validation = { allowed: true, risk: 'safe', reason: 'Read exact tool output referenced by this session' };
4166
4465
  }
4167
4466
  if (!validation.allowed) {
@@ -4332,21 +4631,86 @@ You are operating in a text-and-code modality without direct image pixel renderi
4332
4631
  // Cold observer mutation assessment fail-open
4333
4632
  }
4334
4633
 
4335
- // A standing grant can avoid repeat prompts in supervised modes.
4336
- // Mode C is autonomous for in-scope work. Whole-file deletion asks
4634
+ // Declarative enterprise policy (`causyne.policy.json`): deterministic
4635
+ // allow / ask / deny gate outside the model. Runs after Sandbox and Cold
4636
+ // Observer so it can never weaken workspace isolation or observer vetoes.
4637
+ const enterpriseDecision = evaluateEnterprisePolicy({
4638
+ tool: functionName,
4639
+ args,
4640
+ workspaceRoot: this.workspaceRoot
4641
+ });
4642
+ if (enterpriseDecision.effect === 'deny') {
4643
+ this.emitEvent({
4644
+ type: 'status',
4645
+ message: `Enterprise Policy Denied: ${enterpriseDecision.reason}`
4646
+ });
4647
+ auditLog.log({
4648
+ event: 'enterprise_policy_denied',
4649
+ taskId: this.taskId,
4650
+ tool: functionName,
4651
+ dimension: enterpriseDecision.matchedDimension,
4652
+ rule: enterpriseDecision.matchedRule,
4653
+ reason: enterpriseDecision.reason
4654
+ });
4655
+ coldObserver.recordToolOutcome(this.taskId, functionName, args, {
4656
+ success: false,
4657
+ error: `[ENTERPRISE POLICY DENIED]: ${enterpriseDecision.reason}`
4658
+ });
4659
+ this.messages.push({
4660
+ role: 'tool',
4661
+ tool_call_id: toolCall.id,
4662
+ name: functionName,
4663
+ content: JSON.stringify({
4664
+ success: false,
4665
+ error: `[ENTERPRISE POLICY DENIED]: ${enterpriseDecision.reason}`
4666
+ })
4667
+ });
4668
+ continue;
4669
+ }
4670
+
4671
+ // A standing grant can avoid repeat prompts in Workspace Write.
4672
+ // Full access runs in-scope work directly. Whole-file deletion asks
4337
4673
  // unless this session explicitly granted the fs_delete tool; a broad
4338
4674
  // shell grant cannot authorize deletion. Sandbox denials and observer
4339
4675
  // vetoes have already run and are never lifted by prompt policy.
4676
+ const stepPreset = this.activePermissionPreset();
4340
4677
  const standingApproval = this.isAlwaysAllowed(functionName);
4341
- const needsToolApproval = requiresToolApproval({
4342
- mode: this.config.autonomyMode || 'C',
4678
+ let needsToolApproval = requiresToolApproval({
4679
+ permissionPreset: stepPreset,
4680
+ mode: presetToAutonomyMode(stepPreset),
4343
4681
  tool: functionName,
4344
4682
  args,
4345
4683
  risk: validation.risk,
4346
4684
  heavyDownload: isHeavyAiDownload,
4685
+ reason: validation.reason,
4347
4686
  standingApproval
4348
4687
  });
4349
- if (standingApproval && !needsToolApproval && this.config.autonomyMode !== 'C') {
4688
+ if (enterpriseDecision.effect === 'ask') {
4689
+ needsToolApproval = true;
4690
+ auditLog.log({
4691
+ event: 'enterprise_policy_ask',
4692
+ taskId: this.taskId,
4693
+ tool: functionName,
4694
+ dimension: enterpriseDecision.matchedDimension,
4695
+ rule: enterpriseDecision.matchedRule,
4696
+ reason: enterpriseDecision.reason
4697
+ });
4698
+ } else if (
4699
+ enterpriseDecision.effect === 'allow'
4700
+ && !isWholeFileDeletion(functionName, args)
4701
+ && !isHeavyAiDownload
4702
+ ) {
4703
+ needsToolApproval = false;
4704
+ auditLog.log({
4705
+ event: 'enterprise_policy_allowed',
4706
+ taskId: this.taskId,
4707
+ tool: functionName,
4708
+ dimension: enterpriseDecision.matchedDimension,
4709
+ rule: enterpriseDecision.matchedRule,
4710
+ reason: enterpriseDecision.reason
4711
+ });
4712
+ }
4713
+ if (standingApproval && !needsToolApproval && stepPreset !== 'danger-full-access' && enterpriseDecision.effect !== 'allow') {
4350
4714
  auditLog.log({
4351
4715
  event: 'approval_auto_granted', taskId: this.taskId,
4352
4716
  tool: functionName, risk: validation.risk, reason: 'allow_always'
@@ -4500,8 +4864,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
4500
4864
 
4501
4865
  this._networkHostGuard.after(functionName, args, result);
4502
4866
 
4503
- if (result && result.success !== false && !result.error && ['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
4504
- this.recordWebArtifact(args.path || args.file_path);
4867
+ if (result && result.success !== false && !result.error) {
4868
+ if (['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
4869
+ this.recordWebArtifact(args.path || args.file_path);
4870
+ } else if (functionName === 'apply_patch' && typeof args.patch === 'string') {
4871
+ for (const patchPath of extractPatchTargetPaths(args.patch).paths) {
4872
+ this.recordWebArtifact(patchPath);
4873
+ }
4874
+ }
4505
4875
  }
4506
4876
 
4507
4877
  if (result && result.success !== false && !result.error && ['fs_read', 'view_file', 'read_file'].includes(functionName)) {
@@ -4536,7 +4906,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4536
4906
  }
4537
4907
  }
4538
4908
 
4539
- if (result?.success === true && ['fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit'].includes(functionName)) clearSysRunCache();
4909
+ if (result?.success === true && ['fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit', 'apply_patch'].includes(functionName)) clearSysRunCache();
4540
4910
 
4541
4911
  // The journal is the observer's own record of what actually ran. It
4542
4912
  // is written only after post-hook review, so a formatter that rejects
@@ -4660,7 +5030,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4660
5030
 
4661
5031
  // Sovereign 100-Step Circuit Breaker Checkpoint Gate
4662
5032
  if (this.consecutiveCommands === 100 && !this.circuitBreakerUnlocked) {
4663
- if (this.config.autonomyMode === 'C') {
5033
+ if (this.activePermissionPreset() === 'danger-full-access') {
4664
5034
  this.circuitBreakerUnlocked = true;
4665
5035
  this.emitEvent({ type: 'status', message: `Continuing within the configured ${this.maxSteps}-step task limit.` });
4666
5036
  } else {
@@ -4691,7 +5061,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
4691
5061
 
4692
5062
  // Sovereign Tier Budget Extension Checkpoint Gate
4693
5063
  if (this.stepsCompleted >= this.maxSteps && !this.stopRequested) {
4694
- if (this.config.autonomyMode === 'C') {
5064
+ if (this.activePermissionPreset() === 'danger-full-access') {
4695
5065
  this.stopRequested = true;
4696
5066
  this.emitEvent({ type: 'error', message: `Task reached the configured ${this.maxSteps}-step limit without verified completion.` });
4697
5067
  } else {
@@ -4790,11 +5160,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
4790
5160
  // Per tool, not one number for all of them. A build log and a
4791
5161
  // source file are not equally worth their space in the window.
4792
5162
  // Compatibility fallback preserves complete output when primary store is unavailable.
5163
+ const isRecoveryRead = functionName === 'fs_read' && isOutputRecoveryRead(functionName, args?.path ?? args?.file_path ?? args?.target, recoveryPaths);
4793
5164
  const MAX_RESULT_CHARS = resultCapFor(functionName);
4794
- const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
5165
+ const inlineLimit = Math.min(MAX_RESULT_CHARS, functionName === 'fs_read_skill' || functionName === 'fs_read' ? 16000 : functionName === 'tool_search' ? 8000 : 2500);
4795
5166
  const originalFingerprint = createHash('sha256').update(resultString).digest('hex');
4796
5167
  let spill = null;
4797
- if (resultString.length > inlineLimit) {
5168
+ if (!isRecoveryRead && resultString.length > inlineLimit) {
4798
5169
  const document = renderSpillDocument(result, { taskId: this.taskId, step: this.stepsCompleted, tool: functionName });
4799
5170
  const store = inlineLimit > 2500 ? new ToolOutputStore({ maxChars: inlineLimit, maxLines: 400, maxBytes: Math.max(50 * 1024, inlineLimit * 4) }) : defaultToolOutputStore;
4800
5171
  const stored = processToolOutputWithStore(this.taskId, toolCall.id, document, store);
@@ -4817,22 +5188,31 @@ You are operating in a text-and-code modality without direct image pixel renderi
4817
5188
  }
4818
5189
  }
4819
5190
 
4820
- // Fold identical bytes without treating them as proof of external state.
5191
+ // Fold identical bytes only when the earlier full observation is still
5192
+ // verbatim in active context (never blindfold a re-read of a decayed result).
4821
5193
  const OBSERVATION_FOLD_FLOOR = 600;
4822
5194
  if (resultString.length >= OBSERVATION_FOLD_FLOOR) {
4823
5195
  const digest = originalFingerprint;
4824
- const seenAt = this._observationDigests.get(digest);
4825
- if (seenAt !== undefined) {
5196
+ const seenRecord = this._observationDigests.get(digest) as { step: number; toolCallId: string } | undefined;
5197
+ const earlierStillVerbatim = Boolean(
5198
+ seenRecord && this.messages.some((msg: any) =>
5199
+ msg?.role === 'tool'
5200
+ && msg?.tool_call_id === seenRecord.toolCallId
5201
+ && typeof msg.content === 'string'
5202
+ && !msg.content.startsWith('[decayed]')
5203
+ )
5204
+ );
5205
+ if (seenRecord !== undefined && earlierStillVerbatim) {
4826
5206
  resultString = JSON.stringify({
4827
5207
  ...(result && typeof result.success === 'boolean' ? { success: result.success } : {}),
4828
5208
  identicalResult: true,
4829
- output: `The serialized tool response matches step ${seenAt}. This does not prove external state is unchanged. `
5209
+ output: `The serialized tool response matches step ${seenRecord.step}. This does not prove external state is unchanged. `
4830
5210
  + (spill
4831
5211
  ? `Full output is saved at ${spill.path}; read a relevant range if needed.`
4832
- : 'The earlier response may have left the active context; make a targeted read if its details are needed.')
5212
+ : 'The earlier response is still present in active context.')
4833
5213
  });
4834
5214
  } else {
4835
- this._observationDigests.set(digest, this.stepsCompleted + 1);
5215
+ this._observationDigests.set(digest, { step: this.stepsCompleted + 1, toolCallId: toolCall.id });
4836
5216
  }
4837
5217
  }
4838
5218
 
@@ -4977,6 +5357,18 @@ You are operating in a text-and-code modality without direct image pixel renderi
4977
5357
  : 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
4978
5358
  break;
4979
5359
  }
5360
+ if (e?.code === 'ACP_PARTIAL_TURN') {
5361
+ const completed = Number.isSafeInteger(e.completedNativeActions) && e.completedNativeActions >= 0 ? e.completedNativeActions : 0;
5362
+ const unfinished = Number.isSafeInteger(e.unfinishedNativeActions) && e.unfinishedNativeActions >= 0 ? e.unfinishedNativeActions : 0;
5363
+ const partialText = typeof e.partialText === 'string' ? redactProviderSecrets(e.partialText).slice(0, 4000).trim() : '';
5364
+ if (partialText) this.messages.push({ role: 'assistant', content: partialText });
5365
+ this.messages.push({ role: 'system', content:
5366
+ `[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.` });
5367
+ this.memoryManager.saveHistory(this.messages);
5368
+ this.emitEvent({ type: 'error', message: e.message });
5369
+ auditLog.log({ event: 'acp_partial_turn_checkpoint', taskId: this.taskId, completedNativeActions: completed, unfinishedNativeActions: unfinished, outcome: 'unverified' });
5370
+ break;
5371
+ }
4980
5372
  if (e?.code === 'PROVIDER_EMPTY_RESPONSE'
4981
5373
  || (typeof e?.message === 'string' && e.message.includes('returned no response'))) {
4982
5374
  if (emptyResponseRecoveries++ < 5) {
@@ -5030,15 +5422,34 @@ You are operating in a text-and-code modality without direct image pixel renderi
5030
5422
  // "Thinking" and the only signal was `network_error: fetch failed`
5031
5423
  // repeated in red. From the outside it is indistinguishable from
5032
5424
  // working, and it burns the user's step budget doing nothing.
5033
- const repeated = this.lastFailureType === errorType;
5034
- this.consecutiveFailures = repeated ? this.consecutiveFailures + 1 : 1;
5425
+ // Changing error classes is not successful progress.
5426
+ this.consecutiveFailures++;
5035
5427
  this.lastFailureType = errorType;
5036
5428
 
5429
+ const isContextOverflow = errorType === 'context_overflow';
5430
+ if (isContextOverflow) {
5431
+ const compactRes = compactSessionMessages(this.messages, {
5432
+ keepRecentTurns: Math.max(2, 6 - this.consecutiveFailures * 2),
5433
+ taskId: this.taskId,
5434
+ originalPrompt: this.currentTaskPrompt || this.userPrompt
5435
+ });
5436
+ if (compactRes.compacted) {
5437
+ this.notice(`Context limit exceeded — auto-compacted ${compactRes.removedCount} earlier messages (~${compactRes.reclaimedTokens} tokens reclaimed) and retrying.`);
5438
+ }
5439
+ }
5440
+
5037
5441
  const isNetwork = errorType === NETWORK_ERROR_TYPE;
5442
+ const isRateLimit = errorType === 'rate_limit';
5443
+ const maxAttempts = isRateLimit ? 5 : AgentLoop.MAX_CONSECUTIVE_FAILURES;
5038
5444
  const detail = isNetwork ? explainNetworkError(e, this.config) : e.message;
5039
5445
  auditLog.log({ event: 'loop_error_recovered', taskId: this.taskId, error: e.message, errorType });
5040
5446
 
5041
- if (this.consecutiveFailures >= AgentLoop.MAX_CONSECUTIVE_FAILURES) {
5447
+ const exceededCeiling = isRateLimit
5448
+ ? this.consecutiveFailures >= maxAttempts
5449
+ : this.consecutiveFailures >= AgentLoop.MAX_CONSECUTIVE_FAILURES;
5450
+ if (exceededCeiling) {
5451
+ if (await this.tryZeroCostFailover(isNetwork, isRateLimit, errorType)) continue;
5452
+
5042
5453
  // Nothing is changing between attempts. Stop and say why, rather
5043
5454
  // than spinning until the budget is gone.
5044
5455
  this.emitEvent({
@@ -5054,23 +5465,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
5054
5465
  type: 'step_error',
5055
5466
  tool: 'agent_loop',
5056
5467
  error: `${detail}\n retrying (${this.consecutiveFailures} of `
5057
- + `${AgentLoop.MAX_CONSECUTIVE_FAILURES})`
5468
+ + `${maxAttempts})`
5058
5469
  });
5059
5470
 
5060
- // Back off before trying again. Hammering a failing endpoint as fast
5061
- // as the loop can spin turns a one-second blip into a burst of
5062
- // failures and gives the endpoint no chance to recover.
5063
- await this.backoff(this.consecutiveFailures);
5471
+ // Back off before trying again. Honor provider Retry-After / X-RateLimit-Reset
5472
+ // when present so free-tier 429 limits recover cleanly without hammering.
5473
+ const retryAfterMs = typeof e?.retryAfterMs === 'number' && Number.isFinite(e.retryAfterMs)
5474
+ ? e.retryAfterMs
5475
+ : undefined;
5476
+ await this.backoff(this.consecutiveFailures, retryAfterMs);
5064
5477
 
5065
5478
  // Only tell the MODEL about errors the model can act on. It cannot
5066
- // fix DNS or a firewall, and a system message per attempt grows the
5067
- // context — and the bill — for nothing.
5479
+ // fix DNS, firewalls, HTTP 429 rate limits, or context overflow (already compacted).
5068
5480
  if (!isNetwork) {
5069
- this.messages.push({
5070
- role: 'system',
5071
- content: `[SYSTEM ERROR RECOVERED: A ${errorType} error occurred: "${e.message}". `
5072
- + 'The loop has recovered. You may continue or try a different approach.]'
5073
- });
5481
+ if (!isRateLimit && !isContextOverflow) {
5482
+ this.messages.push({
5483
+ role: 'system',
5484
+ content: `[SYSTEM ERROR RECOVERED: A ${errorType} error occurred: "${e.message}". `
5485
+ + 'The loop has recovered. You may continue or try a different approach.]'
5486
+ });
5487
+ }
5074
5488
  }
5075
5489
  }
5076
5490
  }
@@ -5083,7 +5497,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
5083
5497
 
5084
5498
  async waitForApproval(toolCallId: string): Promise<boolean> {
5085
5499
  const signal = this.abortController?.signal;
5086
- if (this.stopRequested || signal?.aborted) return false;
5500
+ if (this.stopRequested || signal?.aborted || typeof toolCallId !== 'string' || !toolCallId.trim() || this.pendingApprovals.has(toolCallId)) return false;
5087
5501
  this._entitlementGate?.pause();
5088
5502
  try {
5089
5503
  return await new Promise<boolean>((resolve) => {
@@ -5114,8 +5528,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
5114
5528
  * Exponential, capped. Without the abort check a user pressing esc during a
5115
5529
  * backoff would wait out the full delay before anything responded.
5116
5530
  */
5117
- async backoff(attempt: number) {
5118
- const delay = Math.min(8000, 500 * Math.pow(2, Math.max(0, attempt - 1)));
5531
+ async backoff(attempt: number, retryAfterMs?: number) {
5532
+ let delay: number;
5533
+ if (typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
5534
+ const jitter = Math.min(250, Math.floor(retryAfterMs * 0.1));
5535
+ delay = Math.min(60_000, Math.max(50, Math.round(retryAfterMs) + jitter));
5536
+ } else {
5537
+ delay = Math.min(8000, 500 * Math.pow(2, Math.max(0, attempt - 1)));
5538
+ }
5119
5539
  await waitForAbortableDelay(delay, this.abortController?.signal);
5120
5540
  }
5121
5541
 
@@ -5157,4 +5577,56 @@ You are operating in a text-and-code modality without direct image pixel renderi
5157
5577
  validateToolArgs(toolName: string, args: any) {
5158
5578
  return validateAndNormalizeToolArgs(toolName, args, this.workspaceRoot || process.cwd());
5159
5579
  }
5580
+
5581
+ private async tryZeroCostFailover(isNetwork: boolean, isRateLimit: boolean, errorType: string): Promise<boolean> {
5582
+ const canAttemptZeroCostFailover = (isRateLimit || isNetwork)
5583
+ && isZeroCostFailoverEligible(this.config?.provider, this.config?.model)
5584
+ && (this.config?.zeroCostFailover === true || (this._factoryLlmRef != null && this._factoryLlmRef === this.llm));
5585
+ if (!canAttemptZeroCostFailover) return false;
5586
+
5587
+ const triedSet: Set<string> = ((this as any)._zeroCostTriedProviders ||= new Set<string>());
5588
+ triedSet.add(normalizeZeroCostId(this.config?.provider));
5589
+ const nextRoute = await selectNextZeroCostRoute({
5590
+ currentProvider: String(this.config?.provider || ''),
5591
+ currentModel: String(this.config?.model || ''),
5592
+ triedProviders: triedSet,
5593
+ config: this.config,
5594
+ reason: isNetwork ? 'network_error' : 'rate_limit',
5595
+ ...(Array.isArray((this as any).zeroCostFailoverCandidates)
5596
+ ? { candidates: (this as any).zeroCostFailoverCandidates }
5597
+ : {})
5598
+ });
5599
+ if (!nextRoute) return false;
5600
+
5601
+ const prevProvider = String(this.config?.provider || '');
5602
+ triedSet.add(normalizeZeroCostId(nextRoute.provider));
5603
+ this.config = {
5604
+ ...this.config,
5605
+ provider: nextRoute.provider,
5606
+ model: nextRoute.model,
5607
+ apiKey: nextRoute.apiKey
5608
+ };
5609
+ delete this.config.baseUrl;
5610
+ delete this.config.reasoningEffort;
5611
+ delete this.config.reasoningBudgetTokens;
5612
+ this.llm = this.initializeProvider();
5613
+ this._utilityLlm = null;
5614
+ this.consecutiveFailures = 0;
5615
+ this.lastFailureType = null;
5616
+ auditLog.log({
5617
+ event: 'zero_cost_failover',
5618
+ taskId: this.taskId,
5619
+ fromProvider: prevProvider,
5620
+ toProvider: nextRoute.provider,
5621
+ toModel: nextRoute.model,
5622
+ costTier: nextRoute.costTier,
5623
+ reason: errorType
5624
+ });
5625
+ this.notice(
5626
+ `Zero-cost failover ($0): switched from ${prevProvider} to ${nextRoute.provider}`
5627
+ + (nextRoute.model ? ` (${nextRoute.model})` : '')
5628
+ + ` after ${errorType}.`
5629
+ );
5630
+ return true;
5631
+ }
5160
5632
  }