@causyne/agent 1.20.122 → 1.20.127
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/causyne.js +38 -15
- package/docs/SECURITY_REVIEW.md +42 -6
- package/package.json +7 -7
- 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 +181 -4
- package/src/acp/server.js +418 -45
- package/src/acp/server.ts +404 -47
- package/src/agent/abortableDelay.js +2 -2
- package/src/agent/abortableDelay.ts +2 -2
- package/src/agent/errorClassifier.js +51 -7
- package/src/agent/errorClassifier.ts +52 -6
- 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 +673 -236
- package/src/agentLoop.ts +705 -233
- package/src/approvalPolicy.js +61 -10
- package/src/approvalPolicy.ts +69 -11
- 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 +914 -13
- package/src/browser/causyneBrowser.ts +1075 -35
- package/src/browser/searchProviders.js +94 -6
- package/src/browser/searchProviders.ts +89 -6
- package/src/browser/urlPolicy.js +22 -2
- package/src/browser/urlPolicy.ts +19 -2
- 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 +718 -754
- package/src/cliMode.ts +792 -0
- package/src/codebase/repoMap.js +656 -0
- package/src/codebase/repoMap.ts +664 -0
- package/src/commands.js +3806 -2513
- package/src/commands.ts +4162 -0
- package/src/compiledSkills.js +8052 -8054
- package/src/compiledSkills.ts +8078 -0
- package/src/config.js +118 -1
- package/src/config.ts +124 -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 +142 -14
- package/src/core/contextCompactor.ts +150 -15
- package/src/core/goalLoop.js +257 -0
- package/src/core/goalLoop.ts +310 -0
- 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 +646 -268
- package/src/entrypoint.ts +740 -0
- package/src/game/causyneCoreBridge.js +686 -0
- package/src/game/causyneCoreBridge.ts +702 -0
- package/src/game/gameLauncher.js +287 -0
- package/src/game/gameLauncher.ts +352 -0
- package/src/game/gameProvisioner.js +425 -0
- package/src/game/gameProvisioner.ts +488 -0
- package/src/gitSnapshot.js +417 -312
- package/src/gitSnapshot.ts +500 -0
- package/src/headlessCli.js +343 -25
- package/src/headlessCli.ts +343 -20
- 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 +127 -18
- package/src/infra/atomicWriter.ts +141 -20
- package/src/launchIntent.js +85 -4
- package/src/launchIntent.ts +88 -4
- 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 +770 -0
- package/src/lsp/lspClient.ts +862 -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 +255 -15
- package/src/mcp/mcpRegistry.ts +241 -14
- package/src/mcp/mcpSecurity.js +6 -7
- package/src/mcp/mcpSecurity.ts +7 -6
- package/src/memory/contextBudget.js +2 -0
- package/src/memory/contextBudget.ts +1 -0
- 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 +645 -0
- package/src/modelVariants.ts +717 -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/outputRecovery.js +3 -2
- package/src/outputRecovery.ts +4 -2
- package/src/outputStore.js +210 -156
- package/src/outputStore.ts +321 -0
- package/src/permissionPresets.js +327 -0
- package/src/permissionPresets.ts +361 -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 +620 -356
- package/src/providers/antigravity.ts +621 -357
- package/src/providers/base.js +9 -2
- package/src/providers/base.ts +10 -2
- package/src/providers/byokHttp.js +134 -18
- package/src/providers/byokHttp.ts +181 -19
- package/src/providers/byokStream.js +183 -44
- package/src/providers/byokStream.ts +179 -62
- package/src/providers/dashscope-byok.js +50 -8
- package/src/providers/dashscope-byok.ts +59 -13
- 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 +60 -8
- package/src/providers/moonshot.ts +64 -14
- package/src/providers/muse.js +6 -0
- package/src/providers/muse.ts +8 -0
- package/src/providers/ollama.js +299 -21
- package/src/providers/ollama.ts +331 -29
- package/src/providers/openai-compatible.js +81 -12
- package/src/providers/openai-compatible.ts +89 -18
- package/src/providers/openai.js +87 -6
- package/src/providers/openai.ts +74 -6
- package/src/providers/openrouter.js +248 -66
- package/src/providers/openrouter.ts +243 -70
- package/src/providers/qwen-byok.js +50 -8
- package/src/providers/qwen-byok.ts +59 -13
- package/src/providers/wireNormalizer.js +66 -0
- package/src/providers/wireNormalizer.ts +64 -0
- package/src/providers/xai.js +31 -8
- package/src/providers/xai.ts +38 -14
- 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 +330 -326
- package/src/reporting.ts +484 -0
- package/src/sandbox.js +71 -0
- package/src/sandbox.ts +81 -0
- package/src/scheduler/scheduler.js +372 -0
- package/src/scheduler/scheduler.ts +433 -0
- package/src/sessionJournal.js +24 -3
- package/src/sessionJournal.ts +18 -3
- package/src/sessionSearchIndex.js +267 -0
- package/src/sessionSearchIndex.ts +311 -0
- package/src/sessionStore.js +1 -2
- package/src/sessionStore.ts +2 -0
- package/src/skillsManager.js +2 -3
- package/src/skillsManager.ts +2 -3
- 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 +11 -0
- package/src/toolPacks.ts +11 -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 +57 -15
- package/src/tools/generateMediaViaApi.ts +56 -15
- 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/nativeEngine.js +2 -2
- package/src/tools/nativeEngine.ts +2 -2
- package/src/tools/openSourceToolProvisioner.js +2 -2
- package/src/tools/openSourceToolProvisioner.ts +2 -2
- 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/payloadSanitizer.js +0 -1
- package/src/tools/payloadSanitizer.ts +0 -1
- package/src/tools/pdfReader.js +197 -104
- package/src/tools/pdfReader.ts +216 -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/presentDeliverable.js +103 -0
- package/src/tools/presentDeliverable.ts +127 -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/ptcRuntime.js +444 -0
- package/src/tools/ptcRuntime.ts +490 -0
- package/src/tools/ptyTerminal.js +1096 -0
- package/src/tools/ptyTerminal.ts +1231 -0
- package/src/tools/registry.js +308 -287
- package/src/tools/registry.ts +495 -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/toolOutputStore.js +26 -4
- package/src/tools/toolOutputStore.ts +22 -4
- 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 +163 -13
- package/src/tools/webFetch.ts +150 -13
- package/src/tools/webSearch.js +123 -36
- package/src/tools/webSearch.ts +124 -33
- package/src/toolsList.js +5 -0
- package/src/toolsList.ts +5 -0
- package/src/tui/ask.js +159 -168
- package/src/tui/ask.ts +259 -0
- package/src/tui/banner.js +5 -1
- package/src/tui/banner.ts +6 -1
- package/src/tui/block.js +0 -1
- package/src/tui/block.ts +0 -1
- package/src/tui/chatRenderer.js +1194 -1443
- package/src/tui/chatRenderer.ts +1335 -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 +396 -371
- package/src/tui/completion.ts +575 -0
- package/src/tui/composerControls.js +212 -34
- package/src/tui/composerControls.ts +235 -34
- package/src/tui/consoleGuard.js +27 -7
- package/src/tui/consoleGuard.ts +29 -7
- package/src/tui/dialogs.js +867 -733
- package/src/tui/dialogs.ts +971 -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 +166 -161
- package/src/tui/home.ts +252 -0
- package/src/tui/invocation.js +59 -67
- package/src/tui/invocation.ts +116 -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 +22 -15
- package/src/tui/modelPicker.ts +25 -18
- package/src/tui/observerPicker.js +0 -2
- package/src/tui/observerPicker.ts +0 -2
- package/src/tui/overlay.js +2 -6
- package/src/tui/overlay.ts +2 -6
- package/src/tui/prompt.js +1818 -2151
- package/src/tui/prompt.ts +1872 -0
- package/src/tui/runningLight.js +0 -1
- package/src/tui/runningLight.ts +0 -1
- package/src/tui/selectList.js +369 -349
- package/src/tui/selectList.ts +433 -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 +39 -14
- package/src/tui/setup.ts +45 -14
- 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 +9 -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/client/browserPanel.js +702 -0
- package/src/web/client/browserPanel.ts +663 -0
- package/src/web/client/chatStream.js +309 -0
- package/src/web/client/chatStream.ts +289 -0
- package/src/web/client/cliPanel.js +165 -0
- package/src/web/client/cliPanel.ts +171 -0
- package/src/web/client/composer.js +204 -0
- package/src/web/client/composer.ts +209 -0
- package/src/web/client/diffPanel.js +176 -0
- package/src/web/client/diffPanel.ts +203 -0
- package/src/web/client/dom.js +220 -0
- package/src/web/client/dom.ts +221 -0
- package/src/web/client/filesAndCanvas.js +231 -0
- package/src/web/client/filesAndCanvas.ts +238 -0
- package/src/web/client/gameLauncherUi.js +78 -0
- package/src/web/client/gameLauncherUi.ts +78 -0
- package/src/web/client/main.js +301 -0
- package/src/web/client/main.ts +368 -0
- package/src/web/client/markdown.js +364 -0
- package/src/web/client/markdown.ts +373 -0
- package/src/web/client/modelPicker.js +455 -0
- package/src/web/client/modelPicker.ts +451 -0
- package/src/web/client/permissionPresetsUi.js +307 -0
- package/src/web/client/permissionPresetsUi.ts +333 -0
- package/src/web/client/sessions.js +353 -0
- package/src/web/client/sessions.ts +372 -0
- package/src/web/client/settingsModal.js +191 -0
- package/src/web/client/settingsModal.ts +176 -0
- package/src/web/client/state.js +250 -0
- package/src/web/client/state.ts +233 -0
- package/src/web/client/streamSmoother.js +127 -0
- package/src/web/client/streamSmoother.ts +119 -0
- package/src/web/client/studioLayout.js +54 -0
- package/src/web/client/studioLayout.ts +60 -0
- package/src/web/client/studioShell.js +327 -0
- package/src/web/client/studioShell.ts +340 -0
- package/src/web/client/studioStart.js +77 -0
- package/src/web/client/studioStart.ts +89 -0
- package/src/web/client/terminalPanel.js +357 -0
- package/src/web/client/terminalPanel.ts +345 -0
- package/src/web/client/turnView.js +934 -0
- package/src/web/client/turnView.ts +981 -0
- package/src/web/client/types.js +1 -0
- package/src/web/client/types.ts +319 -0
- package/src/web/client/validators.js +106 -0
- package/src/web/client/validators.ts +96 -0
- package/src/web/guiLauncher.js +89 -0
- package/src/web/guiLauncher.ts +119 -0
- package/src/web/server/activeRuns.js +152 -0
- package/src/web/server/activeRuns.ts +171 -0
- package/src/web/server/routesBrowser.js +355 -0
- package/src/web/server/routesBrowser.ts +386 -0
- package/src/web/server/routesChat.js +304 -0
- package/src/web/server/routesChat.ts +347 -0
- package/src/web/server/routesCore.js +472 -0
- package/src/web/server/routesCore.ts +522 -0
- package/src/web/server/routesTerminal.js +162 -0
- package/src/web/server/routesTerminal.ts +182 -0
- package/src/web/server/routesWorkspace.js +510 -0
- package/src/web/server/routesWorkspace.ts +546 -0
- package/src/web/server/security.js +98 -0
- package/src/web/server/security.ts +108 -0
- package/src/web/server/sessionTranscript.js +586 -0
- package/src/web/server/sessionTranscript.ts +566 -0
- package/src/web/server/staticAssets.js +80 -0
- package/src/web/server/staticAssets.ts +91 -0
- package/src/web/server/types.js +1 -0
- package/src/web/server/types.ts +135 -0
- package/src/web/server/workspaceFiles.js +368 -0
- package/src/web/server/workspaceFiles.ts +363 -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/skybridgeServer.js +249 -0
- package/src/web/skybridgeServer.ts +305 -0
- package/src/web/skybridgeUi.js +38 -0
- package/src/web/skybridgeUi.ts +47 -0
- package/src/web/styles/agent.css +380 -0
- package/src/web/styles/composer.css +193 -0
- package/src/web/styles/overlays.css +436 -0
- package/src/web/styles/shell.css +387 -0
- package/src/web/styles/studio.css +723 -0
- package/src/web/styles/thread.css +221 -0
- package/src/web/styles/tokens.css +94 -0
- package/src/web/ui/brandMark.js +73 -0
- package/src/web/ui/brandMark.ts +82 -0
- package/src/web/ui/modalsTemplate.js +139 -0
- package/src/web/ui/modalsTemplate.ts +139 -0
- package/src/web/ui/sidebarTemplate.js +63 -0
- package/src/web/ui/sidebarTemplate.ts +64 -0
- package/src/web/ui/studioTemplate.js +258 -0
- package/src/web/ui/studioTemplate.ts +258 -0
- package/src/web/ui/workspaceTemplate.js +72 -0
- package/src/web/ui/workspaceTemplate.ts +73 -0
- package/src/worktreeManager.js +526 -0
- package/src/worktreeManager.ts +567 -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
|
@@ -0,0 +1,1231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — Interactive Workspace PTY Terminal Manager & Tool
|
|
3
|
+
*
|
|
4
|
+
* Zero-dependency, OS-sandboxed interactive pseudo-terminal manager supporting:
|
|
5
|
+
* - Real POSIX PTY sessions via Python `pty.fork()` + `TIOCSWINSZ` (zero native
|
|
6
|
+
* `postinstall` binary requirement) with transparent fallback to piped shell.
|
|
7
|
+
* - Regex-free character-scanning ANSI/CSI/OSC stream sanitizer (immune to ReDoS)
|
|
8
|
+
* plus OSC 133;D prompt-completion marker detection.
|
|
9
|
+
* - Bounded scrollback ring buffer, live NDJSON subscribers for Skybridge Studio,
|
|
10
|
+
* atomic `agent -> user` takeover semantics, and foreground process-group signaling.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { spawn, spawnSync, execFile, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
14
|
+
import crypto from 'node:crypto';
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import { getEnhancedEnv } from './sysRun.js';
|
|
17
|
+
import { redactTextSecrets } from '../providers/byokHttp.js';
|
|
18
|
+
import {
|
|
19
|
+
resolveOsSandboxMode,
|
|
20
|
+
wrapCommandWithOsSandbox,
|
|
21
|
+
type OsSandboxWrapOptions
|
|
22
|
+
} from './osSandbox.js';
|
|
23
|
+
import {
|
|
24
|
+
boundedInteger,
|
|
25
|
+
getErrorMessage,
|
|
26
|
+
resolveScopedPath,
|
|
27
|
+
resolveToolWorkspaceRoots,
|
|
28
|
+
sanitizeToolError,
|
|
29
|
+
type ToolWorkspaceContext
|
|
30
|
+
} from './toolPathSafety.js';
|
|
31
|
+
|
|
32
|
+
export type TerminalWaitReason = 'stdin_read' | 'inferred_idle' | 'timeout' | 'session_exit';
|
|
33
|
+
export type TerminalControlOwner = 'user' | 'agent';
|
|
34
|
+
export type TerminalOrigin = 'user' | 'agent';
|
|
35
|
+
export type TerminalSignalName = 'SIGINT' | 'SIGTERM' | 'SIGTSTP' | 'SIGHUP' | 'SIGKILL';
|
|
36
|
+
|
|
37
|
+
export interface TerminalSessionSummary {
|
|
38
|
+
id: string;
|
|
39
|
+
name: string;
|
|
40
|
+
shell: string;
|
|
41
|
+
shellLabel: string;
|
|
42
|
+
cwd: string;
|
|
43
|
+
workspaceRoot: string;
|
|
44
|
+
origin: TerminalOrigin;
|
|
45
|
+
control: TerminalControlOwner;
|
|
46
|
+
transport: 'pty' | 'pipe';
|
|
47
|
+
status: 'running' | 'exited';
|
|
48
|
+
exitCode: number | null;
|
|
49
|
+
cols: number;
|
|
50
|
+
rows: number;
|
|
51
|
+
createdAt: number;
|
|
52
|
+
lastActivityAt: number;
|
|
53
|
+
scrollbackBytes: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface TerminalStreamEvent {
|
|
57
|
+
type: 'snapshot' | 'output' | 'control' | 'exit' | 'meta';
|
|
58
|
+
sessionId: string;
|
|
59
|
+
data?: string | undefined;
|
|
60
|
+
control?: TerminalControlOwner | undefined;
|
|
61
|
+
status?: 'running' | 'exited' | undefined;
|
|
62
|
+
exitCode?: number | null | undefined;
|
|
63
|
+
cols?: number | undefined;
|
|
64
|
+
rows?: number | undefined;
|
|
65
|
+
ts: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface AvailableShellInfo {
|
|
69
|
+
id: string;
|
|
70
|
+
label: string;
|
|
71
|
+
path: string;
|
|
72
|
+
isDefault: boolean;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const MAX_PTY_SESSIONS = 10;
|
|
76
|
+
const MAX_SCROLLBACK_CHARS = 256 * 1024;
|
|
77
|
+
const ALLOWED_SIGNALS = new Set<TerminalSignalName>(['SIGINT', 'SIGTERM', 'SIGTSTP', 'SIGHUP', 'SIGKILL']);
|
|
78
|
+
const ALLOWED_POSIX_SHELLS: ReadonlyArray<{ id: string; label: string; path: string }> = [
|
|
79
|
+
{ id: 'zsh', label: 'zsh', path: '/bin/zsh' },
|
|
80
|
+
{ id: 'bash', label: 'bash', path: '/bin/bash' },
|
|
81
|
+
{ id: 'sh', label: 'sh', path: '/bin/sh' },
|
|
82
|
+
{ id: 'usr-zsh', label: 'zsh', path: '/usr/bin/zsh' },
|
|
83
|
+
{ id: 'usr-bash', label: 'bash', path: '/usr/bin/bash' },
|
|
84
|
+
{ id: 'local-zsh', label: 'zsh', path: '/usr/local/bin/zsh' },
|
|
85
|
+
{ id: 'local-bash', label: 'bash', path: '/usr/local/bin/bash' },
|
|
86
|
+
{ id: 'opt-zsh', label: 'zsh', path: '/opt/homebrew/bin/zsh' },
|
|
87
|
+
{ id: 'opt-bash', label: 'bash', path: '/opt/homebrew/bin/bash' }
|
|
88
|
+
];
|
|
89
|
+
const ALLOWED_POSIX_SHELL_PATH_SET = new Set(ALLOWED_POSIX_SHELLS.map((s) => s.path));
|
|
90
|
+
|
|
91
|
+
const PYTHON_PTY_HELPER = `
|
|
92
|
+
import base64, errno, fcntl, json, os, pty, select, signal, struct, subprocess, sys, termios
|
|
93
|
+
|
|
94
|
+
shell = sys.argv[1]
|
|
95
|
+
cols = max(20, min(400, int(sys.argv[2])))
|
|
96
|
+
rows = max(6, min(160, int(sys.argv[3])))
|
|
97
|
+
|
|
98
|
+
def emit(obj):
|
|
99
|
+
sys.stdout.write(json.dumps(obj, separators=(',', ':')) + '\\n')
|
|
100
|
+
sys.stdout.flush()
|
|
101
|
+
|
|
102
|
+
use_pty = True
|
|
103
|
+
proc = None
|
|
104
|
+
pid = None
|
|
105
|
+
master_fd = None
|
|
106
|
+
pipe_in_fd = None
|
|
107
|
+
pipe_out_fd = None
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
pid, master_fd = pty.fork()
|
|
111
|
+
if pid == 0:
|
|
112
|
+
try:
|
|
113
|
+
os.execv(shell, [shell, '-i'])
|
|
114
|
+
except Exception:
|
|
115
|
+
try:
|
|
116
|
+
os.execv(shell, [shell])
|
|
117
|
+
except Exception:
|
|
118
|
+
os._exit(127)
|
|
119
|
+
except OSError:
|
|
120
|
+
use_pty = False
|
|
121
|
+
proc = subprocess.Popen(
|
|
122
|
+
[shell],
|
|
123
|
+
stdin=subprocess.PIPE,
|
|
124
|
+
stdout=subprocess.PIPE,
|
|
125
|
+
stderr=subprocess.STDOUT,
|
|
126
|
+
start_new_session=True,
|
|
127
|
+
)
|
|
128
|
+
pid = proc.pid
|
|
129
|
+
pipe_in_fd = proc.stdin.fileno()
|
|
130
|
+
pipe_out_fd = proc.stdout.fileno()
|
|
131
|
+
|
|
132
|
+
def set_size(r, c):
|
|
133
|
+
if not use_pty or master_fd is None:
|
|
134
|
+
return
|
|
135
|
+
try:
|
|
136
|
+
fcntl.ioctl(master_fd, termios.TIOCSWINSZ, struct.pack('HHHH', r, c, 0, 0))
|
|
137
|
+
try:
|
|
138
|
+
os.killpg(pid, signal.SIGWINCH)
|
|
139
|
+
except Exception:
|
|
140
|
+
pass
|
|
141
|
+
except Exception:
|
|
142
|
+
pass
|
|
143
|
+
|
|
144
|
+
read_fd = master_fd if use_pty else pipe_out_fd
|
|
145
|
+
write_fd = master_fd if use_pty else pipe_in_fd
|
|
146
|
+
|
|
147
|
+
set_size(rows, cols)
|
|
148
|
+
os.set_blocking(read_fd, False)
|
|
149
|
+
emit({'t': 'ready', 'pid': pid, 'mode': 'pty' if use_pty else 'pipe'})
|
|
150
|
+
|
|
151
|
+
stdin_fd = sys.stdin.fileno()
|
|
152
|
+
os.set_blocking(stdin_fd, False)
|
|
153
|
+
cmd_buf = b''
|
|
154
|
+
stdin_open = True
|
|
155
|
+
exit_code = None
|
|
156
|
+
|
|
157
|
+
sig_map = {
|
|
158
|
+
'SIGINT': signal.SIGINT,
|
|
159
|
+
'SIGTERM': signal.SIGTERM,
|
|
160
|
+
'SIGTSTP': signal.SIGTSTP,
|
|
161
|
+
'SIGHUP': signal.SIGHUP,
|
|
162
|
+
'SIGKILL': signal.SIGKILL,
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
def drain_out():
|
|
166
|
+
while True:
|
|
167
|
+
try:
|
|
168
|
+
chunk = os.read(read_fd, 16384)
|
|
169
|
+
if not chunk:
|
|
170
|
+
return False
|
|
171
|
+
emit({'t': 'out', 'b': base64.b64encode(chunk).decode('ascii')})
|
|
172
|
+
except BlockingIOError:
|
|
173
|
+
return True
|
|
174
|
+
except OSError as e:
|
|
175
|
+
if e.errno in (errno.EIO, errno.EBADF):
|
|
176
|
+
return False
|
|
177
|
+
return True
|
|
178
|
+
|
|
179
|
+
while True:
|
|
180
|
+
rlist = [read_fd]
|
|
181
|
+
if stdin_open:
|
|
182
|
+
rlist.append(stdin_fd)
|
|
183
|
+
try:
|
|
184
|
+
ready, _, _ = select.select(rlist, [], [], 0.2)
|
|
185
|
+
except (InterruptedError, ValueError):
|
|
186
|
+
ready = []
|
|
187
|
+
if read_fd in ready:
|
|
188
|
+
if not drain_out():
|
|
189
|
+
break
|
|
190
|
+
if stdin_fd in ready:
|
|
191
|
+
try:
|
|
192
|
+
raw = os.read(stdin_fd, 16384)
|
|
193
|
+
if not raw:
|
|
194
|
+
stdin_open = False
|
|
195
|
+
try:
|
|
196
|
+
os.killpg(pid, signal.SIGHUP)
|
|
197
|
+
except Exception:
|
|
198
|
+
pass
|
|
199
|
+
break
|
|
200
|
+
cmd_buf += raw
|
|
201
|
+
while b'\\n' in cmd_buf:
|
|
202
|
+
line, cmd_buf = cmd_buf.split(b'\\n', 1)
|
|
203
|
+
if not line:
|
|
204
|
+
continue
|
|
205
|
+
try:
|
|
206
|
+
msg = json.loads(line.decode('utf-8', 'replace'))
|
|
207
|
+
except Exception:
|
|
208
|
+
continue
|
|
209
|
+
kind = msg.get('t')
|
|
210
|
+
if kind == 'in':
|
|
211
|
+
data = base64.b64decode(msg.get('b', ''))
|
|
212
|
+
if data:
|
|
213
|
+
try:
|
|
214
|
+
os.write(write_fd, data)
|
|
215
|
+
except OSError:
|
|
216
|
+
pass
|
|
217
|
+
elif kind == 'resize':
|
|
218
|
+
r = max(6, min(160, int(msg.get('rows', rows))))
|
|
219
|
+
c = max(20, min(400, int(msg.get('cols', cols))))
|
|
220
|
+
rows, cols = r, c
|
|
221
|
+
set_size(rows, cols)
|
|
222
|
+
elif kind == 'sig':
|
|
223
|
+
sname = msg.get('s')
|
|
224
|
+
sig = sig_map.get(sname)
|
|
225
|
+
if sig is not None:
|
|
226
|
+
try:
|
|
227
|
+
if use_pty and master_fd is not None:
|
|
228
|
+
fg = os.tcgetpgrp(master_fd)
|
|
229
|
+
os.killpg(fg if fg > 0 else pid, sig)
|
|
230
|
+
else:
|
|
231
|
+
os.killpg(pid, sig)
|
|
232
|
+
except Exception:
|
|
233
|
+
try:
|
|
234
|
+
os.killpg(pid, sig)
|
|
235
|
+
except Exception:
|
|
236
|
+
pass
|
|
237
|
+
elif kind == 'close':
|
|
238
|
+
try:
|
|
239
|
+
os.killpg(pid, signal.SIGTERM)
|
|
240
|
+
except Exception:
|
|
241
|
+
pass
|
|
242
|
+
stdin_open = False
|
|
243
|
+
break
|
|
244
|
+
except BlockingIOError:
|
|
245
|
+
pass
|
|
246
|
+
except OSError:
|
|
247
|
+
stdin_open = False
|
|
248
|
+
break
|
|
249
|
+
if use_pty:
|
|
250
|
+
try:
|
|
251
|
+
wpid, status = os.waitpid(pid, os.WNOHANG)
|
|
252
|
+
if wpid == pid:
|
|
253
|
+
drain_out()
|
|
254
|
+
if os.WIFEXITED(status):
|
|
255
|
+
exit_code = os.WEXITSTATUS(status)
|
|
256
|
+
elif os.WIFSIGNALED(status):
|
|
257
|
+
exit_code = 128 + os.WTERMSIG(status)
|
|
258
|
+
else:
|
|
259
|
+
exit_code = 0
|
|
260
|
+
break
|
|
261
|
+
except ChildProcessError:
|
|
262
|
+
exit_code = 0
|
|
263
|
+
break
|
|
264
|
+
else:
|
|
265
|
+
rc = proc.poll()
|
|
266
|
+
if rc is not None:
|
|
267
|
+
drain_out()
|
|
268
|
+
exit_code = rc
|
|
269
|
+
break
|
|
270
|
+
|
|
271
|
+
if use_pty and master_fd is not None:
|
|
272
|
+
try:
|
|
273
|
+
os.close(master_fd)
|
|
274
|
+
except Exception:
|
|
275
|
+
pass
|
|
276
|
+
elif proc is not None:
|
|
277
|
+
try:
|
|
278
|
+
proc.stdin.close()
|
|
279
|
+
except Exception:
|
|
280
|
+
pass
|
|
281
|
+
try:
|
|
282
|
+
proc.stdout.close()
|
|
283
|
+
except Exception:
|
|
284
|
+
pass
|
|
285
|
+
|
|
286
|
+
if exit_code is None:
|
|
287
|
+
exit_code = 0
|
|
288
|
+
|
|
289
|
+
emit({'t': 'exit', 'code': exit_code})
|
|
290
|
+
`;
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Pure character-scanning terminal escape sanitizer (zero regular expressions).
|
|
294
|
+
* Strips CSI, OSC, DCS, and C1 control sequences across arbitrary chunk boundaries,
|
|
295
|
+
* while surfacing OSC 133;D prompt-completion markers for exact readiness detection.
|
|
296
|
+
*/
|
|
297
|
+
export class TerminalSanitizer {
|
|
298
|
+
private mode: 'text' | 'esc' | 'csi' | 'osc' | 'osc_esc' | 'st_skip' | 'st_esc' = 'text';
|
|
299
|
+
private oscBuf = '';
|
|
300
|
+
|
|
301
|
+
public process(chunk: string): { text: string; promptMarkers: number } {
|
|
302
|
+
let out = '';
|
|
303
|
+
let promptMarkers = 0;
|
|
304
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
305
|
+
const ch = chunk[i]!;
|
|
306
|
+
const code = chunk.charCodeAt(i);
|
|
307
|
+
|
|
308
|
+
if (this.mode === 'text') {
|
|
309
|
+
if (code === 0x1b) {
|
|
310
|
+
this.mode = 'esc';
|
|
311
|
+
} else if (code === 0x0d) {
|
|
312
|
+
// Drop bare CR so \r\n normalizes to \n without overwriting visible text
|
|
313
|
+
} else if (code === 0x08) {
|
|
314
|
+
if (out.length > 0 && out[out.length - 1] !== '\n') {
|
|
315
|
+
out = out.slice(0, -1);
|
|
316
|
+
}
|
|
317
|
+
} else if (code === 0x09 || code === 0x0a || code >= 0x20) {
|
|
318
|
+
out += ch;
|
|
319
|
+
}
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
if (this.mode === 'esc') {
|
|
324
|
+
if (ch === '[') {
|
|
325
|
+
this.mode = 'csi';
|
|
326
|
+
} else if (ch === ']') {
|
|
327
|
+
this.mode = 'osc';
|
|
328
|
+
this.oscBuf = '';
|
|
329
|
+
} else if (ch === 'P' || ch === '_' || ch === '^' || ch === 'X') {
|
|
330
|
+
this.mode = 'st_skip';
|
|
331
|
+
} else if (ch === '(' || ch === ')' || ch === '*' || ch === '+') {
|
|
332
|
+
// Character-set designation consumes one following char
|
|
333
|
+
if (i + 1 < chunk.length) i++;
|
|
334
|
+
this.mode = 'text';
|
|
335
|
+
} else {
|
|
336
|
+
this.mode = 'text';
|
|
337
|
+
}
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (this.mode === 'csi') {
|
|
342
|
+
if (code >= 0x40 && code <= 0x7e) {
|
|
343
|
+
this.mode = 'text';
|
|
344
|
+
}
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
if (this.mode === 'osc') {
|
|
349
|
+
if (code === 0x07) {
|
|
350
|
+
if (this.oscBuf.startsWith('133;D')) promptMarkers++;
|
|
351
|
+
this.oscBuf = '';
|
|
352
|
+
this.mode = 'text';
|
|
353
|
+
} else if (code === 0x1b) {
|
|
354
|
+
this.mode = 'osc_esc';
|
|
355
|
+
} else if (this.oscBuf.length < 256) {
|
|
356
|
+
this.oscBuf += ch;
|
|
357
|
+
}
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (this.mode === 'osc_esc') {
|
|
362
|
+
if (ch === '\\') {
|
|
363
|
+
if (this.oscBuf.startsWith('133;D')) promptMarkers++;
|
|
364
|
+
this.oscBuf = '';
|
|
365
|
+
this.mode = 'text';
|
|
366
|
+
} else {
|
|
367
|
+
this.oscBuf = '';
|
|
368
|
+
this.mode = 'text';
|
|
369
|
+
}
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (this.mode === 'st_skip') {
|
|
374
|
+
if (code === 0x1b) this.mode = 'st_esc';
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if (this.mode === 'st_esc') {
|
|
379
|
+
this.mode = ch === '\\' ? 'text' : 'st_skip';
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
return { text: out, promptMarkers };
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
let cachedPython3Path: string | null | undefined;
|
|
388
|
+
function resolvePython3Path(): string | null {
|
|
389
|
+
if (cachedPython3Path !== undefined) return cachedPython3Path;
|
|
390
|
+
if (process.platform === 'win32') {
|
|
391
|
+
cachedPython3Path = null;
|
|
392
|
+
return null;
|
|
393
|
+
}
|
|
394
|
+
const candidates = ['/usr/bin/python3', '/opt/homebrew/bin/python3', '/usr/local/bin/python3', 'python3'];
|
|
395
|
+
for (const bin of candidates) {
|
|
396
|
+
try {
|
|
397
|
+
const res = spawnSync(bin, ['-c', 'import pty, fcntl, termios; print("ok")'], {
|
|
398
|
+
encoding: 'utf8',
|
|
399
|
+
timeout: 2500,
|
|
400
|
+
stdio: ['ignore', 'pipe', 'ignore']
|
|
401
|
+
});
|
|
402
|
+
if (res.status === 0 && (res.stdout || '').trim() === 'ok') {
|
|
403
|
+
cachedPython3Path = bin;
|
|
404
|
+
return bin;
|
|
405
|
+
}
|
|
406
|
+
} catch {
|
|
407
|
+
// Try next candidate
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
cachedPython3Path = null;
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export function listAvailableShells(): AvailableShellInfo[] {
|
|
415
|
+
if (process.platform === 'win32') {
|
|
416
|
+
return [
|
|
417
|
+
{ id: 'powershell', label: 'PowerShell', path: 'powershell.exe', isDefault: true },
|
|
418
|
+
{ id: 'cmd', label: 'cmd', path: 'cmd.exe', isDefault: false }
|
|
419
|
+
];
|
|
420
|
+
}
|
|
421
|
+
const envShell = (process.env.SHELL || '').trim();
|
|
422
|
+
const seenLabels = new Set<string>();
|
|
423
|
+
const shells: AvailableShellInfo[] = [];
|
|
424
|
+
|
|
425
|
+
const pushIfExists = (shellPath: string, label: string, id: string): void => {
|
|
426
|
+
if (!ALLOWED_POSIX_SHELL_PATH_SET.has(shellPath)) return;
|
|
427
|
+
if (!fs.existsSync(shellPath)) return;
|
|
428
|
+
if (seenLabels.has(label)) return;
|
|
429
|
+
seenLabels.add(label);
|
|
430
|
+
shells.push({
|
|
431
|
+
id,
|
|
432
|
+
label,
|
|
433
|
+
path: shellPath,
|
|
434
|
+
isDefault: shellPath === envShell
|
|
435
|
+
});
|
|
436
|
+
};
|
|
437
|
+
|
|
438
|
+
if (envShell && ALLOWED_POSIX_SHELL_PATH_SET.has(envShell)) {
|
|
439
|
+
const match = ALLOWED_POSIX_SHELLS.find((s) => s.path === envShell);
|
|
440
|
+
if (match) pushIfExists(match.path, match.label, match.id);
|
|
441
|
+
}
|
|
442
|
+
for (const entry of ALLOWED_POSIX_SHELLS) {
|
|
443
|
+
pushIfExists(entry.path, entry.label, entry.id);
|
|
444
|
+
}
|
|
445
|
+
if (shells.length > 0 && !shells.some((s) => s.isDefault)) {
|
|
446
|
+
shells[0]!.isDefault = true;
|
|
447
|
+
}
|
|
448
|
+
return shells;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function resolveRequestedShell(rawShell?: string): { path: string; label: string } {
|
|
452
|
+
const available = listAvailableShells();
|
|
453
|
+
const fallback = available.find((s) => s.isDefault) ?? available[0] ?? {
|
|
454
|
+
path: process.platform === 'win32' ? 'powershell.exe' : '/bin/sh',
|
|
455
|
+
label: process.platform === 'win32' ? 'PowerShell' : 'sh'
|
|
456
|
+
};
|
|
457
|
+
if (typeof rawShell !== 'string' || !rawShell.trim()) {
|
|
458
|
+
return { path: fallback.path, label: fallback.label };
|
|
459
|
+
}
|
|
460
|
+
const q = rawShell.trim().toLowerCase();
|
|
461
|
+
const matched = available.find(
|
|
462
|
+
(s) => s.id.toLowerCase() === q || s.label.toLowerCase() === q || s.path.toLowerCase() === q
|
|
463
|
+
);
|
|
464
|
+
if (matched) return { path: matched.path, label: matched.label };
|
|
465
|
+
return { path: fallback.path, label: fallback.label };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
interface LivePtySession {
|
|
469
|
+
id: string;
|
|
470
|
+
name: string;
|
|
471
|
+
shell: string;
|
|
472
|
+
shellLabel: string;
|
|
473
|
+
cwd: string;
|
|
474
|
+
workspaceRoot: string;
|
|
475
|
+
origin: TerminalOrigin;
|
|
476
|
+
control: TerminalControlOwner;
|
|
477
|
+
transport: 'pty' | 'pipe';
|
|
478
|
+
proc: ChildProcessWithoutNullStreams;
|
|
479
|
+
detachedGroup: boolean;
|
|
480
|
+
childPid: number | null;
|
|
481
|
+
status: 'running' | 'exited';
|
|
482
|
+
exitCode: number | null;
|
|
483
|
+
cols: number;
|
|
484
|
+
rows: number;
|
|
485
|
+
createdAt: number;
|
|
486
|
+
lastActivityAt: number;
|
|
487
|
+
scrollback: string;
|
|
488
|
+
sanitizer: TerminalSanitizer;
|
|
489
|
+
promptMarkerCount: number;
|
|
490
|
+
stdoutLineBuf: string;
|
|
491
|
+
subscribers: Set<(ev: TerminalStreamEvent) => void>;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function trimScrollback(text: string): string {
|
|
495
|
+
if (text.length <= MAX_SCROLLBACK_CHARS) return text;
|
|
496
|
+
let cut = text.length - MAX_SCROLLBACK_CHARS;
|
|
497
|
+
// Preserve UTF-16 surrogate pair boundary
|
|
498
|
+
const code = text.charCodeAt(cut);
|
|
499
|
+
if (code >= 0xdc00 && code <= 0xdfff && cut + 1 < text.length) {
|
|
500
|
+
cut += 1;
|
|
501
|
+
}
|
|
502
|
+
return text.slice(cut);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function terminateChildTree(proc: ChildProcessWithoutNullStreams, detachedGroup: boolean, force = false): void {
|
|
506
|
+
const pid = proc.pid;
|
|
507
|
+
try { proc.stdin?.end(); } catch { /* ignore */ }
|
|
508
|
+
if (!pid) return;
|
|
509
|
+
if (process.platform === 'win32') {
|
|
510
|
+
try {
|
|
511
|
+
if (force) {
|
|
512
|
+
spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 2000 });
|
|
513
|
+
} else {
|
|
514
|
+
execFile('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, timeout: 4000 }, () => {});
|
|
515
|
+
}
|
|
516
|
+
} catch { /* ignore */ }
|
|
517
|
+
try { proc.kill(); } catch { /* ignore */ }
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
const sig: NodeJS.Signals = force ? 'SIGKILL' : 'SIGTERM';
|
|
521
|
+
if (detachedGroup) {
|
|
522
|
+
try {
|
|
523
|
+
process.kill(-pid, sig);
|
|
524
|
+
return;
|
|
525
|
+
} catch { /* fallback */ }
|
|
526
|
+
}
|
|
527
|
+
try { proc.kill(sig); } catch { /* ignore */ }
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
export class PtyTerminalManager {
|
|
531
|
+
private readonly sessions = new Map<string, LivePtySession>();
|
|
532
|
+
private counter = 0;
|
|
533
|
+
|
|
534
|
+
public listSessions(workspaceRoot?: string): TerminalSessionSummary[] {
|
|
535
|
+
const out: TerminalSessionSummary[] = [];
|
|
536
|
+
for (const session of this.sessions.values()) {
|
|
537
|
+
if (workspaceRoot && session.workspaceRoot !== workspaceRoot) continue;
|
|
538
|
+
out.push(this.toSummary(session));
|
|
539
|
+
}
|
|
540
|
+
return out.sort((a, b) => a.createdAt - b.createdAt);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
public getSession(id: string): TerminalSessionSummary | null {
|
|
544
|
+
const session = this.sessions.get(id);
|
|
545
|
+
return session ? this.toSummary(session) : null;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
public openSession(options: {
|
|
549
|
+
workspaceRoot: string;
|
|
550
|
+
cwd?: string | undefined;
|
|
551
|
+
shell?: string | undefined;
|
|
552
|
+
name?: string | undefined;
|
|
553
|
+
origin?: TerminalOrigin | undefined;
|
|
554
|
+
cols?: number | undefined;
|
|
555
|
+
rows?: number | undefined;
|
|
556
|
+
osSandbox?: string | OsSandboxWrapOptions | undefined;
|
|
557
|
+
}): TerminalSessionSummary {
|
|
558
|
+
const runningCount = [...this.sessions.values()].filter((s) => s.status === 'running').length;
|
|
559
|
+
if (runningCount >= MAX_PTY_SESSIONS) {
|
|
560
|
+
throw new Error(`Maximum concurrent terminal sessions (${MAX_PTY_SESSIONS}) reached. Close an existing terminal first.`);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const scopeCtx: ToolWorkspaceContext = { workspaceRoot: options.workspaceRoot, workspacePaths: [options.workspaceRoot] };
|
|
564
|
+
const resolvedCwd = typeof options.cwd === 'string' && options.cwd.trim()
|
|
565
|
+
? resolveScopedPath(options.cwd, scopeCtx)
|
|
566
|
+
: options.workspaceRoot;
|
|
567
|
+
|
|
568
|
+
const chosenShell = resolveRequestedShell(options.shell);
|
|
569
|
+
const cols = boundedInteger(options.cols, 100, 20, 400);
|
|
570
|
+
const rows = boundedInteger(options.rows, 28, 6, 160);
|
|
571
|
+
const origin: TerminalOrigin = options.origin === 'agent' ? 'agent' : 'user';
|
|
572
|
+
const control: TerminalControlOwner = origin;
|
|
573
|
+
const id = `term_${++this.counter}_${crypto.randomBytes(4).toString('hex')}`;
|
|
574
|
+
const name = typeof options.name === 'string' && options.name.trim()
|
|
575
|
+
? options.name.trim().slice(0, 48)
|
|
576
|
+
: `${chosenShell.label} #${this.counter}`;
|
|
577
|
+
|
|
578
|
+
const python3 = resolvePython3Path();
|
|
579
|
+
const usePty = Boolean(python3 && process.platform !== 'win32');
|
|
580
|
+
const baseCommand = usePty ? python3! : chosenShell.path;
|
|
581
|
+
const baseArgs = usePty
|
|
582
|
+
? ['-u', '-c', PYTHON_PTY_HELPER, chosenShell.path, String(cols), String(rows)]
|
|
583
|
+
: (process.platform === 'win32' && chosenShell.path.toLowerCase().includes('powershell')
|
|
584
|
+
? ['-NoLogo', '-NoProfile', '-NoExit', '-Command', '-']
|
|
585
|
+
: []);
|
|
586
|
+
|
|
587
|
+
const workspaceRoots = [options.workspaceRoot];
|
|
588
|
+
let wrapped;
|
|
589
|
+
if (options.osSandbox && typeof options.osSandbox === 'object') {
|
|
590
|
+
wrapped = wrapCommandWithOsSandbox(baseCommand, baseArgs, {
|
|
591
|
+
...options.osSandbox,
|
|
592
|
+
cwd: options.osSandbox.cwd || resolvedCwd,
|
|
593
|
+
workspaceRoots: options.osSandbox.workspaceRoots || workspaceRoots
|
|
594
|
+
});
|
|
595
|
+
} else {
|
|
596
|
+
const sandboxRes = resolveOsSandboxMode(
|
|
597
|
+
process.env,
|
|
598
|
+
typeof options.osSandbox === 'string' ? options.osSandbox : undefined
|
|
599
|
+
);
|
|
600
|
+
wrapped = wrapCommandWithOsSandbox(baseCommand, baseArgs, {
|
|
601
|
+
mode: sandboxRes.mode,
|
|
602
|
+
strict: sandboxRes.strict,
|
|
603
|
+
allowNetwork: sandboxRes.allowNetwork,
|
|
604
|
+
cwd: resolvedCwd,
|
|
605
|
+
workspaceRoots
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const baseEnv = getEnhancedEnv();
|
|
610
|
+
const env: NodeJS.ProcessEnv = {
|
|
611
|
+
...baseEnv,
|
|
612
|
+
TERM: 'xterm-256color',
|
|
613
|
+
COLORTERM: 'truecolor',
|
|
614
|
+
COLUMNS: String(cols),
|
|
615
|
+
LINES: String(rows),
|
|
616
|
+
CAUSYNE_TERMINAL: '1',
|
|
617
|
+
// OSC 133;D marker for exact prompt-completion readiness in bash/zsh
|
|
618
|
+
PROMPT_COMMAND: 'printf "\\033]133;D;%s\\007" "$?"'
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
const detachedGroup = process.platform !== 'win32';
|
|
622
|
+
const proc = spawn(wrapped.command, wrapped.args, {
|
|
623
|
+
cwd: resolvedCwd,
|
|
624
|
+
env,
|
|
625
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
626
|
+
detached: detachedGroup,
|
|
627
|
+
windowsHide: true
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
const now = Date.now();
|
|
631
|
+
const session: LivePtySession = {
|
|
632
|
+
id,
|
|
633
|
+
name,
|
|
634
|
+
shell: chosenShell.path,
|
|
635
|
+
shellLabel: chosenShell.label,
|
|
636
|
+
cwd: resolvedCwd,
|
|
637
|
+
workspaceRoot: options.workspaceRoot,
|
|
638
|
+
origin,
|
|
639
|
+
control,
|
|
640
|
+
transport: usePty ? 'pty' : 'pipe',
|
|
641
|
+
proc,
|
|
642
|
+
detachedGroup,
|
|
643
|
+
childPid: proc.pid ?? null,
|
|
644
|
+
status: 'running',
|
|
645
|
+
exitCode: null,
|
|
646
|
+
cols,
|
|
647
|
+
rows,
|
|
648
|
+
createdAt: now,
|
|
649
|
+
lastActivityAt: now,
|
|
650
|
+
scrollback: '',
|
|
651
|
+
sanitizer: new TerminalSanitizer(),
|
|
652
|
+
promptMarkerCount: 0,
|
|
653
|
+
stdoutLineBuf: '',
|
|
654
|
+
subscribers: new Set()
|
|
655
|
+
};
|
|
656
|
+
|
|
657
|
+
const appendOutput = (rawChunk: string): void => {
|
|
658
|
+
const cleaned = session.sanitizer.process(rawChunk);
|
|
659
|
+
if (cleaned.promptMarkers > 0) {
|
|
660
|
+
session.promptMarkerCount += cleaned.promptMarkers;
|
|
661
|
+
}
|
|
662
|
+
if (!cleaned.text) return;
|
|
663
|
+
const redacted = redactTextSecrets(cleaned.text);
|
|
664
|
+
session.scrollback = trimScrollback(session.scrollback + redacted);
|
|
665
|
+
session.lastActivityAt = Date.now();
|
|
666
|
+
this.broadcast(session, {
|
|
667
|
+
type: 'output',
|
|
668
|
+
sessionId: session.id,
|
|
669
|
+
data: redacted,
|
|
670
|
+
ts: session.lastActivityAt
|
|
671
|
+
});
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
if (usePty) {
|
|
675
|
+
proc.stdout.on('data', (buf: Buffer) => {
|
|
676
|
+
session.stdoutLineBuf += buf.toString('utf8');
|
|
677
|
+
let nl = session.stdoutLineBuf.indexOf('\n');
|
|
678
|
+
while (nl !== -1) {
|
|
679
|
+
const line = session.stdoutLineBuf.slice(0, nl).trim();
|
|
680
|
+
session.stdoutLineBuf = session.stdoutLineBuf.slice(nl + 1);
|
|
681
|
+
if (line) {
|
|
682
|
+
try {
|
|
683
|
+
const msg = JSON.parse(line) as { t?: string; b?: string; pid?: number; code?: number };
|
|
684
|
+
if (msg.t === 'ready' && typeof msg.pid === 'number') {
|
|
685
|
+
session.childPid = msg.pid;
|
|
686
|
+
} else if (msg.t === 'out' && typeof msg.b === 'string') {
|
|
687
|
+
const decoded = Buffer.from(msg.b, 'base64').toString('utf8');
|
|
688
|
+
appendOutput(decoded);
|
|
689
|
+
} else if (msg.t === 'exit') {
|
|
690
|
+
session.exitCode = typeof msg.code === 'number' ? msg.code : 0;
|
|
691
|
+
}
|
|
692
|
+
} catch {
|
|
693
|
+
// Ignore malformed framed line
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
nl = session.stdoutLineBuf.indexOf('\n');
|
|
697
|
+
}
|
|
698
|
+
});
|
|
699
|
+
proc.stderr.on('data', (buf: Buffer) => {
|
|
700
|
+
const text = buf.toString('utf8');
|
|
701
|
+
if (text.trim()) appendOutput(text);
|
|
702
|
+
});
|
|
703
|
+
} else {
|
|
704
|
+
proc.stdout.on('data', (buf: Buffer) => appendOutput(buf.toString('utf8')));
|
|
705
|
+
proc.stderr.on('data', (buf: Buffer) => appendOutput(buf.toString('utf8')));
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
proc.on('exit', (code) => {
|
|
709
|
+
session.status = 'exited';
|
|
710
|
+
if (session.exitCode === null) {
|
|
711
|
+
session.exitCode = typeof code === 'number' ? code : 0;
|
|
712
|
+
}
|
|
713
|
+
session.lastActivityAt = Date.now();
|
|
714
|
+
this.broadcast(session, {
|
|
715
|
+
type: 'exit',
|
|
716
|
+
sessionId: session.id,
|
|
717
|
+
status: 'exited',
|
|
718
|
+
exitCode: session.exitCode,
|
|
719
|
+
ts: session.lastActivityAt
|
|
720
|
+
});
|
|
721
|
+
});
|
|
722
|
+
|
|
723
|
+
proc.on('error', (err) => {
|
|
724
|
+
appendOutput(`\n[terminal error: ${getErrorMessage(err)}]\n`);
|
|
725
|
+
session.status = 'exited';
|
|
726
|
+
session.exitCode = 1;
|
|
727
|
+
this.broadcast(session, {
|
|
728
|
+
type: 'exit',
|
|
729
|
+
sessionId: session.id,
|
|
730
|
+
status: 'exited',
|
|
731
|
+
exitCode: 1,
|
|
732
|
+
ts: Date.now()
|
|
733
|
+
});
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
this.sessions.set(id, session);
|
|
737
|
+
return this.toSummary(session);
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
public writeInput(
|
|
741
|
+
id: string,
|
|
742
|
+
data: string,
|
|
743
|
+
options: { actor?: TerminalControlOwner | undefined; typed?: boolean | undefined } = {}
|
|
744
|
+
): { ok: boolean; control: TerminalControlOwner; error?: string | undefined; code?: string | undefined } {
|
|
745
|
+
const session = this.sessions.get(id);
|
|
746
|
+
if (!session) return { ok: false, control: 'user', error: `Terminal session "${id}" not found.`, code: 'NOT_FOUND' };
|
|
747
|
+
if (session.status !== 'running') {
|
|
748
|
+
return { ok: false, control: session.control, error: 'Terminal session has already exited.', code: 'SESSION_EXITED' };
|
|
749
|
+
}
|
|
750
|
+
if (data.includes('\0')) {
|
|
751
|
+
return { ok: false, control: session.control, error: 'Input cannot contain NUL bytes.', code: 'INVALID_INPUT' };
|
|
752
|
+
}
|
|
753
|
+
const actor = options.actor ?? 'user';
|
|
754
|
+
if (actor === 'user' && options.typed !== false && session.control === 'agent') {
|
|
755
|
+
session.control = 'user';
|
|
756
|
+
this.broadcast(session, {
|
|
757
|
+
type: 'control',
|
|
758
|
+
sessionId: session.id,
|
|
759
|
+
control: 'user',
|
|
760
|
+
ts: Date.now()
|
|
761
|
+
});
|
|
762
|
+
} else if (actor === 'agent' && session.control === 'user' && session.origin === 'agent') {
|
|
763
|
+
return {
|
|
764
|
+
ok: false,
|
|
765
|
+
control: 'user',
|
|
766
|
+
error: 'Terminal session was taken over by the user. Read-only inspection remains available.',
|
|
767
|
+
code: 'TAKEN_OVER'
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
try {
|
|
772
|
+
if (session.transport === 'pty') {
|
|
773
|
+
const frame = JSON.stringify({ t: 'in', b: Buffer.from(data, 'utf8').toString('base64') }) + '\n';
|
|
774
|
+
session.proc.stdin.write(frame);
|
|
775
|
+
} else {
|
|
776
|
+
session.proc.stdin.write(data);
|
|
777
|
+
}
|
|
778
|
+
session.lastActivityAt = Date.now();
|
|
779
|
+
return { ok: true, control: session.control };
|
|
780
|
+
} catch (err) {
|
|
781
|
+
return { ok: false, control: session.control, error: getErrorMessage(err), code: 'WRITE_FAILED' };
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
public resizeSession(id: string, cols: number, rows: number): boolean {
|
|
786
|
+
const session = this.sessions.get(id);
|
|
787
|
+
if (!session || session.status !== 'running') return false;
|
|
788
|
+
const safeCols = boundedInteger(cols, session.cols, 20, 400);
|
|
789
|
+
const safeRows = boundedInteger(rows, session.rows, 6, 160);
|
|
790
|
+
session.cols = safeCols;
|
|
791
|
+
session.rows = safeRows;
|
|
792
|
+
if (session.transport === 'pty') {
|
|
793
|
+
try {
|
|
794
|
+
session.proc.stdin.write(`${JSON.stringify({ t: 'resize', cols: safeCols, rows: safeRows })}\n`);
|
|
795
|
+
} catch {
|
|
796
|
+
return false;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
this.broadcast(session, {
|
|
800
|
+
type: 'meta',
|
|
801
|
+
sessionId: session.id,
|
|
802
|
+
cols: safeCols,
|
|
803
|
+
rows: safeRows,
|
|
804
|
+
control: session.control,
|
|
805
|
+
status: session.status,
|
|
806
|
+
ts: Date.now()
|
|
807
|
+
});
|
|
808
|
+
return true;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
public signalSession(
|
|
812
|
+
id: string,
|
|
813
|
+
signalName: TerminalSignalName,
|
|
814
|
+
actor: TerminalControlOwner = 'user'
|
|
815
|
+
): { ok: boolean; error?: string | undefined; code?: string | undefined } {
|
|
816
|
+
const session = this.sessions.get(id);
|
|
817
|
+
if (!session) return { ok: false, error: `Terminal session "${id}" not found.`, code: 'NOT_FOUND' };
|
|
818
|
+
if (session.status !== 'running') return { ok: false, error: 'Terminal session has already exited.', code: 'SESSION_EXITED' };
|
|
819
|
+
if (!ALLOWED_SIGNALS.has(signalName)) return { ok: false, error: `Unsupported signal: ${signalName}`, code: 'INVALID_SIGNAL' };
|
|
820
|
+
if (signalName === 'SIGKILL') {
|
|
821
|
+
return { ok: false, error: 'Refusing SIGKILL on interactive terminal session. Use SIGINT, SIGTERM, or close().', code: 'SIGNAL_DENIED' };
|
|
822
|
+
}
|
|
823
|
+
if (actor === 'agent' && session.control === 'user' && session.origin === 'agent') {
|
|
824
|
+
return { ok: false, error: 'Terminal session was taken over by the user.', code: 'TAKEN_OVER' };
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
if (session.transport === 'pty') {
|
|
828
|
+
try {
|
|
829
|
+
session.proc.stdin.write(`${JSON.stringify({ t: 'sig', s: signalName })}\n`);
|
|
830
|
+
return { ok: true };
|
|
831
|
+
} catch (err) {
|
|
832
|
+
return { ok: false, error: getErrorMessage(err) };
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
if (signalName === 'SIGINT') {
|
|
837
|
+
try { session.proc.stdin.write('\x03'); } catch { /* ignore */ }
|
|
838
|
+
}
|
|
839
|
+
try {
|
|
840
|
+
session.proc.kill(signalName);
|
|
841
|
+
return { ok: true };
|
|
842
|
+
} catch (err) {
|
|
843
|
+
return { ok: false, error: getErrorMessage(err) };
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
public readScrollback(
|
|
848
|
+
id: string,
|
|
849
|
+
options: { tailChars?: number | undefined; offsetFromEnd?: number | undefined } = {}
|
|
850
|
+
): { ok: boolean; text: string; totalChars: number; status: 'running' | 'exited'; exitCode: number | null; control: TerminalControlOwner } {
|
|
851
|
+
const session = this.sessions.get(id);
|
|
852
|
+
if (!session) {
|
|
853
|
+
return { ok: false, text: '', totalChars: 0, status: 'exited', exitCode: null, control: 'user' };
|
|
854
|
+
}
|
|
855
|
+
const total = session.scrollback.length;
|
|
856
|
+
const limit = boundedInteger(options.tailChars, 16_000, 200, 64_000);
|
|
857
|
+
const offset = boundedInteger(options.offsetFromEnd, 0, 0, total);
|
|
858
|
+
const end = Math.max(0, total - offset);
|
|
859
|
+
const start = Math.max(0, end - limit);
|
|
860
|
+
return {
|
|
861
|
+
ok: true,
|
|
862
|
+
text: session.scrollback.slice(start, end),
|
|
863
|
+
totalChars: total,
|
|
864
|
+
status: session.status,
|
|
865
|
+
exitCode: session.exitCode,
|
|
866
|
+
control: session.control
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
public async sendAndWait(
|
|
871
|
+
id: string,
|
|
872
|
+
input: string,
|
|
873
|
+
options: {
|
|
874
|
+
submit?: boolean | undefined;
|
|
875
|
+
timeoutMs?: number | undefined;
|
|
876
|
+
idleMs?: number | undefined;
|
|
877
|
+
actor?: TerminalControlOwner | undefined;
|
|
878
|
+
} = {}
|
|
879
|
+
): Promise<{
|
|
880
|
+
ok: boolean;
|
|
881
|
+
output: string;
|
|
882
|
+
waitReason: TerminalWaitReason;
|
|
883
|
+
status: 'running' | 'exited';
|
|
884
|
+
exitCode: number | null;
|
|
885
|
+
error?: string | undefined;
|
|
886
|
+
code?: string | undefined;
|
|
887
|
+
}> {
|
|
888
|
+
const session = this.sessions.get(id);
|
|
889
|
+
if (!session) {
|
|
890
|
+
return {
|
|
891
|
+
ok: false,
|
|
892
|
+
output: '',
|
|
893
|
+
waitReason: 'session_exit',
|
|
894
|
+
status: 'exited',
|
|
895
|
+
exitCode: null,
|
|
896
|
+
error: `Terminal session "${id}" not found.`,
|
|
897
|
+
code: 'NOT_FOUND'
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
const startLen = session.scrollback.length;
|
|
902
|
+
const startMarkers = session.promptMarkerCount;
|
|
903
|
+
const payload = options.submit === false ? input : `${input}\n`;
|
|
904
|
+
const writeRes = this.writeInput(id, payload, { actor: options.actor ?? 'agent', typed: false });
|
|
905
|
+
if (!writeRes.ok) {
|
|
906
|
+
return {
|
|
907
|
+
ok: false,
|
|
908
|
+
output: '',
|
|
909
|
+
waitReason: session.status === 'exited' ? 'session_exit' : 'timeout',
|
|
910
|
+
status: session.status,
|
|
911
|
+
exitCode: session.exitCode,
|
|
912
|
+
error: writeRes.error,
|
|
913
|
+
code: writeRes.code
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
const timeoutMs = boundedInteger(options.timeoutMs, 15_000, 500, 90_000);
|
|
918
|
+
const idleMs = boundedInteger(options.idleMs, 750, 200, 10_000);
|
|
919
|
+
const deadline = Date.now() + timeoutMs;
|
|
920
|
+
let lastDataAt = Date.now();
|
|
921
|
+
let seenBytes = 0;
|
|
922
|
+
|
|
923
|
+
return new Promise((resolve) => {
|
|
924
|
+
let settled = false;
|
|
925
|
+
let idleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
926
|
+
let hardTimer: ReturnType<typeof setTimeout> | null = null;
|
|
927
|
+
|
|
928
|
+
const finish = (reason: TerminalWaitReason): void => {
|
|
929
|
+
if (settled) return;
|
|
930
|
+
settled = true;
|
|
931
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
932
|
+
if (hardTimer) clearTimeout(hardTimer);
|
|
933
|
+
unsub();
|
|
934
|
+
const delta = session.scrollback.length >= startLen
|
|
935
|
+
? session.scrollback.slice(startLen)
|
|
936
|
+
: session.scrollback.slice(-Math.min(session.scrollback.length, 16_000));
|
|
937
|
+
resolve({
|
|
938
|
+
ok: true,
|
|
939
|
+
output: delta.slice(0, 32_000),
|
|
940
|
+
waitReason: reason,
|
|
941
|
+
status: session.status,
|
|
942
|
+
exitCode: session.exitCode
|
|
943
|
+
});
|
|
944
|
+
};
|
|
945
|
+
|
|
946
|
+
const scheduleIdle = (): void => {
|
|
947
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
948
|
+
const remaining = Math.max(50, deadline - Date.now());
|
|
949
|
+
idleTimer = setTimeout(() => {
|
|
950
|
+
if (session.promptMarkerCount > startMarkers) {
|
|
951
|
+
finish('stdin_read');
|
|
952
|
+
} else if (seenBytes > 0 && Date.now() - lastDataAt >= idleMs - 40) {
|
|
953
|
+
finish('inferred_idle');
|
|
954
|
+
} else if (Date.now() >= deadline) {
|
|
955
|
+
finish('timeout');
|
|
956
|
+
} else {
|
|
957
|
+
scheduleIdle();
|
|
958
|
+
}
|
|
959
|
+
}, Math.min(idleMs, remaining));
|
|
960
|
+
};
|
|
961
|
+
|
|
962
|
+
const unsub = this.subscribe(id, (ev) => {
|
|
963
|
+
if (ev.type === 'exit') {
|
|
964
|
+
finish('session_exit');
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
if (ev.type === 'output' && ev.data) {
|
|
968
|
+
seenBytes += ev.data.length;
|
|
969
|
+
lastDataAt = Date.now();
|
|
970
|
+
if (session.promptMarkerCount > startMarkers) {
|
|
971
|
+
// Brief settle to capture any trailing prompt text
|
|
972
|
+
setTimeout(() => finish('stdin_read'), 60);
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
scheduleIdle();
|
|
976
|
+
}
|
|
977
|
+
}, false);
|
|
978
|
+
|
|
979
|
+
hardTimer = setTimeout(() => finish('timeout'), timeoutMs);
|
|
980
|
+
scheduleIdle();
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
public subscribe(
|
|
985
|
+
id: string,
|
|
986
|
+
listener: (ev: TerminalStreamEvent) => void,
|
|
987
|
+
sendSnapshot = true
|
|
988
|
+
): () => void {
|
|
989
|
+
const session = this.sessions.get(id);
|
|
990
|
+
if (!session) return () => {};
|
|
991
|
+
session.subscribers.add(listener);
|
|
992
|
+
if (sendSnapshot) {
|
|
993
|
+
try {
|
|
994
|
+
listener({
|
|
995
|
+
type: 'snapshot',
|
|
996
|
+
sessionId: session.id,
|
|
997
|
+
data: session.scrollback,
|
|
998
|
+
control: session.control,
|
|
999
|
+
status: session.status,
|
|
1000
|
+
exitCode: session.exitCode,
|
|
1001
|
+
cols: session.cols,
|
|
1002
|
+
rows: session.rows,
|
|
1003
|
+
ts: Date.now()
|
|
1004
|
+
});
|
|
1005
|
+
} catch {
|
|
1006
|
+
// Ignore subscriber failure
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
return () => {
|
|
1010
|
+
session.subscribers.delete(listener);
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
public closeSession(id: string): boolean {
|
|
1015
|
+
const session = this.sessions.get(id);
|
|
1016
|
+
if (!session) return false;
|
|
1017
|
+
if (session.status === 'running') {
|
|
1018
|
+
if (session.transport === 'pty') {
|
|
1019
|
+
try { session.proc.stdin.write(`${JSON.stringify({ t: 'close' })}\n`); } catch { /* ignore */ }
|
|
1020
|
+
}
|
|
1021
|
+
terminateChildTree(session.proc, session.detachedGroup, false);
|
|
1022
|
+
setTimeout(() => {
|
|
1023
|
+
if (session.status === 'running') {
|
|
1024
|
+
terminateChildTree(session.proc, session.detachedGroup, true);
|
|
1025
|
+
}
|
|
1026
|
+
}, 600).unref?.();
|
|
1027
|
+
}
|
|
1028
|
+
session.status = 'exited';
|
|
1029
|
+
session.subscribers.clear();
|
|
1030
|
+
this.sessions.delete(id);
|
|
1031
|
+
return true;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
public closeAll(): void {
|
|
1035
|
+
for (const session of this.sessions.values()) {
|
|
1036
|
+
terminateChildTree(session.proc, session.detachedGroup, true);
|
|
1037
|
+
session.subscribers.clear();
|
|
1038
|
+
}
|
|
1039
|
+
this.sessions.clear();
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
private broadcast(session: LivePtySession, ev: TerminalStreamEvent): void {
|
|
1043
|
+
for (const sub of [...session.subscribers]) {
|
|
1044
|
+
try {
|
|
1045
|
+
sub(ev);
|
|
1046
|
+
} catch {
|
|
1047
|
+
// Isolate subscriber errors
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
private toSummary(session: LivePtySession): TerminalSessionSummary {
|
|
1053
|
+
return {
|
|
1054
|
+
id: session.id,
|
|
1055
|
+
name: session.name,
|
|
1056
|
+
shell: session.shell,
|
|
1057
|
+
shellLabel: session.shellLabel,
|
|
1058
|
+
cwd: session.cwd,
|
|
1059
|
+
workspaceRoot: session.workspaceRoot,
|
|
1060
|
+
origin: session.origin,
|
|
1061
|
+
control: session.control,
|
|
1062
|
+
transport: session.transport,
|
|
1063
|
+
status: session.status,
|
|
1064
|
+
exitCode: session.exitCode,
|
|
1065
|
+
cols: session.cols,
|
|
1066
|
+
rows: session.rows,
|
|
1067
|
+
createdAt: session.createdAt,
|
|
1068
|
+
lastActivityAt: session.lastActivityAt,
|
|
1069
|
+
scrollbackBytes: Buffer.byteLength(session.scrollback, 'utf8')
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
export const ptyTerminalManager = new PtyTerminalManager();
|
|
1075
|
+
|
|
1076
|
+
process.on('exit', () => {
|
|
1077
|
+
ptyTerminalManager.closeAll();
|
|
1078
|
+
});
|
|
1079
|
+
|
|
1080
|
+
export interface PtyTerminalToolArgs {
|
|
1081
|
+
action: 'open' | 'send' | 'read' | 'signal' | 'resize' | 'list' | 'close';
|
|
1082
|
+
sessionId?: string | undefined;
|
|
1083
|
+
input?: string | undefined;
|
|
1084
|
+
submit?: boolean | undefined;
|
|
1085
|
+
shell?: string | undefined;
|
|
1086
|
+
cwd?: string | undefined;
|
|
1087
|
+
name?: string | undefined;
|
|
1088
|
+
signal?: TerminalSignalName | undefined;
|
|
1089
|
+
cols?: number | undefined;
|
|
1090
|
+
rows?: number | undefined;
|
|
1091
|
+
timeoutMs?: number | undefined;
|
|
1092
|
+
tailChars?: number | undefined;
|
|
1093
|
+
offsetFromEnd?: number | undefined;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
export const ptyTerminalTool = {
|
|
1097
|
+
schema: {
|
|
1098
|
+
name: 'terminal.pty',
|
|
1099
|
+
description:
|
|
1100
|
+
'Manage real interactive PTY terminal sessions inside the workspace (REPLs, interactive CLIs, shells, debuggers). Supports open, send (with submit=false for raw control/partial input), read paginated scrollback, signal (SIGINT/SIGTERM/SIGTSTP/SIGHUP), resize, list, and close.',
|
|
1101
|
+
parameters: {
|
|
1102
|
+
type: 'object',
|
|
1103
|
+
properties: {
|
|
1104
|
+
action: {
|
|
1105
|
+
type: 'string',
|
|
1106
|
+
enum: ['open', 'send', 'read', 'signal', 'resize', 'list', 'close'],
|
|
1107
|
+
description: 'Interactive PTY terminal action.'
|
|
1108
|
+
},
|
|
1109
|
+
sessionId: { type: 'string', description: 'Target terminal session ID (required for send, read, signal, resize, close).' },
|
|
1110
|
+
input: { type: 'string', description: 'Text or control sequence to send (for send action).' },
|
|
1111
|
+
submit: { type: 'boolean', description: 'Append newline after input (default true). Set false for raw/control input.' },
|
|
1112
|
+
shell: { type: 'string', description: 'Optional shell name (zsh, bash, sh) when opening a session.' },
|
|
1113
|
+
cwd: { type: 'string', description: 'Optional workspace-relative working directory when opening a session.' },
|
|
1114
|
+
name: { type: 'string', description: 'Optional display name for the terminal session.' },
|
|
1115
|
+
signal: {
|
|
1116
|
+
type: 'string',
|
|
1117
|
+
enum: ['SIGINT', 'SIGTERM', 'SIGTSTP', 'SIGHUP'],
|
|
1118
|
+
description: 'POSIX signal for the signal action.'
|
|
1119
|
+
},
|
|
1120
|
+
cols: { type: 'integer', description: 'Terminal width in columns (20-400).' },
|
|
1121
|
+
rows: { type: 'integer', description: 'Terminal height in rows (6-160).' },
|
|
1122
|
+
timeoutMs: { type: 'integer', description: 'Maximum wait time in ms for send output (500-90000).' },
|
|
1123
|
+
tailChars: { type: 'integer', description: 'Maximum characters to return for read action (200-64000).' },
|
|
1124
|
+
offsetFromEnd: { type: 'integer', description: 'Offset backwards from newest scrollback end for pagination.' }
|
|
1125
|
+
},
|
|
1126
|
+
required: ['action'],
|
|
1127
|
+
additionalProperties: false
|
|
1128
|
+
}
|
|
1129
|
+
},
|
|
1130
|
+
|
|
1131
|
+
async execute(args: PtyTerminalToolArgs, context: ToolWorkspaceContext = {}) {
|
|
1132
|
+
try {
|
|
1133
|
+
const scope = resolveToolWorkspaceRoots(context);
|
|
1134
|
+
const workspaceRoot = scope.primaryRoot || process.cwd();
|
|
1135
|
+
const action = args?.action;
|
|
1136
|
+
|
|
1137
|
+
if (action === 'list') {
|
|
1138
|
+
const sessions = ptyTerminalManager.listSessions(workspaceRoot);
|
|
1139
|
+
return {
|
|
1140
|
+
success: true,
|
|
1141
|
+
sessions,
|
|
1142
|
+
shells: listAvailableShells(),
|
|
1143
|
+
output: sessions.length === 0
|
|
1144
|
+
? 'No active interactive PTY sessions.'
|
|
1145
|
+
: sessions.map((s) => `${s.id} (${s.shellLabel}, ${s.status}, control=${s.control}) — ${s.name}`).join('\n')
|
|
1146
|
+
};
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
if (action === 'open') {
|
|
1150
|
+
const created = ptyTerminalManager.openSession({
|
|
1151
|
+
workspaceRoot,
|
|
1152
|
+
cwd: args.cwd,
|
|
1153
|
+
shell: args.shell,
|
|
1154
|
+
name: args.name,
|
|
1155
|
+
origin: 'agent',
|
|
1156
|
+
cols: args.cols,
|
|
1157
|
+
rows: args.rows
|
|
1158
|
+
});
|
|
1159
|
+
// Give shell brief startup settle so initial prompt is captured
|
|
1160
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
1161
|
+
const initial = ptyTerminalManager.readScrollback(created.id, { tailChars: 4000 });
|
|
1162
|
+
return {
|
|
1163
|
+
success: true,
|
|
1164
|
+
session: created,
|
|
1165
|
+
output: `Opened PTY session ${created.id} (${created.shellLabel}, ${created.transport}) in ${created.cwd}.\n${initial.text}`.trim()
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
const sessionId = typeof args?.sessionId === 'string' ? args.sessionId.trim() : '';
|
|
1170
|
+
if (!sessionId) return { success: false, error: 'sessionId is required for this terminal action.' };
|
|
1171
|
+
|
|
1172
|
+
if (action === 'send') {
|
|
1173
|
+
if (typeof args.input !== 'string') return { success: false, error: 'input string is required for send action.' };
|
|
1174
|
+
const res = await ptyTerminalManager.sendAndWait(sessionId, args.input, {
|
|
1175
|
+
submit: args.submit !== false,
|
|
1176
|
+
timeoutMs: args.timeoutMs,
|
|
1177
|
+
actor: 'agent'
|
|
1178
|
+
});
|
|
1179
|
+
if (!res.ok) return { success: false, error: res.error || 'Terminal send failed.', code: res.code };
|
|
1180
|
+
return {
|
|
1181
|
+
success: true,
|
|
1182
|
+
waitReason: res.waitReason,
|
|
1183
|
+
status: res.status,
|
|
1184
|
+
exitCode: res.exitCode,
|
|
1185
|
+
output: res.output || `(no new output; waitReason=${res.waitReason})`
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
if (action === 'read') {
|
|
1190
|
+
const res = ptyTerminalManager.readScrollback(sessionId, {
|
|
1191
|
+
tailChars: args.tailChars,
|
|
1192
|
+
offsetFromEnd: args.offsetFromEnd
|
|
1193
|
+
});
|
|
1194
|
+
if (!res.ok) return { success: false, error: `Terminal session "${sessionId}" not found.` };
|
|
1195
|
+
return {
|
|
1196
|
+
success: true,
|
|
1197
|
+
status: res.status,
|
|
1198
|
+
exitCode: res.exitCode,
|
|
1199
|
+
control: res.control,
|
|
1200
|
+
totalChars: res.totalChars,
|
|
1201
|
+
output: res.text || '(empty scrollback)'
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
if (action === 'signal') {
|
|
1206
|
+
const sig = args.signal ?? 'SIGINT';
|
|
1207
|
+
const res = ptyTerminalManager.signalSession(sessionId, sig, 'agent');
|
|
1208
|
+
if (!res.ok) return { success: false, error: res.error || 'Failed to deliver signal.', code: res.code };
|
|
1209
|
+
return { success: true, output: `Sent ${sig} to terminal session ${sessionId}.` };
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
if (action === 'resize') {
|
|
1213
|
+
const ok = ptyTerminalManager.resizeSession(sessionId, args.cols ?? 100, args.rows ?? 28);
|
|
1214
|
+
return ok
|
|
1215
|
+
? { success: true, output: `Resized terminal session ${sessionId}.` }
|
|
1216
|
+
: { success: false, error: `Unable to resize terminal session "${sessionId}".` };
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
if (action === 'close') {
|
|
1220
|
+
const closed = ptyTerminalManager.closeSession(sessionId);
|
|
1221
|
+
return closed
|
|
1222
|
+
? { success: true, output: `Closed terminal session ${sessionId}.` }
|
|
1223
|
+
: { success: false, error: `Terminal session "${sessionId}" not found.` };
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
return { success: false, error: `Unknown terminal.pty action: ${String(action)}` };
|
|
1227
|
+
} catch (error) {
|
|
1228
|
+
return { success: false, error: sanitizeToolError(error) };
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
};
|