@wonderwhy-er/desktop-commander 0.2.52 → 0.3.0
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/dist/command-manager.d.ts +7 -2
- package/dist/command-manager.js +16 -11
- package/dist/config-manager.d.ts +55 -3
- package/dist/config-manager.js +329 -87
- package/dist/config-recovery.d.ts +28 -0
- package/dist/config-recovery.js +81 -0
- package/dist/config.d.ts +1 -0
- package/dist/config.js +9 -0
- package/dist/handlers/filesystem-handlers.d.ts +1 -1
- package/dist/handlers/filesystem-handlers.js +26 -16
- package/dist/handlers/search-answers.d.ts +58 -0
- package/dist/handlers/search-answers.js +172 -0
- package/dist/handlers/search-handlers.js +4 -92
- package/dist/index.js +14 -7
- package/dist/npm-scripts/remote.js +17 -3
- package/dist/remote-device/desktop-commander-integration.d.ts +1 -0
- package/dist/remote-device/desktop-commander-integration.js +19 -25
- package/dist/remote-device/device.d.ts +14 -0
- package/dist/remote-device/device.js +137 -30
- package/dist/remote-device/diagnostics/device-log.d.ts +63 -0
- package/dist/remote-device/diagnostics/device-log.js +219 -0
- package/dist/remote-device/diagnostics/redact.d.ts +1 -0
- package/dist/remote-device/diagnostics/redact.js +76 -0
- package/dist/remote-device/diagnostics/report.d.ts +118 -0
- package/dist/remote-device/diagnostics/report.js +748 -0
- package/dist/remote-device/diagnostics/upload.d.ts +11 -0
- package/dist/remote-device/diagnostics/upload.js +59 -0
- package/dist/remote-device/realtime-health-telemetry.d.ts +35 -0
- package/dist/remote-device/realtime-health-telemetry.js +110 -0
- package/dist/remote-device/remote-channel.d.ts +36 -4
- package/dist/remote-device/remote-channel.js +230 -50
- package/dist/remote-device/scripts/blocking-offline-update.js +108 -69
- package/dist/remote-device/transport-telemetry.d.ts +32 -0
- package/dist/remote-device/transport-telemetry.js +48 -0
- package/dist/search-manager.d.ts +239 -27
- package/dist/search-manager.js +746 -312
- package/dist/server.js +124 -222
- package/dist/terminal-manager.d.ts +138 -21
- package/dist/terminal-manager.js +300 -215
- package/dist/tools/config.d.ts +1 -1
- package/dist/tools/config.js +21 -70
- package/dist/tools/edit.js +12 -4
- package/dist/tools/filesystem.d.ts +30 -6
- package/dist/tools/filesystem.js +246 -140
- package/dist/tools/improved-process-tools.d.ts +9 -3
- package/dist/tools/improved-process-tools.js +171 -68
- package/dist/tools/pdf/extract-images.d.ts +2 -0
- package/dist/tools/pdf/extract-images.js +4 -1
- package/dist/tools/pdf/index.d.ts +5 -3
- package/dist/tools/pdf/index.js +4 -3
- package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
- package/dist/tools/pdf/lib/pdf2md.js +12 -5
- package/dist/tools/pdf/manipulations.d.ts +12 -1
- package/dist/tools/pdf/manipulations.js +17 -4
- package/dist/tools/pdf/markdown.d.ts +96 -0
- package/dist/tools/pdf/markdown.js +485 -20
- package/dist/tools/pdf/utils.d.ts +2 -2
- package/dist/tools/pdf/utils.js +4 -4
- package/dist/tools/process.js +8 -5
- package/dist/tools/schemas.d.ts +1 -11
- package/dist/tools/schemas.js +15 -14
- package/dist/types.d.ts +1 -1
- package/dist/ui/config-editor/config-editor-runtime.js +53 -53
- package/dist/ui/config-editor/src/app.js +2 -15
- package/dist/ui/file-preview/preview-runtime.js +190 -182
- package/dist/utils/ab-test.js +27 -9
- package/dist/utils/atomic-write.d.ts +14 -0
- package/dist/utils/atomic-write.js +80 -0
- package/dist/utils/capture.d.ts +17 -1
- package/dist/utils/capture.js +177 -68
- package/dist/utils/exit-process.d.ts +24 -0
- package/dist/utils/exit-process.js +31 -0
- package/dist/utils/feature-flags.js +2 -1
- package/dist/utils/files/base.d.ts +3 -1
- package/dist/utils/files/docx.d.ts +3 -0
- package/dist/utils/files/docx.js +24 -9
- package/dist/utils/files/excel.d.ts +10 -0
- package/dist/utils/files/excel.js +93 -33
- package/dist/utils/files/factory.d.ts +22 -1
- package/dist/utils/files/factory.js +59 -4
- package/dist/utils/files/image.d.ts +12 -4
- package/dist/utils/files/image.js +19 -8
- package/dist/utils/files/index.d.ts +5 -3
- package/dist/utils/files/index.js +4 -3
- package/dist/utils/files/pdf.js +18 -36
- package/dist/utils/files/text.d.ts +21 -5
- package/dist/utils/files/text.js +90 -86
- package/dist/utils/internal-facts.d.ts +3 -0
- package/dist/utils/internal-facts.js +23 -0
- package/dist/utils/lazy-package.d.ts +25 -0
- package/dist/utils/lazy-package.js +44 -0
- package/dist/utils/open-browser.js +2 -1
- package/dist/utils/process-detection.d.ts +24 -5
- package/dist/utils/process-detection.js +199 -89
- package/dist/utils/process-tree.d.ts +14 -0
- package/dist/utils/process-tree.js +223 -0
- package/dist/utils/rename.d.ts +9 -0
- package/dist/utils/rename.js +74 -0
- package/dist/utils/ripgrep-resolver.js +9 -14
- package/dist/utils/shell.d.ts +42 -0
- package/dist/utils/shell.js +187 -0
- package/dist/utils/system-info.d.ts +1 -0
- package/dist/utils/system-info.js +40 -25
- package/dist/utils/trackTools.js +2 -1
- package/dist/utils/usageTracker.d.ts +0 -39
- package/dist/utils/usageTracker.js +1 -161
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
- package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
- package/package.json +32 -16
- package/vendor/telemetry-contract/README.md +56 -0
- package/vendor/telemetry-contract/package.json +32 -0
- package/vendor/telemetry-contract/transport.d.ts +38 -0
- package/vendor/telemetry-contract/transport.js +164 -0
- package/vendor/telemetry-contract/transport.test.js +39 -0
package/dist/terminal-manager.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { spawn } from 'child_process';
|
|
2
|
-
import
|
|
3
|
-
import { DEFAULT_COMMAND_TIMEOUT } from './config.js';
|
|
2
|
+
import { DEFAULT_COMMAND_TIMEOUT, MAX_PROCESS_WAIT_MS } from './config.js';
|
|
4
3
|
import { configManager } from './config-manager.js';
|
|
5
4
|
import { capture } from "./utils/capture.js";
|
|
6
|
-
import { analyzeProcessState } from './utils/process-detection.js';
|
|
5
|
+
import { analyzeProcessState, STATE_DETECTION_TAIL_CHARS } from './utils/process-detection.js';
|
|
6
|
+
import { getDefaultShell, getShellSpawnArgs } from './utils/shell.js';
|
|
7
|
+
import { terminateProcessTree } from './utils/process-tree.js';
|
|
7
8
|
/**
|
|
8
9
|
* Standard Windows PATHEXT value, used to repair a corrupted PATHEXT before
|
|
9
10
|
* spawning child shells.
|
|
@@ -32,76 +33,35 @@ function getRepairedPathExt() {
|
|
|
32
33
|
}
|
|
33
34
|
return current;
|
|
34
35
|
}
|
|
36
|
+
const OUTPUT_STREAMS = ['stdout', 'stderr'];
|
|
37
|
+
function newStreamTails() {
|
|
38
|
+
return { stdout: { text: '', chars: 0, turn: 0 }, stderr: { text: '', chars: 0, turn: 0 } };
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The one place that turns a caller's timeout_ms into the time a process wait
|
|
42
|
+
* may actually block. When `capped`, the call returns at the ceiling with the
|
|
43
|
+
* process still running and the caller continues with read_process_output.
|
|
44
|
+
*/
|
|
45
|
+
export function getProcessWaitLimit(timeoutMs, capMs = MAX_PROCESS_WAIT_MS) {
|
|
46
|
+
return { waitMs: Math.min(timeoutMs, capMs), capMs, capped: timeoutMs > capMs };
|
|
47
|
+
}
|
|
35
48
|
/**
|
|
36
49
|
* Output buffering caps. Without a cap, a process emitting enough output makes
|
|
37
50
|
* string concatenation throw "RangeError: Invalid string length" at V8's max
|
|
38
51
|
* string size (~536M chars) inside a stdout 'data' handler — an uncaught
|
|
39
52
|
* exception that kills the whole server (index.ts exits on uncaughtException).
|
|
40
|
-
* The cap also bounds the
|
|
41
|
-
*
|
|
53
|
+
* The cap also bounds the cost of the reads that are O(total output), such as
|
|
54
|
+
* since-start snapshot reads.
|
|
42
55
|
*/
|
|
43
56
|
export const MAX_BUFFERED_OUTPUT_CHARS = 50 * 1024 * 1024; // per session; oldest lines evicted first
|
|
44
57
|
const MAX_LINE_CHARS = 1024 * 1024; // force-split longer lines so eviction can work
|
|
45
|
-
const MAX_WAIT_OUTPUT_CHARS = 2 * 1024 * 1024; // start_process wait buffer (
|
|
46
|
-
/**
|
|
47
|
-
* Get the appropriate spawn configuration for a given shell
|
|
48
|
-
* This handles login shell flags for different shell types
|
|
49
|
-
*/
|
|
50
|
-
function getShellSpawnArgs(shellPath, command) {
|
|
51
|
-
const shellName = path.basename(shellPath).toLowerCase();
|
|
52
|
-
// Unix shells with login flag support
|
|
53
|
-
if (shellName.includes('bash') || shellName.includes('zsh')) {
|
|
54
|
-
return {
|
|
55
|
-
executable: shellPath,
|
|
56
|
-
args: ['-l', '-c', command],
|
|
57
|
-
useShellOption: false
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
// PowerShell Core (cross-platform, supports -Login)
|
|
61
|
-
if (shellName === 'pwsh' || shellName === 'pwsh.exe') {
|
|
62
|
-
return {
|
|
63
|
-
executable: shellPath,
|
|
64
|
-
args: ['-Login', '-Command', command],
|
|
65
|
-
useShellOption: false
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
// Windows PowerShell 5.1 (no login flag support)
|
|
69
|
-
if (shellName === 'powershell' || shellName === 'powershell.exe') {
|
|
70
|
-
return {
|
|
71
|
-
executable: shellPath,
|
|
72
|
-
args: ['-Command', command],
|
|
73
|
-
useShellOption: false
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
// CMD
|
|
77
|
-
if (shellName === 'cmd' || shellName === 'cmd.exe') {
|
|
78
|
-
return {
|
|
79
|
-
executable: shellPath,
|
|
80
|
-
args: ['/c', command],
|
|
81
|
-
windowsVerbatim: true,
|
|
82
|
-
useShellOption: false
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
// Fish shell (uses -l for login, -c for command)
|
|
86
|
-
if (shellName.includes('fish')) {
|
|
87
|
-
return {
|
|
88
|
-
executable: shellPath,
|
|
89
|
-
args: ['-l', '-c', command],
|
|
90
|
-
useShellOption: false
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
// Unknown/other shells - use shell option for safety
|
|
94
|
-
// This provides a fallback for shells we don't explicitly handle
|
|
95
|
-
return {
|
|
96
|
-
executable: command,
|
|
97
|
-
args: [],
|
|
98
|
-
useShellOption: shellPath
|
|
99
|
-
};
|
|
100
|
-
}
|
|
58
|
+
const MAX_WAIT_OUTPUT_CHARS = 2 * 1024 * 1024; // start_process wait buffer (the initial output it returns)
|
|
101
59
|
export class TerminalManager {
|
|
102
60
|
constructor() {
|
|
103
61
|
this.sessions = new Map();
|
|
104
62
|
this.completedSessions = new Map();
|
|
63
|
+
this.deliveryTurn = 0;
|
|
64
|
+
this.deliveryTurnOpen = false;
|
|
105
65
|
}
|
|
106
66
|
/**
|
|
107
67
|
* Send input to a running process
|
|
@@ -128,19 +88,17 @@ export class TerminalManager {
|
|
|
128
88
|
return false;
|
|
129
89
|
}
|
|
130
90
|
}
|
|
131
|
-
async executeCommand(command, timeoutMs = DEFAULT_COMMAND_TIMEOUT, shell, collectTiming = false) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
}
|
|
139
|
-
catch (error) {
|
|
140
|
-
// If there's an error getting the config, fall back to default
|
|
141
|
-
shellToUse = true;
|
|
142
|
-
}
|
|
91
|
+
async executeCommand(command, timeoutMs = DEFAULT_COMMAND_TIMEOUT, shell, collectTiming = false, maxWaitMs = MAX_PROCESS_WAIT_MS) {
|
|
92
|
+
let config = {};
|
|
93
|
+
try {
|
|
94
|
+
config = await configManager.getConfig();
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
// If there's an error getting the config, fall back to the default shell
|
|
143
98
|
}
|
|
99
|
+
// Get the shell from config if not specified
|
|
100
|
+
const shellToUse = shell || config.defaultShell || getDefaultShell();
|
|
101
|
+
const waitLimit = getProcessWaitLimit(timeoutMs, maxWaitMs);
|
|
144
102
|
// For REPL interactions, we need to ensure stdin, stdout, and stderr are properly configured
|
|
145
103
|
// Note: No special stdio options needed here, Node.js handles pipes by default
|
|
146
104
|
// Enhance SSH commands automatically
|
|
@@ -149,39 +107,18 @@ export class TerminalManager {
|
|
|
149
107
|
enhancedCommand = command.replace(/^ssh /, 'ssh -t ');
|
|
150
108
|
console.log(`Enhanced SSH command: ${enhancedCommand}`);
|
|
151
109
|
}
|
|
152
|
-
// Get the appropriate spawn configuration for the shell
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
};
|
|
165
|
-
// Add shell option if needed (for unknown shells)
|
|
166
|
-
if (spawnConfig.useShellOption) {
|
|
167
|
-
spawnOptions.shell = spawnConfig.useShellOption;
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
else {
|
|
171
|
-
// Boolean or undefined shell - use default shell option behavior
|
|
172
|
-
spawnConfig = {
|
|
173
|
-
executable: enhancedCommand,
|
|
174
|
-
args: [],
|
|
175
|
-
useShellOption: shellToUse
|
|
176
|
-
};
|
|
177
|
-
spawnOptions = {
|
|
178
|
-
shell: shellToUse,
|
|
179
|
-
env: {
|
|
180
|
-
...process.env,
|
|
181
|
-
TERM: 'xterm-256color'
|
|
182
|
-
},
|
|
183
|
-
windowsHide: true // Prevent visible console windows on Windows
|
|
184
|
-
};
|
|
110
|
+
// Get the appropriate spawn configuration for the shell, with login flags where appropriate
|
|
111
|
+
const spawnConfig = getShellSpawnArgs(shellToUse, enhancedCommand);
|
|
112
|
+
const spawnOptions = {
|
|
113
|
+
env: {
|
|
114
|
+
...process.env,
|
|
115
|
+
TERM: 'xterm-256color' // Better terminal compatibility
|
|
116
|
+
},
|
|
117
|
+
windowsHide: true // Prevent visible console windows on Windows
|
|
118
|
+
};
|
|
119
|
+
// Add shell option if needed (for unknown shells)
|
|
120
|
+
if (spawnConfig.useShellOption) {
|
|
121
|
+
spawnOptions.shell = spawnConfig.useShellOption;
|
|
185
122
|
}
|
|
186
123
|
// Repair PATHEXT on Windows before spawning. On some Windows DXT launches
|
|
187
124
|
// the server process inherits a corrupted PATHEXT (e.g. ".CPL"), which we
|
|
@@ -228,10 +165,12 @@ export class TerminalManager {
|
|
|
228
165
|
// Ensure childProcess.pid is defined before proceeding
|
|
229
166
|
if (!childProcess.pid) {
|
|
230
167
|
// Return a consistent error object instead of throwing
|
|
168
|
+
const output = 'Error: Failed to get process ID. The command could not be executed.';
|
|
231
169
|
return {
|
|
232
170
|
pid: -1, // Use -1 to indicate an error state
|
|
233
|
-
output
|
|
234
|
-
isBlocked: false
|
|
171
|
+
output,
|
|
172
|
+
isBlocked: false,
|
|
173
|
+
processState: analyzeProcessState(output)
|
|
235
174
|
};
|
|
236
175
|
}
|
|
237
176
|
const session = {
|
|
@@ -239,11 +178,12 @@ export class TerminalManager {
|
|
|
239
178
|
process: childProcess,
|
|
240
179
|
outputLines: [], // Line-based buffer
|
|
241
180
|
lastReadIndex: 0, // Track where "new" output starts
|
|
242
|
-
|
|
181
|
+
lastReadOpenLine: '',
|
|
243
182
|
startTime: new Date(),
|
|
244
183
|
bufferedChars: 0,
|
|
245
184
|
evictedLines: 0,
|
|
246
|
-
evictedChars: 0
|
|
185
|
+
evictedChars: 0,
|
|
186
|
+
streams: newStreamTails()
|
|
247
187
|
};
|
|
248
188
|
this.sessions.set(childProcess.pid, session);
|
|
249
189
|
// Timing telemetry
|
|
@@ -255,14 +195,26 @@ export class TerminalManager {
|
|
|
255
195
|
return new Promise((resolve) => {
|
|
256
196
|
let resolved = false;
|
|
257
197
|
let periodicCheck = null;
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
198
|
+
let waitTimer = null;
|
|
199
|
+
// Whether the process waits for input, judged as the periodic check does:
|
|
200
|
+
// from the end of each output stream, not from the chunk that just came
|
|
201
|
+
// (a chunk can end in the middle of a line, e.g. right after "<div>").
|
|
202
|
+
const waitingForInput = () => this.getProcessState(childProcess.pid)?.isWaitingForInput === true;
|
|
203
|
+
const resolveOnce = (waitResult) => {
|
|
261
204
|
if (resolved)
|
|
262
205
|
return;
|
|
263
206
|
resolved = true;
|
|
264
207
|
if (periodicCheck)
|
|
265
208
|
clearInterval(periodicCheck);
|
|
209
|
+
if (waitTimer)
|
|
210
|
+
clearTimeout(waitTimer);
|
|
211
|
+
// The state the wait ended in, from the session: finished if the
|
|
212
|
+
// process exited, else judged from its output. A process error after
|
|
213
|
+
// the exit leaves no session behind, so the text it returns is judged.
|
|
214
|
+
const result = {
|
|
215
|
+
...waitResult,
|
|
216
|
+
processState: this.getProcessState(childProcess.pid) ?? analyzeProcessState(waitResult.output)
|
|
217
|
+
};
|
|
266
218
|
// Add timing info if requested
|
|
267
219
|
if (collectTiming) {
|
|
268
220
|
const endTime = Date.now();
|
|
@@ -279,11 +231,15 @@ export class TerminalManager {
|
|
|
279
231
|
}
|
|
280
232
|
resolve(result);
|
|
281
233
|
};
|
|
282
|
-
// Now that resolveOnce exists, route process errors into it
|
|
283
|
-
//
|
|
284
|
-
//
|
|
234
|
+
// Now that resolveOnce exists, route process errors into it, so the caller
|
|
235
|
+
// doesn't sit waiting for output. The session goes only if the process
|
|
236
|
+
// has exited: Node also emits 'error' when a kill fails or a message can't
|
|
237
|
+
// be sent, and the process runs on. It then stays listed, readable and
|
|
238
|
+
// terminable, and its 'exit' records the completion as usual.
|
|
285
239
|
forwardProcessError = (err) => {
|
|
286
|
-
|
|
240
|
+
if (childProcess.exitCode !== null || childProcess.signalCode !== null) {
|
|
241
|
+
this.sessions.delete(childProcess.pid);
|
|
242
|
+
}
|
|
287
243
|
exitReason = 'process_exit';
|
|
288
244
|
resolveOnce({
|
|
289
245
|
pid: childProcess.pid,
|
|
@@ -302,16 +258,15 @@ export class TerminalManager {
|
|
|
302
258
|
if (!firstOutputTime)
|
|
303
259
|
firstOutputTime = now;
|
|
304
260
|
lastOutputTime = now;
|
|
305
|
-
// `output` only feeds the wait-phase result
|
|
306
|
-
//
|
|
261
|
+
// `output` only feeds the wait-phase result, so stop growing it once
|
|
262
|
+
// resolved and keep only a bounded tail.
|
|
307
263
|
if (!resolved) {
|
|
308
264
|
output += text;
|
|
309
265
|
if (output.length > MAX_WAIT_OUTPUT_CHARS) {
|
|
310
266
|
output = output.slice(-Math.floor(MAX_WAIT_OUTPUT_CHARS / 2));
|
|
311
267
|
}
|
|
312
268
|
}
|
|
313
|
-
|
|
314
|
-
this.appendToLineBuffer(session, text);
|
|
269
|
+
this.recordOutput(session, 'stdout', text);
|
|
315
270
|
// Record output event if collecting timing
|
|
316
271
|
if (collectTiming) {
|
|
317
272
|
outputEvents.push({
|
|
@@ -322,9 +277,8 @@ export class TerminalManager {
|
|
|
322
277
|
snippet: text.slice(0, 50).replace(/\n/g, '\\n')
|
|
323
278
|
});
|
|
324
279
|
}
|
|
325
|
-
// Immediate check for
|
|
326
|
-
if (
|
|
327
|
-
session.isBlocked = true;
|
|
280
|
+
// Immediate check for a prompt
|
|
281
|
+
if (waitingForInput()) {
|
|
328
282
|
exitReason = 'early_exit_quick_pattern';
|
|
329
283
|
if (collectTiming && outputEvents.length > 0) {
|
|
330
284
|
outputEvents[outputEvents.length - 1].matchedPattern = 'quick_pattern';
|
|
@@ -348,8 +302,7 @@ export class TerminalManager {
|
|
|
348
302
|
output = output.slice(-Math.floor(MAX_WAIT_OUTPUT_CHARS / 2));
|
|
349
303
|
}
|
|
350
304
|
}
|
|
351
|
-
|
|
352
|
-
this.appendToLineBuffer(session, text);
|
|
305
|
+
this.recordOutput(session, 'stderr', text);
|
|
353
306
|
// Record output event if collecting timing
|
|
354
307
|
if (collectTiming) {
|
|
355
308
|
outputEvents.push({
|
|
@@ -363,40 +316,34 @@ export class TerminalManager {
|
|
|
363
316
|
});
|
|
364
317
|
// Periodic comprehensive check every 100ms
|
|
365
318
|
periodicCheck = setInterval(() => {
|
|
366
|
-
if (
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
output,
|
|
374
|
-
isBlocked: true
|
|
375
|
-
});
|
|
376
|
-
}
|
|
319
|
+
if (waitingForInput()) {
|
|
320
|
+
exitReason = 'early_exit_periodic_check';
|
|
321
|
+
resolveOnce({
|
|
322
|
+
pid: childProcess.pid,
|
|
323
|
+
output,
|
|
324
|
+
isBlocked: true
|
|
325
|
+
});
|
|
377
326
|
}
|
|
378
327
|
}, 100);
|
|
379
|
-
// Timeout fallback
|
|
380
|
-
|
|
381
|
-
|
|
328
|
+
// Timeout fallback, bounded by the wait ceiling so the call returns
|
|
329
|
+
// before the MCP client gives up on it; the process keeps running.
|
|
330
|
+
waitTimer = setTimeout(() => {
|
|
382
331
|
exitReason = 'timeout';
|
|
383
332
|
resolveOnce({
|
|
384
333
|
pid: childProcess.pid,
|
|
385
334
|
output,
|
|
386
|
-
isBlocked: true
|
|
335
|
+
isBlocked: true,
|
|
336
|
+
...(waitLimit.capped && { waitCappedAtMs: waitLimit.capMs })
|
|
387
337
|
});
|
|
388
|
-
},
|
|
389
|
-
childProcess.on('exit', (code) => {
|
|
338
|
+
}, waitLimit.waitMs);
|
|
339
|
+
childProcess.on('exit', (code, signal) => {
|
|
390
340
|
if (childProcess.pid) {
|
|
391
341
|
// Store completed session before removing active session
|
|
392
342
|
this.completedSessions.set(childProcess.pid, {
|
|
393
|
-
|
|
394
|
-
outputLines: [...session.outputLines], // Copy line buffer
|
|
343
|
+
session,
|
|
395
344
|
exitCode: code,
|
|
396
|
-
|
|
397
|
-
endTime: new Date()
|
|
398
|
-
evictedLines: session.evictedLines,
|
|
399
|
-
evictedChars: session.evictedChars
|
|
345
|
+
signal,
|
|
346
|
+
endTime: new Date()
|
|
400
347
|
});
|
|
401
348
|
// Keep only last 100 completed sessions
|
|
402
349
|
if (this.completedSessions.size > 100) {
|
|
@@ -414,6 +361,35 @@ export class TerminalManager {
|
|
|
414
361
|
});
|
|
415
362
|
});
|
|
416
363
|
}
|
|
364
|
+
/**
|
|
365
|
+
* Add a chunk of one stream's output to the session: to the merged line
|
|
366
|
+
* buffer, and to that stream's tail for state detection.
|
|
367
|
+
*/
|
|
368
|
+
recordOutput(session, stream, text) {
|
|
369
|
+
this.appendToLineBuffer(session, text);
|
|
370
|
+
const tail = session.streams[stream];
|
|
371
|
+
tail.text = (text.length >= STATE_DETECTION_TAIL_CHARS ? text : tail.text + text).slice(-STATE_DETECTION_TAIL_CHARS);
|
|
372
|
+
tail.chars += text.length;
|
|
373
|
+
tail.turn = this.currentDeliveryTurn();
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Number of the event-loop turn now delivering output; every chunk
|
|
377
|
+
* dispatched before the next check phase (setImmediate) shares it.
|
|
378
|
+
*
|
|
379
|
+
* stdout and stderr are separate pipes. Each turn delivers what the OS had
|
|
380
|
+
* ready when the loop polled, so a chunk delivered in a later turn was
|
|
381
|
+
* written after the chunks of earlier turns. Within one turn the pipes come
|
|
382
|
+
* in either order: when python -i's final stdout newline and its stderr
|
|
383
|
+
* ">>> " prompt are both waiting, the prompt is often delivered first.
|
|
384
|
+
*/
|
|
385
|
+
currentDeliveryTurn() {
|
|
386
|
+
if (!this.deliveryTurnOpen) {
|
|
387
|
+
this.deliveryTurnOpen = true;
|
|
388
|
+
this.deliveryTurn++;
|
|
389
|
+
setImmediate(() => { this.deliveryTurnOpen = false; });
|
|
390
|
+
}
|
|
391
|
+
return this.deliveryTurn;
|
|
392
|
+
}
|
|
417
393
|
/**
|
|
418
394
|
* Append text to a session's line buffer
|
|
419
395
|
* Handles partial lines and newline splitting
|
|
@@ -457,14 +433,20 @@ export class TerminalManager {
|
|
|
457
433
|
// Enforce the per-session cap by evicting the oldest lines. Keeps the
|
|
458
434
|
// buffer far below V8's max string length so concatenation and join()
|
|
459
435
|
// can never throw "Invalid string length" and kill the server.
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
436
|
+
// Count them first and drop them with one splice: on an array this large
|
|
437
|
+
// every shift() copies the whole array, and a line-by-line shift() stalled
|
|
438
|
+
// the event loop for seconds per chunk once a session reached the cap.
|
|
439
|
+
let evicted = 0;
|
|
440
|
+
while (session.bufferedChars > MAX_BUFFERED_OUTPUT_CHARS && evicted < session.outputLines.length - 1) {
|
|
441
|
+
const droppedJoinedChars = session.outputLines[evicted].length + 1; // +1 for its join separator
|
|
463
442
|
session.bufferedChars -= droppedJoinedChars;
|
|
464
443
|
session.evictedChars += droppedJoinedChars;
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
444
|
+
evicted++;
|
|
445
|
+
}
|
|
446
|
+
if (evicted > 0) {
|
|
447
|
+
session.outputLines.splice(0, evicted);
|
|
448
|
+
session.evictedLines += evicted;
|
|
449
|
+
session.lastReadIndex = Math.max(0, session.lastReadIndex - evicted);
|
|
468
450
|
}
|
|
469
451
|
}
|
|
470
452
|
/**
|
|
@@ -478,53 +460,92 @@ export class TerminalManager {
|
|
|
478
460
|
// First check active sessions
|
|
479
461
|
const session = this.sessions.get(pid);
|
|
480
462
|
if (session) {
|
|
481
|
-
const result = this.readFromLineBuffer(session
|
|
463
|
+
const result = this.readFromLineBuffer(session, offset, length, false, undefined);
|
|
482
464
|
result.evictedLines = session.evictedLines;
|
|
483
465
|
return result;
|
|
484
466
|
}
|
|
485
|
-
// Then check completed sessions
|
|
467
|
+
// Then check completed sessions: they keep their read position, so
|
|
468
|
+
// reading on after the exit continues where the last read stopped
|
|
486
469
|
const completedSession = this.completedSessions.get(pid);
|
|
487
470
|
if (completedSession) {
|
|
488
|
-
const runtimeMs = completedSession.endTime.getTime() - completedSession.startTime.getTime();
|
|
489
|
-
const result = this.readFromLineBuffer(completedSession.
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
result.evictedLines = completedSession.evictedLines;
|
|
471
|
+
const runtimeMs = completedSession.endTime.getTime() - completedSession.session.startTime.getTime();
|
|
472
|
+
const result = this.readFromLineBuffer(completedSession.session, offset, length, true, completedSession.exitCode, runtimeMs);
|
|
473
|
+
result.evictedLines = completedSession.session.evictedLines;
|
|
474
|
+
result.signal = completedSession.signal;
|
|
493
475
|
return result;
|
|
494
476
|
}
|
|
495
477
|
return null;
|
|
496
478
|
}
|
|
497
479
|
/**
|
|
498
|
-
*
|
|
480
|
+
* Whether a default read (offset 0) has anything to return: complete lines
|
|
481
|
+
* past the read position, or an unfinished last line with text a read
|
|
482
|
+
* hasn't returned (see readFromLineBuffer). Line counts alone can't tell
|
|
483
|
+
* the second: text appended to that line adds no line.
|
|
484
|
+
*/
|
|
485
|
+
hasUnreadOutput(pid) {
|
|
486
|
+
const session = this.sessions.get(pid) ?? this.completedSessions.get(pid)?.session;
|
|
487
|
+
if (!session) {
|
|
488
|
+
return false;
|
|
489
|
+
}
|
|
490
|
+
return session.outputLines.length - 1 > session.lastReadIndex || TerminalManager.openLineHasNewText(session);
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Whether the unfinished last line has text that a default read hasn't
|
|
494
|
+
* returned. Empty, it has nothing to return. Its text is compared with what
|
|
495
|
+
* a read last returned only while it is the line that read stopped at: a
|
|
496
|
+
* later line is new even when its text is the same (a REPL's next ">>> ").
|
|
497
|
+
*/
|
|
498
|
+
static openLineHasNewText(session) {
|
|
499
|
+
const lines = session.outputLines;
|
|
500
|
+
const openLine = lines[lines.length - 1] ?? '';
|
|
501
|
+
return openLine !== '' && (lines.length - 1 !== session.lastReadIndex || openLine !== session.lastReadOpenLine);
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Internal helper to read from a session's line buffer with offset/length
|
|
499
505
|
*/
|
|
500
|
-
readFromLineBuffer(
|
|
501
|
-
const
|
|
506
|
+
readFromLineBuffer(session, offset, length, isComplete, exitCode, runtimeMs) {
|
|
507
|
+
const lines = session.outputLines;
|
|
508
|
+
// The empty last line after a trailing newline holds nothing: it isn't
|
|
509
|
+
// counted (total, remaining, tail offsets) or returned. A last line with
|
|
510
|
+
// text, unfinished or not, is.
|
|
511
|
+
const totalLines = lines[lines.length - 1] === '' ? lines.length - 1 : lines.length;
|
|
502
512
|
let startIndex;
|
|
503
513
|
let linesToRead;
|
|
514
|
+
let readableEnd = totalLines;
|
|
504
515
|
if (offset < 0) {
|
|
505
516
|
// Negative offset = start position from end, then read 'length' lines forward
|
|
506
517
|
// e.g., offset=-50, length=10 means: start 50 lines from end, read 10 lines
|
|
507
518
|
const fromEnd = Math.abs(offset);
|
|
508
519
|
startIndex = Math.max(0, totalLines - fromEnd);
|
|
509
|
-
linesToRead = lines.slice(startIndex, startIndex + length);
|
|
520
|
+
linesToRead = lines.slice(startIndex, Math.min(startIndex + length, totalLines));
|
|
510
521
|
// Don't update lastReadIndex for tail reads
|
|
511
522
|
}
|
|
512
523
|
else if (offset === 0) {
|
|
513
|
-
// offset=0 means "from where I last read" (like getNewOutput)
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
//
|
|
517
|
-
|
|
524
|
+
// offset=0 means "from where I last read" (like getNewOutput).
|
|
525
|
+
// The last line is unfinished: output is appended to it until a newline
|
|
526
|
+
// arrives, even after the exit (a process the command started can still
|
|
527
|
+
// write). So it is returned only when it has text a read hasn't
|
|
528
|
+
// returned, and the read position never moves past it: counting it as
|
|
529
|
+
// read would lose whatever is appended to it next.
|
|
530
|
+
const openLineIndex = Math.max(lines.length - 1, 0);
|
|
531
|
+
readableEnd = TerminalManager.openLineHasNewText(session) ? lines.length : openLineIndex;
|
|
532
|
+
startIndex = session.lastReadIndex;
|
|
533
|
+
linesToRead = lines.slice(startIndex, Math.min(startIndex + length, readableEnd));
|
|
534
|
+
const readTo = startIndex + linesToRead.length;
|
|
535
|
+
if (readTo === lines.length) {
|
|
536
|
+
session.lastReadOpenLine = lines[lines.length - 1];
|
|
537
|
+
}
|
|
538
|
+
session.lastReadIndex = Math.min(readTo, openLineIndex);
|
|
518
539
|
}
|
|
519
540
|
else {
|
|
520
541
|
// Positive offset = absolute position
|
|
521
542
|
startIndex = offset;
|
|
522
|
-
linesToRead = lines.slice(startIndex, startIndex + length);
|
|
543
|
+
linesToRead = lines.slice(startIndex, Math.min(startIndex + length, totalLines));
|
|
523
544
|
// Don't update lastReadIndex for absolute position reads
|
|
524
545
|
}
|
|
525
546
|
const readCount = linesToRead.length;
|
|
526
547
|
const endIndex = startIndex + readCount;
|
|
527
|
-
const remaining = Math.max(0,
|
|
548
|
+
const remaining = Math.max(0, readableEnd - endIndex);
|
|
528
549
|
return {
|
|
529
550
|
lines: linesToRead,
|
|
530
551
|
totalLines,
|
|
@@ -546,7 +567,7 @@ export class TerminalManager {
|
|
|
546
567
|
}
|
|
547
568
|
const completedSession = this.completedSessions.get(pid);
|
|
548
569
|
if (completedSession) {
|
|
549
|
-
return completedSession.outputLines.length;
|
|
570
|
+
return completedSession.session.outputLines.length;
|
|
550
571
|
}
|
|
551
572
|
return null;
|
|
552
573
|
}
|
|
@@ -585,17 +606,7 @@ export class TerminalManager {
|
|
|
585
606
|
*/
|
|
586
607
|
captureOutputSnapshot(pid) {
|
|
587
608
|
const session = this.sessions.get(pid);
|
|
588
|
-
|
|
589
|
-
const fullOutput = session.outputLines.join('\n');
|
|
590
|
-
return {
|
|
591
|
-
// Absolute since process start (includes evicted output), so the
|
|
592
|
-
// offset stays valid even if the cap evicts lines between
|
|
593
|
-
// snapshot and read.
|
|
594
|
-
totalChars: session.evictedChars + fullOutput.length,
|
|
595
|
-
lineCount: session.evictedLines + session.outputLines.length
|
|
596
|
-
};
|
|
597
|
-
}
|
|
598
|
-
return null;
|
|
609
|
+
return session ? TerminalManager.endOfOutput(session) : null;
|
|
599
610
|
}
|
|
600
611
|
/**
|
|
601
612
|
* Get output that appeared since a snapshot was taken.
|
|
@@ -603,30 +614,99 @@ export class TerminalManager {
|
|
|
603
614
|
* Also checks completed sessions in case process finished between snapshot and poll.
|
|
604
615
|
*/
|
|
605
616
|
getOutputSinceSnapshot(pid, snapshot) {
|
|
606
|
-
|
|
617
|
+
return this.readOutputSince(pid, snapshot)?.output ?? null;
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Output that appeared since `snapshot`, plus the snapshot at the current end
|
|
621
|
+
* of output. A poller passes `next` back in to read only the output that
|
|
622
|
+
* arrived since its previous poll. Costs O(output since snapshot), never
|
|
623
|
+
* O(whole buffer), so polling stays cheap however much history the session
|
|
624
|
+
* has retained. Also checks completed sessions in case the process finished
|
|
625
|
+
* between snapshot and poll.
|
|
626
|
+
*/
|
|
627
|
+
readOutputSince(pid, snapshot) {
|
|
628
|
+
const buffer = this.sessions.get(pid) ?? this.completedSessions.get(pid)?.session;
|
|
629
|
+
if (!buffer) {
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
return {
|
|
633
|
+
output: TerminalManager.outputSinceSnapshot(buffer, snapshot.totalChars),
|
|
634
|
+
next: TerminalManager.endOfOutput(buffer)
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Snapshot at the current end of a buffer, in O(1): bufferedChars is the
|
|
639
|
+
* joined length of the retained lines, so nothing is joined here.
|
|
640
|
+
*/
|
|
641
|
+
static endOfOutput(buffer) {
|
|
642
|
+
return {
|
|
643
|
+
// Absolute since process start (includes evicted output), so the
|
|
644
|
+
// offset stays valid even if the cap evicts lines between
|
|
645
|
+
// snapshot and read.
|
|
646
|
+
totalChars: buffer.evictedChars + buffer.bufferedChars,
|
|
647
|
+
lineCount: buffer.evictedLines + buffer.outputLines.length,
|
|
648
|
+
streamChars: { stdout: buffer.streams.stdout.chars, stderr: buffer.streams.stderr.chars }
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* The process's state: finished once it has exited, whatever its output
|
|
653
|
+
* says; otherwise waiting for input or running, judged from the end of the
|
|
654
|
+
* output it wrote since `since` (default: since it started). Reads only the
|
|
655
|
+
* per-stream tails, so it costs the same however much output the process
|
|
656
|
+
* has produced. The one place start_process, interact_with_process,
|
|
657
|
+
* read_process_output and list_sessions get the state from.
|
|
658
|
+
*/
|
|
659
|
+
getProcessState(pid, since) {
|
|
607
660
|
const session = this.sessions.get(pid);
|
|
608
661
|
if (session) {
|
|
609
|
-
return TerminalManager.
|
|
662
|
+
return analyzeProcessState(TerminalManager.lastWrittenOutput(session.streams, since), pid);
|
|
610
663
|
}
|
|
611
|
-
// Fallback to completed sessions - process may have finished between snapshot and poll
|
|
612
664
|
const completedSession = this.completedSessions.get(pid);
|
|
613
|
-
if (completedSession) {
|
|
614
|
-
return
|
|
665
|
+
if (!completedSession) {
|
|
666
|
+
return null;
|
|
615
667
|
}
|
|
616
|
-
|
|
668
|
+
const lastOutput = TerminalManager.lastWrittenOutput(completedSession.session.streams, since).join('\n');
|
|
669
|
+
return { isWaitingForInput: false, isFinished: true, isRunning: false, lastOutput };
|
|
617
670
|
}
|
|
618
671
|
/**
|
|
619
|
-
*
|
|
620
|
-
*
|
|
621
|
-
*
|
|
672
|
+
* The output since `since` of each stream that may have written last: the
|
|
673
|
+
* streams delivered in the latest turn that delivered anything since then.
|
|
674
|
+
* Their relative order within that turn is unknown (see
|
|
675
|
+
* currentDeliveryTurn), so each is judged on its own; streams last
|
|
676
|
+
* delivered in an earlier turn wrote before them and can't end the output.
|
|
622
677
|
*/
|
|
623
|
-
static
|
|
624
|
-
const
|
|
625
|
-
|
|
626
|
-
|
|
678
|
+
static lastWrittenOutput(streams, since) {
|
|
679
|
+
const recent = OUTPUT_STREAMS
|
|
680
|
+
.map(name => {
|
|
681
|
+
const { text, chars, turn } = streams[name];
|
|
682
|
+
const newChars = chars - (since?.streamChars[name] ?? 0);
|
|
683
|
+
return { text: newChars > 0 ? text.slice(-newChars) : '', turn };
|
|
684
|
+
})
|
|
685
|
+
.filter(stream => stream.text.length > 0);
|
|
686
|
+
const lastTurn = Math.max(...recent.map(stream => stream.turn));
|
|
687
|
+
return recent.filter(stream => stream.turn === lastTurn).map(stream => stream.text);
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* New output since a snapshot, in absolute (since process start) offsets:
|
|
691
|
+
* the last (end - snapshot) chars of the joined buffer. Walks back from the
|
|
692
|
+
* newest line only until the snapshot position is covered and joins just
|
|
693
|
+
* those lines. If eviction dropped part of the unseen output, returns what
|
|
694
|
+
* the buffer still holds — the oldest unseen chars are lost to the cap.
|
|
695
|
+
*/
|
|
696
|
+
static outputSinceSnapshot(buffer, snapshotTotalChars) {
|
|
697
|
+
const { outputLines } = buffer;
|
|
698
|
+
const newChars = buffer.evictedChars + buffer.bufferedChars - snapshotTotalChars;
|
|
699
|
+
if (newChars <= 0 || outputLines.length === 0) {
|
|
627
700
|
return ''; // No new output
|
|
628
701
|
}
|
|
629
|
-
|
|
702
|
+
let firstLine = outputLines.length - 1;
|
|
703
|
+
let tailChars = outputLines[firstLine].length; // Joined length of outputLines[firstLine..]
|
|
704
|
+
while (tailChars < newChars && firstLine > 0) {
|
|
705
|
+
firstLine--;
|
|
706
|
+
tailChars += outputLines[firstLine].length + 1; // +1 for its join separator
|
|
707
|
+
}
|
|
708
|
+
const tail = outputLines.slice(firstLine).join('\n');
|
|
709
|
+
return tail.substring(Math.max(0, tail.length - newChars));
|
|
630
710
|
}
|
|
631
711
|
/**
|
|
632
712
|
* Get a session by PID
|
|
@@ -636,32 +716,37 @@ export class TerminalManager {
|
|
|
636
716
|
getSession(pid) {
|
|
637
717
|
return this.sessions.get(pid);
|
|
638
718
|
}
|
|
639
|
-
|
|
719
|
+
/**
|
|
720
|
+
* End a session: its shell and every process the command started (see
|
|
721
|
+
* terminateProcessTree). Killing only the shell left the program running.
|
|
722
|
+
* Resolves once they are gone: 'terminated', or 'failed' if some could not
|
|
723
|
+
* be ended; 'not_found' when no session runs as `pid`. Never rejects.
|
|
724
|
+
*/
|
|
725
|
+
async forceTerminate(pid) {
|
|
640
726
|
const session = this.sessions.get(pid);
|
|
641
727
|
if (!session) {
|
|
642
|
-
return
|
|
728
|
+
return 'not_found';
|
|
643
729
|
}
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
if (
|
|
648
|
-
session.
|
|
649
|
-
|
|
650
|
-
}
|
|
651
|
-
return true;
|
|
730
|
+
if (!session.termination) {
|
|
731
|
+
// Calls made while it runs share it; a failed one is dropped, so the next call tries again
|
|
732
|
+
session.termination = terminateProcessTree(session.process).then((ended) => {
|
|
733
|
+
if (!ended)
|
|
734
|
+
session.termination = undefined;
|
|
735
|
+
return ended;
|
|
736
|
+
});
|
|
652
737
|
}
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
656
|
-
capture('server_request_error', { error: errorMessage, message: `Failed to terminate process ${pid}:` });
|
|
657
|
-
return false;
|
|
738
|
+
if (await session.termination) {
|
|
739
|
+
return 'terminated';
|
|
658
740
|
}
|
|
741
|
+
capture('server_request_error', { error: 'Process tree termination failed', message: `Failed to terminate process ${pid}:` });
|
|
742
|
+
return 'failed';
|
|
659
743
|
}
|
|
660
744
|
listActiveSessions() {
|
|
661
745
|
const now = new Date();
|
|
662
746
|
return Array.from(this.sessions.values()).map(session => ({
|
|
663
747
|
pid: session.pid,
|
|
664
|
-
|
|
748
|
+
// Waiting for input now, judged from its output like every other state answer
|
|
749
|
+
isBlocked: this.getProcessState(session.pid)?.isWaitingForInput ?? false,
|
|
665
750
|
runtime: now.getTime() - session.startTime.getTime()
|
|
666
751
|
}));
|
|
667
752
|
}
|