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