@causyne/agent 1.20.122 → 1.20.124
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/causyne.js +38 -15
- package/docs/SECURITY_REVIEW.md +42 -6
- package/package.json +5 -5
- package/src/acp/agentCatalog.js +74 -50
- package/src/acp/agentCatalog.ts +82 -49
- package/src/acp/client.js +309 -86
- package/src/acp/client.ts +291 -84
- package/src/acp/protocol.js +147 -3
- package/src/acp/protocol.ts +162 -3
- package/src/acp/server.js +138 -39
- package/src/acp/server.ts +122 -41
- package/src/agent/errorClassifier.js +42 -6
- package/src/agent/errorClassifier.ts +44 -5
- 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 +598 -217
- package/src/agentLoop.ts +621 -215
- package/src/approvalPolicy.js +28 -1
- package/src/approvalPolicy.ts +28 -1
- package/src/auditLog.js +641 -48
- package/src/auditLog.ts +661 -0
- package/src/autoUpdate.js +32 -5
- package/src/autoUpdate.ts +27 -5
- 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 +884 -10
- package/src/browser/causyneBrowser.ts +1042 -32
- package/src/browser/searchProviders.js +94 -6
- package/src/browser/searchProviders.ts +89 -6
- 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 +103 -1
- package/src/config.ts +110 -1
- package/src/configVault.js +29 -2
- package/src/configVault.ts +26 -2
- 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/sanitizer.js +23 -1
- package/src/continuum/sanitizer.ts +23 -1
- package/src/continuum/ui/continuumPicker.js +0 -2
- package/src/continuum/ui/continuumPicker.ts +0 -2
- package/src/continuum/ui/continuumPickerView.js +0 -2
- package/src/continuum/ui/continuumPickerView.ts +4 -20
- package/src/core/contextCompactor.js +88 -7
- package/src/core/contextCompactor.ts +87 -8
- package/src/creative/liveBridge.js +3 -2
- package/src/creative/liveBridge.ts +4 -2
- package/src/creative/studioScripts.js +1 -1
- package/src/creative/studioScripts.ts +1 -1
- package/src/decideTools.js +7 -2
- package/src/decideTools.ts +7 -2
- package/src/decisionPolicy.js +10 -2
- package/src/decisionPolicy.ts +10 -2
- 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/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/installer.js +60 -29
- package/src/engines/installer.ts +73 -22
- 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 +324 -13
- package/src/headlessCli.ts +321 -12
- package/src/hooks.js +247 -26
- package/src/hooks.ts +236 -26
- package/src/ignoreRules.js +297 -0
- package/src/ignoreRules.ts +308 -0
- package/src/implementationPlan.js +7 -6
- package/src/implementationPlan.ts +8 -6
- package/src/infra/atomicWriter.js +92 -19
- package/src/infra/atomicWriter.ts +108 -19
- package/src/launchIntent.js +13 -2
- package/src/launchIntent.ts +13 -2
- 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.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/modelVariants.js +600 -0
- package/src/modelVariants.ts +663 -0
- package/src/observer/evidence.js +5 -1
- package/src/observer/evidence.ts +5 -1
- package/src/osKeychain.js +17 -9
- package/src/osKeychain.ts +14 -9
- package/src/outputStore.js +210 -156
- package/src/outputStore.ts +321 -0
- package/src/planCache.js +3 -6
- package/src/planCache.ts +3 -6
- 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/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/providers/acp.js +234 -49
- package/src/providers/acp.ts +240 -50
- package/src/providers/anthropic.js +152 -47
- package/src/providers/anthropic.ts +152 -45
- package/src/providers/antigravity.js +565 -354
- package/src/providers/antigravity.ts +555 -355
- package/src/providers/base.js +9 -2
- package/src/providers/base.ts +10 -2
- package/src/providers/byokHttp.js +127 -17
- package/src/providers/byokHttp.ts +175 -18
- package/src/providers/byokStream.js +162 -36
- package/src/providers/byokStream.ts +162 -55
- package/src/providers/dashscope-byok.js +29 -3
- package/src/providers/dashscope-byok.ts +30 -2
- package/src/providers/deepseek.js +12 -3
- package/src/providers/deepseek.ts +12 -3
- package/src/providers/factory.js +41 -0
- package/src/providers/factory.ts +42 -0
- package/src/providers/gemini.js +74 -22
- package/src/providers/gemini.ts +78 -26
- package/src/providers/moonshot.js +36 -3
- package/src/providers/moonshot.ts +32 -3
- package/src/providers/ollama.js +267 -21
- package/src/providers/ollama.ts +302 -29
- package/src/providers/openai-compatible.js +67 -11
- package/src/providers/openai-compatible.ts +78 -17
- package/src/providers/openai.js +25 -2
- package/src/providers/openai.ts +24 -2
- package/src/providers/openrouter.js +233 -66
- package/src/providers/openrouter.ts +226 -70
- package/src/providers/qwen-byok.js +29 -3
- package/src/providers/qwen-byok.ts +30 -2
- package/src/providers/wireNormalizer.js +66 -0
- package/src/providers/wireNormalizer.ts +64 -0
- package/src/providers/xai.js +10 -3
- package/src/providers/xai.ts +9 -3
- 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/reporting.js +328 -326
- package/src/reporting.ts +482 -0
- package/src/sandbox.js +37 -0
- package/src/sandbox.ts +38 -0
- package/src/sessionJournal.js +24 -3
- package/src/sessionJournal.ts +18 -3
- package/src/sessionStore.js +1 -2
- package/src/sessionStore.ts +2 -0
- package/src/slopDetector.js +202 -265
- package/src/slopDetector.ts +279 -0
- package/src/smartToolsUse.js +10 -4
- package/src/smartToolsUse.ts +10 -4
- package/src/stallGuard.js +10 -3
- package/src/stallGuard.ts +9 -3
- package/src/taskBuffer.js +91 -40
- package/src/taskBuffer.ts +94 -0
- package/src/tokenTracker.js +78 -11
- package/src/tokenTracker.ts +69 -11
- package/src/toolPacks.js +5 -0
- package/src/toolPacks.ts +5 -0
- package/src/tools/applyPatch.js +610 -0
- package/src/tools/applyPatch.ts +661 -0
- package/src/tools/archive.js +135 -21
- package/src/tools/archive.ts +136 -21
- 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/desktopAct.js +185 -197
- package/src/tools/desktopAct.ts +257 -0
- 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 +192 -74
- package/src/tools/fsEdit.ts +201 -72
- package/src/tools/fsMove.js +79 -52
- package/src/tools/fsMove.ts +108 -0
- package/src/tools/fsRead.js +54 -15
- package/src/tools/fsRead.ts +55 -15
- package/src/tools/fsSearch.js +5 -0
- package/src/tools/fsSearch.ts +5 -0
- package/src/tools/fsWrite.js +14 -6
- package/src/tools/fsWrite.ts +14 -6
- 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 +53 -12
- package/src/tools/generateMediaViaApi.ts +52 -12
- 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/multiEdit.js +16 -76
- package/src/tools/multiEdit.ts +20 -77
- package/src/tools/osSandbox.js +152 -15
- package/src/tools/osSandbox.ts +148 -15
- package/src/tools/palmierAutomator.js +147 -95
- package/src/tools/palmierAutomator.ts +171 -0
- package/src/tools/pdfReader.js +95 -104
- package/src/tools/pdfReader.ts +125 -0
- 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/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/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/subagentOrchestrator.js +404 -348
- package/src/tools/subagentOrchestrator.ts +457 -0
- package/src/tools/sysRun.js +83 -26
- package/src/tools/sysRun.ts +80 -26
- package/src/tools/toolForge.js +84 -67
- package/src/tools/toolForge.ts +102 -0
- package/src/tools/toolPathSafety.js +262 -0
- package/src/tools/toolPathSafety.ts +308 -0
- package/src/tools/toolScanner.js +28 -0
- package/src/tools/toolScanner.ts +29 -0
- package/src/tools/toolSelfRepair.js +21 -6
- package/src/tools/toolSelfRepair.ts +26 -6
- package/src/tools/walkerSafety.ts +1 -0
- package/src/tools/webFetch.js +5 -2
- package/src/tools/webFetch.ts +5 -2
- 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/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 +27 -7
- package/src/tui/consoleGuard.ts +29 -7
- 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 +0 -2
- package/src/tui/messageInteraction.ts +0 -2
- package/src/tui/modelPicker.js +0 -3
- package/src/tui/modelPicker.ts +3 -6
- package/src/tui/observerPicker.js +0 -2
- package/src/tui/observerPicker.ts +0 -2
- package/src/tui/overlay.js +0 -1
- package/src/tui/overlay.ts +0 -1
- 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 +0 -1
- package/src/tui/sessionPicker.ts +0 -1
- package/src/tui/sessionPickerView.js +0 -2
- package/src/tui/sessionPickerView.ts +4 -21
- 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/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/workspaceSwitch.js +4 -2
- package/src/tui/workspaceSwitch.ts +5 -2
- package/src/types/contracts.ts +4 -1
- 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/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/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/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/provisioning/capabilityProvisioner.d.ts +0 -12
- package/src/slopDetector.d.ts +0 -3
- package/src/taskBuffer.d.ts +0 -1
- package/src/tools/desktopAct.d.ts +0 -10
- package/src/tools/registry.d.ts +0 -5
- package/src/tui/chatRenderer.d.ts +0 -27
- package/src/tui/diff.d.ts +0 -3
- package/src/utils/cli_ui.d.ts +0 -19
- package/src/utils/paths.d.ts +0 -3
- package/src/verification/skillCatalog.d.ts +0 -1
- package/src/version.d.ts +0 -1
package/src/commands.ts
ADDED
|
@@ -0,0 +1,3985 @@
|
|
|
1
|
+
// Sovereign Slash-Command Registry — one table for the local terminal.
|
|
2
|
+
//
|
|
3
|
+
// WHY ONE TABLE
|
|
4
|
+
// Commands are declared once and rendered by the terminal chat and completion
|
|
5
|
+
// UI, so help, parsing and execution cannot drift apart.
|
|
6
|
+
//
|
|
7
|
+
// WHAT A COMMAND IS
|
|
8
|
+
// A thin, synchronous-ish surface over capability that already exists in the
|
|
9
|
+
// local harness. /clear is memoryManager.clearHistory(), /stop is the abort controller,
|
|
10
|
+
// /undo is src/checkpoints.js. Nothing here reimplements behaviour; it exposes it.
|
|
11
|
+
//
|
|
12
|
+
// ZERO-MALWARE: pure JS over existing modules. No shell, no dependency, no eval.
|
|
13
|
+
|
|
14
|
+
import { COMPILED_SKILLS } from './compiledSkills.js';
|
|
15
|
+
import {
|
|
16
|
+
readCompiledSkill, listCompiledSkills, invalidateUserSkills, userSkillProblems
|
|
17
|
+
} from './skillsManager.js';
|
|
18
|
+
import {
|
|
19
|
+
userSkillsRoot, parseSkillId, writeUserSkill, deleteUserSkill, skillTemplate
|
|
20
|
+
} from './userSkills.js';
|
|
21
|
+
import { buildContextText, buildUsageText, buildCheckpointsText, buildUndoText, buildStatusText } from './reporting.js';
|
|
22
|
+
import { loadConfig, saveConfig } from './config.js';
|
|
23
|
+
import {
|
|
24
|
+
resolveAvailableModels,
|
|
25
|
+
getCuratedModels,
|
|
26
|
+
getLiveAntigravityModels,
|
|
27
|
+
getModelVariantsForPeer,
|
|
28
|
+
getAvailableProvidersOverview,
|
|
29
|
+
resolveAvailableProvidersOverview,
|
|
30
|
+
pickDefaultPeerModel
|
|
31
|
+
} from './dynamicCatalogue.js';
|
|
32
|
+
import { DEFAULT_MODEL_BY_PROVIDER, PEER_MODEL_CATALOGUE } from './modelCatalogue.js';
|
|
33
|
+
import { isAcpProvider } from './providers/acp.js';
|
|
34
|
+
import {
|
|
35
|
+
formatRedactedProviderErrorReport,
|
|
36
|
+
getRecentProviderDiagnostics
|
|
37
|
+
} from './providers/byokHttp.js';
|
|
38
|
+
import {
|
|
39
|
+
formatByokProbeReport,
|
|
40
|
+
runZeroSpendByokProbe
|
|
41
|
+
} from './verification/byokSmokeProbe.js';
|
|
42
|
+
import { listSessions, getActiveSessionId, renameSession, getSession } from './sessionStore.js';
|
|
43
|
+
import {
|
|
44
|
+
serverStatus, grantServer, revokeServer, addServer, removeServer,
|
|
45
|
+
connectServer, disconnectServer, refreshServer
|
|
46
|
+
} from './mcp/mcpRegistry.js';
|
|
47
|
+
import { analyzeFiles, formatFindings } from './slopDetector.js';
|
|
48
|
+
import * as designPalettesMod from './designPalettes.js';
|
|
49
|
+
const { suggestMovements, formatMovementBrief, DESIGN_MOVEMENTS } = designPalettesMod as any;
|
|
50
|
+
import {
|
|
51
|
+
loadPeerProfiles, addPeerProfile, removePeerProfile, listAllPeers, getPeerProfile
|
|
52
|
+
} from './acp/peerProfiles.js';
|
|
53
|
+
import {
|
|
54
|
+
detectAllPeers, testPeerHandshake, BUILTIN_PEER_PRESETS
|
|
55
|
+
} from './acp/agentCatalog.js';
|
|
56
|
+
import fs from 'node:fs';
|
|
57
|
+
import os from 'node:os';
|
|
58
|
+
import path from 'node:path';
|
|
59
|
+
import { execFileSync } from 'node:child_process';
|
|
60
|
+
import { runCopyCommand, runPasteCommand } from './tui/chatboxClipboard.js';
|
|
61
|
+
import { loadLocalImageAttachment, formatByteSize } from './tui/clipboardImage.js';
|
|
62
|
+
import { getPackageVersion } from './version.js';
|
|
63
|
+
import { listGroups } from './checkpoints.js';
|
|
64
|
+
import * as pluginManagerMod from './plugins/pluginManager.js';
|
|
65
|
+
const listPlugins = (pluginManagerMod as any).listPlugins as () => any[];
|
|
66
|
+
import {
|
|
67
|
+
getOpenRouterStatus,
|
|
68
|
+
startLoopbackAuth,
|
|
69
|
+
saveOpenRouterKey,
|
|
70
|
+
disconnectOpenRouter,
|
|
71
|
+
setOpenRouterDataCollection,
|
|
72
|
+
buildAuthorizationUrl,
|
|
73
|
+
generatePkceCodes
|
|
74
|
+
} from './auth/openrouterAuth.js';
|
|
75
|
+
import { isPhysicalPathAllowed } from './agent/workspaceBoundary.js';
|
|
76
|
+
import { isBlockedWorkspaceRoot } from './sandboxPolicy.js';
|
|
77
|
+
import { isCredentialPath } from './sandbox.js';
|
|
78
|
+
import { atomicWriteSecretFileSync } from './configVault.js';
|
|
79
|
+
import { redactProviderSecrets, redactTextSecrets } from './providers/byokHttp.js';
|
|
80
|
+
import { safeDisplay } from './tui/text.js';
|
|
81
|
+
import { formatEnterprisePolicyReport, loadEnterprisePolicy } from './enterprisePolicy.js';
|
|
82
|
+
import { auditLog, formatAuditExport, type AuditExportFormat } from './auditLog.js';
|
|
83
|
+
import { probeOsSandbox, resolveOsSandboxMode } from './tools/osSandbox.js';
|
|
84
|
+
import { probeOsKeychain, resolveKeychainMode } from './osKeychain.js';
|
|
85
|
+
import { detectZeroCostProviders } from './zeroCostRouting.js';
|
|
86
|
+
import { assertSafeWorkspaceOutput, atomicWriteFileSafe } from './tools/toolPathSafety.js';
|
|
87
|
+
import { sanitizeSubprocessEnv } from './tools/subprocessEnv.js';
|
|
88
|
+
import { formatLspStatusReport, lspCodeIntel } from './tools/lspCodeIntel.js';
|
|
89
|
+
import {
|
|
90
|
+
createWorktree,
|
|
91
|
+
inspectWorktreeDiff,
|
|
92
|
+
listWorktrees,
|
|
93
|
+
mergeWorktree,
|
|
94
|
+
pruneManagedWorktrees,
|
|
95
|
+
removeWorktree
|
|
96
|
+
} from './worktreeManager.js';
|
|
97
|
+
import { collectWorkingTreeDiff, renderDiffReview } from './diffReview.js';
|
|
98
|
+
import { fetchFailedCiLogs, formatPrStatusReport, inspectPrStatus, preparePrDraft } from './prWorkflow.js';
|
|
99
|
+
import { formatEvalScorecard, runCodingEvalSuite } from './benchmarks/codingEval.js';
|
|
100
|
+
import { formatProjectRulesReport } from './projectInstructions.js';
|
|
101
|
+
import { buildRepoMap } from './codebase/repoMap.js';
|
|
102
|
+
import { backgroundTaskManager } from './backgroundTasks.js';
|
|
103
|
+
import {
|
|
104
|
+
resolveModelVariants,
|
|
105
|
+
matchVariantOption,
|
|
106
|
+
normalizeVariantToken,
|
|
107
|
+
type ModelVariantSpec
|
|
108
|
+
} from './modelVariants.js';
|
|
109
|
+
import {
|
|
110
|
+
launchGuiServer,
|
|
111
|
+
getGuiServerStatus,
|
|
112
|
+
stopGuiServer
|
|
113
|
+
} from './web/guiLauncher.js';
|
|
114
|
+
|
|
115
|
+
export interface CommandCompletionItem {
|
|
116
|
+
value: string;
|
|
117
|
+
label: string;
|
|
118
|
+
description?: string | undefined;
|
|
119
|
+
match?: string | undefined;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface CommandResult {
|
|
123
|
+
ok: boolean;
|
|
124
|
+
output?: string | undefined;
|
|
125
|
+
effect?: string | undefined;
|
|
126
|
+
title?: string | undefined;
|
|
127
|
+
[key: string]: any;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface CommandContext {
|
|
131
|
+
surface?: string | undefined;
|
|
132
|
+
loop?: any;
|
|
133
|
+
prompt?: any;
|
|
134
|
+
scanner?: any;
|
|
135
|
+
[key: string]: any;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface SlashCommandDefinition {
|
|
139
|
+
name: string;
|
|
140
|
+
aliases?: string[] | undefined;
|
|
141
|
+
scope: 'local';
|
|
142
|
+
usage: string;
|
|
143
|
+
description: string;
|
|
144
|
+
dialogTitle?: string | undefined;
|
|
145
|
+
complete?: () => CommandCompletionItem[];
|
|
146
|
+
run: (argv: string[], ctx: CommandContext) => CommandResult | Promise<CommandResult>;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface ParsedCommand {
|
|
150
|
+
name: string;
|
|
151
|
+
argv: string[];
|
|
152
|
+
raw: string;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export const SCOPES = ['local'] as const;
|
|
156
|
+
|
|
157
|
+
function ok(output: string, extra: Record<string, any> = {}): CommandResult {
|
|
158
|
+
return { ok: true, output, ...extra };
|
|
159
|
+
}
|
|
160
|
+
function fail(output: string): CommandResult {
|
|
161
|
+
return { ok: false, output };
|
|
162
|
+
}
|
|
163
|
+
function errMsg(err: unknown): string {
|
|
164
|
+
return err instanceof Error ? err.message : String(err);
|
|
165
|
+
}
|
|
166
|
+
function runGitCommand(args: string[], cwd: string): string {
|
|
167
|
+
const env: NodeJS.ProcessEnv = {
|
|
168
|
+
...sanitizeSubprocessEnv(process.env),
|
|
169
|
+
GIT_TERMINAL_PROMPT: '0'
|
|
170
|
+
};
|
|
171
|
+
delete env.GIT_EXTERNAL_DIFF;
|
|
172
|
+
delete env.GIT_PAGER;
|
|
173
|
+
delete env.GIT_EDITOR;
|
|
174
|
+
delete env.GIT_SSH_COMMAND;
|
|
175
|
+
return execFileSync('git', args, {
|
|
176
|
+
cwd,
|
|
177
|
+
encoding: 'utf8',
|
|
178
|
+
timeout: 15_000,
|
|
179
|
+
maxBuffer: 2 * 1024 * 1024,
|
|
180
|
+
windowsHide: true,
|
|
181
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
182
|
+
env
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function resetStandingApprovals(context: CommandContext): Promise<void> {
|
|
187
|
+
const { revokeAllAlways } = await import('./approvalGrants.js');
|
|
188
|
+
revokeAllAlways();
|
|
189
|
+
if (context.loop && typeof context.loop.resetApprovalScope === 'function') {
|
|
190
|
+
context.loop.resetApprovalScope();
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function resolveActiveVariantSpec(config: Record<string, any>, ctx: CommandContext = {}): ModelVariantSpec {
|
|
195
|
+
const provider = String(config.provider || '').trim();
|
|
196
|
+
const model = String(config.model || '').trim();
|
|
197
|
+
const liveAcpVariant = typeof ctx.loop?.llm?.getLiveVariantOption === 'function'
|
|
198
|
+
? ctx.loop.llm.getLiveVariantOption()
|
|
199
|
+
: null;
|
|
200
|
+
let ollamaSupportsThinking: boolean | null = null;
|
|
201
|
+
if (provider.toLowerCase() === 'ollama' && ctx.loop?.llm) {
|
|
202
|
+
const metaCache = (ctx.loop.llm as any)._modelMetaCache as Map<string, { supportsThinking?: boolean }> | undefined;
|
|
203
|
+
const cachedMeta = metaCache?.get(model);
|
|
204
|
+
if (cachedMeta && typeof cachedMeta.supportsThinking === 'boolean') {
|
|
205
|
+
ollamaSupportsThinking = cachedMeta.supportsThinking;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const providerLower = provider.toLowerCase();
|
|
209
|
+
const liveAgyModels = (providerLower.includes('antigravity') || providerLower === 'agy')
|
|
210
|
+
? getLiveAntigravityModels(config)
|
|
211
|
+
: undefined;
|
|
212
|
+
const peerModelVariants = isAcpProvider(provider)
|
|
213
|
+
? getModelVariantsForPeer(provider, model, config)
|
|
214
|
+
: undefined;
|
|
215
|
+
return resolveModelVariants({
|
|
216
|
+
provider,
|
|
217
|
+
model,
|
|
218
|
+
currentVariant: typeof config.reasoningEffort === 'string' ? config.reasoningEffort : null,
|
|
219
|
+
liveAcpVariant,
|
|
220
|
+
peerModelVariants,
|
|
221
|
+
ollamaSupportsThinking,
|
|
222
|
+
availableAgyModels: liveAgyModels && liveAgyModels.length > 0 ? liveAgyModels : undefined
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function formatVariantStatusReport(spec: ModelVariantSpec): string {
|
|
227
|
+
const sourceLabels: Record<ModelVariantSpec['source'], string> = {
|
|
228
|
+
acp_live: 'ACP peer live configOptions',
|
|
229
|
+
peer_catalogue: 'ACP peer published catalogue',
|
|
230
|
+
agy_models: 'Antigravity live sibling models',
|
|
231
|
+
ollama_live: 'Ollama local capabilities',
|
|
232
|
+
model_family: 'Model capability registry',
|
|
233
|
+
none: 'Not tunable'
|
|
234
|
+
};
|
|
235
|
+
const lines = [
|
|
236
|
+
`Provider : ${safeDisplay(spec.provider || 'none')}`,
|
|
237
|
+
`Model : ${safeDisplay(spec.model || 'none')}`,
|
|
238
|
+
`Detection : ${sourceLabels[spec.source]}`,
|
|
239
|
+
`Active Variant : ${safeDisplay(spec.currentVariant || (spec.defaultVariant ? `auto (${spec.defaultVariant})` : 'default'))}`
|
|
240
|
+
];
|
|
241
|
+
if (spec.supported && spec.options.length > 0) {
|
|
242
|
+
lines.push('');
|
|
243
|
+
lines.push('Supported Variants:');
|
|
244
|
+
for (const opt of spec.options) {
|
|
245
|
+
const isActive = Boolean(spec.currentVariant && opt.id.toLowerCase() === spec.currentVariant.toLowerCase());
|
|
246
|
+
const marker = isActive ? '●' : '○';
|
|
247
|
+
lines.push(` ${marker} ${safeDisplay(opt.id).padEnd(10)} ${safeDisplay(opt.label)} — ${safeDisplay(opt.description)}`);
|
|
248
|
+
}
|
|
249
|
+
lines.push('');
|
|
250
|
+
lines.push('Usage: /variant <level> | /variant auto');
|
|
251
|
+
if (spec.note) lines.push(`Note: ${safeDisplay(spec.note)}`);
|
|
252
|
+
} else {
|
|
253
|
+
lines.push('');
|
|
254
|
+
lines.push(`Info: ${safeDisplay(spec.note)}`);
|
|
255
|
+
}
|
|
256
|
+
return lines.join('\n');
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function applySelectedVariant(
|
|
260
|
+
rawChoice: string,
|
|
261
|
+
spec: ModelVariantSpec,
|
|
262
|
+
config: Record<string, any>,
|
|
263
|
+
ctx: CommandContext = {}
|
|
264
|
+
): Promise<CommandResult> {
|
|
265
|
+
const norm = normalizeVariantToken(rawChoice);
|
|
266
|
+
if (norm === 'auto') {
|
|
267
|
+
delete config.reasoningEffort;
|
|
268
|
+
delete config.reasoningBudgetTokens;
|
|
269
|
+
saveConfig(config);
|
|
270
|
+
const liveAcp = typeof ctx.loop?.llm?.getLiveVariantOption === 'function'
|
|
271
|
+
? ctx.loop.llm.getLiveVariantOption()
|
|
272
|
+
: null;
|
|
273
|
+
if (
|
|
274
|
+
liveAcp
|
|
275
|
+
&& Array.isArray(liveAcp.options)
|
|
276
|
+
&& liveAcp.options.some((opt: { value?: string }) => String(opt?.value || '').toLowerCase() === 'default')
|
|
277
|
+
&& typeof ctx.loop?.llm?.applyVariant === 'function'
|
|
278
|
+
) {
|
|
279
|
+
await ctx.loop.llm.applyVariant('default', liveAcp.configOptionId || spec.acpConfigId);
|
|
280
|
+
}
|
|
281
|
+
if (ctx.loop) {
|
|
282
|
+
ctx.loop.config = loadConfig();
|
|
283
|
+
if (typeof ctx.loop.updateTierLimits === 'function') {
|
|
284
|
+
ctx.loop.updateTierLimits();
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (ctx.prompt) {
|
|
288
|
+
if (typeof ctx.prompt.updateModel === 'function') {
|
|
289
|
+
ctx.prompt.updateModel(config.provider || spec.provider, config.model || spec.model, '');
|
|
290
|
+
} else {
|
|
291
|
+
ctx.prompt.renderer?.status?.setSession?.({ variant: '' });
|
|
292
|
+
ctx.prompt.surface?.setSessionInfo?.({ variant: '' });
|
|
293
|
+
ctx.prompt.scheduleDraw?.();
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return ok(
|
|
297
|
+
`Reasoning variant reset to model default${spec.defaultVariant ? ` (${safeDisplay(spec.defaultVariant)})` : ''} for ${safeDisplay(spec.provider)} / ${safeDisplay(spec.model)}.`,
|
|
298
|
+
{ effect: 'inline' }
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
if (!spec.supported || spec.options.length === 0) {
|
|
303
|
+
return fail(
|
|
304
|
+
`${safeDisplay(spec.provider || 'Active provider')} / ${safeDisplay(spec.model || 'active model')} does not expose tunable reasoning variants.\n${safeDisplay(spec.note)}`
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const matched = matchVariantOption(spec, rawChoice);
|
|
309
|
+
if (!matched) {
|
|
310
|
+
const allowed = spec.options.map((o) => o.id).join(', ');
|
|
311
|
+
return fail(
|
|
312
|
+
`Variant "${safeDisplay(rawChoice)}" is not supported by ${safeDisplay(spec.model || spec.provider)}.\nSupported variants: ${allowed}, auto`
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
config.reasoningEffort = matched.id;
|
|
317
|
+
const modelChanged = Boolean(matched.targetModelId && matched.targetModelId !== config.model);
|
|
318
|
+
if (matched.targetModelId) {
|
|
319
|
+
config.model = matched.targetModelId;
|
|
320
|
+
}
|
|
321
|
+
saveConfig(config);
|
|
322
|
+
|
|
323
|
+
let liveSynced = false;
|
|
324
|
+
if (typeof ctx.loop?.llm?.applyVariant === 'function' && !modelChanged) {
|
|
325
|
+
liveSynced = Boolean(await ctx.loop.llm.applyVariant(matched.id, matched.acpConfigId));
|
|
326
|
+
if (ctx.loop) {
|
|
327
|
+
ctx.loop.config = loadConfig();
|
|
328
|
+
}
|
|
329
|
+
} else if (ctx.loop) {
|
|
330
|
+
ctx.loop.config = loadConfig();
|
|
331
|
+
if (typeof ctx.loop.updateTierLimits === 'function') {
|
|
332
|
+
ctx.loop.updateTierLimits();
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (ctx.prompt) {
|
|
337
|
+
if (typeof ctx.prompt.updateModel === 'function') {
|
|
338
|
+
ctx.prompt.updateModel(config.provider || spec.provider, config.model || spec.model, matched.id);
|
|
339
|
+
} else if (ctx.prompt.renderer?.status) {
|
|
340
|
+
ctx.prompt.renderer.status.setSession({
|
|
341
|
+
provider: config.provider || spec.provider,
|
|
342
|
+
model: config.model || spec.model,
|
|
343
|
+
variant: matched.id
|
|
344
|
+
});
|
|
345
|
+
ctx.prompt.surface?.setSessionInfo?.({
|
|
346
|
+
provider: config.provider || spec.provider,
|
|
347
|
+
model: config.model || spec.model,
|
|
348
|
+
variant: matched.id
|
|
349
|
+
});
|
|
350
|
+
if (typeof ctx.prompt.scheduleDraw === 'function') ctx.prompt.scheduleDraw();
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const syncNote = liveSynced
|
|
355
|
+
? ' (applied live to active ACP session)'
|
|
356
|
+
: (modelChanged ? ` (switched model to ${safeDisplay(config.model)})` : '');
|
|
357
|
+
return ok(
|
|
358
|
+
`Variant set to ${safeDisplay(matched.label)} (${safeDisplay(matched.id)}) for ${safeDisplay(spec.provider)} / ${safeDisplay(config.model || spec.model)}${syncNote}.`,
|
|
359
|
+
{ effect: 'inline' }
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// ---------------------------------------------------------------------------
|
|
364
|
+
// The table
|
|
365
|
+
// ---------------------------------------------------------------------------
|
|
366
|
+
|
|
367
|
+
export const COMMANDS: SlashCommandDefinition[] = [
|
|
368
|
+
{
|
|
369
|
+
name: 'setup', aliases: ['config', 'connect'], scope: 'local', usage: '/setup',
|
|
370
|
+
description: 'Configure provider, endpoint, model and autonomy',
|
|
371
|
+
run: async (_argv, ctx) => {
|
|
372
|
+
if (!ctx.prompt) return ok('Run causyne setup in an interactive terminal.');
|
|
373
|
+
const { configureInPrompt } = await import('./tui/home.js');
|
|
374
|
+
const result = await configureInPrompt(ctx.prompt, { loadConfig, saveConfig });
|
|
375
|
+
if (result) {
|
|
376
|
+
const fresh = loadConfig();
|
|
377
|
+
if (ctx.loop) {
|
|
378
|
+
ctx.loop.config = fresh;
|
|
379
|
+
if (typeof ctx.loop.updateTierLimits === 'function') {
|
|
380
|
+
ctx.loop.updateTierLimits();
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
const nextVariant = typeof fresh.reasoningEffort === 'string' ? fresh.reasoningEffort : '';
|
|
384
|
+
if (typeof ctx.prompt.updateModel === 'function') {
|
|
385
|
+
ctx.prompt.updateModel(fresh.provider || result.provider, fresh.model || result.model, nextVariant);
|
|
386
|
+
} else {
|
|
387
|
+
ctx.prompt.renderer?.status?.setSession?.({
|
|
388
|
+
provider: fresh.provider || result.provider,
|
|
389
|
+
model: fresh.model || result.model,
|
|
390
|
+
variant: nextVariant
|
|
391
|
+
});
|
|
392
|
+
ctx.prompt.surface?.setSessionInfo?.({
|
|
393
|
+
provider: fresh.provider || result.provider,
|
|
394
|
+
model: fresh.model || result.model,
|
|
395
|
+
variant: nextVariant,
|
|
396
|
+
autonomyMode: fresh.autonomyMode
|
|
397
|
+
});
|
|
398
|
+
ctx.prompt.scheduleDraw?.();
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return ok(result ? `Saved ${result.provider} / ${result.model}. Connection has not been tested.` : 'Cancelled. Nothing was changed.');
|
|
402
|
+
}
|
|
403
|
+
},
|
|
404
|
+
|
|
405
|
+
{
|
|
406
|
+
name: 'help',
|
|
407
|
+
aliases: ['?', 'commands'],
|
|
408
|
+
scope: 'local',
|
|
409
|
+
usage: '/help [command]',
|
|
410
|
+
description: 'List the available commands',
|
|
411
|
+
dialogTitle: 'Commands',
|
|
412
|
+
complete: () => {
|
|
413
|
+
return listCommands('terminal').map((c) => ({
|
|
414
|
+
value: c.name,
|
|
415
|
+
label: c.name,
|
|
416
|
+
description: c.description
|
|
417
|
+
}));
|
|
418
|
+
},
|
|
419
|
+
run: (argv, ctx) => {
|
|
420
|
+
const [wanted] = argv;
|
|
421
|
+
if (wanted) {
|
|
422
|
+
const command = resolveCommand(wanted);
|
|
423
|
+
if (!command) return fail(`No command named "${safeDisplay(wanted)}". Try /help.`);
|
|
424
|
+
const aliases = command.aliases?.length ? `\n aliases : ${command.aliases.map(a => '/' + a).join(', ')}` : '';
|
|
425
|
+
return ok(`${command.usage}\n ${command.description}${aliases}`);
|
|
426
|
+
}
|
|
427
|
+
const visible = listCommands(ctx.surface);
|
|
428
|
+
const width = visible.reduce((max, c) => Math.max(max, c.usage.length), 0);
|
|
429
|
+
const lines = ['Commands', ''];
|
|
430
|
+
for (const command of visible) {
|
|
431
|
+
lines.push(` ${command.usage.padEnd(width)} ${command.description}`);
|
|
432
|
+
}
|
|
433
|
+
lines.push('');
|
|
434
|
+
lines.push('Anything not starting with / is sent to the agent as a task.');
|
|
435
|
+
return ok(lines.join('\n'));
|
|
436
|
+
}
|
|
437
|
+
},
|
|
438
|
+
|
|
439
|
+
{
|
|
440
|
+
name: 'cd',
|
|
441
|
+
aliases: ['cwd', 'workspace'],
|
|
442
|
+
scope: 'local',
|
|
443
|
+
usage: '/cd [directory]',
|
|
444
|
+
description: 'View or change active working directory and project focus',
|
|
445
|
+
complete: () => {
|
|
446
|
+
try {
|
|
447
|
+
const entries = fs.readdirSync(process.cwd(), { withFileTypes: true });
|
|
448
|
+
return entries
|
|
449
|
+
.filter(e => e.isDirectory() && !e.name.startsWith('.'))
|
|
450
|
+
.map(e => ({
|
|
451
|
+
value: e.name.includes(' ') ? `"${e.name}"` : e.name,
|
|
452
|
+
label: e.name + '/',
|
|
453
|
+
description: 'directory'
|
|
454
|
+
}));
|
|
455
|
+
} catch (e) {
|
|
456
|
+
return [];
|
|
457
|
+
}
|
|
458
|
+
},
|
|
459
|
+
run: async (argv, ctx) => {
|
|
460
|
+
const target = argv.join(' ').trim().replace(/^["']|["']$/g, '');
|
|
461
|
+
if (!target) {
|
|
462
|
+
return ok(`Current working directory: ${safeDisplay(process.cwd())}`);
|
|
463
|
+
}
|
|
464
|
+
if (target.includes('\0')) {
|
|
465
|
+
return fail('Invalid directory path.');
|
|
466
|
+
}
|
|
467
|
+
const expanded = target === '~'
|
|
468
|
+
? os.homedir()
|
|
469
|
+
: (target.startsWith('~/') || target.startsWith('~\\') ? path.join(os.homedir(), target.slice(2)) : target);
|
|
470
|
+
const resolved = path.resolve(process.cwd(), expanded);
|
|
471
|
+
let stat: fs.Stats;
|
|
472
|
+
try {
|
|
473
|
+
stat = fs.statSync(resolved);
|
|
474
|
+
} catch {
|
|
475
|
+
return fail(`Directory not found: ${safeDisplay(resolved)}`);
|
|
476
|
+
}
|
|
477
|
+
if (!stat.isDirectory()) {
|
|
478
|
+
return fail(`Not a directory: ${safeDisplay(resolved)}`);
|
|
479
|
+
}
|
|
480
|
+
// Do not mutate the existing AgentLoop: its workspaceRoot, Sandbox,
|
|
481
|
+
// MemoryManager and loaded session belong to the previous workspace.
|
|
482
|
+
// The chat controller rebuilds the loop after this explicit command.
|
|
483
|
+
let canonicalRoot: string;
|
|
484
|
+
try {
|
|
485
|
+
canonicalRoot = fs.realpathSync(resolved);
|
|
486
|
+
if (isBlockedWorkspaceRoot(canonicalRoot)) {
|
|
487
|
+
return fail(`Refusing to switch workspace into blocked system directory: ${safeDisplay(canonicalRoot)}`);
|
|
488
|
+
}
|
|
489
|
+
process.chdir(canonicalRoot);
|
|
490
|
+
} catch (err) {
|
|
491
|
+
return fail(`Cannot switch to ${safeDisplay(resolved)}: ${errMsg(err)}`);
|
|
492
|
+
}
|
|
493
|
+
if (ctx.prompt && typeof ctx.prompt.setWorkingRoot === 'function') {
|
|
494
|
+
ctx.prompt.setWorkingRoot(canonicalRoot);
|
|
495
|
+
}
|
|
496
|
+
return ok(`Working directory changed to: ${canonicalRoot}`, {
|
|
497
|
+
effect: 'workspace-changed', workspaceRoot: canonicalRoot
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
},
|
|
501
|
+
|
|
502
|
+
{
|
|
503
|
+
name: 'skill',
|
|
504
|
+
scope: 'local',
|
|
505
|
+
usage: '/skill new <domain>/<name> | /skill edit <domain>/<name> | /skill rm <domain>/<name> | /skill mine',
|
|
506
|
+
description: 'Create, edit or remove your own skills',
|
|
507
|
+
|
|
508
|
+
// Only the ACTIONS. This used to append the user's skill ids too, but a
|
|
509
|
+
// skill id is the second argument (`/skill rm team/x`) and completion only
|
|
510
|
+
// reaches the first — so accepting one produced `/skill team/x` and an
|
|
511
|
+
// "Unknown action" error. Offering something in a position where it cannot
|
|
512
|
+
// work is worse than offering nothing.
|
|
513
|
+
complete: () => {
|
|
514
|
+
const mine = listCompiledSkills().filter((skill) => skill.source === 'user');
|
|
515
|
+
return [
|
|
516
|
+
{ value: 'new', label: 'new', description: 'scaffold a new skill you own' },
|
|
517
|
+
{ value: 'mine', label: 'mine', description: `list your own skills (${mine.length})` },
|
|
518
|
+
{ value: 'edit', label: 'edit', description: 'show where one of your skills lives' },
|
|
519
|
+
{ value: 'rm', label: 'rm', description: 'remove one of your skills' }
|
|
520
|
+
];
|
|
521
|
+
},
|
|
522
|
+
|
|
523
|
+
run: (argv) => {
|
|
524
|
+
const [action, target, ...rest] = argv;
|
|
525
|
+
const mine = () => listCompiledSkills().filter((skill) => skill.source === 'user');
|
|
526
|
+
if (rest.length > 0) {
|
|
527
|
+
return fail(`/skill takes at most one target. Ignored: ${JSON.stringify(rest.join(' '))}\n`
|
|
528
|
+
+ 'A skill name is one word: lowercase letters, digits and hyphens.');
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
if (action === 'clear' || action === 'off' || action === 'reset') {
|
|
532
|
+
return { ok: true, effect: 'clear-skill', output: 'Active skill cleared.' };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
if (!action || (action === 'new' && !target) || action === 'create') {
|
|
536
|
+
return { ok: true, effect: 'create-skill' };
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
if (action === 'mine' || action === 'list') {
|
|
540
|
+
const own = mine();
|
|
541
|
+
const problems = userSkillProblems();
|
|
542
|
+
const lines = [`Your own skills (${own.length})`, ''];
|
|
543
|
+
if (own.length === 0) {
|
|
544
|
+
lines.push(` none yet — ${userSkillsRoot()}`);
|
|
545
|
+
lines.push('');
|
|
546
|
+
lines.push(' /skill new <domain>/<name> scaffold one');
|
|
547
|
+
lines.push(' or ask Causyne to write one for you: "make me a skill for our release process"');
|
|
548
|
+
} else {
|
|
549
|
+
for (const skill of own) lines.push(` ${skill.domain}/${skill.id} — ${skill.description}`);
|
|
550
|
+
lines.push('');
|
|
551
|
+
lines.push(` stored in ${userSkillsRoot()}`);
|
|
552
|
+
lines.push(' yours shadow a compiled skill of the same id, so you can correct any of them');
|
|
553
|
+
}
|
|
554
|
+
if (problems.length > 0) {
|
|
555
|
+
lines.push('');
|
|
556
|
+
lines.push('Problems:');
|
|
557
|
+
for (const problem of problems) lines.push(` ${problem}`);
|
|
558
|
+
}
|
|
559
|
+
return ok(lines.join('\n'));
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
if (action === 'new') {
|
|
563
|
+
const parsed = parseSkillId(target);
|
|
564
|
+
if (parsed.error) return fail(parsed.error);
|
|
565
|
+
const domain = parsed.domain || '';
|
|
566
|
+
const skillName = parsed.name || '';
|
|
567
|
+
const written = writeUserSkill({
|
|
568
|
+
domain,
|
|
569
|
+
name: skillName,
|
|
570
|
+
content: skillTemplate(domain, skillName)
|
|
571
|
+
});
|
|
572
|
+
if (!written.ok) return fail(written.error || 'Could not create skill.');
|
|
573
|
+
invalidateUserSkills();
|
|
574
|
+
return ok([
|
|
575
|
+
`Created ${parsed.domain}/${parsed.name}`,
|
|
576
|
+
'',
|
|
577
|
+
` ${written.path}`,
|
|
578
|
+
'',
|
|
579
|
+
'Open it and fill in the workflow. Every step ends with a "Done when:" line you can',
|
|
580
|
+
'actually check, and the file closes with a Verification section — that is what makes',
|
|
581
|
+
'a skill a procedure rather than a note. The description decides when the agent reaches',
|
|
582
|
+
'for it, so write it as "what this does. Use when …".'
|
|
583
|
+
].join('\n'));
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
if (action === 'edit') {
|
|
587
|
+
const parsed = parseSkillId(target);
|
|
588
|
+
if (parsed.error) return fail(parsed.error);
|
|
589
|
+
const found = mine().find((s) => s.domain === parsed.domain && s.id === parsed.name);
|
|
590
|
+
if (!found) {
|
|
591
|
+
return fail(`${target} is not one of your skills. /skill mine lists them, `
|
|
592
|
+
+ `/skill new ${target} creates it.`);
|
|
593
|
+
}
|
|
594
|
+
return ok(`${target}\n\n ${path.join(userSkillsRoot(), parsed.domain || '', parsed.name || '', 'SKILL.md')}`);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
if (action === 'rm') {
|
|
598
|
+
const parsed = parseSkillId(target);
|
|
599
|
+
if (parsed.error) return fail(parsed.error);
|
|
600
|
+
const removed = deleteUserSkill(parsed.domain || '', parsed.name || '');
|
|
601
|
+
if (!removed.ok) return fail(removed.error || 'Could not remove skill.');
|
|
602
|
+
invalidateUserSkills();
|
|
603
|
+
return ok(`Removed ${target}`);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
return fail(`Unknown action "${action}". Use new, edit, rm or mine.`);
|
|
607
|
+
}
|
|
608
|
+
},
|
|
609
|
+
{
|
|
610
|
+
name: 'skills',
|
|
611
|
+
scope: 'local',
|
|
612
|
+
usage: '/skills [domain | domain/skill [instruction] | domain/skill --show]',
|
|
613
|
+
description: 'Run a skill on your task, browse the library, or read one with --show',
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* Argument suggestions, offered as the user types `/skills <prefix>`.
|
|
617
|
+
*
|
|
618
|
+
* openclaw's contract (src/tui/commands.ts getArgumentCompletions): the
|
|
619
|
+
* command owns its argument vocabulary and the prompt asks for it. Ranking
|
|
620
|
+
* and filtering are the prompt's job — this returns the whole vocabulary and
|
|
621
|
+
* completion.js scores it with the same function it uses for commands and
|
|
622
|
+
* filenames, so `/skills doc` reaches devops/docker-multi-stage-builds by a
|
|
623
|
+
* basename-prefix match rather than needing the domain typed first.
|
|
624
|
+
*
|
|
625
|
+
* Domains are offered alongside skills because `/skills devops` is a valid
|
|
626
|
+
* argument in its own right.
|
|
627
|
+
*/
|
|
628
|
+
complete: () => {
|
|
629
|
+
const skills = listCompiledSkills();
|
|
630
|
+
const domains = [...new Set(skills.map((skill) => skill.domain))]
|
|
631
|
+
.map((domain) => ({
|
|
632
|
+
value: domain,
|
|
633
|
+
label: domain,
|
|
634
|
+
description: `${skills.filter((s) => s.domain === domain).length} skills`
|
|
635
|
+
}));
|
|
636
|
+
const base = [
|
|
637
|
+
{ value: 'clear', label: 'clear', description: 'clear the currently active skill' },
|
|
638
|
+
...domains
|
|
639
|
+
];
|
|
640
|
+
return base.concat(skills.map((skill) => ({
|
|
641
|
+
value: `${skill.domain}/${skill.id}`,
|
|
642
|
+
// Rank against the skill id as well as the full path, so typing the
|
|
643
|
+
// skill name alone finds it without knowing which domain it lives in.
|
|
644
|
+
match: `${skill.domain}/${skill.id}`,
|
|
645
|
+
label: `${skill.domain}/${skill.id}`,
|
|
646
|
+
description: skill.description
|
|
647
|
+
})));
|
|
648
|
+
},
|
|
649
|
+
run: (argv) => {
|
|
650
|
+
const [target] = argv;
|
|
651
|
+
|
|
652
|
+
if (target === 'clear' || target === 'off' || target === 'reset') {
|
|
653
|
+
return { ok: true, effect: 'clear-skill', output: 'Active skill cleared.' };
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
if (!target) {
|
|
657
|
+
const catalogue = listCompiledSkills();
|
|
658
|
+
if (catalogue.length === 0) return ok('No skills are compiled into this build.');
|
|
659
|
+
|
|
660
|
+
// An interactive terminal browses; everything else reads. The picker is
|
|
661
|
+
// fuzzy-searchable and truncates to its own pane, so a 100-skill library
|
|
662
|
+
// stays usable and cannot overflow the terminal — the failure the flat
|
|
663
|
+
// listing had at five skills, let alone a hundred.
|
|
664
|
+
const summary = ['Compiled skills', ''];
|
|
665
|
+
const byDomain = new Map();
|
|
666
|
+
for (const skill of catalogue) {
|
|
667
|
+
if (!byDomain.has(skill.domain)) byDomain.set(skill.domain, []);
|
|
668
|
+
byDomain.get(skill.domain).push(skill);
|
|
669
|
+
}
|
|
670
|
+
for (const [domain, skills] of byDomain) {
|
|
671
|
+
summary.push(` ${domain} (${skills.length})`);
|
|
672
|
+
for (const skill of skills) {
|
|
673
|
+
summary.push(` ${domain}/${skill.id} — ${skill.description || skill.name || ''}`);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
summary.push('');
|
|
677
|
+
summary.push(`${catalogue.length} skills across ${byDomain.size} domains.`);
|
|
678
|
+
summary.push('Read one with /skills <domain>/<skill>.');
|
|
679
|
+
|
|
680
|
+
const pickerItems = [
|
|
681
|
+
{
|
|
682
|
+
domain: 'custom',
|
|
683
|
+
id: 'create',
|
|
684
|
+
name: '+ Create new skill...',
|
|
685
|
+
description: 'Author a new custom procedure with interactive wizard',
|
|
686
|
+
isCreateAction: true
|
|
687
|
+
},
|
|
688
|
+
...catalogue
|
|
689
|
+
];
|
|
690
|
+
|
|
691
|
+
return { ok: true, output: summary.join('\n'), effect: 'pick-skill', items: pickerItems };
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
if (target.includes('/')) {
|
|
695
|
+
const separator = target.indexOf('/');
|
|
696
|
+
const domain = target.slice(0, separator);
|
|
697
|
+
const id = target.slice(separator + 1);
|
|
698
|
+
const content = readCompiledSkill(domain, id);
|
|
699
|
+
if (typeof content === 'string' && content.startsWith('Error:')) return fail(content);
|
|
700
|
+
|
|
701
|
+
// Everything after the skill id is the TASK.
|
|
702
|
+
//
|
|
703
|
+
// `/skills` used to take argv[0] and discard the rest, so
|
|
704
|
+
// `/skills data/notebook-to-production please produksi ini` silently
|
|
705
|
+
// threw away "please produksi ini" and printed the document instead.
|
|
706
|
+
const instruction = argv.slice(1).join(' ').trim();
|
|
707
|
+
|
|
708
|
+
// `--show` reads it as a document. Anything else RUNS it.
|
|
709
|
+
if (instruction === '--show' || instruction === '-s') {
|
|
710
|
+
return ok(stripFrontmatter(content));
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
return {
|
|
714
|
+
ok: true,
|
|
715
|
+
effect: 'invoke-skill',
|
|
716
|
+
skill: { id: `${domain}/${id}`, content },
|
|
717
|
+
instruction,
|
|
718
|
+
output: `${domain}/${id}`
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
if (/[\r\n\0]/.test(target)) {
|
|
723
|
+
return fail('Invalid skill domain.');
|
|
724
|
+
}
|
|
725
|
+
const skills = Object.hasOwn(COMPILED_SKILLS, target) ? COMPILED_SKILLS[target] : undefined;
|
|
726
|
+
if (!skills) {
|
|
727
|
+
return fail(`No skill domain "${safeDisplay(target)}". Available: ${Object.keys(COMPILED_SKILLS).join(', ')}`);
|
|
728
|
+
}
|
|
729
|
+
const names = Object.keys(skills);
|
|
730
|
+
if (names.length === 0) return ok(`Domain "${target}" has no compiled skills.`);
|
|
731
|
+
|
|
732
|
+
const listing = [`${target} skills (${names.length})`, '',
|
|
733
|
+
...names.map(id => ` ${target}/${id} — ${skills[id]?.description || ''}`)].join('\n');
|
|
734
|
+
|
|
735
|
+
// Trailing text after a DOMAIN means the user tried to invoke something.
|
|
736
|
+
// A domain is not a skill, so it cannot be run — but silently listing and
|
|
737
|
+
// discarding what they typed is the same failure the skill branch had.
|
|
738
|
+
const extra = argv.slice(1).join(' ').trim();
|
|
739
|
+
if (extra && extra !== '--show' && extra !== '-s') {
|
|
740
|
+
return fail(`"${target}" is a domain, not a skill — there is nothing to run.\n`
|
|
741
|
+
+ `Pick one of its skills and try again, for example:\n`
|
|
742
|
+
+ ` /skills ${target}/${names[0]} ${extra}\n\n${listing}`);
|
|
743
|
+
}
|
|
744
|
+
return ok(listing);
|
|
745
|
+
}
|
|
746
|
+
},
|
|
747
|
+
|
|
748
|
+
{
|
|
749
|
+
name: 'undo',
|
|
750
|
+
scope: 'local',
|
|
751
|
+
usage: '/undo [taskId] [--step] [--full] [--apply]',
|
|
752
|
+
description: "Preview rolling back the last task's file changes (--apply to write)",
|
|
753
|
+
dialogTitle: 'Undo',
|
|
754
|
+
complete: () => {
|
|
755
|
+
try {
|
|
756
|
+
const groups = listGroups(10);
|
|
757
|
+
return [
|
|
758
|
+
{ value: '--apply', label: '--apply', description: 'apply rollback directly to workspace' },
|
|
759
|
+
{ value: '--step', label: '--step', description: 'roll back just the single last file change' },
|
|
760
|
+
{ value: '--full', label: '--full', description: 'roll back entire workspace tree drift' },
|
|
761
|
+
...groups.map((g) => ({
|
|
762
|
+
value: g.taskId,
|
|
763
|
+
label: g.taskId,
|
|
764
|
+
description: g.prompt ? `${g.prompt.slice(0, 36)} (${g.fileEntries.length} files)` : `${g.fileEntries.length} files`
|
|
765
|
+
}))
|
|
766
|
+
];
|
|
767
|
+
} catch (e) {
|
|
768
|
+
return [
|
|
769
|
+
{ value: '--apply', label: '--apply', description: 'apply rollback directly' },
|
|
770
|
+
{ value: '--step', label: '--step', description: 'roll back just the single last file change' }
|
|
771
|
+
];
|
|
772
|
+
}
|
|
773
|
+
},
|
|
774
|
+
run: (argv, ctx = {}) => {
|
|
775
|
+
const allowedFlags = new Set(['--apply', '--step', '--full']);
|
|
776
|
+
const flags = new Set(argv.filter(a => a.startsWith('--')));
|
|
777
|
+
for (const flag of flags) {
|
|
778
|
+
if (!allowedFlags.has(flag)) {
|
|
779
|
+
return fail(`Unknown /undo flag "${safeDisplay(flag)}". Allowed flags: --apply, --step, --full.`);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
const taskId = argv.find(a => !a.startsWith('--'));
|
|
783
|
+
if (taskId && /[\r\n\0]/.test(taskId)) {
|
|
784
|
+
return fail('Invalid checkpoint task ID.');
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
// PREVIEW by default. Typing /undo used to restore files immediately —
|
|
788
|
+
// no preview, no confirmation, and none of the running-task guard the
|
|
789
|
+
// structured rollback flow has. A chat box is not a place where one word
|
|
790
|
+
// should be able to overwrite a day's work, so the destructive form has
|
|
791
|
+
// to be asked for by name.
|
|
792
|
+
const apply = flags.has('--apply');
|
|
793
|
+
const workspaceRoot = ctx.loop?.workspaceRoot || process.cwd();
|
|
794
|
+
|
|
795
|
+
const { ok: succeeded, text } = buildUndoText(taskId, {
|
|
796
|
+
step: flags.has('--step'),
|
|
797
|
+
full: flags.has('--full'),
|
|
798
|
+
dryRun: !apply,
|
|
799
|
+
workspaceRoot
|
|
800
|
+
});
|
|
801
|
+
|
|
802
|
+
if (!succeeded) return fail(text);
|
|
803
|
+
if (apply) {
|
|
804
|
+
if (ctx.loop?.memoryManager && typeof ctx.loop.memoryManager.loadHistory === 'function') {
|
|
805
|
+
const rewoundMessages = ctx.loop.memoryManager.loadHistory();
|
|
806
|
+
ctx.loop.messages = rewoundMessages;
|
|
807
|
+
const renderer = ctx.prompt?.renderer || ctx.loop?.connection?.renderer;
|
|
808
|
+
if (renderer && typeof renderer.renderSessionHistory === 'function') {
|
|
809
|
+
renderer.renderSessionHistory(rewoundMessages, {
|
|
810
|
+
id: ctx.loop.memoryManager.sessionId,
|
|
811
|
+
title: ctx.loop.memoryManager.sessionTitle || 'Session',
|
|
812
|
+
messagesCount: rewoundMessages.length
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
if (ctx.prompt?.surface?.viewport && typeof ctx.prompt.surface.viewport.toBottom === 'function') {
|
|
816
|
+
ctx.prompt.surface.viewport.toBottom();
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
return ok(text, { effect: 'inline' });
|
|
820
|
+
}
|
|
821
|
+
return ok(`${text}\n\nNothing was written. Run the same command with --apply to restore these files.`);
|
|
822
|
+
}
|
|
823
|
+
},
|
|
824
|
+
|
|
825
|
+
{
|
|
826
|
+
name: 'print',
|
|
827
|
+
scope: 'local',
|
|
828
|
+
usage: '/print',
|
|
829
|
+
description: 'Flush this session into the terminal scrollback and start the stage clean',
|
|
830
|
+
run: (argv, ctx) => {
|
|
831
|
+
// The Stage keeps the transcript in memory and paints a window of it, so
|
|
832
|
+
// until you exit, nothing is in your terminal's own scrollback to grep,
|
|
833
|
+
// copy or pipe. This is the way out without ending the session — and it
|
|
834
|
+
// prints BEFORE clearing, because ctrl+L in a terminal leaves your history
|
|
835
|
+
// behind and so must this.
|
|
836
|
+
const surface = ctx && ctx.prompt && ctx.prompt.surface;
|
|
837
|
+
if (!surface) {
|
|
838
|
+
return ok('Nothing to flush: this session already prints straight into your terminal.');
|
|
839
|
+
}
|
|
840
|
+
const rows = surface.flushAndClear();
|
|
841
|
+
return ok(`Printed ${rows} row${rows === 1 ? '' : 's'} into your terminal scrollback.`);
|
|
842
|
+
}
|
|
843
|
+
},
|
|
844
|
+
|
|
845
|
+
{
|
|
846
|
+
name: 'checkpoints',
|
|
847
|
+
aliases: ['ck'],
|
|
848
|
+
scope: 'local',
|
|
849
|
+
usage: '/checkpoints [count]',
|
|
850
|
+
description: 'List recent undo checkpoints',
|
|
851
|
+
dialogTitle: 'Checkpoints',
|
|
852
|
+
run: (argv) => {
|
|
853
|
+
const parsed = parseInt(argv[0] || '', 10);
|
|
854
|
+
const count = Number.isFinite(parsed) ? Math.max(1, Math.min(200, parsed)) : 15;
|
|
855
|
+
return ok(buildCheckpointsText(count));
|
|
856
|
+
}
|
|
857
|
+
},
|
|
858
|
+
|
|
859
|
+
{
|
|
860
|
+
name: 'context',
|
|
861
|
+
aliases: ['ctx'],
|
|
862
|
+
scope: 'local',
|
|
863
|
+
usage: '/context',
|
|
864
|
+
description: 'Show what fills the context window',
|
|
865
|
+
dialogTitle: 'Context',
|
|
866
|
+
run: () => ok(buildContextText())
|
|
867
|
+
},
|
|
868
|
+
|
|
869
|
+
{
|
|
870
|
+
name: 'usage',
|
|
871
|
+
aliases: ['cost'],
|
|
872
|
+
scope: 'local',
|
|
873
|
+
usage: '/usage',
|
|
874
|
+
description: 'Show token usage and estimated cost',
|
|
875
|
+
dialogTitle: 'Usage',
|
|
876
|
+
run: async (argv, ctx = {}) => {
|
|
877
|
+
if (ctx.prompt && typeof ctx.prompt.toggleUsageCard === 'function') {
|
|
878
|
+
await ctx.prompt.toggleUsageCard(ctx.loop);
|
|
879
|
+
return ok('', { effect: 'silent' });
|
|
880
|
+
}
|
|
881
|
+
return ok(await buildUsageText());
|
|
882
|
+
}
|
|
883
|
+
},
|
|
884
|
+
|
|
885
|
+
{
|
|
886
|
+
name: 'diff',
|
|
887
|
+
aliases: ['changes', 'git-diff'],
|
|
888
|
+
scope: 'local',
|
|
889
|
+
usage: '/diff [file] [--staged|staged] [--stat|stat] [--ref <git-ref>]',
|
|
890
|
+
description: 'Inspect structured working-tree or staged unified diffs for the active workspace',
|
|
891
|
+
dialogTitle: 'Diff Review',
|
|
892
|
+
complete: () => [
|
|
893
|
+
{ value: '--staged', label: '--staged', description: 'show staged changes only (--cached)' },
|
|
894
|
+
{ value: '--stat', label: '--stat', description: 'show changed file summary statistics' }
|
|
895
|
+
],
|
|
896
|
+
run: (argv, ctx = {}) => {
|
|
897
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
898
|
+
let staged = false;
|
|
899
|
+
let statOnly = false;
|
|
900
|
+
let ref: string | undefined;
|
|
901
|
+
let filePath: string | undefined;
|
|
902
|
+
for (let i = 0; i < argv.length; i++) {
|
|
903
|
+
const tok = argv[i] ?? '';
|
|
904
|
+
const lower = tok.toLowerCase();
|
|
905
|
+
if (lower === 'staged' || lower === '--staged' || lower === '--cached') staged = true;
|
|
906
|
+
else if (lower === 'stat' || lower === '--stat') statOnly = true;
|
|
907
|
+
else if (lower === '--ref') ref = argv[++i];
|
|
908
|
+
else if (lower.startsWith('--ref=')) ref = tok.slice('--ref='.length);
|
|
909
|
+
else if (tok && !tok.startsWith('-') && !filePath) filePath = tok;
|
|
910
|
+
}
|
|
911
|
+
try {
|
|
912
|
+
const report = collectWorkingTreeDiff(ws, { staged, ref, filePath });
|
|
913
|
+
return ok(renderDiffReview(report, { statOnly }));
|
|
914
|
+
} catch (err) {
|
|
915
|
+
return fail(`Could not inspect git diff: ${safeDisplay(errMsg(err))}`);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
},
|
|
919
|
+
|
|
920
|
+
{
|
|
921
|
+
name: 'plans',
|
|
922
|
+
scope: 'local',
|
|
923
|
+
usage: '/plans [import <json-file> | forget]',
|
|
924
|
+
description: 'Inspect, pre-warm, or clear reusable task plans',
|
|
925
|
+
dialogTitle: 'Plan cache',
|
|
926
|
+
complete: () => [
|
|
927
|
+
{ value: 'import', label: 'import', description: 'import seed plans from a JSON file' },
|
|
928
|
+
{ value: 'forget', label: 'forget', description: 'clear all cached plans' }
|
|
929
|
+
],
|
|
930
|
+
run: async (args = []) => {
|
|
931
|
+
const cache = await import('./planCache.js');
|
|
932
|
+
const verb = String(args[0] || '').toLowerCase();
|
|
933
|
+
|
|
934
|
+
if (verb === 'forget') {
|
|
935
|
+
const removed = cache.forgetPlans();
|
|
936
|
+
return ok(`Forgot ${removed} cached plan${removed === 1 ? '' : 's'}.`);
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
if (verb === 'import') {
|
|
940
|
+
const requested = args.slice(1).join(' ').trim();
|
|
941
|
+
if (!requested) return fail('Usage: /plans import <json-file>');
|
|
942
|
+
if (requested.includes('\0')) return fail('Invalid plan file path.');
|
|
943
|
+
const expanded = requested === '~'
|
|
944
|
+
? os.homedir()
|
|
945
|
+
: (requested.startsWith('~/') || requested.startsWith('~\\') ? path.join(os.homedir(), requested.slice(2)) : requested);
|
|
946
|
+
const file = path.resolve(expanded);
|
|
947
|
+
try {
|
|
948
|
+
const stat = fs.lstatSync(file);
|
|
949
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1024 * 1024) {
|
|
950
|
+
return fail('Plan seed must be one regular JSON file (not a symlink) no larger than 1 MB.');
|
|
951
|
+
}
|
|
952
|
+
const outcome = cache.prewarmPlans(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
953
|
+
const detail = outcome.errors.length > 0 ? `\n${outcome.errors.join('\n')}` : '';
|
|
954
|
+
return outcome.accepted > 0
|
|
955
|
+
? ok(`Imported ${outcome.accepted} plan${outcome.accepted === 1 ? '' : 's'}; rejected ${outcome.rejected}.${detail}`)
|
|
956
|
+
: fail(`No plans were imported.${detail}`);
|
|
957
|
+
} catch (error) {
|
|
958
|
+
return fail(`Could not import plan seeds: ${errMsg(error)}`);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
const stats = cache.planStats();
|
|
963
|
+
return ok([
|
|
964
|
+
`${stats.count} cached plan${stats.count === 1 ? '' : 's'}`,
|
|
965
|
+
`Hits: ${stats.hits}/${stats.lookups} (${(stats.hitRate * 100).toFixed(1)}%) — exact ${stats.exactHits}, fuzzy ${stats.fuzzyHits}`,
|
|
966
|
+
`Average lookup: ${stats.averageLookupMs.toFixed(3)} ms; max ${stats.maxLookupMs.toFixed(3)} ms`,
|
|
967
|
+
stats.disabled
|
|
968
|
+
? `Lookup cooling down until ${new Date(stats.disabledUntil).toISOString()} after persistent misses.`
|
|
969
|
+
: 'Lookup active.',
|
|
970
|
+
'',
|
|
971
|
+
'Pre-warm with /plans import <json-file>. Clear with /plans forget.'
|
|
972
|
+
].join('\n'));
|
|
973
|
+
}
|
|
974
|
+
},
|
|
975
|
+
|
|
976
|
+
{
|
|
977
|
+
name: 'plugins',
|
|
978
|
+
scope: 'local',
|
|
979
|
+
usage: '/plugins [list | enable <name> | disable <name>]',
|
|
980
|
+
description: 'Inspect or change trust for local plugins',
|
|
981
|
+
dialogTitle: 'Plugins',
|
|
982
|
+
complete: () => {
|
|
983
|
+
try {
|
|
984
|
+
const rows = listPlugins();
|
|
985
|
+
return [
|
|
986
|
+
{ value: 'list', label: 'list', description: 'list local plugins and trust status' },
|
|
987
|
+
...rows.map((p: any) => ({
|
|
988
|
+
value: `enable ${p.name}`,
|
|
989
|
+
label: `enable ${p.name}`,
|
|
990
|
+
description: `enable plugin ${p.name}`
|
|
991
|
+
})),
|
|
992
|
+
...rows.map((p: any) => ({
|
|
993
|
+
value: `disable ${p.name}`,
|
|
994
|
+
label: `disable ${p.name}`,
|
|
995
|
+
description: `disable plugin ${p.name}`
|
|
996
|
+
}))
|
|
997
|
+
];
|
|
998
|
+
} catch (e) {
|
|
999
|
+
return [
|
|
1000
|
+
{ value: 'list', label: 'list', description: 'list local plugins' },
|
|
1001
|
+
{ value: 'enable', label: 'enable', description: 'enable a local plugin' },
|
|
1002
|
+
{ value: 'disable', label: 'disable', description: 'disable a local plugin' }
|
|
1003
|
+
];
|
|
1004
|
+
}
|
|
1005
|
+
},
|
|
1006
|
+
run: async (args = []) => {
|
|
1007
|
+
const manager: any = await import('./plugins/pluginManager.js');
|
|
1008
|
+
const verb = String(args[0] || '').toLowerCase();
|
|
1009
|
+
const name = String(args[1] || '');
|
|
1010
|
+
if (verb === 'enable') {
|
|
1011
|
+
if (!name) return fail('Usage: /plugins enable <name>');
|
|
1012
|
+
const result = manager.enablePlugin(name);
|
|
1013
|
+
return result.ok
|
|
1014
|
+
? ok(`Enabled ${name} at manifest digest ${result.digest}. Changes will revoke trust automatically.`)
|
|
1015
|
+
: fail(`Could not enable ${name}: ${result.error}`);
|
|
1016
|
+
}
|
|
1017
|
+
if (verb === 'disable') {
|
|
1018
|
+
if (!name) return fail('Usage: /plugins disable <name>');
|
|
1019
|
+
const result = manager.disablePlugin(name);
|
|
1020
|
+
return result.ok ? ok(`Disabled ${name}.`) : fail(`Could not disable ${name}: ${result.error}`);
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
const rows = manager.listPlugins();
|
|
1024
|
+
if (rows.length === 0) return ok(`No local plugins. Plugin root: ${manager.PLUGIN_ROOT}`);
|
|
1025
|
+
return ok(rows.map((plugin: any) => {
|
|
1026
|
+
const state = plugin.invalid ? 'invalid' : plugin.modified ? 'modified; trust revoked' : plugin.enabled ? 'enabled' : 'disabled';
|
|
1027
|
+
const capabilities = Array.isArray(plugin.capabilities) && plugin.capabilities.length > 0
|
|
1028
|
+
? plugin.capabilities.join(', ')
|
|
1029
|
+
: 'none';
|
|
1030
|
+
return ` ${plugin.name} ${plugin.version || ''} — ${state}; capabilities: ${capabilities}`;
|
|
1031
|
+
}).join('\n') + `\n\nPlugin root: ${manager.PLUGIN_ROOT}`);
|
|
1032
|
+
}
|
|
1033
|
+
},
|
|
1034
|
+
|
|
1035
|
+
{
|
|
1036
|
+
name: 'new',
|
|
1037
|
+
aliases: ['new-session'],
|
|
1038
|
+
scope: 'local',
|
|
1039
|
+
usage: '/new',
|
|
1040
|
+
description: 'Start a new clean chat session in this workspace',
|
|
1041
|
+
dialogTitle: 'New Session',
|
|
1042
|
+
run: async (_args = [], context = {}) => {
|
|
1043
|
+
const store = await import('./sessionStore.js');
|
|
1044
|
+
const memory = context.loop && context.loop.memoryManager;
|
|
1045
|
+
const workspace = context.loop?.workspaceRoot || context.prompt?.root || process.cwd();
|
|
1046
|
+
const next = memory ? memory.startNewSession('Untitled') : store.createSession(workspace, 'Untitled', true);
|
|
1047
|
+
await resetStandingApprovals(context);
|
|
1048
|
+
if (context.loop) {
|
|
1049
|
+
context.loop.messages = [];
|
|
1050
|
+
context.loop.taskId = `cli_chat_${Date.now()}`;
|
|
1051
|
+
if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
|
|
1052
|
+
context.loop.tokenTracker.reset();
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
const renderer = context.prompt?.renderer || context.loop?.connection?.renderer;
|
|
1056
|
+
if (renderer && typeof renderer.renderSessionHistory === 'function') {
|
|
1057
|
+
renderer.renderSessionHistory([], { id: next.id, title: next.title, messagesCount: 0 });
|
|
1058
|
+
}
|
|
1059
|
+
if (context.prompt?.surface?.viewport && typeof context.prompt.surface.viewport.toBottom === 'function') {
|
|
1060
|
+
context.prompt.surface.viewport.toBottom();
|
|
1061
|
+
}
|
|
1062
|
+
if (context.prompt?.editor?.clear) {
|
|
1063
|
+
context.prompt.editor.clear();
|
|
1064
|
+
if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
|
|
1065
|
+
}
|
|
1066
|
+
return ok(`Started new session: "${next.title}" (${next.id}).`, { effect: 'inline' });
|
|
1067
|
+
}
|
|
1068
|
+
},
|
|
1069
|
+
|
|
1070
|
+
{
|
|
1071
|
+
name: 'sessions',
|
|
1072
|
+
aliases: ['session'],
|
|
1073
|
+
scope: 'local',
|
|
1074
|
+
usage: '/sessions [new | switch <id> | delete <id>]',
|
|
1075
|
+
description: 'List chat sessions, or switch to one',
|
|
1076
|
+
dialogTitle: 'Sessions',
|
|
1077
|
+
complete: () => {
|
|
1078
|
+
try {
|
|
1079
|
+
const rows = listSessions().slice(0, 15);
|
|
1080
|
+
return [
|
|
1081
|
+
{ value: 'new', label: 'new', description: 'start a fresh conversation in this workspace' },
|
|
1082
|
+
...rows.map((r: any) => ({
|
|
1083
|
+
value: `switch ${r.id}`,
|
|
1084
|
+
label: `switch ${r.id}`,
|
|
1085
|
+
description: `${r.title} (${r.messageCount} msgs)`
|
|
1086
|
+
}))
|
|
1087
|
+
];
|
|
1088
|
+
} catch (e) {
|
|
1089
|
+
return [{ value: 'new', label: 'new', description: 'start a fresh conversation' }];
|
|
1090
|
+
}
|
|
1091
|
+
},
|
|
1092
|
+
run: async (args = [], context = {}) => {
|
|
1093
|
+
const store = await import('./sessionStore.js');
|
|
1094
|
+
const verb = String(args[0] || '').toLowerCase();
|
|
1095
|
+
const memory = context.loop && context.loop.memoryManager;
|
|
1096
|
+
const workspace = context.loop?.workspaceRoot || context.prompt?.root || process.cwd();
|
|
1097
|
+
|
|
1098
|
+
// If interactive TUI prompt is available and no sub-arguments are given, open interactive picker modal
|
|
1099
|
+
if ((!args || args.length === 0 || (args.length === 1 && args[0] === '')) && context.prompt) {
|
|
1100
|
+
const { runInteractiveSessionPicker } = await import('./tui/sessionPicker.js');
|
|
1101
|
+
const message = await runInteractiveSessionPicker(context.prompt, {
|
|
1102
|
+
loop: context.loop,
|
|
1103
|
+
workspace
|
|
1104
|
+
});
|
|
1105
|
+
return ok(message, { effect: 'silent' });
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
if (verb === 'new') {
|
|
1109
|
+
const next = memory ? memory.startNewSession('Untitled') : store.createSession(workspace, 'Untitled', true);
|
|
1110
|
+
await resetStandingApprovals(context);
|
|
1111
|
+
if (context.loop) {
|
|
1112
|
+
context.loop.messages = [];
|
|
1113
|
+
context.loop.taskId = `cli_chat_${Date.now()}`;
|
|
1114
|
+
if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
|
|
1115
|
+
context.loop.tokenTracker.reset();
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
if (context.prompt?.editor?.clear) {
|
|
1119
|
+
context.prompt.editor.clear();
|
|
1120
|
+
if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
|
|
1121
|
+
}
|
|
1122
|
+
return ok(`Started new session: "${next.title}" (${next.id}).`, { effect: 'inline' });
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
if (verb === 'switch' && args[1]) {
|
|
1126
|
+
const next = memory ? memory.useSession(args[1]) : store.switchSession(args[1]);
|
|
1127
|
+
if (!next) return fail(`No session "${args[1]}".`);
|
|
1128
|
+
await resetStandingApprovals(context);
|
|
1129
|
+
const historyMessages = memory ? memory.loadHistory() : next.messages.filter((m: any) => m.role !== 'system');
|
|
1130
|
+
if (context.loop) {
|
|
1131
|
+
context.loop.messages = historyMessages;
|
|
1132
|
+
context.loop.taskId = `cli_chat_${Date.now()}`;
|
|
1133
|
+
if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
|
|
1134
|
+
context.loop.tokenTracker.reset();
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
const renderer = context.prompt?.renderer || context.loop?.connection?.renderer;
|
|
1138
|
+
if (renderer && typeof renderer.renderSessionHistory === 'function') {
|
|
1139
|
+
renderer.renderSessionHistory(historyMessages, {
|
|
1140
|
+
id: next.id,
|
|
1141
|
+
title: next.title,
|
|
1142
|
+
messagesCount: next.messages.length
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
if (context.prompt?.surface?.viewport && typeof context.prompt.surface.viewport.toBottom === 'function') {
|
|
1146
|
+
context.prompt.surface.viewport.toBottom();
|
|
1147
|
+
}
|
|
1148
|
+
if (context.prompt?.editor?.clear) {
|
|
1149
|
+
context.prompt.editor.clear();
|
|
1150
|
+
if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
|
|
1151
|
+
}
|
|
1152
|
+
return ok(`Switched to "${next.title}" (${next.messages.length} messages, ${next.id}).`, { effect: 'inline' });
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
if (verb === 'fork') {
|
|
1156
|
+
const sourceId = args[1] || (memory ? memory.sessionId : store.getActiveSessionId());
|
|
1157
|
+
if (!sourceId) return fail('No session specified to fork.');
|
|
1158
|
+
const forked = memory && memory.sessionId === sourceId
|
|
1159
|
+
? memory.forkSession()
|
|
1160
|
+
: store.forkSession(sourceId, { makeActive: true });
|
|
1161
|
+
if (!forked) return fail(`Could not fork session "${sourceId}".`);
|
|
1162
|
+
|
|
1163
|
+
// CRITICAL TRUST INVARIANT (Claude Code Architecture, p. 24):
|
|
1164
|
+
// Permissions and allowlists NEVER carry across forks.
|
|
1165
|
+
const { revokeAllAlways } = await import('./approvalGrants.js');
|
|
1166
|
+
revokeAllAlways();
|
|
1167
|
+
if (context.loop && typeof context.loop.resetApprovalScope === 'function') {
|
|
1168
|
+
context.loop.resetApprovalScope();
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
const historyMessages = memory ? memory.loadHistory() : forked.messages.filter((m: any) => m.role !== 'system');
|
|
1172
|
+
if (context.loop) {
|
|
1173
|
+
context.loop.messages = historyMessages;
|
|
1174
|
+
context.loop.taskId = `cli_chat_${Date.now()}`;
|
|
1175
|
+
if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
|
|
1176
|
+
context.loop.tokenTracker.reset();
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
const renderer = context.prompt?.renderer || context.loop?.connection?.renderer;
|
|
1180
|
+
if (renderer && typeof renderer.renderSessionHistory === 'function') {
|
|
1181
|
+
renderer.renderSessionHistory(historyMessages, {
|
|
1182
|
+
id: forked.id,
|
|
1183
|
+
title: forked.title,
|
|
1184
|
+
messagesCount: forked.messages.length
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
if (context.prompt?.surface?.viewport && typeof context.prompt.surface.viewport.toBottom === 'function') {
|
|
1188
|
+
context.prompt.surface.viewport.toBottom();
|
|
1189
|
+
}
|
|
1190
|
+
if (context.prompt?.editor?.clear) {
|
|
1191
|
+
context.prompt.editor.clear();
|
|
1192
|
+
if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
|
|
1193
|
+
}
|
|
1194
|
+
return ok(`Forked session into "${forked.title}" (${forked.messages.length} messages, ${forked.id}).\nPermissions and standing approvals were reset; any gated actions will request authorization anew.`, { effect: 'inline' });
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
if (verb === 'delete' && args[1]) {
|
|
1198
|
+
return store.deleteSession(args[1]) ? ok(`Deleted session "${args[1]}".`) : fail(`No session "${args[1]}".`);
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
const rows = store.listSessions();
|
|
1202
|
+
if (rows.length === 0) {
|
|
1203
|
+
return ok('No sessions yet. This conversation becomes one as soon as you send something.');
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
const active = memory?.sessionId || store.getActiveSessionId();
|
|
1207
|
+
const { formatSessionsTextReport } = await import('./tui/sessionPicker.js');
|
|
1208
|
+
|
|
1209
|
+
return ok(
|
|
1210
|
+
formatSessionsTextReport(rows, active, workspace),
|
|
1211
|
+
{ effect: 'pick-session', items: rows, active }
|
|
1212
|
+
);
|
|
1213
|
+
}
|
|
1214
|
+
},
|
|
1215
|
+
|
|
1216
|
+
{
|
|
1217
|
+
name: 'fork',
|
|
1218
|
+
aliases: ['branch', 'fork-session'],
|
|
1219
|
+
scope: 'local',
|
|
1220
|
+
usage: '/fork [sessionId]',
|
|
1221
|
+
description: 'Fork the conversation into a new session without copying permissions',
|
|
1222
|
+
dialogTitle: 'Fork Session',
|
|
1223
|
+
complete: () => {
|
|
1224
|
+
try {
|
|
1225
|
+
const rows = listSessions().slice(0, 15);
|
|
1226
|
+
return rows.map((r: any) => ({
|
|
1227
|
+
value: r.id,
|
|
1228
|
+
label: r.id,
|
|
1229
|
+
description: `${r.title} (${r.messageCount} msgs)`
|
|
1230
|
+
}));
|
|
1231
|
+
} catch (e) {
|
|
1232
|
+
return [];
|
|
1233
|
+
}
|
|
1234
|
+
},
|
|
1235
|
+
run: async (args = [], context = {}) => {
|
|
1236
|
+
const store = await import('./sessionStore.js');
|
|
1237
|
+
const { revokeAllAlways } = await import('./approvalGrants.js');
|
|
1238
|
+
const memory = context.loop && context.loop.memoryManager;
|
|
1239
|
+
|
|
1240
|
+
const sourceId = args[0] || (memory ? memory.sessionId : store.getActiveSessionId());
|
|
1241
|
+
if (!sourceId) {
|
|
1242
|
+
return fail('No active or specified session to fork.');
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
const sourceSession = store.getSession(sourceId);
|
|
1246
|
+
if (!sourceSession) {
|
|
1247
|
+
return fail(`Session "${sourceId}" not found.`);
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
const forked = memory && memory.sessionId === sourceId
|
|
1251
|
+
? memory.forkSession()
|
|
1252
|
+
: store.forkSession(sourceId, { makeActive: true });
|
|
1253
|
+
|
|
1254
|
+
if (!forked) {
|
|
1255
|
+
return fail(`Could not fork session "${sourceId}".`);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
// CRITICAL SECURITY INVARIANT (Claude Code Architecture, p. 24):
|
|
1259
|
+
// Permissions and allowlists MUST NOT be copied across the fork.
|
|
1260
|
+
revokeAllAlways();
|
|
1261
|
+
if (context.loop && typeof context.loop.resetApprovalScope === 'function') {
|
|
1262
|
+
context.loop.resetApprovalScope();
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
if (memory) {
|
|
1266
|
+
memory.session = forked;
|
|
1267
|
+
}
|
|
1268
|
+
const historyMessages = memory ? memory.loadHistory() : forked.messages.filter((m: any) => m.role !== 'system');
|
|
1269
|
+
if (context.loop) {
|
|
1270
|
+
context.loop.messages = historyMessages;
|
|
1271
|
+
context.loop.taskId = `cli_chat_${Date.now()}`;
|
|
1272
|
+
if (context.loop.tokenTracker && typeof context.loop.tokenTracker.reset === 'function') {
|
|
1273
|
+
context.loop.tokenTracker.reset();
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
const renderer = context.prompt?.renderer || context.loop?.connection?.renderer;
|
|
1278
|
+
if (renderer && typeof renderer.renderSessionHistory === 'function') {
|
|
1279
|
+
renderer.renderSessionHistory(historyMessages, {
|
|
1280
|
+
id: forked.id,
|
|
1281
|
+
title: forked.title,
|
|
1282
|
+
messagesCount: forked.messages.length
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
if (context.prompt?.surface?.viewport && typeof context.prompt.surface.viewport.toBottom === 'function') {
|
|
1286
|
+
context.prompt.surface.viewport.toBottom();
|
|
1287
|
+
}
|
|
1288
|
+
if (context.prompt?.editor?.clear) {
|
|
1289
|
+
context.prompt.editor.clear();
|
|
1290
|
+
if (typeof context.prompt.scheduleDraw === 'function') context.prompt.scheduleDraw();
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
return ok(`Forked session "${sourceSession.title}" into "${forked.title}" (${forked.id}) with ${forked.messages.length} messages.\nPermissions and allowlists reset: tools will request approval anew.`, { effect: 'inline' });
|
|
1294
|
+
}
|
|
1295
|
+
},
|
|
1296
|
+
|
|
1297
|
+
{
|
|
1298
|
+
name: 'continuum',
|
|
1299
|
+
aliases: ['resume'],
|
|
1300
|
+
scope: 'local',
|
|
1301
|
+
usage: '/continuum [list | read <id> | adopt <id>]',
|
|
1302
|
+
description: 'Cross-agent session extraction and resumption (Antigravity, OpenCode, Codex, Claude Code)',
|
|
1303
|
+
dialogTitle: 'Continuum',
|
|
1304
|
+
complete: () => [
|
|
1305
|
+
{ value: 'list', label: 'list', description: 'scan and list cross-agent sessions' },
|
|
1306
|
+
{ value: 'adopt', label: 'adopt', description: 'adopt and resume a peer agent session' },
|
|
1307
|
+
{ value: 'read', label: 'read', description: 'preview transcript of a peer session' }
|
|
1308
|
+
],
|
|
1309
|
+
run: async (args = [], context = {}) => {
|
|
1310
|
+
const {
|
|
1311
|
+
ContinuumScanner,
|
|
1312
|
+
adoptContinuumSession,
|
|
1313
|
+
runInteractiveContinuum,
|
|
1314
|
+
openContinuumPreview
|
|
1315
|
+
} = await import('./continuum/index.js');
|
|
1316
|
+
|
|
1317
|
+
const verb = String(args[0] || '').toLowerCase();
|
|
1318
|
+
const targetId = args[1];
|
|
1319
|
+
|
|
1320
|
+
// If interactive modal prompt is available and no subverb is passed
|
|
1321
|
+
if (!verb && context.prompt && typeof context.prompt.openLayer === 'function') {
|
|
1322
|
+
const resultText = await runInteractiveContinuum(context.prompt, {
|
|
1323
|
+
loop: context.loop
|
|
1324
|
+
});
|
|
1325
|
+
return ok(resultText, { effect: 'silent' });
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
const scanner = context.scanner || new ContinuumScanner();
|
|
1329
|
+
|
|
1330
|
+
if (verb === 'read' && targetId) {
|
|
1331
|
+
if (context.prompt && typeof context.prompt.openLayer === 'function') {
|
|
1332
|
+
const opened = await openContinuumPreview(targetId, context.prompt, scanner);
|
|
1333
|
+
if (opened) return ok(`Displaying preview for ${targetId}.`);
|
|
1334
|
+
}
|
|
1335
|
+
const detail = await scanner.fetchSession(targetId);
|
|
1336
|
+
if (!detail) return fail(`No peer session found with ID "${targetId}".`);
|
|
1337
|
+
const transcriptText = (Array.isArray(detail.messages) ? detail.messages : [])
|
|
1338
|
+
.map((m: any) => `[${safeDisplay(String(m?.role || 'unknown').toUpperCase())}] ${safeDisplay(typeof m?.content === 'string' ? m.content : JSON.stringify(m?.content ?? ''))}`)
|
|
1339
|
+
.join('\n\n');
|
|
1340
|
+
return ok(`=== ${safeDisplay(detail.title)} (${safeDisplay(detail.sourceLabel)}) ===\nWorkspace: ${safeDisplay(detail.workspacePath)}\n\n${transcriptText}`);
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
if (verb === 'adopt' && targetId) {
|
|
1344
|
+
const adoptRes = await adoptContinuumSession(targetId, {
|
|
1345
|
+
scanner,
|
|
1346
|
+
currentLoopMessages: context.loop?.messages
|
|
1347
|
+
});
|
|
1348
|
+
if (!adoptRes.ok) return fail(adoptRes.error || `Failed to adopt session "${targetId}".`);
|
|
1349
|
+
await resetStandingApprovals(context);
|
|
1350
|
+
if (context.loop?.memoryManager) {
|
|
1351
|
+
context.loop.memoryManager.useSession(adoptRes.sessionId);
|
|
1352
|
+
if (typeof context.loop.memoryManager.loadHistory === 'function') {
|
|
1353
|
+
context.loop.messages = context.loop.memoryManager.loadHistory();
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
return ok(`Successfully adopted session "${adoptRes.title}" from ${adoptRes.sourcePlatform.toUpperCase()} (${adoptRes.messageCount} messages compacted).\nActive Causyne session: ${adoptRes.sessionId}.`);
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
// Default or 'list':
|
|
1360
|
+
const sessions = await scanner.scanAllSessions({ limit: 40 });
|
|
1361
|
+
if (sessions.length === 0) {
|
|
1362
|
+
return ok('No peer agent sessions discovered across Antigravity, OpenCode, Codex, or Claude Code.');
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
const lines = sessions.map((s: any) => {
|
|
1366
|
+
const ts = typeof s.updatedAt === 'number' && Number.isFinite(s.updatedAt) ? s.updatedAt : Date.now();
|
|
1367
|
+
const when = new Date(ts).toISOString().slice(0, 16).replace('T', ' ');
|
|
1368
|
+
const ws = s.workspacePath ? safeDisplay(path.basename(s.workspacePath)) : '(default)';
|
|
1369
|
+
return ` [${safeDisplay(s.sourceLabel).padEnd(12)}] ${safeDisplay(s.id).padEnd(38)} ${when} ${String(s.messageCount ?? 0).padStart(3)} msgs ${ws}\n ${safeDisplay(s.title)}`;
|
|
1370
|
+
});
|
|
1371
|
+
|
|
1372
|
+
return ok(
|
|
1373
|
+
`Discovered ${sessions.length} cross-agent sessions:\n`
|
|
1374
|
+
+ lines.join('\n')
|
|
1375
|
+
+ '\n\nUsage:\n /continuum — open interactive picker\n /continuum adopt <id> — adopt & resume session\n /continuum read <id> — preview full transcript'
|
|
1376
|
+
);
|
|
1377
|
+
}
|
|
1378
|
+
},
|
|
1379
|
+
|
|
1380
|
+
{
|
|
1381
|
+
name: 'cortex',
|
|
1382
|
+
aliases: ['memory'],
|
|
1383
|
+
scope: 'local',
|
|
1384
|
+
usage: '/cortex [status | list | search <query> | on | off | forget <id|--workspace>]',
|
|
1385
|
+
description: 'Inspect, search, toggle, or clear persistent Cortex memory',
|
|
1386
|
+
dialogTitle: 'Cortex Memory',
|
|
1387
|
+
complete: () => [
|
|
1388
|
+
{ value: 'status', label: 'status', description: 'show Cortex memory counts and engine status' },
|
|
1389
|
+
{ value: 'list', label: 'list', description: 'list recent memories stored for this workspace' },
|
|
1390
|
+
{ value: 'search', label: 'search', description: 'semantic search across stored memories' },
|
|
1391
|
+
{ value: 'on', label: 'on', description: 'enable persistent Cortex memory recall' },
|
|
1392
|
+
{ value: 'off', label: 'off', description: 'disable persistent Cortex memory recall' },
|
|
1393
|
+
{ value: 'forget --workspace', label: 'forget --workspace', description: 'clear memories for the current workspace' }
|
|
1394
|
+
],
|
|
1395
|
+
run: async (argv, ctx = {}) => {
|
|
1396
|
+
const sub = String(argv[0] || 'status').trim().toLowerCase();
|
|
1397
|
+
const workspace = ctx.loop?.workspaceRoot || process.cwd();
|
|
1398
|
+
|
|
1399
|
+
if (sub === 'on' || sub === 'enable' || sub === 'off' || sub === 'disable') {
|
|
1400
|
+
const enabled = sub === 'on' || sub === 'enable';
|
|
1401
|
+
const config = loadConfig();
|
|
1402
|
+
const prev = config.cortex && typeof config.cortex === 'object' ? config.cortex : {};
|
|
1403
|
+
config.cortex = { ...prev, enabled };
|
|
1404
|
+
saveConfig(config);
|
|
1405
|
+
if (ctx.loop) {
|
|
1406
|
+
ctx.loop.config = loadConfig();
|
|
1407
|
+
}
|
|
1408
|
+
return ok(
|
|
1409
|
+
`Cortex persistent memory is now ${enabled ? 'ENABLED' : 'DISABLED'}.`,
|
|
1410
|
+
{ effect: 'inline' }
|
|
1411
|
+
);
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
const config = loadConfig();
|
|
1415
|
+
const enabled = config.cortex?.enabled !== false;
|
|
1416
|
+
|
|
1417
|
+
let cortexDb: any;
|
|
1418
|
+
try {
|
|
1419
|
+
const mod = await import('./cortex/vectorDb.js');
|
|
1420
|
+
cortexDb = mod.cortexDb;
|
|
1421
|
+
} catch (e) {
|
|
1422
|
+
return fail(`Cortex memory backend could not be loaded: ${safeDisplay(errMsg(e))}`);
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
if (sub === 'status') {
|
|
1426
|
+
try {
|
|
1427
|
+
const stats = await cortexDb.stats();
|
|
1428
|
+
const byKindText = Array.isArray(stats.byKind) && stats.byKind.length > 0
|
|
1429
|
+
? stats.byKind.map((k: any) => `${safeDisplay(String(k.kind || 'general'))}: ${k.c}`).join(', ')
|
|
1430
|
+
: 'none';
|
|
1431
|
+
const newest = stats.newest
|
|
1432
|
+
? new Date(stats.newest).toISOString().slice(0, 16).replace('T', ' ')
|
|
1433
|
+
: 'never';
|
|
1434
|
+
return ok([
|
|
1435
|
+
`Cortex Status : ${enabled ? 'Enabled' : 'Disabled'}`,
|
|
1436
|
+
`Engine : ${safeDisplay(String(stats.engineType || 'native'))}`,
|
|
1437
|
+
`Neural Vectors : ${stats.isNeural ? 'Active' : 'Lexical fallback'}`,
|
|
1438
|
+
`Stored Memories : ${stats.total} (${stats.distinct} distinct across ${stats.workspaces} workspace${stats.workspaces === 1 ? '' : 's'})`,
|
|
1439
|
+
`Extended Store : ${stats.episodicCount ?? 0} episodic, ${stats.factsCount ?? 0} durable facts`,
|
|
1440
|
+
`Breakdown : ${byKindText}`,
|
|
1441
|
+
`Last Updated : ${newest}`,
|
|
1442
|
+
'',
|
|
1443
|
+
'Commands: /cortex list | /cortex search <query> | /cortex on | /cortex off | /cortex forget <id|--workspace>'
|
|
1444
|
+
].join('\n'));
|
|
1445
|
+
} catch (e) {
|
|
1446
|
+
return ok([
|
|
1447
|
+
`Cortex Status : ${enabled ? 'Enabled' : 'Disabled'}`,
|
|
1448
|
+
`Store : Not initialized (${safeDisplay(errMsg(e))})`
|
|
1449
|
+
].join('\n'));
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
if (sub === 'list' || sub === 'ls') {
|
|
1454
|
+
const rows = await cortexDb.inventory({ workspace });
|
|
1455
|
+
if (!Array.isArray(rows) || rows.length === 0) {
|
|
1456
|
+
return ok(`No Cortex memories stored for ${safeDisplay(path.basename(workspace) || workspace)}.`);
|
|
1457
|
+
}
|
|
1458
|
+
const preview = rows.slice(0, 20).map((r: any) => {
|
|
1459
|
+
const snippet = safeDisplay(String(r.text || '').replace(/\s+/g, ' ').trim()).slice(0, 110);
|
|
1460
|
+
return ` [${safeDisplay(String(r.kind || 'general')).padEnd(9)}] ${safeDisplay(String(r.id))} (hits:${r.hits ?? 0})\n ${snippet}`;
|
|
1461
|
+
});
|
|
1462
|
+
return ok(`Cortex memories for ${safeDisplay(path.basename(workspace) || workspace)} (${rows.length}):\n\n${preview.join('\n')}`);
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
if (sub === 'search' || sub === 'find') {
|
|
1466
|
+
const query = argv.slice(1).join(' ').trim();
|
|
1467
|
+
if (!query) return fail('Usage: /cortex search <query>');
|
|
1468
|
+
const hits = await cortexDb.search(query, 8, { workspace });
|
|
1469
|
+
if (!Array.isArray(hits) || hits.length === 0) {
|
|
1470
|
+
return ok(`No Cortex memories matched "${safeDisplay(query)}".`);
|
|
1471
|
+
}
|
|
1472
|
+
const lines = hits.map((h: any, idx: number) => {
|
|
1473
|
+
const pct = Number.isFinite(h.score) ? `${Math.round(h.score * 100)}%` : 'n/a';
|
|
1474
|
+
const snippet = safeDisplay(String(h.text || '').replace(/\s+/g, ' ').trim()).slice(0, 140);
|
|
1475
|
+
return ` ${idx + 1}. [${safeDisplay(String(h.kind || 'general'))} · ${pct}] ${safeDisplay(String(h.id))}\n ${snippet}`;
|
|
1476
|
+
});
|
|
1477
|
+
return ok(`Cortex matches for "${safeDisplay(query)}":\n\n${lines.join('\n')}`);
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
if (sub === 'forget' || sub === 'delete' || sub === 'clear') {
|
|
1481
|
+
const target = String(argv[1] || '').trim();
|
|
1482
|
+
if (!target) {
|
|
1483
|
+
return fail('Usage: /cortex forget <memoryId> | /cortex forget --workspace');
|
|
1484
|
+
}
|
|
1485
|
+
if (target === '--workspace') {
|
|
1486
|
+
const removed = await cortexDb.forget({ workspace });
|
|
1487
|
+
return ok(`Removed ${removed} Cortex memor${removed === 1 ? 'y' : 'ies'} for workspace ${safeDisplay(path.basename(workspace) || workspace)}.`, { effect: 'inline' });
|
|
1488
|
+
}
|
|
1489
|
+
const removed = await cortexDb.forget({ id: target });
|
|
1490
|
+
return removed > 0
|
|
1491
|
+
? ok(`Forgot Cortex memory "${safeDisplay(target)}".`, { effect: 'inline' })
|
|
1492
|
+
: fail(`No Cortex memory found with ID "${safeDisplay(target)}".`);
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
return fail(`Unknown /cortex subcommand "${safeDisplay(sub)}". Try /cortex status, list, search <query>, on, off, or forget <id|--workspace>.`);
|
|
1496
|
+
}
|
|
1497
|
+
},
|
|
1498
|
+
|
|
1499
|
+
{
|
|
1500
|
+
name: 'approvals',
|
|
1501
|
+
scope: 'local',
|
|
1502
|
+
usage: '/approvals [clear]',
|
|
1503
|
+
description: 'List tools granted "Allow always", or revoke them',
|
|
1504
|
+
dialogTitle: 'Approvals',
|
|
1505
|
+
complete: () => [
|
|
1506
|
+
{ value: 'clear', label: 'clear', description: 'revoke all standing "Allow always" grants' }
|
|
1507
|
+
],
|
|
1508
|
+
// A standing grant with no way to see or revoke it is a trap, not a
|
|
1509
|
+
// convenience. This is the way out, and the confirm dialog that grants one
|
|
1510
|
+
// names this command so the user is told about it at the moment it matters.
|
|
1511
|
+
run: async (args = []) => {
|
|
1512
|
+
const { listAlwaysAllowed, revokeAllAlways } = await import('./approvalGrants.js');
|
|
1513
|
+
|
|
1514
|
+
if (String(args[0] || '').toLowerCase() === 'clear') {
|
|
1515
|
+
const count = revokeAllAlways();
|
|
1516
|
+
return ok(count === 0
|
|
1517
|
+
? 'No standing approvals to revoke.'
|
|
1518
|
+
: `Revoked ${count} standing approval${count === 1 ? '' : 's'}. Causyne will ask again.`);
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
const granted = listAlwaysAllowed();
|
|
1522
|
+
if (granted.length === 0) {
|
|
1523
|
+
return ok('No standing approvals. Every gated action still asks.');
|
|
1524
|
+
}
|
|
1525
|
+
return ok(
|
|
1526
|
+
'Running without asking, until Causyne restarts:\n'
|
|
1527
|
+
+ granted.map((tool) => ` - ${tool}`).join('\n')
|
|
1528
|
+
+ '\n\nRevoke with /approvals clear.'
|
|
1529
|
+
);
|
|
1530
|
+
}
|
|
1531
|
+
},
|
|
1532
|
+
|
|
1533
|
+
{
|
|
1534
|
+
name: 'thinking',
|
|
1535
|
+
aliases: ['thought', 'thoughts'],
|
|
1536
|
+
scope: 'local',
|
|
1537
|
+
usage: '/thinking [toggle|expand|collapse]',
|
|
1538
|
+
description: 'Toggle or fold thinking process chunks in the conversation transcript',
|
|
1539
|
+
complete: () => [
|
|
1540
|
+
{ value: 'toggle', label: 'toggle', description: 'toggle collapsed state of thinking blocks' },
|
|
1541
|
+
{ value: 'expand', label: 'expand', description: 'expand all thinking blocks' },
|
|
1542
|
+
{ value: 'collapse', label: 'collapse', description: 'collapse all thinking blocks' }
|
|
1543
|
+
],
|
|
1544
|
+
run: (argv, ctx) => {
|
|
1545
|
+
const surface = ctx?.prompt?.surface;
|
|
1546
|
+
const transcript = surface?.transcript;
|
|
1547
|
+
const reasoningFrames = Array.isArray(transcript?.frames)
|
|
1548
|
+
? transcript.frames.filter((f: any) => f.kind === 'reasoning' || f.meta?.reasoning === true)
|
|
1549
|
+
: [];
|
|
1550
|
+
const sub = (argv[0] || 'toggle').toLowerCase();
|
|
1551
|
+
if (sub !== 'toggle' && sub !== 'expand' && sub !== 'collapse') {
|
|
1552
|
+
return fail('Usage: /thinking [toggle|expand|collapse]');
|
|
1553
|
+
}
|
|
1554
|
+
let newCollapsed: boolean;
|
|
1555
|
+
if (sub === 'expand') {
|
|
1556
|
+
newCollapsed = false;
|
|
1557
|
+
} else if (sub === 'collapse') {
|
|
1558
|
+
newCollapsed = true;
|
|
1559
|
+
} else {
|
|
1560
|
+
const last = reasoningFrames[reasoningFrames.length - 1];
|
|
1561
|
+
newCollapsed = !Boolean(last?.meta?.collapsed);
|
|
1562
|
+
}
|
|
1563
|
+
for (const frame of reasoningFrames) {
|
|
1564
|
+
if (frame.meta) {
|
|
1565
|
+
frame.meta.collapsed = newCollapsed;
|
|
1566
|
+
frame.rows = null;
|
|
1567
|
+
frame.renderedWidth = -1;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
if (transcript) {
|
|
1571
|
+
transcript.cache = null;
|
|
1572
|
+
transcript.revision++;
|
|
1573
|
+
transcript.changed?.();
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
const msg = reasoningFrames.length === 0
|
|
1577
|
+
? 'No thinking process frames found in the current conversation.'
|
|
1578
|
+
: `${newCollapsed ? 'Collapsed' : 'Expanded'} ${reasoningFrames.length} thinking frame${reasoningFrames.length === 1 ? '' : 's'}.`;
|
|
1579
|
+
|
|
1580
|
+
if (ctx.prompt) {
|
|
1581
|
+
ctx.prompt.notice = msg;
|
|
1582
|
+
if (ctx.prompt.scheduleDraw) ctx.prompt.scheduleDraw();
|
|
1583
|
+
return ok(msg, { effect: 'silent' });
|
|
1584
|
+
}
|
|
1585
|
+
return ok(msg);
|
|
1586
|
+
}
|
|
1587
|
+
},
|
|
1588
|
+
|
|
1589
|
+
{
|
|
1590
|
+
name: 'clear',
|
|
1591
|
+
aliases: ['reset'],
|
|
1592
|
+
scope: 'local',
|
|
1593
|
+
usage: '/clear',
|
|
1594
|
+
description: 'Clear the conversation and start from a fresh context',
|
|
1595
|
+
run: (argv, ctx) => {
|
|
1596
|
+
const loop = ctx.loop;
|
|
1597
|
+
if (loop) {
|
|
1598
|
+
loop.messages = [];
|
|
1599
|
+
loop.unlockedPacks = new Set();
|
|
1600
|
+
loop.unlockedTools = new Set();
|
|
1601
|
+
loop.unlockOrder = [];
|
|
1602
|
+
loop.staticContext = null;
|
|
1603
|
+
loop.isInitialized = false;
|
|
1604
|
+
if (typeof loop.rearmAbortController === 'function') loop.rearmAbortController();
|
|
1605
|
+
if (loop.memoryManager) loop.memoryManager.clearHistory();
|
|
1606
|
+
if (loop.tokenTracker && typeof loop.tokenTracker.reset === 'function') {
|
|
1607
|
+
loop.tokenTracker.reset();
|
|
1608
|
+
}
|
|
1609
|
+
if (ctx.prompt && Array.isArray(ctx.prompt.pendingAttachments)) {
|
|
1610
|
+
ctx.prompt.pendingAttachments = [];
|
|
1611
|
+
}
|
|
1612
|
+
const renderer = ctx.prompt?.renderer || loop.connection?.renderer;
|
|
1613
|
+
if (renderer && typeof renderer.clearTranscript === 'function') {
|
|
1614
|
+
renderer.clearTranscript();
|
|
1615
|
+
}
|
|
1616
|
+
if (ctx.prompt?.surface?.viewport && typeof ctx.prompt.surface.viewport.toBottom === 'function') {
|
|
1617
|
+
ctx.prompt.surface.viewport.toBottom();
|
|
1618
|
+
}
|
|
1619
|
+
if (ctx.prompt?.scheduleDraw) ctx.prompt.scheduleDraw();
|
|
1620
|
+
return ok('Conversation cleared. The next task starts from a clean context.');
|
|
1621
|
+
}
|
|
1622
|
+
return fail('No active session to clear.');
|
|
1623
|
+
}
|
|
1624
|
+
},
|
|
1625
|
+
|
|
1626
|
+
{
|
|
1627
|
+
name: 'compact',
|
|
1628
|
+
aliases: ['compress', 'summarize'],
|
|
1629
|
+
scope: 'local',
|
|
1630
|
+
usage: '/compact [--preview] [--keep <turns>] [focus instructions]',
|
|
1631
|
+
description: 'Condense earlier conversation turns into a structured state checkpoint to reclaim tokens',
|
|
1632
|
+
dialogTitle: 'Context Compaction',
|
|
1633
|
+
complete: () => [
|
|
1634
|
+
{ value: '--preview', label: '--preview', description: 'estimate token savings without modifying history' },
|
|
1635
|
+
{ value: '--keep 6', label: '--keep 6', description: 'preserve 6 recent turns after compaction' }
|
|
1636
|
+
],
|
|
1637
|
+
run: async (argv, ctx) => {
|
|
1638
|
+
const { runCompactSlashCommand } = await import('./core/contextCompactor.js');
|
|
1639
|
+
const res = await runCompactSlashCommand(argv, ctx);
|
|
1640
|
+
return res.ok ? ok(res.output) : fail(res.output);
|
|
1641
|
+
}
|
|
1642
|
+
},
|
|
1643
|
+
|
|
1644
|
+
{
|
|
1645
|
+
name: 'copy',
|
|
1646
|
+
aliases: ['cp', 'clip'],
|
|
1647
|
+
scope: 'local',
|
|
1648
|
+
usage: '/copy [input | last | <text>]',
|
|
1649
|
+
description: 'Copy chatbox input, last assistant response, or text to system clipboard',
|
|
1650
|
+
complete: () => [
|
|
1651
|
+
{ value: 'last', label: 'last', description: 'copy last assistant response to clipboard' },
|
|
1652
|
+
{ value: 'input', label: 'input', description: 'copy current chatbox input to clipboard' }
|
|
1653
|
+
],
|
|
1654
|
+
run: (argv, ctx) => {
|
|
1655
|
+
const res = runCopyCommand(argv, ctx);
|
|
1656
|
+
return res.ok
|
|
1657
|
+
? ok(res.output, { effect: ctx.prompt ? 'silent' : undefined })
|
|
1658
|
+
: fail(res.output);
|
|
1659
|
+
}
|
|
1660
|
+
},
|
|
1661
|
+
|
|
1662
|
+
{
|
|
1663
|
+
name: 'paste',
|
|
1664
|
+
aliases: ['pasteclip'],
|
|
1665
|
+
scope: 'local',
|
|
1666
|
+
usage: '/paste [text]',
|
|
1667
|
+
description: 'Paste clipboard content or text into the chatbox input',
|
|
1668
|
+
run: (argv, ctx) => {
|
|
1669
|
+
const res = runPasteCommand(argv, ctx);
|
|
1670
|
+
return res.ok
|
|
1671
|
+
? ok(res.output, { effect: ctx.prompt ? 'silent' : undefined })
|
|
1672
|
+
: fail(res.output);
|
|
1673
|
+
}
|
|
1674
|
+
},
|
|
1675
|
+
|
|
1676
|
+
{
|
|
1677
|
+
name: 'image',
|
|
1678
|
+
aliases: ['attach', 'screenshot'],
|
|
1679
|
+
scope: 'local',
|
|
1680
|
+
usage: '/image [path]',
|
|
1681
|
+
description: 'Attach a screenshot from clipboard or a local image file to the chat prompt',
|
|
1682
|
+
run: (argv, ctx) => {
|
|
1683
|
+
if (!ctx.prompt) {
|
|
1684
|
+
return fail('The /image command is only available in interactive chat mode.');
|
|
1685
|
+
}
|
|
1686
|
+
if (argv.length === 0) {
|
|
1687
|
+
const res = runPasteCommand([], ctx);
|
|
1688
|
+
return res.ok ? ok(res.output, { effect: 'silent' }) : fail(res.output);
|
|
1689
|
+
}
|
|
1690
|
+
let rawPath = argv.join(' ').trim();
|
|
1691
|
+
if (
|
|
1692
|
+
(rawPath.startsWith('"') && rawPath.endsWith('"') && rawPath.length >= 2) ||
|
|
1693
|
+
(rawPath.startsWith("'") && rawPath.endsWith("'") && rawPath.length >= 2)
|
|
1694
|
+
) {
|
|
1695
|
+
rawPath = rawPath.slice(1, -1).trim();
|
|
1696
|
+
}
|
|
1697
|
+
if (!rawPath || rawPath.includes('\0')) {
|
|
1698
|
+
return fail('Invalid image path.');
|
|
1699
|
+
}
|
|
1700
|
+
const img = loadLocalImageAttachment(rawPath);
|
|
1701
|
+
if (!img) {
|
|
1702
|
+
return fail(`Could not load image at "${safeDisplay(rawPath)}". Ensure file exists and is a valid image (PNG, JPEG, WebP, GIF).`);
|
|
1703
|
+
}
|
|
1704
|
+
if (!Array.isArray(ctx.prompt.pendingAttachments)) {
|
|
1705
|
+
ctx.prompt.pendingAttachments = [];
|
|
1706
|
+
}
|
|
1707
|
+
ctx.prompt.pendingAttachments.push(img);
|
|
1708
|
+
const cleanImgName = safeDisplay(img.name);
|
|
1709
|
+
ctx.prompt.editor?.insert?.(`[Image: ${cleanImgName}] `);
|
|
1710
|
+
ctx.prompt.notice = `attached image ${cleanImgName} (${formatByteSize(img.size)})`;
|
|
1711
|
+
ctx.prompt.scheduleDraw?.();
|
|
1712
|
+
return ok(`Attached image ${cleanImgName} (${formatByteSize(img.size)}) to chat prompt.`, { effect: 'silent' });
|
|
1713
|
+
}
|
|
1714
|
+
},
|
|
1715
|
+
|
|
1716
|
+
{
|
|
1717
|
+
name: 'stop',
|
|
1718
|
+
aliases: ['abort'],
|
|
1719
|
+
scope: 'local',
|
|
1720
|
+
usage: '/stop',
|
|
1721
|
+
description: 'Stop the task that is currently running',
|
|
1722
|
+
run: (argv, ctx) => {
|
|
1723
|
+
const loop = ctx.loop;
|
|
1724
|
+
if (loop && typeof loop.abort === 'function') {
|
|
1725
|
+
loop.abort();
|
|
1726
|
+
if (ctx.prompt) ctx.prompt.notice = 'stop requested';
|
|
1727
|
+
return ok('Stop requested.', { effect: ctx.prompt ? 'silent' : undefined });
|
|
1728
|
+
}
|
|
1729
|
+
return fail('Nothing is running.');
|
|
1730
|
+
}
|
|
1731
|
+
},
|
|
1732
|
+
|
|
1733
|
+
{
|
|
1734
|
+
name: 'model',
|
|
1735
|
+
aliases: ['models'],
|
|
1736
|
+
scope: 'local',
|
|
1737
|
+
usage: '/model [list | refresh | provider/model | model]',
|
|
1738
|
+
description: 'Show, list or change the model in use',
|
|
1739
|
+
dialogTitle: 'Model',
|
|
1740
|
+
complete: () => {
|
|
1741
|
+
const config = loadConfig();
|
|
1742
|
+
const currentProvider = config.provider || '';
|
|
1743
|
+
const overview = getAvailableProvidersOverview(config);
|
|
1744
|
+
const items = [
|
|
1745
|
+
{ value: 'list', label: 'list', description: 'overview of all BYOK and ACP models' },
|
|
1746
|
+
{ value: 'refresh', label: 'refresh', description: 'poll provider API for live models' }
|
|
1747
|
+
];
|
|
1748
|
+
|
|
1749
|
+
// 1. Models for the active provider
|
|
1750
|
+
const curated = getCuratedModels(currentProvider);
|
|
1751
|
+
for (const m of curated) {
|
|
1752
|
+
items.push({ value: m, label: m, description: `[active] ${currentProvider}` });
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
// 2. ACP Peer Agents (with live auto-detected status)
|
|
1756
|
+
for (const peer of overview.acp) {
|
|
1757
|
+
const statusTag = peer.installed ? '(ready)' : '(not installed)';
|
|
1758
|
+
items.push({
|
|
1759
|
+
value: peer.providerKey,
|
|
1760
|
+
label: peer.providerKey,
|
|
1761
|
+
description: `[ACP: ${peer.label}] ${statusTag}`
|
|
1762
|
+
});
|
|
1763
|
+
|
|
1764
|
+
if (peer.installed && Array.isArray(peer.models)) {
|
|
1765
|
+
for (const m of peer.models.slice(0, 3)) {
|
|
1766
|
+
if (peer.isCurrent && curated.includes(m)) continue;
|
|
1767
|
+
const targetVal = m.includes('/') ? m : `${peer.providerKey}/${m}`;
|
|
1768
|
+
items.push({
|
|
1769
|
+
value: targetVal,
|
|
1770
|
+
label: targetVal,
|
|
1771
|
+
description: `[ACP: ${peer.label}]`
|
|
1772
|
+
});
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
// 3. BYOK Providers (Cloud & Local)
|
|
1778
|
+
for (const p of overview.byok) {
|
|
1779
|
+
const configTag = p.isConfigured ? '(configured)' : '(needs key)';
|
|
1780
|
+
items.push({
|
|
1781
|
+
value: p.id,
|
|
1782
|
+
label: p.id,
|
|
1783
|
+
description: `[BYOK: ${p.label}] ${configTag}`
|
|
1784
|
+
});
|
|
1785
|
+
|
|
1786
|
+
if (p.isConfigured && Array.isArray(p.models)) {
|
|
1787
|
+
for (const m of p.models.slice(0, 2)) {
|
|
1788
|
+
if (p.isCurrent && curated.includes(m)) continue;
|
|
1789
|
+
items.push({
|
|
1790
|
+
value: `${p.id}/${m}`,
|
|
1791
|
+
label: `${p.id}/${m}`,
|
|
1792
|
+
description: `[BYOK: ${p.label}]`
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
return items;
|
|
1799
|
+
},
|
|
1800
|
+
run: async (argv, ctx = {}) => {
|
|
1801
|
+
const config = loadConfig();
|
|
1802
|
+
const overview = getAvailableProvidersOverview(config);
|
|
1803
|
+
|
|
1804
|
+
if (argv.length === 0) {
|
|
1805
|
+
if (ctx.prompt) {
|
|
1806
|
+
const { runInteractiveModelPicker } = await import('./tui/modelPicker.js');
|
|
1807
|
+
const output = await runInteractiveModelPicker(ctx.prompt, { loadConfig, saveConfig }, { loop: ctx.loop });
|
|
1808
|
+
if (ctx.loop) {
|
|
1809
|
+
ctx.loop.config = loadConfig();
|
|
1810
|
+
if (typeof ctx.loop.updateTierLimits === 'function') {
|
|
1811
|
+
ctx.loop.updateTierLimits();
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
return ok(output, { effect: 'silent' });
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
const lines = [
|
|
1818
|
+
`Active Provider : ${config.provider || 'no provider configured'}`,
|
|
1819
|
+
`Active Model : ${config.model || 'none'}`,
|
|
1820
|
+
'',
|
|
1821
|
+
'────────────────────────────────────────────────────────────',
|
|
1822
|
+
'BYOK PROVIDERS (Cloud & Local API)',
|
|
1823
|
+
'────────────────────────────────────────────────────────────'
|
|
1824
|
+
];
|
|
1825
|
+
for (const p of overview.byok) {
|
|
1826
|
+
const status = p.isConfigured ? (p.isCurrent ? '● Configured (Active)' : '○ Configured') : '─ Not configured (run /setup)';
|
|
1827
|
+
lines.push(` • ${p.label.padEnd(26)} [${status}]`);
|
|
1828
|
+
}
|
|
1829
|
+
lines.push('');
|
|
1830
|
+
lines.push('────────────────────────────────────────────────────────────');
|
|
1831
|
+
lines.push('ACP PEER AGENTS (Local Coding Agents & CLI Engines)');
|
|
1832
|
+
lines.push('────────────────────────────────────────────────────────────');
|
|
1833
|
+
for (const peer of overview.acp) {
|
|
1834
|
+
const icon = peer.installed ? '✓' : '✕';
|
|
1835
|
+
const status = peer.installed ? (peer.isCurrent ? 'READY (Active)' : 'READY') : 'NOT INSTALLED';
|
|
1836
|
+
lines.push(` ${icon} ${peer.label.padEnd(24)} — ${status}`);
|
|
1837
|
+
}
|
|
1838
|
+
lines.push('');
|
|
1839
|
+
lines.push('Use /model list to see all models in each category.');
|
|
1840
|
+
lines.push('Use /model <name> or /model acp/<peer> to switch model.');
|
|
1841
|
+
lines.push('Use /setup to configure credentials and endpoints.');
|
|
1842
|
+
return ok(lines.join('\n'));
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
const first = (argv[0] || '').toLowerCase();
|
|
1846
|
+
if (first === 'list' || first === 'ls') {
|
|
1847
|
+
const targetProvider = argv[1];
|
|
1848
|
+
|
|
1849
|
+
// Specific provider requested (e.g. /model list gemini)
|
|
1850
|
+
if (targetProvider && targetProvider !== 'all') {
|
|
1851
|
+
const result = await resolveAvailableModels(targetProvider, config);
|
|
1852
|
+
const active = config.model;
|
|
1853
|
+
const lines = [
|
|
1854
|
+
`Available models for ${targetProvider} (source: ${result.source}):`,
|
|
1855
|
+
''
|
|
1856
|
+
];
|
|
1857
|
+
for (const m of result.models) {
|
|
1858
|
+
const isCurrent = m === active && config.provider === targetProvider;
|
|
1859
|
+
lines.push(` ${isCurrent ? '• ' : ' '}${m}${isCurrent ? ' (active)' : ''}`);
|
|
1860
|
+
}
|
|
1861
|
+
if (result.models.length === 0) {
|
|
1862
|
+
lines.push(' (this peer CLI publishes no model list; enter one with /model <name>)');
|
|
1863
|
+
}
|
|
1864
|
+
lines.push('');
|
|
1865
|
+
lines.push('Use /model <name> to select, or /model refresh to poll the provider API.');
|
|
1866
|
+
return ok(lines.join('\n'));
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
// Comprehensive categorized listing
|
|
1870
|
+
const lines = [
|
|
1871
|
+
'============================================================',
|
|
1872
|
+
'BYOK PROVIDERS (Cloud APIs & Local Endpoints)',
|
|
1873
|
+
'============================================================'
|
|
1874
|
+
];
|
|
1875
|
+
for (const p of overview.byok) {
|
|
1876
|
+
const badge = p.isConfigured ? (p.isCurrent ? '● ACTIVE' : '○ CONFIGURED') : 'NEEDS KEY';
|
|
1877
|
+
lines.push(` • ${p.label} [${badge}]`);
|
|
1878
|
+
const modelSample = p.models.slice(0, 5).join(', ');
|
|
1879
|
+
lines.push(` Models: ${modelSample}${p.models.length > 5 ? `, ... (${p.models.length} total)` : ''}`);
|
|
1880
|
+
lines.push(` Switch: /model ${p.id}/${p.defaultModel}`);
|
|
1881
|
+
lines.push('');
|
|
1882
|
+
}
|
|
1883
|
+
|
|
1884
|
+
lines.push('============================================================');
|
|
1885
|
+
lines.push('ACP PEER AGENTS (Local Agents & CLI Engines)');
|
|
1886
|
+
lines.push('============================================================');
|
|
1887
|
+
for (const peer of overview.acp) {
|
|
1888
|
+
const icon = peer.installed ? '✓' : '✕';
|
|
1889
|
+
const status = peer.installed ? (peer.isCurrent ? 'READY (Active)' : 'READY') : 'NOT INSTALLED';
|
|
1890
|
+
lines.push(` ${icon} ${peer.label} — ${status}`);
|
|
1891
|
+
lines.push(` Command: ${peer.command}`);
|
|
1892
|
+
if (peer.installed) {
|
|
1893
|
+
lines.push(` Models: ${peer.models.join(', ')}`);
|
|
1894
|
+
lines.push(` Switch: /model ${peer.providerKey}`);
|
|
1895
|
+
} else {
|
|
1896
|
+
lines.push(` Setup: ${peer.setupInstruction}`);
|
|
1897
|
+
}
|
|
1898
|
+
lines.push('');
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
lines.push('------------------------------------------------------------');
|
|
1902
|
+
lines.push('Use /model <name> or /model acp/<peer> to select.');
|
|
1903
|
+
lines.push('Use /setup to configure credentials or endpoints.');
|
|
1904
|
+
return ok(lines.join('\n'));
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
if (first === 'refresh') {
|
|
1908
|
+
const targetRefresh = argv[1];
|
|
1909
|
+
if (targetRefresh && targetRefresh.toLowerCase() === 'all') {
|
|
1910
|
+
const refreshed = await resolveAvailableProvidersOverview(config, { forceRefresh: true });
|
|
1911
|
+
const readyCount = refreshed.acp.filter(p => p.installed).length + refreshed.byok.filter(p => p.isConfigured).length;
|
|
1912
|
+
return ok(`Refreshed live models across ${readyCount} installed/configured providers. Run /model list to view.`);
|
|
1913
|
+
}
|
|
1914
|
+
const providerToRefresh = targetRefresh || config.provider;
|
|
1915
|
+
if (!providerToRefresh) return fail('No provider configured. Run /setup first.');
|
|
1916
|
+
const result = await resolveAvailableModels(providerToRefresh, config, true);
|
|
1917
|
+
return ok(`Refreshed ${providerToRefresh} models (${result.models.length} available, source: ${result.source}). Run /model list to view.`);
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
if (first === 'test') {
|
|
1921
|
+
const targetProvider = argv[1] || config.provider;
|
|
1922
|
+
const targetModel = argv[2] || (targetProvider === config.provider ? config.model : undefined);
|
|
1923
|
+
if (!targetProvider) return fail('No provider specified or configured. Run /setup first.');
|
|
1924
|
+
|
|
1925
|
+
const testConfig: Record<string, any> = { ...config, provider: targetProvider };
|
|
1926
|
+
if (targetModel) {
|
|
1927
|
+
testConfig.model = targetModel;
|
|
1928
|
+
} else if (targetProvider !== config.provider) {
|
|
1929
|
+
delete testConfig.model;
|
|
1930
|
+
}
|
|
1931
|
+
if (config.providerKeys && Object.hasOwn(config.providerKeys, targetProvider) && config.providerKeys[targetProvider]) {
|
|
1932
|
+
testConfig.apiKey = config.providerKeys[targetProvider];
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
try {
|
|
1936
|
+
const { createProvider } = await import('./providers/factory.js');
|
|
1937
|
+
const providerInstance = createProvider(testConfig);
|
|
1938
|
+
const t0 = performance.now();
|
|
1939
|
+
const response = await providerInstance.chat([
|
|
1940
|
+
{ role: 'user', content: 'Respond with exactly: OK' }
|
|
1941
|
+
], { maxTokens: 16 });
|
|
1942
|
+
const latencyMs = Math.round(performance.now() - t0);
|
|
1943
|
+
|
|
1944
|
+
const outputLines = [
|
|
1945
|
+
`✓ API Call Test Succeeded: "${targetProvider}" / "${providerInstance.model || targetModel || 'default'}"`,
|
|
1946
|
+
'',
|
|
1947
|
+
` • Round-trip Latency : ${latencyMs} ms`,
|
|
1948
|
+
` • Response Content : ${JSON.stringify(response.content || '').slice(0, 80)}`,
|
|
1949
|
+
` • Tokens Used : ${response.usage ? `${response.usage.promptTokens} in / ${response.usage.completionTokens} out` : 'unreported'}`,
|
|
1950
|
+
'',
|
|
1951
|
+
'Wire format, credentials, and model endpoint are verified and accurate.'
|
|
1952
|
+
];
|
|
1953
|
+
return ok(outputLines.join('\n'));
|
|
1954
|
+
} catch (err) {
|
|
1955
|
+
return fail(
|
|
1956
|
+
`✕ API Call Test Failed for "${targetProvider}" / "${targetModel || config.model || 'default'}":\n\n`
|
|
1957
|
+
+ ` Error: ${safeDisplay(redactProviderSecrets(errMsg(err)))}\n\n`
|
|
1958
|
+
+ `Checks:\n`
|
|
1959
|
+
+ ` - Verify the API key in /setup.\n`
|
|
1960
|
+
+ ` - Check if the model is active with "/model list ${targetProvider}".\n`
|
|
1961
|
+
+ ` - Ensure the provider endpoint or account has sufficient quota.`
|
|
1962
|
+
);
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
const rawRequested = argv.join(' ').trim().replace(/^\/model\s+/i, '');
|
|
1967
|
+
if (!rawRequested || /[\r\n\0]/.test(rawRequested)) {
|
|
1968
|
+
return fail('Invalid provider or model identifier.');
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
// Helper to cleanly activate a provider + model, persist config, update live loop & prompt
|
|
1972
|
+
const activateModel = (nextProvider: string, nextModel: string, feedbackMessage?: string): CommandResult => {
|
|
1973
|
+
if (/[\r\n\0]/.test(nextProvider) || /[\r\n\0]/.test(nextModel)) {
|
|
1974
|
+
return fail('Invalid provider or model identifier.');
|
|
1975
|
+
}
|
|
1976
|
+
const isProviderChange = nextProvider !== config.provider;
|
|
1977
|
+
if (isProviderChange) {
|
|
1978
|
+
if (nextProvider === 'antigravity' || nextProvider === 'pi' || nextProvider.startsWith('acp/')) {
|
|
1979
|
+
config.apiKey = '';
|
|
1980
|
+
delete config.baseUrl;
|
|
1981
|
+
} else {
|
|
1982
|
+
config.apiKey = (config.providerKeys && Object.hasOwn(config.providerKeys, nextProvider) && config.providerKeys[nextProvider]) || '';
|
|
1983
|
+
delete config.baseUrl;
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
config.provider = nextProvider;
|
|
1987
|
+
config.model = nextModel;
|
|
1988
|
+
if (config.reasoningEffort) {
|
|
1989
|
+
const nextSpec = resolveActiveVariantSpec(config);
|
|
1990
|
+
if (nextSpec.source === 'agy_models' || !nextSpec.supported || !matchVariantOption(nextSpec, String(config.reasoningEffort))) {
|
|
1991
|
+
delete config.reasoningEffort;
|
|
1992
|
+
delete config.reasoningBudgetTokens;
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
saveConfig(config);
|
|
1996
|
+
|
|
1997
|
+
if (ctx.loop) {
|
|
1998
|
+
ctx.loop.config = loadConfig();
|
|
1999
|
+
if (typeof ctx.loop.updateTierLimits === 'function') {
|
|
2000
|
+
ctx.loop.updateTierLimits();
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
if (ctx.prompt) {
|
|
2004
|
+
const activeVariant = typeof config.reasoningEffort === 'string' ? config.reasoningEffort : '';
|
|
2005
|
+
if (typeof ctx.prompt.updateModel === 'function') {
|
|
2006
|
+
ctx.prompt.updateModel(config.provider, config.model, activeVariant);
|
|
2007
|
+
} else if (ctx.prompt.renderer?.status) {
|
|
2008
|
+
ctx.prompt.renderer.status.setSession({ provider: config.provider, model: config.model, variant: activeVariant });
|
|
2009
|
+
ctx.prompt.surface?.setSessionInfo?.({ provider: config.provider, model: config.model, variant: activeVariant });
|
|
2010
|
+
if (typeof ctx.prompt.scheduleDraw === 'function') ctx.prompt.scheduleDraw();
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
return ok(feedbackMessage || `Now using ${config.provider} / ${config.model}.`, { effect: 'inline' });
|
|
2014
|
+
};
|
|
2015
|
+
|
|
2016
|
+
// 1. Antigravity provider (e.g. antigravity or antigravity/Gemini 3.8 Flash (High))
|
|
2017
|
+
if (rawRequested.toLowerCase() === 'antigravity' || rawRequested.toLowerCase().startsWith('antigravity/')) {
|
|
2018
|
+
const agyPeer = overview.acp.find(p => p.id === 'antigravity');
|
|
2019
|
+
if (agyPeer && !agyPeer.installed) {
|
|
2020
|
+
return fail(`Notice: Antigravity CLI (agy) is not installed on this machine.\nSetup: ${agyPeer.setupInstruction}\n\nModel was not changed.`);
|
|
2021
|
+
}
|
|
2022
|
+
const agyModel = rawRequested.includes('/')
|
|
2023
|
+
? rawRequested.slice(rawRequested.indexOf('/') + 1).trim()
|
|
2024
|
+
: pickDefaultPeerModel('antigravity', agyPeer?.models);
|
|
2025
|
+
return activateModel('antigravity', agyModel, `Now using Google Antigravity / ${agyModel}.`);
|
|
2026
|
+
}
|
|
2027
|
+
|
|
2028
|
+
// 2. acp/<peer> or acp/<peer>/<model>
|
|
2029
|
+
const acpTarget = rawRequested.match(/^acp\/([a-z0-9_-]+)(?:\/(.+))?$/i);
|
|
2030
|
+
if (acpTarget) {
|
|
2031
|
+
const peer = (acpTarget[1] || '').toLowerCase();
|
|
2032
|
+
const nextProvider = `acp/${peer}`;
|
|
2033
|
+
const peerInfo = overview.acp.find(p => p.id === peer);
|
|
2034
|
+
if (peerInfo && !peerInfo.installed) {
|
|
2035
|
+
return fail(`Notice: "${peerInfo.label}" CLI is not installed on this machine.\nBinary "${peerInfo.id}" was not found on PATH.\nSetup: ${peerInfo.setupInstruction}\n\nModel was not changed.`);
|
|
2036
|
+
}
|
|
2037
|
+
const peerModel = acpTarget[2]
|
|
2038
|
+
? acpTarget[2].trim()
|
|
2039
|
+
: pickDefaultPeerModel(nextProvider, peerInfo?.models);
|
|
2040
|
+
return activateModel(nextProvider, peerModel, `Now using ${nextProvider} / ${peerModel}.`);
|
|
2041
|
+
}
|
|
2042
|
+
|
|
2043
|
+
// 2b. OpenRouter `:free` models (e.g. qwen/qwen3-coder:free, deepseek/deepseek-r1:free)
|
|
2044
|
+
// Must be recognized BEFORE ACP peer and BYOK vendor-prefix matching so `qwen/...:free`
|
|
2045
|
+
// never triggers a missing Qwen Code CLI error or switches to Qwen BYOK.
|
|
2046
|
+
if (rawRequested.toLowerCase().endsWith(':free') && rawRequested.includes('/')) {
|
|
2047
|
+
const targetProv = (config.provider === 'openrouter' || config.provider === 'openrouter-free')
|
|
2048
|
+
? config.provider
|
|
2049
|
+
: 'openrouter';
|
|
2050
|
+
return activateModel(targetProv, rawRequested, `Now using ${targetProv} / ${rawRequested}.`);
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
// 3. Known ACP peer directly (e.g. opencode, opencode/deepseek-v4.1-flash-free, claude)
|
|
2054
|
+
const slashIndex = rawRequested.indexOf('/');
|
|
2055
|
+
const prefix = (slashIndex > 0 ? rawRequested.slice(0, slashIndex) : rawRequested).toLowerCase();
|
|
2056
|
+
const acpPeer = overview.acp.find(p => p.id === prefix || p.providerKey === prefix);
|
|
2057
|
+
if (acpPeer && acpPeer.id !== 'antigravity') {
|
|
2058
|
+
const nextProvider = acpPeer.providerKey;
|
|
2059
|
+
if (!acpPeer.installed) {
|
|
2060
|
+
return fail(`Notice: "${acpPeer.label}" CLI is not installed on this machine.\nBinary "${acpPeer.id}" was not found on PATH.\nSetup: ${acpPeer.setupInstruction}\n\nModel was not changed.`);
|
|
2061
|
+
}
|
|
2062
|
+
let peerModel;
|
|
2063
|
+
if (slashIndex > 0) {
|
|
2064
|
+
const rest = rawRequested.slice(slashIndex + 1).trim();
|
|
2065
|
+
if (
|
|
2066
|
+
(Array.isArray(acpPeer.models) && acpPeer.models.includes(rawRequested)) ||
|
|
2067
|
+
(PEER_MODEL_CATALOGUE[acpPeer.id]?.includes(rawRequested)) ||
|
|
2068
|
+
(acpPeer.id === 'opencode' && rawRequested.startsWith('opencode/'))
|
|
2069
|
+
) {
|
|
2070
|
+
peerModel = rawRequested;
|
|
2071
|
+
} else {
|
|
2072
|
+
peerModel = rest;
|
|
2073
|
+
}
|
|
2074
|
+
} else {
|
|
2075
|
+
peerModel = pickDefaultPeerModel(nextProvider, acpPeer.models);
|
|
2076
|
+
}
|
|
2077
|
+
return activateModel(nextProvider, peerModel, `Now using ${nextProvider} / ${peerModel}.`);
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
// 4. Known BYOK provider prefix (e.g. gemini/gemini-2.5-flash, anthropic/claude-3-7-sonnet)
|
|
2081
|
+
const byokProvider = overview.byok.find(p => p.id === prefix || (p.id === 'qwen' && prefix === 'dashscope-byok'));
|
|
2082
|
+
if (byokProvider) {
|
|
2083
|
+
const nextProvider = byokProvider.id;
|
|
2084
|
+
const byokModel = slashIndex > 0 ? rawRequested.slice(slashIndex + 1).trim() : (DEFAULT_MODEL_BY_PROVIDER[nextProvider] || byokProvider.defaultModel);
|
|
2085
|
+
return activateModel(nextProvider, byokModel, `Now using ${nextProvider} / ${byokModel}.`);
|
|
2086
|
+
}
|
|
2087
|
+
|
|
2088
|
+
// 5. Look up by model name across BYOK and ACP catalogues
|
|
2089
|
+
for (const p of overview.byok) {
|
|
2090
|
+
if (p.models && p.models.some(m => m.toLowerCase() === rawRequested.toLowerCase())) {
|
|
2091
|
+
const exactModel = p.models.find(m => m.toLowerCase() === rawRequested.toLowerCase()) || rawRequested;
|
|
2092
|
+
return activateModel(p.id, exactModel, `Now using ${p.id} / ${exactModel}.`);
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
for (const peer of overview.acp) {
|
|
2096
|
+
if (peer.models && peer.models.some(m => m.toLowerCase() === rawRequested.toLowerCase())) {
|
|
2097
|
+
const exactModel = peer.models.find(m => m.toLowerCase() === rawRequested.toLowerCase()) || rawRequested;
|
|
2098
|
+
return activateModel(peer.providerKey, exactModel, `Now using ${peer.providerKey} / ${exactModel}.`);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
// 6. If currently in ACP or on a provider whose models contain slashes (e.g. OpenRouter, Ollama, Groq, OpenAI-compatible)
|
|
2103
|
+
if (isAcpProvider(config.provider)) {
|
|
2104
|
+
return activateModel(config.provider, rawRequested, `Now using ${config.provider} / ${rawRequested}.`);
|
|
2105
|
+
}
|
|
2106
|
+
const SLASHED_MODEL_PROVIDERS = new Set([
|
|
2107
|
+
'openrouter', 'openrouter-free', 'openai-compatible', 'ollama', 'groq', 'cerebras', 'together', 'fireworks'
|
|
2108
|
+
]);
|
|
2109
|
+
if (slashIndex > 0 && config.provider && SLASHED_MODEL_PROVIDERS.has(config.provider.toLowerCase())) {
|
|
2110
|
+
return activateModel(config.provider, rawRequested, `Now using ${config.provider} / ${rawRequested}.`);
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
// 7. Bare model name on the active provider (never fabricate an unknown provider from an arbitrary slash)
|
|
2114
|
+
if (slashIndex > 0 && config.provider) {
|
|
2115
|
+
return activateModel(config.provider, rawRequested, `Now using ${config.provider} / ${rawRequested}.`);
|
|
2116
|
+
}
|
|
2117
|
+
if (slashIndex > 0) {
|
|
2118
|
+
const prov = rawRequested.slice(0, slashIndex).trim();
|
|
2119
|
+
const mod = rawRequested.slice(slashIndex + 1).trim();
|
|
2120
|
+
return activateModel(prov, mod, `Now using ${prov} / ${mod}.`);
|
|
2121
|
+
} else {
|
|
2122
|
+
return activateModel(config.provider || 'antigravity', rawRequested, `Now using ${config.provider || 'antigravity'} / ${rawRequested}.`);
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
},
|
|
2126
|
+
|
|
2127
|
+
{
|
|
2128
|
+
name: 'variant',
|
|
2129
|
+
aliases: ['effort', 'reasoning'],
|
|
2130
|
+
scope: 'local',
|
|
2131
|
+
usage: '/variant [level | auto | list]',
|
|
2132
|
+
description: 'Detect and set reasoning variant/effort for the active model or ACP peer',
|
|
2133
|
+
dialogTitle: 'Model Variant',
|
|
2134
|
+
complete: () => {
|
|
2135
|
+
const config = loadConfig();
|
|
2136
|
+
const spec = resolveActiveVariantSpec(config);
|
|
2137
|
+
const items: CommandCompletionItem[] = spec.options.map((opt) => ({
|
|
2138
|
+
value: opt.id,
|
|
2139
|
+
label: opt.id,
|
|
2140
|
+
description: `${opt.label} — ${opt.description}`
|
|
2141
|
+
}));
|
|
2142
|
+
items.push({
|
|
2143
|
+
value: 'auto',
|
|
2144
|
+
label: 'auto',
|
|
2145
|
+
description: spec.defaultVariant
|
|
2146
|
+
? `reset to model default (${spec.defaultVariant})`
|
|
2147
|
+
: 'reset to model default reasoning behavior'
|
|
2148
|
+
});
|
|
2149
|
+
items.push({
|
|
2150
|
+
value: 'list',
|
|
2151
|
+
label: 'list',
|
|
2152
|
+
description: 'inspect detected reasoning capabilities for the active model'
|
|
2153
|
+
});
|
|
2154
|
+
return items;
|
|
2155
|
+
},
|
|
2156
|
+
run: async (argv, ctx = {}) => {
|
|
2157
|
+
const config = loadConfig();
|
|
2158
|
+
const spec = resolveActiveVariantSpec(config, ctx);
|
|
2159
|
+
|
|
2160
|
+
if (argv.length === 0) {
|
|
2161
|
+
if (ctx.prompt && typeof ctx.prompt.openLayer === 'function' && spec.supported && spec.options.length > 0) {
|
|
2162
|
+
const { SelectLayer } = await import('./tui/dialogs.js');
|
|
2163
|
+
const pickerItems = [
|
|
2164
|
+
...spec.options.map((opt) => {
|
|
2165
|
+
const isActive = Boolean(spec.currentVariant && opt.id.toLowerCase() === spec.currentVariant.toLowerCase());
|
|
2166
|
+
return {
|
|
2167
|
+
id: opt.id,
|
|
2168
|
+
value: opt.id,
|
|
2169
|
+
label: `${isActive ? '● ' : ' '}${opt.label} (${opt.id})`,
|
|
2170
|
+
description: opt.description,
|
|
2171
|
+
category: `${spec.model || spec.provider} — ${spec.source === 'acp_live' ? 'ACP Live' : (spec.source === 'peer_catalogue' ? 'Peer Catalogue' : (spec.source === 'agy_models' ? 'Antigravity' : (spec.source === 'ollama_live' ? 'Ollama Local' : 'Detected')))}`
|
|
2172
|
+
};
|
|
2173
|
+
}),
|
|
2174
|
+
{
|
|
2175
|
+
id: 'auto',
|
|
2176
|
+
value: 'auto',
|
|
2177
|
+
label: `${!spec.currentVariant ? '● ' : ' '}Auto (model default)`,
|
|
2178
|
+
description: spec.defaultVariant
|
|
2179
|
+
? `Use provider default (${spec.defaultVariant})`
|
|
2180
|
+
: 'Clear explicit reasoning override',
|
|
2181
|
+
category: 'Reset'
|
|
2182
|
+
}
|
|
2183
|
+
];
|
|
2184
|
+
|
|
2185
|
+
const chosen = await new Promise<string | null>((resolve) => {
|
|
2186
|
+
const layer = new SelectLayer({
|
|
2187
|
+
title: `Variant · ${safeDisplay(spec.model || spec.provider || 'Active Model')}`,
|
|
2188
|
+
items: pickerItems,
|
|
2189
|
+
showFilter: pickerItems.length > 6,
|
|
2190
|
+
placeholder: 'Filter reasoning variants...',
|
|
2191
|
+
onPick: (item: any) => {
|
|
2192
|
+
resolve(item ? String(item.value || item.id || '') : null);
|
|
2193
|
+
}
|
|
2194
|
+
});
|
|
2195
|
+
ctx.prompt.openLayer(layer);
|
|
2196
|
+
});
|
|
2197
|
+
|
|
2198
|
+
if (!chosen) {
|
|
2199
|
+
return ok('Variant unchanged.', { effect: 'silent' });
|
|
2200
|
+
}
|
|
2201
|
+
return applySelectedVariant(chosen, spec, config, ctx);
|
|
2202
|
+
}
|
|
2203
|
+
|
|
2204
|
+
return ok(formatVariantStatusReport(spec));
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
const rawArg = argv.join(' ').trim();
|
|
2208
|
+
const firstLower = String(argv[0] || '').trim().toLowerCase();
|
|
2209
|
+
if (firstLower === 'list' || firstLower === 'status' || firstLower === 'show') {
|
|
2210
|
+
return ok(formatVariantStatusReport(spec));
|
|
2211
|
+
}
|
|
2212
|
+
if (/[\r\n\0]/.test(rawArg)) {
|
|
2213
|
+
return fail('Invalid variant value.');
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
return applySelectedVariant(rawArg, spec, config, ctx);
|
|
2217
|
+
}
|
|
2218
|
+
},
|
|
2219
|
+
|
|
2220
|
+
{
|
|
2221
|
+
name: 'gui',
|
|
2222
|
+
aliases: ['web', 'studio'],
|
|
2223
|
+
scope: 'local',
|
|
2224
|
+
usage: '/gui [open | status | stop | --port <n> | --no-open]',
|
|
2225
|
+
description: 'Launch, inspect, or stop the local Causyne Web Studio GUI in your browser',
|
|
2226
|
+
complete: () => [
|
|
2227
|
+
{ value: 'open', label: 'open', description: 'start and open Causyne Web Studio in your browser' },
|
|
2228
|
+
{ value: 'status', label: 'status', description: 'show active Web Studio URL, port, and workspace' },
|
|
2229
|
+
{ value: 'stop', label: 'stop', description: 'shut down the local Web Studio server' },
|
|
2230
|
+
{ value: '--no-open', label: '--no-open', description: 'start Web Studio without automatically opening a browser tab' }
|
|
2231
|
+
],
|
|
2232
|
+
run: async (argv, ctx = {}) => {
|
|
2233
|
+
const tokens = argv.map((t) => String(t || '').trim()).filter(Boolean);
|
|
2234
|
+
const first = (tokens[0] || 'open').toLowerCase();
|
|
2235
|
+
|
|
2236
|
+
if (first === 'status') {
|
|
2237
|
+
const status = getGuiServerStatus();
|
|
2238
|
+
if (!status.running) {
|
|
2239
|
+
return ok('Causyne Web Studio GUI is not running. Run /gui to launch it for this workspace.', { effect: 'inline' });
|
|
2240
|
+
}
|
|
2241
|
+
return ok([
|
|
2242
|
+
'Causyne Web Studio GUI — Running (127.0.0.1 loopback only)',
|
|
2243
|
+
` URL : ${status.url}`,
|
|
2244
|
+
` Workspace : ${safeDisplay(status.workspaceRoot || '')}`,
|
|
2245
|
+
' Stop : /gui stop (also stops automatically on CLI exit)'
|
|
2246
|
+
].join('\n'), { effect: 'inline' });
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2249
|
+
if (first === 'stop' || first === 'close' || first === 'off') {
|
|
2250
|
+
const stopped = await stopGuiServer();
|
|
2251
|
+
if (ctx.prompt) {
|
|
2252
|
+
ctx.prompt.notice = stopped ? 'Web Studio GUI stopped' : 'Web Studio GUI was not running';
|
|
2253
|
+
ctx.prompt.scheduleDraw?.();
|
|
2254
|
+
}
|
|
2255
|
+
return ok(
|
|
2256
|
+
stopped ? 'Stopped local Causyne Web Studio GUI server.' : 'Causyne Web Studio GUI is not currently running.',
|
|
2257
|
+
{ effect: 'inline' }
|
|
2258
|
+
);
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2261
|
+
let port = 0;
|
|
2262
|
+
let noOpen = false;
|
|
2263
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
2264
|
+
const tok = tokens[i]!;
|
|
2265
|
+
const lower = tok.toLowerCase();
|
|
2266
|
+
if (lower === 'open' || lower === 'start') continue;
|
|
2267
|
+
if (lower === '--no-open' || lower === '--no-browser') {
|
|
2268
|
+
noOpen = true;
|
|
2269
|
+
continue;
|
|
2270
|
+
}
|
|
2271
|
+
if (lower === '--port' && i + 1 < tokens.length) {
|
|
2272
|
+
const parsed = Number.parseInt(tokens[++i]!, 10);
|
|
2273
|
+
if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) {
|
|
2274
|
+
return fail(`Invalid port "${safeDisplay(tokens[i]!)}". Expected 0-65535.`);
|
|
2275
|
+
}
|
|
2276
|
+
port = parsed;
|
|
2277
|
+
continue;
|
|
2278
|
+
}
|
|
2279
|
+
if (lower.startsWith('--port=')) {
|
|
2280
|
+
const rawPort = tok.slice('--port='.length);
|
|
2281
|
+
const parsed = Number.parseInt(rawPort, 10);
|
|
2282
|
+
if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) {
|
|
2283
|
+
return fail(`Invalid port "${safeDisplay(rawPort)}". Expected 0-65535.`);
|
|
2284
|
+
}
|
|
2285
|
+
port = parsed;
|
|
2286
|
+
continue;
|
|
2287
|
+
}
|
|
2288
|
+
return fail(`Unknown /gui option "${safeDisplay(tok)}". Usage: /gui [open | status | stop | --port <n> | --no-open]`);
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
const workspaceRoot = ctx.loop?.workspaceRoot || process.cwd();
|
|
2292
|
+
const { handle, reused, openedBrowser, browserHint, copiedToClipboard } = await launchGuiServer({
|
|
2293
|
+
workspaceRoot,
|
|
2294
|
+
port,
|
|
2295
|
+
openBrowser: !noOpen
|
|
2296
|
+
});
|
|
2297
|
+
|
|
2298
|
+
if (ctx.prompt) {
|
|
2299
|
+
ctx.prompt.notice = `Web Studio live at ${handle.origin}`;
|
|
2300
|
+
ctx.prompt.scheduleDraw?.();
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
const outLines = [
|
|
2304
|
+
reused
|
|
2305
|
+
? 'Causyne Web Studio GUI is already running (127.0.0.1 loopback only):'
|
|
2306
|
+
: 'Causyne Web Studio GUI started (127.0.0.1 loopback only · 256-bit session nonce):',
|
|
2307
|
+
` Open URL : ${handle.url}${copiedToClipboard ? ' (copied to clipboard)' : ''}`,
|
|
2308
|
+
` Workspace : ${safeDisplay(handle.workspaceRoot)}`,
|
|
2309
|
+
` Browser : ${openedBrowser ? 'Opened in your default browser' : 'Open the URL above in your browser'}`
|
|
2310
|
+
];
|
|
2311
|
+
if (browserHint) {
|
|
2312
|
+
outLines.push(` Remote : ${safeDisplay(browserHint)}`);
|
|
2313
|
+
}
|
|
2314
|
+
outLines.push(' Control : /gui status | /gui stop (auto-stops when CLI exits)');
|
|
2315
|
+
return ok(outLines.join('\n'), { effect: 'inline' });
|
|
2316
|
+
}
|
|
2317
|
+
},
|
|
2318
|
+
|
|
2319
|
+
{
|
|
2320
|
+
name: 'openrouter',
|
|
2321
|
+
aliases: ['free'],
|
|
2322
|
+
scope: 'local',
|
|
2323
|
+
usage: '/openrouter [status | connect | disconnect | privacy <deny|allow>]',
|
|
2324
|
+
description: 'Connect OpenRouter account for free cloud AI models (openrouter/free)',
|
|
2325
|
+
dialogTitle: 'OpenRouter Free',
|
|
2326
|
+
complete: () => [
|
|
2327
|
+
{ value: 'status', label: 'status', description: 'view connection and data collection status' },
|
|
2328
|
+
{ value: 'connect', label: 'connect', description: 'connect your OpenRouter account via OAuth PKCE' },
|
|
2329
|
+
{ value: 'privacy deny', label: 'privacy deny', description: 'strict privacy (default): restrict provider data collection' },
|
|
2330
|
+
{ value: 'privacy allow', label: 'privacy allow', description: 'permit routing to training-eligible providers' },
|
|
2331
|
+
{ value: 'disconnect', label: 'disconnect', description: 'disconnect OpenRouter account' }
|
|
2332
|
+
],
|
|
2333
|
+
run: async (argv, ctx = {}) => {
|
|
2334
|
+
const sub = (argv[0] || 'status').toLowerCase();
|
|
2335
|
+
|
|
2336
|
+
if (sub === 'status') {
|
|
2337
|
+
const status = getOpenRouterStatus();
|
|
2338
|
+
const lines = [
|
|
2339
|
+
'OpenRouter Free Models — Connection Status',
|
|
2340
|
+
'',
|
|
2341
|
+
` • Connected : ${status.connected ? 'YES' : 'NO'}`,
|
|
2342
|
+
` • Active Provider : ${status.active ? 'YES (OpenRouter is active)' : 'NO (using ' + (loadConfig().provider || 'none') + ')'}`,
|
|
2343
|
+
` • Default Model : ${status.model}`,
|
|
2344
|
+
` • Privacy Policy : provider.data_collection = "${status.dataCollection}"`,
|
|
2345
|
+
` • Stored Key : ${status.maskedKey || 'none'} (${status.keySource || 'unconfigured'})`,
|
|
2346
|
+
'',
|
|
2347
|
+
status.connected
|
|
2348
|
+
? 'OpenRouter Free is ready. Run "/model openrouter/free" to select it.'
|
|
2349
|
+
: 'To connect your account, run "/openrouter connect".'
|
|
2350
|
+
];
|
|
2351
|
+
return ok(lines.join('\n'));
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
if (sub === 'disconnect') {
|
|
2355
|
+
const updatedConfig = disconnectOpenRouter();
|
|
2356
|
+
if (ctx.loop) {
|
|
2357
|
+
ctx.loop.config = updatedConfig;
|
|
2358
|
+
if (typeof ctx.loop.updateTierLimits === 'function') {
|
|
2359
|
+
ctx.loop.updateTierLimits();
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
if (ctx.prompt) {
|
|
2363
|
+
if (typeof ctx.prompt.updateModel === 'function') {
|
|
2364
|
+
ctx.prompt.updateModel(
|
|
2365
|
+
updatedConfig.provider || 'antigravity',
|
|
2366
|
+
updatedConfig.model || 'Gemini 3.8 Flash (Low)'
|
|
2367
|
+
);
|
|
2368
|
+
} else if (ctx.prompt.renderer?.status) {
|
|
2369
|
+
ctx.prompt.renderer.status.setSession({
|
|
2370
|
+
provider: updatedConfig.provider || 'antigravity',
|
|
2371
|
+
model: updatedConfig.model || 'Gemini 3.8 Flash (Low)'
|
|
2372
|
+
});
|
|
2373
|
+
if (typeof ctx.prompt.scheduleDraw === 'function') ctx.prompt.scheduleDraw();
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
return ok(
|
|
2377
|
+
`OpenRouter account disconnected and API key removed from local vault.\n` +
|
|
2378
|
+
`Active model reverted to ${updatedConfig.provider || 'antigravity'} / ${updatedConfig.model || 'Gemini 3.8 Flash (Low)'}.`
|
|
2379
|
+
);
|
|
2380
|
+
}
|
|
2381
|
+
|
|
2382
|
+
if (sub === 'privacy' || sub === 'data-collection' || sub === 'allow' || sub === 'deny') {
|
|
2383
|
+
const val = (sub === 'allow' || sub === 'deny') ? sub : (argv[1] || '').toLowerCase();
|
|
2384
|
+
if (val !== 'deny' && val !== 'allow') {
|
|
2385
|
+
return fail('Usage: /openrouter privacy <deny | allow>');
|
|
2386
|
+
}
|
|
2387
|
+
setOpenRouterDataCollection(val);
|
|
2388
|
+
if (ctx.loop?.config) {
|
|
2389
|
+
ctx.loop.config.openrouterDataCollection = val;
|
|
2390
|
+
}
|
|
2391
|
+
const disclosure = val === 'allow'
|
|
2392
|
+
? '\nNotice: Setting data_collection to "allow" means training-eligible providers are eligible for routing. It does not by itself establish user consent to model training or guarantee training occurs.'
|
|
2393
|
+
: '\nNotice: Strict privacy active. Provider data collection for model training is strictly denied.';
|
|
2394
|
+
return ok(`OpenRouter data_collection policy set to "${val}".${disclosure}`);
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
if (sub === 'connect') {
|
|
2398
|
+
const candidateKey = argv[1];
|
|
2399
|
+
if (candidateKey && candidateKey.trim()) {
|
|
2400
|
+
const trimmedKey = candidateKey.trim();
|
|
2401
|
+
if (/[\s\r\n\0]/.test(trimmedKey) || trimmedKey.length < 8) {
|
|
2402
|
+
return fail('Invalid OpenRouter API key format.');
|
|
2403
|
+
}
|
|
2404
|
+
saveOpenRouterKey(trimmedKey, { setAsActive: true });
|
|
2405
|
+
return ok('Saved OpenRouter API key and switched active model to openrouter/free.');
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
const isSsh = Boolean(process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.SSH_CONNECTION);
|
|
2409
|
+
if (isSsh) {
|
|
2410
|
+
const pkce = generatePkceCodes();
|
|
2411
|
+
const authUrl = buildAuthorizationUrl('urn:ietf:wg:oauth:2.0:oob', pkce.codeChallenge, pkce.state);
|
|
2412
|
+
const lines = [
|
|
2413
|
+
'SSH / Headless environment detected.',
|
|
2414
|
+
'Please open the following authorization URL in your browser:',
|
|
2415
|
+
'',
|
|
2416
|
+
` ${authUrl}`,
|
|
2417
|
+
'',
|
|
2418
|
+
'After authorizing, configure your key using:',
|
|
2419
|
+
' /openrouter connect <your-api-key>'
|
|
2420
|
+
];
|
|
2421
|
+
return ok(lines.join('\n'));
|
|
2422
|
+
}
|
|
2423
|
+
|
|
2424
|
+
try {
|
|
2425
|
+
const resultPromise = startLoopbackAuth({
|
|
2426
|
+
timeoutMs: 120_000,
|
|
2427
|
+
openBrowser: true
|
|
2428
|
+
});
|
|
2429
|
+
|
|
2430
|
+
if (ctx.prompt && typeof ctx.prompt.scheduleDraw === 'function') {
|
|
2431
|
+
ctx.prompt.scheduleDraw();
|
|
2432
|
+
}
|
|
2433
|
+
|
|
2434
|
+
const { apiKey } = await resultPromise;
|
|
2435
|
+
saveOpenRouterKey(apiKey, { setAsActive: true });
|
|
2436
|
+
|
|
2437
|
+
if (ctx.loop) {
|
|
2438
|
+
ctx.loop.config = loadConfig();
|
|
2439
|
+
}
|
|
2440
|
+
if (ctx.prompt) {
|
|
2441
|
+
if (typeof ctx.prompt.updateModel === 'function') {
|
|
2442
|
+
ctx.prompt.updateModel('openrouter', 'openrouter/free');
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
return ok('Successfully authenticated with OpenRouter! Now using openrouter/free.');
|
|
2447
|
+
} catch (err) {
|
|
2448
|
+
return fail(`OpenRouter connection error: ${safeDisplay(redactProviderSecrets(errMsg(err)))}\nFallback: run "/openrouter connect <api-key>" with an API key from https://openrouter.ai/keys`);
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
|
|
2452
|
+
return fail('Usage: /openrouter [status | connect | disconnect | privacy <deny|allow>]');
|
|
2453
|
+
}
|
|
2454
|
+
},
|
|
2455
|
+
|
|
2456
|
+
{
|
|
2457
|
+
name: 'mcp',
|
|
2458
|
+
scope: 'local',
|
|
2459
|
+
usage: '/mcp [list | add <name> <cmd…> | add <name> --url <url> | remove|grant|revoke|connect|disconnect|test|refresh <name>]',
|
|
2460
|
+
description: 'Manage and diagnose MCP server connections',
|
|
2461
|
+
dialogTitle: 'MCP servers',
|
|
2462
|
+
complete: () => {
|
|
2463
|
+
try {
|
|
2464
|
+
const servers = serverStatus();
|
|
2465
|
+
const base = [
|
|
2466
|
+
{ value: 'list', label: 'list', description: 'list configured MCP servers' },
|
|
2467
|
+
{ value: 'add', label: 'add', description: 'add a new stdio or SSE/HTTP MCP server' }
|
|
2468
|
+
];
|
|
2469
|
+
for (const s of servers) {
|
|
2470
|
+
base.push({ value: `test ${s.name}`, label: `test ${s.name}`, description: `test ${s.name} connection` });
|
|
2471
|
+
base.push({ value: `grant ${s.name}`, label: `grant ${s.name}`, description: `grant consent to ${s.name}` });
|
|
2472
|
+
base.push({ value: `revoke ${s.name}`, label: `revoke ${s.name}`, description: `revoke consent from ${s.name}` });
|
|
2473
|
+
base.push({ value: `remove ${s.name}`, label: `remove ${s.name}`, description: `remove ${s.name}` });
|
|
2474
|
+
base.push({ value: `refresh ${s.name}`, label: `refresh ${s.name}`, description: `refresh tools for ${s.name}` });
|
|
2475
|
+
base.push({ value: `disconnect ${s.name}`, label: `disconnect ${s.name}`, description: `disconnect ${s.name}` });
|
|
2476
|
+
}
|
|
2477
|
+
return base;
|
|
2478
|
+
} catch (e) {
|
|
2479
|
+
return [{ value: 'add', label: 'add', description: 'add an MCP server' }];
|
|
2480
|
+
}
|
|
2481
|
+
},
|
|
2482
|
+
run: async (argv) => {
|
|
2483
|
+
const [action, serverName, ...rest] = argv;
|
|
2484
|
+
|
|
2485
|
+
if (action === 'add') {
|
|
2486
|
+
if (!serverName) {
|
|
2487
|
+
return fail('Usage: mcp add <name> <command> [args…]\n or: mcp add <name> --url <https://…>');
|
|
2488
|
+
}
|
|
2489
|
+
if (rest.length === 0) return fail(`Give "${serverName}" a command to run, or --url for an HTTP server.`);
|
|
2490
|
+
|
|
2491
|
+
let definition;
|
|
2492
|
+
if (rest[0] === '--url') {
|
|
2493
|
+
if (!rest[1]) return fail('--url needs a URL.');
|
|
2494
|
+
definition = { name: serverName, url: rest[1] };
|
|
2495
|
+
} else {
|
|
2496
|
+
definition = { name: serverName, command: rest[0] || '', args: rest.slice(1) };
|
|
2497
|
+
}
|
|
2498
|
+
|
|
2499
|
+
const result = addServer(definition);
|
|
2500
|
+
if (!result.ok) return fail(`Could not add "${serverName}": ${result.error}`);
|
|
2501
|
+
|
|
2502
|
+
// Registering is not consenting — say so, because a stdio server is a
|
|
2503
|
+
// process Causyne will spawn on this machine.
|
|
2504
|
+
return ok(
|
|
2505
|
+
`Added "${serverName}".\n\n`
|
|
2506
|
+
+ `It is NOT enabled yet. A stdio MCP server is a program Causyne runs on\n`
|
|
2507
|
+
+ `this computer, so enabling it is a separate, deliberate step:\n`
|
|
2508
|
+
+ ` mcp grant ${serverName}`
|
|
2509
|
+
);
|
|
2510
|
+
}
|
|
2511
|
+
|
|
2512
|
+
if (action === 'remove') {
|
|
2513
|
+
if (!serverName) return fail('Usage: /mcp remove <server>');
|
|
2514
|
+
const result = removeServer(serverName);
|
|
2515
|
+
if (!result.ok) return fail(result.error || 'Could not remove server.');
|
|
2516
|
+
return ok(`Removed "${serverName}" and dropped its consent.`);
|
|
2517
|
+
}
|
|
2518
|
+
|
|
2519
|
+
if (action === 'grant' || action === 'revoke') {
|
|
2520
|
+
if (!serverName) return fail(`Usage: /mcp ${action} <server>`);
|
|
2521
|
+
const known = serverStatus().some(s => s.name === serverName);
|
|
2522
|
+
if (!known) return fail(`No MCP server named "${serverName}" is configured.`);
|
|
2523
|
+
if (action === 'grant') {
|
|
2524
|
+
const granted = grantServer(serverName);
|
|
2525
|
+
if (!granted.ok) return fail(granted.error || 'Could not grant server.');
|
|
2526
|
+
return ok(`Granted "${serverName}". Its tools enter the catalogue on the next task.`);
|
|
2527
|
+
}
|
|
2528
|
+
revokeServer(serverName);
|
|
2529
|
+
return ok(`Revoked "${serverName}". Its tools are no longer callable.`);
|
|
2530
|
+
}
|
|
2531
|
+
|
|
2532
|
+
if (action && ['connect', 'test', 'refresh', 'disconnect'].includes(action)) {
|
|
2533
|
+
if (!serverName) return fail(`Usage: /mcp ${action} <server>`);
|
|
2534
|
+
const known = serverStatus().some(server => server.name === serverName);
|
|
2535
|
+
if (!known) return fail(`No MCP server named "${serverName}" is configured.`);
|
|
2536
|
+
|
|
2537
|
+
if (action === 'disconnect') {
|
|
2538
|
+
await disconnectServer(serverName);
|
|
2539
|
+
return ok(`Disconnected "${serverName}". Its grant remains in place.`);
|
|
2540
|
+
}
|
|
2541
|
+
|
|
2542
|
+
if (action === 'refresh') {
|
|
2543
|
+
const tools = await refreshServer(serverName);
|
|
2544
|
+
return ok(`Refreshed "${safeDisplay(serverName)}": ${tools.length} tool(s) available${tools.length ? ` — ${tools.map(tool => safeDisplay(tool.name)).join(', ')}` : ''}.`);
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
const client = await connectServer(serverName);
|
|
2548
|
+
return ok(
|
|
2549
|
+
`${action === 'test' ? 'MCP test passed' : 'Connected'}: "${safeDisplay(serverName)}"\n`
|
|
2550
|
+
+ `Transport: ${safeDisplay(client.status.transport || 'unknown')}\n`
|
|
2551
|
+
+ `Server: ${client.serverInfo ? `${safeDisplay(client.serverInfo.name)} ${safeDisplay(client.serverInfo.version)}` : 'identity not provided'}\n`
|
|
2552
|
+
+ `Tools: ${client.tools.length}${client.tools.length ? ` — ${client.tools.map(tool => safeDisplay(tool.name)).join(', ')}` : ''}`
|
|
2553
|
+
);
|
|
2554
|
+
}
|
|
2555
|
+
|
|
2556
|
+
if (action && action !== 'list') {
|
|
2557
|
+
return fail(`Unknown mcp action "${action}". Try: list, add, remove, grant, revoke, connect, disconnect, test, refresh.`);
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
const servers = serverStatus();
|
|
2561
|
+
if (servers.length === 0) {
|
|
2562
|
+
return ok('No MCP servers are configured.\n\nAdd one with:\n mcp add <name> <command> [args…]\n mcp add <name> --url <https://…>\n\n(prefix with / in chat, or `causyne-agent mcp …` in a terminal)', { effect: 'pick-mcp' });
|
|
2563
|
+
}
|
|
2564
|
+
const lines = ['MCP servers', ''];
|
|
2565
|
+
for (const server of servers) {
|
|
2566
|
+
lines.push(` ${safeDisplay(server.name)} [${safeDisplay(server.transport)}] ${server.granted ? 'granted' : 'NOT granted'} ${safeDisplay(server.status)}`);
|
|
2567
|
+
lines.push(` ${safeDisplay(server.target)}`);
|
|
2568
|
+
if (server.tools.length > 0) lines.push(` tools: ${server.tools.map((t: unknown) => safeDisplay(t)).join(', ')}`);
|
|
2569
|
+
if (server.error) lines.push(` error: ${safeDisplay(redactProviderSecrets(String(server.error)))}`);
|
|
2570
|
+
}
|
|
2571
|
+
lines.push('');
|
|
2572
|
+
lines.push(' mcp grant <name> to enable, mcp test <name> to diagnose, mcp remove <name> to delete.');
|
|
2573
|
+
return ok(lines.join('\n'), { effect: 'pick-mcp' });
|
|
2574
|
+
}
|
|
2575
|
+
},
|
|
2576
|
+
|
|
2577
|
+
{
|
|
2578
|
+
name: 'peers',
|
|
2579
|
+
scope: 'local',
|
|
2580
|
+
usage: '/peers [list | detect | test <id> | add <id> <command…> | remove <id>]',
|
|
2581
|
+
description: 'Manage, discover, and test external ACP peer agents (Claude Code, OpenCode, Codex, Gemini, Hermes, etc.)',
|
|
2582
|
+
dialogTitle: 'ACP peer agents',
|
|
2583
|
+
complete: () => {
|
|
2584
|
+
try {
|
|
2585
|
+
const peers = listAllPeers();
|
|
2586
|
+
return [
|
|
2587
|
+
{ value: 'list', label: 'list', description: 'list configured and preset ACP peer agents' },
|
|
2588
|
+
{ value: 'detect', label: 'detect', description: 'scan system for installed ACP agents' },
|
|
2589
|
+
...peers.map((p) => ({
|
|
2590
|
+
value: `test ${p.id}`,
|
|
2591
|
+
label: `test ${p.id}`,
|
|
2592
|
+
description: `test zero-token handshake with ${p.label}`
|
|
2593
|
+
})),
|
|
2594
|
+
...peers.map((p) => ({
|
|
2595
|
+
value: `remove ${p.id}`,
|
|
2596
|
+
label: `remove ${p.id}`,
|
|
2597
|
+
description: `remove peer profile for ${p.label}`
|
|
2598
|
+
}))
|
|
2599
|
+
];
|
|
2600
|
+
} catch (e) {
|
|
2601
|
+
return [{ value: 'detect', label: 'detect', description: 'scan system for installed ACP agents' }];
|
|
2602
|
+
}
|
|
2603
|
+
},
|
|
2604
|
+
run: async (argv) => {
|
|
2605
|
+
const [action, peerId, ...rest] = argv;
|
|
2606
|
+
|
|
2607
|
+
if (action === 'detect') {
|
|
2608
|
+
const detected = await detectAllPeers();
|
|
2609
|
+
const lines = ['Discovered ACP Peer Agents', ''];
|
|
2610
|
+
for (const item of detected) {
|
|
2611
|
+
const statusIcon = item.status === 'ready' ? '✓' : (item.status === 'needs_auth' ? '△ ' : '✕');
|
|
2612
|
+
lines.push(` ${statusIcon} ${safeDisplay(item.id)} (${safeDisplay(item.label)}) — ${safeDisplay(item.status.toUpperCase())}`);
|
|
2613
|
+
lines.push(` Command: ${safeDisplay(item.command)} ${item.args.map(a => safeDisplay(a)).join(' ')}`);
|
|
2614
|
+
if (item.details) lines.push(` Details: ${safeDisplay(redactProviderSecrets(item.details))}`);
|
|
2615
|
+
if (item.setupInstruction) lines.push(` Setup: ${safeDisplay(item.setupInstruction)}`);
|
|
2616
|
+
}
|
|
2617
|
+
lines.push('');
|
|
2618
|
+
lines.push('Use /peers test <id> to test zero-token handshake against a specific peer.');
|
|
2619
|
+
lines.push('Any ready peer can be your model provider: /model acp/<id>');
|
|
2620
|
+
return ok(lines.join('\n'));
|
|
2621
|
+
}
|
|
2622
|
+
|
|
2623
|
+
if (action === 'test') {
|
|
2624
|
+
if (!peerId) return fail('Usage: /peers test <id>');
|
|
2625
|
+
if (peerId === 'antigravity') {
|
|
2626
|
+
const { resolveAgyBinary } = await import('./providers/antigravity.js');
|
|
2627
|
+
const bin = resolveAgyBinary();
|
|
2628
|
+
if (!path.isAbsolute(bin) || !fs.existsSync(bin)) {
|
|
2629
|
+
return fail(
|
|
2630
|
+
'✕ Agent Peer Test Failed: "antigravity"\n\n'
|
|
2631
|
+
+ 'Error: Antigravity CLI binary (agy) was not found on PATH or standard install locations.'
|
|
2632
|
+
);
|
|
2633
|
+
}
|
|
2634
|
+
return ok(
|
|
2635
|
+
`✓ Agent Peer Test Passed: "antigravity"\n\n`
|
|
2636
|
+
+ `Agent: Google Antigravity (AGY)\n`
|
|
2637
|
+
+ `Command: ${safeDisplay(bin)} --output-format json\n`
|
|
2638
|
+
+ `Policy: local-cli\n`
|
|
2639
|
+
+ `Frontier Models: Gemini 4 Argon, Gemini 3.8 Flash, Claude Sonnet 5.5\n\n`
|
|
2640
|
+
+ `Ready to serve as primary AI provider or peer delegation.`
|
|
2641
|
+
);
|
|
2642
|
+
}
|
|
2643
|
+
const profile = getPeerProfile(peerId);
|
|
2644
|
+
if (!profile) return fail(`No peer agent found for "${peerId}". Try /peers detect to see available agents.`);
|
|
2645
|
+
|
|
2646
|
+
const handshake = await testPeerHandshake({
|
|
2647
|
+
command: profile.command,
|
|
2648
|
+
args: profile.args,
|
|
2649
|
+
cwd: profile.cwd || process.cwd(),
|
|
2650
|
+
...(profile.env ? { env: profile.env } : {}),
|
|
2651
|
+
timeoutMs: 15000
|
|
2652
|
+
});
|
|
2653
|
+
|
|
2654
|
+
if (handshake.ready) {
|
|
2655
|
+
const name = handshake.agentInfo
|
|
2656
|
+
? `${safeDisplay(handshake.agentInfo.name)} ${safeDisplay(handshake.agentInfo.version)}`
|
|
2657
|
+
: safeDisplay(profile.label);
|
|
2658
|
+
return ok(
|
|
2659
|
+
`✓ ACP Peer Test Passed: "${safeDisplay(peerId)}"\n\n`
|
|
2660
|
+
+ `Agent: ${name}\n`
|
|
2661
|
+
+ `Command: ${safeDisplay(profile.command)} ${profile.args.map(a => safeDisplay(a)).join(' ')}\n`
|
|
2662
|
+
+ `Policy: ${safeDisplay(profile.policy)}\n`
|
|
2663
|
+
+ `Auth Methods: ${handshake.authMethods?.map(m => safeDisplay(m)).join(', ') || 'none'}\n\n`
|
|
2664
|
+
+ `Ready to receive delegated tasks via peer_agent_delegate.`
|
|
2665
|
+
);
|
|
2666
|
+
} else {
|
|
2667
|
+
return fail(
|
|
2668
|
+
`✕ ACP Peer Test Failed: "${safeDisplay(peerId)}"\n\n`
|
|
2669
|
+
+ `Error: ${safeDisplay(redactProviderSecrets(handshake.error || 'Handshake failed'))}\n`
|
|
2670
|
+
+ `Command: ${safeDisplay(profile.command)} ${safeDisplay(profile.args.join(' '))}`
|
|
2671
|
+
);
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
|
|
2675
|
+
if (action === 'add') {
|
|
2676
|
+
if (!peerId) return fail('Usage: /peers add <id> <command> [args…]');
|
|
2677
|
+
const normalizedPeerId = peerId.trim().toLowerCase();
|
|
2678
|
+
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(normalizedPeerId)) {
|
|
2679
|
+
return fail('Invalid peer id. Use 1-64 lowercase letters, digits, dots, hyphens, or underscores.');
|
|
2680
|
+
}
|
|
2681
|
+
if (rest.length === 0) return fail(`Give "${normalizedPeerId}" a command to run (e.g. opencode acp).`);
|
|
2682
|
+
const cmd = rest[0] || '';
|
|
2683
|
+
const peerArgs = rest.slice(1);
|
|
2684
|
+
if (!cmd.trim() || /[\r\n\0]/.test(cmd) || peerArgs.some(a => /[\r\n\0]/.test(a))) {
|
|
2685
|
+
return fail('Peer command and arguments must not contain control characters or NUL bytes.');
|
|
2686
|
+
}
|
|
2687
|
+
|
|
2688
|
+
const newProfile = {
|
|
2689
|
+
id: normalizedPeerId,
|
|
2690
|
+
label: safeDisplay(peerId),
|
|
2691
|
+
command: cmd,
|
|
2692
|
+
args: peerArgs,
|
|
2693
|
+
cwd: null,
|
|
2694
|
+
policy: 'workspace' as const,
|
|
2695
|
+
timeoutSeconds: 180,
|
|
2696
|
+
env: {}
|
|
2697
|
+
};
|
|
2698
|
+
|
|
2699
|
+
const res = addPeerProfile(newProfile);
|
|
2700
|
+
if (!res.ok) return fail(`Could not save peer: ${res.error}`);
|
|
2701
|
+
return ok(`Added peer "${peerId}" [policy: workspace]. Edit ~/.causyne/peers.json to customize policy, timeout, or environment.`);
|
|
2702
|
+
}
|
|
2703
|
+
|
|
2704
|
+
if (action === 'remove') {
|
|
2705
|
+
if (!peerId) return fail('Usage: /peers remove <id>');
|
|
2706
|
+
const res = removePeerProfile(peerId);
|
|
2707
|
+
if (!res.ok) return fail(res.error || `Could not remove peer "${peerId}".`);
|
|
2708
|
+
return ok(`Removed peer profile "${peerId}".`);
|
|
2709
|
+
}
|
|
2710
|
+
|
|
2711
|
+
if (action && action !== 'list') {
|
|
2712
|
+
return fail(`Unknown peers action "${action}". Try: list, detect, test, add, remove.`);
|
|
2713
|
+
}
|
|
2714
|
+
|
|
2715
|
+
// Default: list all configured and discovered peers
|
|
2716
|
+
const peers = listAllPeers();
|
|
2717
|
+
const lines = ['Configured & Preset ACP Peer Agents', ''];
|
|
2718
|
+
for (const peer of peers) {
|
|
2719
|
+
lines.push(` • ${safeDisplay(peer.id)} (${safeDisplay(peer.label)}) [policy: ${safeDisplay(peer.policy)}, timeout: ${peer.timeoutSeconds}s]`);
|
|
2720
|
+
lines.push(` Command: ${safeDisplay(peer.command)} ${peer.args.map(a => safeDisplay(a)).join(' ')}`);
|
|
2721
|
+
}
|
|
2722
|
+
lines.push('');
|
|
2723
|
+
lines.push('Commands:');
|
|
2724
|
+
lines.push(' /peers detect Scan local system for installed ACP agents');
|
|
2725
|
+
lines.push(' /peers test <id> Verify zero-token connection to an agent');
|
|
2726
|
+
lines.push(' /peers add <id> Add or override a peer command');
|
|
2727
|
+
return ok(lines.join('\n'));
|
|
2728
|
+
}
|
|
2729
|
+
},
|
|
2730
|
+
|
|
2731
|
+
{
|
|
2732
|
+
name: 'slop',
|
|
2733
|
+
scope: 'local',
|
|
2734
|
+
usage: '/slop <file… | directory> [--movements]',
|
|
2735
|
+
description: 'Score HTML/CSS against the anti-AI-slop rules (Vision §7)',
|
|
2736
|
+
dialogTitle: 'Slop audit',
|
|
2737
|
+
complete: () => [
|
|
2738
|
+
{ value: '--movements', label: '--movements', description: 'show recommended design movements' }
|
|
2739
|
+
],
|
|
2740
|
+
run: (argv) => {
|
|
2741
|
+
const wantsMovements = argv.includes('--movements');
|
|
2742
|
+
const targets = argv.filter(a => !a.startsWith('--'));
|
|
2743
|
+
|
|
2744
|
+
if (wantsMovements && targets.length === 0) {
|
|
2745
|
+
return ok('Design movements to commit to:\n\n' + formatMovementBrief(DESIGN_MOVEMENTS));
|
|
2746
|
+
}
|
|
2747
|
+
const scanTargets = targets.length > 0 ? targets : ['.'];
|
|
2748
|
+
|
|
2749
|
+
const MAX_SLOP_FILE_BYTES = 2 * 1024 * 1024;
|
|
2750
|
+
const MAX_SLOP_FILES = 200;
|
|
2751
|
+
const files: Array<{ path: string; content: string }> = [];
|
|
2752
|
+
const collect = (target: string): string | null => {
|
|
2753
|
+
if (typeof target !== 'string' || !target || target.includes('\0')) return 'invalid target path';
|
|
2754
|
+
const expanded = target === '~'
|
|
2755
|
+
? os.homedir()
|
|
2756
|
+
: (target.startsWith('~/') || target.startsWith('~\\') ? path.join(os.homedir(), target.slice(2)) : target);
|
|
2757
|
+
const resolved = path.resolve(expanded);
|
|
2758
|
+
let stats: fs.Stats;
|
|
2759
|
+
try { stats = fs.lstatSync(resolved); } catch { return `not found: ${safeDisplay(target)}`; }
|
|
2760
|
+
if (stats.isSymbolicLink()) return `refused symlink: ${safeDisplay(target)}`;
|
|
2761
|
+
|
|
2762
|
+
if (stats.isDirectory()) {
|
|
2763
|
+
const stack: string[] = [resolved];
|
|
2764
|
+
while (stack.length > 0 && files.length < MAX_SLOP_FILES) {
|
|
2765
|
+
const dir = stack.pop()!;
|
|
2766
|
+
let entries: fs.Dirent[];
|
|
2767
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
|
|
2768
|
+
for (const entry of entries) {
|
|
2769
|
+
if (files.length >= MAX_SLOP_FILES) break;
|
|
2770
|
+
if (entry.isSymbolicLink()) continue;
|
|
2771
|
+
if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
|
|
2772
|
+
const full = path.join(dir, entry.name);
|
|
2773
|
+
if (entry.isDirectory()) {
|
|
2774
|
+
stack.push(full);
|
|
2775
|
+
} else if (entry.isFile()) {
|
|
2776
|
+
try {
|
|
2777
|
+
const fStat = fs.lstatSync(full);
|
|
2778
|
+
if (!fStat.isSymbolicLink() && fStat.isFile() && fStat.size <= MAX_SLOP_FILE_BYTES) {
|
|
2779
|
+
files.push({ path: full, content: fs.readFileSync(full, 'utf8') });
|
|
2780
|
+
}
|
|
2781
|
+
} catch { /* ignore unreadable file */ }
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
}
|
|
2785
|
+
return null;
|
|
2786
|
+
}
|
|
2787
|
+
if (!stats.isFile() || stats.size > MAX_SLOP_FILE_BYTES) {
|
|
2788
|
+
return `skipped non-regular or oversized file: ${safeDisplay(target)}`;
|
|
2789
|
+
}
|
|
2790
|
+
if (files.length >= MAX_SLOP_FILES) return null;
|
|
2791
|
+
try { files.push({ path: resolved, content: fs.readFileSync(resolved, 'utf8') }); } catch {
|
|
2792
|
+
return `could not read: ${safeDisplay(target)}`;
|
|
2793
|
+
}
|
|
2794
|
+
return null;
|
|
2795
|
+
};
|
|
2796
|
+
|
|
2797
|
+
const problems = scanTargets.map(collect).filter(Boolean);
|
|
2798
|
+
if (files.length === 0) {
|
|
2799
|
+
return ok(problems.length > 0 ? problems.join('\n') : 'No HTML/CSS/component files found — nothing to score. Try: /slop <path> or /slop --movements.');
|
|
2800
|
+
}
|
|
2801
|
+
|
|
2802
|
+
const result = analyzeFiles(files);
|
|
2803
|
+
if (result.scanned.length === 0) {
|
|
2804
|
+
return ok('No HTML/CSS/component files among the targets — nothing to score.');
|
|
2805
|
+
}
|
|
2806
|
+
if (result.findings.length === 0) {
|
|
2807
|
+
return ok(`Scanned ${result.scanned.length} file(s). Score 0 — clean. No slop signatures found.`);
|
|
2808
|
+
}
|
|
2809
|
+
const brief = result.verdict === 'slop' ? formatMovementBrief(suggestMovements([], 3)) : '';
|
|
2810
|
+
return ok(`Scanned ${result.scanned.length} file(s).\n\n` + formatFindings(result, brief));
|
|
2811
|
+
}
|
|
2812
|
+
},
|
|
2813
|
+
|
|
2814
|
+
{
|
|
2815
|
+
name: 'status',
|
|
2816
|
+
scope: 'local',
|
|
2817
|
+
usage: '/status',
|
|
2818
|
+
description: 'Show the current provider, autonomy mode and workspace scope',
|
|
2819
|
+
dialogTitle: 'Status',
|
|
2820
|
+
// One builder, shared with `causyne status`, so status output cannot drift.
|
|
2821
|
+
run: (argv, ctx = {}) => {
|
|
2822
|
+
if (ctx.prompt && typeof ctx.prompt.toggleStatusCard === 'function') {
|
|
2823
|
+
ctx.prompt.toggleStatusCard(ctx.loop);
|
|
2824
|
+
return ok('', { effect: 'silent' });
|
|
2825
|
+
}
|
|
2826
|
+
return ok(buildStatusText({ loop: ctx.loop || null }));
|
|
2827
|
+
}
|
|
2828
|
+
},
|
|
2829
|
+
|
|
2830
|
+
{
|
|
2831
|
+
name: 'observer',
|
|
2832
|
+
scope: 'local',
|
|
2833
|
+
usage: '/observer [status|toggle|mode <deterministic|advisory>|endpoint <url|none>|model <name>|strictness <relaxed|standard|strict>|test|audit|reset]',
|
|
2834
|
+
description: 'Inspect or configure the Cold Observer',
|
|
2835
|
+
dialogTitle: 'Cold Observer',
|
|
2836
|
+
complete: () => [
|
|
2837
|
+
{ value: 'status', label: 'status', description: 'view Cold Observer status and audits' },
|
|
2838
|
+
{ value: 'toggle', label: 'toggle', description: 'toggle Cold Observer on/off' },
|
|
2839
|
+
{ value: 'mode deterministic', label: 'mode deterministic', description: 'fast deterministic rules' },
|
|
2840
|
+
{ value: 'mode advisory', label: 'mode advisory', description: 'neural advisory verification' },
|
|
2841
|
+
{ value: 'strictness standard', label: 'strictness standard', description: 'standard safety strictness' },
|
|
2842
|
+
{ value: 'strictness strict', label: 'strictness strict', description: 'maximum safety strictness' },
|
|
2843
|
+
{ value: 'test', label: 'test', description: 'test advisory endpoint' },
|
|
2844
|
+
{ value: 'audit', label: 'audit', description: 'show recent audit history' },
|
|
2845
|
+
{ value: 'reset', label: 'reset', description: 'restore default settings' }
|
|
2846
|
+
],
|
|
2847
|
+
run: async (argv, ctx = {}) => {
|
|
2848
|
+
const { coldObserver } = await import('./observer/coldObserver.js');
|
|
2849
|
+
|
|
2850
|
+
// If interactive prompt is active and no sub-arguments or 'status' is given, open the interactive setup menu
|
|
2851
|
+
if ((!argv || argv.length === 0 || argv[0] === '' || argv[0] === 'status') && ctx.prompt) {
|
|
2852
|
+
const { runInteractiveObserverPicker } = await import('./tui/observerPicker.js');
|
|
2853
|
+
const message = await runInteractiveObserverPicker(ctx.prompt);
|
|
2854
|
+
return ok(message, { effect: 'silent' });
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
const sub = (argv[0] || 'status').toLowerCase();
|
|
2858
|
+
|
|
2859
|
+
if (sub === 'toggle') {
|
|
2860
|
+
const current = coldObserver.getConfig();
|
|
2861
|
+
coldObserver.updateConfig({ enabled: !current.enabled });
|
|
2862
|
+
return ok(`Cold Observer is now ${!current.enabled ? 'ENABLED' : 'DISABLED'}.`);
|
|
2863
|
+
}
|
|
2864
|
+
|
|
2865
|
+
if (sub === 'mode') {
|
|
2866
|
+
const targetMode = String(argv[1] || '').toLowerCase();
|
|
2867
|
+
if (!['deterministic', 'advisory', 'local', 'hybrid'].includes(targetMode)) {
|
|
2868
|
+
return fail('Invalid mode. Choose: deterministic or advisory.');
|
|
2869
|
+
}
|
|
2870
|
+
coldObserver.updateConfig({ mode: targetMode as any });
|
|
2871
|
+
return ok(`Cold Observer mode set to "${coldObserver.getConfig().mode}".`);
|
|
2872
|
+
}
|
|
2873
|
+
|
|
2874
|
+
if (sub === 'endpoint') {
|
|
2875
|
+
const target = String(argv[1] || '').trim();
|
|
2876
|
+
try {
|
|
2877
|
+
coldObserver.updateConfig({ endpoint: target === 'none' ? '' : target });
|
|
2878
|
+
} catch (error) {
|
|
2879
|
+
return fail(error instanceof Error ? error.message : 'Invalid endpoint.');
|
|
2880
|
+
}
|
|
2881
|
+
const endpoint = coldObserver.getConfig().endpoint;
|
|
2882
|
+
return ok(endpoint ? `Advisory endpoint set to ${endpoint}.` : 'Advisory endpoint cleared.');
|
|
2883
|
+
}
|
|
2884
|
+
|
|
2885
|
+
if (sub === 'model') {
|
|
2886
|
+
const target = String(argv[1] || '').trim();
|
|
2887
|
+
coldObserver.updateConfig({ model: target === 'none' ? '' : target });
|
|
2888
|
+
const model = coldObserver.getConfig().model;
|
|
2889
|
+
return ok(model ? `Advisory model set to ${model}.` : 'Advisory model cleared.');
|
|
2890
|
+
}
|
|
2891
|
+
|
|
2892
|
+
if (sub === 'strictness') {
|
|
2893
|
+
const target = String(argv[1] || '').toLowerCase();
|
|
2894
|
+
if (!['relaxed', 'standard', 'strict', 'moderate', 'paranoid'].includes(target)) {
|
|
2895
|
+
return fail('Invalid strictness. Choose: relaxed, standard, or strict.');
|
|
2896
|
+
}
|
|
2897
|
+
coldObserver.updateConfig({ strictness: target as any });
|
|
2898
|
+
return ok(`Cold Observer strictness set to "${coldObserver.getConfig().strictness}".`);
|
|
2899
|
+
}
|
|
2900
|
+
|
|
2901
|
+
if (sub === 'test') {
|
|
2902
|
+
const health = await coldObserver.healthCheck();
|
|
2903
|
+
if (!health.endpoint) {
|
|
2904
|
+
return ok('No advisory endpoint configured. The deterministic observer needs no endpoint and remains active.');
|
|
2905
|
+
}
|
|
2906
|
+
return ok([
|
|
2907
|
+
`Endpoint: ${health.endpoint}`,
|
|
2908
|
+
`Model: ${health.model || '(unset)'}`,
|
|
2909
|
+
`Healthy: ${health.healthy ? 'yes' : 'no'} (${health.latencyMs}ms)`,
|
|
2910
|
+
`Detail: ${health.detail}`
|
|
2911
|
+
].join('\n'));
|
|
2912
|
+
}
|
|
2913
|
+
|
|
2914
|
+
if (sub === 'reset') {
|
|
2915
|
+
coldObserver.updateConfig({
|
|
2916
|
+
enabled: true,
|
|
2917
|
+
mode: 'deterministic',
|
|
2918
|
+
endpoint: '',
|
|
2919
|
+
model: '',
|
|
2920
|
+
timeoutMs: 800,
|
|
2921
|
+
strictness: 'standard'
|
|
2922
|
+
});
|
|
2923
|
+
return ok('Cold Observer configuration reset to defaults.');
|
|
2924
|
+
}
|
|
2925
|
+
|
|
2926
|
+
if (sub === 'audit') {
|
|
2927
|
+
const audits = coldObserver.getAuditHistory();
|
|
2928
|
+
if (audits.length === 0) {
|
|
2929
|
+
return ok('No Cold Observer audit records yet.');
|
|
2930
|
+
}
|
|
2931
|
+
const lines = audits.slice(-10).map((a) => {
|
|
2932
|
+
const time = new Date(a.timestamp).toLocaleTimeString();
|
|
2933
|
+
const tag = a.type === 'mutation' ? `[mutation ${a.tool || ''}]` : '[verification]';
|
|
2934
|
+
const score = typeof a.riskScore === 'number' ? `(risk ${(a.riskScore * 100).toFixed(0)}%)` : '';
|
|
2935
|
+
const veto = a.veto ? 'VETO' : 'pass';
|
|
2936
|
+
return `${time} ${tag} ${veto} ${score} ${a.details}`;
|
|
2937
|
+
});
|
|
2938
|
+
return ok(`Recent Cold Observer audits (last 10):\n\n${lines.join('\n')}`);
|
|
2939
|
+
}
|
|
2940
|
+
|
|
2941
|
+
const cfg = coldObserver.getConfig();
|
|
2942
|
+
const audits = coldObserver.getAuditHistory();
|
|
2943
|
+
const vetoes = audits.filter((a) => a.veto).length;
|
|
2944
|
+
return ok([
|
|
2945
|
+
'Cold Observer',
|
|
2946
|
+
'──────────────────────────────────────────────',
|
|
2947
|
+
`Status: ${cfg.enabled ? 'Active (mutations and completion claims)' : 'Disabled'}`,
|
|
2948
|
+
`Mode: ${cfg.mode.toUpperCase()}`,
|
|
2949
|
+
`Strictness: ${cfg.strictness}`,
|
|
2950
|
+
`Advisory: ${cfg.endpoint ? `${cfg.model || '(model unset)'} at ${cfg.endpoint}` : 'not configured (deterministic only)'}`,
|
|
2951
|
+
`Audit events: ${audits.length} recorded (${vetoes} vetoes enforced)`,
|
|
2952
|
+
'',
|
|
2953
|
+
'Subcommands:',
|
|
2954
|
+
' /observer toggle Enable or disable protection',
|
|
2955
|
+
' /observer mode <deterministic|advisory> Choose the review mode',
|
|
2956
|
+
' /observer endpoint <url|none> Set a loopback advisory endpoint',
|
|
2957
|
+
' /observer model <name> Set the advisory model name',
|
|
2958
|
+
' /observer strictness <relaxed|standard|strict>',
|
|
2959
|
+
' /observer test Probe the advisory endpoint',
|
|
2960
|
+
' /observer audit Inspect recent audits',
|
|
2961
|
+
' /observer reset Restore defaults'
|
|
2962
|
+
].join('\n'));
|
|
2963
|
+
}
|
|
2964
|
+
},
|
|
2965
|
+
|
|
2966
|
+
{
|
|
2967
|
+
name: 'acp',
|
|
2968
|
+
scope: 'local',
|
|
2969
|
+
usage: '/acp [status|peers]',
|
|
2970
|
+
description: 'Agent Client Protocol (ACP) server and peer delegation status',
|
|
2971
|
+
dialogTitle: 'Agent Client Protocol',
|
|
2972
|
+
complete: () => [
|
|
2973
|
+
{ value: 'status', label: 'status', description: 'view ACP protocol server status' },
|
|
2974
|
+
{ value: 'peers', label: 'peers', description: 'view ACP peer delegation configuration' }
|
|
2975
|
+
],
|
|
2976
|
+
run: async (argv) => {
|
|
2977
|
+
const sub = (argv[0] || 'status').toLowerCase();
|
|
2978
|
+
if (sub === 'peer' || sub === 'peers') {
|
|
2979
|
+
const { loadPeerProfiles, peerProfilesPath } = await import('./acp/peerProfiles.js');
|
|
2980
|
+
const profiles = loadPeerProfiles();
|
|
2981
|
+
return ok([
|
|
2982
|
+
'Peer delegation (ACP)',
|
|
2983
|
+
'──────────────────────────────────────────────',
|
|
2984
|
+
`Profiles file: ${peerProfilesPath()}`,
|
|
2985
|
+
`Configured: ${profiles.length === 0 ? 'none' : profiles.map((p) => `${p.id} (${p.policy})`).join(', ')}`,
|
|
2986
|
+
'',
|
|
2987
|
+
'The model selects a profile id and writes a prompt. Executable, arguments,',
|
|
2988
|
+
'working directory, and environment always come from the profile file.'
|
|
2989
|
+
].join('\n'));
|
|
2990
|
+
}
|
|
2991
|
+
return ok([
|
|
2992
|
+
'Agent Client Protocol (ACP) - Causyne Agent',
|
|
2993
|
+
'──────────────────────────────────────────────',
|
|
2994
|
+
'Version: ACP v1 (JSON-RPC 2.0 over stdio)',
|
|
2995
|
+
'Server command: causyne acp',
|
|
2996
|
+
'Wire: newline-delimited JSON-RPC',
|
|
2997
|
+
'Sessions: session/new, session/prompt, session/cancel, session/update',
|
|
2998
|
+
'Optional: session/list, session/close, session/set_mode',
|
|
2999
|
+
'Workspace: one workspace per server process',
|
|
3000
|
+
'',
|
|
3001
|
+
'Run "causyne acp" to connect this agent to any ACP client.'
|
|
3002
|
+
].join('\n'));
|
|
3003
|
+
}
|
|
3004
|
+
},
|
|
3005
|
+
|
|
3006
|
+
{
|
|
3007
|
+
name: 'init',
|
|
3008
|
+
aliases: ['initialize'],
|
|
3009
|
+
scope: 'local',
|
|
3010
|
+
usage: '/init',
|
|
3011
|
+
description: 'Inspect active workspace architecture and generate or update AGENTS.md instructions',
|
|
3012
|
+
dialogTitle: 'Workspace Init',
|
|
3013
|
+
run: async (argv, ctx = {}) => {
|
|
3014
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3015
|
+
let files: string[] = [];
|
|
3016
|
+
try {
|
|
3017
|
+
if (fs.existsSync(ws)) files = fs.readdirSync(ws);
|
|
3018
|
+
} catch {
|
|
3019
|
+
files = [];
|
|
3020
|
+
}
|
|
3021
|
+
const hasPkg = files.includes('package.json');
|
|
3022
|
+
const hasCargo = files.includes('Cargo.toml');
|
|
3023
|
+
const hasPy = files.includes('pyproject.toml') || files.includes('requirements.txt');
|
|
3024
|
+
const hasGo = files.includes('go.mod');
|
|
3025
|
+
const hasAgents = files.includes('AGENTS.md');
|
|
3026
|
+
|
|
3027
|
+
const detected = [];
|
|
3028
|
+
if (hasPkg) detected.push('Node.js / JavaScript / TypeScript');
|
|
3029
|
+
if (hasCargo) detected.push('Rust / Cargo');
|
|
3030
|
+
if (hasPy) detected.push('Python');
|
|
3031
|
+
if (hasGo) detected.push('Go');
|
|
3032
|
+
if (detected.length === 0) detected.push('Generic workspace');
|
|
3033
|
+
|
|
3034
|
+
const summary = [
|
|
3035
|
+
`Workspace Initializer: ${ws}`,
|
|
3036
|
+
`Ecosystem: ${detected.join(', ')}`,
|
|
3037
|
+
`AGENTS.md: ${hasAgents ? 'Present (ready for refresh)' : 'Not found (needs creation)'}`,
|
|
3038
|
+
'',
|
|
3039
|
+
'To have Causyne Agent inspect and establish conventions for this project,',
|
|
3040
|
+
'run this turn or press Enter to prompt the agent:'
|
|
3041
|
+
].join('\n');
|
|
3042
|
+
|
|
3043
|
+
if (ctx.prompt) {
|
|
3044
|
+
ctx.prompt.editor.setText('Analyze this project architecture, testing setup, and style conventions, then create or update AGENTS.md for this workspace.');
|
|
3045
|
+
ctx.prompt.scheduleDraw();
|
|
3046
|
+
return ok(summary, { effect: 'inline' });
|
|
3047
|
+
}
|
|
3048
|
+
return ok(summary);
|
|
3049
|
+
}
|
|
3050
|
+
},
|
|
3051
|
+
|
|
3052
|
+
{
|
|
3053
|
+
name: 'review',
|
|
3054
|
+
aliases: ['code-review', 'pr-review'],
|
|
3055
|
+
scope: 'local',
|
|
3056
|
+
usage: '/review [target]',
|
|
3057
|
+
description: 'Run an immediate code review on working tree changes or a file',
|
|
3058
|
+
dialogTitle: 'Code Review',
|
|
3059
|
+
run: async (argv, ctx = {}) => {
|
|
3060
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3061
|
+
const target = argv.join(' ').trim();
|
|
3062
|
+
let promptText = '';
|
|
3063
|
+
if (target) {
|
|
3064
|
+
promptText = `Please review ${target} for security vulnerabilities, logic correctness, performance, and best practices.`;
|
|
3065
|
+
} else {
|
|
3066
|
+
try {
|
|
3067
|
+
const status = runGitCommand(['status', '--short'], ws).trim();
|
|
3068
|
+
if (!status) {
|
|
3069
|
+
return ok('Working tree is clean. To review a specific file, run: /review <path>');
|
|
3070
|
+
}
|
|
3071
|
+
promptText = `Please review current uncommitted workspace changes (git diff) for correctness, edge cases, regression risk, and code quality.`;
|
|
3072
|
+
} catch {
|
|
3073
|
+
promptText = `Please review the files in this workspace for code quality, architectural consistency, and potential bugs.`;
|
|
3074
|
+
}
|
|
3075
|
+
}
|
|
3076
|
+
|
|
3077
|
+
if (ctx.prompt) {
|
|
3078
|
+
ctx.prompt.editor.setText(promptText);
|
|
3079
|
+
ctx.prompt.scheduleDraw();
|
|
3080
|
+
return ok(`Ready to review: "${promptText}"`, { effect: 'inline' });
|
|
3081
|
+
}
|
|
3082
|
+
return ok(`Code review target: ${promptText}`);
|
|
3083
|
+
}
|
|
3084
|
+
},
|
|
3085
|
+
|
|
3086
|
+
{
|
|
3087
|
+
name: 'retry',
|
|
3088
|
+
aliases: ['again', 'redo'],
|
|
3089
|
+
scope: 'local',
|
|
3090
|
+
usage: '/retry',
|
|
3091
|
+
description: 'Re-send the last user prompt in this session',
|
|
3092
|
+
run: async (argv, ctx = {}) => {
|
|
3093
|
+
const messages = ctx.loop?.messages || [];
|
|
3094
|
+
const lastUser = [...messages].reverse().find(m => m.role === 'user' && typeof m.content === 'string');
|
|
3095
|
+
if (!lastUser || !lastUser.content) {
|
|
3096
|
+
return fail('No previous user prompt found in this session to retry.');
|
|
3097
|
+
}
|
|
3098
|
+
const promptText = lastUser.content;
|
|
3099
|
+
if (ctx.prompt) {
|
|
3100
|
+
ctx.prompt.editor.setText(promptText);
|
|
3101
|
+
ctx.prompt.scheduleDraw();
|
|
3102
|
+
return ok(`Re-loaded last prompt: "${promptText.slice(0, 80)}"`, { effect: 'inline' });
|
|
3103
|
+
}
|
|
3104
|
+
return ok(`Last prompt: ${promptText}`);
|
|
3105
|
+
}
|
|
3106
|
+
},
|
|
3107
|
+
|
|
3108
|
+
{
|
|
3109
|
+
name: 'title',
|
|
3110
|
+
aliases: ['rename'],
|
|
3111
|
+
scope: 'local',
|
|
3112
|
+
usage: '/title [new title]',
|
|
3113
|
+
description: 'View or rename the active chat session title',
|
|
3114
|
+
dialogTitle: 'Session Title',
|
|
3115
|
+
run: async (argv, ctx = {}) => {
|
|
3116
|
+
const activeId = getActiveSessionId();
|
|
3117
|
+
if (!activeId) return fail('No active session.');
|
|
3118
|
+
const session = getSession(activeId);
|
|
3119
|
+
const currentTitle = session ? session.title : 'Untitled';
|
|
3120
|
+
|
|
3121
|
+
const rawTitle = argv.join(' ').trim();
|
|
3122
|
+
if (!rawTitle) {
|
|
3123
|
+
return ok(`Active session ID: ${safeDisplay(activeId)}\nCurrent title: "${safeDisplay(currentTitle)}"\n\nTo rename, run: /title <new name>`);
|
|
3124
|
+
}
|
|
3125
|
+
const newTitle = safeDisplay(rawTitle).replace(/[\r\n]+/g, ' ').trim().slice(0, 120);
|
|
3126
|
+
if (!newTitle) {
|
|
3127
|
+
return fail('Session title cannot be empty.');
|
|
3128
|
+
}
|
|
3129
|
+
|
|
3130
|
+
const renamed = renameSession(activeId, newTitle);
|
|
3131
|
+
if (!renamed) return fail(`Could not rename session "${activeId}".`);
|
|
3132
|
+
|
|
3133
|
+
if (ctx.loop?.memoryManager?.session) {
|
|
3134
|
+
ctx.loop.memoryManager.session.title = newTitle;
|
|
3135
|
+
}
|
|
3136
|
+
if (ctx.prompt?.renderer?.status) {
|
|
3137
|
+
ctx.prompt.renderer.status.setSession({ title: newTitle });
|
|
3138
|
+
}
|
|
3139
|
+
if (ctx.prompt?.surface?.stage) {
|
|
3140
|
+
ctx.prompt.scheduleDraw();
|
|
3141
|
+
}
|
|
3142
|
+
|
|
3143
|
+
return ok(`Session renamed to: "${newTitle}"`, { effect: 'inline' });
|
|
3144
|
+
}
|
|
3145
|
+
},
|
|
3146
|
+
|
|
3147
|
+
{
|
|
3148
|
+
name: 'mode',
|
|
3149
|
+
aliases: ['autonomy'],
|
|
3150
|
+
scope: 'local',
|
|
3151
|
+
usage: '/mode [A | B | C]',
|
|
3152
|
+
description: 'View or switch autonomy mode (A: Ask, B: Balanced, C: Autonomous)',
|
|
3153
|
+
dialogTitle: 'Autonomy Mode',
|
|
3154
|
+
complete: () => [
|
|
3155
|
+
{ value: 'A', label: 'A', description: 'Ask — review actions before execution' },
|
|
3156
|
+
{ value: 'B', label: 'B', description: 'Balanced — normal supervised autonomy' },
|
|
3157
|
+
{ value: 'C', label: 'C', description: 'Autonomous — maximum runway within policy' }
|
|
3158
|
+
],
|
|
3159
|
+
run: async (argv, ctx = {}) => {
|
|
3160
|
+
const config = loadConfig();
|
|
3161
|
+
const target = (argv[0] || '').toUpperCase().trim();
|
|
3162
|
+
if (!target) {
|
|
3163
|
+
if (ctx.prompt) {
|
|
3164
|
+
const { openModeControl } = await import('./tui/composerControls.js');
|
|
3165
|
+
if (ctx.loop) {
|
|
3166
|
+
openModeControl(ctx.prompt, ctx.loop);
|
|
3167
|
+
return ok('Opened mode selector.', { effect: 'silent' });
|
|
3168
|
+
}
|
|
3169
|
+
}
|
|
3170
|
+
return ok(`Current autonomy mode: ${config.autonomyMode || 'B'}\nModes:\n A: Ask (confirm gated actions)\n B: Balanced (supervised execution)\n C: Autonomous (independent execution)`);
|
|
3171
|
+
}
|
|
3172
|
+
|
|
3173
|
+
if (!['A', 'B', 'C'].includes(target)) {
|
|
3174
|
+
return fail(`Invalid mode "${target}". Choose A, B, or C.`);
|
|
3175
|
+
}
|
|
3176
|
+
|
|
3177
|
+
config.autonomyMode = target;
|
|
3178
|
+
saveConfig(config);
|
|
3179
|
+
if (ctx.loop && typeof ctx.loop.setAutonomyMode === 'function') {
|
|
3180
|
+
ctx.loop.setAutonomyMode(target);
|
|
3181
|
+
}
|
|
3182
|
+
if (ctx.prompt) {
|
|
3183
|
+
ctx.prompt.renderer?.status?.setSession?.({ autonomyMode: target });
|
|
3184
|
+
ctx.prompt.surface?.setSessionInfo?.({ autonomyMode: target });
|
|
3185
|
+
ctx.prompt.notice = `Mode ${target} active`;
|
|
3186
|
+
if (ctx.prompt.scheduleDraw) ctx.prompt.scheduleDraw();
|
|
3187
|
+
return ok(`Autonomy mode switched to ${target}.`, { effect: 'inline' });
|
|
3188
|
+
}
|
|
3189
|
+
return ok(`Autonomy mode switched to ${target}.`);
|
|
3190
|
+
}
|
|
3191
|
+
},
|
|
3192
|
+
|
|
3193
|
+
{
|
|
3194
|
+
name: 'doctor',
|
|
3195
|
+
aliases: ['health', 'diagnostics'],
|
|
3196
|
+
scope: 'local',
|
|
3197
|
+
usage: '/doctor [--report|--probe]',
|
|
3198
|
+
description: 'Run environment, provider, and tool health diagnostics (--report for redacted errors, --probe for $0 live test)',
|
|
3199
|
+
dialogTitle: 'Doctor',
|
|
3200
|
+
run: async (argv, ctx = {}) => {
|
|
3201
|
+
const config = loadConfig();
|
|
3202
|
+
const wantsReport = Array.isArray(argv)
|
|
3203
|
+
&& argv.some((tok) => tok === '--report' || tok === 'report' || tok === '--errors');
|
|
3204
|
+
if (wantsReport) {
|
|
3205
|
+
return ok(formatRedactedProviderErrorReport({
|
|
3206
|
+
provider: config.provider,
|
|
3207
|
+
model: config.model,
|
|
3208
|
+
causyneVersion: getPackageVersion()
|
|
3209
|
+
}));
|
|
3210
|
+
}
|
|
3211
|
+
const wantsProbe = Array.isArray(argv)
|
|
3212
|
+
&& argv.some((tok) => tok === '--probe' || tok === 'probe');
|
|
3213
|
+
if (wantsProbe) {
|
|
3214
|
+
const report = await runZeroSpendByokProbe();
|
|
3215
|
+
return ok(formatByokProbeReport(report));
|
|
3216
|
+
}
|
|
3217
|
+
const lines = ['Causyne Health & Diagnostics', ''];
|
|
3218
|
+
|
|
3219
|
+
const nodeVer = process.version;
|
|
3220
|
+
const nodeOk = parseInt(nodeVer.slice(1).split('.')[0] || '0', 10) >= 24;
|
|
3221
|
+
lines.push(` ${nodeOk ? '✓' : '△'} Node.js version : ${nodeVer} ${nodeOk ? '(supported)' : '(Node >= 24 required)'}`);
|
|
3222
|
+
lines.push(` • Platform : ${process.platform} (${process.arch})`);
|
|
3223
|
+
|
|
3224
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3225
|
+
let isGit = false;
|
|
3226
|
+
try {
|
|
3227
|
+
runGitCommand(['rev-parse', '--is-inside-work-tree'], ws);
|
|
3228
|
+
isGit = true;
|
|
3229
|
+
} catch {}
|
|
3230
|
+
lines.push(` ✓ Workspace root : ${ws}`);
|
|
3231
|
+
lines.push(` ${isGit ? '✓' : '•'} Git repository : ${isGit ? 'active' : 'not a git repo'}`);
|
|
3232
|
+
|
|
3233
|
+
const provider = config.provider || 'not configured';
|
|
3234
|
+
const model = config.model || 'default';
|
|
3235
|
+
lines.push(` • Provider / Model : ${safeDisplay(provider)} / ${safeDisplay(model)}`);
|
|
3236
|
+
|
|
3237
|
+
const sandboxCap = probeOsSandbox();
|
|
3238
|
+
const sandboxMode = resolveOsSandboxMode(process.env);
|
|
3239
|
+
const keychainCap = probeOsKeychain({ env: process.env });
|
|
3240
|
+
const keychainMode = resolveKeychainMode(process.env);
|
|
3241
|
+
const policyState = loadEnterprisePolicy(ws, process.env);
|
|
3242
|
+
const auditCheck = auditLog.verifyAuditChain({ days: 7 });
|
|
3243
|
+
lines.push(` • OS Sandbox : ${sandboxMode.mode} (${sandboxCap.backend}${sandboxCap.available ? ', available' : ', unavailable'})`);
|
|
3244
|
+
lines.push(` • OS Keychain : ${keychainMode} (${keychainCap.backend}${keychainCap.available ? ', available' : ', unavailable'})`);
|
|
3245
|
+
lines.push(` • Enterprise Policy : ${!policyState.found ? 'not configured' : (policyState.error ? `INVALID (${safeDisplay(policyState.error)})` : `active (${safeDisplay(policyState.sourcePath)})`)}`);
|
|
3246
|
+
lines.push(` ${auditCheck.ok ? '✓' : '✕'} Audit Chain : ${auditCheck.ok ? `verified (${auditCheck.entriesVerified} hashed entries)` : `${auditCheck.errors.length} integrity error(s)`}`);
|
|
3247
|
+
|
|
3248
|
+
const servers = serverStatus();
|
|
3249
|
+
const grantedCount = servers.filter(s => s.granted).length;
|
|
3250
|
+
lines.push(` • MCP Servers : ${servers.length} configured (${grantedCount} granted)`);
|
|
3251
|
+
|
|
3252
|
+
const peers = listAllPeers();
|
|
3253
|
+
lines.push(` • ACP Peers : ${peers.length} available`);
|
|
3254
|
+
|
|
3255
|
+
const zeroCost = await detectZeroCostProviders({ config, probeOllama: true, timeoutMs: 700 });
|
|
3256
|
+
const readyZeroCost = zeroCost.filter((z) => z.readiness === 'ready');
|
|
3257
|
+
lines.push('');
|
|
3258
|
+
lines.push(`Zero-Cost ($0 API) Routes (${readyZeroCost.length} ready)`);
|
|
3259
|
+
if (zeroCost.length === 0) {
|
|
3260
|
+
lines.push(' • None detected yet — install Ollama (`ollama pull qwen2.5-coder`) or run `/openrouter connect`.');
|
|
3261
|
+
} else {
|
|
3262
|
+
for (const z of zeroCost) {
|
|
3263
|
+
const icon = z.readiness === 'ready' ? '✓' : '△';
|
|
3264
|
+
lines.push(` ${icon} ${safeDisplay(z.label)} [${safeDisplay(z.provider)}${z.model ? ` / ${safeDisplay(z.model)}` : ''}] — ${safeDisplay(z.readiness)}`);
|
|
3265
|
+
}
|
|
3266
|
+
}
|
|
3267
|
+
|
|
3268
|
+
const recentHttpErrors = getRecentProviderDiagnostics();
|
|
3269
|
+
if (recentHttpErrors.length > 0) {
|
|
3270
|
+
lines.push('');
|
|
3271
|
+
lines.push(`Recent Provider HTTP Errors: ${recentHttpErrors.length} recorded (run \`/doctor --report\` for a redacted diagnostic report).`);
|
|
3272
|
+
}
|
|
3273
|
+
|
|
3274
|
+
const criticalIssues: string[] = [];
|
|
3275
|
+
const warnings: string[] = [];
|
|
3276
|
+
if (!nodeOk) criticalIssues.push(`Node.js ${nodeVer} is unsupported — upgrade to Node.js >= 24.`);
|
|
3277
|
+
if (!auditCheck.ok) criticalIssues.push(`Audit log chain has ${auditCheck.errors.length} integrity error(s) — run \`/audit verify\`.`);
|
|
3278
|
+
if (policyState.found && policyState.error) criticalIssues.push(`Enterprise policy invalid: ${safeDisplay(policyState.error)}`);
|
|
3279
|
+
if (!config.provider) warnings.push('No active provider configured — run `/setup` or `/model`.');
|
|
3280
|
+
|
|
3281
|
+
lines.push('');
|
|
3282
|
+
if (criticalIssues.length > 0) {
|
|
3283
|
+
lines.push(`Diagnostics found ${criticalIssues.length} critical issue(s)${warnings.length > 0 ? ` and ${warnings.length} warning(s)` : ''}:`);
|
|
3284
|
+
for (const issue of criticalIssues) lines.push(` ✕ ${issue}`);
|
|
3285
|
+
for (const warn of warnings) lines.push(` △ ${warn}`);
|
|
3286
|
+
return { ok: false, output: lines.join('\n') };
|
|
3287
|
+
}
|
|
3288
|
+
if (warnings.length > 0) {
|
|
3289
|
+
lines.push(`Diagnostics passed with ${warnings.length} warning(s):`);
|
|
3290
|
+
for (const warn of warnings) lines.push(` △ ${warn}`);
|
|
3291
|
+
return ok(lines.join('\n'));
|
|
3292
|
+
}
|
|
3293
|
+
lines.push('All diagnostic invariants passed. Run /peers detect or /model list for component details.');
|
|
3294
|
+
return ok(lines.join('\n'));
|
|
3295
|
+
}
|
|
3296
|
+
},
|
|
3297
|
+
|
|
3298
|
+
{
|
|
3299
|
+
name: 'export',
|
|
3300
|
+
aliases: ['share', 'save'],
|
|
3301
|
+
scope: 'local',
|
|
3302
|
+
usage: '/export [filename.md]',
|
|
3303
|
+
description: 'Export conversation transcript to a Markdown document in the workspace',
|
|
3304
|
+
dialogTitle: 'Export Conversation',
|
|
3305
|
+
run: async (argv, ctx = {}) => {
|
|
3306
|
+
const activeId = getActiveSessionId();
|
|
3307
|
+
if (!activeId) return fail('No active session to export.');
|
|
3308
|
+
const session = getSession(activeId);
|
|
3309
|
+
if (!session || !session.messages || session.messages.length === 0) {
|
|
3310
|
+
return fail('Session has no messages to export.');
|
|
3311
|
+
}
|
|
3312
|
+
|
|
3313
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3314
|
+
const safeId = String(activeId).replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
3315
|
+
const defaultFilename = `causyne-session-${safeId}.md`;
|
|
3316
|
+
const filename = argv.join(' ').trim() || defaultFilename;
|
|
3317
|
+
if (filename.includes('\0')) {
|
|
3318
|
+
return fail('Invalid export filename.');
|
|
3319
|
+
}
|
|
3320
|
+
const targetPath = path.resolve(ws, filename);
|
|
3321
|
+
if (!isPhysicalPathAllowed(targetPath, [ws], false)) {
|
|
3322
|
+
return fail(`Refusing to export outside the active workspace: ${safeDisplay(targetPath)}`);
|
|
3323
|
+
}
|
|
3324
|
+
if (isCredentialPath(targetPath)) {
|
|
3325
|
+
return fail(`Refusing to overwrite credential or sensitive file: ${safeDisplay(targetPath)}`);
|
|
3326
|
+
}
|
|
3327
|
+
try {
|
|
3328
|
+
const existing = fs.lstatSync(targetPath);
|
|
3329
|
+
if (existing.isSymbolicLink() || !existing.isFile()) {
|
|
3330
|
+
return fail(`Refusing to export to symlink or non-regular file: ${safeDisplay(targetPath)}`);
|
|
3331
|
+
}
|
|
3332
|
+
} catch (statErr: unknown) {
|
|
3333
|
+
const code = typeof statErr === 'object' && statErr !== null && 'code' in statErr ? String(statErr.code) : '';
|
|
3334
|
+
if (code !== 'ENOENT') {
|
|
3335
|
+
return fail(`Could not inspect export target: ${errMsg(statErr)}`);
|
|
3336
|
+
}
|
|
3337
|
+
}
|
|
3338
|
+
|
|
3339
|
+
const createdIso = Number.isFinite(session.createdAt)
|
|
3340
|
+
? new Date(session.createdAt).toISOString()
|
|
3341
|
+
: new Date().toISOString();
|
|
3342
|
+
const header = `# Causyne Agent Conversation Export\n\n- **Session ID**: \`${safeDisplay(session.id)}\`\n- **Title**: ${safeDisplay(session.title)}\n- **Date**: ${createdIso}\n- **Workspace**: \`${safeDisplay(session.workspace)}\`\n- **Total Messages**: ${session.messages.length}\n\n---\n\n`;
|
|
3343
|
+
|
|
3344
|
+
const body = session.messages
|
|
3345
|
+
.filter((m: any) => m && m.role !== 'system')
|
|
3346
|
+
.map((m: any) => {
|
|
3347
|
+
const roleLabel = m.role === 'user' ? '### User' : '### Causyne Agent';
|
|
3348
|
+
let rawContent: string;
|
|
3349
|
+
if (typeof m.content === 'string') {
|
|
3350
|
+
rawContent = m.content;
|
|
3351
|
+
} else {
|
|
3352
|
+
try { rawContent = JSON.stringify(m.content, null, 2) ?? ''; } catch { rawContent = String(m.content); }
|
|
3353
|
+
}
|
|
3354
|
+
return `${roleLabel}\n\n${redactTextSecrets(rawContent)}\n`;
|
|
3355
|
+
})
|
|
3356
|
+
.join('\n---\n\n');
|
|
3357
|
+
|
|
3358
|
+
try {
|
|
3359
|
+
atomicWriteSecretFileSync(targetPath, redactTextSecrets(header + body));
|
|
3360
|
+
return ok(`Exported conversation to: ${safeDisplay(targetPath)}`);
|
|
3361
|
+
} catch (err) {
|
|
3362
|
+
return fail(`Could not export conversation: ${errMsg(err)}`);
|
|
3363
|
+
}
|
|
3364
|
+
}
|
|
3365
|
+
},
|
|
3366
|
+
|
|
3367
|
+
{
|
|
3368
|
+
name: 'policy',
|
|
3369
|
+
scope: 'local',
|
|
3370
|
+
usage: '/policy [status|validate]',
|
|
3371
|
+
description: 'Inspect or validate declarative enterprise policy (causyne.policy.json)',
|
|
3372
|
+
dialogTitle: 'Enterprise Policy',
|
|
3373
|
+
complete: () => [
|
|
3374
|
+
{ value: 'status', label: 'status', description: 'show active enterprise policy rules' },
|
|
3375
|
+
{ value: 'validate', label: 'validate', description: 'validate enterprise policy syntax and fail-closed status' }
|
|
3376
|
+
],
|
|
3377
|
+
run: async (argv, ctx = {}) => {
|
|
3378
|
+
const sub = (argv[0] || 'status').toLowerCase();
|
|
3379
|
+
if (sub !== 'status' && sub !== 'validate') {
|
|
3380
|
+
return fail(`Unknown policy action "${safeDisplay(sub)}". Try: status, validate.`);
|
|
3381
|
+
}
|
|
3382
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3383
|
+
const report = formatEnterprisePolicyReport(ws);
|
|
3384
|
+
return report.ok ? ok(report.text) : fail(report.text);
|
|
3385
|
+
}
|
|
3386
|
+
},
|
|
3387
|
+
|
|
3388
|
+
{
|
|
3389
|
+
name: 'audit',
|
|
3390
|
+
scope: 'local',
|
|
3391
|
+
usage: '/audit [recent|export] [--format jsonl|csv] [--limit N] [--days N] [--event NAME] [--tool NAME] [--output FILE]',
|
|
3392
|
+
description: 'Inspect or export local security audit logs (JSONL or CSV)',
|
|
3393
|
+
dialogTitle: 'Audit Log',
|
|
3394
|
+
complete: () => [
|
|
3395
|
+
{ value: 'recent', label: 'recent', description: 'show recent audit log entries' },
|
|
3396
|
+
{ value: 'verify', label: 'verify', description: 'verify tamper-evident SHA-256 audit hash chain' },
|
|
3397
|
+
{ value: 'prune --days 30', label: 'prune --days 30', description: 'delete daily audit logs older than N days' },
|
|
3398
|
+
{ value: 'export --format jsonl', label: 'export --format jsonl', description: 'export audit entries as JSONL' },
|
|
3399
|
+
{ value: 'export --format csv', label: 'export --format csv', description: 'export audit entries as CSV (formula-safe)' },
|
|
3400
|
+
{ value: 'export --format ocsf', label: 'export --format ocsf', description: 'export audit entries as OCSF v1.1.0 SIEM JSONL' }
|
|
3401
|
+
],
|
|
3402
|
+
run: async (argv, ctx = {}) => {
|
|
3403
|
+
let action = '';
|
|
3404
|
+
let formatRaw = 'jsonl';
|
|
3405
|
+
let limitRaw: string | undefined;
|
|
3406
|
+
let daysRaw: string | undefined;
|
|
3407
|
+
let eventFilter: string | undefined;
|
|
3408
|
+
let toolFilter: string | undefined;
|
|
3409
|
+
let outputFile: string | undefined;
|
|
3410
|
+
|
|
3411
|
+
for (let i = 0; i < argv.length; i++) {
|
|
3412
|
+
const token = argv[i] ?? '';
|
|
3413
|
+
if (!token) continue;
|
|
3414
|
+
if (token === '--format' || token === '-f') {
|
|
3415
|
+
formatRaw = argv[++i] ?? '';
|
|
3416
|
+
} else if (token.startsWith('--format=')) {
|
|
3417
|
+
formatRaw = token.slice('--format='.length);
|
|
3418
|
+
} else if (token === '--limit' || token === '-n') {
|
|
3419
|
+
limitRaw = argv[++i];
|
|
3420
|
+
} else if (token.startsWith('--limit=')) {
|
|
3421
|
+
limitRaw = token.slice('--limit='.length);
|
|
3422
|
+
} else if (token === '--days') {
|
|
3423
|
+
daysRaw = argv[++i];
|
|
3424
|
+
} else if (token.startsWith('--days=')) {
|
|
3425
|
+
daysRaw = token.slice('--days='.length);
|
|
3426
|
+
} else if (token === '--event') {
|
|
3427
|
+
eventFilter = argv[++i];
|
|
3428
|
+
} else if (token.startsWith('--event=')) {
|
|
3429
|
+
eventFilter = token.slice('--event='.length);
|
|
3430
|
+
} else if (token === '--tool') {
|
|
3431
|
+
toolFilter = argv[++i];
|
|
3432
|
+
} else if (token.startsWith('--tool=')) {
|
|
3433
|
+
toolFilter = token.slice('--tool='.length);
|
|
3434
|
+
} else if (token === '--output' || token === '-o') {
|
|
3435
|
+
outputFile = argv[++i];
|
|
3436
|
+
} else if (token.startsWith('--output=')) {
|
|
3437
|
+
outputFile = token.slice('--output='.length);
|
|
3438
|
+
} else if (!token.startsWith('-') && !action) {
|
|
3439
|
+
action = token.toLowerCase();
|
|
3440
|
+
} else {
|
|
3441
|
+
return fail(`Unknown audit option "${safeDisplay(token)}".`);
|
|
3442
|
+
}
|
|
3443
|
+
}
|
|
3444
|
+
|
|
3445
|
+
const mode = action || 'recent';
|
|
3446
|
+
if (mode !== 'recent' && mode !== 'export' && mode !== 'verify' && mode !== 'prune') {
|
|
3447
|
+
return fail(`Unknown audit action "${safeDisplay(mode)}". Try: recent, verify, prune, export.`);
|
|
3448
|
+
}
|
|
3449
|
+
|
|
3450
|
+
const fmtLower = formatRaw.trim().toLowerCase();
|
|
3451
|
+
if (fmtLower !== 'jsonl' && fmtLower !== 'csv' && fmtLower !== 'ocsf') {
|
|
3452
|
+
return fail(`Unsupported audit export format "${safeDisplay(formatRaw)}". Use jsonl, csv, or ocsf.`);
|
|
3453
|
+
}
|
|
3454
|
+
const format: AuditExportFormat = fmtLower;
|
|
3455
|
+
|
|
3456
|
+
const parsedLimit = limitRaw !== undefined ? Number.parseInt(limitRaw, 10) : (mode === 'export' ? 1000 : 50);
|
|
3457
|
+
const limit = Number.isFinite(parsedLimit) && parsedLimit > 0 ? Math.min(50_000, parsedLimit) : (mode === 'export' ? 1000 : 50);
|
|
3458
|
+
const parsedDays = daysRaw !== undefined ? Number.parseInt(daysRaw, 10) : undefined;
|
|
3459
|
+
const days = parsedDays !== undefined && Number.isFinite(parsedDays) && parsedDays > 0 ? Math.min(365, parsedDays) : undefined;
|
|
3460
|
+
|
|
3461
|
+
if (mode === 'verify') {
|
|
3462
|
+
const result = auditLog.verifyAuditChain({ days });
|
|
3463
|
+
const summaryLines = [
|
|
3464
|
+
`Audit Chain Verification: ${result.ok ? 'VERIFIED' : 'FAILED'}`,
|
|
3465
|
+
` Files checked : ${result.filesChecked}`,
|
|
3466
|
+
` Entries verified : ${result.entriesVerified}`,
|
|
3467
|
+
...(result.legacyEntries > 0 ? [` Legacy entries : ${result.legacyEntries}`] : [])
|
|
3468
|
+
];
|
|
3469
|
+
if (!result.ok) {
|
|
3470
|
+
summaryLines.push(` Integrity errors : ${result.errors.length}`);
|
|
3471
|
+
for (const err of result.errors.slice(0, 10)) {
|
|
3472
|
+
summaryLines.push(` • ${safeDisplay(err.file)}:${err.line} — ${safeDisplay(err.reason)}`);
|
|
3473
|
+
}
|
|
3474
|
+
return fail(summaryLines.join('\n'));
|
|
3475
|
+
}
|
|
3476
|
+
return ok(summaryLines.join('\n'));
|
|
3477
|
+
}
|
|
3478
|
+
|
|
3479
|
+
if (mode === 'prune') {
|
|
3480
|
+
const retentionDays = days ?? 30;
|
|
3481
|
+
const pruned = auditLog.pruneAuditLogs(retentionDays);
|
|
3482
|
+
return ok(`Pruned ${pruned.deleted.length} audit log file(s) older than ${retentionDays} day(s); kept ${pruned.kept}.`);
|
|
3483
|
+
}
|
|
3484
|
+
|
|
3485
|
+
const entries = auditLog.readAuditLogs({
|
|
3486
|
+
limit,
|
|
3487
|
+
days,
|
|
3488
|
+
event: eventFilter,
|
|
3489
|
+
tool: toolFilter
|
|
3490
|
+
});
|
|
3491
|
+
|
|
3492
|
+
if (mode === 'export') {
|
|
3493
|
+
const payload = formatAuditExport(entries, format);
|
|
3494
|
+
if (outputFile) {
|
|
3495
|
+
if (outputFile.includes('\0')) return fail('Invalid output file path.');
|
|
3496
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3497
|
+
try {
|
|
3498
|
+
const safeOut = await assertSafeWorkspaceOutput(outputFile, { workspaceRoot: ws });
|
|
3499
|
+
if (isCredentialPath(safeOut)) {
|
|
3500
|
+
return fail(`Refusing to overwrite credential or sensitive file: ${safeDisplay(safeOut)}`);
|
|
3501
|
+
}
|
|
3502
|
+
await atomicWriteFileSafe(safeOut, payload, { mode: 0o600 });
|
|
3503
|
+
return ok(`Exported ${entries.length} audit entry(s) (${format}) to ${safeDisplay(safeOut)}`);
|
|
3504
|
+
} catch (err) {
|
|
3505
|
+
return fail(`Could not write audit export: ${safeDisplay(errMsg(err))}`);
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
return ok(payload, { raw: true });
|
|
3509
|
+
}
|
|
3510
|
+
|
|
3511
|
+
if (entries.length === 0) {
|
|
3512
|
+
return ok('No matching audit log entries found.');
|
|
3513
|
+
}
|
|
3514
|
+
const lines = [`Recent Audit Events (${entries.length})`, ''];
|
|
3515
|
+
for (const entry of entries) {
|
|
3516
|
+
const ts = safeDisplay(String(entry.ts || ''));
|
|
3517
|
+
const ev = safeDisplay(String(entry.event || 'event'));
|
|
3518
|
+
const tool = entry.tool ? ` tool=${safeDisplay(String(entry.tool))}` : '';
|
|
3519
|
+
const reason = entry.reason ? ` — ${safeDisplay(String(entry.reason)).slice(0, 120)}` : '';
|
|
3520
|
+
lines.push(` ${ts} [${ev}]${tool}${reason}`);
|
|
3521
|
+
}
|
|
3522
|
+
return ok(lines.join('\n'));
|
|
3523
|
+
}
|
|
3524
|
+
},
|
|
3525
|
+
|
|
3526
|
+
{
|
|
3527
|
+
name: 'lsp',
|
|
3528
|
+
scope: 'local',
|
|
3529
|
+
usage: '/lsp [status|diagnostics <file>|symbols <file>|hover <file> <line> [col]|definition <file> <line> [col]]',
|
|
3530
|
+
description: 'Inspect Language Server Protocol servers or run live semantic code intelligence',
|
|
3531
|
+
dialogTitle: 'LSP Code Intelligence',
|
|
3532
|
+
complete: () => [
|
|
3533
|
+
{ value: 'status', label: 'status', description: 'list installed and active language servers' },
|
|
3534
|
+
{ value: 'diagnostics', label: 'diagnostics <file>', description: 'run live compiler/type diagnostics on a file' },
|
|
3535
|
+
{ value: 'symbols', label: 'symbols <file>', description: 'list semantic symbols in a file' }
|
|
3536
|
+
],
|
|
3537
|
+
run: async (argv, ctx = {}) => {
|
|
3538
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3539
|
+
const sub = (argv[0] || 'status').toLowerCase();
|
|
3540
|
+
if (sub === 'status') {
|
|
3541
|
+
return ok(formatLspStatusReport(ws));
|
|
3542
|
+
}
|
|
3543
|
+
if (sub === 'diagnostics' || sub === 'symbols') {
|
|
3544
|
+
const file = argv[1];
|
|
3545
|
+
if (!file) return fail(`Usage: /lsp ${sub} <file>`);
|
|
3546
|
+
const res = await lspCodeIntel.execute({ action: sub, path: file }, { workspaceRoot: ws });
|
|
3547
|
+
return res.success ? ok(res.output || '') : fail(res.error || 'LSP query failed.');
|
|
3548
|
+
}
|
|
3549
|
+
if (sub === 'definition' || sub === 'references' || sub === 'hover') {
|
|
3550
|
+
const file = argv[1];
|
|
3551
|
+
const line = Number.parseInt(argv[2] || '', 10);
|
|
3552
|
+
const col = Number.parseInt(argv[3] || '1', 10);
|
|
3553
|
+
if (!file || !Number.isFinite(line) || line < 1) {
|
|
3554
|
+
return fail(`Usage: /lsp ${sub} <file> <line> [column]`);
|
|
3555
|
+
}
|
|
3556
|
+
const res = await lspCodeIntel.execute(
|
|
3557
|
+
{ action: sub, path: file, line, column: Number.isFinite(col) && col >= 1 ? col : 1 },
|
|
3558
|
+
{ workspaceRoot: ws }
|
|
3559
|
+
);
|
|
3560
|
+
return res.success ? ok(res.output || '') : fail(res.error || 'LSP query failed.');
|
|
3561
|
+
}
|
|
3562
|
+
return fail(`Unknown lsp action "${safeDisplay(sub)}". Try: status, diagnostics, symbols, definition, references, hover.`);
|
|
3563
|
+
}
|
|
3564
|
+
},
|
|
3565
|
+
|
|
3566
|
+
{
|
|
3567
|
+
name: 'worktree',
|
|
3568
|
+
aliases: ['wt'],
|
|
3569
|
+
scope: 'local',
|
|
3570
|
+
usage: '/worktree [list|create [name]|diff <id>|merge <id> [--squash] [--cleanup]|remove <id>|prune]',
|
|
3571
|
+
description: 'Manage isolated git worktrees for conflict-free parallel work',
|
|
3572
|
+
dialogTitle: 'Git Worktrees',
|
|
3573
|
+
complete: () => [
|
|
3574
|
+
{ value: 'list', label: 'list', description: 'list git worktrees in this repository' },
|
|
3575
|
+
{ value: 'create', label: 'create [name]', description: 'create a new isolated git worktree' },
|
|
3576
|
+
{ value: 'diff', label: 'diff <id>', description: 'inspect diff for a managed worktree' },
|
|
3577
|
+
{ value: 'merge', label: 'merge <id>', description: 'merge a managed worktree cleanly into the current branch' },
|
|
3578
|
+
{ value: 'remove', label: 'remove <id>', description: 'remove a managed worktree and its temporary branch' },
|
|
3579
|
+
{ value: 'prune', label: 'prune', description: 'clean stale worktree metadata' }
|
|
3580
|
+
],
|
|
3581
|
+
run: async (argv, ctx = {}) => {
|
|
3582
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3583
|
+
const sub = (argv[0] || 'list').toLowerCase();
|
|
3584
|
+
try {
|
|
3585
|
+
if (sub === 'list') {
|
|
3586
|
+
const list = listWorktrees(ws);
|
|
3587
|
+
if (list.length === 0) return ok('No Git worktrees found (workspace is not a Git repository).');
|
|
3588
|
+
const lines = [`Git Worktrees (${list.length})`, ''];
|
|
3589
|
+
for (const wt of list) {
|
|
3590
|
+
const badge = wt.managed ? '[causyne]' : '[primary]';
|
|
3591
|
+
lines.push(` • ${wt.id} ${badge} branch=${safeDisplay(wt.branch || '(detached)')}`);
|
|
3592
|
+
lines.push(` ${safeDisplay(wt.path)}`);
|
|
3593
|
+
}
|
|
3594
|
+
return ok(lines.join('\n'));
|
|
3595
|
+
}
|
|
3596
|
+
if (sub === 'create') {
|
|
3597
|
+
const created = createWorktree(ws, { name: argv[1] });
|
|
3598
|
+
return ok(`Created isolated worktree "${created.id}" on branch ${created.branch}\n Path: ${safeDisplay(created.path)}`);
|
|
3599
|
+
}
|
|
3600
|
+
if (sub === 'diff') {
|
|
3601
|
+
const id = argv[1];
|
|
3602
|
+
if (!id) return fail('Usage: /worktree diff <id>');
|
|
3603
|
+
const report = inspectWorktreeDiff(ws, id);
|
|
3604
|
+
const header = `Worktree "${report.id}" (${report.branch || 'detached'}) — ${report.changedFiles.length} changed file(s)`;
|
|
3605
|
+
return ok([header, report.stat, '', report.diff || '(no diff)'].filter(Boolean).join('\n'));
|
|
3606
|
+
}
|
|
3607
|
+
if (sub === 'merge') {
|
|
3608
|
+
const id = argv[1];
|
|
3609
|
+
if (!id) return fail('Usage: /worktree merge <id> [--squash] [--cleanup]');
|
|
3610
|
+
const squash = argv.includes('--squash');
|
|
3611
|
+
const cleanup = argv.includes('--cleanup');
|
|
3612
|
+
const res = mergeWorktree(ws, id, { squash, cleanup });
|
|
3613
|
+
return res.merged ? ok(res.summary) : fail(`${res.summary}${res.error ? `\n${res.error}` : ''}`);
|
|
3614
|
+
}
|
|
3615
|
+
if (sub === 'remove') {
|
|
3616
|
+
const id = argv[1];
|
|
3617
|
+
if (!id) return fail('Usage: /worktree remove <id>');
|
|
3618
|
+
const res = removeWorktree(ws, id, { deleteBranch: !argv.includes('--keep-branch') });
|
|
3619
|
+
return ok(`Removed worktree "${safeDisplay(id)}" (branch deleted: ${res.branchDeleted ? 'yes' : 'no'}).`);
|
|
3620
|
+
}
|
|
3621
|
+
if (sub === 'prune') {
|
|
3622
|
+
const res = pruneManagedWorktrees(ws);
|
|
3623
|
+
return ok(`Pruned ${res.pruned} stale managed worktree directory(s).`);
|
|
3624
|
+
}
|
|
3625
|
+
return fail(`Unknown worktree action "${safeDisplay(sub)}". Try: list, create, diff, merge, remove, prune.`);
|
|
3626
|
+
} catch (err) {
|
|
3627
|
+
return fail(safeDisplay(errMsg(err)));
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
3630
|
+
},
|
|
3631
|
+
|
|
3632
|
+
{
|
|
3633
|
+
name: 'pr',
|
|
3634
|
+
scope: 'local',
|
|
3635
|
+
usage: '/pr [status|draft [baseBranch]|logs [runId]]',
|
|
3636
|
+
description: 'Inspect GitHub Pull Request status, draft diff-grounded PR summaries, or fetch failed CI logs',
|
|
3637
|
+
dialogTitle: 'Pull Request & CI',
|
|
3638
|
+
complete: () => [
|
|
3639
|
+
{ value: 'status', label: 'status', description: 'show branch & PR check status' },
|
|
3640
|
+
{ value: 'draft', label: 'draft [base]', description: 'generate a diff-grounded PR draft' },
|
|
3641
|
+
{ value: 'logs', label: 'logs [runId]', description: 'fetch redacted failure logs from the latest failed CI run' }
|
|
3642
|
+
],
|
|
3643
|
+
run: async (argv, ctx = {}) => {
|
|
3644
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3645
|
+
const sub = (argv[0] || 'status').toLowerCase();
|
|
3646
|
+
try {
|
|
3647
|
+
if (sub === 'status') {
|
|
3648
|
+
return ok(formatPrStatusReport(inspectPrStatus(ws)));
|
|
3649
|
+
}
|
|
3650
|
+
if (sub === 'draft') {
|
|
3651
|
+
const draft = preparePrDraft(ws, argv[1] || 'main');
|
|
3652
|
+
return ok(`Title: ${draft.title}\n\n${draft.body}`);
|
|
3653
|
+
}
|
|
3654
|
+
if (sub === 'logs') {
|
|
3655
|
+
const res = fetchFailedCiLogs(ws, argv[1]);
|
|
3656
|
+
return res.ok ? ok(res.output) : fail(res.output);
|
|
3657
|
+
}
|
|
3658
|
+
return fail(`Unknown pr action "${safeDisplay(sub)}". Try: status, draft, logs.`);
|
|
3659
|
+
} catch (err) {
|
|
3660
|
+
return fail(safeDisplay(errMsg(err)));
|
|
3661
|
+
}
|
|
3662
|
+
}
|
|
3663
|
+
},
|
|
3664
|
+
|
|
3665
|
+
{
|
|
3666
|
+
name: 'rules',
|
|
3667
|
+
scope: 'local',
|
|
3668
|
+
usage: '/rules',
|
|
3669
|
+
description: 'Show hierarchical project instructions loaded from CAUSYNE.md, AGENTS.md, CLAUDE.md, and .causyne/rules/',
|
|
3670
|
+
dialogTitle: 'Project Rules',
|
|
3671
|
+
run: async (_argv, ctx = {}) => {
|
|
3672
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3673
|
+
return ok(formatProjectRulesReport(ws));
|
|
3674
|
+
}
|
|
3675
|
+
},
|
|
3676
|
+
|
|
3677
|
+
{
|
|
3678
|
+
name: 'map',
|
|
3679
|
+
aliases: ['repomap'],
|
|
3680
|
+
scope: 'local',
|
|
3681
|
+
usage: '/map [--chars N] [focusFile...]',
|
|
3682
|
+
description: 'Render a PageRank-ranked repository symbol and dependency architecture map',
|
|
3683
|
+
dialogTitle: 'Repository Map',
|
|
3684
|
+
run: async (argv, ctx = {}) => {
|
|
3685
|
+
const ws = ctx.loop?.workspaceRoot || process.cwd();
|
|
3686
|
+
let maxChars = 6000;
|
|
3687
|
+
const focusFiles: string[] = [];
|
|
3688
|
+
for (let i = 0; i < argv.length; i++) {
|
|
3689
|
+
const tok = argv[i] ?? '';
|
|
3690
|
+
if (tok === '--chars') {
|
|
3691
|
+
const parsed = Number.parseInt(argv[++i] || '6000', 10);
|
|
3692
|
+
if (Number.isFinite(parsed) && parsed >= 400) maxChars = Math.min(48_000, parsed);
|
|
3693
|
+
} else if (tok.startsWith('--chars=')) {
|
|
3694
|
+
const parsed = Number.parseInt(tok.slice('--chars='.length), 10);
|
|
3695
|
+
if (Number.isFinite(parsed) && parsed >= 400) maxChars = Math.min(48_000, parsed);
|
|
3696
|
+
} else if (tok && !tok.startsWith('-')) {
|
|
3697
|
+
focusFiles.push(tok);
|
|
3698
|
+
}
|
|
3699
|
+
}
|
|
3700
|
+
const result = buildRepoMap(ws, { maxChars, focusFiles });
|
|
3701
|
+
return ok(result.rendered);
|
|
3702
|
+
}
|
|
3703
|
+
},
|
|
3704
|
+
|
|
3705
|
+
{
|
|
3706
|
+
name: 'tasks',
|
|
3707
|
+
scope: 'local',
|
|
3708
|
+
usage: '/tasks [list|output <id>|stop <id>]',
|
|
3709
|
+
description: 'Inspect or stop managed OS-sandboxed background tasks',
|
|
3710
|
+
dialogTitle: 'Background Tasks',
|
|
3711
|
+
complete: () => [
|
|
3712
|
+
{ value: 'list', label: 'list', description: 'list managed background tasks' },
|
|
3713
|
+
{ value: 'output', label: 'output <id>', description: 'read buffered output from a task' },
|
|
3714
|
+
{ value: 'stop', label: 'stop <id>', description: 'stop a running background task' }
|
|
3715
|
+
],
|
|
3716
|
+
run: async (argv) => {
|
|
3717
|
+
const sub = (argv[0] || 'list').toLowerCase();
|
|
3718
|
+
if (sub === 'list') {
|
|
3719
|
+
const list = backgroundTaskManager.list();
|
|
3720
|
+
if (list.length === 0) return ok('No managed background tasks recorded.');
|
|
3721
|
+
const lines = [`Background Tasks (${list.length})`, ''];
|
|
3722
|
+
for (const t of list) {
|
|
3723
|
+
lines.push(` • ${t.taskId} [${t.status}] (${t.sandboxBackend}) ${t.label}`);
|
|
3724
|
+
}
|
|
3725
|
+
return ok(lines.join('\n'));
|
|
3726
|
+
}
|
|
3727
|
+
const id = argv[1];
|
|
3728
|
+
if (!id) return fail(`Usage: /tasks ${sub} <taskId>`);
|
|
3729
|
+
try {
|
|
3730
|
+
if (sub === 'output') {
|
|
3731
|
+
const res = backgroundTaskManager.readOutput(id, 0);
|
|
3732
|
+
return ok(res.output || `(no output yet; status=${res.status.status})`);
|
|
3733
|
+
}
|
|
3734
|
+
if (sub === 'stop') {
|
|
3735
|
+
const snap = backgroundTaskManager.stop(id);
|
|
3736
|
+
return ok(`Stopped background task ${snap.taskId} (status=${snap.status}).`);
|
|
3737
|
+
}
|
|
3738
|
+
return fail(`Unknown tasks action "${safeDisplay(sub)}". Try: list, output, stop.`);
|
|
3739
|
+
} catch (err) {
|
|
3740
|
+
return fail(safeDisplay(errMsg(err)));
|
|
3741
|
+
}
|
|
3742
|
+
}
|
|
3743
|
+
},
|
|
3744
|
+
|
|
3745
|
+
{
|
|
3746
|
+
name: 'eval',
|
|
3747
|
+
scope: 'local',
|
|
3748
|
+
usage: '/eval [--json]',
|
|
3749
|
+
description: 'Run the reproducible Causyne coding & governance benchmark suite',
|
|
3750
|
+
dialogTitle: 'Coding Eval Scorecard',
|
|
3751
|
+
run: async (argv) => {
|
|
3752
|
+
const asJson = argv.includes('--json');
|
|
3753
|
+
const scorecard = await runCodingEvalSuite();
|
|
3754
|
+
const output = asJson ? JSON.stringify(scorecard, null, 2) : formatEvalScorecard(scorecard);
|
|
3755
|
+
return scorecard.passedTasks === scorecard.totalTasks
|
|
3756
|
+
? ok(output, asJson ? { raw: true } : {})
|
|
3757
|
+
: fail(output);
|
|
3758
|
+
}
|
|
3759
|
+
},
|
|
3760
|
+
|
|
3761
|
+
{
|
|
3762
|
+
name: 'version',
|
|
3763
|
+
aliases: ['v', 'about'],
|
|
3764
|
+
scope: 'local',
|
|
3765
|
+
usage: '/version',
|
|
3766
|
+
description: 'Display Causyne Agent version and runtime environment',
|
|
3767
|
+
dialogTitle: 'Version',
|
|
3768
|
+
run: async () => {
|
|
3769
|
+
const version = getPackageVersion();
|
|
3770
|
+
const config = loadConfig();
|
|
3771
|
+
return ok([
|
|
3772
|
+
`Causyne Agent v${version}`,
|
|
3773
|
+
` Runtime : Node.js ${process.version} (${process.platform} ${process.arch})`,
|
|
3774
|
+
` Provider : ${config.provider || 'default'}`,
|
|
3775
|
+
` Model : ${config.model || 'default'}`,
|
|
3776
|
+
` License : Business Source License 1.1 (BUSL-1.1)`,
|
|
3777
|
+
` Website : https://causyne.com`
|
|
3778
|
+
].join('\n'));
|
|
3779
|
+
}
|
|
3780
|
+
},
|
|
3781
|
+
|
|
3782
|
+
{
|
|
3783
|
+
name: 'exit',
|
|
3784
|
+
aliases: ['quit'],
|
|
3785
|
+
scope: 'local',
|
|
3786
|
+
usage: '/exit',
|
|
3787
|
+
description: 'Leave the chat',
|
|
3788
|
+
run: () => ok('Goodbye.', { effect: 'exit' })
|
|
3789
|
+
}
|
|
3790
|
+
];
|
|
3791
|
+
|
|
3792
|
+
// ---------------------------------------------------------------------------
|
|
3793
|
+
// Lookup and parsing
|
|
3794
|
+
// ---------------------------------------------------------------------------
|
|
3795
|
+
|
|
3796
|
+
export function resolveCommand(name: unknown): SlashCommandDefinition | null {
|
|
3797
|
+
const normalized = String(name || '').replace(/^\//, '').trim().toLowerCase();
|
|
3798
|
+
if (!normalized) return null;
|
|
3799
|
+
return COMMANDS.find(c => c.name === normalized || (c.aliases || []).includes(normalized)) || null;
|
|
3800
|
+
}
|
|
3801
|
+
|
|
3802
|
+
/** Commands visible on the local terminal surface. */
|
|
3803
|
+
/**
|
|
3804
|
+
* Drop the YAML frontmatter before showing a skill to a human.
|
|
3805
|
+
*
|
|
3806
|
+
* The frontmatter is routing metadata for the agent — `name:` and
|
|
3807
|
+
* `description:` — and printing it verbatim is why an invoked skill looked like
|
|
3808
|
+
* a file dump rather than a procedure.
|
|
3809
|
+
*/
|
|
3810
|
+
function stripFrontmatter(content: unknown): string {
|
|
3811
|
+
const text = String(content == null ? '' : content);
|
|
3812
|
+
let start = -1;
|
|
3813
|
+
if (text.startsWith('---\n')) {
|
|
3814
|
+
start = 4;
|
|
3815
|
+
} else if (text.startsWith('---\r\n')) {
|
|
3816
|
+
start = 5;
|
|
3817
|
+
}
|
|
3818
|
+
if (start === -1) return text;
|
|
3819
|
+
let pos = start;
|
|
3820
|
+
while (pos <= text.length) {
|
|
3821
|
+
const nl = text.indexOf('\n', pos);
|
|
3822
|
+
const lineEnd = nl === -1 ? text.length : nl;
|
|
3823
|
+
const rawLine = text.slice(pos, lineEnd);
|
|
3824
|
+
const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
|
|
3825
|
+
if (line === '---') {
|
|
3826
|
+
let restStart = nl === -1 ? text.length : nl + 1;
|
|
3827
|
+
while (restStart < text.length && (text.charCodeAt(restStart) === 10 || text.charCodeAt(restStart) === 13)) {
|
|
3828
|
+
restStart++;
|
|
3829
|
+
}
|
|
3830
|
+
return text.slice(restStart);
|
|
3831
|
+
}
|
|
3832
|
+
if (nl === -1) break;
|
|
3833
|
+
pos = nl + 1;
|
|
3834
|
+
}
|
|
3835
|
+
return text;
|
|
3836
|
+
}
|
|
3837
|
+
|
|
3838
|
+
export function listCommands(surface = 'terminal'): SlashCommandDefinition[] {
|
|
3839
|
+
return surface === 'terminal' ? COMMANDS.slice() : [];
|
|
3840
|
+
}
|
|
3841
|
+
|
|
3842
|
+
/**
|
|
3843
|
+
* Split a raw input line into a command and its arguments.
|
|
3844
|
+
*
|
|
3845
|
+
* Returns null for anything that is not a slash command, which is the signal to
|
|
3846
|
+
* the caller that this line is a task for the agent. A bare "/" is not a
|
|
3847
|
+
* command, and neither is a path like "/usr/local/bin" — requiring a letter
|
|
3848
|
+
* immediately after the slash keeps absolute paths out of the command namespace.
|
|
3849
|
+
*/
|
|
3850
|
+
/**
|
|
3851
|
+
* Tokenize slash-command arguments in linear O(n) time supporting single quotes,
|
|
3852
|
+
* double quotes, and macOS/POSIX escaped spaces while preserving literal
|
|
3853
|
+
* Windows backslashes before ordinary path characters (e.g. `C:\Users\name`).
|
|
3854
|
+
*/
|
|
3855
|
+
export function tokenizeCommandArgs(input: string): string[] {
|
|
3856
|
+
const tokens: string[] = [];
|
|
3857
|
+
let current = '';
|
|
3858
|
+
let inToken = false;
|
|
3859
|
+
let quote: '"' | "'" | null = null;
|
|
3860
|
+
|
|
3861
|
+
for (let i = 0; i < input.length; i++) {
|
|
3862
|
+
const ch = input[i]!;
|
|
3863
|
+
if (quote === "'") {
|
|
3864
|
+
if (ch === "'") {
|
|
3865
|
+
quote = null;
|
|
3866
|
+
} else {
|
|
3867
|
+
current += ch;
|
|
3868
|
+
}
|
|
3869
|
+
continue;
|
|
3870
|
+
}
|
|
3871
|
+
|
|
3872
|
+
if (quote === '"') {
|
|
3873
|
+
if (ch === '"') {
|
|
3874
|
+
quote = null;
|
|
3875
|
+
} else if (ch === '\\' && i + 1 < input.length) {
|
|
3876
|
+
const next = input[i + 1]!;
|
|
3877
|
+
if (next === '"' || next === '\\') {
|
|
3878
|
+
current += next;
|
|
3879
|
+
i++;
|
|
3880
|
+
} else {
|
|
3881
|
+
current += ch;
|
|
3882
|
+
}
|
|
3883
|
+
} else {
|
|
3884
|
+
current += ch;
|
|
3885
|
+
}
|
|
3886
|
+
continue;
|
|
3887
|
+
}
|
|
3888
|
+
|
|
3889
|
+
if (ch === '"' || ch === "'") {
|
|
3890
|
+
quote = ch;
|
|
3891
|
+
inToken = true;
|
|
3892
|
+
continue;
|
|
3893
|
+
}
|
|
3894
|
+
|
|
3895
|
+
if (ch === '\\' && i + 1 < input.length) {
|
|
3896
|
+
const next = input[i + 1]!;
|
|
3897
|
+
if (next === ' ' || next === '\t' || next === '"' || next === "'") {
|
|
3898
|
+
current += next;
|
|
3899
|
+
inToken = true;
|
|
3900
|
+
i++;
|
|
3901
|
+
continue;
|
|
3902
|
+
}
|
|
3903
|
+
}
|
|
3904
|
+
|
|
3905
|
+
if (/\s/.test(ch)) {
|
|
3906
|
+
if (inToken) {
|
|
3907
|
+
tokens.push(current);
|
|
3908
|
+
current = '';
|
|
3909
|
+
inToken = false;
|
|
3910
|
+
}
|
|
3911
|
+
continue;
|
|
3912
|
+
}
|
|
3913
|
+
|
|
3914
|
+
current += ch;
|
|
3915
|
+
inToken = true;
|
|
3916
|
+
}
|
|
3917
|
+
|
|
3918
|
+
if (inToken) {
|
|
3919
|
+
tokens.push(current);
|
|
3920
|
+
}
|
|
3921
|
+
return tokens;
|
|
3922
|
+
}
|
|
3923
|
+
|
|
3924
|
+
export function parseCommand(input: unknown): ParsedCommand | null {
|
|
3925
|
+
if (typeof input !== 'string' || input.length > 65_536 || input.includes('\0')) return null;
|
|
3926
|
+
const trimmed = input.trim();
|
|
3927
|
+
if (!trimmed.startsWith('/')) return null;
|
|
3928
|
+
|
|
3929
|
+
const parts = tokenizeCommandArgs(trimmed.slice(1));
|
|
3930
|
+
const name = (parts.shift() || '').toLowerCase();
|
|
3931
|
+
|
|
3932
|
+
// The name must be a single bare word. Requiring that is what keeps absolute
|
|
3933
|
+
// paths out of the command namespace: "/usr/local/bin" has a slash in its
|
|
3934
|
+
// first token, so it is a task for the agent, not a command named
|
|
3935
|
+
// "usr/local/bin". Anchored, not a loose prefix test — see rules.json ZM-09
|
|
3936
|
+
// on why guards must be context-aware.
|
|
3937
|
+
if (!/^[a-z?][a-z0-9_-]*$/.test(name)) return null;
|
|
3938
|
+
|
|
3939
|
+
return { name, argv: parts, raw: trimmed };
|
|
3940
|
+
}
|
|
3941
|
+
|
|
3942
|
+
export function isCommandInput(input: unknown): boolean {
|
|
3943
|
+
return parseCommand(input) !== null;
|
|
3944
|
+
}
|
|
3945
|
+
|
|
3946
|
+
/**
|
|
3947
|
+
* Execute a parsed command.
|
|
3948
|
+
*
|
|
3949
|
+
* Never throws: a command that fails reports it as output, because both surfaces
|
|
3950
|
+
* render the result into a conversation rather than a stack trace.
|
|
3951
|
+
*/
|
|
3952
|
+
export async function runCommand(
|
|
3953
|
+
name: string,
|
|
3954
|
+
argv?: string[] | null,
|
|
3955
|
+
ctx?: CommandContext | null
|
|
3956
|
+
): Promise<CommandResult> {
|
|
3957
|
+
const safeCtx: CommandContext = ctx && typeof ctx === 'object' ? ctx : {};
|
|
3958
|
+
const safeArgv: string[] = Array.isArray(argv) ? argv.map(a => String(a ?? '')) : [];
|
|
3959
|
+
const surface = safeCtx.surface || 'terminal';
|
|
3960
|
+
const command = resolveCommand(name);
|
|
3961
|
+
|
|
3962
|
+
if (!command) {
|
|
3963
|
+
return fail(`Unknown command "/${safeDisplay(name)}". Try /help.`);
|
|
3964
|
+
}
|
|
3965
|
+
if (surface !== 'terminal') {
|
|
3966
|
+
return fail(`"/${command.name}" is not available on this surface.`);
|
|
3967
|
+
}
|
|
3968
|
+
|
|
3969
|
+
try {
|
|
3970
|
+
const result = await command.run(safeArgv, { ...safeCtx, surface });
|
|
3971
|
+
if (command.dialogTitle && result && !result.effect) {
|
|
3972
|
+
return { ...result, effect: 'dialog', title: command.dialogTitle };
|
|
3973
|
+
}
|
|
3974
|
+
return result;
|
|
3975
|
+
} catch (e) {
|
|
3976
|
+
return fail(`/${command.name} failed: ${safeDisplay(redactProviderSecrets(errMsg(e)))}`);
|
|
3977
|
+
}
|
|
3978
|
+
}
|
|
3979
|
+
|
|
3980
|
+
/** Convenience for a surface holding a raw line. Returns null if not a command. */
|
|
3981
|
+
export async function handleInput(input: unknown, ctx: CommandContext = {}): Promise<CommandResult | null> {
|
|
3982
|
+
const parsed = parseCommand(input);
|
|
3983
|
+
if (!parsed) return null;
|
|
3984
|
+
return runCommand(parsed.name, parsed.argv, ctx);
|
|
3985
|
+
}
|