@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
|
@@ -0,0 +1,2622 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Local Skybridge Server (`causyne web`)
|
|
3
|
+
*
|
|
4
|
+
* Foreground, user-initiated, loopback-only (`127.0.0.1`) HTTP + NDJSON bridge
|
|
5
|
+
* connecting a local browser tab (or verified `https://causyne.com` origin) to
|
|
6
|
+
* the user's selected local workspace folder and full Causyne Agent runtime.
|
|
7
|
+
*
|
|
8
|
+
* Security invariants:
|
|
9
|
+
* 1. Binds strictly to `127.0.0.1` — never `0.0.0.0` or LAN interfaces.
|
|
10
|
+
* 2. Strict `Host` header validation (`127.0.0.1:<port>` / `localhost:<port>`)
|
|
11
|
+
* blocks DNS Rebinding attacks.
|
|
12
|
+
* 3. Strict `Origin` allowlist (`http://127.0.0.1:<port>`, `http://localhost:<port>`,
|
|
13
|
+
* `https://causyne.com`, `https://www.causyne.com`) + Chrome Private Network
|
|
14
|
+
* Access (PNA) preflight headers block CSRF & cross-site hijacking.
|
|
15
|
+
* 4. 256-bit cryptographic session nonce verified with `crypto.timingSafeEqual`
|
|
16
|
+
* on every `/api/*` endpoint via `Authorization: Bearer <token>`.
|
|
17
|
+
* 5. Every file read/list/write is strictly locked inside `workspaceRoot` via
|
|
18
|
+
* `isPhysicalPathAllowed()` + `atomicWriteFileSync()` + audit logging.
|
|
19
|
+
* 6. Zero persistent daemon, zero `postinstall`, zero outbound reverse tunnel.
|
|
20
|
+
*/
|
|
21
|
+
import http from 'node:http';
|
|
22
|
+
import crypto from 'node:crypto';
|
|
23
|
+
import fs from 'node:fs';
|
|
24
|
+
import path from 'node:path';
|
|
25
|
+
import { execFileSync } from 'node:child_process';
|
|
26
|
+
import { AgentLoop } from '../agentLoop.js';
|
|
27
|
+
import { createApprovalScope } from '../approvalGrants.js';
|
|
28
|
+
import { isPhysicalPathAllowed, physicalPath } from '../agent/workspaceBoundary.js';
|
|
29
|
+
import { atomicWriteFileSync } from '../infra/atomicWriter.js';
|
|
30
|
+
import { applyProviderOverrides, loadConfig, resolveProviderApiKey, saveConfig } from '../config.js';
|
|
31
|
+
import { detectZeroCostProviders } from '../zeroCostRouting.js';
|
|
32
|
+
import { DEFAULT_MODEL_BY_PROVIDER, MODEL_CATALOGUE } from '../modelCatalogue.js';
|
|
33
|
+
import { getAvailableProvidersOverview, resolveAvailableProvidersOverview } from '../dynamicCatalogue.js';
|
|
34
|
+
import { buildModelPickerItems } from '../tui/modelPicker.js';
|
|
35
|
+
import { disconnectOpenRouter } from '../auth/openrouterAuth.js';
|
|
36
|
+
import { createSession, deleteSession, getSession, listSessions, renameSession, saveSessionMessages } from '../sessionJournal.js';
|
|
37
|
+
import { collectWorkingTreeDiff, parseUnifiedDiff } from '../diffReview.js';
|
|
38
|
+
import { auditLog } from '../auditLog.js';
|
|
39
|
+
import { getPackageVersion } from '../version.js';
|
|
40
|
+
import { formatRedactedProviderErrorReport, redactProviderSecrets } from '../providers/byokHttp.js';
|
|
41
|
+
import { isIgnoredByCausyneIgnore } from '../ignoreRules.js';
|
|
42
|
+
import { listCommands, parseCommand, runCommand } from '../commands.js';
|
|
43
|
+
import { formatByokProbeReport, runZeroSpendByokProbe } from '../verification/byokSmokeProbe.js';
|
|
44
|
+
import { listGroups } from '../checkpoints.js';
|
|
45
|
+
import { listCompiledSkills } from '../skillsManager.js';
|
|
46
|
+
import { serverStatus, closeAll as closeAllMcpServers } from '../mcp/mcpRegistry.js';
|
|
47
|
+
import { lspSessionManager } from '../lsp/lspClient.js';
|
|
48
|
+
import { listAllPeers } from '../acp/peerProfiles.js';
|
|
49
|
+
import { listWorktrees } from '../worktreeManager.js';
|
|
50
|
+
import { backgroundTaskManager } from '../backgroundTasks.js';
|
|
51
|
+
import { causyneBrowser, expandSearchMacro } from '../browser/causyneBrowser.js';
|
|
52
|
+
import { discoverLocalCdpTabs, importExplicitUserBrowserData, syncLocalCdpTabToCausyne } from './skybridgeBrowserBridge.js';
|
|
53
|
+
import { CAUSYNE_BROWSER_MCP_NAME, handleBrowserMcpRpc } from './skybridgeBrowserMcp.js';
|
|
54
|
+
import { DAILY_LIMIT_SUPPORT_MESSAGE, EntitlementAccessError, EntitlementClient } from '../licensing/entitlements.js';
|
|
55
|
+
import { LICENSE_ENFORCEMENT_ENABLED, isValidLicensePlan } from '../licensing/policy.js';
|
|
56
|
+
import { renderSkybridgeHtml, getCausyneFaviconSvg } from './skybridgeUi.js';
|
|
57
|
+
const MAX_JSON_BODY_BYTES = 1024 * 1024;
|
|
58
|
+
const MAX_FILE_READ_BYTES = 512 * 1024;
|
|
59
|
+
const MAX_FILE_WRITE_BYTES = 2 * 1024 * 1024;
|
|
60
|
+
const MAX_ATTACHMENT_BYTES = 32 * 1024;
|
|
61
|
+
const MAX_ATTACHMENTS = 6;
|
|
62
|
+
const MAX_LIST_ENTRIES = 250;
|
|
63
|
+
const SKIPPED_DIRS = new Set(['.git', 'node_modules', '.next', 'dist', 'build', '.venv']);
|
|
64
|
+
const ALLOWED_REMOTE_ORIGINS = new Set(['https://causyne.com', 'https://www.causyne.com']);
|
|
65
|
+
const SAFE_SESSION_ID_RE = /^s_[a-zA-Z0-9_-]{3,80}$/;
|
|
66
|
+
const SAFE_PROVIDER_RE = /^[a-zA-Z0-9._/-]{1,64}$/;
|
|
67
|
+
const SAFE_MODEL_RE = /^[a-zA-Z0-9._/:()+ -]{1,128}$/;
|
|
68
|
+
const PROVIDER_KEY_FOR_CATALOG_LABEL = {
|
|
69
|
+
'DeepSeek': 'deepseek',
|
|
70
|
+
'Qwen': 'qwen',
|
|
71
|
+
'Anthropic': 'anthropic',
|
|
72
|
+
'OpenAI': 'openai',
|
|
73
|
+
'Gemini': 'gemini',
|
|
74
|
+
'Meta (Muse)': 'muse',
|
|
75
|
+
'Ollama (Local)': 'ollama',
|
|
76
|
+
'Alibaba (DashScope)': 'dashscope-byok',
|
|
77
|
+
'Moonshot (Kimi)': 'moonshot',
|
|
78
|
+
'xAI (Grok)': 'xai',
|
|
79
|
+
'Google Antigravity': 'antigravity',
|
|
80
|
+
'Pi (Local Peer)': 'pi',
|
|
81
|
+
'ACP (Peer Agents)': 'acp',
|
|
82
|
+
'OpenCode (ACP)': 'acp/opencode',
|
|
83
|
+
'Claude Code (ACP)': 'acp/claude',
|
|
84
|
+
'OpenRouter (Free)': 'openrouter',
|
|
85
|
+
'Groq (Free Tier)': 'groq',
|
|
86
|
+
'Cerebras (Free Tier)': 'cerebras',
|
|
87
|
+
'Mistral (Free Tier)': 'mistral'
|
|
88
|
+
};
|
|
89
|
+
export function isAllowedSkybridgeHost(hostHeader, port) {
|
|
90
|
+
if (!hostHeader || typeof hostHeader !== 'string')
|
|
91
|
+
return false;
|
|
92
|
+
const normalized = hostHeader.trim().toLowerCase();
|
|
93
|
+
return normalized === `127.0.0.1:${port}`
|
|
94
|
+
|| normalized === `localhost:${port}`
|
|
95
|
+
|| normalized === `[::1]:${port}`;
|
|
96
|
+
}
|
|
97
|
+
export function isAllowedSkybridgeOrigin(originHeader, port, extraOrigins = []) {
|
|
98
|
+
if (!originHeader || typeof originHeader !== 'string')
|
|
99
|
+
return true;
|
|
100
|
+
const trimmed = originHeader.trim();
|
|
101
|
+
if (!trimmed || trimmed === 'null')
|
|
102
|
+
return false;
|
|
103
|
+
let parsed;
|
|
104
|
+
try {
|
|
105
|
+
parsed = new URL(trimmed);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
const canonical = parsed.origin.toLowerCase();
|
|
111
|
+
if (canonical === `http://127.0.0.1:${port}` || canonical === `http://localhost:${port}`) {
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
if (ALLOWED_REMOTE_ORIGINS.has(canonical))
|
|
115
|
+
return true;
|
|
116
|
+
for (const extra of extraOrigins) {
|
|
117
|
+
try {
|
|
118
|
+
const parsedExtra = new URL(extra);
|
|
119
|
+
if (parsedExtra.protocol === 'https:' && parsedExtra.origin.toLowerCase() === canonical) {
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
// ignore invalid extra origin
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
function timingSafeBearerMatch(authHeader, expectedToken) {
|
|
130
|
+
if (!authHeader || typeof authHeader !== 'string')
|
|
131
|
+
return false;
|
|
132
|
+
const prefix = 'Bearer ';
|
|
133
|
+
if (!authHeader.startsWith(prefix))
|
|
134
|
+
return false;
|
|
135
|
+
const supplied = authHeader.slice(prefix.length).trim();
|
|
136
|
+
const a = Buffer.from(supplied, 'utf8');
|
|
137
|
+
const b = Buffer.from(expectedToken, 'utf8');
|
|
138
|
+
if (a.length !== b.length || a.length === 0)
|
|
139
|
+
return false;
|
|
140
|
+
return crypto.timingSafeEqual(a, b);
|
|
141
|
+
}
|
|
142
|
+
function applySecurityHeaders(res, originHeader, originAllowed) {
|
|
143
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
144
|
+
res.setHeader('X-Frame-Options', 'DENY');
|
|
145
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
146
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
147
|
+
if (originHeader && originAllowed) {
|
|
148
|
+
res.setHeader('Access-Control-Allow-Origin', originHeader);
|
|
149
|
+
res.setHeader('Access-Control-Allow-Private-Network', 'true');
|
|
150
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS');
|
|
151
|
+
res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');
|
|
152
|
+
res.setHeader('Vary', 'Origin, Access-Control-Request-Private-Network');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function sendJson(res, status, payload) {
|
|
156
|
+
const body = JSON.stringify(payload);
|
|
157
|
+
res.statusCode = status;
|
|
158
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
159
|
+
res.end(body);
|
|
160
|
+
}
|
|
161
|
+
async function readJsonBody(req, maxBytes = MAX_JSON_BODY_BYTES) {
|
|
162
|
+
const chunks = [];
|
|
163
|
+
let total = 0;
|
|
164
|
+
for await (const chunk of req) {
|
|
165
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
166
|
+
total += buf.length;
|
|
167
|
+
if (total > maxBytes) {
|
|
168
|
+
throw new Error('Request body exceeded maximum allowed size.');
|
|
169
|
+
}
|
|
170
|
+
chunks.push(buf);
|
|
171
|
+
}
|
|
172
|
+
const text = Buffer.concat(chunks).toString('utf8').trim();
|
|
173
|
+
if (!text)
|
|
174
|
+
return {};
|
|
175
|
+
const parsed = JSON.parse(text);
|
|
176
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
177
|
+
throw new Error('JSON request body must be an object.');
|
|
178
|
+
}
|
|
179
|
+
return parsed;
|
|
180
|
+
}
|
|
181
|
+
function resolveWorkspaceRelativePath(workspaceRoot, rawRel) {
|
|
182
|
+
if (typeof rawRel !== 'string' || rawRel.includes('\0'))
|
|
183
|
+
return null;
|
|
184
|
+
const cleaned = rawRel.trim();
|
|
185
|
+
if (!cleaned)
|
|
186
|
+
return null;
|
|
187
|
+
if (path.isAbsolute(cleaned))
|
|
188
|
+
return null;
|
|
189
|
+
const candidate = path.resolve(workspaceRoot, cleaned);
|
|
190
|
+
if (!isPhysicalPathAllowed(candidate, [workspaceRoot], false))
|
|
191
|
+
return null;
|
|
192
|
+
return candidate;
|
|
193
|
+
}
|
|
194
|
+
function listWorkspaceEntries(workspaceRoot, relDir, query = '') {
|
|
195
|
+
const targetDir = relDir ? resolveWorkspaceRelativePath(workspaceRoot, relDir) : workspaceRoot;
|
|
196
|
+
if (!targetDir)
|
|
197
|
+
throw new Error('Requested directory is outside the locked workspace.');
|
|
198
|
+
const q = query.trim().toLowerCase();
|
|
199
|
+
const entries = [];
|
|
200
|
+
const scan = (dir, depth) => {
|
|
201
|
+
if (entries.length >= MAX_LIST_ENTRIES)
|
|
202
|
+
return;
|
|
203
|
+
let dirents;
|
|
204
|
+
try {
|
|
205
|
+
dirents = fs.readdirSync(dir, { withFileTypes: true });
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
for (const d of dirents) {
|
|
211
|
+
if (entries.length >= MAX_LIST_ENTRIES)
|
|
212
|
+
break;
|
|
213
|
+
if (d.isSymbolicLink())
|
|
214
|
+
continue;
|
|
215
|
+
if (d.isDirectory() && SKIPPED_DIRS.has(d.name))
|
|
216
|
+
continue;
|
|
217
|
+
const abs = path.join(dir, d.name);
|
|
218
|
+
if (!isPhysicalPathAllowed(abs, [workspaceRoot], false))
|
|
219
|
+
continue;
|
|
220
|
+
if (isIgnoredByCausyneIgnore(abs, workspaceRoot, d.isDirectory()))
|
|
221
|
+
continue;
|
|
222
|
+
const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');
|
|
223
|
+
const isDir = d.isDirectory();
|
|
224
|
+
let size = 0;
|
|
225
|
+
if (!isDir) {
|
|
226
|
+
try {
|
|
227
|
+
size = fs.statSync(abs).size;
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
size = 0;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (!q || rel.toLowerCase().includes(q)) {
|
|
234
|
+
entries.push({ path: rel, name: d.name, type: isDir ? 'dir' : 'file', size });
|
|
235
|
+
}
|
|
236
|
+
if (q && isDir && depth < 3) {
|
|
237
|
+
scan(abs, depth + 1);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
scan(targetDir, 0);
|
|
242
|
+
entries.sort((a, b) => (a.type === b.type ? a.path.localeCompare(b.path) : a.type === 'dir' ? -1 : 1));
|
|
243
|
+
return entries;
|
|
244
|
+
}
|
|
245
|
+
const MUTATING_FILE_TOOLS = new Set([
|
|
246
|
+
'fs_write', 'fs_edit', 'multi_edit', 'apply_patch', 'fs_delete', 'fs_move',
|
|
247
|
+
'write_file', 'edit_file', 'write', 'edit', 'multiedit', 'replace_file_content',
|
|
248
|
+
'multi_replace_file_content', 'write_to_file', 'create_file', 'document_forge',
|
|
249
|
+
'ui_forge', 'screenshot', 'generate_media_via_api', 'code_verify_syntax'
|
|
250
|
+
]);
|
|
251
|
+
const SHELL_TOOLS = new Set(['sysrun', 'bash', 'shell', 'run_command', 'execute_command']);
|
|
252
|
+
function formatByteSize(bytes) {
|
|
253
|
+
if (!Number.isFinite(bytes) || bytes < 0)
|
|
254
|
+
return '0 B';
|
|
255
|
+
if (bytes < 1024)
|
|
256
|
+
return `${Math.round(bytes)} B`;
|
|
257
|
+
if (bytes < 1024 * 1024)
|
|
258
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
259
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
260
|
+
}
|
|
261
|
+
function normalizeWorkspaceRelCandidate(workspaceRoot, raw, baseDir) {
|
|
262
|
+
if (typeof raw !== 'string')
|
|
263
|
+
return null;
|
|
264
|
+
let trimmed = raw.trim().replace(/^["'`]+|["'`]+$/g, '');
|
|
265
|
+
if (!trimmed || trimmed.includes('\0') || trimmed.length > 500)
|
|
266
|
+
return null;
|
|
267
|
+
if (/^https?:\/\//i.test(trimmed))
|
|
268
|
+
return null;
|
|
269
|
+
if (trimmed.toLowerCase().startsWith('file://')) {
|
|
270
|
+
trimmed = trimmed.slice('file://'.length);
|
|
271
|
+
const hashIdx = trimmed.indexOf('#');
|
|
272
|
+
if (hashIdx >= 0)
|
|
273
|
+
trimmed = trimmed.slice(0, hashIdx);
|
|
274
|
+
const queryIdx = trimmed.indexOf('?');
|
|
275
|
+
if (queryIdx >= 0)
|
|
276
|
+
trimmed = trimmed.slice(0, queryIdx);
|
|
277
|
+
try {
|
|
278
|
+
trimmed = decodeURIComponent(trimmed);
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
// Keep raw decoded string if percent encoding is malformed.
|
|
282
|
+
}
|
|
283
|
+
if (/^\/[A-Za-z]:[\\/]/.test(trimmed)) {
|
|
284
|
+
trimmed = trimmed.slice(1);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
const lineAnchor = trimmed.match(/^(.+?\.[a-zA-Z0-9]{1,8})#L\d+(?:-L?\d+)?$/);
|
|
289
|
+
if (lineAnchor?.[1])
|
|
290
|
+
trimmed = lineAnchor[1];
|
|
291
|
+
}
|
|
292
|
+
const escNl = trimmed.indexOf('\\n');
|
|
293
|
+
if (escNl >= 0)
|
|
294
|
+
trimmed = trimmed.slice(0, escNl);
|
|
295
|
+
trimmed = trimmed.replace(/[),.;:]+$/g, '').trim();
|
|
296
|
+
if (!trimmed || trimmed === '.' || trimmed === '/')
|
|
297
|
+
return null;
|
|
298
|
+
let rel = trimmed;
|
|
299
|
+
if (path.isAbsolute(trimmed)) {
|
|
300
|
+
const absNorm = path.resolve(trimmed);
|
|
301
|
+
if (!isPhysicalPathAllowed(absNorm, [workspaceRoot], false))
|
|
302
|
+
return null;
|
|
303
|
+
rel = path.relative(workspaceRoot, absNorm);
|
|
304
|
+
}
|
|
305
|
+
else if (baseDir && path.isAbsolute(baseDir)) {
|
|
306
|
+
const absNorm = path.resolve(baseDir, trimmed);
|
|
307
|
+
if (!isPhysicalPathAllowed(absNorm, [workspaceRoot], false))
|
|
308
|
+
return null;
|
|
309
|
+
rel = path.relative(workspaceRoot, absNorm);
|
|
310
|
+
}
|
|
311
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
|
|
312
|
+
if (!abs)
|
|
313
|
+
return null;
|
|
314
|
+
const normalized = path.relative(workspaceRoot, abs).split(path.sep).join('/');
|
|
315
|
+
return normalized && !normalized.startsWith('..') ? normalized : null;
|
|
316
|
+
}
|
|
317
|
+
function tokenizeSimpleShell(command) {
|
|
318
|
+
const tokens = [];
|
|
319
|
+
let current = '';
|
|
320
|
+
let quote = null;
|
|
321
|
+
for (let i = 0; i < command.length; i += 1) {
|
|
322
|
+
const ch = command[i];
|
|
323
|
+
if (quote) {
|
|
324
|
+
if (ch === quote) {
|
|
325
|
+
quote = null;
|
|
326
|
+
}
|
|
327
|
+
else {
|
|
328
|
+
current += ch;
|
|
329
|
+
}
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
if (ch === '"' || ch === "'") {
|
|
333
|
+
quote = ch;
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
|
|
337
|
+
if (current) {
|
|
338
|
+
tokens.push(current);
|
|
339
|
+
current = '';
|
|
340
|
+
}
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (ch === ';' || ch === '|') {
|
|
344
|
+
if (current) {
|
|
345
|
+
tokens.push(current);
|
|
346
|
+
current = '';
|
|
347
|
+
}
|
|
348
|
+
tokens.push(ch);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
if (ch === '&' && command[i + 1] === '&') {
|
|
352
|
+
if (current) {
|
|
353
|
+
tokens.push(current);
|
|
354
|
+
current = '';
|
|
355
|
+
}
|
|
356
|
+
tokens.push('&&');
|
|
357
|
+
i += 1;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
current += ch;
|
|
361
|
+
}
|
|
362
|
+
if (current)
|
|
363
|
+
tokens.push(current);
|
|
364
|
+
return tokens;
|
|
365
|
+
}
|
|
366
|
+
function extractShellWriteTargets(command, workspaceRoot, cwdArg) {
|
|
367
|
+
const found = [];
|
|
368
|
+
let curDir = workspaceRoot;
|
|
369
|
+
if (typeof cwdArg === 'string' && cwdArg.trim()) {
|
|
370
|
+
const resolvedCwd = path.isAbsolute(cwdArg.trim())
|
|
371
|
+
? path.resolve(cwdArg.trim())
|
|
372
|
+
: path.resolve(workspaceRoot, cwdArg.trim());
|
|
373
|
+
if (isPhysicalPathAllowed(resolvedCwd, [workspaceRoot], false)) {
|
|
374
|
+
curDir = resolvedCwd;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
const tokens = tokenizeSimpleShell(command);
|
|
378
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
379
|
+
const tok = tokens[i];
|
|
380
|
+
if (tok === 'cd' && tokens[i + 1]) {
|
|
381
|
+
const nextDir = tokens[i + 1];
|
|
382
|
+
const resolved = path.isAbsolute(nextDir)
|
|
383
|
+
? path.resolve(nextDir)
|
|
384
|
+
: path.resolve(curDir, nextDir);
|
|
385
|
+
if (isPhysicalPathAllowed(resolved, [workspaceRoot], false)) {
|
|
386
|
+
curDir = resolved;
|
|
387
|
+
}
|
|
388
|
+
i += 1;
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
if ((tok === '-o' || tok === '--output' || tok === '>' || tok === '>>' || tok === 'tee') && tokens[i + 1]) {
|
|
392
|
+
const target = tokens[i + 1];
|
|
393
|
+
if (target !== '/dev/null' && !target.startsWith('-')) {
|
|
394
|
+
const norm = normalizeWorkspaceRelCandidate(workspaceRoot, target, curDir);
|
|
395
|
+
if (norm)
|
|
396
|
+
found.push(norm);
|
|
397
|
+
}
|
|
398
|
+
i += 1;
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
if (tok === 'screencapture') {
|
|
402
|
+
let j = i + 1;
|
|
403
|
+
while (j < tokens.length && tokens[j] !== ';' && tokens[j] !== '&&' && tokens[j] !== '|') {
|
|
404
|
+
const arg = tokens[j];
|
|
405
|
+
if (!arg.startsWith('-')) {
|
|
406
|
+
const norm = normalizeWorkspaceRelCandidate(workspaceRoot, arg, curDir);
|
|
407
|
+
if (norm)
|
|
408
|
+
found.push(norm);
|
|
409
|
+
}
|
|
410
|
+
j += 1;
|
|
411
|
+
}
|
|
412
|
+
i = j - 1;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return found;
|
|
416
|
+
}
|
|
417
|
+
function extractPatchPathsFromText(patchText) {
|
|
418
|
+
const found = [];
|
|
419
|
+
for (const line of patchText.split(/\r?\n/)) {
|
|
420
|
+
const m = line.match(/^\*\*\*\s+(?:Add|Update|Delete)\s+File:\s+(.+)$/);
|
|
421
|
+
if (m?.[1])
|
|
422
|
+
found.push(m[1].trim());
|
|
423
|
+
const diffM = line.match(/^(?:\+\+\+|---)\s+[ab]\/(.+)$/);
|
|
424
|
+
if (diffM?.[1])
|
|
425
|
+
found.push(diffM[1].trim());
|
|
426
|
+
}
|
|
427
|
+
return found;
|
|
428
|
+
}
|
|
429
|
+
function buildSynthesizedWriteHunk(content) {
|
|
430
|
+
const lines = content.split(/\r?\n/);
|
|
431
|
+
if (lines.length > 0 && lines[lines.length - 1] === '')
|
|
432
|
+
lines.pop();
|
|
433
|
+
const capped = lines.slice(0, 140).map((ln) => `+${ln}`);
|
|
434
|
+
if (lines.length > 140)
|
|
435
|
+
capped.push(`+... (${lines.length - 140} more lines)`);
|
|
436
|
+
return {
|
|
437
|
+
additions: lines.length,
|
|
438
|
+
hunks: capped.length > 0
|
|
439
|
+
? [{ header: `@@ -0,0 +1,${lines.length} @@`, lines: capped }]
|
|
440
|
+
: []
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
function buildSynthesizedEditHunk(oldStr, newStr) {
|
|
444
|
+
const oldLines = oldStr ? oldStr.split(/\r?\n/) : [];
|
|
445
|
+
const newLines = newStr ? newStr.split(/\r?\n/) : [];
|
|
446
|
+
const diffLines = [];
|
|
447
|
+
for (const ln of oldLines.slice(0, 80))
|
|
448
|
+
diffLines.push(`-${ln}`);
|
|
449
|
+
for (const ln of newLines.slice(0, 80))
|
|
450
|
+
diffLines.push(`+${ln}`);
|
|
451
|
+
return {
|
|
452
|
+
additions: newLines.length,
|
|
453
|
+
deletions: oldLines.length,
|
|
454
|
+
hunks: diffLines.length > 0
|
|
455
|
+
? [{ header: `@@ -1,${oldLines.length} +1,${newLines.length} @@`, lines: diffLines }]
|
|
456
|
+
: []
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
function hasFileExtension(relPath) {
|
|
460
|
+
const base = path.posix.basename(relPath);
|
|
461
|
+
const dot = base.lastIndexOf('.');
|
|
462
|
+
return dot > 0 && dot < base.length - 1 && base.length - dot <= 10;
|
|
463
|
+
}
|
|
464
|
+
export function extractSessionFileEvidence(messages, workspaceRoot) {
|
|
465
|
+
const evidenceMap = new Map();
|
|
466
|
+
const touchedDirs = new Set();
|
|
467
|
+
const recordFile = (raw, opts = {}) => {
|
|
468
|
+
const norm = normalizeWorkspaceRelCandidate(workspaceRoot, raw, opts.baseDir);
|
|
469
|
+
if (!norm)
|
|
470
|
+
return;
|
|
471
|
+
const dir = path.posix.dirname(norm);
|
|
472
|
+
if (dir && dir !== '.')
|
|
473
|
+
touchedDirs.add(dir);
|
|
474
|
+
const existing = evidenceMap.get(norm);
|
|
475
|
+
if (!existing) {
|
|
476
|
+
evidenceMap.set(norm, {
|
|
477
|
+
path: norm,
|
|
478
|
+
status: opts.status ?? 'added',
|
|
479
|
+
bytesWritten: opts.bytesWritten,
|
|
480
|
+
additions: opts.additions ?? 0,
|
|
481
|
+
deletions: opts.deletions ?? 0,
|
|
482
|
+
hunks: opts.hunks ?? []
|
|
483
|
+
});
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
if (opts.status === 'deleted')
|
|
487
|
+
existing.status = 'deleted';
|
|
488
|
+
else if (opts.status === 'modified' && existing.status !== 'added')
|
|
489
|
+
existing.status = 'modified';
|
|
490
|
+
if (typeof opts.bytesWritten === 'number' && opts.bytesWritten > 0) {
|
|
491
|
+
existing.bytesWritten = opts.bytesWritten;
|
|
492
|
+
}
|
|
493
|
+
if (opts.hunks && opts.hunks.length > 0) {
|
|
494
|
+
existing.hunks = opts.hunks;
|
|
495
|
+
existing.additions = opts.additions ?? existing.additions;
|
|
496
|
+
existing.deletions = opts.deletions ?? existing.deletions;
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
const assistantBacktickCandidates = [];
|
|
500
|
+
for (const msg of messages) {
|
|
501
|
+
const rec = msg;
|
|
502
|
+
const toolCalls = Array.isArray(rec.tool_calls)
|
|
503
|
+
? rec.tool_calls
|
|
504
|
+
: [];
|
|
505
|
+
for (const tc of toolCalls) {
|
|
506
|
+
const fn = (tc.function && typeof tc.function === 'object' ? tc.function : tc);
|
|
507
|
+
const name = typeof fn.name === 'string' ? fn.name.trim().toLowerCase() : '';
|
|
508
|
+
if (!name)
|
|
509
|
+
continue;
|
|
510
|
+
let args = null;
|
|
511
|
+
if (typeof fn.arguments === 'string') {
|
|
512
|
+
try {
|
|
513
|
+
const parsed = JSON.parse(fn.arguments);
|
|
514
|
+
if (parsed && typeof parsed === 'object')
|
|
515
|
+
args = parsed;
|
|
516
|
+
}
|
|
517
|
+
catch {
|
|
518
|
+
args = null;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
else if (fn.arguments && typeof fn.arguments === 'object') {
|
|
522
|
+
args = fn.arguments;
|
|
523
|
+
}
|
|
524
|
+
if (!args)
|
|
525
|
+
continue;
|
|
526
|
+
if (MUTATING_FILE_TOOLS.has(name)) {
|
|
527
|
+
const status = name === 'fs_delete'
|
|
528
|
+
? 'deleted'
|
|
529
|
+
: name.includes('edit') || name.includes('patch') || name.includes('replace')
|
|
530
|
+
? 'modified'
|
|
531
|
+
: 'added';
|
|
532
|
+
const synthWrite = typeof args.content === 'string' && args.content.length > 0
|
|
533
|
+
? buildSynthesizedWriteHunk(args.content)
|
|
534
|
+
: null;
|
|
535
|
+
const synthEdit = (typeof args.old_string === 'string' || typeof args.new_string === 'string')
|
|
536
|
+
&& (Boolean(args.old_string) || Boolean(args.new_string))
|
|
537
|
+
? buildSynthesizedEditHunk(String(args.old_string || ''), String(args.new_string || ''))
|
|
538
|
+
: null;
|
|
539
|
+
const pathKeys = [
|
|
540
|
+
'path', 'filePath', 'file_path', 'targetFile', 'target_path',
|
|
541
|
+
'filename', 'file', 'destination', 'outputFile', 'output_path', 'outputPath'
|
|
542
|
+
];
|
|
543
|
+
for (const key of pathKeys) {
|
|
544
|
+
recordFile(args[key], {
|
|
545
|
+
status,
|
|
546
|
+
additions: synthWrite?.additions ?? synthEdit?.additions ?? 0,
|
|
547
|
+
deletions: synthEdit?.deletions ?? 0,
|
|
548
|
+
hunks: synthWrite?.hunks ?? synthEdit?.hunks ?? []
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
if (typeof args.patch === 'string') {
|
|
552
|
+
for (const p of extractPatchPathsFromText(args.patch)) {
|
|
553
|
+
recordFile(p, { status: 'modified' });
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
if (Array.isArray(args.edits)) {
|
|
557
|
+
for (const ed of args.edits) {
|
|
558
|
+
if (ed && typeof ed === 'object') {
|
|
559
|
+
recordFile(ed.path, { status: 'modified' });
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
else if (name === 'browser_act' && Array.isArray(args.actions)) {
|
|
565
|
+
for (const a of args.actions) {
|
|
566
|
+
if (a && typeof a === 'object') {
|
|
567
|
+
const actObj = a;
|
|
568
|
+
if (actObj.filePath)
|
|
569
|
+
recordFile(actObj.filePath, { status: 'modified' });
|
|
570
|
+
if (actObj.outputPath)
|
|
571
|
+
recordFile(actObj.outputPath, { status: 'added' });
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
else if (SHELL_TOOLS.has(name) && typeof args.command === 'string') {
|
|
576
|
+
for (const p of extractShellWriteTargets(args.command, workspaceRoot, args.cwd)) {
|
|
577
|
+
recordFile(p, { status: 'added' });
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
const extActions = Array.isArray(rec.external_actions)
|
|
582
|
+
? rec.external_actions
|
|
583
|
+
: [];
|
|
584
|
+
for (const act of extActions) {
|
|
585
|
+
const name = typeof act.name === 'string' ? act.name.trim().toLowerCase() : '';
|
|
586
|
+
if (!name)
|
|
587
|
+
continue;
|
|
588
|
+
if (MUTATING_FILE_TOOLS.has(name)) {
|
|
589
|
+
recordFile(act.detail, { status: name.includes('edit') ? 'modified' : 'added' });
|
|
590
|
+
const params = act.parameters && typeof act.parameters === 'object'
|
|
591
|
+
? act.parameters
|
|
592
|
+
: null;
|
|
593
|
+
if (params) {
|
|
594
|
+
for (const key of ['path', 'filePath', 'file_path', 'targetFile', 'filename', 'file', 'destination', 'outputPath']) {
|
|
595
|
+
recordFile(params[key], { status: name.includes('edit') ? 'modified' : 'added' });
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
else if (SHELL_TOOLS.has(name) && typeof act.detail === 'string') {
|
|
600
|
+
for (const p of extractShellWriteTargets(act.detail, workspaceRoot)) {
|
|
601
|
+
recordFile(p, { status: 'added' });
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
const rawText = typeof msg.content === 'string' ? msg.content : '';
|
|
606
|
+
if (msg.role === 'tool' && rawText) {
|
|
607
|
+
let toolText = rawText;
|
|
608
|
+
try {
|
|
609
|
+
const parsed = JSON.parse(rawText);
|
|
610
|
+
if (parsed && typeof parsed === 'object' && typeof parsed.output === 'string') {
|
|
611
|
+
toolText = parsed.output;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
catch {
|
|
615
|
+
// Keep raw plain text tool output.
|
|
616
|
+
}
|
|
617
|
+
for (const m of toolText.matchAll(/Atomically wrote (\d+) bytes to ([^\r\n"'}]+)/g)) {
|
|
618
|
+
recordFile(m[2], { status: 'added', bytesWritten: Number(m[1]) || undefined });
|
|
619
|
+
}
|
|
620
|
+
for (const m of toolText.matchAll(/Saved (\d+)-byte screenshot to ([^\r\n"'}]+)/g)) {
|
|
621
|
+
recordFile(m[2], { status: 'added', bytesWritten: Number(m[1]) || undefined });
|
|
622
|
+
}
|
|
623
|
+
for (const m of toolText.matchAll(/(?:Successfully edited|Successfully wrote|Created file|Patched)\s+([^\r\n"'}]+)/g)) {
|
|
624
|
+
recordFile(m[1], { status: 'modified' });
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
if (msg.role === 'assistant' && rawText) {
|
|
628
|
+
for (const m of rawText.matchAll(/file:\/\/[^\s)\]"'<>]+/g)) {
|
|
629
|
+
recordFile(m[0], { status: 'added' });
|
|
630
|
+
}
|
|
631
|
+
for (const m of rawText.matchAll(/`([^`\r\n]{3,240})`/g)) {
|
|
632
|
+
const candidate = m[1];
|
|
633
|
+
if (candidate.includes('/') && hasFileExtension(candidate) && !candidate.includes(' ')) {
|
|
634
|
+
assistantBacktickCandidates.push(candidate);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
for (const cand of assistantBacktickCandidates) {
|
|
640
|
+
const norm = normalizeWorkspaceRelCandidate(workspaceRoot, cand);
|
|
641
|
+
if (!norm || evidenceMap.has(norm))
|
|
642
|
+
continue;
|
|
643
|
+
const dir = path.posix.dirname(norm);
|
|
644
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, norm);
|
|
645
|
+
const inTouchedDir = Boolean(dir && dir !== '.' && touchedDirs.has(dir));
|
|
646
|
+
const existsUntrackedDotAsset = Boolean(abs && norm.startsWith('.') && fs.existsSync(abs));
|
|
647
|
+
if (inTouchedDir || existsUntrackedDotAsset) {
|
|
648
|
+
recordFile(norm, { status: 'added' });
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
// Drop bare parent directories when concrete child files in that directory are present.
|
|
652
|
+
const allPaths = [...evidenceMap.keys()];
|
|
653
|
+
for (const p of allPaths) {
|
|
654
|
+
if (!hasFileExtension(p)) {
|
|
655
|
+
const prefix = `${p}/`;
|
|
656
|
+
if (allPaths.some((other) => other.startsWith(prefix))) {
|
|
657
|
+
evidenceMap.delete(p);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
return evidenceMap;
|
|
662
|
+
}
|
|
663
|
+
export function extractSessionTouchedFiles(messages, workspaceRoot) {
|
|
664
|
+
return [...extractSessionFileEvidence(messages, workspaceRoot).keys()].sort();
|
|
665
|
+
}
|
|
666
|
+
function summarizeArgsTarget(args) {
|
|
667
|
+
if (!args)
|
|
668
|
+
return '';
|
|
669
|
+
for (const key of ['path', 'filePath', 'file_path', 'file', 'command', 'query', 'url', 'skill_id']) {
|
|
670
|
+
if (typeof args[key] === 'string' && String(args[key]).trim()) {
|
|
671
|
+
return String(args[key]).trim().slice(0, 100);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
return '';
|
|
675
|
+
}
|
|
676
|
+
function extractSessionDisplayMessages(messages) {
|
|
677
|
+
const toolOutputsById = new Map();
|
|
678
|
+
for (const msg of messages) {
|
|
679
|
+
if (msg.role !== 'tool')
|
|
680
|
+
continue;
|
|
681
|
+
const rec = msg;
|
|
682
|
+
const id = typeof rec.tool_call_id === 'string' ? rec.tool_call_id : '';
|
|
683
|
+
if (!id)
|
|
684
|
+
continue;
|
|
685
|
+
const raw = typeof msg.content === 'string' ? msg.content : '';
|
|
686
|
+
let failed = false;
|
|
687
|
+
let summary = raw.trim().slice(0, 360);
|
|
688
|
+
try {
|
|
689
|
+
const parsed = JSON.parse(raw);
|
|
690
|
+
if (parsed && typeof parsed === 'object') {
|
|
691
|
+
if (parsed.success === false || typeof parsed.error === 'string')
|
|
692
|
+
failed = true;
|
|
693
|
+
if (typeof parsed.error === 'string')
|
|
694
|
+
summary = parsed.error.slice(0, 360);
|
|
695
|
+
else if (typeof parsed.output === 'string')
|
|
696
|
+
summary = parsed.output.slice(0, 360);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
catch {
|
|
700
|
+
// plain text tool output
|
|
701
|
+
}
|
|
702
|
+
toolOutputsById.set(id, { output: summary, failed });
|
|
703
|
+
}
|
|
704
|
+
const out = [];
|
|
705
|
+
for (const msg of messages) {
|
|
706
|
+
if (msg.role !== 'user' && msg.role !== 'assistant')
|
|
707
|
+
continue;
|
|
708
|
+
const rec = msg;
|
|
709
|
+
let text = '';
|
|
710
|
+
if (typeof msg.content === 'string') {
|
|
711
|
+
text = msg.content;
|
|
712
|
+
}
|
|
713
|
+
else if (Array.isArray(msg.content)) {
|
|
714
|
+
const parts = [];
|
|
715
|
+
for (const block of msg.content) {
|
|
716
|
+
if (block && typeof block === 'object' && typeof block.text === 'string') {
|
|
717
|
+
parts.push(String(block.text));
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
text = parts.join('\n');
|
|
721
|
+
}
|
|
722
|
+
const trimmed = text.trim();
|
|
723
|
+
if (msg.role === 'user') {
|
|
724
|
+
if (!trimmed)
|
|
725
|
+
continue;
|
|
726
|
+
out.push({ role: 'user', content: trimmed });
|
|
727
|
+
continue;
|
|
728
|
+
}
|
|
729
|
+
const steps = [];
|
|
730
|
+
const extActions = Array.isArray(rec.external_actions)
|
|
731
|
+
? rec.external_actions
|
|
732
|
+
: [];
|
|
733
|
+
for (const act of extActions) {
|
|
734
|
+
const rawName = typeof act.name === 'string' ? act.name.trim() : '';
|
|
735
|
+
const rawDetail = typeof act.detail === 'string' ? act.detail.trim() : '';
|
|
736
|
+
if (!rawName || rawName === 'true' || rawName === ':' || rawDetail === 'true' || rawDetail === ':')
|
|
737
|
+
continue;
|
|
738
|
+
steps.push({
|
|
739
|
+
tool: rawName.replace(/^causyne[-_]browser[_:]/i, ''),
|
|
740
|
+
target: rawDetail.slice(0, 100),
|
|
741
|
+
status: act.status === 'failed' ? 'failed' : 'done'
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
const toolCalls = Array.isArray(rec.tool_calls)
|
|
745
|
+
? rec.tool_calls
|
|
746
|
+
: [];
|
|
747
|
+
for (const tc of toolCalls) {
|
|
748
|
+
const fn = (tc.function && typeof tc.function === 'object' ? tc.function : tc);
|
|
749
|
+
const name = typeof fn.name === 'string' ? fn.name.trim() : '';
|
|
750
|
+
if (!name || name === 'true' || name === ':')
|
|
751
|
+
continue;
|
|
752
|
+
let args = null;
|
|
753
|
+
if (typeof fn.arguments === 'string') {
|
|
754
|
+
try {
|
|
755
|
+
const parsed = JSON.parse(fn.arguments);
|
|
756
|
+
if (parsed && typeof parsed === 'object')
|
|
757
|
+
args = parsed;
|
|
758
|
+
}
|
|
759
|
+
catch {
|
|
760
|
+
args = null;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
else if (fn.arguments && typeof fn.arguments === 'object') {
|
|
764
|
+
args = fn.arguments;
|
|
765
|
+
}
|
|
766
|
+
const tcId = typeof tc.id === 'string' ? tc.id : '';
|
|
767
|
+
const matchedOut = tcId ? toolOutputsById.get(tcId) : undefined;
|
|
768
|
+
steps.push({
|
|
769
|
+
tool: name,
|
|
770
|
+
target: summarizeArgsTarget(args),
|
|
771
|
+
status: matchedOut?.failed ? 'failed' : 'done',
|
|
772
|
+
...(matchedOut?.output ? { output: matchedOut.output } : {})
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
const rawReasoning = typeof rec.reasoning_content === 'string' ? rec.reasoning_content.trim() : '';
|
|
776
|
+
const reasoning = rawReasoning ? rawReasoning.slice(0, 8000) : undefined;
|
|
777
|
+
if (!trimmed && steps.length === 0 && !reasoning)
|
|
778
|
+
continue;
|
|
779
|
+
const msgBlocks = [];
|
|
780
|
+
if (reasoning)
|
|
781
|
+
msgBlocks.push({ kind: 'reasoning', content: reasoning });
|
|
782
|
+
if (steps.length > 0)
|
|
783
|
+
msgBlocks.push({ kind: 'steps', steps });
|
|
784
|
+
if (trimmed)
|
|
785
|
+
msgBlocks.push({ kind: 'text', content: trimmed });
|
|
786
|
+
// Merge consecutive assistant messages between user turns into one cohesive Claude-style turn
|
|
787
|
+
// while preserving exact chronological interleaved blocks (reasoning -> steps -> text -> steps -> text).
|
|
788
|
+
const prev = out.length > 0 ? out[out.length - 1] : null;
|
|
789
|
+
if (prev && prev.role === 'assistant') {
|
|
790
|
+
const prevBlocks = prev.blocks ? [...prev.blocks] : [];
|
|
791
|
+
for (const blk of msgBlocks) {
|
|
792
|
+
const lastBlk = prevBlocks.length > 0 ? prevBlocks[prevBlocks.length - 1] : null;
|
|
793
|
+
if (blk.kind === 'steps' && lastBlk && lastBlk.kind === 'steps') {
|
|
794
|
+
lastBlk.steps = [...lastBlk.steps, ...blk.steps];
|
|
795
|
+
}
|
|
796
|
+
else if (blk.kind === 'reasoning' && lastBlk && lastBlk.kind === 'reasoning') {
|
|
797
|
+
lastBlk.content = `${lastBlk.content}\n\n${blk.content}`.slice(0, 8000);
|
|
798
|
+
}
|
|
799
|
+
else {
|
|
800
|
+
prevBlocks.push(blk);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
prev.blocks = prevBlocks;
|
|
804
|
+
if (steps.length > 0)
|
|
805
|
+
prev.steps = [...(prev.steps || []), ...steps];
|
|
806
|
+
if (reasoning)
|
|
807
|
+
prev.reasoning = prev.reasoning ? `${prev.reasoning}\n\n${reasoning}`.slice(0, 8000) : reasoning;
|
|
808
|
+
if (trimmed)
|
|
809
|
+
prev.content = prev.content ? `${prev.content}\n\n${trimmed}` : trimmed;
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
out.push({
|
|
813
|
+
role: 'assistant',
|
|
814
|
+
content: trimmed,
|
|
815
|
+
...(reasoning ? { reasoning } : {}),
|
|
816
|
+
...(steps.length > 0 ? { steps } : {}),
|
|
817
|
+
blocks: msgBlocks
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
return out;
|
|
821
|
+
}
|
|
822
|
+
function buildWorkspacePromptWithAttachments(workspaceRoot, prompt, rawAttachments) {
|
|
823
|
+
if (!Array.isArray(rawAttachments) || rawAttachments.length === 0) {
|
|
824
|
+
return { effectivePrompt: prompt, attachedPaths: [] };
|
|
825
|
+
}
|
|
826
|
+
const attachedPaths = [];
|
|
827
|
+
const sections = [];
|
|
828
|
+
for (const raw of rawAttachments.slice(0, MAX_ATTACHMENTS)) {
|
|
829
|
+
if (typeof raw !== 'string')
|
|
830
|
+
continue;
|
|
831
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, raw);
|
|
832
|
+
if (!abs)
|
|
833
|
+
continue;
|
|
834
|
+
if (isIgnoredByCausyneIgnore(abs, workspaceRoot, false))
|
|
835
|
+
continue;
|
|
836
|
+
try {
|
|
837
|
+
const stat = fs.lstatSync(abs);
|
|
838
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
839
|
+
continue;
|
|
840
|
+
const buf = fs.readFileSync(abs);
|
|
841
|
+
if (buf.includes(0))
|
|
842
|
+
continue;
|
|
843
|
+
const sliced = buf.length > MAX_ATTACHMENT_BYTES ? buf.subarray(0, MAX_ATTACHMENT_BYTES) : buf;
|
|
844
|
+
const rel = path.relative(workspaceRoot, abs).split(path.sep).join('/');
|
|
845
|
+
const truncatedNote = buf.length > MAX_ATTACHMENT_BYTES ? '\n[truncated]' : '';
|
|
846
|
+
attachedPaths.push(rel);
|
|
847
|
+
sections.push(`--- Attached workspace file: ${rel} ---\n${sliced.toString('utf8')}${truncatedNote}`);
|
|
848
|
+
}
|
|
849
|
+
catch {
|
|
850
|
+
// skip unreadable attachment
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
if (sections.length === 0) {
|
|
854
|
+
return { effectivePrompt: prompt, attachedPaths: [] };
|
|
855
|
+
}
|
|
856
|
+
return {
|
|
857
|
+
effectivePrompt: `${sections.join('\n\n')}\n\n${prompt}`,
|
|
858
|
+
attachedPaths
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
function workspaceMatchesSession(sessionWorkspace, workspaceRoot) {
|
|
862
|
+
if (!sessionWorkspace)
|
|
863
|
+
return false;
|
|
864
|
+
const resolvedSession = physicalPath(sessionWorkspace);
|
|
865
|
+
return resolvedSession === workspaceRoot || sessionWorkspace === workspaceRoot;
|
|
866
|
+
}
|
|
867
|
+
function parseSessionIdRoute(pathname) {
|
|
868
|
+
const prefix = '/api/sessions/';
|
|
869
|
+
if (!pathname.startsWith(prefix))
|
|
870
|
+
return null;
|
|
871
|
+
const raw = pathname.slice(prefix.length);
|
|
872
|
+
if (!raw || raw.includes('/'))
|
|
873
|
+
return null;
|
|
874
|
+
let decoded = '';
|
|
875
|
+
try {
|
|
876
|
+
decoded = decodeURIComponent(raw);
|
|
877
|
+
}
|
|
878
|
+
catch {
|
|
879
|
+
return null;
|
|
880
|
+
}
|
|
881
|
+
return SAFE_SESSION_ID_RE.test(decoded) ? decoded : null;
|
|
882
|
+
}
|
|
883
|
+
function parseSessionStreamRoute(pathname) {
|
|
884
|
+
const prefix = '/api/sessions/';
|
|
885
|
+
const suffix = '/stream';
|
|
886
|
+
if (!pathname.startsWith(prefix) || !pathname.endsWith(suffix))
|
|
887
|
+
return null;
|
|
888
|
+
const raw = pathname.slice(prefix.length, pathname.length - suffix.length);
|
|
889
|
+
if (!raw || raw.includes('/'))
|
|
890
|
+
return null;
|
|
891
|
+
let decoded = '';
|
|
892
|
+
try {
|
|
893
|
+
decoded = decodeURIComponent(raw);
|
|
894
|
+
}
|
|
895
|
+
catch {
|
|
896
|
+
return null;
|
|
897
|
+
}
|
|
898
|
+
return SAFE_SESSION_ID_RE.test(decoded) ? decoded : null;
|
|
899
|
+
}
|
|
900
|
+
const MAX_RUN_BUFFERED_FRAMES = 2400;
|
|
901
|
+
const MAX_RUN_BUFFERED_BYTES = 2 * 1024 * 1024;
|
|
902
|
+
const STREAM_HEARTBEAT_MS = 15_000;
|
|
903
|
+
function readLastGitCommitDiffForFile(workspaceRoot, relPath) {
|
|
904
|
+
if (!relPath || relPath.startsWith('-') || relPath.includes('\0'))
|
|
905
|
+
return null;
|
|
906
|
+
try {
|
|
907
|
+
const raw = execFileSync('git', ['log', '-n', '1', '--format=', '--unified=3', '--no-color', '-p', '--', relPath], {
|
|
908
|
+
cwd: workspaceRoot,
|
|
909
|
+
encoding: 'utf8',
|
|
910
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
911
|
+
maxBuffer: 256 * 1024,
|
|
912
|
+
timeout: 3000,
|
|
913
|
+
windowsHide: true
|
|
914
|
+
});
|
|
915
|
+
if (!raw || !raw.trim())
|
|
916
|
+
return null;
|
|
917
|
+
const parsed = parseUnifiedDiff(raw);
|
|
918
|
+
const first = parsed[0];
|
|
919
|
+
if (!first || first.hunks.length === 0)
|
|
920
|
+
return null;
|
|
921
|
+
return {
|
|
922
|
+
additions: first.additions,
|
|
923
|
+
deletions: first.deletions,
|
|
924
|
+
hunks: first.hunks.slice(0, 12).map((h) => ({
|
|
925
|
+
header: h.header,
|
|
926
|
+
lines: h.lines.slice(0, 140)
|
|
927
|
+
}))
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
catch {
|
|
931
|
+
return null;
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
export async function startSkybridgeServer(options = {}) {
|
|
935
|
+
const rawRoot = options.workspaceRoot || process.cwd();
|
|
936
|
+
const resolvedRoot = physicalPath(rawRoot);
|
|
937
|
+
if (!resolvedRoot || !fs.existsSync(resolvedRoot) || !fs.statSync(resolvedRoot).isDirectory()) {
|
|
938
|
+
throw new Error(`Invalid Skybridge workspace directory: ${rawRoot}`);
|
|
939
|
+
}
|
|
940
|
+
const workspaceRoot = resolvedRoot;
|
|
941
|
+
const token = options.token || crypto.randomBytes(32).toString('base64url');
|
|
942
|
+
const requestedPort = typeof options.port === 'number'
|
|
943
|
+
&& Number.isInteger(options.port)
|
|
944
|
+
&& options.port >= 0
|
|
945
|
+
&& options.port <= 65535
|
|
946
|
+
? options.port
|
|
947
|
+
: 0;
|
|
948
|
+
const extraOrigins = options.allowedOrigins ?? [];
|
|
949
|
+
const version = getPackageVersion();
|
|
950
|
+
const hasCustomFactory = typeof options.loopFactory === 'function';
|
|
951
|
+
let boundPort = requestedPort;
|
|
952
|
+
const serverApprovalScope = createApprovalScope();
|
|
953
|
+
const buildSharedBrowserPeerMcp = () => {
|
|
954
|
+
if (!boundPort)
|
|
955
|
+
return [];
|
|
956
|
+
return [{
|
|
957
|
+
type: 'http',
|
|
958
|
+
name: CAUSYNE_BROWSER_MCP_NAME,
|
|
959
|
+
url: `http://127.0.0.1:${boundPort}/api/mcp/browser`,
|
|
960
|
+
headers: [{ name: 'Authorization', value: `Bearer ${token}` }]
|
|
961
|
+
}];
|
|
962
|
+
};
|
|
963
|
+
const loopFactory = options.loopFactory ?? ((sink, taskId, prompt, opts) => {
|
|
964
|
+
const loopOptions = {
|
|
965
|
+
workspaceRoot: opts.workspaceRoot,
|
|
966
|
+
approvalScope: serverApprovalScope,
|
|
967
|
+
peerMcpServers: buildSharedBrowserPeerMcp()
|
|
968
|
+
};
|
|
969
|
+
if (opts.sessionId)
|
|
970
|
+
loopOptions.memorySessionId = opts.sessionId;
|
|
971
|
+
if (opts.provider)
|
|
972
|
+
loopOptions.provider = opts.provider;
|
|
973
|
+
if (opts.model)
|
|
974
|
+
loopOptions.model = opts.model;
|
|
975
|
+
const loop = new AgentLoop(sink, taskId, prompt, loopOptions);
|
|
976
|
+
if (opts.mode === 'A' || opts.mode === 'B' || opts.mode === 'C') {
|
|
977
|
+
try {
|
|
978
|
+
loop.setAutonomyMode(opts.mode);
|
|
979
|
+
}
|
|
980
|
+
catch {
|
|
981
|
+
// Fallback when custom mode normalization differs.
|
|
982
|
+
}
|
|
983
|
+
if (loop.sandbox) {
|
|
984
|
+
loop.sandbox.autonomyMode = opts.mode;
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
const pendingDecisions = new Map();
|
|
988
|
+
loop.waitForDecision = (request) => {
|
|
989
|
+
const reqId = typeof request?.id === 'string' && request.id ? request.id : `dec_${Date.now()}`;
|
|
990
|
+
return new Promise((resolve) => {
|
|
991
|
+
pendingDecisions.set(reqId, resolve);
|
|
992
|
+
});
|
|
993
|
+
};
|
|
994
|
+
return {
|
|
995
|
+
run: () => loop.run(),
|
|
996
|
+
abort: () => {
|
|
997
|
+
for (const [, resolve] of pendingDecisions) {
|
|
998
|
+
try {
|
|
999
|
+
resolve(null);
|
|
1000
|
+
}
|
|
1001
|
+
catch { /* ignore */ }
|
|
1002
|
+
}
|
|
1003
|
+
pendingDecisions.clear();
|
|
1004
|
+
loop.abort();
|
|
1005
|
+
},
|
|
1006
|
+
resolveApproval: (toolCallId, approved) => {
|
|
1007
|
+
const resolver = loop.pendingApprovals.get(toolCallId);
|
|
1008
|
+
if (resolver)
|
|
1009
|
+
resolver(approved);
|
|
1010
|
+
},
|
|
1011
|
+
resolveDecision: (requestId, answer) => {
|
|
1012
|
+
const resolver = pendingDecisions.get(requestId);
|
|
1013
|
+
if (resolver) {
|
|
1014
|
+
pendingDecisions.delete(requestId);
|
|
1015
|
+
resolver(answer);
|
|
1016
|
+
}
|
|
1017
|
+
},
|
|
1018
|
+
grantAlways: (toolName) => {
|
|
1019
|
+
serverApprovalScope.grantAlways(toolName);
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
});
|
|
1023
|
+
const activeRuns = new Map();
|
|
1024
|
+
let taskCounter = 0;
|
|
1025
|
+
const findActiveRun = (sessionId) => {
|
|
1026
|
+
if (sessionId && activeRuns.has(sessionId)) {
|
|
1027
|
+
return activeRuns.get(sessionId) ?? null;
|
|
1028
|
+
}
|
|
1029
|
+
if (!sessionId && activeRuns.size === 1) {
|
|
1030
|
+
return activeRuns.values().next().value ?? null;
|
|
1031
|
+
}
|
|
1032
|
+
return null;
|
|
1033
|
+
};
|
|
1034
|
+
const pushRunFrame = (run, raw) => {
|
|
1035
|
+
const clean = raw.replace(/\r?\n/g, ' ');
|
|
1036
|
+
const frameBytes = Buffer.byteLength(clean, 'utf8');
|
|
1037
|
+
if (run.frames.length < MAX_RUN_BUFFERED_FRAMES && run.bufferedBytes + frameBytes <= MAX_RUN_BUFFERED_BYTES) {
|
|
1038
|
+
run.frames.push(clean);
|
|
1039
|
+
run.bufferedBytes += frameBytes;
|
|
1040
|
+
}
|
|
1041
|
+
for (const send of run.subscribers) {
|
|
1042
|
+
try {
|
|
1043
|
+
send(clean);
|
|
1044
|
+
}
|
|
1045
|
+
catch {
|
|
1046
|
+
// Isolate subscriber write failures so detached runs continue uninterrupted.
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
};
|
|
1050
|
+
const attachRunStream = (req, res, run, replayBuffered) => {
|
|
1051
|
+
req.setTimeout(0);
|
|
1052
|
+
res.setTimeout(0);
|
|
1053
|
+
try {
|
|
1054
|
+
req.socket?.setKeepAlive(true, STREAM_HEARTBEAT_MS);
|
|
1055
|
+
}
|
|
1056
|
+
catch { /* ignore */ }
|
|
1057
|
+
res.statusCode = 200;
|
|
1058
|
+
res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
|
|
1059
|
+
res.setHeader('Transfer-Encoding', 'chunked');
|
|
1060
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
1061
|
+
res.setHeader('X-Accel-Buffering', 'no');
|
|
1062
|
+
res.flushHeaders?.();
|
|
1063
|
+
const writeLine = (cleanFrame) => {
|
|
1064
|
+
if (res.writableEnded || res.destroyed)
|
|
1065
|
+
return;
|
|
1066
|
+
res.write(`${cleanFrame}\n`);
|
|
1067
|
+
};
|
|
1068
|
+
const heartbeatTimer = setInterval(() => {
|
|
1069
|
+
if (res.writableEnded || res.destroyed)
|
|
1070
|
+
return;
|
|
1071
|
+
writeLine(JSON.stringify({ type: 'heartbeat', ts: Date.now() }));
|
|
1072
|
+
}, STREAM_HEARTBEAT_MS);
|
|
1073
|
+
heartbeatTimer.unref?.();
|
|
1074
|
+
let detached = false;
|
|
1075
|
+
const detach = () => {
|
|
1076
|
+
if (detached)
|
|
1077
|
+
return;
|
|
1078
|
+
detached = true;
|
|
1079
|
+
clearInterval(heartbeatTimer);
|
|
1080
|
+
run.subscribers.delete(writeLine);
|
|
1081
|
+
run.doneSubscribers.delete(finishResponse);
|
|
1082
|
+
};
|
|
1083
|
+
const finishResponse = () => {
|
|
1084
|
+
detach();
|
|
1085
|
+
if (!res.writableEnded && !res.destroyed)
|
|
1086
|
+
res.end();
|
|
1087
|
+
};
|
|
1088
|
+
// Disconnecting a browser tab or switching chats ONLY unsubscribes this HTTP response.
|
|
1089
|
+
// It NEVER aborts the detached AgentLoop; only explicit POST /api/stop cancels it.
|
|
1090
|
+
res.on('close', detach);
|
|
1091
|
+
if (replayBuffered) {
|
|
1092
|
+
for (const frame of run.frames) {
|
|
1093
|
+
writeLine(frame);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
if (run.status === 'running' || run.status === 'awaiting_client') {
|
|
1097
|
+
run.subscribers.add(writeLine);
|
|
1098
|
+
run.doneSubscribers.add(finishResponse);
|
|
1099
|
+
}
|
|
1100
|
+
else {
|
|
1101
|
+
finishResponse();
|
|
1102
|
+
}
|
|
1103
|
+
};
|
|
1104
|
+
const sessionTouchedFilesMap = new Map();
|
|
1105
|
+
const recordSessionTouchedFile = (sessionId, rawPath) => {
|
|
1106
|
+
if (!sessionId || !SAFE_SESSION_ID_RE.test(sessionId))
|
|
1107
|
+
return;
|
|
1108
|
+
const norm = normalizeWorkspaceRelCandidate(workspaceRoot, rawPath);
|
|
1109
|
+
if (!norm)
|
|
1110
|
+
return;
|
|
1111
|
+
let set = sessionTouchedFilesMap.get(sessionId);
|
|
1112
|
+
if (!set) {
|
|
1113
|
+
set = new Set();
|
|
1114
|
+
sessionTouchedFilesMap.set(sessionId, set);
|
|
1115
|
+
}
|
|
1116
|
+
set.add(norm);
|
|
1117
|
+
};
|
|
1118
|
+
let browserControlOwner = 'human';
|
|
1119
|
+
let browserAgentActivity = {
|
|
1120
|
+
active: false,
|
|
1121
|
+
tool: '',
|
|
1122
|
+
detail: '',
|
|
1123
|
+
updatedAt: 0
|
|
1124
|
+
};
|
|
1125
|
+
const browserStreamClients = new Set();
|
|
1126
|
+
const broadcastBrowserNotice = (payload) => {
|
|
1127
|
+
for (const send of browserStreamClients) {
|
|
1128
|
+
try {
|
|
1129
|
+
send(payload);
|
|
1130
|
+
}
|
|
1131
|
+
catch {
|
|
1132
|
+
// Isolate individual stream clients.
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
const server = http.createServer(async (req, res) => {
|
|
1137
|
+
const hostHeader = req.headers.host;
|
|
1138
|
+
if (!isAllowedSkybridgeHost(hostHeader, boundPort)) {
|
|
1139
|
+
res.statusCode = 403;
|
|
1140
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1141
|
+
res.end(JSON.stringify({ error: 'Forbidden Host header (DNS rebinding protection).' }));
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
const originHeader = typeof req.headers.origin === 'string' ? req.headers.origin : undefined;
|
|
1145
|
+
const originAllowed = isAllowedSkybridgeOrigin(originHeader, boundPort, extraOrigins);
|
|
1146
|
+
applySecurityHeaders(res, originHeader, originAllowed);
|
|
1147
|
+
if (originHeader && !originAllowed) {
|
|
1148
|
+
sendJson(res, 403, { error: 'Origin not permitted by Causyne Skybridge.' });
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
if (req.method === 'OPTIONS') {
|
|
1152
|
+
res.statusCode = 204;
|
|
1153
|
+
res.end();
|
|
1154
|
+
return;
|
|
1155
|
+
}
|
|
1156
|
+
const parsedUrl = new URL(req.url || '/', `http://127.0.0.1:${boundPort}`);
|
|
1157
|
+
const pathname = parsedUrl.pathname;
|
|
1158
|
+
if (req.method === 'GET' && pathname === '/favicon.svg') {
|
|
1159
|
+
res.statusCode = 200;
|
|
1160
|
+
res.setHeader('Content-Type', 'image/svg+xml; charset=utf-8');
|
|
1161
|
+
res.setHeader('Cache-Control', 'public, max-age=3600');
|
|
1162
|
+
res.end(getCausyneFaviconSvg());
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
if (req.method === 'GET' && pathname === '/favicon.ico') {
|
|
1166
|
+
res.statusCode = 204;
|
|
1167
|
+
res.end();
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
if (req.method === 'GET' && pathname === '/') {
|
|
1171
|
+
const cspNonce = crypto.randomBytes(16).toString('base64url');
|
|
1172
|
+
res.statusCode = 200;
|
|
1173
|
+
res.setHeader('Content-Security-Policy', `default-src 'self'; script-src 'self' 'nonce-${cspNonce}'; `
|
|
1174
|
+
+ `style-src 'self' 'unsafe-inline'; img-src 'self' data:; `
|
|
1175
|
+
+ `frame-src http://127.0.0.1:* http://localhost:*; `
|
|
1176
|
+
+ `connect-src 'self'; frame-ancestors 'none'`);
|
|
1177
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
1178
|
+
res.end(renderSkybridgeHtml({
|
|
1179
|
+
cspNonce,
|
|
1180
|
+
workspaceName: path.basename(workspaceRoot),
|
|
1181
|
+
version
|
|
1182
|
+
}));
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
if (!pathname.startsWith('/api/')) {
|
|
1186
|
+
sendJson(res, 404, { error: 'Not found.' });
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
if (!timingSafeBearerMatch(req.headers.authorization, token)) {
|
|
1190
|
+
sendJson(res, 401, { error: 'Unauthorized. Valid Skybridge Bearer token required.' });
|
|
1191
|
+
return;
|
|
1192
|
+
}
|
|
1193
|
+
try {
|
|
1194
|
+
if (req.method === 'GET' && pathname === '/api/health') {
|
|
1195
|
+
const config = loadConfig();
|
|
1196
|
+
const zeroCost = await detectZeroCostProviders({ config, probeOllama: false });
|
|
1197
|
+
const readyZeroCost = zeroCost.filter((z) => z.readiness === 'ready');
|
|
1198
|
+
sendJson(res, 200, {
|
|
1199
|
+
ok: true,
|
|
1200
|
+
version,
|
|
1201
|
+
workspaceRoot,
|
|
1202
|
+
workspaceName: path.basename(workspaceRoot),
|
|
1203
|
+
provider: config.provider || 'unconfigured',
|
|
1204
|
+
model: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default',
|
|
1205
|
+
zeroCostReadyCount: readyZeroCost.length,
|
|
1206
|
+
zeroCostRoutes: readyZeroCost.map((z) => ({
|
|
1207
|
+
id: z.id,
|
|
1208
|
+
provider: z.provider,
|
|
1209
|
+
model: z.model,
|
|
1210
|
+
label: z.label,
|
|
1211
|
+
costTier: z.costTier
|
|
1212
|
+
})),
|
|
1213
|
+
busy: activeRuns.size > 0
|
|
1214
|
+
});
|
|
1215
|
+
return;
|
|
1216
|
+
}
|
|
1217
|
+
if (req.method === 'GET' && pathname === '/api/models') {
|
|
1218
|
+
const config = loadConfig();
|
|
1219
|
+
const forceRefresh = parsedUrl.searchParams.get('refresh') === '1';
|
|
1220
|
+
const allowLive = forceRefresh || parsedUrl.searchParams.get('live') === '1';
|
|
1221
|
+
const overview = allowLive
|
|
1222
|
+
? await resolveAvailableProvidersOverview(config, { forceRefresh })
|
|
1223
|
+
: getAvailableProvidersOverview(config);
|
|
1224
|
+
const activeProviderRaw = String(config.provider || '').toLowerCase().trim();
|
|
1225
|
+
const initialTab = activeProviderRaw === 'openrouter'
|
|
1226
|
+
? 'free'
|
|
1227
|
+
: (activeProviderRaw === 'antigravity'
|
|
1228
|
+
|| activeProviderRaw === 'agy'
|
|
1229
|
+
|| activeProviderRaw === 'pi'
|
|
1230
|
+
|| activeProviderRaw === 'acp'
|
|
1231
|
+
|| activeProviderRaw.startsWith('acp/')
|
|
1232
|
+
? 'acp'
|
|
1233
|
+
: 'byok');
|
|
1234
|
+
const tabs = {
|
|
1235
|
+
acp: buildModelPickerItems(config, overview, { tab: 'acp', maxAcpPerPeer: Infinity }),
|
|
1236
|
+
byok: buildModelPickerItems(config, overview, { tab: 'byok', maxAcpPerPeer: Infinity }),
|
|
1237
|
+
free: buildModelPickerItems(config, overview, { tab: 'free', maxAcpPerPeer: Infinity })
|
|
1238
|
+
};
|
|
1239
|
+
const zeroCost = await detectZeroCostProviders({ config, probeOllama: false });
|
|
1240
|
+
const readySet = new Set(zeroCost.filter((z) => z.readiness === 'ready').map((z) => z.provider));
|
|
1241
|
+
const groups = Object.entries(MODEL_CATALOGUE).map(([label, models]) => {
|
|
1242
|
+
const providerId = PROVIDER_KEY_FOR_CATALOG_LABEL[label] || label.toLowerCase();
|
|
1243
|
+
const hasKey = Boolean(resolveProviderApiKey(config, providerId));
|
|
1244
|
+
const isZeroCostReady = readySet.has(providerId);
|
|
1245
|
+
return {
|
|
1246
|
+
label,
|
|
1247
|
+
provider: providerId,
|
|
1248
|
+
configured: hasKey || isZeroCostReady,
|
|
1249
|
+
zeroCostReady: isZeroCostReady,
|
|
1250
|
+
defaultModel: DEFAULT_MODEL_BY_PROVIDER[providerId] || models[0] || '',
|
|
1251
|
+
models
|
|
1252
|
+
};
|
|
1253
|
+
});
|
|
1254
|
+
sendJson(res, 200, {
|
|
1255
|
+
ok: true,
|
|
1256
|
+
activeProvider: config.provider || 'unconfigured',
|
|
1257
|
+
activeModel: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || '',
|
|
1258
|
+
initialTab,
|
|
1259
|
+
tabs,
|
|
1260
|
+
overview,
|
|
1261
|
+
zeroCost: zeroCost.map((z) => ({
|
|
1262
|
+
id: z.id,
|
|
1263
|
+
provider: z.provider,
|
|
1264
|
+
model: z.model,
|
|
1265
|
+
label: z.label,
|
|
1266
|
+
costTier: z.costTier,
|
|
1267
|
+
readiness: z.readiness
|
|
1268
|
+
})),
|
|
1269
|
+
groups
|
|
1270
|
+
});
|
|
1271
|
+
return;
|
|
1272
|
+
}
|
|
1273
|
+
if (req.method === 'POST' && pathname === '/api/model') {
|
|
1274
|
+
const body = await readJsonBody(req);
|
|
1275
|
+
const action = typeof body.action === 'string' ? body.action.trim() : '';
|
|
1276
|
+
const provider = typeof body.provider === 'string' ? body.provider.trim() : '';
|
|
1277
|
+
const model = typeof body.model === 'string' ? body.model.trim() : '';
|
|
1278
|
+
if (action === 'disconnect' && provider === 'openrouter') {
|
|
1279
|
+
disconnectOpenRouter();
|
|
1280
|
+
const updated = loadConfig();
|
|
1281
|
+
auditLog.log({ event: 'skybridge_openrouter_disconnect' });
|
|
1282
|
+
sendJson(res, 200, {
|
|
1283
|
+
ok: true,
|
|
1284
|
+
disconnected: true,
|
|
1285
|
+
provider: updated.provider || 'unconfigured',
|
|
1286
|
+
model: updated.model || DEFAULT_MODEL_BY_PROVIDER[String(updated.provider || '')] || 'default'
|
|
1287
|
+
});
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
if (!provider || !SAFE_PROVIDER_RE.test(provider)) {
|
|
1291
|
+
sendJson(res, 400, { error: 'Valid provider identifier is required.' });
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
if (model && !SAFE_MODEL_RE.test(model)) {
|
|
1295
|
+
sendJson(res, 400, { error: 'Invalid model identifier.' });
|
|
1296
|
+
return;
|
|
1297
|
+
}
|
|
1298
|
+
const config = loadConfig();
|
|
1299
|
+
const resolvedModel = model || DEFAULT_MODEL_BY_PROVIDER[provider] || '';
|
|
1300
|
+
applyProviderOverrides(config, provider, resolvedModel);
|
|
1301
|
+
saveConfig(config);
|
|
1302
|
+
auditLog.log({
|
|
1303
|
+
event: 'skybridge_model_switch',
|
|
1304
|
+
provider: config.provider,
|
|
1305
|
+
model: config.model
|
|
1306
|
+
});
|
|
1307
|
+
sendJson(res, 200, {
|
|
1308
|
+
ok: true,
|
|
1309
|
+
provider: config.provider,
|
|
1310
|
+
model: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default'
|
|
1311
|
+
});
|
|
1312
|
+
return;
|
|
1313
|
+
}
|
|
1314
|
+
if (req.method === 'GET' && pathname === '/api/sessions') {
|
|
1315
|
+
const all = listSessions();
|
|
1316
|
+
const scoped = all.filter((row) => workspaceMatchesSession(row.workspace, workspaceRoot));
|
|
1317
|
+
sendJson(res, 200, {
|
|
1318
|
+
ok: true,
|
|
1319
|
+
sessions: scoped.slice(0, 50).map((row) => {
|
|
1320
|
+
const run = activeRuns.get(row.id);
|
|
1321
|
+
const isRunning = Boolean(run && (run.status === 'running' || run.status === 'awaiting_client'));
|
|
1322
|
+
return {
|
|
1323
|
+
id: row.id,
|
|
1324
|
+
title: row.title,
|
|
1325
|
+
createdAt: row.createdAt,
|
|
1326
|
+
updatedAt: row.updatedAt,
|
|
1327
|
+
messageCount: row.messageCount,
|
|
1328
|
+
running: isRunning,
|
|
1329
|
+
awaitingClient: Boolean(run && run.status === 'awaiting_client')
|
|
1330
|
+
};
|
|
1331
|
+
})
|
|
1332
|
+
});
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
const sessionStreamId = parseSessionStreamRoute(pathname);
|
|
1336
|
+
if (req.method === 'GET' && sessionStreamId) {
|
|
1337
|
+
const run = activeRuns.get(sessionStreamId);
|
|
1338
|
+
if (!run || (run.status !== 'running' && run.status !== 'awaiting_client')) {
|
|
1339
|
+
res.statusCode = 200;
|
|
1340
|
+
res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
|
|
1341
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
1342
|
+
res.end(`${JSON.stringify({ type: 'idle', sessionId: sessionStreamId })}\n`);
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
attachRunStream(req, res, run, true);
|
|
1346
|
+
return;
|
|
1347
|
+
}
|
|
1348
|
+
if (req.method === 'POST' && pathname === '/api/sessions') {
|
|
1349
|
+
const body = await readJsonBody(req);
|
|
1350
|
+
const rawTitle = typeof body.title === 'string' ? body.title.trim().slice(0, 80) : '';
|
|
1351
|
+
const created = createSession(workspaceRoot, rawTitle || 'Untitled', false);
|
|
1352
|
+
sendJson(res, 201, {
|
|
1353
|
+
ok: true,
|
|
1354
|
+
session: {
|
|
1355
|
+
id: created.id,
|
|
1356
|
+
title: created.title,
|
|
1357
|
+
createdAt: created.createdAt,
|
|
1358
|
+
updatedAt: created.updatedAt,
|
|
1359
|
+
messageCount: 0,
|
|
1360
|
+
messages: []
|
|
1361
|
+
}
|
|
1362
|
+
});
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
const sessionIdParam = parseSessionIdRoute(pathname);
|
|
1366
|
+
if (sessionIdParam) {
|
|
1367
|
+
const existing = getSession(sessionIdParam);
|
|
1368
|
+
if (!existing || !workspaceMatchesSession(existing.workspace, workspaceRoot)) {
|
|
1369
|
+
sendJson(res, 404, { error: 'Session not found in this workspace.' });
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
if (req.method === 'GET') {
|
|
1373
|
+
const persistedTouched = extractSessionTouchedFiles(existing.messages, workspaceRoot);
|
|
1374
|
+
const liveTouched = [...(sessionTouchedFilesMap.get(existing.id) ?? [])];
|
|
1375
|
+
const touchedFiles = [...new Set([...persistedTouched, ...liveTouched])].sort();
|
|
1376
|
+
const activeRun = activeRuns.get(existing.id);
|
|
1377
|
+
const isRunning = Boolean(activeRun && (activeRun.status === 'running' || activeRun.status === 'awaiting_client'));
|
|
1378
|
+
sendJson(res, 200, {
|
|
1379
|
+
ok: true,
|
|
1380
|
+
session: {
|
|
1381
|
+
id: existing.id,
|
|
1382
|
+
title: existing.title,
|
|
1383
|
+
createdAt: existing.createdAt,
|
|
1384
|
+
updatedAt: existing.updatedAt,
|
|
1385
|
+
messageCount: existing.messages.length,
|
|
1386
|
+
messages: extractSessionDisplayMessages(existing.messages),
|
|
1387
|
+
touchedFiles,
|
|
1388
|
+
running: isRunning,
|
|
1389
|
+
awaitingClient: Boolean(activeRun && activeRun.status === 'awaiting_client'),
|
|
1390
|
+
activeRun: isRunning && activeRun ? {
|
|
1391
|
+
taskId: activeRun.taskId,
|
|
1392
|
+
status: activeRun.status,
|
|
1393
|
+
prompt: activeRun.prompt,
|
|
1394
|
+
startedAt: activeRun.startedAt
|
|
1395
|
+
} : null
|
|
1396
|
+
}
|
|
1397
|
+
});
|
|
1398
|
+
return;
|
|
1399
|
+
}
|
|
1400
|
+
if (req.method === 'PATCH') {
|
|
1401
|
+
const body = await readJsonBody(req);
|
|
1402
|
+
const nextTitle = typeof body.title === 'string' ? body.title.trim().slice(0, 80) : '';
|
|
1403
|
+
if (!nextTitle) {
|
|
1404
|
+
sendJson(res, 400, { error: 'A non-empty session title is required.' });
|
|
1405
|
+
return;
|
|
1406
|
+
}
|
|
1407
|
+
const updated = renameSession(existing.id, nextTitle);
|
|
1408
|
+
if (!updated) {
|
|
1409
|
+
sendJson(res, 400, { error: 'Could not rename session.' });
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
sendJson(res, 200, { ok: true, id: existing.id, title: nextTitle });
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
if (req.method === 'DELETE') {
|
|
1416
|
+
const removed = deleteSession(existing.id);
|
|
1417
|
+
sendJson(res, removed ? 200 : 404, { ok: removed, id: existing.id });
|
|
1418
|
+
return;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
if (req.method === 'GET' && pathname === '/api/files') {
|
|
1422
|
+
const dir = parsedUrl.searchParams.get('dir') || '';
|
|
1423
|
+
const q = parsedUrl.searchParams.get('q') || '';
|
|
1424
|
+
const entries = listWorkspaceEntries(workspaceRoot, dir, q);
|
|
1425
|
+
const parentDir = dir ? path.posix.dirname(dir.replace(/\\/g, '/')) : '';
|
|
1426
|
+
sendJson(res, 200, {
|
|
1427
|
+
ok: true,
|
|
1428
|
+
dir,
|
|
1429
|
+
parentDir: parentDir === '.' ? '' : parentDir,
|
|
1430
|
+
entries
|
|
1431
|
+
});
|
|
1432
|
+
return;
|
|
1433
|
+
}
|
|
1434
|
+
if (req.method === 'GET' && pathname === '/api/file') {
|
|
1435
|
+
const rel = parsedUrl.searchParams.get('path') || '';
|
|
1436
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
|
|
1437
|
+
if (!abs) {
|
|
1438
|
+
sendJson(res, 403, { error: 'Path is outside the locked workspace boundary.' });
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
const stat = fs.lstatSync(abs);
|
|
1442
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
1443
|
+
sendJson(res, 403, { error: 'Only regular workspace files can be read.' });
|
|
1444
|
+
return;
|
|
1445
|
+
}
|
|
1446
|
+
if (stat.size > MAX_FILE_READ_BYTES) {
|
|
1447
|
+
sendJson(res, 413, { error: `File exceeds ${MAX_FILE_READ_BYTES} byte preview limit.` });
|
|
1448
|
+
return;
|
|
1449
|
+
}
|
|
1450
|
+
const content = fs.readFileSync(abs, 'utf8');
|
|
1451
|
+
sendJson(res, 200, {
|
|
1452
|
+
ok: true,
|
|
1453
|
+
path: path.relative(workspaceRoot, abs).split(path.sep).join('/'),
|
|
1454
|
+
size: stat.size,
|
|
1455
|
+
content
|
|
1456
|
+
});
|
|
1457
|
+
return;
|
|
1458
|
+
}
|
|
1459
|
+
if (req.method === 'POST' && pathname === '/api/file') {
|
|
1460
|
+
const body = await readJsonBody(req, MAX_FILE_WRITE_BYTES);
|
|
1461
|
+
const rel = typeof body.path === 'string' ? body.path : '';
|
|
1462
|
+
const content = typeof body.content === 'string' ? body.content : null;
|
|
1463
|
+
if (!rel || content === null) {
|
|
1464
|
+
sendJson(res, 400, { error: 'Both `path` and string `content` are required.' });
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
|
|
1468
|
+
if (!abs) {
|
|
1469
|
+
sendJson(res, 403, { error: 'Refusing write outside locked workspace boundary.' });
|
|
1470
|
+
return;
|
|
1471
|
+
}
|
|
1472
|
+
const relNormalized = path.relative(workspaceRoot, abs).split(path.sep).join('/');
|
|
1473
|
+
if (isIgnoredByCausyneIgnore(abs, workspaceRoot, false)) {
|
|
1474
|
+
sendJson(res, 403, { error: 'File path is blocked by .causyneignore.' });
|
|
1475
|
+
return;
|
|
1476
|
+
}
|
|
1477
|
+
const byteCount = Buffer.byteLength(content, 'utf8');
|
|
1478
|
+
if (byteCount > MAX_FILE_WRITE_BYTES) {
|
|
1479
|
+
sendJson(res, 413, { error: 'File content exceeds maximum write limit.' });
|
|
1480
|
+
return;
|
|
1481
|
+
}
|
|
1482
|
+
atomicWriteFileSync(abs, content);
|
|
1483
|
+
if (typeof body.sessionId === 'string') {
|
|
1484
|
+
recordSessionTouchedFile(body.sessionId.trim(), relNormalized);
|
|
1485
|
+
}
|
|
1486
|
+
auditLog.log({ event: 'skybridge_file_write', path: relNormalized, bytes: byteCount });
|
|
1487
|
+
sendJson(res, 200, { ok: true, path: relNormalized, bytes: byteCount });
|
|
1488
|
+
return;
|
|
1489
|
+
}
|
|
1490
|
+
if (req.method === 'GET' && pathname === '/api/diff') {
|
|
1491
|
+
const staged = parsedUrl.searchParams.get('staged') === '1';
|
|
1492
|
+
const rawSessionId = (parsedUrl.searchParams.get('sessionId') || '').trim();
|
|
1493
|
+
const sessionId = SAFE_SESSION_ID_RE.test(rawSessionId) ? rawSessionId : '';
|
|
1494
|
+
const rawScope = (parsedUrl.searchParams.get('scope') || '').trim().toLowerCase();
|
|
1495
|
+
const scope = rawScope === 'session' && sessionId ? 'session' : 'workspace';
|
|
1496
|
+
const sessionEvidenceMap = new Map();
|
|
1497
|
+
if (sessionId) {
|
|
1498
|
+
const sess = getSession(sessionId);
|
|
1499
|
+
if (sess && workspaceMatchesSession(sess.workspace, workspaceRoot)) {
|
|
1500
|
+
for (const [p, ev] of extractSessionFileEvidence(sess.messages, workspaceRoot)) {
|
|
1501
|
+
sessionEvidenceMap.set(p, ev);
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
for (const p of sessionTouchedFilesMap.get(sessionId) ?? []) {
|
|
1505
|
+
if (!sessionEvidenceMap.has(p)) {
|
|
1506
|
+
sessionEvidenceMap.set(p, {
|
|
1507
|
+
path: p,
|
|
1508
|
+
status: 'modified',
|
|
1509
|
+
additions: 0,
|
|
1510
|
+
deletions: 0,
|
|
1511
|
+
hunks: []
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
const buildNonGitSessionEntry = (rel, ev, isGit) => {
|
|
1517
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, rel);
|
|
1518
|
+
let existsOnDisk = false;
|
|
1519
|
+
let diskSize = 0;
|
|
1520
|
+
let diskHunks = [];
|
|
1521
|
+
let diskAdditions = 0;
|
|
1522
|
+
let diskDeletions = 0;
|
|
1523
|
+
let fromLastCommit = false;
|
|
1524
|
+
if (abs) {
|
|
1525
|
+
try {
|
|
1526
|
+
const st = fs.lstatSync(abs);
|
|
1527
|
+
if (!st.isSymbolicLink() && st.isFile()) {
|
|
1528
|
+
existsOnDisk = true;
|
|
1529
|
+
diskSize = st.size;
|
|
1530
|
+
if (isGit && (!ev || ev.hunks.length === 0)) {
|
|
1531
|
+
const commitDiff = readLastGitCommitDiffForFile(workspaceRoot, rel);
|
|
1532
|
+
if (commitDiff) {
|
|
1533
|
+
diskHunks = commitDiff.hunks;
|
|
1534
|
+
diskAdditions = commitDiff.additions;
|
|
1535
|
+
diskDeletions = commitDiff.deletions;
|
|
1536
|
+
fromLastCommit = true;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
if (diskHunks.length === 0 && st.size > 0 && st.size <= 48 * 1024 && (!ev || ev.hunks.length === 0)) {
|
|
1540
|
+
const buf = fs.readFileSync(abs);
|
|
1541
|
+
if (!buf.includes(0)) {
|
|
1542
|
+
const synth = buildSynthesizedWriteHunk(buf.toString('utf8'));
|
|
1543
|
+
diskHunks = synth.hunks;
|
|
1544
|
+
diskAdditions = synth.additions;
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
catch {
|
|
1550
|
+
existsOnDisk = false;
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
const hunks = ev && ev.hunks.length > 0 ? ev.hunks : diskHunks;
|
|
1554
|
+
const additions = ev && ev.additions > 0 ? ev.additions : diskAdditions;
|
|
1555
|
+
const deletions = ev && ev.deletions > 0 ? ev.deletions : diskDeletions;
|
|
1556
|
+
const status = fromLastCommit && diskDeletions > 0
|
|
1557
|
+
? 'modified'
|
|
1558
|
+
: (ev?.status ?? (existsOnDisk ? 'modified' : 'added'));
|
|
1559
|
+
let note;
|
|
1560
|
+
if (existsOnDisk) {
|
|
1561
|
+
if (fromLastCommit) {
|
|
1562
|
+
note = 'Latest committed diff on disk';
|
|
1563
|
+
}
|
|
1564
|
+
else if (hunks.length === 0) {
|
|
1565
|
+
note = diskSize > 0
|
|
1566
|
+
? `On disk (${formatByteSize(diskSize)}) · ${isGit ? 'committed or binary asset' : 'workspace file'}`
|
|
1567
|
+
: (isGit ? 'Clean on disk' : 'Touched in this conversation');
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
else {
|
|
1571
|
+
const sizeLabel = ev?.bytesWritten ? ` (${formatByteSize(ev.bytesWritten)})` : '';
|
|
1572
|
+
note = `Written in this chat${sizeLabel} · no longer on disk`;
|
|
1573
|
+
}
|
|
1574
|
+
return {
|
|
1575
|
+
path: rel,
|
|
1576
|
+
status,
|
|
1577
|
+
additions,
|
|
1578
|
+
deletions,
|
|
1579
|
+
inGitDiff: false,
|
|
1580
|
+
existsOnDisk,
|
|
1581
|
+
note,
|
|
1582
|
+
hunks
|
|
1583
|
+
};
|
|
1584
|
+
};
|
|
1585
|
+
try {
|
|
1586
|
+
const report = collectWorkingTreeDiff(workspaceRoot, { staged });
|
|
1587
|
+
const mappedWorkspaceFiles = report.files.slice(0, 60).map((f) => {
|
|
1588
|
+
const abs = resolveWorkspaceRelativePath(workspaceRoot, f.displayPath);
|
|
1589
|
+
let existsOnDisk = f.status !== 'deleted';
|
|
1590
|
+
let note;
|
|
1591
|
+
if (abs && f.hunks.length === 0 && f.status !== 'deleted') {
|
|
1592
|
+
try {
|
|
1593
|
+
const st = fs.lstatSync(abs);
|
|
1594
|
+
existsOnDisk = st.isFile();
|
|
1595
|
+
if (existsOnDisk)
|
|
1596
|
+
note = `Binary or large asset (${formatByteSize(st.size)})`;
|
|
1597
|
+
}
|
|
1598
|
+
catch {
|
|
1599
|
+
existsOnDisk = false;
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
return {
|
|
1603
|
+
path: f.displayPath,
|
|
1604
|
+
status: f.status,
|
|
1605
|
+
additions: f.additions,
|
|
1606
|
+
deletions: f.deletions,
|
|
1607
|
+
inGitDiff: true,
|
|
1608
|
+
existsOnDisk,
|
|
1609
|
+
note,
|
|
1610
|
+
hunks: f.hunks.slice(0, 20).map((h) => ({
|
|
1611
|
+
header: h.header,
|
|
1612
|
+
lines: h.lines.slice(0, 200)
|
|
1613
|
+
}))
|
|
1614
|
+
};
|
|
1615
|
+
});
|
|
1616
|
+
const matchedSessionGitFiles = mappedWorkspaceFiles.filter((f) => sessionEvidenceMap.has(f.path));
|
|
1617
|
+
const matchedPaths = new Set(matchedSessionGitFiles.map((f) => f.path));
|
|
1618
|
+
const extraSessionFiles = [...sessionEvidenceMap.keys()]
|
|
1619
|
+
.sort()
|
|
1620
|
+
.filter((rel) => !matchedPaths.has(rel))
|
|
1621
|
+
.map((rel) => buildNonGitSessionEntry(rel, sessionEvidenceMap.get(rel), true));
|
|
1622
|
+
const sessionFiles = [...matchedSessionGitFiles, ...extraSessionFiles];
|
|
1623
|
+
const returnedFiles = scope === 'session' ? sessionFiles : mappedWorkspaceFiles;
|
|
1624
|
+
const totalAdditions = scope === 'session'
|
|
1625
|
+
? returnedFiles.reduce((sum, f) => sum + f.additions, 0)
|
|
1626
|
+
: report.totalAdditions;
|
|
1627
|
+
const totalDeletions = scope === 'session'
|
|
1628
|
+
? returnedFiles.reduce((sum, f) => sum + f.deletions, 0)
|
|
1629
|
+
: report.totalDeletions;
|
|
1630
|
+
sendJson(res, 200, {
|
|
1631
|
+
ok: true,
|
|
1632
|
+
isGitRepo: true,
|
|
1633
|
+
scope,
|
|
1634
|
+
sessionId: sessionId || null,
|
|
1635
|
+
staged: report.staged,
|
|
1636
|
+
workspaceFileCount: mappedWorkspaceFiles.length,
|
|
1637
|
+
sessionFileCount: sessionFiles.length,
|
|
1638
|
+
totalAdditions,
|
|
1639
|
+
totalDeletions,
|
|
1640
|
+
truncated: report.truncated,
|
|
1641
|
+
files: returnedFiles
|
|
1642
|
+
});
|
|
1643
|
+
}
|
|
1644
|
+
catch {
|
|
1645
|
+
const fallbackSessionFiles = [...sessionEvidenceMap.keys()]
|
|
1646
|
+
.sort()
|
|
1647
|
+
.map((rel) => buildNonGitSessionEntry(rel, sessionEvidenceMap.get(rel), false));
|
|
1648
|
+
sendJson(res, 200, {
|
|
1649
|
+
ok: true,
|
|
1650
|
+
isGitRepo: false,
|
|
1651
|
+
scope,
|
|
1652
|
+
sessionId: sessionId || null,
|
|
1653
|
+
staged,
|
|
1654
|
+
workspaceFileCount: 0,
|
|
1655
|
+
sessionFileCount: fallbackSessionFiles.length,
|
|
1656
|
+
totalAdditions: fallbackSessionFiles.reduce((sum, f) => sum + f.additions, 0),
|
|
1657
|
+
totalDeletions: fallbackSessionFiles.reduce((sum, f) => sum + f.deletions, 0),
|
|
1658
|
+
truncated: false,
|
|
1659
|
+
files: scope === 'session' ? fallbackSessionFiles : []
|
|
1660
|
+
});
|
|
1661
|
+
}
|
|
1662
|
+
return;
|
|
1663
|
+
}
|
|
1664
|
+
if (req.method === 'GET' && pathname === '/api/doctor/report') {
|
|
1665
|
+
const config = loadConfig();
|
|
1666
|
+
sendJson(res, 200, {
|
|
1667
|
+
ok: true,
|
|
1668
|
+
report: formatRedactedProviderErrorReport({
|
|
1669
|
+
provider: config.provider,
|
|
1670
|
+
model: config.model,
|
|
1671
|
+
causyneVersion: version
|
|
1672
|
+
})
|
|
1673
|
+
});
|
|
1674
|
+
return;
|
|
1675
|
+
}
|
|
1676
|
+
if (req.method === 'GET' && pathname === '/api/license/status') {
|
|
1677
|
+
const liveRequested = parsedUrl.searchParams.get('live') === '1';
|
|
1678
|
+
const hasCustomClient = Boolean(options.entitlementClient);
|
|
1679
|
+
if (!LICENSE_ENFORCEMENT_ENABLED && !hasCustomClient && !liveRequested) {
|
|
1680
|
+
sendJson(res, 200, {
|
|
1681
|
+
ok: true,
|
|
1682
|
+
enforcementEnabled: false,
|
|
1683
|
+
entitlement: 'free',
|
|
1684
|
+
plan: 'free',
|
|
1685
|
+
paidUntil: null,
|
|
1686
|
+
dailySeconds: 21_600,
|
|
1687
|
+
remainingSeconds: 21_600,
|
|
1688
|
+
resetsAt: null,
|
|
1689
|
+
recoveryCode: null,
|
|
1690
|
+
supportMessage: DAILY_LIMIT_SUPPORT_MESSAGE
|
|
1691
|
+
});
|
|
1692
|
+
return;
|
|
1693
|
+
}
|
|
1694
|
+
try {
|
|
1695
|
+
const client = options.entitlementClient ?? new EntitlementClient();
|
|
1696
|
+
const data = await client.status();
|
|
1697
|
+
sendJson(res, 200, {
|
|
1698
|
+
ok: true,
|
|
1699
|
+
enforcementEnabled: LICENSE_ENFORCEMENT_ENABLED,
|
|
1700
|
+
entitlement: typeof data?.entitlement === 'string' ? data.entitlement : 'free',
|
|
1701
|
+
plan: typeof data?.plan === 'string' ? data.plan : 'free',
|
|
1702
|
+
status: typeof data?.status === 'string' ? data.status : 'free',
|
|
1703
|
+
paidUntil: typeof data?.paidUntil === 'string' ? data.paidUntil : null,
|
|
1704
|
+
dailySeconds: typeof data?.dailySeconds === 'number' ? data.dailySeconds : null,
|
|
1705
|
+
remainingSeconds: typeof data?.remainingSeconds === 'number' ? data.remainingSeconds : null,
|
|
1706
|
+
resetsAt: typeof data?.resetsAt === 'string' ? data.resetsAt : null,
|
|
1707
|
+
recoveryCode: typeof data?.recoveryCode === 'string' ? data.recoveryCode : null,
|
|
1708
|
+
supportMessage: typeof data?.upgradeMessage === 'string' ? data.upgradeMessage : DAILY_LIMIT_SUPPORT_MESSAGE
|
|
1709
|
+
});
|
|
1710
|
+
}
|
|
1711
|
+
catch (err) {
|
|
1712
|
+
const msg = err instanceof EntitlementAccessError
|
|
1713
|
+
? err.message
|
|
1714
|
+
: 'Unable to reach licensing service right now.';
|
|
1715
|
+
sendJson(res, 503, { ok: false, error: msg, enforcementEnabled: LICENSE_ENFORCEMENT_ENABLED });
|
|
1716
|
+
}
|
|
1717
|
+
return;
|
|
1718
|
+
}
|
|
1719
|
+
if (req.method === 'POST' && pathname === '/api/license/checkout') {
|
|
1720
|
+
const body = await readJsonBody(req);
|
|
1721
|
+
const plan = typeof body.plan === 'string' ? body.plan.trim() : '';
|
|
1722
|
+
if (!isValidLicensePlan(plan)) {
|
|
1723
|
+
sendJson(res, 400, { error: 'Unknown Causyne plan.' });
|
|
1724
|
+
return;
|
|
1725
|
+
}
|
|
1726
|
+
try {
|
|
1727
|
+
const client = options.entitlementClient ?? new EntitlementClient();
|
|
1728
|
+
const result = await client.checkout(plan);
|
|
1729
|
+
auditLog.log({ event: 'skybridge_license_checkout', plan });
|
|
1730
|
+
sendJson(res, 200, { ok: true, plan, url: result.url });
|
|
1731
|
+
}
|
|
1732
|
+
catch (err) {
|
|
1733
|
+
const msg = err instanceof EntitlementAccessError
|
|
1734
|
+
? err.message
|
|
1735
|
+
: 'Unable to start Paddle checkout right now. Visit https://causyne.com/pricing.html.';
|
|
1736
|
+
sendJson(res, 502, { ok: false, error: msg });
|
|
1737
|
+
}
|
|
1738
|
+
return;
|
|
1739
|
+
}
|
|
1740
|
+
if (req.method === 'POST' && pathname === '/api/license/recover') {
|
|
1741
|
+
const body = await readJsonBody(req);
|
|
1742
|
+
const code = typeof body.recoveryCode === 'string' ? body.recoveryCode.trim() : '';
|
|
1743
|
+
try {
|
|
1744
|
+
const client = options.entitlementClient ?? new EntitlementClient();
|
|
1745
|
+
const result = await client.recover(code);
|
|
1746
|
+
auditLog.log({ event: 'skybridge_license_recover', ok: true });
|
|
1747
|
+
sendJson(res, 200, {
|
|
1748
|
+
ok: true,
|
|
1749
|
+
entitlement: result?.entitlement ?? 'pro',
|
|
1750
|
+
plan: result?.plan ?? 'monthly',
|
|
1751
|
+
paidUntil: result?.paidUntil ?? null
|
|
1752
|
+
});
|
|
1753
|
+
}
|
|
1754
|
+
catch (err) {
|
|
1755
|
+
const status = err instanceof EntitlementAccessError && err.code === 'INVALID_RECOVERY_CODE' ? 400 : 404;
|
|
1756
|
+
const msg = err instanceof EntitlementAccessError ? err.message : 'Could not link recovery code.';
|
|
1757
|
+
sendJson(res, status, { ok: false, error: msg });
|
|
1758
|
+
}
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
if (req.method === 'POST' && pathname === '/api/license/portal') {
|
|
1762
|
+
try {
|
|
1763
|
+
const client = options.entitlementClient ?? new EntitlementClient();
|
|
1764
|
+
const result = await client.portal();
|
|
1765
|
+
sendJson(res, 200, { ok: true, url: result.url });
|
|
1766
|
+
}
|
|
1767
|
+
catch (err) {
|
|
1768
|
+
const msg = err instanceof EntitlementAccessError ? err.message : 'Billing portal unavailable.';
|
|
1769
|
+
sendJson(res, 502, { ok: false, error: msg });
|
|
1770
|
+
}
|
|
1771
|
+
return;
|
|
1772
|
+
}
|
|
1773
|
+
if (req.method === 'POST' && pathname === '/api/doctor/probe') {
|
|
1774
|
+
const report = await runZeroSpendByokProbe();
|
|
1775
|
+
sendJson(res, 200, {
|
|
1776
|
+
ok: true,
|
|
1777
|
+
report: formatByokProbeReport(report),
|
|
1778
|
+
summary: {
|
|
1779
|
+
testedCount: report.testedCount,
|
|
1780
|
+
passedCount: report.passedCount,
|
|
1781
|
+
failedCount: report.failedCount,
|
|
1782
|
+
skippedCount: report.skippedCount
|
|
1783
|
+
}
|
|
1784
|
+
});
|
|
1785
|
+
return;
|
|
1786
|
+
}
|
|
1787
|
+
if (req.method === 'POST' && pathname === '/api/config/key') {
|
|
1788
|
+
const body = await readJsonBody(req);
|
|
1789
|
+
const provider = typeof body.provider === 'string' ? body.provider.trim().toLowerCase() : '';
|
|
1790
|
+
const apiKey = typeof body.apiKey === 'string' ? body.apiKey.trim() : '';
|
|
1791
|
+
const forbidden = new Set(['__proto__', 'constructor', 'prototype']);
|
|
1792
|
+
if (!provider || forbidden.has(provider) || !SAFE_PROVIDER_RE.test(provider)) {
|
|
1793
|
+
sendJson(res, 400, { error: 'Valid provider identifier is required.' });
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
if (!apiKey || apiKey.length < 4 || apiKey.length > 512) {
|
|
1797
|
+
sendJson(res, 400, { error: 'API key must be between 4 and 512 characters.' });
|
|
1798
|
+
return;
|
|
1799
|
+
}
|
|
1800
|
+
const config = loadConfig();
|
|
1801
|
+
const existingKeys = config.providerKeys && typeof config.providerKeys === 'object' && !Array.isArray(config.providerKeys)
|
|
1802
|
+
? { ...config.providerKeys }
|
|
1803
|
+
: {};
|
|
1804
|
+
existingKeys[provider] = apiKey;
|
|
1805
|
+
config.providerKeys = existingKeys;
|
|
1806
|
+
if (String(config.provider || '').trim().toLowerCase() === provider || body.activate === true) {
|
|
1807
|
+
applyProviderOverrides(config, provider, typeof body.model === 'string' ? body.model.trim() : undefined);
|
|
1808
|
+
}
|
|
1809
|
+
saveConfig(config);
|
|
1810
|
+
auditLog.log({ event: 'skybridge_vault_key_saved', provider });
|
|
1811
|
+
sendJson(res, 200, {
|
|
1812
|
+
ok: true,
|
|
1813
|
+
provider,
|
|
1814
|
+
configured: true,
|
|
1815
|
+
activeProvider: config.provider || 'unconfigured',
|
|
1816
|
+
activeModel: config.model || DEFAULT_MODEL_BY_PROVIDER[String(config.provider || '')] || 'default'
|
|
1817
|
+
});
|
|
1818
|
+
return;
|
|
1819
|
+
}
|
|
1820
|
+
if (req.method === 'GET' && pathname === '/api/commands') {
|
|
1821
|
+
const commands = listCommands('terminal').map((cmd) => ({
|
|
1822
|
+
name: cmd.name,
|
|
1823
|
+
aliases: cmd.aliases ?? [],
|
|
1824
|
+
usage: cmd.usage,
|
|
1825
|
+
description: cmd.description
|
|
1826
|
+
}));
|
|
1827
|
+
sendJson(res, 200, { ok: true, commands });
|
|
1828
|
+
return;
|
|
1829
|
+
}
|
|
1830
|
+
if (req.method === 'POST' && pathname === '/api/command') {
|
|
1831
|
+
const body = await readJsonBody(req);
|
|
1832
|
+
let cmdName = '';
|
|
1833
|
+
let cmdArgv = [];
|
|
1834
|
+
if (typeof body.input === 'string' && body.input.trim()) {
|
|
1835
|
+
const rawLine = body.input.trim().startsWith('/') ? body.input.trim() : `/${body.input.trim()}`;
|
|
1836
|
+
const parsed = parseCommand(rawLine);
|
|
1837
|
+
if (!parsed) {
|
|
1838
|
+
sendJson(res, 400, { error: 'Invalid CLI slash command syntax.' });
|
|
1839
|
+
return;
|
|
1840
|
+
}
|
|
1841
|
+
cmdName = parsed.name;
|
|
1842
|
+
cmdArgv = parsed.argv;
|
|
1843
|
+
}
|
|
1844
|
+
else if (typeof body.name === 'string' && body.name.trim()) {
|
|
1845
|
+
cmdName = body.name.trim().toLowerCase();
|
|
1846
|
+
cmdArgv = Array.isArray(body.argv) ? body.argv.map((x) => String(x ?? '')) : [];
|
|
1847
|
+
}
|
|
1848
|
+
else {
|
|
1849
|
+
sendJson(res, 400, { error: 'Command input or name is required.' });
|
|
1850
|
+
return;
|
|
1851
|
+
}
|
|
1852
|
+
if (cmdName === 'exit' || cmdName === 'quit') {
|
|
1853
|
+
sendJson(res, 200, {
|
|
1854
|
+
ok: true,
|
|
1855
|
+
command: cmdName,
|
|
1856
|
+
title: 'Exit',
|
|
1857
|
+
output: 'Press Ctrl+C in the terminal running `causyne web` to stop the local Skybridge server cleanly.'
|
|
1858
|
+
});
|
|
1859
|
+
return;
|
|
1860
|
+
}
|
|
1861
|
+
const prevCwd = process.cwd();
|
|
1862
|
+
let result;
|
|
1863
|
+
try {
|
|
1864
|
+
if (prevCwd !== workspaceRoot)
|
|
1865
|
+
process.chdir(workspaceRoot);
|
|
1866
|
+
result = await runCommand(cmdName, cmdArgv, {
|
|
1867
|
+
surface: 'terminal',
|
|
1868
|
+
workspaceRoot,
|
|
1869
|
+
cwd: workspaceRoot
|
|
1870
|
+
});
|
|
1871
|
+
}
|
|
1872
|
+
finally {
|
|
1873
|
+
try {
|
|
1874
|
+
if (process.cwd() !== prevCwd)
|
|
1875
|
+
process.chdir(prevCwd);
|
|
1876
|
+
}
|
|
1877
|
+
catch { /* ignore */ }
|
|
1878
|
+
}
|
|
1879
|
+
auditLog.log({ event: 'skybridge_cli_command', command: cmdName, ok: Boolean(result.ok) });
|
|
1880
|
+
sendJson(res, 200, {
|
|
1881
|
+
ok: Boolean(result.ok),
|
|
1882
|
+
command: cmdName,
|
|
1883
|
+
title: typeof result.title === 'string' ? result.title : `/${cmdName}`,
|
|
1884
|
+
effect: typeof result.effect === 'string' ? result.effect : null,
|
|
1885
|
+
output: redactProviderSecrets(String(result.output || ''))
|
|
1886
|
+
});
|
|
1887
|
+
return;
|
|
1888
|
+
}
|
|
1889
|
+
if (req.method === 'GET' && pathname === '/api/cli/overview') {
|
|
1890
|
+
const checkpoints = listGroups(12).map((g) => ({
|
|
1891
|
+
id: g.taskId,
|
|
1892
|
+
createdAt: g.ts,
|
|
1893
|
+
label: g.prompt || g.taskId,
|
|
1894
|
+
fileCount: Array.isArray(g.fileEntries) ? g.fileEntries.length : 0
|
|
1895
|
+
}));
|
|
1896
|
+
const skills = listCompiledSkills();
|
|
1897
|
+
const mcpServers = serverStatus().map((s) => ({
|
|
1898
|
+
name: s.name,
|
|
1899
|
+
connected: Boolean(s.connected),
|
|
1900
|
+
granted: Boolean(s.granted),
|
|
1901
|
+
toolsCount: typeof s.toolsCount === 'number' ? s.toolsCount : 0
|
|
1902
|
+
}));
|
|
1903
|
+
const peers = listAllPeers().map((p) => ({
|
|
1904
|
+
name: p.id,
|
|
1905
|
+
label: p.label,
|
|
1906
|
+
command: p.command
|
|
1907
|
+
}));
|
|
1908
|
+
const tasks = backgroundTaskManager.list().slice(0, 20).map((t) => ({
|
|
1909
|
+
id: t.taskId,
|
|
1910
|
+
label: t.label,
|
|
1911
|
+
command: t.command,
|
|
1912
|
+
status: t.status,
|
|
1913
|
+
startedAt: t.startedAt
|
|
1914
|
+
}));
|
|
1915
|
+
let worktrees = [];
|
|
1916
|
+
try {
|
|
1917
|
+
worktrees = listWorktrees(workspaceRoot).map((w) => ({
|
|
1918
|
+
path: w.path,
|
|
1919
|
+
branch: w.branch || 'detached',
|
|
1920
|
+
managed: Boolean(w.managed)
|
|
1921
|
+
}));
|
|
1922
|
+
}
|
|
1923
|
+
catch {
|
|
1924
|
+
worktrees = [];
|
|
1925
|
+
}
|
|
1926
|
+
sendJson(res, 200, {
|
|
1927
|
+
ok: true,
|
|
1928
|
+
commandsCount: listCommands('terminal').length,
|
|
1929
|
+
skillsCount: skills.length,
|
|
1930
|
+
checkpoints,
|
|
1931
|
+
mcpServers,
|
|
1932
|
+
peers,
|
|
1933
|
+
tasks,
|
|
1934
|
+
worktrees,
|
|
1935
|
+
browserActive: causyneBrowser({ workspace: workspaceRoot }).isActive(),
|
|
1936
|
+
browserControlOwner
|
|
1937
|
+
});
|
|
1938
|
+
return;
|
|
1939
|
+
}
|
|
1940
|
+
if (req.method === 'GET' && pathname === '/api/mcp/browser') {
|
|
1941
|
+
res.statusCode = 405;
|
|
1942
|
+
res.setHeader('Allow', 'POST');
|
|
1943
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
1944
|
+
res.end(JSON.stringify({ error: 'Use POST for Streamable HTTP MCP JSON-RPC requests.' }));
|
|
1945
|
+
return;
|
|
1946
|
+
}
|
|
1947
|
+
if (req.method === 'POST' && pathname === '/api/mcp/browser') {
|
|
1948
|
+
const body = await readJsonBody(req);
|
|
1949
|
+
const reply = await handleBrowserMcpRpc(body, {
|
|
1950
|
+
workspaceRoot,
|
|
1951
|
+
version,
|
|
1952
|
+
onActivity: (activity) => {
|
|
1953
|
+
if (activity.phase === 'start') {
|
|
1954
|
+
browserControlOwner = 'agent';
|
|
1955
|
+
browserAgentActivity = {
|
|
1956
|
+
active: true,
|
|
1957
|
+
tool: activity.tool,
|
|
1958
|
+
detail: activity.detail,
|
|
1959
|
+
updatedAt: Date.now()
|
|
1960
|
+
};
|
|
1961
|
+
}
|
|
1962
|
+
else {
|
|
1963
|
+
browserAgentActivity = { active: false, tool: '', detail: '', updatedAt: Date.now() };
|
|
1964
|
+
}
|
|
1965
|
+
broadcastBrowserNotice({
|
|
1966
|
+
type: 'agent_activity',
|
|
1967
|
+
controlOwner: browserControlOwner,
|
|
1968
|
+
agentActivity: browserAgentActivity
|
|
1969
|
+
});
|
|
1970
|
+
}
|
|
1971
|
+
});
|
|
1972
|
+
if (reply === null) {
|
|
1973
|
+
res.statusCode = 202;
|
|
1974
|
+
res.end();
|
|
1975
|
+
return;
|
|
1976
|
+
}
|
|
1977
|
+
sendJson(res, 200, reply);
|
|
1978
|
+
return;
|
|
1979
|
+
}
|
|
1980
|
+
if (req.method === 'GET' && pathname === '/api/browser/state') {
|
|
1981
|
+
const ensure = parsedUrl.searchParams.get('ensure') === '1';
|
|
1982
|
+
const browser = causyneBrowser({ workspace: workspaceRoot });
|
|
1983
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: ensure });
|
|
1984
|
+
sendJson(res, 200, {
|
|
1985
|
+
ok: true,
|
|
1986
|
+
controlOwner: browserControlOwner,
|
|
1987
|
+
agentActivity: browserAgentActivity,
|
|
1988
|
+
computerUsePolicy: 'tiered-approval',
|
|
1989
|
+
...frame
|
|
1990
|
+
});
|
|
1991
|
+
return;
|
|
1992
|
+
}
|
|
1993
|
+
if (req.method === 'GET' && pathname === '/api/browser/stream') {
|
|
1994
|
+
const browser = causyneBrowser({ workspace: workspaceRoot });
|
|
1995
|
+
res.statusCode = 200;
|
|
1996
|
+
res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
|
|
1997
|
+
res.setHeader('Transfer-Encoding', 'chunked');
|
|
1998
|
+
res.setHeader('X-Accel-Buffering', 'no');
|
|
1999
|
+
const writeStreamLine = (payload) => {
|
|
2000
|
+
if (res.writableEnded || res.destroyed)
|
|
2001
|
+
return;
|
|
2002
|
+
try {
|
|
2003
|
+
res.write(`${JSON.stringify(payload)}\n`);
|
|
2004
|
+
}
|
|
2005
|
+
catch {
|
|
2006
|
+
// Stream closed mid-write.
|
|
2007
|
+
}
|
|
2008
|
+
};
|
|
2009
|
+
const unsub = browser.subscribeLiveStream((ev) => {
|
|
2010
|
+
writeStreamLine({
|
|
2011
|
+
...ev,
|
|
2012
|
+
controlOwner: browserControlOwner,
|
|
2013
|
+
agentActivity: browserAgentActivity,
|
|
2014
|
+
computerUsePolicy: 'tiered-approval'
|
|
2015
|
+
});
|
|
2016
|
+
});
|
|
2017
|
+
browserStreamClients.add(writeStreamLine);
|
|
2018
|
+
writeStreamLine({
|
|
2019
|
+
type: 'agent_activity',
|
|
2020
|
+
controlOwner: browserControlOwner,
|
|
2021
|
+
agentActivity: browserAgentActivity,
|
|
2022
|
+
computerUsePolicy: 'tiered-approval'
|
|
2023
|
+
});
|
|
2024
|
+
const keepAlive = setInterval(() => {
|
|
2025
|
+
writeStreamLine({ type: 'ping', ts: Date.now() });
|
|
2026
|
+
}, 15_000);
|
|
2027
|
+
keepAlive.unref?.();
|
|
2028
|
+
const cleanup = () => {
|
|
2029
|
+
clearInterval(keepAlive);
|
|
2030
|
+
browserStreamClients.delete(writeStreamLine);
|
|
2031
|
+
unsub();
|
|
2032
|
+
};
|
|
2033
|
+
req.on('close', cleanup);
|
|
2034
|
+
res.on('close', cleanup);
|
|
2035
|
+
return;
|
|
2036
|
+
}
|
|
2037
|
+
if (req.method === 'POST' && pathname === '/api/browser/input') {
|
|
2038
|
+
const body = await readJsonBody(req);
|
|
2039
|
+
const kind = typeof body.kind === 'string' ? body.kind.trim() : '';
|
|
2040
|
+
const allowedKinds = new Set([
|
|
2041
|
+
'click', 'dblclick', 'contextmenu', 'mousedown', 'mousemove', 'mouseup', 'wheel', 'type', 'key', 'paste'
|
|
2042
|
+
]);
|
|
2043
|
+
if (!allowedKinds.has(kind)) {
|
|
2044
|
+
sendJson(res, 400, { error: 'Unsupported live browser input kind.' });
|
|
2045
|
+
return;
|
|
2046
|
+
}
|
|
2047
|
+
browserControlOwner = 'human';
|
|
2048
|
+
const browser = causyneBrowser({ workspace: workspaceRoot });
|
|
2049
|
+
const result = await browser.dispatchLiveInput({
|
|
2050
|
+
kind: kind,
|
|
2051
|
+
x: typeof body.x === 'number' ? body.x : undefined,
|
|
2052
|
+
y: typeof body.y === 'number' ? body.y : undefined,
|
|
2053
|
+
deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
|
|
2054
|
+
deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
|
|
2055
|
+
text: typeof body.text === 'string' ? body.text : undefined,
|
|
2056
|
+
key: typeof body.key === 'string' ? body.key : undefined,
|
|
2057
|
+
button: body.button === 'right' || body.button === 'middle' ? body.button : 'left',
|
|
2058
|
+
skipFrame: true
|
|
2059
|
+
});
|
|
2060
|
+
sendJson(res, 200, { ok: result.ok, controlOwner: browserControlOwner });
|
|
2061
|
+
return;
|
|
2062
|
+
}
|
|
2063
|
+
if (req.method === 'POST' && pathname === '/api/browser/action') {
|
|
2064
|
+
const body = await readJsonBody(req);
|
|
2065
|
+
const action = typeof body.action === 'string' ? body.action.trim() : '';
|
|
2066
|
+
const browser = causyneBrowser({ workspace: workspaceRoot });
|
|
2067
|
+
if (action === 'setMode') {
|
|
2068
|
+
browserControlOwner = 'human';
|
|
2069
|
+
const rawPref = typeof body.enginePreference === 'string' ? body.enginePreference.trim() : '';
|
|
2070
|
+
const enginePreference = rawPref === 'camoufox'
|
|
2071
|
+
|| rawPref === 'chromium'
|
|
2072
|
+
|| rawPref === 'auto'
|
|
2073
|
+
? rawPref
|
|
2074
|
+
: undefined;
|
|
2075
|
+
const frame = await browser.setDisplayMode({
|
|
2076
|
+
visible: typeof body.visible === 'boolean' ? body.visible : undefined,
|
|
2077
|
+
enginePreference,
|
|
2078
|
+
ensureStarted: body.ensureStarted === true
|
|
2079
|
+
});
|
|
2080
|
+
auditLog.log({
|
|
2081
|
+
event: 'skybridge_browser_mode_switch',
|
|
2082
|
+
visible: frame.visible,
|
|
2083
|
+
engine: frame.engine,
|
|
2084
|
+
enginePreference: frame.enginePreference
|
|
2085
|
+
});
|
|
2086
|
+
broadcastBrowserNotice({
|
|
2087
|
+
type: 'meta',
|
|
2088
|
+
controlOwner: browserControlOwner,
|
|
2089
|
+
agentActivity: browserAgentActivity,
|
|
2090
|
+
...frame
|
|
2091
|
+
});
|
|
2092
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
|
|
2093
|
+
return;
|
|
2094
|
+
}
|
|
2095
|
+
if (action === 'takeControl') {
|
|
2096
|
+
browserControlOwner = 'human';
|
|
2097
|
+
browserAgentActivity = { active: false, tool: '', detail: '', updatedAt: Date.now() };
|
|
2098
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: false });
|
|
2099
|
+
broadcastBrowserNotice({ type: 'agent_activity', controlOwner: browserControlOwner, agentActivity: browserAgentActivity });
|
|
2100
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
|
|
2101
|
+
return;
|
|
2102
|
+
}
|
|
2103
|
+
if (action === 'handToAgent') {
|
|
2104
|
+
browserControlOwner = 'agent';
|
|
2105
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: false });
|
|
2106
|
+
broadcastBrowserNotice({ type: 'agent_activity', controlOwner: browserControlOwner, agentActivity: browserAgentActivity });
|
|
2107
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
|
|
2108
|
+
return;
|
|
2109
|
+
}
|
|
2110
|
+
if (action === 'start') {
|
|
2111
|
+
browserControlOwner = 'human';
|
|
2112
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: true });
|
|
2113
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
|
|
2114
|
+
return;
|
|
2115
|
+
}
|
|
2116
|
+
if (action === 'close') {
|
|
2117
|
+
await browser.close();
|
|
2118
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: false });
|
|
2119
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
|
|
2120
|
+
return;
|
|
2121
|
+
}
|
|
2122
|
+
if (action === 'goto' || action === 'newTab') {
|
|
2123
|
+
browserControlOwner = 'human';
|
|
2124
|
+
let rawUrl = typeof body.url === 'string' ? body.url.trim() : '';
|
|
2125
|
+
if (rawUrl.startsWith('@')) {
|
|
2126
|
+
const idx = rawUrl.indexOf(' ');
|
|
2127
|
+
const macro = idx === -1 ? rawUrl : rawUrl.slice(0, idx);
|
|
2128
|
+
const q = idx === -1 ? '' : rawUrl.slice(idx + 1).trim();
|
|
2129
|
+
const expanded = expandSearchMacro(macro, q);
|
|
2130
|
+
if (!expanded) {
|
|
2131
|
+
sendJson(res, 400, { error: 'Unsupported browser search macro.' });
|
|
2132
|
+
return;
|
|
2133
|
+
}
|
|
2134
|
+
rawUrl = expanded;
|
|
2135
|
+
}
|
|
2136
|
+
else if (rawUrl && !/^https?:\/\//i.test(rawUrl)) {
|
|
2137
|
+
rawUrl = rawUrl.includes('.') || rawUrl.startsWith('localhost')
|
|
2138
|
+
? `https://${rawUrl}`
|
|
2139
|
+
: (expandSearchMacro('@duckduckgo_search', rawUrl) || `https://duckduckgo.com/?q=${encodeURIComponent(rawUrl)}`);
|
|
2140
|
+
}
|
|
2141
|
+
await browser.run([action === 'newTab' ? { type: 'newTab', ...(rawUrl ? { url: rawUrl } : {}) } : { type: 'goto', url: rawUrl || 'about:blank' }], { workspace: workspaceRoot });
|
|
2142
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: true });
|
|
2143
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
|
|
2144
|
+
return;
|
|
2145
|
+
}
|
|
2146
|
+
if (action === 'back' || action === 'forward' || action === 'reload') {
|
|
2147
|
+
browserControlOwner = 'human';
|
|
2148
|
+
await browser.run([{ type: action }], { workspace: workspaceRoot });
|
|
2149
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: true });
|
|
2150
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
|
|
2151
|
+
return;
|
|
2152
|
+
}
|
|
2153
|
+
if ((action === 'switchTab' || action === 'closeTab') && typeof body.tabId === 'string' && body.tabId.trim()) {
|
|
2154
|
+
browserControlOwner = 'human';
|
|
2155
|
+
await browser.run([{ type: action, tabId: body.tabId.trim() }], { workspace: workspaceRoot });
|
|
2156
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: true });
|
|
2157
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
|
|
2158
|
+
return;
|
|
2159
|
+
}
|
|
2160
|
+
if (action === 'viewport') {
|
|
2161
|
+
const width = Math.max(320, Math.min(1920, Number(body.width) || 1280));
|
|
2162
|
+
const height = Math.max(480, Math.min(1200, Number(body.height) || 800));
|
|
2163
|
+
await browser.run([{ type: 'viewport', width, height }], { workspace: workspaceRoot });
|
|
2164
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: true });
|
|
2165
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, ...frame });
|
|
2166
|
+
return;
|
|
2167
|
+
}
|
|
2168
|
+
if (action === 'snapshot') {
|
|
2169
|
+
const snap = await browser.snapshot(0);
|
|
2170
|
+
const frame = await browser.captureLiveFrame({ ensureStarted: true });
|
|
2171
|
+
sendJson(res, 200, {
|
|
2172
|
+
ok: true,
|
|
2173
|
+
controlOwner: browserControlOwner,
|
|
2174
|
+
snapshot: snap.text,
|
|
2175
|
+
refsCount: snap.refsCount,
|
|
2176
|
+
...frame
|
|
2177
|
+
});
|
|
2178
|
+
return;
|
|
2179
|
+
}
|
|
2180
|
+
if (action === 'click'
|
|
2181
|
+
|| action === 'dblclick'
|
|
2182
|
+
|| action === 'contextmenu'
|
|
2183
|
+
|| action === 'mousedown'
|
|
2184
|
+
|| action === 'mousemove'
|
|
2185
|
+
|| action === 'mouseup'
|
|
2186
|
+
|| action === 'wheel'
|
|
2187
|
+
|| action === 'type'
|
|
2188
|
+
|| action === 'key'
|
|
2189
|
+
|| action === 'paste') {
|
|
2190
|
+
browserControlOwner = 'human';
|
|
2191
|
+
const frame = await browser.interactAt({
|
|
2192
|
+
kind: action,
|
|
2193
|
+
x: typeof body.x === 'number' ? body.x : undefined,
|
|
2194
|
+
y: typeof body.y === 'number' ? body.y : undefined,
|
|
2195
|
+
deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
|
|
2196
|
+
deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
|
|
2197
|
+
text: typeof body.text === 'string' ? body.text : undefined,
|
|
2198
|
+
key: typeof body.key === 'string' ? body.key : undefined,
|
|
2199
|
+
button: body.button === 'right' || body.button === 'middle' ? body.button : 'left'
|
|
2200
|
+
});
|
|
2201
|
+
sendJson(res, 200, { ok: true, controlOwner: browserControlOwner, agentActivity: browserAgentActivity, ...frame });
|
|
2202
|
+
return;
|
|
2203
|
+
}
|
|
2204
|
+
sendJson(res, 400, { error: 'Unsupported shared browser action.' });
|
|
2205
|
+
return;
|
|
2206
|
+
}
|
|
2207
|
+
if (req.method === 'GET' && pathname === '/api/browser/cdp/tabs') {
|
|
2208
|
+
const portParam = parsedUrl.searchParams.get('port') || '9222';
|
|
2209
|
+
const discovered = await discoverLocalCdpTabs(portParam);
|
|
2210
|
+
sendJson(res, 200, {
|
|
2211
|
+
ok: true,
|
|
2212
|
+
port: discovered.port,
|
|
2213
|
+
tabs: discovered.tabs.map((t) => ({ id: t.id, title: t.title, url: t.url }))
|
|
2214
|
+
});
|
|
2215
|
+
return;
|
|
2216
|
+
}
|
|
2217
|
+
if (req.method === 'POST' && pathname === '/api/browser/cdp/sync') {
|
|
2218
|
+
const body = await readJsonBody(req);
|
|
2219
|
+
const targetId = typeof body.targetId === 'string' ? body.targetId.trim() : '';
|
|
2220
|
+
if (!targetId) {
|
|
2221
|
+
sendJson(res, 400, { error: 'targetId is required to sync a local browser tab.' });
|
|
2222
|
+
return;
|
|
2223
|
+
}
|
|
2224
|
+
const synced = await syncLocalCdpTabToCausyne({
|
|
2225
|
+
workspaceRoot,
|
|
2226
|
+
port: body.port ?? 9222,
|
|
2227
|
+
targetId,
|
|
2228
|
+
includeCookies: body.includeCookies === true
|
|
2229
|
+
});
|
|
2230
|
+
browserControlOwner = 'human';
|
|
2231
|
+
auditLog.log({
|
|
2232
|
+
event: 'skybridge_browser_cdp_sync',
|
|
2233
|
+
importedCookies: synced.importedCookies
|
|
2234
|
+
});
|
|
2235
|
+
sendJson(res, 200, {
|
|
2236
|
+
ok: true,
|
|
2237
|
+
controlOwner: browserControlOwner,
|
|
2238
|
+
syncedUrl: synced.syncedUrl,
|
|
2239
|
+
importedCookies: synced.importedCookies,
|
|
2240
|
+
...synced.frame
|
|
2241
|
+
});
|
|
2242
|
+
return;
|
|
2243
|
+
}
|
|
2244
|
+
if (req.method === 'POST' && pathname === '/api/browser/import') {
|
|
2245
|
+
const body = await readJsonBody(req);
|
|
2246
|
+
const rawText = typeof body.rawText === 'string' ? body.rawText : '';
|
|
2247
|
+
const summary = await importExplicitUserBrowserData({
|
|
2248
|
+
workspaceRoot,
|
|
2249
|
+
rawText,
|
|
2250
|
+
openFirstUrl: body.openFirstUrl !== false
|
|
2251
|
+
});
|
|
2252
|
+
const frame = await causyneBrowser({ workspace: workspaceRoot }).captureLiveFrame({ ensureStarted: false });
|
|
2253
|
+
auditLog.log({
|
|
2254
|
+
event: 'skybridge_browser_import',
|
|
2255
|
+
importedCookies: summary.importedCookies,
|
|
2256
|
+
urlsCount: summary.importedUrls.length
|
|
2257
|
+
});
|
|
2258
|
+
sendJson(res, 200, {
|
|
2259
|
+
ok: true,
|
|
2260
|
+
controlOwner: browserControlOwner,
|
|
2261
|
+
...summary,
|
|
2262
|
+
...frame
|
|
2263
|
+
});
|
|
2264
|
+
return;
|
|
2265
|
+
}
|
|
2266
|
+
if (req.method === 'POST' && pathname === '/api/approve') {
|
|
2267
|
+
const body = await readJsonBody(req);
|
|
2268
|
+
const toolCallId = typeof body.toolCallId === 'string' ? body.toolCallId.trim() : '';
|
|
2269
|
+
const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
|
|
2270
|
+
? body.sessionId.trim()
|
|
2271
|
+
: '';
|
|
2272
|
+
const approved = body.approved === true;
|
|
2273
|
+
const remember = body.remember === true;
|
|
2274
|
+
const toolName = typeof body.tool === 'string' ? body.tool.trim().slice(0, 80) : '';
|
|
2275
|
+
const targetRun = findActiveRun(sessionId || null);
|
|
2276
|
+
if (!toolCallId || !targetRun?.loop.resolveApproval) {
|
|
2277
|
+
sendJson(res, 400, { error: 'No active pending approval matches that toolCallId.' });
|
|
2278
|
+
return;
|
|
2279
|
+
}
|
|
2280
|
+
if (approved && remember && toolName && targetRun.loop.grantAlways) {
|
|
2281
|
+
targetRun.loop.grantAlways(toolName);
|
|
2282
|
+
auditLog.log({ event: 'skybridge_approval_grant_always', tool: toolName });
|
|
2283
|
+
}
|
|
2284
|
+
targetRun.status = 'running';
|
|
2285
|
+
targetRun.loop.resolveApproval(toolCallId, approved);
|
|
2286
|
+
sendJson(res, 200, { ok: true, toolCallId, approved, remembered: Boolean(approved && remember && toolName) });
|
|
2287
|
+
return;
|
|
2288
|
+
}
|
|
2289
|
+
if (req.method === 'POST' && pathname === '/api/decision') {
|
|
2290
|
+
const body = await readJsonBody(req);
|
|
2291
|
+
const requestId = typeof body.requestId === 'string' ? body.requestId.trim() : '';
|
|
2292
|
+
const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
|
|
2293
|
+
? body.sessionId.trim()
|
|
2294
|
+
: '';
|
|
2295
|
+
const label = typeof body.label === 'string' ? body.label.trim().slice(0, 400) : '';
|
|
2296
|
+
const optionId = typeof body.optionId === 'string' ? body.optionId.trim().slice(0, 120) : null;
|
|
2297
|
+
const custom = body.custom === true;
|
|
2298
|
+
const targetRun = findActiveRun(sessionId || null);
|
|
2299
|
+
if (!requestId || !targetRun?.loop.resolveDecision) {
|
|
2300
|
+
sendJson(res, 400, { error: 'No active pending decision matches that requestId.' });
|
|
2301
|
+
return;
|
|
2302
|
+
}
|
|
2303
|
+
targetRun.status = 'running';
|
|
2304
|
+
targetRun.loop.resolveDecision(requestId, label ? { optionId, label, custom } : null);
|
|
2305
|
+
sendJson(res, 200, { ok: true, requestId, label });
|
|
2306
|
+
return;
|
|
2307
|
+
}
|
|
2308
|
+
if (req.method === 'POST' && pathname === '/api/stop') {
|
|
2309
|
+
let stopSessionId = '';
|
|
2310
|
+
try {
|
|
2311
|
+
const body = await readJsonBody(req);
|
|
2312
|
+
if (typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())) {
|
|
2313
|
+
stopSessionId = body.sessionId.trim();
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
catch {
|
|
2317
|
+
// Empty body is valid for /api/stop.
|
|
2318
|
+
}
|
|
2319
|
+
if (stopSessionId) {
|
|
2320
|
+
const run = activeRuns.get(stopSessionId);
|
|
2321
|
+
if (run) {
|
|
2322
|
+
run.userStopped = true;
|
|
2323
|
+
run.loop.abort?.();
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
else {
|
|
2327
|
+
for (const run of activeRuns.values()) {
|
|
2328
|
+
run.userStopped = true;
|
|
2329
|
+
run.loop.abort?.();
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
sendJson(res, 200, { ok: true });
|
|
2333
|
+
return;
|
|
2334
|
+
}
|
|
2335
|
+
if (req.method === 'POST' && pathname === '/api/chat') {
|
|
2336
|
+
const body = await readJsonBody(req);
|
|
2337
|
+
const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
|
|
2338
|
+
const rawMode = typeof body.mode === 'string' ? body.mode.trim().toUpperCase() : 'B';
|
|
2339
|
+
const mode = rawMode === 'A' || rawMode === 'B' || rawMode === 'C' ? rawMode : 'B';
|
|
2340
|
+
const requestedSessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
|
|
2341
|
+
? body.sessionId.trim()
|
|
2342
|
+
: '';
|
|
2343
|
+
const providerOverride = typeof body.provider === 'string' && SAFE_PROVIDER_RE.test(body.provider.trim())
|
|
2344
|
+
? body.provider.trim()
|
|
2345
|
+
: undefined;
|
|
2346
|
+
const modelOverride = typeof body.model === 'string' && SAFE_MODEL_RE.test(body.model.trim())
|
|
2347
|
+
? body.model.trim()
|
|
2348
|
+
: undefined;
|
|
2349
|
+
if (!prompt) {
|
|
2350
|
+
sendJson(res, 400, { error: 'Prompt text is required.' });
|
|
2351
|
+
return;
|
|
2352
|
+
}
|
|
2353
|
+
let boundSession = requestedSessionId ? getSession(requestedSessionId) : null;
|
|
2354
|
+
if (boundSession && !workspaceMatchesSession(boundSession.workspace, workspaceRoot)) {
|
|
2355
|
+
boundSession = null;
|
|
2356
|
+
}
|
|
2357
|
+
if (!boundSession && !hasCustomFactory) {
|
|
2358
|
+
boundSession = createSession(workspaceRoot, prompt.slice(0, 60), false);
|
|
2359
|
+
}
|
|
2360
|
+
const runKey = boundSession?.id || '__ephemeral__';
|
|
2361
|
+
const existingRun = activeRuns.get(runKey);
|
|
2362
|
+
if (existingRun && (existingRun.status === 'running' || existingRun.status === 'awaiting_client')) {
|
|
2363
|
+
sendJson(res, 409, {
|
|
2364
|
+
error: 'This conversation already has a task running. Stop it or wait for completion.'
|
|
2365
|
+
});
|
|
2366
|
+
return;
|
|
2367
|
+
}
|
|
2368
|
+
const { effectivePrompt, attachedPaths } = buildWorkspacePromptWithAttachments(workspaceRoot, prompt, body.attachments);
|
|
2369
|
+
const taskId = `web-${++taskCounter}-${Date.now()}`;
|
|
2370
|
+
let collectedAssistantText = '';
|
|
2371
|
+
let runRef = null;
|
|
2372
|
+
const emitFrame = (raw) => {
|
|
2373
|
+
const clean = raw.replace(/\r?\n/g, ' ');
|
|
2374
|
+
try {
|
|
2375
|
+
const parsed = JSON.parse(clean);
|
|
2376
|
+
if (parsed.type === 'agent_chunk' && typeof parsed.delta === 'string') {
|
|
2377
|
+
collectedAssistantText += parsed.delta;
|
|
2378
|
+
}
|
|
2379
|
+
else if (parsed.type === 'agent_message' && typeof parsed.content === 'string' && !collectedAssistantText) {
|
|
2380
|
+
collectedAssistantText = parsed.content;
|
|
2381
|
+
}
|
|
2382
|
+
if (runRef && (parsed.type === 'approval_request' || parsed.type === 'decision_request')) {
|
|
2383
|
+
runRef.status = 'awaiting_client';
|
|
2384
|
+
}
|
|
2385
|
+
const toolLower = typeof parsed.tool === 'string' ? parsed.tool.toLowerCase() : '';
|
|
2386
|
+
const actionLower = typeof parsed.actionName === 'string' ? parsed.actionName.toLowerCase() : '';
|
|
2387
|
+
if (boundSession?.id) {
|
|
2388
|
+
if (parsed.type === 'code_progress' && typeof parsed.path === 'string') {
|
|
2389
|
+
recordSessionTouchedFile(boundSession.id, parsed.path);
|
|
2390
|
+
}
|
|
2391
|
+
else if ((parsed.type === 'step_complete' || parsed.type === 'tool_result')
|
|
2392
|
+
&& MUTATING_FILE_TOOLS.has(toolLower)
|
|
2393
|
+
&& parsed.args) {
|
|
2394
|
+
for (const key of ['path', 'filePath', 'file_path', 'targetFile', 'filename', 'file', 'destination']) {
|
|
2395
|
+
recordSessionTouchedFile(boundSession.id, parsed.args[key]);
|
|
2396
|
+
}
|
|
2397
|
+
}
|
|
2398
|
+
else if (parsed.type === 'notice' && MUTATING_FILE_TOOLS.has(actionLower) && parsed.detail) {
|
|
2399
|
+
recordSessionTouchedFile(boundSession.id, parsed.detail);
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
const isBrowserTool = toolLower.includes('browser');
|
|
2403
|
+
const isComputerTool = toolLower.includes('computer_use') || toolLower.includes('desktop_act');
|
|
2404
|
+
if ((parsed.type === 'step_start' || parsed.type === 'tool_start') && (isBrowserTool || isComputerTool)) {
|
|
2405
|
+
if (isBrowserTool)
|
|
2406
|
+
browserControlOwner = 'agent';
|
|
2407
|
+
const detail = isBrowserTool && Array.isArray(parsed.args?.actions) && parsed.args.actions[0]
|
|
2408
|
+
? String(parsed.args.actions[0].type || 'browser.act')
|
|
2409
|
+
: String(parsed.args?.action || parsed.tool || '');
|
|
2410
|
+
browserAgentActivity = {
|
|
2411
|
+
active: true,
|
|
2412
|
+
tool: parsed.tool || 'browser.act',
|
|
2413
|
+
detail: detail.slice(0, 80),
|
|
2414
|
+
updatedAt: Date.now()
|
|
2415
|
+
};
|
|
2416
|
+
broadcastBrowserNotice({
|
|
2417
|
+
type: 'agent_activity',
|
|
2418
|
+
controlOwner: browserControlOwner,
|
|
2419
|
+
agentActivity: browserAgentActivity
|
|
2420
|
+
});
|
|
2421
|
+
}
|
|
2422
|
+
else if ((parsed.type === 'step_complete' || parsed.type === 'step_error' || parsed.type === 'tool_complete')
|
|
2423
|
+
&& (isBrowserTool || isComputerTool)) {
|
|
2424
|
+
browserAgentActivity = { active: false, tool: '', detail: '', updatedAt: Date.now() };
|
|
2425
|
+
broadcastBrowserNotice({
|
|
2426
|
+
type: 'agent_activity',
|
|
2427
|
+
controlOwner: browserControlOwner,
|
|
2428
|
+
agentActivity: browserAgentActivity
|
|
2429
|
+
});
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
catch {
|
|
2433
|
+
// pass raw frame through untouched
|
|
2434
|
+
}
|
|
2435
|
+
if (runRef)
|
|
2436
|
+
pushRunFrame(runRef, clean);
|
|
2437
|
+
};
|
|
2438
|
+
const wrappedSink = { readyState: 1, send: emitFrame };
|
|
2439
|
+
const loop = loopFactory(wrappedSink, taskId, effectivePrompt, {
|
|
2440
|
+
workspaceRoot,
|
|
2441
|
+
mode,
|
|
2442
|
+
sessionId: boundSession?.id,
|
|
2443
|
+
provider: providerOverride,
|
|
2444
|
+
model: modelOverride
|
|
2445
|
+
});
|
|
2446
|
+
const run = {
|
|
2447
|
+
key: runKey,
|
|
2448
|
+
sessionId: boundSession?.id || null,
|
|
2449
|
+
taskId,
|
|
2450
|
+
prompt,
|
|
2451
|
+
startedAt: Date.now(),
|
|
2452
|
+
status: 'running',
|
|
2453
|
+
userStopped: false,
|
|
2454
|
+
loop,
|
|
2455
|
+
frames: [],
|
|
2456
|
+
bufferedBytes: 0,
|
|
2457
|
+
subscribers: new Set(),
|
|
2458
|
+
doneSubscribers: new Set()
|
|
2459
|
+
};
|
|
2460
|
+
runRef = run;
|
|
2461
|
+
activeRuns.set(runKey, run);
|
|
2462
|
+
if (boundSession) {
|
|
2463
|
+
pushRunFrame(run, JSON.stringify({
|
|
2464
|
+
type: 'session_bound',
|
|
2465
|
+
sessionId: boundSession.id,
|
|
2466
|
+
title: boundSession.title,
|
|
2467
|
+
attachments: attachedPaths
|
|
2468
|
+
}));
|
|
2469
|
+
}
|
|
2470
|
+
// Attach current HTTP response BEFORE starting loop; detaching later never aborts loop.
|
|
2471
|
+
attachRunStream(req, res, run, true);
|
|
2472
|
+
void (async () => {
|
|
2473
|
+
try {
|
|
2474
|
+
await loop.run();
|
|
2475
|
+
if (boundSession && hasCustomFactory && collectedAssistantText.trim()) {
|
|
2476
|
+
const latest = getSession(boundSession.id);
|
|
2477
|
+
if (latest) {
|
|
2478
|
+
const nextMessages = [
|
|
2479
|
+
...latest.messages,
|
|
2480
|
+
{ role: 'user', content: prompt },
|
|
2481
|
+
{ role: 'assistant', content: collectedAssistantText.trim() }
|
|
2482
|
+
];
|
|
2483
|
+
saveSessionMessages(boundSession.id, nextMessages);
|
|
2484
|
+
}
|
|
2485
|
+
}
|
|
2486
|
+
const refreshed = boundSession ? getSession(boundSession.id) : null;
|
|
2487
|
+
if (run.userStopped) {
|
|
2488
|
+
run.status = 'stopped';
|
|
2489
|
+
pushRunFrame(run, JSON.stringify({
|
|
2490
|
+
type: 'stopped',
|
|
2491
|
+
taskId,
|
|
2492
|
+
sessionId: boundSession?.id || null,
|
|
2493
|
+
title: refreshed?.title || boundSession?.title || null,
|
|
2494
|
+
userStopped: true
|
|
2495
|
+
}));
|
|
2496
|
+
}
|
|
2497
|
+
else {
|
|
2498
|
+
run.status = 'completed';
|
|
2499
|
+
pushRunFrame(run, JSON.stringify({
|
|
2500
|
+
type: 'done',
|
|
2501
|
+
taskId,
|
|
2502
|
+
sessionId: boundSession?.id || null,
|
|
2503
|
+
title: refreshed?.title || boundSession?.title || null
|
|
2504
|
+
}));
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
catch (err) {
|
|
2508
|
+
run.status = run.userStopped ? 'stopped' : 'errored';
|
|
2509
|
+
if (run.userStopped) {
|
|
2510
|
+
pushRunFrame(run, JSON.stringify({
|
|
2511
|
+
type: 'stopped',
|
|
2512
|
+
taskId,
|
|
2513
|
+
sessionId: boundSession?.id || null,
|
|
2514
|
+
userStopped: true
|
|
2515
|
+
}));
|
|
2516
|
+
}
|
|
2517
|
+
else if (err instanceof EntitlementAccessError && err.code === 'DAILY_LIMIT_REACHED') {
|
|
2518
|
+
pushRunFrame(run, JSON.stringify({
|
|
2519
|
+
type: 'error',
|
|
2520
|
+
code: 'DAILY_LIMIT_REACHED',
|
|
2521
|
+
message: err.message || DAILY_LIMIT_SUPPORT_MESSAGE
|
|
2522
|
+
}));
|
|
2523
|
+
}
|
|
2524
|
+
else {
|
|
2525
|
+
auditLog.log({
|
|
2526
|
+
event: 'skybridge_chat_error',
|
|
2527
|
+
taskId,
|
|
2528
|
+
detail: redactProviderSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
|
|
2529
|
+
});
|
|
2530
|
+
pushRunFrame(run, JSON.stringify({
|
|
2531
|
+
type: 'error',
|
|
2532
|
+
message: 'Task failed. Inspect local audit log or run `/doctor --report` for sanitized details.'
|
|
2533
|
+
}));
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
finally {
|
|
2537
|
+
for (const doneCb of [...run.doneSubscribers]) {
|
|
2538
|
+
try {
|
|
2539
|
+
doneCb();
|
|
2540
|
+
}
|
|
2541
|
+
catch { /* ignore */ }
|
|
2542
|
+
}
|
|
2543
|
+
run.subscribers.clear();
|
|
2544
|
+
run.doneSubscribers.clear();
|
|
2545
|
+
if (activeRuns.get(runKey) === run) {
|
|
2546
|
+
activeRuns.delete(runKey);
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
})();
|
|
2550
|
+
return;
|
|
2551
|
+
}
|
|
2552
|
+
sendJson(res, 404, { error: 'Unknown Skybridge API endpoint.' });
|
|
2553
|
+
}
|
|
2554
|
+
catch (err) {
|
|
2555
|
+
const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
|
|
2556
|
+
const status = code === 'ENOENT' ? 404 : 400;
|
|
2557
|
+
auditLog.log({
|
|
2558
|
+
event: 'skybridge_request_error',
|
|
2559
|
+
path: pathname,
|
|
2560
|
+
status,
|
|
2561
|
+
detail: redactProviderSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
|
|
2562
|
+
});
|
|
2563
|
+
const safeError = status === 404
|
|
2564
|
+
? 'Requested workspace resource was not found.'
|
|
2565
|
+
: 'Skybridge request could not be processed.';
|
|
2566
|
+
if (!res.headersSent)
|
|
2567
|
+
sendJson(res, status, { error: safeError });
|
|
2568
|
+
else if (!res.writableEnded)
|
|
2569
|
+
res.end();
|
|
2570
|
+
}
|
|
2571
|
+
});
|
|
2572
|
+
// Disable Node's default 5-minute requestTimeout so long AgentLoop runs never drop mid-stream.
|
|
2573
|
+
server.requestTimeout = 0;
|
|
2574
|
+
server.timeout = 0;
|
|
2575
|
+
server.headersTimeout = 60_000;
|
|
2576
|
+
server.keepAliveTimeout = 65_000;
|
|
2577
|
+
await new Promise((resolve, reject) => {
|
|
2578
|
+
server.once('error', reject);
|
|
2579
|
+
server.listen(requestedPort, '127.0.0.1', () => {
|
|
2580
|
+
server.off('error', reject);
|
|
2581
|
+
const addr = server.address();
|
|
2582
|
+
boundPort = addr?.port ?? requestedPort;
|
|
2583
|
+
resolve();
|
|
2584
|
+
});
|
|
2585
|
+
});
|
|
2586
|
+
const origin = `http://127.0.0.1:${boundPort}`;
|
|
2587
|
+
const url = `${origin}/#token=${token}`;
|
|
2588
|
+
auditLog.log({ event: 'skybridge_started', port: boundPort, workspaceRoot });
|
|
2589
|
+
return {
|
|
2590
|
+
url,
|
|
2591
|
+
origin,
|
|
2592
|
+
port: boundPort,
|
|
2593
|
+
token,
|
|
2594
|
+
workspaceRoot,
|
|
2595
|
+
close: async () => {
|
|
2596
|
+
for (const run of activeRuns.values()) {
|
|
2597
|
+
run.userStopped = true;
|
|
2598
|
+
run.loop.abort?.();
|
|
2599
|
+
for (const doneCb of [...run.doneSubscribers]) {
|
|
2600
|
+
try {
|
|
2601
|
+
doneCb();
|
|
2602
|
+
}
|
|
2603
|
+
catch { /* ignore */ }
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
activeRuns.clear();
|
|
2607
|
+
await Promise.race([
|
|
2608
|
+
Promise.allSettled([
|
|
2609
|
+
Promise.resolve().then(() => closeAllMcpServers()),
|
|
2610
|
+
Promise.resolve().then(() => lspSessionManager.shutdownAll()),
|
|
2611
|
+
Promise.resolve().then(() => backgroundTaskManager.stopAll())
|
|
2612
|
+
]),
|
|
2613
|
+
new Promise((resolve) => {
|
|
2614
|
+
const timer = setTimeout(resolve, 2500);
|
|
2615
|
+
timer.unref?.();
|
|
2616
|
+
})
|
|
2617
|
+
]);
|
|
2618
|
+
server.closeAllConnections?.();
|
|
2619
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
2620
|
+
}
|
|
2621
|
+
};
|
|
2622
|
+
}
|