@causyne/agent 1.20.121 → 1.20.124
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/bin/causyne.js +38 -15
- package/docs/SECURITY_REVIEW.md +42 -6
- package/package.json +5 -5
- package/src/acp/agentCatalog.js +141 -62
- package/src/acp/agentCatalog.ts +142 -65
- package/src/acp/client.js +489 -109
- package/src/acp/client.ts +465 -108
- package/src/acp/peerProfiles.js +55 -22
- package/src/acp/peerProfiles.ts +51 -22
- package/src/acp/protocol.js +181 -8
- package/src/acp/protocol.ts +189 -8
- package/src/acp/server.js +250 -53
- package/src/acp/server.ts +234 -53
- package/src/agent/errorClassifier.js +48 -8
- package/src/agent/errorClassifier.ts +50 -7
- package/src/agent/providerFailure.js +1 -1
- package/src/agent/providerFailure.ts +7 -1
- package/src/agent/toolArgValidator.js +38 -4
- package/src/agent/toolArgValidator.ts +39 -4
- package/src/agent/toolTurnIntegrity.js +28 -7
- package/src/agent/toolTurnIntegrity.ts +25 -6
- package/src/agent/workspaceBoundary.js +30 -4
- package/src/agent/workspaceBoundary.ts +32 -4
- package/src/agentLoop.js +609 -222
- package/src/agentLoop.ts +632 -220
- package/src/approvalGrants.js +19 -7
- package/src/approvalGrants.ts +20 -7
- package/src/approvalPolicy.js +76 -16
- package/src/approvalPolicy.ts +74 -16
- package/src/auditLog.js +641 -48
- package/src/auditLog.ts +661 -0
- package/src/autoUpdate.js +37 -7
- package/src/autoUpdate.ts +32 -7
- package/src/backgroundTasks.js +328 -0
- package/src/backgroundTasks.ts +339 -0
- package/src/benchmarks/codingEval.js +558 -0
- package/src/benchmarks/codingEval.ts +628 -0
- package/src/benchmarks/planCache.js +115 -134
- package/src/benchmarks/planCache.ts +163 -0
- package/src/browser/browserRuntime.js +52 -0
- package/src/browser/browserRuntime.ts +55 -0
- package/src/browser/causyneBrowser.js +887 -12
- package/src/browser/causyneBrowser.ts +1045 -34
- package/src/browser/searchProviders.js +95 -7
- package/src/browser/searchProviders.ts +90 -7
- package/src/browser/urlPolicy.js +8 -1
- package/src/browser/urlPolicy.ts +7 -1
- package/src/browser/workspacePathSafety.js +6 -4
- package/src/browser/workspacePathSafety.ts +7 -4
- package/src/capabilities.js +18 -17
- package/src/capabilities.ts +38 -0
- package/src/checkpoints.js +1241 -1127
- package/src/checkpoints.ts +1377 -0
- package/src/cliMode.js +707 -755
- package/src/cliMode.ts +780 -0
- package/src/codebase/repoMap.js +656 -0
- package/src/codebase/repoMap.ts +664 -0
- package/src/commands.js +3651 -2514
- package/src/commands.ts +3985 -0
- package/src/compiledSkills.js +8052 -8054
- package/src/compiledSkills.ts +8078 -0
- package/src/config.js +389 -250
- package/src/config.ts +451 -0
- package/src/configVault.js +113 -19
- package/src/configVault.ts +103 -19
- package/src/contextManager.js +473 -557
- package/src/contextManager.ts +599 -0
- package/src/continuum/adapters/antigravity.js +8 -3
- package/src/continuum/adapters/antigravity.ts +8 -3
- package/src/continuum/compactor.js +2 -1
- package/src/continuum/compactor.ts +2 -1
- package/src/continuum/sanitizer.js +33 -4
- package/src/continuum/sanitizer.ts +32 -4
- package/src/continuum/ui/continuumPicker.js +0 -2
- package/src/continuum/ui/continuumPicker.ts +0 -2
- package/src/continuum/ui/continuumPickerView.js +3 -4
- package/src/continuum/ui/continuumPickerView.ts +7 -22
- package/src/core/contextCompactor.js +88 -7
- package/src/core/contextCompactor.ts +87 -8
- package/src/cortex/vectorDb.js +26 -15
- package/src/cortex/vectorDb.ts +26 -16
- package/src/creative/liveBridge.js +10 -7
- package/src/creative/liveBridge.ts +11 -7
- package/src/creative/studioScripts.js +17 -6
- package/src/creative/studioScripts.ts +15 -6
- package/src/decideTools.js +7 -2
- package/src/decideTools.ts +7 -2
- package/src/decisionPolicy.js +26 -6
- package/src/decisionPolicy.ts +24 -6
- package/src/designPalettes.js +72 -84
- package/src/designPalettes.ts +111 -0
- package/src/devMode.js +2 -2
- package/src/devMode.ts +6 -0
- package/src/diffReview.js +370 -0
- package/src/diffReview.ts +407 -0
- package/src/documentEngine/antiSlopAuditor.js +10 -5
- package/src/documentEngine/antiSlopAuditor.ts +11 -5
- package/src/documentEngine/documentForge.js +47 -15
- package/src/documentEngine/documentForge.ts +43 -14
- package/src/dynamicCatalogue.js +311 -11
- package/src/dynamicCatalogue.ts +331 -11
- package/src/embodimentSession.js +143 -154
- package/src/embodimentSession.ts +173 -0
- package/src/engines/design.js +2 -1
- package/src/engines/design.ts +2 -1
- package/src/engines/film.js +4 -4
- package/src/engines/film.ts +2 -2
- package/src/engines/installer.js +60 -29
- package/src/engines/installer.ts +73 -22
- package/src/engines/light.js +2 -1
- package/src/engines/light.ts +2 -1
- package/src/engines/registry.js +1 -1
- package/src/engines/registry.ts +1 -1
- package/src/engines/reverseHarness.js +4 -3
- package/src/engines/reverseHarness.ts +4 -3
- package/src/enterprisePolicy.js +660 -0
- package/src/enterprisePolicy.ts +728 -0
- package/src/entrypoint.js +514 -268
- package/src/entrypoint.ts +607 -0
- package/src/gitSnapshot.js +417 -312
- package/src/gitSnapshot.ts +500 -0
- package/src/headlessCli.js +326 -14
- package/src/headlessCli.ts +323 -13
- package/src/historyPruner.js +3 -2
- package/src/historyPruner.ts +3 -2
- package/src/hooks.js +250 -26
- package/src/hooks.ts +239 -26
- package/src/ignoreRules.js +297 -0
- package/src/ignoreRules.ts +308 -0
- package/src/implementationPlan.js +28 -17
- package/src/implementationPlan.ts +29 -17
- package/src/infra/atomicWriter.js +96 -20
- package/src/infra/atomicWriter.ts +112 -20
- package/src/launchIntent.js +14 -3
- package/src/launchIntent.ts +14 -3
- package/src/licensing/entitlements.js +553 -237
- package/src/licensing/entitlements.ts +590 -0
- package/src/licensing/policy.js +17 -1
- package/src/licensing/policy.ts +31 -0
- package/src/lsp/lspCatalog.js +398 -0
- package/src/lsp/lspCatalog.ts +452 -0
- package/src/lsp/lspClient.js +699 -0
- package/src/lsp/lspClient.ts +799 -0
- package/src/lsp/lspProtocol.js +121 -0
- package/src/lsp/lspProtocol.ts +140 -0
- package/src/mcp/mcpClient.js +69 -8
- package/src/mcp/mcpClient.ts +66 -9
- package/src/mcp/mcpRegistry.js +180 -7
- package/src/mcp/mcpRegistry.ts +171 -7
- package/src/mcp/mcpSecurity.js +6 -7
- package/src/mcp/mcpSecurity.ts +7 -6
- package/src/memory/episodicStore.js +2 -5
- package/src/memory/episodicStore.ts +2 -5
- package/src/memory/scopedFacts.js +1 -1
- package/src/memory/scopedFacts.ts +1 -1
- package/src/memory/symbolFolder.js +1 -1
- package/src/memory/symbolFolder.ts +1 -1
- package/src/memory.js +80 -32
- package/src/memory.ts +111 -0
- package/src/memoryManager.js +151 -143
- package/src/memoryManager.ts +182 -0
- package/src/modelCatalogue.js +172 -195
- package/src/modelCatalogue.ts +201 -0
- package/src/modelIds.js +8 -27
- package/src/modelIds.ts +33 -0
- package/src/modelRouter.js +1 -1
- package/src/modelRouter.ts +1 -1
- package/src/modelVariants.js +600 -0
- package/src/modelVariants.ts +663 -0
- package/src/observer/evidence.js +15 -5
- package/src/observer/evidence.ts +15 -5
- package/src/osKeychain.js +79 -17
- package/src/osKeychain.ts +64 -17
- package/src/outputStore.js +210 -156
- package/src/outputStore.ts +321 -0
- package/src/perception.js +3 -2
- package/src/perception.ts +3 -2
- package/src/planCache.js +5 -8
- package/src/planCache.ts +5 -8
- package/src/plugins/pluginManager.js +689 -461
- package/src/plugins/pluginManager.ts +807 -0
- package/src/plugins/pluginRunner.js +82 -37
- package/src/plugins/pluginRunner.ts +98 -0
- package/src/plugins/pluginSkills.js +47 -9
- package/src/plugins/pluginSkills.ts +46 -8
- package/src/pluginsFactory/discovery.js +0 -1
- package/src/pluginsFactory/discovery.ts +0 -1
- package/src/pluginsFactory/pluginsFactory.js +19 -11
- package/src/pluginsFactory/pluginsFactory.ts +18 -11
- package/src/pluginsFactory/templates.js +17 -4
- package/src/pluginsFactory/templates.ts +17 -4
- package/src/prWorkflow.js +337 -0
- package/src/prWorkflow.ts +376 -0
- package/src/procSignal.js +1 -2
- package/src/procSignal.ts +1 -3
- package/src/projectInstructions.js +319 -0
- package/src/projectInstructions.ts +361 -0
- package/src/promptMentions.js +2 -2
- package/src/promptMentions.ts +2 -2
- package/src/providers/acp.js +235 -50
- package/src/providers/acp.ts +241 -51
- package/src/providers/anthropic.js +431 -400
- package/src/providers/anthropic.ts +493 -0
- package/src/providers/antigravity.js +575 -358
- package/src/providers/antigravity.ts +565 -359
- package/src/providers/base.js +229 -320
- package/src/providers/base.ts +348 -0
- package/src/providers/byokHttp.js +183 -30
- package/src/providers/byokHttp.ts +232 -32
- package/src/providers/byokStream.js +287 -70
- package/src/providers/byokStream.ts +282 -71
- package/src/providers/dashscope-byok.js +123 -89
- package/src/providers/dashscope-byok.ts +142 -0
- package/src/providers/deepseek.js +82 -72
- package/src/providers/deepseek.ts +108 -0
- package/src/providers/factory.js +76 -28
- package/src/providers/factory.ts +82 -0
- package/src/providers/gemini.js +279 -278
- package/src/providers/gemini.ts +313 -0
- package/src/providers/loopGuard.js +9 -5
- package/src/providers/loopGuard.ts +10 -5
- package/src/providers/moonshot.js +103 -72
- package/src/providers/moonshot.ts +122 -0
- package/src/providers/muse.js +82 -152
- package/src/providers/muse.ts +122 -0
- package/src/providers/ollama.js +360 -106
- package/src/providers/ollama.ts +408 -0
- package/src/providers/openai-compatible.js +168 -95
- package/src/providers/openai-compatible.ts +200 -0
- package/src/providers/openai.js +45 -15
- package/src/providers/openai.ts +52 -0
- package/src/providers/openrouter.js +342 -113
- package/src/providers/openrouter.ts +333 -116
- package/src/providers/pi.js +6 -0
- package/src/providers/pi.ts +6 -0
- package/src/providers/qwen-byok.js +122 -87
- package/src/providers/qwen-byok.ts +141 -0
- package/src/providers/toolContracts.js +40 -14
- package/src/providers/toolContracts.ts +35 -14
- package/src/providers/wireNormalizer.js +144 -11
- package/src/providers/wireNormalizer.ts +132 -12
- package/src/providers/xai.js +80 -72
- package/src/providers/xai.ts +103 -0
- package/src/provisioning/capabilityConsent.js +29 -11
- package/src/provisioning/capabilityConsent.ts +42 -0
- package/src/provisioning/capabilityProvisioner.js +309 -197
- package/src/provisioning/capabilityProvisioner.ts +413 -0
- package/src/provisioning/capabilityTools.js +31 -17
- package/src/provisioning/capabilityTools.ts +43 -0
- package/src/provisioning/npmInstall.js +33 -5
- package/src/provisioning/npmInstall.ts +33 -5
- package/src/reliability/assetEvidence.js +4 -2
- package/src/reliability/assetEvidence.ts +4 -2
- package/src/reporting.js +328 -326
- package/src/reporting.ts +482 -0
- package/src/sandbox.js +526 -554
- package/src/sandbox.ts +590 -0
- package/src/sandboxPolicy.js +95 -16
- package/src/sandboxPolicy.ts +97 -16
- package/src/sessionJournal.js +32 -6
- package/src/sessionJournal.ts +27 -6
- package/src/sessionStore.js +1 -2
- package/src/sessionStore.ts +2 -0
- package/src/skills/skillResourceSafety.js +19 -8
- package/src/skills/skillResourceSafety.ts +16 -7
- package/src/skillsManager.js +3 -3
- package/src/skillsManager.ts +3 -3
- package/src/slopDetector.js +202 -265
- package/src/slopDetector.ts +279 -0
- package/src/smartToolsUse.js +38 -8
- package/src/smartToolsUse.ts +39 -11
- package/src/stallGuard.js +53 -23
- package/src/stallGuard.ts +53 -23
- package/src/subagentJournal.js +6 -4
- package/src/subagentJournal.ts +6 -4
- package/src/taskBuffer.js +91 -40
- package/src/taskBuffer.ts +94 -0
- package/src/textDiff.js +6 -1
- package/src/textDiff.ts +6 -1
- package/src/timeMachine.js +7 -1
- package/src/timeMachine.ts +7 -1
- package/src/tokenTracker.js +120 -38
- package/src/tokenTracker.ts +110 -38
- package/src/toolPacks.js +8 -1
- package/src/toolPacks.ts +8 -1
- package/src/tools/applyPatch.js +610 -0
- package/src/tools/applyPatch.ts +661 -0
- package/src/tools/archive.js +372 -48
- package/src/tools/archive.ts +372 -48
- package/src/tools/astryxOracle.js +77 -72
- package/src/tools/astryxOracle.ts +95 -0
- package/src/tools/axSnapshot.js +127 -147
- package/src/tools/axSnapshot.ts +174 -0
- package/src/tools/backgroundTask.js +86 -0
- package/src/tools/backgroundTask.ts +121 -0
- package/src/tools/blenderAutomator.js +434 -390
- package/src/tools/blenderAutomator.ts +623 -0
- package/src/tools/checkSystemSpecs.js +54 -61
- package/src/tools/checkSystemSpecs.ts +73 -0
- package/src/tools/clipboard.js +42 -31
- package/src/tools/clipboard.ts +61 -0
- package/src/tools/codeSearchAst.js +359 -91
- package/src/tools/codeSearchAst.ts +399 -0
- package/src/tools/codeSearcher.js +179 -37
- package/src/tools/codeSearcher.ts +188 -33
- package/src/tools/codeTools.js +208 -245
- package/src/tools/codeTools.ts +271 -0
- package/src/tools/codebaseSearch.js +5 -0
- package/src/tools/codebaseSearch.ts +5 -0
- package/src/tools/computerUse.js +7 -3
- package/src/tools/computerUse.ts +7 -3
- package/src/tools/creativeApps.js +13 -8
- package/src/tools/creativeApps.ts +22 -9
- package/src/tools/deferredMcpSearch.js +26 -14
- package/src/tools/deferredMcpSearch.ts +26 -14
- package/src/tools/desktopAct.js +185 -197
- package/src/tools/desktopAct.ts +257 -0
- package/src/tools/desktopOpen.js +69 -10
- package/src/tools/desktopOpen.ts +70 -11
- package/src/tools/documentForge.js +167 -82
- package/src/tools/documentForge.ts +169 -84
- package/src/tools/dynamicLoader.js +4 -40
- package/src/tools/dynamicLoader.ts +13 -0
- package/src/tools/executeProceduralMedia.js +117 -86
- package/src/tools/executeProceduralMedia.ts +135 -0
- package/src/tools/fileTracker.js +74 -0
- package/src/tools/fileTracker.ts +94 -0
- package/src/tools/fsDelete.js +57 -47
- package/src/tools/fsDelete.ts +80 -0
- package/src/tools/fsEdit.js +250 -61
- package/src/tools/fsEdit.ts +265 -63
- package/src/tools/fsFind.js +8 -5
- package/src/tools/fsFind.ts +7 -4
- package/src/tools/fsMove.js +79 -52
- package/src/tools/fsMove.ts +108 -0
- package/src/tools/fsRead.js +163 -18
- package/src/tools/fsRead.ts +169 -18
- package/src/tools/fsSearch.js +5 -0
- package/src/tools/fsSearch.ts +5 -0
- package/src/tools/fsWrite.js +31 -11
- package/src/tools/fsWrite.ts +31 -13
- package/src/tools/gameAiBehaviorTree.js +74 -91
- package/src/tools/gameAiBehaviorTree.ts +219 -0
- package/src/tools/gameAnimationRig.js +128 -147
- package/src/tools/gameAnimationRig.ts +215 -0
- package/src/tools/gameAssetFetcher.js +403 -441
- package/src/tools/gameAssetFetcher.ts +477 -0
- package/src/tools/gameAssetHarvester.js +171 -200
- package/src/tools/gameAssetHarvester.ts +261 -0
- package/src/tools/gameAudioSynth.js +223 -259
- package/src/tools/gameAudioSynth.ts +255 -0
- package/src/tools/gameBuilder.js +100 -91
- package/src/tools/gameBuilder.ts +913 -0
- package/src/tools/gameCanvasAudit.js +138 -96
- package/src/tools/gameCanvasAudit.ts +157 -0
- package/src/tools/gameCinematicSequencer.js +93 -111
- package/src/tools/gameCinematicSequencer.ts +165 -0
- package/src/tools/gameDataForge.js +115 -118
- package/src/tools/gameDataForge.ts +151 -0
- package/src/tools/gameDialogueTreeGen.js +125 -156
- package/src/tools/gameDialogueTreeGen.ts +159 -0
- package/src/tools/gameEconomyBalancer.js +150 -153
- package/src/tools/gameEconomyBalancer.ts +186 -0
- package/src/tools/gameEntitySpawner.js +91 -108
- package/src/tools/gameEntitySpawner.ts +209 -0
- package/src/tools/gameLoreForge.js +125 -147
- package/src/tools/gameLoreForge.ts +162 -0
- package/src/tools/gameQuestArcBuilder.js +105 -144
- package/src/tools/gameQuestArcBuilder.ts +147 -0
- package/src/tools/gameSceneBuilder.js +143 -149
- package/src/tools/gameSceneBuilder.ts +196 -0
- package/src/tools/gameShaderForge.js +83 -101
- package/src/tools/gameShaderForge.ts +181 -0
- package/src/tools/gameTilemapGenerator.js +99 -129
- package/src/tools/gameTilemapGenerator.ts +158 -0
- package/src/tools/gameUiHudBuilder.js +109 -129
- package/src/tools/gameUiHudBuilder.ts +300 -0
- package/src/tools/gameVfxEmitterGen.js +86 -89
- package/src/tools/gameVfxEmitterGen.ts +133 -0
- package/src/tools/gameWebRuntimeInspector.js +153 -86
- package/src/tools/gameWebRuntimeInspector.ts +167 -0
- package/src/tools/generateMediaViaApi.js +126 -22
- package/src/tools/generateMediaViaApi.ts +123 -22
- package/src/tools/gitExec.js +133 -86
- package/src/tools/gitExec.ts +146 -0
- package/src/tools/gitWorktree.js +115 -0
- package/src/tools/gitWorktree.ts +150 -0
- package/src/tools/godotAutomator.js +417 -394
- package/src/tools/godotAutomator.ts +530 -0
- package/src/tools/lspCodeIntel.js +217 -0
- package/src/tools/lspCodeIntel.ts +260 -0
- package/src/tools/manageLocalAiDependencies.js +242 -206
- package/src/tools/manageLocalAiDependencies.ts +288 -0
- package/src/tools/memoryRecall.js +62 -11
- package/src/tools/memoryRecall.ts +70 -13
- package/src/tools/memoryWrite.js +27 -14
- package/src/tools/memoryWrite.ts +30 -14
- package/src/tools/multiEdit.js +73 -63
- package/src/tools/multiEdit.ts +80 -65
- package/src/tools/nativeEngine.js +33 -18
- package/src/tools/nativeEngine.ts +31 -18
- package/src/tools/openSourceToolProvisioner.js +49 -14
- package/src/tools/openSourceToolProvisioner.ts +54 -15
- package/src/tools/osSandbox.js +202 -25
- package/src/tools/osSandbox.ts +192 -25
- package/src/tools/palmierAutomator.js +147 -95
- package/src/tools/palmierAutomator.ts +171 -0
- package/src/tools/payloadSanitizer.js +40 -8
- package/src/tools/payloadSanitizer.ts +39 -8
- package/src/tools/pdfReader.js +95 -104
- package/src/tools/pdfReader.ts +125 -0
- package/src/tools/peerAgent.js +96 -34
- package/src/tools/peerAgent.ts +114 -37
- package/src/tools/persistentShell.js +267 -144
- package/src/tools/persistentShell.ts +314 -0
- package/src/tools/pluginManager.js +84 -72
- package/src/tools/pluginManager.ts +109 -0
- package/src/tools/pluginsFactory.js +38 -6
- package/src/tools/pluginsFactory.ts +42 -6
- package/src/tools/printer.js +278 -296
- package/src/tools/printer.ts +326 -0
- package/src/tools/procTerm.js +96 -83
- package/src/tools/procTerm.ts +127 -0
- package/src/tools/processList.js +45 -48
- package/src/tools/processList.ts +73 -0
- package/src/tools/readNativeSkill.js +10 -8
- package/src/tools/readNativeSkill.ts +10 -8
- package/src/tools/registry.js +298 -286
- package/src/tools/registry.ts +486 -0
- package/src/tools/repoMap.js +46 -0
- package/src/tools/repoMap.ts +66 -0
- package/src/tools/requestDecision.js +10 -3
- package/src/tools/requestDecision.ts +10 -3
- package/src/tools/resolveAutomator.js +91 -17
- package/src/tools/resolveAutomator.ts +102 -17
- package/src/tools/reverseEngineering.js +168 -41
- package/src/tools/reverseEngineering.ts +161 -41
- package/src/tools/subagentOrchestrator.js +404 -348
- package/src/tools/subagentOrchestrator.ts +457 -0
- package/src/tools/sysRun.js +148 -51
- package/src/tools/sysRun.ts +142 -46
- package/src/tools/toolDispatch.js +24 -1
- package/src/tools/toolDispatch.ts +21 -1
- package/src/tools/toolForge.js +84 -67
- package/src/tools/toolForge.ts +102 -0
- package/src/tools/toolOutputStore.js +62 -23
- package/src/tools/toolOutputStore.ts +56 -23
- package/src/tools/toolPathSafety.js +262 -0
- package/src/tools/toolPathSafety.ts +308 -0
- package/src/tools/toolScanner.js +41 -10
- package/src/tools/toolScanner.ts +42 -10
- package/src/tools/toolSelfRepair.js +115 -34
- package/src/tools/toolSelfRepair.ts +122 -34
- package/src/tools/uiForge.js +71 -6
- package/src/tools/uiForge.ts +74 -6
- package/src/tools/viewImage.js +62 -17
- package/src/tools/viewImage.ts +57 -12
- package/src/tools/visionInspector.js +15 -3
- package/src/tools/visionInspector.ts +15 -3
- package/src/tools/walkerSafety.js +2 -0
- package/src/tools/walkerSafety.ts +2 -0
- package/src/tools/webFetch.js +110 -12
- package/src/tools/webFetch.ts +110 -13
- package/src/toolsList.js +5 -0
- package/src/toolsList.ts +5 -0
- package/src/tui/ask.js +159 -168
- package/src/tui/ask.ts +259 -0
- package/src/tui/banner.js +3 -2
- package/src/tui/banner.ts +3 -2
- package/src/tui/block.js +0 -1
- package/src/tui/block.ts +0 -1
- package/src/tui/chatRenderer.js +1193 -1441
- package/src/tui/chatRenderer.ts +1336 -0
- package/src/tui/clipboardImage.js +36 -12
- package/src/tui/clipboardImage.ts +39 -13
- package/src/tui/clipboardSync.js +34 -9
- package/src/tui/clipboardSync.ts +38 -9
- package/src/tui/codeProgress.js +0 -1
- package/src/tui/codeProgress.ts +0 -1
- package/src/tui/completion.js +395 -371
- package/src/tui/completion.ts +574 -0
- package/src/tui/composerControls.js +113 -19
- package/src/tui/composerControls.ts +124 -19
- package/src/tui/consoleGuard.js +39 -11
- package/src/tui/consoleGuard.ts +38 -11
- package/src/tui/dialogs.js +864 -717
- package/src/tui/dialogs.ts +984 -0
- package/src/tui/diff.js +205 -195
- package/src/tui/diff.ts +336 -0
- package/src/tui/history.js +143 -108
- package/src/tui/history.ts +167 -0
- package/src/tui/home.js +165 -161
- package/src/tui/home.ts +251 -0
- package/src/tui/invocation.js +58 -65
- package/src/tui/invocation.ts +117 -0
- package/src/tui/keys.js +437 -420
- package/src/tui/keys.ts +597 -0
- package/src/tui/lineEditor.js +477 -432
- package/src/tui/lineEditor.ts +542 -0
- package/src/tui/messageActionPlacement.js +0 -1
- package/src/tui/messageActionPlacement.ts +0 -1
- package/src/tui/messageInteraction.js +2 -5
- package/src/tui/messageInteraction.ts +2 -5
- package/src/tui/modelPicker.js +1 -3
- package/src/tui/modelPicker.ts +4 -6
- package/src/tui/observerPicker.js +0 -2
- package/src/tui/observerPicker.ts +0 -2
- package/src/tui/overlay.js +3 -2
- package/src/tui/overlay.ts +3 -2
- package/src/tui/prompt.js +1816 -2151
- package/src/tui/prompt.ts +1870 -0
- package/src/tui/runningLight.js +0 -1
- package/src/tui/runningLight.ts +0 -1
- package/src/tui/selectList.js +365 -337
- package/src/tui/selectList.ts +441 -0
- package/src/tui/sessionPicker.js +3 -3
- package/src/tui/sessionPicker.ts +3 -3
- package/src/tui/sessionPickerView.js +7 -3
- package/src/tui/sessionPickerView.ts +10 -22
- package/src/tui/sessionSidebar.js +3 -1
- package/src/tui/sessionSidebar.ts +4 -1
- package/src/tui/setup.js +17 -5
- package/src/tui/setup.ts +19 -5
- package/src/tui/skillAuthoring.js +0 -2
- package/src/tui/skillAuthoring.ts +0 -3
- package/src/tui/stageSurface.js +829 -909
- package/src/tui/stageSurface.ts +1003 -0
- package/src/tui/statusLine.js +7 -4
- package/src/tui/statusLine.ts +7 -3
- package/src/tui/terminalInputFramer.js +82 -69
- package/src/tui/terminalInputFramer.ts +116 -0
- package/src/tui/text.js +25 -10
- package/src/tui/text.ts +24 -10
- package/src/tui/textLayout.js +0 -1
- package/src/tui/textLayout.ts +0 -1
- package/src/tui/theme.js +245 -250
- package/src/tui/theme.ts +441 -0
- package/src/tui/thinkingBox.js +0 -1
- package/src/tui/thinkingBox.ts +0 -1
- package/src/tui/toolOutputNormalizer.js +2 -3
- package/src/tui/toolOutputNormalizer.ts +4 -3
- package/src/tui/transcript.js +239 -216
- package/src/tui/transcript.ts +324 -0
- package/src/tui/turnRail.js +53 -54
- package/src/tui/turnRail.ts +51 -49
- package/src/tui/usageCard.js +0 -2
- package/src/tui/usageCard.ts +0 -2
- package/src/tui/viewport.js +4 -4
- package/src/tui/viewport.ts +5 -5
- package/src/tui/workspaceIdentity.js +2 -1
- package/src/tui/workspaceIdentity.ts +2 -1
- package/src/tui/workspaceSwitch.js +4 -2
- package/src/tui/workspaceSwitch.ts +5 -2
- package/src/types/contracts.ts +4 -1
- package/src/uncertainty.js +8 -3
- package/src/uncertainty.ts +8 -3
- package/src/utils/browserOpen.js +107 -0
- package/src/utils/browserOpen.ts +129 -0
- package/src/utils/cli_ui.js +0 -0
- package/src/utils/cli_ui.ts +158 -0
- package/src/utils/paths.js +8 -5
- package/src/utils/paths.ts +9 -7
- package/src/utils/winSpawn.js +248 -0
- package/src/utils/winSpawn.ts +275 -0
- package/src/verification/boundedExplorer.js +138 -107
- package/src/verification/boundedExplorer.ts +154 -0
- package/src/verification/byokSmokeProbe.js +193 -0
- package/src/verification/byokSmokeProbe.ts +234 -0
- package/src/verification/cliProbe.js +144 -110
- package/src/verification/cliProbe.ts +170 -0
- package/src/verification/featureMap.js +105 -75
- package/src/verification/featureMap.ts +124 -0
- package/src/verification/interactivePty.js +195 -100
- package/src/verification/interactivePty.ts +333 -0
- package/src/verification/propertyProbe.js +109 -101
- package/src/verification/propertyProbe.ts +159 -0
- package/src/verification/ptyProbe.js +168 -73
- package/src/verification/ptyProbe.ts +254 -0
- package/src/verification/skillCatalog.js +25 -25
- package/src/verification/skillCatalog.ts +66 -0
- package/src/verification/statechart.js +140 -127
- package/src/verification/statechart.ts +196 -0
- package/src/verification/uiRuntime.js +80 -49
- package/src/verification/uiRuntime.ts +88 -0
- package/src/version.js +37 -32
- package/src/version.ts +45 -0
- package/src/vfeTracker.js +9 -3
- package/src/vfeTracker.ts +9 -3
- package/src/web/guiLauncher.js +89 -0
- package/src/web/guiLauncher.ts +119 -0
- package/src/web/skybridgeBrowserBridge.js +256 -0
- package/src/web/skybridgeBrowserBridge.ts +285 -0
- package/src/web/skybridgeBrowserMcp.js +730 -0
- package/src/web/skybridgeBrowserMcp.ts +813 -0
- package/src/web/skybridgeClientScript.js +3951 -0
- package/src/web/skybridgeClientScript.ts +3952 -0
- package/src/web/skybridgeServer.js +2622 -0
- package/src/web/skybridgeServer.ts +2787 -0
- package/src/web/skybridgeStyles.js +827 -0
- package/src/web/skybridgeStyles.ts +828 -0
- package/src/web/skybridgeUi.js +472 -0
- package/src/web/skybridgeUi.ts +485 -0
- package/src/worktreeManager.js +511 -0
- package/src/worktreeManager.ts +546 -0
- package/src/zeroCostFailover.js +168 -0
- package/src/zeroCostFailover.ts +198 -0
- package/src/zeroCostRouting.js +391 -0
- package/src/zeroCostRouting.ts +437 -0
- package/src/agentLoop.d.ts +0 -65
- package/src/auditLog.d.ts +0 -3
- package/src/checkpoints.d.ts +0 -4
- package/src/compiledSkills.d.ts +0 -5
- package/src/config.d.ts +0 -2
- package/src/contextManager.d.ts +0 -14
- package/src/designPalettes.d.ts +0 -2
- package/src/devMode.d.ts +0 -1
- package/src/embodimentSession.d.ts +0 -2
- package/src/licensing/entitlements.d.ts +0 -14
- package/src/memory.d.ts +0 -13
- package/src/memoryManager.d.ts +0 -1
- package/src/modelCatalogue.d.ts +0 -6
- package/src/modelIds.d.ts +0 -2
- package/src/outputStore.d.ts +0 -4
- package/src/plugins/pluginManager.d.ts +0 -7
- package/src/providers/antigravity.d.ts +0 -19
- package/src/providers/base.d.ts +0 -94
- package/src/providers/factory.d.ts +0 -1
- package/src/provisioning/capabilityProvisioner.d.ts +0 -12
- package/src/sandbox.d.ts +0 -1
- package/src/slopDetector.d.ts +0 -3
- package/src/taskBuffer.d.ts +0 -1
- package/src/tools/desktopAct.d.ts +0 -10
- package/src/tools/registry.d.ts +0 -5
- package/src/tui/chatRenderer.d.ts +0 -27
- package/src/tui/diff.d.ts +0 -3
- package/src/utils/cli_ui.d.ts +0 -19
- package/src/utils/paths.d.ts +0 -3
- package/src/verification/skillCatalog.d.ts +0 -1
- package/src/version.d.ts +0 -1
package/src/agentLoop.js
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';
|
|
@@ -9,9 +10,13 @@ import { normalizeAgentFailure } from './agent/providerFailure.js';
|
|
|
9
10
|
import { classifyAgentError, getRetryHintForError } from './agent/errorClassifier.js';
|
|
10
11
|
import { isActionableTaskPrompt, isGenericHandoffResponse, isDesktopWallpaperChangePrompt, isExecutionOrLaunchTaskPrompt, isCodeAuthoringTaskPrompt, extractSkillIdFromPrompt, isDirectGameTask, isProviderPlanOrQuotaRefusal, isMidTaskProgressText } from './agent/promptIntent.js';
|
|
11
12
|
import { validateAndNormalizeToolArgs } from './agent/toolArgValidator.js';
|
|
13
|
+
import { physicalPath, isWithinPhysicalPath } from './agent/workspaceBoundary.js';
|
|
12
14
|
import { resolveTaskTokenCeiling, peerCallTokenCeiling, isAntigravityPeer, isTerminalBudgetFailure, desktopDeadline, remainingDesktopTime, DEFAULT_AGY_TASK_TOKENS } from './budget/budgetPolicy.js';
|
|
13
15
|
import { PEER_COLLABORATION_POLICY } from './providers/collaborationPolicy.js';
|
|
16
|
+
import { isAcpProvider } from './providers/acp.js';
|
|
17
|
+
import { causyneBrowser } from './browser/causyneBrowser.js';
|
|
14
18
|
import { createHash, randomUUID } from 'crypto';
|
|
19
|
+
import { fileURLToPath } from 'node:url';
|
|
15
20
|
import { execFileSync } from 'node:child_process';
|
|
16
21
|
import { processApprovalScope, createApprovalScope } from './approvalGrants.js';
|
|
17
22
|
import { pruneSessions as pruneEmbodimentSessions, describeSession } from './embodimentSession.js';
|
|
@@ -25,7 +30,7 @@ import { validateToolArguments } from './tools/argumentValidation.js';
|
|
|
25
30
|
import { Sandbox } from './sandbox.js';
|
|
26
31
|
import { auditLog } from './auditLog.js';
|
|
27
32
|
import { hasMatchingHook, runConfiguredHooks } from './hooks.js';
|
|
28
|
-
import { loadConfig } from './config.js';
|
|
33
|
+
import { loadConfig, applyProviderOverrides } from './config.js';
|
|
29
34
|
import { isDevEmulator } from './devMode.js';
|
|
30
35
|
import { TokenTracker } from './tokenTracker.js';
|
|
31
36
|
import { getMemoryContextString } from './memory.js';
|
|
@@ -33,14 +38,17 @@ import { MemoryManager } from './memoryManager.js';
|
|
|
33
38
|
import { cortexDb, isSearchablePrompt } from './cortex/vectorDb.js';
|
|
34
39
|
import { buildStructuralSummary, condenseAndSave } from './cortex/autoCondenser.js';
|
|
35
40
|
import { episodicStore, compileToolObservation } from './memory/episodicStore.js';
|
|
36
|
-
import { buildCodexStyleSummary, compactSessionMessages, autoCompactIfUnderPressure } from './core/contextCompactor.js';
|
|
41
|
+
import { buildCodexStyleSummary, compactSessionMessages, autoCompactIfUnderPressure, findSafeCompactionSplitIndex } from './core/contextCompactor.js';
|
|
37
42
|
import { analyzeTask, buildTaskBrief } from './taskShape.js';
|
|
38
43
|
import { lookupPlan, recordPlan, recordPlanAsync, recordMiss, renderPlanHint, toStep, recordAPCPipelineLatency, lookupAlternativeStep, failureClass } from './planCache.js';
|
|
39
44
|
import { routedConfig } from './modelRouter.js';
|
|
40
45
|
import { assessStep, isThrashing } from './uncertainty.js';
|
|
41
46
|
import { assessDecisionRequirement, isMutatingToolCall, requiresImplementationPlan } from './decisionPolicy.js';
|
|
42
47
|
import { normalizePeerPlanEntries, extractLivePlanFromText, stripToolCallMarkup, stripThinkBlocks, extractToolCallJsonObjects, resolveToolCallEnvelopeArguments } from './implementationPlan.js';
|
|
43
|
-
import { requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
|
|
48
|
+
import { isWholeFileDeletion, requiresToolApproval, withToolAutonomyMode } from './approvalPolicy.js';
|
|
49
|
+
import { evaluateEnterprisePolicy } from './enterprisePolicy.js';
|
|
50
|
+
import { isZeroCostFailoverEligible, normalizeZeroCostId, selectNextZeroCostRoute } from './zeroCostFailover.js';
|
|
51
|
+
import { formatProjectInstructionsPrompt, loadProjectInstructions } from './projectInstructions.js';
|
|
44
52
|
import { AGENT_USER_POLICY } from './agentPolicy.js';
|
|
45
53
|
import { VFETracker } from './vfeTracker.js';
|
|
46
54
|
import { coldObserver } from './observer/coldObserver.js';
|
|
@@ -60,12 +68,14 @@ import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from '.
|
|
|
60
68
|
import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
|
|
61
69
|
import { ToolOutputStore, defaultToolOutputStore, processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
|
|
62
70
|
import { beginTask as beginCheckpointTask, captureBeforeMutation, pruneStore as pruneCheckpointStore, resolveProjectRoot } from './checkpoints.js';
|
|
71
|
+
import { extractPatchTargetPaths } from './tools/applyPatch.js';
|
|
63
72
|
import fsSync from 'fs';
|
|
64
73
|
import os from 'os';
|
|
65
74
|
import path from 'path';
|
|
66
75
|
import { analyzeFiles, formatFindings, isScannableFile } from './slopDetector.js';
|
|
67
76
|
import { suggestMovements, formatMovementBrief } from './designPalettes.js';
|
|
68
77
|
import { createProvider } from './providers/factory.js';
|
|
78
|
+
import { redactProviderSecrets } from './providers/byokHttp.js';
|
|
69
79
|
import { isNativeMutation } from './providers/antigravity.js';
|
|
70
80
|
import { resolveMentionedContext } from './promptMentions.js';
|
|
71
81
|
import { isLaunchOnlyPrompt, launchScopeError, isNoExecutionPrompt, isReadOnlyOrExplanatoryPrompt, readOnlyScopeError } from './launchIntent.js';
|
|
@@ -105,7 +115,7 @@ export { isActionableTaskPrompt, isGenericHandoffResponse, isDesktopWallpaperCha
|
|
|
105
115
|
function readMacDesktopPictures() {
|
|
106
116
|
try {
|
|
107
117
|
return execFileSync('osascript', ['-e', 'tell application "System Events" to get picture of every desktop'], {
|
|
108
|
-
encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore']
|
|
118
|
+
encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, env: sanitizeSubprocessEnv(process.env)
|
|
109
119
|
}).trim() || null;
|
|
110
120
|
}
|
|
111
121
|
catch {
|
|
@@ -116,63 +126,22 @@ const SYSTEM_PROMPT = `You are Causyne Agent, an autonomous local AI agent. Your
|
|
|
116
126
|
|
|
117
127
|
${PEER_COLLABORATION_POLICY}
|
|
118
128
|
|
|
119
|
-
# Your Capabilities
|
|
120
|
-
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.
|
|
121
|
-
|
|
122
129
|
${AGENT_USER_POLICY}
|
|
123
130
|
|
|
124
|
-
#
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
-
|
|
129
|
-
-
|
|
130
|
-
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
- **
|
|
134
|
-
- **
|
|
135
|
-
- **
|
|
136
|
-
- **
|
|
137
|
-
- **
|
|
138
|
-
- **No Chitchat**: Tools are for actions, text output is *only* for communication. Do not add explanatory comments within tool calls or code blocks.
|
|
139
|
-
- **File Paths**: ALWAYS output the absolute path of any file you create, modify, or generate so the user knows exactly where it is.
|
|
140
|
-
|
|
141
|
-
# Task Management & Planning
|
|
142
|
-
- 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.
|
|
143
|
-
- 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.
|
|
144
|
-
- Check off completed TODOs immediately before reporting progress. Do not batch up multiple task completions.
|
|
145
|
-
- 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.
|
|
146
|
-
|
|
147
|
-
# Durable Decisions
|
|
148
|
-
- 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.
|
|
149
|
-
- 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.
|
|
150
|
-
|
|
151
|
-
# Efficient Tool Use
|
|
152
|
-
- Batch independent searches and reads when useful. Keep edits, dependent operations, approvals, and verification in a safe order. Never run conflicting writes concurrently.
|
|
153
|
-
|
|
154
|
-
# Context Understanding & Searching
|
|
155
|
-
- Semantic search (or grep) is your MAIN exploration tool. Start with a broad, high-level query.
|
|
156
|
-
- Batch independent searches when the task needs them. Gather enough evidence to choose the next useful action; avoid repeating unchanged probes.
|
|
157
|
-
- Expand research when uncertainty or a failed check justifies it. Keep exploration proportional to the user's goal.
|
|
158
|
-
|
|
159
|
-
# Making Code Changes & Execution
|
|
160
|
-
- **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.
|
|
161
|
-
- **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'.
|
|
162
|
-
- **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.
|
|
163
|
-
- **No TODOs/Comments**: Do not add comments for trivial code. NEVER use inline comments. Avoid TODO comments—implement the logic instead.
|
|
164
|
-
- **Runnable Code**: Ensure generated code can be run immediately. Add all necessary imports, dependencies, and scaffolding (e.g. requirements.txt) if building from scratch.
|
|
165
|
-
|
|
166
|
-
# Git Workflow & Best Practices
|
|
167
|
-
- 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.
|
|
168
|
-
- Zero feature explanations or commentary on commit subject lines.
|
|
169
|
-
|
|
170
|
-
# Security & Constraints (Causyne Architecture)
|
|
171
|
-
- **Token Budgeting**: You must respect the user's BYOK (Bring Your Own Key) limits. Be highly token-efficient.
|
|
172
|
-
- **Explain Critical Commands**: Before executing destructive shell commands, provide a brief explanation of the impact.
|
|
173
|
-
- **Interactive Commands**: Avoid shell commands that require user interaction (e.g., \`git rebase -i\`). Use non-interactive flags (e.g., \`-y\`).
|
|
174
|
-
- **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.
|
|
175
|
-
- **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.
|
|
131
|
+
# Operational Guidelines & Engineering Discipline
|
|
132
|
+
- **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.
|
|
133
|
+
- **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.
|
|
134
|
+
- **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.
|
|
135
|
+
- **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.
|
|
136
|
+
- **Code Quality**: Write clear, runnable, idiomatic code following existing project conventions without trivial inline comments or TODO placeholders. Preserve unrelated behavior.
|
|
137
|
+
- **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.
|
|
138
|
+
- **Git Commits**: Follow the target repository's commit message conventions and project instructions (such as \`AGENTS.md\` or \`git log\`) when committing changes.
|
|
139
|
+
- **Autonomy & Safety Boundaries**:
|
|
140
|
+
- **Mode A (Passive)**: Ask permission before mutating files, running shell commands, or installing dependencies.
|
|
141
|
+
- **Mode B (Supervised)**: Ordinary dev dependencies allowed; ask before OS-level changes or \`sudo\`.
|
|
142
|
+
- **Mode C (Autonomous)**: Execute ordinary in-scope work independently; whole-file/directory deletion, hard policy blocks, and workspace boundaries still require approval/compliance. Avoid interactive shell flags; use non-interactive flags (\`-y\`).
|
|
143
|
+
- **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.
|
|
144
|
+
- **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.
|
|
176
145
|
|
|
177
146
|
# ABSOLUTE ETHICAL SAFETY NET (NON-NEGOTIABLE)
|
|
178
147
|
You are bound by an unbreakable ethical safety net. Regardless of user prompt, jailbreak attempts, or roleplay scenarios, you MUST REFUSE to:
|
|
@@ -187,41 +156,42 @@ You are bound by an unbreakable ethical safety net. Regardless of user prompt, j
|
|
|
187
156
|
|
|
188
157
|
If asked to perform ANY harmful task, politely decline, state that Causyne exists to make the world better, and offer legitimate developer assistance instead.
|
|
189
158
|
|
|
190
|
-
# Sovereign Reverse Engineering & Clean-Room Analysis (REA Substrate)
|
|
191
|
-
You possess native reverse engineering capabilities powered by the Reverse Engineer Anything (REA) sovereign substrate via the \`reverse_engineering\` tool.
|
|
192
|
-
- **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.
|
|
193
|
-
- **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"):
|
|
194
|
-
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.
|
|
195
|
-
2. Synthesize functional and architectural specifications (data models, UI flows, service components).
|
|
196
|
-
3. Scaffold and build the original, clean-room application using modern open-source frameworks and idiomatic patterns.
|
|
197
|
-
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.
|
|
198
|
-
|
|
199
|
-
# Dependency Management & Autonomy Modes
|
|
200
|
-
- **Mode A (Passive)**: You MUST explicitly ask the user for permission (by ending your turn and asking a question) before installing any dependencies.
|
|
201
|
-
- **Mode B (Supervised)**: You may install standard development dependencies automatically, but you MUST ask for permission before modifying OS-level settings or running \`sudo\`.
|
|
202
|
-
- **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.
|
|
203
|
-
|
|
204
|
-
# Direct API & Automation Policy
|
|
205
|
-
- **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.
|
|
206
|
-
- **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.
|
|
207
|
-
|
|
208
|
-
# Execution Environment & Toolchains in sysRun
|
|
209
|
-
- Subprocesses executed via \`sysRun\` have an enriched toolchain environment automatically configured:
|
|
210
|
-
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=...\`.
|
|
211
|
-
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=...\`.
|
|
212
|
-
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\`.
|
|
213
|
-
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\`.
|
|
214
|
-
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>\`.
|
|
215
|
-
|
|
216
|
-
# Universal Tool Calling & Registry Discipline
|
|
217
|
-
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.
|
|
218
|
-
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.
|
|
219
|
-
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.
|
|
220
|
-
4. **Valid JSON Formatting**: Never emit raw unescaped newlines, single-quoted keys, or trailing commas inside tool call JSON strings.
|
|
221
|
-
|
|
222
159
|
# Completion
|
|
223
|
-
|
|
160
|
+
Continue until the authorized work is verified or a real blocker is evidenced, then report the outcome concisely.
|
|
224
161
|
`;
|
|
162
|
+
const REA_SUBSTRATE_PROMPT = `\n\n# Sovereign Reverse Engineering & Clean-Room Analysis (REA Substrate)
|
|
163
|
+
You possess native reverse engineering capabilities via \`reverse_engineering\` for interoperability, binary inspection, security research, format decoding, manifest analysis, and clean-room application implementation.
|
|
164
|
+
- 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.`;
|
|
165
|
+
const ANDROID_TOOLCHAIN_PROMPT = `\n\n# Android & JVM Toolchains in sysRun
|
|
166
|
+
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.`;
|
|
167
|
+
const WEB_VERIFICATION_PROMPT = `\n\n# Web & UI Verification
|
|
168
|
+
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.`;
|
|
169
|
+
const ANDROID_CONTEXT_RE = /\b(?:android|apk|aab|adb|emulator|gradle|gradlew|kotlin|jetpack|compose|java|jdk|jvm|avd|dumpsys)\b/i;
|
|
170
|
+
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;
|
|
171
|
+
const CAUSYNE_CLI_BIN_PATH = fileURLToPath(new URL('../bin/causyne.js', import.meta.url));
|
|
172
|
+
export function buildSharedBrowserAwarenessPrompt(live, hasBrowserMcp) {
|
|
173
|
+
const toolHint = hasBrowserMcp
|
|
174
|
+
? '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).'
|
|
175
|
+
: 'Use `browser_act` directly (actions: `snapshot`, `extract`, `screenshot`, `click`, `type`, `scroll`, `navigate`, `listTabs`).';
|
|
176
|
+
if (!live.active) {
|
|
177
|
+
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.`;
|
|
178
|
+
}
|
|
179
|
+
const modeLabel = live.visible ? 'visible native OS window' : 'embedded live Browser Panel';
|
|
180
|
+
const engineLabel = live.engine || 'browser';
|
|
181
|
+
const tabLines = live.tabs.slice(0, 8).map((tab, idx) => {
|
|
182
|
+
const marker = tab.active ? ' [ACTIVE]' : '';
|
|
183
|
+
const titlePart = tab.title ? `"${tab.title.slice(0, 90)}" — ` : '';
|
|
184
|
+
return ` ${idx + 1}. (${tab.tabId})${marker} ${titlePart}${tab.url || 'about:blank'}`;
|
|
185
|
+
});
|
|
186
|
+
return [
|
|
187
|
+
`\n\n◆ SHARED WORKSPACE BROWSER (LIVE — shared directly with the user beside this chat):`,
|
|
188
|
+
`- Runtime: ${engineLabel} (${modeLabel}, viewport ${live.viewport.width}x${live.viewport.height})`,
|
|
189
|
+
`- Active tab: ${live.title ? `"${live.title.slice(0, 120)}" — ` : ''}${live.url || 'about:blank'} (tabId=${live.activeTabId || 'active'})`,
|
|
190
|
+
...(tabLines.length > 0 ? [`- Open tabs (${live.tabs.length}):`, ...tabLines] : []),
|
|
191
|
+
`- 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}`,
|
|
192
|
+
`- 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.`
|
|
193
|
+
].join('\n');
|
|
194
|
+
}
|
|
225
195
|
function getProviderSpecificPrompt(provider = '') {
|
|
226
196
|
const p = provider.toLowerCase();
|
|
227
197
|
if (p === 'anthropic') {
|
|
@@ -339,11 +309,12 @@ export function skillSystemMessage(skill) {
|
|
|
339
309
|
}];
|
|
340
310
|
}
|
|
341
311
|
export function explainNetworkError(error, config = {}) {
|
|
312
|
+
const safeConfig = config && typeof config === 'object' ? config : {};
|
|
342
313
|
const cause = error && error.cause;
|
|
343
|
-
const code = (cause && (cause.code || cause.errno)) || '';
|
|
314
|
+
const code = String((cause && (cause.code || cause.errno)) || error?.code || error?.errno || '');
|
|
344
315
|
let host = '';
|
|
345
316
|
try {
|
|
346
|
-
const raw =
|
|
317
|
+
const raw = safeConfig.baseUrl && String(safeConfig.baseUrl).trim();
|
|
347
318
|
if (raw)
|
|
348
319
|
host = new URL(raw).host;
|
|
349
320
|
}
|
|
@@ -359,14 +330,17 @@ export function explainNetworkError(error, config = {}) {
|
|
|
359
330
|
EHOSTUNREACH: 'that host is unreachable from this network',
|
|
360
331
|
ENETUNREACH: 'this machine has no route to the network',
|
|
361
332
|
EPIPE: 'the connection closed mid-request',
|
|
333
|
+
UND_ERR_SOCKET: 'the upstream socket closed unexpectedly',
|
|
334
|
+
ECONNABORTED: 'the connection was aborted mid-request',
|
|
335
|
+
UND_ERR_BODY_TIMEOUT: 'the server response body stalled',
|
|
362
336
|
CERT_HAS_EXPIRED: 'the TLS certificate has expired',
|
|
363
337
|
DEPTH_ZERO_SELF_SIGNED_CERT: 'the TLS certificate is self-signed — a proxy may be intercepting',
|
|
364
338
|
UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'the TLS certificate could not be verified — a proxy may be intercepting',
|
|
365
339
|
SELF_SIGNED_CERT_IN_CHAIN: 'a self-signed certificate is in the chain — a proxy may be intercepting'
|
|
366
340
|
};
|
|
367
|
-
const reason = REASONS[code] || (code ? `the connection failed (${code})` : 'the connection failed');
|
|
341
|
+
const reason = (Object.hasOwn(REASONS, code) ? REASONS[code] : undefined) || (code ? `the connection failed (${code})` : 'the connection failed');
|
|
368
342
|
const where = host ? ` reaching ${host}` : '';
|
|
369
|
-
const provider =
|
|
343
|
+
const provider = safeConfig.provider ? ` via ${safeConfig.provider}` : '';
|
|
370
344
|
const checks = [];
|
|
371
345
|
if (code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'ENETUNREACH') {
|
|
372
346
|
checks.push('confirm this machine is online');
|
|
@@ -393,6 +367,13 @@ const NETWORK_ERROR_TYPE = "network_error";
|
|
|
393
367
|
class RetryConsentCheckpoint extends Error {
|
|
394
368
|
constructor() { super('Peer paused after three failed attempts; explicit retry approval is required.'); }
|
|
395
369
|
}
|
|
370
|
+
export function resolveToolsCatalogPromptBlock(provider, fullToolsListText) {
|
|
371
|
+
const norm = String(provider || '').trim().toLowerCase();
|
|
372
|
+
if (norm === 'ollama') {
|
|
373
|
+
return 'Additional specialized tools are available on demand via tool_search(query).';
|
|
374
|
+
}
|
|
375
|
+
return fullToolsListText;
|
|
376
|
+
}
|
|
396
377
|
export class AgentLoop {
|
|
397
378
|
/**
|
|
398
379
|
* How many times in a row the same class of failure may repeat before the
|
|
@@ -419,14 +400,20 @@ export class AgentLoop {
|
|
|
419
400
|
this.modelOverride = typeof options.model === 'string' && options.model.trim()
|
|
420
401
|
? options.model.trim()
|
|
421
402
|
: null;
|
|
403
|
+
this.variantOverride = typeof options.variant === 'string' && options.variant.trim()
|
|
404
|
+
? options.variant.trim().toLowerCase()
|
|
405
|
+
: null;
|
|
422
406
|
this.approvalScope = options.approvalScope && typeof options.approvalScope.isAlwaysAllowed === 'function'
|
|
423
407
|
? options.approvalScope
|
|
424
408
|
: processApprovalScope;
|
|
409
|
+
this.peerMcpServers = Array.isArray(options.peerMcpServers)
|
|
410
|
+
? [...options.peerMcpServers]
|
|
411
|
+
: [];
|
|
425
412
|
this.config = loadConfig();
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
413
|
+
applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
|
|
414
|
+
if (this.variantOverride) {
|
|
415
|
+
this.config.reasoningEffort = this.variantOverride;
|
|
416
|
+
}
|
|
430
417
|
this.sandbox = new Sandbox({ workspaceRoot: this.workspaceRoot });
|
|
431
418
|
// Retire spilled tool outputs past their retention window. Fire-and-forget
|
|
432
419
|
// at task start rather than on a timer: nothing may run in the background
|
|
@@ -454,7 +441,9 @@ export class AgentLoop {
|
|
|
454
441
|
this.taskBuffer = new TaskBuffer();
|
|
455
442
|
this.tokenTracker = new TokenTracker();
|
|
456
443
|
this.llm = this.initializeProvider();
|
|
457
|
-
this.memoryManager = new MemoryManager(this.workspaceRoot, options.memorySessionId || null
|
|
444
|
+
this.memoryManager = new MemoryManager(this.workspaceRoot, options.memorySessionId || null, {
|
|
445
|
+
ephemeral: options.ephemeralSession === true
|
|
446
|
+
});
|
|
458
447
|
this.messages = this.memoryManager.loadHistory(); // Persistent context window
|
|
459
448
|
this.stepsCompleted = 0;
|
|
460
449
|
this.consecutiveCommands = 0;
|
|
@@ -481,7 +470,10 @@ export class AgentLoop {
|
|
|
481
470
|
this.consecutiveBlockedActions = 0; // V8 Transcendence: Circuit Breaker
|
|
482
471
|
this.recentActionSignatures = [];
|
|
483
472
|
this.consecutiveReadOnlySteps = 0;
|
|
484
|
-
this.stallGuard = new StallGuardController(
|
|
473
|
+
this.stallGuard = new StallGuardController({
|
|
474
|
+
hardStopEnabled: true,
|
|
475
|
+
identicalCallHaltAfter: TIME_MACHINE_MAX_ATTEMPTS + 1
|
|
476
|
+
});
|
|
485
477
|
this.smartToolsGovernor = new SmartToolsGovernor(4);
|
|
486
478
|
this._smartToolsNudge = null;
|
|
487
479
|
this.activeFreeFormPaths = new Map();
|
|
@@ -566,6 +558,9 @@ export class AgentLoop {
|
|
|
566
558
|
this.approvalScope = createApprovalScope();
|
|
567
559
|
this.autonomyOverride = null;
|
|
568
560
|
this.circuitBreakerUnlocked = false;
|
|
561
|
+
for (const toolCallId of [...this.pendingApprovals.keys()]) {
|
|
562
|
+
this.handleApprovalResponse(toolCallId, false);
|
|
563
|
+
}
|
|
569
564
|
this.pendingApprovals.clear();
|
|
570
565
|
}
|
|
571
566
|
// V6: Adaptive Temperature based on task intent
|
|
@@ -714,7 +709,7 @@ export class AgentLoop {
|
|
|
714
709
|
return Boolean(answer && answer.optionId === 'allow');
|
|
715
710
|
}
|
|
716
711
|
recordWebArtifact(candidate) {
|
|
717
|
-
if (typeof candidate !== 'string' || !isScannableFile(candidate))
|
|
712
|
+
if (typeof candidate !== 'string' || candidate.length === 0 || candidate.length > 4096 || candidate.includes('\0') || !isScannableFile(candidate))
|
|
718
713
|
return;
|
|
719
714
|
const lower = candidate.toLowerCase();
|
|
720
715
|
// Exclude test files, spec files, python scripts, and backend code from invalidating web verification
|
|
@@ -733,9 +728,10 @@ export class AgentLoop {
|
|
|
733
728
|
}
|
|
734
729
|
}
|
|
735
730
|
recordInspectedWebFile(candidate) {
|
|
736
|
-
if (typeof candidate !== 'string' || !candidate.trim())
|
|
731
|
+
if (typeof candidate !== 'string' || !candidate.trim() || candidate.includes('\0'))
|
|
737
732
|
return;
|
|
738
|
-
const
|
|
733
|
+
const scanText = candidate.length > 32768 ? candidate.slice(0, 32768) : candidate;
|
|
734
|
+
const matches = scanText.match(/[\w./-]+\.(?:html?|css|jsx|tsx|vue|svelte)\b/gi) || [scanText];
|
|
739
735
|
for (const rawMatch of matches) {
|
|
740
736
|
if (!isScannableFile(rawMatch))
|
|
741
737
|
continue;
|
|
@@ -869,7 +865,14 @@ export class AgentLoop {
|
|
|
869
865
|
catch (e) {
|
|
870
866
|
this.debugLog(`episodic context build skipped: ${e.message}`);
|
|
871
867
|
}
|
|
872
|
-
|
|
868
|
+
let projectInstructions = '';
|
|
869
|
+
try {
|
|
870
|
+
projectInstructions = formatProjectInstructionsPrompt(loadProjectInstructions(this.workspaceRoot));
|
|
871
|
+
}
|
|
872
|
+
catch (e) {
|
|
873
|
+
this.debugLog(`project instructions load skipped: ${e.message}`);
|
|
874
|
+
}
|
|
875
|
+
return { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext, projectInstructions };
|
|
873
876
|
}
|
|
874
877
|
rearmAbortController() {
|
|
875
878
|
this.abortController = new AbortController();
|
|
@@ -877,11 +880,16 @@ export class AgentLoop {
|
|
|
877
880
|
abort() {
|
|
878
881
|
this.stopRequested = true;
|
|
879
882
|
if (this.abortController) {
|
|
880
|
-
|
|
883
|
+
try {
|
|
884
|
+
this.abortController.abort();
|
|
885
|
+
}
|
|
886
|
+
catch {
|
|
887
|
+
// An abort listener error must not prevent provider/approval teardown.
|
|
888
|
+
}
|
|
881
889
|
}
|
|
882
890
|
if (this.llm && typeof this.llm.abort === 'function') {
|
|
883
891
|
try {
|
|
884
|
-
this.llm.abort();
|
|
892
|
+
void Promise.resolve(this.llm.abort()).catch(() => { });
|
|
885
893
|
}
|
|
886
894
|
catch {
|
|
887
895
|
// ignore provider abort errors
|
|
@@ -889,7 +897,7 @@ export class AgentLoop {
|
|
|
889
897
|
}
|
|
890
898
|
else if (this.llm && typeof this.llm.close === 'function') {
|
|
891
899
|
try {
|
|
892
|
-
void this.llm.close();
|
|
900
|
+
void Promise.resolve(this.llm.close()).catch(() => { });
|
|
893
901
|
}
|
|
894
902
|
catch {
|
|
895
903
|
// ignore provider close errors
|
|
@@ -947,7 +955,9 @@ export class AgentLoop {
|
|
|
947
955
|
initializeProvider() {
|
|
948
956
|
if (!this.config?.provider)
|
|
949
957
|
return null;
|
|
950
|
-
|
|
958
|
+
const provider = createProvider(this.config);
|
|
959
|
+
this._factoryLlmRef = provider;
|
|
960
|
+
return provider;
|
|
951
961
|
}
|
|
952
962
|
/**
|
|
953
963
|
* Tools that only observe. Nothing here writes to disk, mutates process
|
|
@@ -1018,6 +1028,18 @@ export class AgentLoop {
|
|
|
1018
1028
|
}
|
|
1019
1029
|
if (!validation || validation.allowed === false || validation.risk !== 'safe')
|
|
1020
1030
|
continue;
|
|
1031
|
+
try {
|
|
1032
|
+
const enterpriseDecision = evaluateEnterprisePolicy({
|
|
1033
|
+
tool: functionName,
|
|
1034
|
+
args,
|
|
1035
|
+
workspaceRoot: this.workspaceRoot
|
|
1036
|
+
});
|
|
1037
|
+
if (enterpriseDecision.effect === 'deny' || enterpriseDecision.effect === 'ask')
|
|
1038
|
+
continue;
|
|
1039
|
+
}
|
|
1040
|
+
catch {
|
|
1041
|
+
continue;
|
|
1042
|
+
}
|
|
1021
1043
|
const tool = resolveTool(functionName);
|
|
1022
1044
|
if (!tool || typeof tool.execute !== 'function')
|
|
1023
1045
|
continue;
|
|
@@ -1060,6 +1082,9 @@ export class AgentLoop {
|
|
|
1060
1082
|
}
|
|
1061
1083
|
/** Apply host policy to an ACP operation without disabling the peer itself. */
|
|
1062
1084
|
resolvePeerFilePath(file) {
|
|
1085
|
+
if (typeof file !== 'string' || !file.trim() || file.includes('\0')) {
|
|
1086
|
+
throw new Error('ACP path was not authorized');
|
|
1087
|
+
}
|
|
1063
1088
|
const target = path.resolve(this.workspaceRoot, file);
|
|
1064
1089
|
let ancestor = target;
|
|
1065
1090
|
while (true) {
|
|
@@ -1096,6 +1121,21 @@ export class AgentLoop {
|
|
|
1096
1121
|
const validation = this.sandbox.validate(tool, args);
|
|
1097
1122
|
if (!validation.allowed)
|
|
1098
1123
|
return false;
|
|
1124
|
+
const enterpriseDecision = evaluateEnterprisePolicy({
|
|
1125
|
+
tool,
|
|
1126
|
+
args,
|
|
1127
|
+
workspaceRoot: this.workspaceRoot
|
|
1128
|
+
});
|
|
1129
|
+
if (enterpriseDecision.effect === 'deny') {
|
|
1130
|
+
auditLog.log({
|
|
1131
|
+
event: 'peer_operation_policy_denied',
|
|
1132
|
+
taskId: this.taskId,
|
|
1133
|
+
tool,
|
|
1134
|
+
rule: enterpriseDecision.matchedRule,
|
|
1135
|
+
dimension: enterpriseDecision.matchedDimension
|
|
1136
|
+
});
|
|
1137
|
+
return false;
|
|
1138
|
+
}
|
|
1099
1139
|
const hook = await this.runPreToolUse(tool, args, id);
|
|
1100
1140
|
if (hook?.denied)
|
|
1101
1141
|
return false;
|
|
@@ -1103,11 +1143,13 @@ export class AgentLoop {
|
|
|
1103
1143
|
if (assessment.veto)
|
|
1104
1144
|
return false;
|
|
1105
1145
|
const isModeC = (this.config.autonomyMode || 'C') === 'C';
|
|
1106
|
-
const needsApproval =
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1146
|
+
const needsApproval = enterpriseDecision.effect === 'ask'
|
|
1147
|
+
|| (!isModeC && uncertain)
|
|
1148
|
+
|| requiresToolApproval({
|
|
1149
|
+
mode: this.config.autonomyMode || 'C', tool, args,
|
|
1150
|
+
risk: assessment.requiresConfirmation ? 'dangerous' : validation.risk,
|
|
1151
|
+
heavyDownload: false, standingApproval: this.isAlwaysAllowed(tool)
|
|
1152
|
+
});
|
|
1111
1153
|
if (needsApproval) {
|
|
1112
1154
|
this.emitEvent({ type: 'approval_request', toolCallId: id, tool, args, risk: validation.risk });
|
|
1113
1155
|
if (!await this.waitForApproval(id))
|
|
@@ -1119,7 +1161,21 @@ export class AgentLoop {
|
|
|
1119
1161
|
return true;
|
|
1120
1162
|
}
|
|
1121
1163
|
async requestPeerPermission(request) {
|
|
1122
|
-
const
|
|
1164
|
+
const options = Array.isArray(request?.options) ? request.options : [];
|
|
1165
|
+
const allowOption = options.find(item => item?.kind === 'allow_once');
|
|
1166
|
+
const rejectOption = options.find(item => item?.kind === 'reject_once')
|
|
1167
|
+
?? options.find(item => item?.kind === 'reject_always');
|
|
1168
|
+
const denyOutcome = () => {
|
|
1169
|
+
if (this.stopRequested || this.abortController.signal.aborted) {
|
|
1170
|
+
return { outcome: 'cancelled' };
|
|
1171
|
+
}
|
|
1172
|
+
return rejectOption?.optionId
|
|
1173
|
+
? { outcome: 'selected', optionId: rejectOption.optionId }
|
|
1174
|
+
: { outcome: 'cancelled' };
|
|
1175
|
+
};
|
|
1176
|
+
const call = request?.toolCall;
|
|
1177
|
+
if (!call || typeof call !== 'object' || typeof call.toolCallId !== 'string' || !call.toolCallId.trim())
|
|
1178
|
+
return denyOutcome();
|
|
1123
1179
|
const raw = call.rawInput && typeof call.rawInput === 'object' && !Array.isArray(call.rawInput)
|
|
1124
1180
|
? call.rawInput : {};
|
|
1125
1181
|
const args = { ...raw };
|
|
@@ -1131,7 +1187,7 @@ export class AgentLoop {
|
|
|
1131
1187
|
args[field] = this.resolvePeerFilePath(args[field]);
|
|
1132
1188
|
}
|
|
1133
1189
|
catch {
|
|
1134
|
-
return
|
|
1190
|
+
return denyOutcome();
|
|
1135
1191
|
}
|
|
1136
1192
|
}
|
|
1137
1193
|
}
|
|
@@ -1143,12 +1199,11 @@ export class AgentLoop {
|
|
|
1143
1199
|
args.command = args.cmd;
|
|
1144
1200
|
const uncertain = !['read', 'search', 'fetch', 'think'].includes(call.kind || '')
|
|
1145
1201
|
&& (tool === 'peer_native' || (tool === 'sysRun' ? !args.command : !args.path));
|
|
1146
|
-
const option = request.options.find(item => item.kind === 'allow_once');
|
|
1147
1202
|
// Never propagate a standing peer grant across sessions or forks.
|
|
1148
|
-
if (!
|
|
1149
|
-
return
|
|
1203
|
+
if (!allowOption || !await this.authorizePeerOperation(tool, { ...args, peerTitle: call.title }, `peer:${call.toolCallId}`, uncertain)) {
|
|
1204
|
+
return denyOutcome();
|
|
1150
1205
|
}
|
|
1151
|
-
return { outcome: 'selected', optionId:
|
|
1206
|
+
return { outcome: 'selected', optionId: allowOption.optionId };
|
|
1152
1207
|
}
|
|
1153
1208
|
async executePeerFile(tool, file, content, options) {
|
|
1154
1209
|
const target = this.resolvePeerFilePath(file);
|
|
@@ -1156,19 +1211,34 @@ export class AgentLoop {
|
|
|
1156
1211
|
throw new Error('ACP line must be a positive integer');
|
|
1157
1212
|
if (options?.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 1))
|
|
1158
1213
|
throw new Error('ACP limit must be a positive integer');
|
|
1214
|
+
if (options?.limit !== undefined && !Number.isSafeInteger((options.line || 1) + (options.limit - 1)))
|
|
1215
|
+
throw new Error('ACP line range exceeds the safe integer limit');
|
|
1159
1216
|
const args = { path: target, ...(tool === 'fs_write' ? { content } : {}),
|
|
1160
1217
|
...(options?.line !== undefined ? { startLine: options.line } : {}),
|
|
1161
|
-
...(options?.limit !== undefined ? { endLine: (options.line || 1) + options.limit - 1 } : {}) };
|
|
1218
|
+
...(options?.limit !== undefined ? { endLine: (options.line || 1) + (options.limit - 1) } : {}) };
|
|
1162
1219
|
const id = `peer-file:${randomUUID()}:${tool}`;
|
|
1163
1220
|
if (!await this.authorizePeerOperation(tool, args, id))
|
|
1164
1221
|
throw new Error('The requested ACP file operation was not authorized');
|
|
1222
|
+
this.resolvePeerFilePath(target);
|
|
1165
1223
|
if (tool === 'fs_write')
|
|
1166
1224
|
captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
|
|
1167
1225
|
let result;
|
|
1168
1226
|
if (tool === 'fs_read') {
|
|
1169
1227
|
// ACP expects the actual requested text, not the host tool's paging
|
|
1170
1228
|
// warning appended to a silently shortened file.
|
|
1229
|
+
const lstat = fsSync.lstatSync(target);
|
|
1230
|
+
if (lstat.isSymbolicLink() && !this.sandbox.grantAllAccess) {
|
|
1231
|
+
const realTarget = physicalPath(target);
|
|
1232
|
+
const stillAllowed = realTarget !== null && this.sandbox.workspacePaths.some((root) => {
|
|
1233
|
+
const realRoot = physicalPath(root);
|
|
1234
|
+
return realRoot !== null && isWithinPhysicalPath(realTarget, realRoot);
|
|
1235
|
+
});
|
|
1236
|
+
if (!stillAllowed)
|
|
1237
|
+
throw new Error('ACP symlink target was not authorized by the selected workspace');
|
|
1238
|
+
}
|
|
1171
1239
|
const stat = fsSync.statSync(target);
|
|
1240
|
+
if (!stat.isFile())
|
|
1241
|
+
throw new Error('ACP read_text_file requires a regular file');
|
|
1172
1242
|
if (stat.size > 4 * 1024 * 1024)
|
|
1173
1243
|
throw new Error('ACP text file exceeds the 4 MiB client transfer limit');
|
|
1174
1244
|
const bytes = fsSync.readFileSync(target);
|
|
@@ -1214,7 +1284,14 @@ export class AgentLoop {
|
|
|
1214
1284
|
}
|
|
1215
1285
|
}
|
|
1216
1286
|
if (this.eventSink && this.eventSink.readyState === 1) {
|
|
1217
|
-
|
|
1287
|
+
let serialized;
|
|
1288
|
+
try {
|
|
1289
|
+
serialized = JSON.stringify({ taskId: this.taskId, ...messageObj });
|
|
1290
|
+
}
|
|
1291
|
+
catch {
|
|
1292
|
+
serialized = JSON.stringify({ taskId: this.taskId, type: String(messageObj?.type || 'notice') });
|
|
1293
|
+
}
|
|
1294
|
+
this.eventSink.send(serialized);
|
|
1218
1295
|
}
|
|
1219
1296
|
}
|
|
1220
1297
|
// WHAT BELONGS HERE: things the user would want to know even though they did
|
|
@@ -1237,13 +1314,16 @@ export class AgentLoop {
|
|
|
1237
1314
|
debugLog(message) {
|
|
1238
1315
|
if (process.env.CAUSYNE_DEBUG !== '1')
|
|
1239
1316
|
return;
|
|
1240
|
-
|
|
1317
|
+
// eslint-disable-next-line no-control-regex
|
|
1318
|
+
const clean = redactProviderSecrets(String(message ?? '')).replace(/[\x00-\x1f\x7f]+/g, ' ').slice(0, 4096);
|
|
1319
|
+
process.stderr.write(`[causyne] ${clean}\n`);
|
|
1241
1320
|
}
|
|
1242
1321
|
handleApprovalResponse(toolCallId, approved) {
|
|
1243
1322
|
if (this.pendingApprovals.has(toolCallId)) {
|
|
1244
1323
|
const resolve = this.pendingApprovals.get(toolCallId);
|
|
1245
|
-
resolve(approved);
|
|
1246
1324
|
this.pendingApprovals.delete(toolCallId);
|
|
1325
|
+
if (typeof resolve === 'function')
|
|
1326
|
+
resolve(approved === true);
|
|
1247
1327
|
}
|
|
1248
1328
|
}
|
|
1249
1329
|
updateImplementationPlan(update, options = {}) {
|
|
@@ -1251,10 +1331,20 @@ export class AgentLoop {
|
|
|
1251
1331
|
// crash an active run. Empty arrays remain valid and can clear the plan.
|
|
1252
1332
|
if (!update || !Array.isArray(update.plan))
|
|
1253
1333
|
return;
|
|
1254
|
-
const nextPlan = update.plan
|
|
1334
|
+
const nextPlan = update.plan
|
|
1335
|
+
.filter((item) => Boolean(item) && typeof item === 'object')
|
|
1336
|
+
.map((item) => ({ ...item }));
|
|
1255
1337
|
const prevText = this._implementationPlan.map((item) => item.step).join('\n');
|
|
1256
|
-
const
|
|
1257
|
-
|
|
1338
|
+
const planKey = (entries) => {
|
|
1339
|
+
try {
|
|
1340
|
+
return JSON.stringify(entries.map((item) => ({ id: item?.id, step: item?.step, status: item?.status })));
|
|
1341
|
+
}
|
|
1342
|
+
catch {
|
|
1343
|
+
return String(entries.length);
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
const prevKey = planKey(this._implementationPlan);
|
|
1347
|
+
const nextKey = planKey(nextPlan);
|
|
1258
1348
|
this._implementationPlan = nextPlan;
|
|
1259
1349
|
if (options.seeded !== undefined) {
|
|
1260
1350
|
this._implementationPlanSeeded = Boolean(options.seeded);
|
|
@@ -1421,16 +1511,24 @@ export class AgentLoop {
|
|
|
1421
1511
|
}
|
|
1422
1512
|
}
|
|
1423
1513
|
async requestDecision(request) {
|
|
1514
|
+
if (!request || typeof request !== 'object')
|
|
1515
|
+
return null;
|
|
1424
1516
|
if (this.stopRequested || this.abortController?.signal?.aborted)
|
|
1425
1517
|
return null;
|
|
1426
|
-
const
|
|
1427
|
-
|
|
1428
|
-
|
|
1518
|
+
const safeOptions = Array.isArray(request.options) ? request.options : [];
|
|
1519
|
+
let fingerprintInput;
|
|
1520
|
+
try {
|
|
1521
|
+
fingerprintInput = JSON.stringify({ kind: request.kind, question: request.question, options: safeOptions.map((option) => option?.id ?? null) });
|
|
1522
|
+
}
|
|
1523
|
+
catch {
|
|
1524
|
+
fingerprintInput = `${String(request.kind || '')}:${String(request.question || '')}`;
|
|
1525
|
+
}
|
|
1526
|
+
const fingerprint = createHash('sha256').update(fingerprintInput).digest('hex');
|
|
1429
1527
|
const remembered = request.ephemeral === true ? null : this._decisionAnswers.get(fingerprint);
|
|
1430
1528
|
if (remembered)
|
|
1431
1529
|
return remembered;
|
|
1432
1530
|
this.emitEvent({ type: 'decision_request', request });
|
|
1433
|
-
auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount:
|
|
1531
|
+
auditLog.log({ event: 'decision_requested', taskId: this.taskId, kind: request.kind, optionCount: safeOptions.length });
|
|
1434
1532
|
// CAUSYNE_ENTITLEMENT_V1: unresolved durable decisions do not consume fresh leases.
|
|
1435
1533
|
this._entitlementGate?.pause();
|
|
1436
1534
|
let answer;
|
|
@@ -1478,10 +1576,10 @@ export class AgentLoop {
|
|
|
1478
1576
|
this.config = loadConfig();
|
|
1479
1577
|
if (this.autonomyOverride)
|
|
1480
1578
|
this.config.autonomyMode = this.autonomyOverride;
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1579
|
+
applyProviderOverrides(this.config, this.providerOverride, this.modelOverride);
|
|
1580
|
+
if (this.variantOverride) {
|
|
1581
|
+
this.config.reasoningEffort = this.variantOverride;
|
|
1582
|
+
}
|
|
1485
1583
|
if (typeof this.initializeProvider === 'function') {
|
|
1486
1584
|
const nextProvider = this.initializeProvider();
|
|
1487
1585
|
if (nextProvider) {
|
|
@@ -1901,13 +1999,58 @@ export class AgentLoop {
|
|
|
1901
1999
|
}
|
|
1902
2000
|
}
|
|
1903
2001
|
else if (att.type === 'document') {
|
|
2002
|
+
if (typeof att.name !== 'string' || typeof att.base64 !== 'string' || !att.base64.trim()) {
|
|
2003
|
+
this.notice('skipped malformed document attachment', 'warn');
|
|
2004
|
+
continue;
|
|
2005
|
+
}
|
|
1904
2006
|
const fs = await import('fs');
|
|
1905
2007
|
const path = await import('path');
|
|
1906
2008
|
// Ensure unique name to prevent overwriting
|
|
1907
|
-
const
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
2009
|
+
const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024;
|
|
2010
|
+
if (att.base64.length > Math.ceil(MAX_ATTACHMENT_BYTES * 4 / 3) + 64) {
|
|
2011
|
+
this.notice('skipped oversized document attachment (exceeds 16 MiB limit)', 'warn');
|
|
2012
|
+
continue;
|
|
2013
|
+
}
|
|
2014
|
+
const decodedBytes = Buffer.from(att.base64, 'base64');
|
|
2015
|
+
if (decodedBytes.length > MAX_ATTACHMENT_BYTES) {
|
|
2016
|
+
this.notice('skipped oversized document attachment (exceeds 16 MiB limit)', 'warn');
|
|
2017
|
+
continue;
|
|
2018
|
+
}
|
|
2019
|
+
const baseName = path.basename(att.name).replace(/[^a-zA-Z0-9.\-_]/g, '_').replace(/^\.+/, '');
|
|
2020
|
+
const safeName = (!baseName || baseName === '.' || baseName === '..') ? 'attachment.bin' : baseName.slice(0, 128);
|
|
2021
|
+
const realWorkspaceRoot = physicalPath(this.workspaceRoot);
|
|
2022
|
+
if (!realWorkspaceRoot) {
|
|
2023
|
+
this.notice('skipped document attachment: workspace root could not be resolved', 'warn');
|
|
2024
|
+
continue;
|
|
2025
|
+
}
|
|
2026
|
+
const ext = path.extname(safeName);
|
|
2027
|
+
const stem = ext ? safeName.slice(0, -ext.length) : safeName;
|
|
2028
|
+
let finalName = safeName;
|
|
2029
|
+
let writePath = '';
|
|
2030
|
+
let saved = false;
|
|
2031
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
2032
|
+
finalName = attempt === 0 ? safeName : `${stem}-${attempt}${ext}`;
|
|
2033
|
+
const candidatePath = path.join(realWorkspaceRoot, finalName);
|
|
2034
|
+
const resolvedCandidate = physicalPath(candidatePath);
|
|
2035
|
+
if (!resolvedCandidate || !isWithinPhysicalPath(resolvedCandidate, realWorkspaceRoot))
|
|
2036
|
+
break;
|
|
2037
|
+
try {
|
|
2038
|
+
fs.writeFileSync(candidatePath, decodedBytes, { flag: 'wx', mode: 0o600 });
|
|
2039
|
+
writePath = candidatePath;
|
|
2040
|
+
saved = true;
|
|
2041
|
+
break;
|
|
2042
|
+
}
|
|
2043
|
+
catch (writeErr) {
|
|
2044
|
+
if (writeErr?.code === 'EEXIST')
|
|
2045
|
+
continue;
|
|
2046
|
+
throw writeErr;
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
if (!saved) {
|
|
2050
|
+
this.notice(`could not save attached document '${safeName}' safely without overwriting`, 'warn');
|
|
2051
|
+
continue;
|
|
2052
|
+
}
|
|
2053
|
+
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.]`;
|
|
1911
2054
|
this.notice(`saved attached document to ${writePath}`);
|
|
1912
2055
|
}
|
|
1913
2056
|
}
|
|
@@ -2009,17 +2152,25 @@ export class AgentLoop {
|
|
|
2009
2152
|
// tool payloads decay into stubs, and anything amputated is physically
|
|
2010
2153
|
// replaced by a summary, so memory, disk and CPU all stay bounded.
|
|
2011
2154
|
const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
|
|
2012
|
-
const
|
|
2155
|
+
const rawCharPool = resolveCharPool(activeTier, this.config.maxCharPool, {
|
|
2013
2156
|
provider: this.config.provider,
|
|
2014
2157
|
model: this.config.model,
|
|
2015
2158
|
overrideTokens: this.config.contextTokens || this.config.maxContextTokens
|
|
2016
2159
|
});
|
|
2160
|
+
// Keep MAX_CHAR_POOL as the true model context ceiling for accurate usage reporting,
|
|
2161
|
+
// while reserving 25% compaction headroom for system prompt, tool schemas, and output tokens.
|
|
2162
|
+
const MAX_CHAR_POOL = rawCharPool;
|
|
2163
|
+
const COMPACTION_CHAR_POOL = this.config.maxCharPool
|
|
2164
|
+
? MAX_CHAR_POOL
|
|
2165
|
+
: Math.max(24_000, Math.floor(MAX_CHAR_POOL * 0.75));
|
|
2017
2166
|
// 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
|
|
2018
|
-
//
|
|
2019
|
-
//
|
|
2167
|
+
// Under low context pressure (<25% of pool), keep more recent small file reads
|
|
2168
|
+
// verbatim so models do not lose a 1-2 KB source file after four tool calls.
|
|
2169
|
+
const currentMessageChars = measureMessages(this.messages);
|
|
2170
|
+
const lowContextPressure = currentMessageChars < COMPACTION_CHAR_POOL * 0.25;
|
|
2020
2171
|
const observationPrune = pruneStaleToolObservations(this.messages, {
|
|
2021
|
-
keepRecent: this.config.keepRecentToolResults ?? 4,
|
|
2022
|
-
minChars: 600,
|
|
2172
|
+
keepRecent: this.config.keepRecentToolResults ?? (lowContextPressure ? 12 : 4),
|
|
2173
|
+
minChars: lowContextPressure ? 2400 : 600,
|
|
2023
2174
|
taskId: this.taskId
|
|
2024
2175
|
});
|
|
2025
2176
|
const argumentPrune = pruneExecutedToolArguments(this.messages, { taskId: this.taskId });
|
|
@@ -2032,7 +2183,7 @@ export class AgentLoop {
|
|
|
2032
2183
|
if (typeof message.spillPath === 'string')
|
|
2033
2184
|
recoveryPaths.add(path.resolve(message.spillPath));
|
|
2034
2185
|
}
|
|
2035
|
-
const compaction = applyProgressiveCompaction(this.messages,
|
|
2186
|
+
const compaction = applyProgressiveCompaction(this.messages, COMPACTION_CHAR_POOL, {
|
|
2036
2187
|
// historyPruner preserves full output before eliding it. The legacy
|
|
2037
2188
|
// decay path cannot promise that recovery, so keep it disabled here.
|
|
2038
2189
|
enableEphemeralDecay: false,
|
|
@@ -2061,7 +2212,7 @@ export class AgentLoop {
|
|
|
2061
2212
|
limitChars: MAX_CHAR_POOL
|
|
2062
2213
|
});
|
|
2063
2214
|
}
|
|
2064
|
-
const { window: slidingWindow, splitIndex } = buildWindow(this.messages,
|
|
2215
|
+
const { window: slidingWindow, splitIndex } = buildWindow(this.messages, COMPACTION_CHAR_POOL);
|
|
2065
2216
|
// What the context window actually holds right now.
|
|
2066
2217
|
//
|
|
2067
2218
|
// The footer's context meter was being fed `usedTokens` — the CUMULATIVE
|
|
@@ -2075,16 +2226,16 @@ export class AgentLoop {
|
|
|
2075
2226
|
// built from, one line after it is built.
|
|
2076
2227
|
this._contextChars = measureMessages(slidingWindow);
|
|
2077
2228
|
this._contextLimitChars = MAX_CHAR_POOL;
|
|
2078
|
-
// Real compaction: physically collapse the amputated range
|
|
2079
|
-
//
|
|
2080
|
-
// never compacted away.
|
|
2229
|
+
// Real compaction: physically collapse the amputated range at a turn-safe
|
|
2230
|
+
// boundary so role=tool results are never orphaned from their tool_calls.
|
|
2081
2231
|
if (splitIndex >= 1) {
|
|
2082
|
-
const
|
|
2083
|
-
|
|
2232
|
+
const safeSplit = findSafeCompactionSplitIndex(this.messages, splitIndex);
|
|
2233
|
+
const dropped = safeSplit >= 1 ? this.messages.slice(1, safeSplit + 1) : [];
|
|
2234
|
+
if (dropped.length > 0 && safeSplit >= 1) {
|
|
2084
2235
|
const compactSummary = buildRecoverableDroppedSummary(dropped, buildCodexStyleSummary(dropped, this.currentTaskPrompt || this.userPrompt)
|
|
2085
2236
|
|| buildStructuralSummary(dropped)
|
|
2086
2237
|
|| describeDroppedMessages(dropped));
|
|
2087
|
-
const removed = compactInPlace(this.messages,
|
|
2238
|
+
const removed = compactInPlace(this.messages, safeSplit, compactSummary);
|
|
2088
2239
|
this._lastCompactionIndex = null;
|
|
2089
2240
|
this.debugLog(`compacted ${removed} messages out of the live context`);
|
|
2090
2241
|
auditLog.log({
|
|
@@ -2119,8 +2270,15 @@ export class AgentLoop {
|
|
|
2119
2270
|
deniedTools: this.config.deniedTools
|
|
2120
2271
|
});
|
|
2121
2272
|
await this.ensureToolsList(eligibleTools);
|
|
2273
|
+
const promptForDomain = this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '';
|
|
2274
|
+
const liveBrowserAwareness = causyneBrowser({ workspace: this.workspaceRoot }).getLiveAwarenessContext();
|
|
2275
|
+
const sharedBrowserRelevant = liveBrowserAwareness.active || SHARED_BROWSER_INTENT_RE.test(promptForDomain);
|
|
2276
|
+
if (sharedBrowserRelevant) {
|
|
2277
|
+
this.savedTools.admitTool('browser_act');
|
|
2278
|
+
}
|
|
2122
2279
|
const permittedTools = this.toolScope instanceof Set && this.toolScope.size > 0
|
|
2123
|
-
? eligibleTools.filter((tool) => this.toolScope.has(tool.name)
|
|
2280
|
+
? eligibleTools.filter((tool) => this.toolScope.has(tool.name) || (sharedBrowserRelevant && tool.name === 'browser_act'))
|
|
2281
|
+
: eligibleTools;
|
|
2124
2282
|
const dynamicTools = this.smartTools.schemas(permittedTools, this.unlockedTools, this.unlockedPacks, this.config.grantAllTools === true);
|
|
2125
2283
|
const dynamicToolNames = dynamicTools.map((t) => t.name);
|
|
2126
2284
|
// Pre-flight universal schema audit (toolsScan): verify dialect readiness and cache
|
|
@@ -2144,20 +2302,27 @@ export class AgentLoop {
|
|
|
2144
2302
|
? "/ (ALL ACCESS GRANTED - You can read/write anywhere EXCEPT system protected folders like /etc or /System)"
|
|
2145
2303
|
: (this.sandbox.workspacePaths ? this.sandbox.workspacePaths.join(', ') : this.workspaceRoot);
|
|
2146
2304
|
const baseProviderPrompt = getProviderSpecificPrompt(this.config.provider);
|
|
2147
|
-
const
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2305
|
+
const domainArchetype = determineToolScope(promptForDomain, this.taskShape).archetype;
|
|
2306
|
+
const isVisualOrWebTask = isWebIntent(promptForDomain)
|
|
2307
|
+
|| this.hasWebSurfaceArtifacts()
|
|
2308
|
+
|| domainArchetype === 'web_engineering'
|
|
2309
|
+
|| domainArchetype === 'game_development'
|
|
2310
|
+
|| domainArchetype === 'media_3d_generation';
|
|
2311
|
+
const sensoryAwareness = isVisualOrWebTask
|
|
2312
|
+
? (this.llm.supportsVision
|
|
2313
|
+
? `\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE
|
|
2314
|
+
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.`
|
|
2315
|
+
: `\n# SENSORY PROFILE: TEXT & CODE ENGINE (VISION INACTIVE)
|
|
2316
|
+
Verify Web/UI/3D work programmatically via browser_act (DOM snapshot + runtimeErrors), code_verify_syntax, and unit tests.`)
|
|
2317
|
+
: (this.llm.supportsVision
|
|
2318
|
+
? '\n# SENSORY PROFILE: MULTIMODAL VISION ACTIVE'
|
|
2319
|
+
: '\n# SENSORY PROFILE: TEXT & CODE ENGINE — verify changes via project tests, typechecks, and execution logs.');
|
|
2320
|
+
const domainPrompts = [
|
|
2321
|
+
(this.unlockedPacks.has('reverse_engineering') || domainArchetype === 'reverse_engineering') ? REA_SUBSTRATE_PROMPT : '',
|
|
2322
|
+
(ANDROID_CONTEXT_RE.test(promptForDomain) || ANDROID_CONTEXT_RE.test(String(this.workspaceContext?.projectType || ''))) ? ANDROID_TOOLCHAIN_PROMPT : '',
|
|
2323
|
+
isVisualOrWebTask ? WEB_VERIFICATION_PROMPT : ''
|
|
2324
|
+
].join('');
|
|
2325
|
+
const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}${domainPrompts}`;
|
|
2161
2326
|
const memoryContext = getMemoryContextString({ workspaceRoot: this.workspaceRoot });
|
|
2162
2327
|
// --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
|
|
2163
2328
|
// Cortex retrieval, design detection, creative-pattern lookup and the
|
|
@@ -2168,7 +2333,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2168
2333
|
if (!this.staticContext) {
|
|
2169
2334
|
this.staticContext = await this.buildStaticContext();
|
|
2170
2335
|
}
|
|
2171
|
-
const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext } = this.staticContext;
|
|
2336
|
+
const { lessonsLearned, designContext, antiRepeatDirective, universalSkillsContext, planHint, episodicContext, projectInstructions } = this.staticContext;
|
|
2172
2337
|
// --- WORKSPACE AWARENESS ---
|
|
2173
2338
|
// perception.buildContext() output used to be computed and discarded,
|
|
2174
2339
|
// leaving the agent blind and forcing it to rediscover the project with
|
|
@@ -2262,6 +2427,22 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2262
2427
|
catch (e) {
|
|
2263
2428
|
this.debugLog(`uncertainty gate skipped: ${e.message}`);
|
|
2264
2429
|
}
|
|
2430
|
+
const effectivePeerMcpServers = Array.isArray(this.peerMcpServers)
|
|
2431
|
+
? [...this.peerMcpServers]
|
|
2432
|
+
: [];
|
|
2433
|
+
const hasConfiguredBrowserMcp = effectivePeerMcpServers.some((srv) => srv?.name === 'causyne-browser');
|
|
2434
|
+
if (!hasConfiguredBrowserMcp && isAcpProvider(this.config?.provider) && !process.env.NODE_TEST_CONTEXT) {
|
|
2435
|
+
effectivePeerMcpServers.push({
|
|
2436
|
+
name: 'causyne-browser',
|
|
2437
|
+
command: process.execPath,
|
|
2438
|
+
args: [CAUSYNE_CLI_BIN_PATH, 'browser-mcp', '--workspace', this.workspaceRoot],
|
|
2439
|
+
env: []
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2442
|
+
const hasBrowserMcpAttached = effectivePeerMcpServers.some((srv) => srv?.name === 'causyne-browser');
|
|
2443
|
+
const sharedBrowserPrompt = buildSharedBrowserAwarenessPrompt(liveBrowserAwareness, hasBrowserMcpAttached);
|
|
2444
|
+
const isLocalOllama = String(this.config?.provider || '').trim().toLowerCase() === 'ollama';
|
|
2445
|
+
const effectiveToolsListText = resolveToolsCatalogPromptBlock(this.config?.provider, this.toolsListText || renderToolsList(buildToolsList()));
|
|
2265
2446
|
const systemMessages = [
|
|
2266
2447
|
// [1] stable for the entire task — the primary cache anchor.
|
|
2267
2448
|
{ role: 'system', content: SYSTEM_PROMPT, cacheAnchor: true },
|
|
@@ -2269,7 +2450,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2269
2450
|
// is stable within a task and gets its own breakpoint.
|
|
2270
2451
|
{
|
|
2271
2452
|
role: 'system',
|
|
2272
|
-
content: `${taskBrief ? taskBrief + '\n\n' : ''}${
|
|
2453
|
+
content: `${taskBrief ? taskBrief + '\n\n' : ''}${effectiveToolsListText}${activePlaybooks ? '\n\n' + activePlaybooks : ''}`,
|
|
2273
2454
|
cacheAnchor: true
|
|
2274
2455
|
},
|
|
2275
2456
|
// [3] per-task STATIC context — provider activation, detected design,
|
|
@@ -2278,7 +2459,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2278
2459
|
// is byte-identical every step; cached.
|
|
2279
2460
|
{
|
|
2280
2461
|
role: 'system',
|
|
2281
|
-
content: `${providerPrompt}${designContext}${workspaceSummary}${lessonsLearned}${episodicContext ? '\n\n' + episodicContext : ''}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}
|
|
2462
|
+
content: `${providerPrompt}${designContext}${workspaceSummary}${projectInstructions || ''}${lessonsLearned}${!isLocalOllama && episodicContext ? '\n\n' + episodicContext : ''}${planHint ? '\n' + planHint + '\n' : ''}${antiRepeatDirective}${!isLocalOllama && universalSkillsContext ? '\n' + universalSkillsContext : ''}`,
|
|
2282
2463
|
cacheAnchor: true
|
|
2283
2464
|
},
|
|
2284
2465
|
// [4] THE INVOKED SKILL, when the user named one.
|
|
@@ -2295,12 +2476,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2295
2476
|
// so it anchors too.
|
|
2296
2477
|
...(skillSystemMessage(this.activeSkill) || []),
|
|
2297
2478
|
// [5] VOLATILE tail — the only bytes that may differ between steps:
|
|
2298
|
-
// autonomy/workspace paths (change via config)
|
|
2299
|
-
// (grows via memory_write mid-task).
|
|
2300
|
-
//
|
|
2479
|
+
// autonomy/workspace paths (change via config), live shared browser
|
|
2480
|
+
// state, and persistent memory (grows via memory_write mid-task).
|
|
2481
|
+
// Kept LAST and UNcached so a change here never invalidates [1]-[3].
|
|
2301
2482
|
{
|
|
2302
2483
|
role: 'system',
|
|
2303
|
-
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}` : ''}`
|
|
2484
|
+
content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)${sharedBrowserPrompt}${memoryContext ? `\n\n◆ PERSISTENT MEMORY (workspace-relevant notes — actual repository files and docs on disk always override memory if anything conflicts):\n${memoryContext}` : ''}`
|
|
2304
2485
|
}
|
|
2305
2486
|
];
|
|
2306
2487
|
// Dev-only visibility into what fills each step's prompt. Set
|
|
@@ -2439,6 +2620,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2439
2620
|
const response = await this.llm.chat(prunedMessages, {
|
|
2440
2621
|
taskId: this.taskId,
|
|
2441
2622
|
conversationId: this.memoryManager?.sessionId || this.taskId,
|
|
2623
|
+
cacheKey: `causyne_${createHash('sha256').update(`${this.workspaceRoot}:${this.memoryManager?.sessionId || this.taskId}`).digest('hex').slice(0, 32)}`,
|
|
2442
2624
|
taskIntent: isLaunchOnlyPrompt(this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '') ? 'launch' : 'general',
|
|
2443
2625
|
taskArchetype: determineToolScope(this.taskIntentPrompt || this.currentTaskPrompt || this.userPrompt || '', this.taskShape).archetype,
|
|
2444
2626
|
hardBudget: hardBudget,
|
|
@@ -2457,6 +2639,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2457
2639
|
? remainingBudget : undefined,
|
|
2458
2640
|
taskDeadlineMs: this._taskWallDeadlineAt ?? undefined,
|
|
2459
2641
|
workspaceRoot: this.workspaceRoot,
|
|
2642
|
+
...(effectivePeerMcpServers.length > 0 ? { peerMcpServers: effectivePeerMcpServers } : {}),
|
|
2460
2643
|
onPeerPermission: (request) => this.requestPeerPermission(request),
|
|
2461
2644
|
onPeerFileRead: (file, options) => this.executePeerFile('fs_read', file, undefined, options),
|
|
2462
2645
|
onPeerFileWrite: async (file, content) => { await this.executePeerFile('fs_write', file, content); },
|
|
@@ -2524,6 +2707,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2524
2707
|
if (cleanProse && !cleanProse.startsWith('```')) {
|
|
2525
2708
|
this.emitEvent({
|
|
2526
2709
|
type: 'agent_message',
|
|
2710
|
+
streamId: invocation,
|
|
2527
2711
|
content: cleanProse,
|
|
2528
2712
|
delta: _chunk,
|
|
2529
2713
|
streaming: true
|
|
@@ -2688,7 +2872,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2688
2872
|
}
|
|
2689
2873
|
else if (action.status === 'failed') {
|
|
2690
2874
|
this.emitEvent({ type: 'status', message: '' });
|
|
2691
|
-
this.emitEvent({
|
|
2875
|
+
this.emitEvent({
|
|
2876
|
+
type: 'warning',
|
|
2877
|
+
nativeStep: true,
|
|
2878
|
+
nativeFailed: true,
|
|
2879
|
+
actionName: action.name,
|
|
2880
|
+
detail: action.detail,
|
|
2881
|
+
message: `${this.config.provider || 'Provider'} could not ${action.name}${detail}`
|
|
2882
|
+
});
|
|
2692
2883
|
}
|
|
2693
2884
|
}
|
|
2694
2885
|
}).catch((error) => {
|
|
@@ -2774,6 +2965,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2774
2965
|
// the project's own CHAR_POOLS convention, instead of comparing a token
|
|
2775
2966
|
// count to a character limit.
|
|
2776
2967
|
const reportedPromptTokens = Number(response.usage?.promptTokens || 0);
|
|
2968
|
+
const reportedCompletionTokens = Number(response.usage?.completionTokens || 0);
|
|
2777
2969
|
if (response.usage?.measurement === 'provider_reported'
|
|
2778
2970
|
&& response.usage?.measurementScope !== 'cumulative'
|
|
2779
2971
|
&& Number.isFinite(reportedPromptTokens)
|
|
@@ -2797,8 +2989,20 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2797
2989
|
lifetimeCostUsd: tracking.lifetimeCostUsd || 0,
|
|
2798
2990
|
contextChars: this._contextChars || 0,
|
|
2799
2991
|
contextLimitChars: this._contextLimitChars || 0,
|
|
2800
|
-
cachedTokens
|
|
2992
|
+
cachedTokens,
|
|
2993
|
+
inputTokens: Number.isFinite(reportedPromptTokens) && reportedPromptTokens > 0 ? reportedPromptTokens : 0,
|
|
2994
|
+
outputTokens: Number.isFinite(reportedCompletionTokens) && reportedCompletionTokens > 0 ? reportedCompletionTokens : 0
|
|
2801
2995
|
});
|
|
2996
|
+
const taskCostCap = typeof this.taskCostLimitUsd === 'number' && Number.isFinite(this.taskCostLimitUsd) && this.taskCostLimitUsd > 0
|
|
2997
|
+
? this.taskCostLimitUsd
|
|
2998
|
+
: null;
|
|
2999
|
+
if (taskCostCap !== null && (tracking.taskCostUsd || 0) >= taskCostCap) {
|
|
3000
|
+
this.emitEvent({
|
|
3001
|
+
type: 'error',
|
|
3002
|
+
message: `Task USD budget limit reached ($${(tracking.taskCostUsd || 0).toFixed(4)} >= $${taskCostCap.toFixed(4)}).`
|
|
3003
|
+
});
|
|
3004
|
+
break;
|
|
3005
|
+
}
|
|
2802
3006
|
if (!tracking.allowed) {
|
|
2803
3007
|
this.emitEvent({ type: 'error', message: tracking.reason });
|
|
2804
3008
|
break;
|
|
@@ -3167,7 +3371,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3167
3371
|
if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations < 3) {
|
|
3168
3372
|
incompleteTurnContinuations++;
|
|
3169
3373
|
if (response.content) {
|
|
3170
|
-
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
3374
|
+
this.emitEvent({ type: 'agent_message', streamId: invocation, content: response.content });
|
|
3171
3375
|
}
|
|
3172
3376
|
const blockedNote = failedExternalActions.length > 0
|
|
3173
3377
|
? ` Note: ${failedExternalActions.map((a) => `${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.`
|
|
@@ -3186,7 +3390,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3186
3390
|
if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations === 3) {
|
|
3187
3391
|
incompleteTurnContinuations++;
|
|
3188
3392
|
if (response.content) {
|
|
3189
|
-
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
3393
|
+
this.emitEvent({ type: 'agent_message', streamId: invocation, content: response.content });
|
|
3190
3394
|
}
|
|
3191
3395
|
this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
|
|
3192
3396
|
this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
|
|
@@ -3210,7 +3414,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3210
3414
|
.replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
|
|
3211
3415
|
.trim();
|
|
3212
3416
|
if (partial.length >= 20) {
|
|
3213
|
-
this.emitEvent({ type: 'agent_message', content: partial });
|
|
3417
|
+
this.emitEvent({ type: 'agent_message', streamId: invocation, content: partial });
|
|
3214
3418
|
}
|
|
3215
3419
|
this.emitEvent({ type: 'error', message: 'The peer ended with an incomplete or progress-only turn. ' +
|
|
3216
3420
|
'Actions may have changed files, but completion is not established.' });
|
|
@@ -3243,9 +3447,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3243
3447
|
if (!hasExternalActions && (isIncompleteTurn || failedExternalActions.length > 0 || !contentText.trim())) {
|
|
3244
3448
|
if (this.stepsCompleted > 0 && incompleteTurnContinuations < 2 && failedExternalActions.length === 0) {
|
|
3245
3449
|
incompleteTurnContinuations++;
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3450
|
+
if (isActionable && taskMutationCount === 0 && !isLaunchOnlyPrompt(taskPrompt) && !isPlanningOnlyRequest(taskPrompt)) {
|
|
3451
|
+
this.emitEvent({ type: 'status', message: 'Continuing execution after reasoning-only turn…' });
|
|
3452
|
+
this.messages.push({ role: 'system', content: '[CONTINUE EXECUTION] Your previous turn produced reasoning without invoking a tool or applying the requested changes. ' +
|
|
3453
|
+
'Continue immediately by calling the appropriate tool (such as fs_edit, apply_patch, fs_write, or sysRun) to implement and verify the task.' });
|
|
3454
|
+
}
|
|
3455
|
+
else {
|
|
3456
|
+
this.emitEvent({ type: 'status', message: 'Requesting the missing final response…' });
|
|
3457
|
+
this.messages.push({ role: 'system', content: '[FINAL RESPONSE REQUIRED] Report actual completed and incomplete work from tool results. ' +
|
|
3458
|
+
'Do not call plan steps or file writes proof of verification.' });
|
|
3459
|
+
}
|
|
3249
3460
|
this.memoryManager.saveHistory(this.messages);
|
|
3250
3461
|
continue;
|
|
3251
3462
|
}
|
|
@@ -3600,6 +3811,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3600
3811
|
const finalToolOutcomes = coldObserver.getToolOutcomes(this.taskId);
|
|
3601
3812
|
const finalToolOutcome = finalToolOutcomes[finalToolOutcomes.length - 1];
|
|
3602
3813
|
if (this.stepsCompleted > 0 && finalToolOutcome && !finalToolOutcome.success) {
|
|
3814
|
+
const blockerExplanation = typeof response.content === 'string'
|
|
3815
|
+
? response.content
|
|
3816
|
+
.replace(/^Antigravity executed:[^\n]*\n*/i, '')
|
|
3817
|
+
.replace(/^Turn completed by [^\n]+ over ACP\.\s*/i, '')
|
|
3818
|
+
.trim()
|
|
3819
|
+
: '';
|
|
3820
|
+
if (blockerExplanation.length >= 20) {
|
|
3821
|
+
this.emitEvent({ type: 'agent_message', streamId: invocation, content: blockerExplanation });
|
|
3822
|
+
}
|
|
3603
3823
|
this.emitEvent({ type: 'error', message: `The last observed tool action failed (${finalToolOutcome.tool}). ` +
|
|
3604
3824
|
'Resolve the error or report partial work; no success has been recorded.' });
|
|
3605
3825
|
this.memoryManager.saveHistory(this.messages);
|
|
@@ -3609,11 +3829,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3609
3829
|
if (isAuthoringTask) {
|
|
3610
3830
|
const outcomes = coldObserver.getToolOutcomes(this.taskId);
|
|
3611
3831
|
const hasCodeOrWorkspaceMutation = this.webArtifacts.size > 0 || outcomes.some((o) => o.success !== false && [
|
|
3612
|
-
'fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit', 'multi_edit',
|
|
3832
|
+
'fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit', 'multi_edit', 'apply_patch',
|
|
3613
3833
|
'ui_forge', 'write_file', 'write_to_file', 'edit_file', 'replace_file_content',
|
|
3614
3834
|
'multi_replace_file_content', 'native_engine', 'update_plan'
|
|
3615
3835
|
].includes(String(o.tool || '')));
|
|
3616
|
-
|
|
3836
|
+
const rawReply = typeof response.content === 'string' ? response.content.trim() : '';
|
|
3837
|
+
const hasVerifiedFailureBlocker = outcomes.some((o) => o.success === false)
|
|
3838
|
+
&& rawReply.length >= 25
|
|
3839
|
+
&& /\b(?:blocked|cannot|unable|missing|permission denied|not installed|failed|error)\b/i.test(rawReply);
|
|
3840
|
+
if (!hasCodeOrWorkspaceMutation && completedNativeActionIds.size === 0 && !hasVerifiedFailureBlocker) {
|
|
3617
3841
|
if (this._nonMutationNudges === undefined)
|
|
3618
3842
|
this._nonMutationNudges = 0;
|
|
3619
3843
|
if (this._nonMutationNudges < 2) {
|
|
@@ -3644,7 +3868,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3644
3868
|
};
|
|
3645
3869
|
const substantiveTerminalContent = cleanTerminalContent(response.content);
|
|
3646
3870
|
if (substantiveTerminalContent.length >= 20) {
|
|
3647
|
-
this.emitEvent({ type: 'agent_message', content: substantiveTerminalContent });
|
|
3871
|
+
this.emitEvent({ type: 'agent_message', streamId: invocation, content: substantiveTerminalContent });
|
|
3648
3872
|
}
|
|
3649
3873
|
else {
|
|
3650
3874
|
const recentSubstantive = [...this.messages].reverse().find(m => m.role === 'assistant'
|
|
@@ -3669,7 +3893,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3669
3893
|
});
|
|
3670
3894
|
}
|
|
3671
3895
|
else if (response.content) {
|
|
3672
|
-
this.emitEvent({ type: 'agent_message', content: response.content });
|
|
3896
|
+
this.emitEvent({ type: 'agent_message', streamId: invocation, content: response.content });
|
|
3673
3897
|
}
|
|
3674
3898
|
}
|
|
3675
3899
|
if (this.stepsCompleted > 0) {
|
|
@@ -3852,7 +4076,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3852
4076
|
let actionSig = `${functionName}:${JSON.stringify(args || {})}`;
|
|
3853
4077
|
if (functionName === 'sysRun' || functionName === 'sysRunBg') {
|
|
3854
4078
|
const rawCmd = String(args?.command || '').trim();
|
|
3855
|
-
if (
|
|
4079
|
+
if (/\bpython[0-9.]*\s/i.test(rawCmd) && /\bimport\s+numpy\b/i.test(rawCmd)) {
|
|
3856
4080
|
actionSig = 'sysRun:probe:numpy';
|
|
3857
4081
|
}
|
|
3858
4082
|
else if (/python[0-9.]*\s+(--version|-V|-c\s+['"]print)/i.test(rawCmd)) {
|
|
@@ -4110,21 +4334,82 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4110
4334
|
catch (_err) {
|
|
4111
4335
|
// Cold observer mutation assessment fail-open
|
|
4112
4336
|
}
|
|
4337
|
+
// Declarative enterprise policy (`causyne.policy.json`): deterministic
|
|
4338
|
+
// allow / ask / deny gate outside the model. Runs after Sandbox and Cold
|
|
4339
|
+
// Observer so it can never weaken workspace isolation or observer vetoes.
|
|
4340
|
+
const enterpriseDecision = evaluateEnterprisePolicy({
|
|
4341
|
+
tool: functionName,
|
|
4342
|
+
args,
|
|
4343
|
+
workspaceRoot: this.workspaceRoot
|
|
4344
|
+
});
|
|
4345
|
+
if (enterpriseDecision.effect === 'deny') {
|
|
4346
|
+
this.emitEvent({
|
|
4347
|
+
type: 'status',
|
|
4348
|
+
message: `Enterprise Policy Denied: ${enterpriseDecision.reason}`
|
|
4349
|
+
});
|
|
4350
|
+
auditLog.log({
|
|
4351
|
+
event: 'enterprise_policy_denied',
|
|
4352
|
+
taskId: this.taskId,
|
|
4353
|
+
tool: functionName,
|
|
4354
|
+
dimension: enterpriseDecision.matchedDimension,
|
|
4355
|
+
rule: enterpriseDecision.matchedRule,
|
|
4356
|
+
reason: enterpriseDecision.reason
|
|
4357
|
+
});
|
|
4358
|
+
coldObserver.recordToolOutcome(this.taskId, functionName, args, {
|
|
4359
|
+
success: false,
|
|
4360
|
+
error: `[ENTERPRISE POLICY DENIED]: ${enterpriseDecision.reason}`
|
|
4361
|
+
});
|
|
4362
|
+
this.messages.push({
|
|
4363
|
+
role: 'tool',
|
|
4364
|
+
tool_call_id: toolCall.id,
|
|
4365
|
+
name: functionName,
|
|
4366
|
+
content: JSON.stringify({
|
|
4367
|
+
success: false,
|
|
4368
|
+
error: `[ENTERPRISE POLICY DENIED]: ${enterpriseDecision.reason}`
|
|
4369
|
+
})
|
|
4370
|
+
});
|
|
4371
|
+
continue;
|
|
4372
|
+
}
|
|
4113
4373
|
// A standing grant can avoid repeat prompts in supervised modes.
|
|
4114
4374
|
// Mode C is autonomous for in-scope work. Whole-file deletion asks
|
|
4115
4375
|
// unless this session explicitly granted the fs_delete tool; a broad
|
|
4116
4376
|
// shell grant cannot authorize deletion. Sandbox denials and observer
|
|
4117
4377
|
// vetoes have already run and are never lifted by prompt policy.
|
|
4118
4378
|
const standingApproval = this.isAlwaysAllowed(functionName);
|
|
4119
|
-
|
|
4379
|
+
let needsToolApproval = requiresToolApproval({
|
|
4120
4380
|
mode: this.config.autonomyMode || 'C',
|
|
4121
4381
|
tool: functionName,
|
|
4122
4382
|
args,
|
|
4123
4383
|
risk: validation.risk,
|
|
4124
4384
|
heavyDownload: isHeavyAiDownload,
|
|
4385
|
+
reason: validation.reason,
|
|
4125
4386
|
standingApproval
|
|
4126
4387
|
});
|
|
4127
|
-
if (
|
|
4388
|
+
if (enterpriseDecision.effect === 'ask') {
|
|
4389
|
+
needsToolApproval = true;
|
|
4390
|
+
auditLog.log({
|
|
4391
|
+
event: 'enterprise_policy_ask',
|
|
4392
|
+
taskId: this.taskId,
|
|
4393
|
+
tool: functionName,
|
|
4394
|
+
dimension: enterpriseDecision.matchedDimension,
|
|
4395
|
+
rule: enterpriseDecision.matchedRule,
|
|
4396
|
+
reason: enterpriseDecision.reason
|
|
4397
|
+
});
|
|
4398
|
+
}
|
|
4399
|
+
else if (enterpriseDecision.effect === 'allow'
|
|
4400
|
+
&& !isWholeFileDeletion(functionName, args)
|
|
4401
|
+
&& !isHeavyAiDownload) {
|
|
4402
|
+
needsToolApproval = false;
|
|
4403
|
+
auditLog.log({
|
|
4404
|
+
event: 'enterprise_policy_allowed',
|
|
4405
|
+
taskId: this.taskId,
|
|
4406
|
+
tool: functionName,
|
|
4407
|
+
dimension: enterpriseDecision.matchedDimension,
|
|
4408
|
+
rule: enterpriseDecision.matchedRule,
|
|
4409
|
+
reason: enterpriseDecision.reason
|
|
4410
|
+
});
|
|
4411
|
+
}
|
|
4412
|
+
if (standingApproval && !needsToolApproval && this.config.autonomyMode !== 'C' && enterpriseDecision.effect !== 'allow') {
|
|
4128
4413
|
auditLog.log({
|
|
4129
4414
|
event: 'approval_auto_granted', taskId: this.taskId,
|
|
4130
4415
|
tool: functionName, risk: validation.risk, reason: 'allow_always'
|
|
@@ -4266,8 +4551,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4266
4551
|
};
|
|
4267
4552
|
}
|
|
4268
4553
|
this._networkHostGuard.after(functionName, args, result);
|
|
4269
|
-
if (result && result.success !== false && !result.error
|
|
4270
|
-
|
|
4554
|
+
if (result && result.success !== false && !result.error) {
|
|
4555
|
+
if (['fs_write', 'fs_edit', 'MultiEdit'].includes(functionName)) {
|
|
4556
|
+
this.recordWebArtifact(args.path || args.file_path);
|
|
4557
|
+
}
|
|
4558
|
+
else if (functionName === 'apply_patch' && typeof args.patch === 'string') {
|
|
4559
|
+
for (const patchPath of extractPatchTargetPaths(args.patch).paths) {
|
|
4560
|
+
this.recordWebArtifact(patchPath);
|
|
4561
|
+
}
|
|
4562
|
+
}
|
|
4271
4563
|
}
|
|
4272
4564
|
if (result && result.success !== false && !result.error && ['fs_read', 'view_file', 'read_file'].includes(functionName)) {
|
|
4273
4565
|
const filePath = String(args.path || args.file_path || args.AbsolutePath || args.target || '');
|
|
@@ -4301,7 +4593,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4301
4593
|
});
|
|
4302
4594
|
}
|
|
4303
4595
|
}
|
|
4304
|
-
if (result?.success === true && ['fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit'].includes(functionName))
|
|
4596
|
+
if (result?.success === true && ['fs_write', 'fs_edit', 'fs_delete', 'fs_move', 'MultiEdit', 'apply_patch'].includes(functionName))
|
|
4305
4597
|
clearSysRunCache();
|
|
4306
4598
|
// The journal is the observer's own record of what actually ran. It
|
|
4307
4599
|
// is written only after post-hook review, so a formatter that rejects
|
|
@@ -4379,7 +4671,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4379
4671
|
this._lastToolResult = observedResult;
|
|
4380
4672
|
// Active Inference: Record step prediction error into VFE rolling tracker
|
|
4381
4673
|
if (this.vfeTracker) {
|
|
4382
|
-
const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool)
|
|
4674
|
+
const isThrash = isThrashing((this._planSteps || []).map((s) => s.tool));
|
|
4383
4675
|
const vfeOutcome = this.vfeTracker.recordStep({
|
|
4384
4676
|
tool: functionName,
|
|
4385
4677
|
success: stepSuccess,
|
|
@@ -4572,23 +4864,28 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4572
4864
|
}
|
|
4573
4865
|
}
|
|
4574
4866
|
}
|
|
4575
|
-
// Fold identical bytes
|
|
4867
|
+
// Fold identical bytes only when the earlier full observation is still
|
|
4868
|
+
// verbatim in active context (never blindfold a re-read of a decayed result).
|
|
4576
4869
|
const OBSERVATION_FOLD_FLOOR = 600;
|
|
4577
4870
|
if (resultString.length >= OBSERVATION_FOLD_FLOOR) {
|
|
4578
4871
|
const digest = originalFingerprint;
|
|
4579
|
-
const
|
|
4580
|
-
|
|
4872
|
+
const seenRecord = this._observationDigests.get(digest);
|
|
4873
|
+
const earlierStillVerbatim = Boolean(seenRecord && this.messages.some((msg) => msg?.role === 'tool'
|
|
4874
|
+
&& msg?.tool_call_id === seenRecord.toolCallId
|
|
4875
|
+
&& typeof msg.content === 'string'
|
|
4876
|
+
&& !msg.content.startsWith('[decayed]')));
|
|
4877
|
+
if (seenRecord !== undefined && earlierStillVerbatim) {
|
|
4581
4878
|
resultString = JSON.stringify({
|
|
4582
4879
|
...(result && typeof result.success === 'boolean' ? { success: result.success } : {}),
|
|
4583
4880
|
identicalResult: true,
|
|
4584
|
-
output: `The serialized tool response matches step ${
|
|
4881
|
+
output: `The serialized tool response matches step ${seenRecord.step}. This does not prove external state is unchanged. `
|
|
4585
4882
|
+ (spill
|
|
4586
4883
|
? `Full output is saved at ${spill.path}; read a relevant range if needed.`
|
|
4587
|
-
: 'The earlier response
|
|
4884
|
+
: 'The earlier response is still present in active context.')
|
|
4588
4885
|
});
|
|
4589
4886
|
}
|
|
4590
4887
|
else {
|
|
4591
|
-
this._observationDigests.set(digest, this.stepsCompleted + 1);
|
|
4888
|
+
this._observationDigests.set(digest, { step: this.stepsCompleted + 1, toolCallId: toolCall.id });
|
|
4592
4889
|
}
|
|
4593
4890
|
}
|
|
4594
4891
|
const isCallFailed = isToolErrorResult(result);
|
|
@@ -4643,13 +4940,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4643
4940
|
// wall-clock limits, before deciding whether recovery is possible.
|
|
4644
4941
|
if (e?.partialUsage) {
|
|
4645
4942
|
const usage = e.partialUsage;
|
|
4646
|
-
|
|
4647
|
-
|
|
4943
|
+
const promptTokens = Number.isFinite(Number(usage.promptTokens)) ? Math.max(0, Number(usage.promptTokens)) : 0;
|
|
4944
|
+
const completionTokens = Number.isFinite(Number(usage.completionTokens)) ? Math.max(0, Number(usage.completionTokens)) : 0;
|
|
4945
|
+
const cachedPromptTokens = Number.isFinite(Number(usage.cachedPromptTokens)) ? Math.max(0, Number(usage.cachedPromptTokens)) : 0;
|
|
4946
|
+
if (promptTokens + completionTokens > 0) {
|
|
4947
|
+
await this.tokenTracker.trackUsage(promptTokens, completionTokens, (message) => this.emitEvent({ type: 'budget_warning', message }), usage);
|
|
4648
4948
|
auditLog.log({
|
|
4649
4949
|
event: 'model_usage', scope: 'agent_loop_primary', taskId: this.taskId,
|
|
4650
4950
|
step: this.stepsCompleted, provider: this.config.provider || 'unknown',
|
|
4651
|
-
promptTokens
|
|
4652
|
-
cachedPromptTokens
|
|
4951
|
+
promptTokens, completionTokens,
|
|
4952
|
+
cachedPromptTokens,
|
|
4653
4953
|
measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
|
|
4654
4954
|
});
|
|
4655
4955
|
}
|
|
@@ -4714,6 +5014,18 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4714
5014
|
: 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
|
|
4715
5015
|
break;
|
|
4716
5016
|
}
|
|
5017
|
+
if (e?.code === 'ACP_PARTIAL_TURN') {
|
|
5018
|
+
const completed = Number.isSafeInteger(e.completedNativeActions) && e.completedNativeActions >= 0 ? e.completedNativeActions : 0;
|
|
5019
|
+
const unfinished = Number.isSafeInteger(e.unfinishedNativeActions) && e.unfinishedNativeActions >= 0 ? e.unfinishedNativeActions : 0;
|
|
5020
|
+
const partialText = typeof e.partialText === 'string' ? redactProviderSecrets(e.partialText).slice(0, 4000).trim() : '';
|
|
5021
|
+
if (partialText)
|
|
5022
|
+
this.messages.push({ role: 'assistant', content: partialText });
|
|
5023
|
+
this.messages.push({ role: 'system', content: `[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.` });
|
|
5024
|
+
this.memoryManager.saveHistory(this.messages);
|
|
5025
|
+
this.emitEvent({ type: 'error', message: e.message });
|
|
5026
|
+
auditLog.log({ event: 'acp_partial_turn_checkpoint', taskId: this.taskId, completedNativeActions: completed, unfinishedNativeActions: unfinished, outcome: 'unverified' });
|
|
5027
|
+
break;
|
|
5028
|
+
}
|
|
4717
5029
|
if (e?.code === 'PROVIDER_EMPTY_RESPONSE'
|
|
4718
5030
|
|| (typeof e?.message === 'string' && e.message.includes('returned no response'))) {
|
|
4719
5031
|
if (emptyResponseRecoveries++ < 5) {
|
|
@@ -4764,13 +5076,31 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4764
5076
|
// "Thinking" and the only signal was `network_error: fetch failed`
|
|
4765
5077
|
// repeated in red. From the outside it is indistinguishable from
|
|
4766
5078
|
// working, and it burns the user's step budget doing nothing.
|
|
4767
|
-
|
|
4768
|
-
this.consecutiveFailures
|
|
5079
|
+
// Changing error classes is not successful progress.
|
|
5080
|
+
this.consecutiveFailures++;
|
|
4769
5081
|
this.lastFailureType = errorType;
|
|
5082
|
+
const isContextOverflow = errorType === 'context_overflow';
|
|
5083
|
+
if (isContextOverflow) {
|
|
5084
|
+
const compactRes = compactSessionMessages(this.messages, {
|
|
5085
|
+
keepRecentTurns: Math.max(2, 6 - this.consecutiveFailures * 2),
|
|
5086
|
+
taskId: this.taskId,
|
|
5087
|
+
originalPrompt: this.currentTaskPrompt || this.userPrompt
|
|
5088
|
+
});
|
|
5089
|
+
if (compactRes.compacted) {
|
|
5090
|
+
this.notice(`Context limit exceeded — auto-compacted ${compactRes.removedCount} earlier messages (~${compactRes.reclaimedTokens} tokens reclaimed) and retrying.`);
|
|
5091
|
+
}
|
|
5092
|
+
}
|
|
4770
5093
|
const isNetwork = errorType === NETWORK_ERROR_TYPE;
|
|
5094
|
+
const isRateLimit = errorType === 'rate_limit';
|
|
5095
|
+
const maxAttempts = isRateLimit ? 5 : AgentLoop.MAX_CONSECUTIVE_FAILURES;
|
|
4771
5096
|
const detail = isNetwork ? explainNetworkError(e, this.config) : e.message;
|
|
4772
5097
|
auditLog.log({ event: 'loop_error_recovered', taskId: this.taskId, error: e.message, errorType });
|
|
4773
|
-
|
|
5098
|
+
const exceededCeiling = isRateLimit
|
|
5099
|
+
? this.consecutiveFailures >= maxAttempts
|
|
5100
|
+
: this.consecutiveFailures >= AgentLoop.MAX_CONSECUTIVE_FAILURES;
|
|
5101
|
+
if (exceededCeiling) {
|
|
5102
|
+
if (await this.tryZeroCostFailover(isNetwork, isRateLimit, errorType))
|
|
5103
|
+
continue;
|
|
4774
5104
|
// Nothing is changing between attempts. Stop and say why, rather
|
|
4775
5105
|
// than spinning until the budget is gone.
|
|
4776
5106
|
this.emitEvent({
|
|
@@ -4784,21 +5114,24 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4784
5114
|
type: 'step_error',
|
|
4785
5115
|
tool: 'agent_loop',
|
|
4786
5116
|
error: `${detail}\n retrying (${this.consecutiveFailures} of `
|
|
4787
|
-
+ `${
|
|
5117
|
+
+ `${maxAttempts})`
|
|
4788
5118
|
});
|
|
4789
|
-
// Back off before trying again.
|
|
4790
|
-
//
|
|
4791
|
-
|
|
4792
|
-
|
|
5119
|
+
// Back off before trying again. Honor provider Retry-After / X-RateLimit-Reset
|
|
5120
|
+
// when present so free-tier 429 limits recover cleanly without hammering.
|
|
5121
|
+
const retryAfterMs = typeof e?.retryAfterMs === 'number' && Number.isFinite(e.retryAfterMs)
|
|
5122
|
+
? e.retryAfterMs
|
|
5123
|
+
: undefined;
|
|
5124
|
+
await this.backoff(this.consecutiveFailures, retryAfterMs);
|
|
4793
5125
|
// Only tell the MODEL about errors the model can act on. It cannot
|
|
4794
|
-
// fix DNS
|
|
4795
|
-
// context — and the bill — for nothing.
|
|
5126
|
+
// fix DNS, firewalls, HTTP 429 rate limits, or context overflow (already compacted).
|
|
4796
5127
|
if (!isNetwork) {
|
|
4797
|
-
|
|
4798
|
-
|
|
4799
|
-
|
|
4800
|
-
|
|
4801
|
-
|
|
5128
|
+
if (!isRateLimit && !isContextOverflow) {
|
|
5129
|
+
this.messages.push({
|
|
5130
|
+
role: 'system',
|
|
5131
|
+
content: `[SYSTEM ERROR RECOVERED: A ${errorType} error occurred: "${e.message}". `
|
|
5132
|
+
+ 'The loop has recovered. You may continue or try a different approach.]'
|
|
5133
|
+
});
|
|
5134
|
+
}
|
|
4802
5135
|
}
|
|
4803
5136
|
}
|
|
4804
5137
|
}
|
|
@@ -4809,7 +5142,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4809
5142
|
}
|
|
4810
5143
|
async waitForApproval(toolCallId) {
|
|
4811
5144
|
const signal = this.abortController?.signal;
|
|
4812
|
-
if (this.stopRequested || signal?.aborted)
|
|
5145
|
+
if (this.stopRequested || signal?.aborted || typeof toolCallId !== 'string' || !toolCallId.trim() || this.pendingApprovals.has(toolCallId))
|
|
4813
5146
|
return false;
|
|
4814
5147
|
this._entitlementGate?.pause();
|
|
4815
5148
|
try {
|
|
@@ -4843,8 +5176,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4843
5176
|
* Exponential, capped. Without the abort check a user pressing esc during a
|
|
4844
5177
|
* backoff would wait out the full delay before anything responded.
|
|
4845
5178
|
*/
|
|
4846
|
-
async backoff(attempt) {
|
|
4847
|
-
|
|
5179
|
+
async backoff(attempt, retryAfterMs) {
|
|
5180
|
+
let delay;
|
|
5181
|
+
if (typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
|
|
5182
|
+
const jitter = Math.min(250, Math.floor(retryAfterMs * 0.1));
|
|
5183
|
+
delay = Math.min(60_000, Math.max(50, Math.round(retryAfterMs) + jitter));
|
|
5184
|
+
}
|
|
5185
|
+
else {
|
|
5186
|
+
delay = Math.min(8000, 500 * Math.pow(2, Math.max(0, attempt - 1)));
|
|
5187
|
+
}
|
|
4848
5188
|
await waitForAbortableDelay(delay, this.abortController?.signal);
|
|
4849
5189
|
}
|
|
4850
5190
|
// V5: Classify errors for intelligent retry decisions
|
|
@@ -4881,4 +5221,51 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4881
5221
|
validateToolArgs(toolName, args) {
|
|
4882
5222
|
return validateAndNormalizeToolArgs(toolName, args, this.workspaceRoot || process.cwd());
|
|
4883
5223
|
}
|
|
5224
|
+
async tryZeroCostFailover(isNetwork, isRateLimit, errorType) {
|
|
5225
|
+
const canAttemptZeroCostFailover = (isRateLimit || isNetwork)
|
|
5226
|
+
&& isZeroCostFailoverEligible(this.config?.provider, this.config?.model)
|
|
5227
|
+
&& (this.config?.zeroCostFailover === true || (this._factoryLlmRef != null && this._factoryLlmRef === this.llm));
|
|
5228
|
+
if (!canAttemptZeroCostFailover)
|
|
5229
|
+
return false;
|
|
5230
|
+
const triedSet = (this._zeroCostTriedProviders ||= new Set());
|
|
5231
|
+
triedSet.add(normalizeZeroCostId(this.config?.provider));
|
|
5232
|
+
const nextRoute = await selectNextZeroCostRoute({
|
|
5233
|
+
currentProvider: String(this.config?.provider || ''),
|
|
5234
|
+
currentModel: String(this.config?.model || ''),
|
|
5235
|
+
triedProviders: triedSet,
|
|
5236
|
+
config: this.config,
|
|
5237
|
+
reason: isNetwork ? 'network_error' : 'rate_limit',
|
|
5238
|
+
...(Array.isArray(this.zeroCostFailoverCandidates)
|
|
5239
|
+
? { candidates: this.zeroCostFailoverCandidates }
|
|
5240
|
+
: {})
|
|
5241
|
+
});
|
|
5242
|
+
if (!nextRoute)
|
|
5243
|
+
return false;
|
|
5244
|
+
const prevProvider = String(this.config?.provider || '');
|
|
5245
|
+
triedSet.add(normalizeZeroCostId(nextRoute.provider));
|
|
5246
|
+
this.config = {
|
|
5247
|
+
...this.config,
|
|
5248
|
+
provider: nextRoute.provider,
|
|
5249
|
+
model: nextRoute.model,
|
|
5250
|
+
apiKey: nextRoute.apiKey
|
|
5251
|
+
};
|
|
5252
|
+
delete this.config.baseUrl;
|
|
5253
|
+
this.llm = this.initializeProvider();
|
|
5254
|
+
this._utilityLlm = null;
|
|
5255
|
+
this.consecutiveFailures = 0;
|
|
5256
|
+
this.lastFailureType = null;
|
|
5257
|
+
auditLog.log({
|
|
5258
|
+
event: 'zero_cost_failover',
|
|
5259
|
+
taskId: this.taskId,
|
|
5260
|
+
fromProvider: prevProvider,
|
|
5261
|
+
toProvider: nextRoute.provider,
|
|
5262
|
+
toModel: nextRoute.model,
|
|
5263
|
+
costTier: nextRoute.costTier,
|
|
5264
|
+
reason: errorType
|
|
5265
|
+
});
|
|
5266
|
+
this.notice(`Zero-cost failover ($0): switched from ${prevProvider} to ${nextRoute.provider}`
|
|
5267
|
+
+ (nextRoute.model ? ` (${nextRoute.model})` : '')
|
|
5268
|
+
+ ` after ${errorType}.`);
|
|
5269
|
+
return true;
|
|
5270
|
+
}
|
|
4884
5271
|
}
|