@causyne/agent 1.20.124 → 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.
Files changed (235) hide show
  1. package/bin/causyne.js +1 -1
  2. package/package.json +4 -4
  3. package/src/acp/protocol.ts +19 -1
  4. package/src/acp/server.js +282 -8
  5. package/src/acp/server.ts +284 -8
  6. package/src/agent/abortableDelay.js +2 -2
  7. package/src/agent/abortableDelay.ts +2 -2
  8. package/src/agent/errorClassifier.js +9 -1
  9. package/src/agent/errorClassifier.ts +8 -1
  10. package/src/agentLoop.js +83 -27
  11. package/src/agentLoop.ts +92 -26
  12. package/src/approvalPolicy.js +34 -10
  13. package/src/approvalPolicy.ts +42 -11
  14. package/src/browser/causyneBrowser.js +30 -3
  15. package/src/browser/causyneBrowser.ts +33 -3
  16. package/src/browser/urlPolicy.js +14 -1
  17. package/src/browser/urlPolicy.ts +12 -1
  18. package/src/cliMode.js +21 -9
  19. package/src/cliMode.ts +20 -8
  20. package/src/commands.js +188 -32
  21. package/src/commands.ts +209 -32
  22. package/src/config.js +19 -4
  23. package/src/config.ts +18 -4
  24. package/src/core/contextCompactor.js +54 -7
  25. package/src/core/contextCompactor.ts +63 -7
  26. package/src/core/goalLoop.js +257 -0
  27. package/src/core/goalLoop.ts +310 -0
  28. package/src/entrypoint.js +135 -3
  29. package/src/entrypoint.ts +136 -3
  30. package/src/game/causyneCoreBridge.js +686 -0
  31. package/src/game/causyneCoreBridge.ts +702 -0
  32. package/src/game/gameLauncher.js +287 -0
  33. package/src/game/gameLauncher.ts +352 -0
  34. package/src/game/gameProvisioner.js +425 -0
  35. package/src/game/gameProvisioner.ts +488 -0
  36. package/src/headlessCli.js +19 -12
  37. package/src/headlessCli.ts +22 -8
  38. package/src/infra/atomicWriter.js +40 -4
  39. package/src/infra/atomicWriter.ts +36 -4
  40. package/src/launchIntent.js +73 -3
  41. package/src/launchIntent.ts +76 -3
  42. package/src/lsp/lspClient.js +83 -12
  43. package/src/lsp/lspClient.ts +75 -12
  44. package/src/mcp/mcpRegistry.js +75 -8
  45. package/src/mcp/mcpRegistry.ts +70 -7
  46. package/src/memory/contextBudget.js +2 -0
  47. package/src/memory/contextBudget.ts +1 -0
  48. package/src/modelVariants.js +45 -0
  49. package/src/modelVariants.ts +54 -0
  50. package/src/outputRecovery.js +3 -2
  51. package/src/outputRecovery.ts +4 -2
  52. package/src/permissionPresets.js +327 -0
  53. package/src/permissionPresets.ts +361 -0
  54. package/src/providers/antigravity.js +62 -9
  55. package/src/providers/antigravity.ts +73 -9
  56. package/src/providers/byokHttp.js +7 -1
  57. package/src/providers/byokHttp.ts +6 -1
  58. package/src/providers/byokStream.js +21 -8
  59. package/src/providers/byokStream.ts +17 -7
  60. package/src/providers/dashscope-byok.js +21 -5
  61. package/src/providers/dashscope-byok.ts +29 -11
  62. package/src/providers/moonshot.js +26 -7
  63. package/src/providers/moonshot.ts +34 -13
  64. package/src/providers/muse.js +6 -0
  65. package/src/providers/muse.ts +8 -0
  66. package/src/providers/ollama.js +39 -7
  67. package/src/providers/ollama.ts +36 -7
  68. package/src/providers/openai-compatible.js +16 -3
  69. package/src/providers/openai-compatible.ts +13 -3
  70. package/src/providers/openai.js +62 -4
  71. package/src/providers/openai.ts +50 -4
  72. package/src/providers/openrouter.js +19 -4
  73. package/src/providers/openrouter.ts +21 -4
  74. package/src/providers/qwen-byok.js +21 -5
  75. package/src/providers/qwen-byok.ts +29 -11
  76. package/src/providers/xai.js +26 -10
  77. package/src/providers/xai.ts +34 -16
  78. package/src/reporting.js +4 -2
  79. package/src/reporting.ts +4 -2
  80. package/src/sandbox.js +34 -0
  81. package/src/sandbox.ts +43 -0
  82. package/src/scheduler/scheduler.js +372 -0
  83. package/src/scheduler/scheduler.ts +433 -0
  84. package/src/sessionSearchIndex.js +267 -0
  85. package/src/sessionSearchIndex.ts +311 -0
  86. package/src/skillsManager.js +2 -3
  87. package/src/skillsManager.ts +2 -3
  88. package/src/toolPacks.js +6 -0
  89. package/src/toolPacks.ts +6 -0
  90. package/src/tools/applyPatch.js +1 -1
  91. package/src/tools/applyPatch.ts +1 -1
  92. package/src/tools/generateMediaViaApi.js +4 -3
  93. package/src/tools/generateMediaViaApi.ts +4 -3
  94. package/src/tools/nativeEngine.js +2 -2
  95. package/src/tools/nativeEngine.ts +2 -2
  96. package/src/tools/openSourceToolProvisioner.js +2 -2
  97. package/src/tools/openSourceToolProvisioner.ts +2 -2
  98. package/src/tools/payloadSanitizer.js +0 -1
  99. package/src/tools/payloadSanitizer.ts +0 -1
  100. package/src/tools/pdfReader.js +122 -20
  101. package/src/tools/pdfReader.ts +111 -20
  102. package/src/tools/presentDeliverable.js +103 -0
  103. package/src/tools/presentDeliverable.ts +127 -0
  104. package/src/tools/ptcRuntime.js +444 -0
  105. package/src/tools/ptcRuntime.ts +490 -0
  106. package/src/tools/ptyTerminal.js +1096 -0
  107. package/src/tools/ptyTerminal.ts +1231 -0
  108. package/src/tools/registry.js +21 -12
  109. package/src/tools/registry.ts +21 -12
  110. package/src/tools/toolOutputStore.js +26 -4
  111. package/src/tools/toolOutputStore.ts +22 -4
  112. package/src/tools/webFetch.js +158 -11
  113. package/src/tools/webFetch.ts +145 -11
  114. package/src/tools/webSearch.js +123 -36
  115. package/src/tools/webSearch.ts +124 -33
  116. package/src/tui/banner.js +5 -1
  117. package/src/tui/banner.ts +6 -1
  118. package/src/tui/chatRenderer.js +1 -2
  119. package/src/tui/chatRenderer.ts +1 -2
  120. package/src/tui/completion.js +1 -0
  121. package/src/tui/completion.ts +1 -0
  122. package/src/tui/composerControls.js +111 -27
  123. package/src/tui/composerControls.ts +124 -28
  124. package/src/tui/dialogs.js +3 -16
  125. package/src/tui/dialogs.ts +3 -16
  126. package/src/tui/home.js +1 -0
  127. package/src/tui/home.ts +1 -0
  128. package/src/tui/invocation.js +1 -2
  129. package/src/tui/invocation.ts +1 -2
  130. package/src/tui/modelPicker.js +22 -12
  131. package/src/tui/modelPicker.ts +22 -12
  132. package/src/tui/overlay.js +2 -5
  133. package/src/tui/overlay.ts +2 -5
  134. package/src/tui/prompt.js +6 -4
  135. package/src/tui/prompt.ts +6 -4
  136. package/src/tui/selectList.js +4 -12
  137. package/src/tui/selectList.ts +4 -12
  138. package/src/tui/setup.js +22 -9
  139. package/src/tui/setup.ts +26 -9
  140. package/src/tui/statusLine.ts +2 -0
  141. package/src/web/client/browserPanel.js +702 -0
  142. package/src/web/client/browserPanel.ts +663 -0
  143. package/src/web/client/chatStream.js +309 -0
  144. package/src/web/client/chatStream.ts +289 -0
  145. package/src/web/client/cliPanel.js +165 -0
  146. package/src/web/client/cliPanel.ts +171 -0
  147. package/src/web/client/composer.js +204 -0
  148. package/src/web/client/composer.ts +209 -0
  149. package/src/web/client/diffPanel.js +176 -0
  150. package/src/web/client/diffPanel.ts +203 -0
  151. package/src/web/client/dom.js +220 -0
  152. package/src/web/client/dom.ts +221 -0
  153. package/src/web/client/filesAndCanvas.js +231 -0
  154. package/src/web/client/filesAndCanvas.ts +238 -0
  155. package/src/web/client/gameLauncherUi.js +78 -0
  156. package/src/web/client/gameLauncherUi.ts +78 -0
  157. package/src/web/client/main.js +301 -0
  158. package/src/web/client/main.ts +368 -0
  159. package/src/web/client/markdown.js +364 -0
  160. package/src/web/client/markdown.ts +373 -0
  161. package/src/web/client/modelPicker.js +455 -0
  162. package/src/web/client/modelPicker.ts +451 -0
  163. package/src/web/client/permissionPresetsUi.js +307 -0
  164. package/src/web/client/permissionPresetsUi.ts +333 -0
  165. package/src/web/client/sessions.js +353 -0
  166. package/src/web/client/sessions.ts +372 -0
  167. package/src/web/client/settingsModal.js +191 -0
  168. package/src/web/client/settingsModal.ts +176 -0
  169. package/src/web/client/state.js +250 -0
  170. package/src/web/client/state.ts +233 -0
  171. package/src/web/client/streamSmoother.js +127 -0
  172. package/src/web/client/streamSmoother.ts +119 -0
  173. package/src/web/client/studioLayout.js +54 -0
  174. package/src/web/client/studioLayout.ts +60 -0
  175. package/src/web/client/studioShell.js +327 -0
  176. package/src/web/client/studioShell.ts +340 -0
  177. package/src/web/client/studioStart.js +77 -0
  178. package/src/web/client/studioStart.ts +89 -0
  179. package/src/web/client/terminalPanel.js +357 -0
  180. package/src/web/client/terminalPanel.ts +345 -0
  181. package/src/web/client/turnView.js +934 -0
  182. package/src/web/client/turnView.ts +981 -0
  183. package/src/web/client/types.js +1 -0
  184. package/src/web/client/types.ts +319 -0
  185. package/src/web/client/validators.js +106 -0
  186. package/src/web/client/validators.ts +96 -0
  187. package/src/web/server/activeRuns.js +152 -0
  188. package/src/web/server/activeRuns.ts +171 -0
  189. package/src/web/server/routesBrowser.js +355 -0
  190. package/src/web/server/routesBrowser.ts +386 -0
  191. package/src/web/server/routesChat.js +304 -0
  192. package/src/web/server/routesChat.ts +347 -0
  193. package/src/web/server/routesCore.js +472 -0
  194. package/src/web/server/routesCore.ts +522 -0
  195. package/src/web/server/routesTerminal.js +162 -0
  196. package/src/web/server/routesTerminal.ts +182 -0
  197. package/src/web/server/routesWorkspace.js +510 -0
  198. package/src/web/server/routesWorkspace.ts +546 -0
  199. package/src/web/server/security.js +98 -0
  200. package/src/web/server/security.ts +108 -0
  201. package/src/web/server/sessionTranscript.js +586 -0
  202. package/src/web/server/sessionTranscript.ts +566 -0
  203. package/src/web/server/staticAssets.js +80 -0
  204. package/src/web/server/staticAssets.ts +91 -0
  205. package/src/web/server/types.js +1 -0
  206. package/src/web/server/types.ts +135 -0
  207. package/src/web/server/workspaceFiles.js +368 -0
  208. package/src/web/server/workspaceFiles.ts +363 -0
  209. package/src/web/skybridgeServer.js +76 -2449
  210. package/src/web/skybridgeServer.ts +118 -2600
  211. package/src/web/skybridgeUi.js +16 -450
  212. package/src/web/skybridgeUi.ts +16 -454
  213. package/src/web/styles/agent.css +380 -0
  214. package/src/web/styles/composer.css +193 -0
  215. package/src/web/styles/overlays.css +436 -0
  216. package/src/web/styles/shell.css +387 -0
  217. package/src/web/styles/studio.css +723 -0
  218. package/src/web/styles/thread.css +221 -0
  219. package/src/web/styles/tokens.css +94 -0
  220. package/src/web/ui/brandMark.js +73 -0
  221. package/src/web/ui/brandMark.ts +82 -0
  222. package/src/web/ui/modalsTemplate.js +139 -0
  223. package/src/web/ui/modalsTemplate.ts +139 -0
  224. package/src/web/ui/sidebarTemplate.js +63 -0
  225. package/src/web/ui/sidebarTemplate.ts +64 -0
  226. package/src/web/ui/studioTemplate.js +258 -0
  227. package/src/web/ui/studioTemplate.ts +258 -0
  228. package/src/web/ui/workspaceTemplate.js +72 -0
  229. package/src/web/ui/workspaceTemplate.ts +73 -0
  230. package/src/worktreeManager.js +16 -1
  231. package/src/worktreeManager.ts +22 -1
  232. package/src/web/skybridgeClientScript.js +0 -3951
  233. package/src/web/skybridgeClientScript.ts +0 -3952
  234. package/src/web/skybridgeStyles.js +0 -827
  235. package/src/web/skybridgeStyles.ts +0 -828
@@ -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
+ };