@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
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { terminalManager, MAX_BUFFERED_OUTPUT_CHARS } from '../terminal-manager.js';
|
|
1
|
+
import { terminalManager, MAX_BUFFERED_OUTPUT_CHARS, getProcessWaitLimit } from '../terminal-manager.js';
|
|
2
2
|
import { commandManager } from '../command-manager.js';
|
|
3
3
|
import { StartProcessArgsSchema, ReadProcessOutputArgsSchema, InteractWithProcessArgsSchema, ForceTerminateArgsSchema } from './schemas.js';
|
|
4
4
|
import { capture } from "../utils/capture.js";
|
|
5
5
|
import { analyzeProcessState, cleanProcessOutput, formatProcessStateMessage } from '../utils/process-detection.js';
|
|
6
|
-
import * as os from 'os';
|
|
7
6
|
import { configManager } from '../config-manager.js';
|
|
7
|
+
import { getDefaultShell } from '../utils/shell.js';
|
|
8
|
+
import { terminateProcessTree } from '../utils/process-tree.js';
|
|
9
|
+
import { MAX_PROCESS_WAIT_MS } from '../config.js';
|
|
8
10
|
import { spawn } from 'child_process';
|
|
9
11
|
import fs from 'fs/promises';
|
|
10
12
|
import path from 'path';
|
|
@@ -16,22 +18,46 @@ const mcpRoot = path.resolve(__dirname, '..', '..');
|
|
|
16
18
|
// Track virtual Node sessions (PIDs that are actually Node fallback sessions)
|
|
17
19
|
const virtualNodeSessions = new Map();
|
|
18
20
|
let virtualPidCounter = -1000; // Use negative PIDs for virtual sessions
|
|
21
|
+
/** How long a node:local script's output pipes may stay open after its timeout ended its tree */
|
|
22
|
+
const PIPES_CLOSE_WAIT_MS = 1000;
|
|
23
|
+
/** The answer when some processes of a session could not be ended */
|
|
24
|
+
function terminationFailedResult(pid) {
|
|
25
|
+
return {
|
|
26
|
+
content: [{ type: "text", text: `Error: Could not terminate every process of session ${pid}; some may still be running` }],
|
|
27
|
+
isError: true,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
19
30
|
/**
|
|
20
31
|
* Execute Node.js code via temp file (fallback when Python unavailable)
|
|
21
32
|
* Creates temp .mjs file in MCP directory for ES module import access
|
|
22
33
|
*/
|
|
23
|
-
async function executeNodeCode(code, timeout_ms = 30000) {
|
|
34
|
+
async function executeNodeCode(code, timeout_ms = 30000, sessionPid) {
|
|
24
35
|
const tempFile = path.join(mcpRoot, `.mcp-exec-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`);
|
|
25
36
|
try {
|
|
26
37
|
await fs.writeFile(tempFile, code, 'utf8');
|
|
27
38
|
const result = await new Promise((resolve) => {
|
|
28
39
|
const proc = spawn(process.execPath, [tempFile], {
|
|
29
40
|
cwd: mcpRoot,
|
|
30
|
-
timeout: timeout_ms,
|
|
31
41
|
windowsHide: true // Prevent visible console windows on Windows
|
|
32
42
|
});
|
|
33
43
|
let stdout = '';
|
|
34
44
|
let stderr = '';
|
|
45
|
+
// Not spawn's own timeout option: that kills only the script, leaving the
|
|
46
|
+
// processes it started running and holding its output pipes open, so
|
|
47
|
+
// 'close' never came and the call never returned.
|
|
48
|
+
const timer = setTimeout(async () => {
|
|
49
|
+
if (await terminateProcessTree(proc)) {
|
|
50
|
+
// The tree ended, but a process that left it before the walk (one
|
|
51
|
+
// started by a child that has exited) may still hold the output
|
|
52
|
+
// pipes: 'close' answers if it comes within PIPES_CLOSE_WAIT_MS
|
|
53
|
+
await new Promise((wait) => setTimeout(wait, PIPES_CLOSE_WAIT_MS).unref());
|
|
54
|
+
}
|
|
55
|
+
// Some of the tree survived, or a process outside it holds the output
|
|
56
|
+
// pipes, so 'close' may never come: answer now and stop reading them
|
|
57
|
+
proc.stdout.destroy();
|
|
58
|
+
proc.stderr.destroy();
|
|
59
|
+
resolve({ stdout, stderr, exitCode: 1, treeSurvived: true });
|
|
60
|
+
}, timeout_ms);
|
|
35
61
|
proc.stdout.on('data', (data) => {
|
|
36
62
|
stdout += data.toString();
|
|
37
63
|
});
|
|
@@ -39,14 +65,19 @@ async function executeNodeCode(code, timeout_ms = 30000) {
|
|
|
39
65
|
stderr += data.toString();
|
|
40
66
|
});
|
|
41
67
|
proc.on('close', (exitCode) => {
|
|
68
|
+
clearTimeout(timer);
|
|
42
69
|
resolve({ stdout, stderr, exitCode: exitCode ?? 1 });
|
|
43
70
|
});
|
|
44
71
|
proc.on('error', (err) => {
|
|
72
|
+
clearTimeout(timer);
|
|
45
73
|
resolve({ stdout, stderr: stderr + '\n' + err.message, exitCode: 1 });
|
|
46
74
|
});
|
|
47
75
|
});
|
|
48
76
|
// Clean up temp file
|
|
49
77
|
await fs.unlink(tempFile).catch(() => { });
|
|
78
|
+
if (result.treeSurvived) {
|
|
79
|
+
return terminationFailedResult(sessionPid);
|
|
80
|
+
}
|
|
50
81
|
if (result.exitCode !== 0) {
|
|
51
82
|
return {
|
|
52
83
|
content: [{
|
|
@@ -56,11 +87,20 @@ async function executeNodeCode(code, timeout_ms = 30000) {
|
|
|
56
87
|
isError: true
|
|
57
88
|
};
|
|
58
89
|
}
|
|
90
|
+
// Each call runs a fresh script and the session waits for the next one; the output isn't cut
|
|
91
|
+
const outputLines = result.stdout.trim().length > 0 ? result.stdout.replace(/\r?\n$/, '').split('\n').length : 0;
|
|
59
92
|
return {
|
|
60
93
|
content: [{
|
|
61
94
|
type: "text",
|
|
62
95
|
text: result.stdout || '(no output)'
|
|
63
|
-
}]
|
|
96
|
+
}],
|
|
97
|
+
structuredContent: {
|
|
98
|
+
pid: sessionPid,
|
|
99
|
+
status: 'waiting_for_input',
|
|
100
|
+
truncated: false,
|
|
101
|
+
shownLines: outputLines,
|
|
102
|
+
totalLines: outputLines,
|
|
103
|
+
},
|
|
64
104
|
};
|
|
65
105
|
}
|
|
66
106
|
catch (error) {
|
|
@@ -78,8 +118,10 @@ async function executeNodeCode(code, timeout_ms = 30000) {
|
|
|
78
118
|
/**
|
|
79
119
|
* Start a new process (renamed from execute_command)
|
|
80
120
|
* Includes early detection of process waiting for input
|
|
121
|
+
* maxWaitMs: ceiling for this call's wait. The tools always use MAX_PROCESS_WAIT_MS;
|
|
122
|
+
* only in-process callers (tests) pass a smaller one. Not part of the tool schema.
|
|
81
123
|
*/
|
|
82
|
-
export async function startProcess(args) {
|
|
124
|
+
export async function startProcess(args, maxWaitMs = MAX_PROCESS_WAIT_MS) {
|
|
83
125
|
const parsed = StartProcessArgsSchema.safeParse(args);
|
|
84
126
|
if (!parsed.success) {
|
|
85
127
|
capture('server_start_process_failed');
|
|
@@ -89,7 +131,9 @@ export async function startProcess(args) {
|
|
|
89
131
|
};
|
|
90
132
|
}
|
|
91
133
|
try {
|
|
92
|
-
|
|
134
|
+
// Each command's first word as typed, so telemetry replaces a path whole
|
|
135
|
+
// (the base name alone would send the last part of it)
|
|
136
|
+
const commands = commandManager.extractCommands(parsed.data.command, true).join(', ');
|
|
93
137
|
capture('server_start_process', {
|
|
94
138
|
command: commandManager.getBaseCommand(parsed.data.command),
|
|
95
139
|
commands: commands
|
|
@@ -105,6 +149,7 @@ export async function startProcess(args) {
|
|
|
105
149
|
return {
|
|
106
150
|
content: [{ type: "text", text: `Error: Command not allowed: ${parsed.data.command}` }],
|
|
107
151
|
isError: true,
|
|
152
|
+
structuredContent: { blocked: true, command: parsed.data.command },
|
|
108
153
|
};
|
|
109
154
|
}
|
|
110
155
|
const commandToRun = parsed.data.command;
|
|
@@ -127,36 +172,23 @@ export async function startProcess(args) {
|
|
|
127
172
|
|
|
128
173
|
🔄 Ready for code - send complete self-contained script via interact_with_process.`
|
|
129
174
|
}],
|
|
175
|
+
structuredContent: { pid: virtualPid, status: 'waiting_for_input' },
|
|
130
176
|
};
|
|
131
177
|
}
|
|
132
178
|
let shellUsed = parsed.data.shell;
|
|
133
179
|
if (!shellUsed) {
|
|
134
180
|
const config = await configManager.getConfig();
|
|
135
|
-
|
|
136
|
-
shellUsed = config.defaultShell;
|
|
137
|
-
}
|
|
138
|
-
else {
|
|
139
|
-
const isWindows = os.platform() === 'win32';
|
|
140
|
-
if (isWindows && process.env.COMSPEC) {
|
|
141
|
-
shellUsed = process.env.COMSPEC;
|
|
142
|
-
}
|
|
143
|
-
else if (!isWindows && process.env.SHELL) {
|
|
144
|
-
shellUsed = process.env.SHELL;
|
|
145
|
-
}
|
|
146
|
-
else {
|
|
147
|
-
shellUsed = isWindows ? 'cmd.exe' : '/bin/sh';
|
|
148
|
-
}
|
|
149
|
-
}
|
|
181
|
+
shellUsed = config.defaultShell || getDefaultShell();
|
|
150
182
|
}
|
|
151
|
-
const result = await terminalManager.executeCommand(commandToRun, parsed.data.timeout_ms, shellUsed, parsed.data.verbose_timing || false);
|
|
183
|
+
const result = await terminalManager.executeCommand(commandToRun, parsed.data.timeout_ms, shellUsed, parsed.data.verbose_timing || false, maxWaitMs);
|
|
152
184
|
if (result.pid === -1) {
|
|
153
185
|
return {
|
|
154
186
|
content: [{ type: "text", text: result.output }],
|
|
155
187
|
isError: true,
|
|
156
188
|
};
|
|
157
189
|
}
|
|
158
|
-
//
|
|
159
|
-
const processState =
|
|
190
|
+
// Whether the process is waiting for input, as detected when the wait ended
|
|
191
|
+
const { processState } = result;
|
|
160
192
|
let statusMessage = '';
|
|
161
193
|
if (processState.isWaitingForInput) {
|
|
162
194
|
statusMessage = `\n🔄 ${formatProcessStateMessage(processState, result.pid)}`;
|
|
@@ -177,8 +209,35 @@ export async function startProcess(args) {
|
|
|
177
209
|
type: "text",
|
|
178
210
|
text: `Process started with PID ${result.pid} (shell: ${shellUsed})\nInitial output:\n${result.output}${statusMessage}${timingMessage}`
|
|
179
211
|
}],
|
|
212
|
+
structuredContent: {
|
|
213
|
+
pid: result.pid,
|
|
214
|
+
shell: shellUsed,
|
|
215
|
+
status: getProcessStatus(processState),
|
|
216
|
+
...getWaitCapFields(result.waitCappedAtMs),
|
|
217
|
+
},
|
|
180
218
|
};
|
|
181
219
|
}
|
|
220
|
+
/**
|
|
221
|
+
* Machine-readable process state for structuredContent, mirroring the
|
|
222
|
+
* status line shown in the text response.
|
|
223
|
+
*/
|
|
224
|
+
function getProcessStatus(state, timedOut = false) {
|
|
225
|
+
if (state.isWaitingForInput)
|
|
226
|
+
return 'waiting_for_input';
|
|
227
|
+
if (state.isFinished)
|
|
228
|
+
return 'finished';
|
|
229
|
+
return timedOut ? 'timeout' : 'running';
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* structuredContent fields telling the caller whether the wait ceiling
|
|
233
|
+
* (not timeout_ms) ended the wait. When it did, status is 'running'
|
|
234
|
+
* and the caller continues with read_process_output.
|
|
235
|
+
*/
|
|
236
|
+
function getWaitCapFields(waitCappedAtMs) {
|
|
237
|
+
return waitCappedAtMs !== undefined
|
|
238
|
+
? { waitCapped: true, waitLimitMs: waitCappedAtMs }
|
|
239
|
+
: { waitCapped: false };
|
|
240
|
+
}
|
|
182
241
|
function formatTimingInfo(timing) {
|
|
183
242
|
let msg = '\n\n📊 Timing Information:\n';
|
|
184
243
|
msg += ` Exit Reason: ${timing.exitReason}\n`;
|
|
@@ -204,8 +263,10 @@ function formatTimingInfo(timing) {
|
|
|
204
263
|
/**
|
|
205
264
|
* Read output from a running process with file-like pagination
|
|
206
265
|
* Supports offset/length parameters for controlled reading
|
|
266
|
+
* maxWaitMs: ceiling for this call's wait. The tools always use MAX_PROCESS_WAIT_MS;
|
|
267
|
+
* only in-process callers (tests) pass a smaller one. Not part of the tool schema.
|
|
207
268
|
*/
|
|
208
|
-
export async function readProcessOutput(args) {
|
|
269
|
+
export async function readProcessOutput(args, maxWaitMs = MAX_PROCESS_WAIT_MS) {
|
|
209
270
|
const parsed = ReadProcessOutputArgsSchema.safeParse(args);
|
|
210
271
|
if (!parsed.success) {
|
|
211
272
|
return {
|
|
@@ -221,6 +282,7 @@ export async function readProcessOutput(args) {
|
|
|
221
282
|
verbose_timing = false } = parsed.data;
|
|
222
283
|
// Timing telemetry
|
|
223
284
|
const startTime = Date.now();
|
|
285
|
+
const { waitMs } = getProcessWaitLimit(timeout_ms, maxWaitMs);
|
|
224
286
|
// For active sessions with no new output yet, optionally wait for output
|
|
225
287
|
const session = terminalManager.getSession(pid);
|
|
226
288
|
if (session && offset === 0) {
|
|
@@ -228,8 +290,7 @@ export async function readProcessOutput(args) {
|
|
|
228
290
|
const waitForOutput = () => {
|
|
229
291
|
return new Promise((resolve) => {
|
|
230
292
|
// Check if there's already new output
|
|
231
|
-
|
|
232
|
-
if (currentLines > session.lastReadIndex) {
|
|
293
|
+
if (terminalManager.hasUnreadOutput(pid)) {
|
|
233
294
|
resolve();
|
|
234
295
|
return;
|
|
235
296
|
}
|
|
@@ -249,17 +310,17 @@ export async function readProcessOutput(args) {
|
|
|
249
310
|
cleanup();
|
|
250
311
|
resolve();
|
|
251
312
|
};
|
|
252
|
-
// Poll for new output
|
|
313
|
+
// Poll for new output, or for the exit (the session is then no
|
|
314
|
+
// longer active): a process that exited writes nothing more itself
|
|
253
315
|
interval = setInterval(() => {
|
|
254
|
-
|
|
255
|
-
if (newLineCount > session.lastReadIndex) {
|
|
316
|
+
if (terminalManager.hasUnreadOutput(pid) || !terminalManager.getSession(pid)) {
|
|
256
317
|
resolveOnce();
|
|
257
318
|
}
|
|
258
319
|
}, 50);
|
|
259
320
|
// Timeout
|
|
260
321
|
timeout = setTimeout(() => {
|
|
261
322
|
resolveOnce();
|
|
262
|
-
},
|
|
323
|
+
}, waitMs);
|
|
263
324
|
});
|
|
264
325
|
};
|
|
265
326
|
await waitForOutput();
|
|
@@ -306,13 +367,14 @@ export async function readProcessOutput(args) {
|
|
|
306
367
|
const runtimeStr = result.runtimeMs !== undefined
|
|
307
368
|
? ` (runtime: ${(result.runtimeMs / 1000).toFixed(2)}s)`
|
|
308
369
|
: '';
|
|
309
|
-
|
|
370
|
+
// A process ended by a signal has no exit code: name the signal instead of "exit code null"
|
|
371
|
+
const ending = result.exitCode === null && result.signal ? `signal ${result.signal}` : `exit code ${result.exitCode}`;
|
|
372
|
+
processStateMessage = `\n✅ Process completed with ${ending}${runtimeStr}`;
|
|
310
373
|
}
|
|
311
374
|
else if (session) {
|
|
312
375
|
// Analyze state for running processes
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
if (processState.isWaitingForInput) {
|
|
376
|
+
const processState = terminalManager.getProcessState(pid);
|
|
377
|
+
if (processState?.isWaitingForInput) {
|
|
316
378
|
processStateMessage = `\n🔄 ${formatProcessStateMessage(processState, pid)}`;
|
|
317
379
|
}
|
|
318
380
|
}
|
|
@@ -333,8 +395,10 @@ export async function readProcessOutput(args) {
|
|
|
333
395
|
/**
|
|
334
396
|
* Interact with a running process (renamed from send_input)
|
|
335
397
|
* Automatically detects when process is ready and returns output
|
|
398
|
+
* maxWaitMs: ceiling for this call's wait. The tools always use MAX_PROCESS_WAIT_MS;
|
|
399
|
+
* only in-process callers (tests) pass a smaller one. Not part of the tool schema.
|
|
336
400
|
*/
|
|
337
|
-
export async function interactWithProcess(args) {
|
|
401
|
+
export async function interactWithProcess(args, maxWaitMs = MAX_PROCESS_WAIT_MS) {
|
|
338
402
|
const parsed = InteractWithProcessArgsSchema.safeParse(args);
|
|
339
403
|
if (!parsed.success) {
|
|
340
404
|
capture('server_interact_with_process_failed', {
|
|
@@ -349,6 +413,7 @@ export async function interactWithProcess(args) {
|
|
|
349
413
|
// Get config for output line limit
|
|
350
414
|
const config = await configManager.getConfig();
|
|
351
415
|
const maxOutputLines = config.fileReadLineLimit ?? 1000;
|
|
416
|
+
const waitLimit = getProcessWaitLimit(timeout_ms, maxWaitMs);
|
|
352
417
|
// Check if this is a virtual Node session (node:local)
|
|
353
418
|
if (virtualNodeSessions.has(pid)) {
|
|
354
419
|
const session = virtualNodeSessions.get(pid);
|
|
@@ -358,8 +423,10 @@ export async function interactWithProcess(args) {
|
|
|
358
423
|
});
|
|
359
424
|
// Execute code via temp file approach
|
|
360
425
|
// Respect per-call timeout if provided, otherwise use session default
|
|
361
|
-
|
|
362
|
-
|
|
426
|
+
// (parsed.data's: timeout_ms above already holds the 8000ms default for processes),
|
|
427
|
+
// within the process wait ceiling: the call answers only once the script ends
|
|
428
|
+
const effectiveTimeout = Math.min(parsed.data.timeout_ms ?? session.timeout_ms, waitLimit.capMs);
|
|
429
|
+
return executeNodeCode(input, effectiveTimeout, pid);
|
|
363
430
|
}
|
|
364
431
|
// Timing telemetry
|
|
365
432
|
const startTime = Date.now();
|
|
@@ -375,7 +442,10 @@ export async function interactWithProcess(args) {
|
|
|
375
442
|
// Capture output snapshot BEFORE sending input
|
|
376
443
|
// This handles REPLs where output is appended to the prompt line
|
|
377
444
|
const outputSnapshot = terminalManager.captureOutputSnapshot(pid);
|
|
378
|
-
|
|
445
|
+
// Only a process that reads its input at a prompt prints prompts in its output
|
|
446
|
+
const readAtPrompt = terminalManager.getProcessState(pid)?.isWaitingForInput ?? false;
|
|
447
|
+
// No snapshot means no active session, which can't take input either
|
|
448
|
+
const success = outputSnapshot !== null && terminalManager.sendInputToProcess(pid, input);
|
|
379
449
|
if (!success) {
|
|
380
450
|
return {
|
|
381
451
|
content: [{ type: "text", text: `Error: Failed to send input to process ${pid}. The process may have exited or doesn't accept input.` }],
|
|
@@ -405,22 +475,25 @@ export async function interactWithProcess(args) {
|
|
|
405
475
|
type: "text",
|
|
406
476
|
text: `✅ Input sent to process ${pid}. Use read_process_output to get the response.${timingMessage}`
|
|
407
477
|
}],
|
|
478
|
+
// Not waited for: no output was read
|
|
479
|
+
structuredContent: { pid, status: 'running', truncated: false, shownLines: 0, totalLines: 0 },
|
|
408
480
|
};
|
|
409
481
|
}
|
|
410
482
|
// Smart waiting with immediate and periodic detection
|
|
411
483
|
let output = "";
|
|
412
484
|
let processState;
|
|
413
485
|
let earlyExit = false;
|
|
414
|
-
|
|
415
|
-
const quickPromptPatterns = />>>\s*$|>\s*$|\$\s*$|#\s*$/;
|
|
486
|
+
let waitCapped = false;
|
|
416
487
|
const waitForResponse = () => {
|
|
417
488
|
return new Promise((resolve) => {
|
|
418
489
|
let resolved = false;
|
|
419
|
-
let attempts = 0;
|
|
420
490
|
const pollIntervalMs = 50; // Poll every 50ms for faster response
|
|
421
|
-
|
|
491
|
+
// A deadline, not a poll count, so a busy event loop can't stretch the wait past the ceiling
|
|
492
|
+
const deadline = Date.now() + waitLimit.waitMs;
|
|
422
493
|
let interval = null;
|
|
423
|
-
|
|
494
|
+
// Advances every poll, so each poll reads only the output that arrived since the
|
|
495
|
+
// previous one (snapshot-based, which handles REPL prompt line appending)
|
|
496
|
+
let readPosition = outputSnapshot;
|
|
424
497
|
let resolveOnce = () => {
|
|
425
498
|
if (resolved)
|
|
426
499
|
return;
|
|
@@ -433,11 +506,11 @@ export async function interactWithProcess(args) {
|
|
|
433
506
|
interval = setInterval(() => {
|
|
434
507
|
if (resolved)
|
|
435
508
|
return;
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
if (newOutput
|
|
509
|
+
const read = terminalManager.readOutputSince(pid, readPosition);
|
|
510
|
+
if (read)
|
|
511
|
+
readPosition = read.next;
|
|
512
|
+
const newOutput = read?.output ?? '';
|
|
513
|
+
if (newOutput.length > 0) {
|
|
441
514
|
const now = Date.now();
|
|
442
515
|
if (!firstOutputTime)
|
|
443
516
|
firstOutputTime = now;
|
|
@@ -447,14 +520,17 @@ export async function interactWithProcess(args) {
|
|
|
447
520
|
timestamp: now,
|
|
448
521
|
deltaMs: now - startTime,
|
|
449
522
|
source: 'periodic_poll',
|
|
450
|
-
length: newOutput.length
|
|
451
|
-
snippet: newOutput.slice(
|
|
523
|
+
length: newOutput.length,
|
|
524
|
+
snippet: newOutput.slice(0, 50).replace(/\n/g, '\\n')
|
|
452
525
|
});
|
|
453
526
|
}
|
|
454
|
-
output
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
527
|
+
// Full output since the snapshot, bounded like the session buffer it came from
|
|
528
|
+
output += newOutput;
|
|
529
|
+
if (output.length > MAX_BUFFERED_OUTPUT_CHARS) {
|
|
530
|
+
output = output.slice(-MAX_BUFFERED_OUTPUT_CHARS);
|
|
531
|
+
}
|
|
532
|
+
// Analyze current state from the end of the output since the snapshot
|
|
533
|
+
processState = terminalManager.getProcessState(pid, outputSnapshot) ?? analyzeProcessState(output, pid);
|
|
458
534
|
// Exit early if we detect the process is waiting for input
|
|
459
535
|
if (processState.isWaitingForInput) {
|
|
460
536
|
earlyExit = true;
|
|
@@ -465,16 +541,19 @@ export async function interactWithProcess(args) {
|
|
|
465
541
|
resolveOnce();
|
|
466
542
|
return;
|
|
467
543
|
}
|
|
468
|
-
// Also exit if process finished
|
|
469
|
-
if (processState.isFinished) {
|
|
470
|
-
exitReason = 'process_finished';
|
|
471
|
-
resolveOnce();
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
544
|
}
|
|
475
|
-
|
|
476
|
-
|
|
545
|
+
// Also exit once the process has exited, whether or not it wrote
|
|
546
|
+
// anything since the previous poll: no answer can come any more
|
|
547
|
+
const state = terminalManager.getProcessState(pid, outputSnapshot);
|
|
548
|
+
if (state?.isFinished) {
|
|
549
|
+
processState = state;
|
|
550
|
+
exitReason = 'process_finished';
|
|
551
|
+
resolveOnce();
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
if (Date.now() >= deadline) {
|
|
477
555
|
exitReason = 'timeout';
|
|
556
|
+
waitCapped = waitLimit.capped;
|
|
478
557
|
resolveOnce();
|
|
479
558
|
}
|
|
480
559
|
}, pollIntervalMs);
|
|
@@ -482,11 +561,13 @@ export async function interactWithProcess(args) {
|
|
|
482
561
|
};
|
|
483
562
|
await waitForResponse();
|
|
484
563
|
// Clean and format output
|
|
485
|
-
let cleanOutput = cleanProcessOutput(output, input);
|
|
564
|
+
let cleanOutput = cleanProcessOutput(output, input, readAtPrompt);
|
|
486
565
|
const timeoutReached = !earlyExit && !processState?.isFinished && !processState?.isWaitingForInput;
|
|
487
566
|
// Apply output line limit to prevent context overflow
|
|
488
567
|
let truncationMessage = '';
|
|
489
568
|
const outputLines = cleanOutput.split('\n');
|
|
569
|
+
const totalLines = cleanOutput.trim().length > 0 ? outputLines.length : 0;
|
|
570
|
+
const shownLines = Math.min(totalLines, maxOutputLines);
|
|
490
571
|
if (outputLines.length > maxOutputLines) {
|
|
491
572
|
const truncatedLines = outputLines.slice(0, maxOutputLines);
|
|
492
573
|
cleanOutput = truncatedLines.join('\n');
|
|
@@ -495,7 +576,7 @@ export async function interactWithProcess(args) {
|
|
|
495
576
|
}
|
|
496
577
|
// Determine final state
|
|
497
578
|
if (!processState) {
|
|
498
|
-
processState = analyzeProcessState(output, pid);
|
|
579
|
+
processState = terminalManager.getProcessState(pid, outputSnapshot) ?? analyzeProcessState(output, pid);
|
|
499
580
|
}
|
|
500
581
|
let statusMessage = '';
|
|
501
582
|
if (processState.isWaitingForInput) {
|
|
@@ -523,12 +604,23 @@ export async function interactWithProcess(args) {
|
|
|
523
604
|
};
|
|
524
605
|
timingMessage = formatTimingInfo(timingInfo);
|
|
525
606
|
}
|
|
607
|
+
// A capped wait didn't reach the caller's timeout_ms: the process is still
|
|
608
|
+
// running and the caller continues with read_process_output
|
|
609
|
+
const structuredContent = {
|
|
610
|
+
pid,
|
|
611
|
+
status: getProcessStatus(processState, timeoutReached && !waitCapped),
|
|
612
|
+
truncated: totalLines > shownLines,
|
|
613
|
+
shownLines,
|
|
614
|
+
totalLines,
|
|
615
|
+
...getWaitCapFields(timeoutReached && waitCapped ? waitLimit.capMs : undefined),
|
|
616
|
+
};
|
|
526
617
|
if (cleanOutput.trim().length === 0 && !timeoutReached) {
|
|
527
618
|
return {
|
|
528
619
|
content: [{
|
|
529
620
|
type: "text",
|
|
530
621
|
text: `✅ Input executed in process ${pid}.\n📭 (No output produced)${statusMessage}${timingMessage}`
|
|
531
622
|
}],
|
|
623
|
+
structuredContent,
|
|
532
624
|
};
|
|
533
625
|
}
|
|
534
626
|
// Format response with better structure and consistent emojis
|
|
@@ -553,6 +645,7 @@ export async function interactWithProcess(args) {
|
|
|
553
645
|
type: "text",
|
|
554
646
|
text: responseText
|
|
555
647
|
}],
|
|
648
|
+
structuredContent,
|
|
556
649
|
};
|
|
557
650
|
}
|
|
558
651
|
catch (error) {
|
|
@@ -588,11 +681,15 @@ export async function forceTerminate(args) {
|
|
|
588
681
|
}],
|
|
589
682
|
};
|
|
590
683
|
}
|
|
591
|
-
|
|
684
|
+
// Returns once the session's processes are gone, so a success means they no longer run
|
|
685
|
+
const outcome = await terminalManager.forceTerminate(pid);
|
|
686
|
+
if (outcome === 'failed') {
|
|
687
|
+
return terminationFailedResult(pid);
|
|
688
|
+
}
|
|
592
689
|
return {
|
|
593
690
|
content: [{
|
|
594
691
|
type: "text",
|
|
595
|
-
text:
|
|
692
|
+
text: outcome === 'terminated'
|
|
596
693
|
? `Successfully initiated termination of session ${pid}`
|
|
597
694
|
: `No active session found for PID ${pid}`
|
|
598
695
|
}],
|
|
@@ -619,5 +716,11 @@ export async function listSessions() {
|
|
|
619
716
|
? 'No active sessions'
|
|
620
717
|
: allSessions.join('\n')
|
|
621
718
|
}],
|
|
719
|
+
structuredContent: {
|
|
720
|
+
sessions: [
|
|
721
|
+
...sessions.map(s => ({ pid: s.pid, type: 'process', isBlocked: s.isBlocked, runtimeMs: s.runtime })),
|
|
722
|
+
...virtualSessions.map(s => ({ pid: s.pid, type: s.type, timeoutMs: s.timeout_ms })),
|
|
723
|
+
],
|
|
724
|
+
},
|
|
622
725
|
};
|
|
623
726
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { LazyPackage } from '../../utils/lazy-package.js';
|
|
1
2
|
export interface ImageInfo {
|
|
2
3
|
/** Object ID within PDF */
|
|
3
4
|
objId: number;
|
|
@@ -24,6 +25,7 @@ export interface ImageCompressionOptions {
|
|
|
24
25
|
/** Maximum dimension to resize to (maintains aspect ratio) */
|
|
25
26
|
maxDimension?: number;
|
|
26
27
|
}
|
|
28
|
+
export declare const unpdfPackage: LazyPackage<Promise<typeof import("unpdf")>>;
|
|
27
29
|
/**
|
|
28
30
|
* Optimized image extraction from PDF using unpdf's built-in extractImages method
|
|
29
31
|
* @param pdfBuffer PDF file as Uint8Array
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { LazyPackage } from '../../utils/lazy-package.js';
|
|
2
|
+
// import(): unpdf is an ES module only. If it fails, Node keeps it failed until a restart.
|
|
3
|
+
export const unpdfPackage = new LazyPackage('unpdf', 'PDF reading support', () => import('unpdf'), true);
|
|
2
4
|
/**
|
|
3
5
|
* Optimized image extraction from PDF using unpdf's built-in extractImages method
|
|
4
6
|
* @param pdfBuffer PDF file as Uint8Array
|
|
@@ -7,6 +9,7 @@ import { getDocumentProxy, extractImages } from 'unpdf';
|
|
|
7
9
|
* @returns Record of page numbers to extracted images
|
|
8
10
|
*/
|
|
9
11
|
export async function extractImagesFromPdf(pdfBuffer, pageNumbers, compressionOptions = {}) {
|
|
12
|
+
const { getDocumentProxy, extractImages } = await unpdfPackage.load();
|
|
10
13
|
const pdfDocument = await getDocumentProxy(pdfBuffer);
|
|
11
14
|
const pagesToProcess = pageNumbers || Array.from({ length: pdfDocument.numPages }, (_, i) => i + 1);
|
|
12
15
|
const pageResults = {};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
export { editPdf } from './manipulations.js';
|
|
1
|
+
export { editPdf, insertRenderOptions, pdfLibPackage } from './manipulations.js';
|
|
2
2
|
export type { PdfOperations, PdfInsertOperation, PdfDeleteOperation } from './manipulations.js';
|
|
3
|
-
export { parsePdfToMarkdown, parseMarkdownToPdf } from './markdown.js';
|
|
3
|
+
export { parsePdfToMarkdown, parseMarkdownToPdf, resolveRender, mdToPdfPackage } from './markdown.js';
|
|
4
|
+
export type { IgnoredRenderOption } from './markdown.js';
|
|
5
|
+
export { pdf2mdPackage } from './lib/pdf2md.js';
|
|
4
6
|
export type { PdfMetadata, PdfPageItem } from './lib/pdf2md.js';
|
|
5
|
-
export { extractImagesFromPdf } from './extract-images.js';
|
|
7
|
+
export { extractImagesFromPdf, unpdfPackage } from './extract-images.js';
|
|
6
8
|
export type { ImageInfo, PageImages } from './extract-images.js';
|
package/dist/tools/pdf/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
-
export { editPdf } from './manipulations.js';
|
|
2
|
-
export { parsePdfToMarkdown, parseMarkdownToPdf } from './markdown.js';
|
|
3
|
-
export {
|
|
1
|
+
export { editPdf, insertRenderOptions, pdfLibPackage } from './manipulations.js';
|
|
2
|
+
export { parsePdfToMarkdown, parseMarkdownToPdf, resolveRender, mdToPdfPackage } from './markdown.js';
|
|
3
|
+
export { pdf2mdPackage } from './lib/pdf2md.js';
|
|
4
|
+
export { extractImagesFromPdf, unpdfPackage } from './extract-images.js';
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
+
import { LazyPackage } from '../../../utils/lazy-package.js';
|
|
1
2
|
import { ImageInfo } from '../extract-images.js';
|
|
3
|
+
export declare const pdf2mdPackage: LazyPackage<{
|
|
4
|
+
parse: any;
|
|
5
|
+
makeTransformations: any;
|
|
6
|
+
transform: any;
|
|
7
|
+
}>;
|
|
2
8
|
/**
|
|
3
9
|
* PDF metadata structure
|
|
4
10
|
*/
|
|
@@ -30,7 +36,8 @@ export type PageRange = {
|
|
|
30
36
|
/**
|
|
31
37
|
* Reads a PDF and converts it to Markdown, returning structured data.
|
|
32
38
|
* @param pdfBuffer The PDF buffer to convert.
|
|
33
|
-
* @param pageNumbers The page numbers to extract. If empty, all pages are extracted
|
|
39
|
+
* @param pageNumbers The page numbers to extract. If an empty array, all pages are extracted;
|
|
40
|
+
* a range that selects no pages (offset past the last page, length 0) extracts none.
|
|
34
41
|
* @returns A Promise that resolves to a PdfParseResult object containing the parsed data.
|
|
35
42
|
*/
|
|
36
43
|
export declare function pdf2md(pdfBuffer: Uint8Array, pageNumbers?: number[] | PageRange): Promise<PdfParseResult>;
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { createRequire } from 'module';
|
|
2
|
+
import { LazyPackage } from '../../../utils/lazy-package.js';
|
|
2
3
|
import { generatePageNumbers } from '../utils.js';
|
|
3
4
|
import { extractImagesFromPdf } from '../extract-images.js';
|
|
4
5
|
const require = createRequire(import.meta.url);
|
|
5
|
-
const
|
|
6
|
-
const {
|
|
6
|
+
export const pdf2mdPackage = new LazyPackage('@opendocsg/pdf2md', 'PDF reading support', () => {
|
|
7
|
+
const { parse } = require('@opendocsg/pdf2md/lib/util/pdf');
|
|
8
|
+
const { makeTransformations, transform } = require('@opendocsg/pdf2md/lib/util/transformations');
|
|
9
|
+
return { parse, makeTransformations, transform };
|
|
10
|
+
});
|
|
7
11
|
/**
|
|
8
12
|
* Extracts metadata from a PDF document.
|
|
9
13
|
* @param pdfDocument The PDF document to extract metadata from.
|
|
@@ -23,21 +27,24 @@ const extractMetadata = ({ pdfDocument, metadata }) => ({
|
|
|
23
27
|
/**
|
|
24
28
|
* Reads a PDF and converts it to Markdown, returning structured data.
|
|
25
29
|
* @param pdfBuffer The PDF buffer to convert.
|
|
26
|
-
* @param pageNumbers The page numbers to extract. If empty, all pages are extracted
|
|
30
|
+
* @param pageNumbers The page numbers to extract. If an empty array, all pages are extracted;
|
|
31
|
+
* a range that selects no pages (offset past the last page, length 0) extracts none.
|
|
27
32
|
* @returns A Promise that resolves to a PdfParseResult object containing the parsed data.
|
|
28
33
|
*/
|
|
29
34
|
export async function pdf2md(pdfBuffer, pageNumbers = []) {
|
|
35
|
+
const { parse, makeTransformations, transform } = pdf2mdPackage.load();
|
|
30
36
|
const result = await parse(pdfBuffer);
|
|
31
37
|
const { fonts, pages, pdfDocument } = result;
|
|
32
38
|
// Calculate which pages to process
|
|
39
|
+
const allPages = Array.isArray(pageNumbers) && pageNumbers.length === 0;
|
|
33
40
|
const filterPageNumbers = Array.isArray(pageNumbers) ?
|
|
34
41
|
pageNumbers :
|
|
35
42
|
generatePageNumbers(pageNumbers.offset, pageNumbers.length, pages.length);
|
|
36
43
|
// Filter and transform pages
|
|
37
|
-
const pagesToProcess =
|
|
44
|
+
const pagesToProcess = allPages ?
|
|
38
45
|
pages :
|
|
39
46
|
pages.filter((_, index) => filterPageNumbers.includes(index + 1));
|
|
40
|
-
const pageNumberMap =
|
|
47
|
+
const pageNumberMap = allPages ?
|
|
41
48
|
pages.map((_, index) => index + 1) :
|
|
42
49
|
filterPageNumbers.filter(pageNum => pageNum >= 1 && pageNum <= pages.length);
|
|
43
50
|
const transformations = makeTransformations(fonts.map);
|
|
@@ -1,13 +1,24 @@
|
|
|
1
|
+
import type { PDFDocument as PDFDocumentType } from 'pdf-lib';
|
|
2
|
+
import { LazyPackage } from '../../utils/lazy-package.js';
|
|
1
3
|
import type { PdfInsertOperationSchema, PdfDeleteOperationSchema, PdfOperationSchema } from '../schemas.js';
|
|
2
4
|
import { z } from 'zod';
|
|
3
5
|
type PdfInsertOperation = z.infer<typeof PdfInsertOperationSchema>;
|
|
4
6
|
type PdfDeleteOperation = z.infer<typeof PdfDeleteOperationSchema>;
|
|
5
7
|
type PdfOperations = z.infer<typeof PdfOperationSchema>;
|
|
6
8
|
export type { PdfOperations, PdfInsertOperation, PdfDeleteOperation };
|
|
9
|
+
export declare const pdfLibPackage: LazyPackage<{
|
|
10
|
+
PDFDocument: typeof PDFDocumentType;
|
|
11
|
+
}>;
|
|
12
|
+
/**
|
|
13
|
+
* The render options for an inserted page's markdown: the call's options, with
|
|
14
|
+
* the page size and margins of the original first page (pageLayout), then the
|
|
15
|
+
* call's pdf_options, then the insert's own pdfOptions, each over the one before.
|
|
16
|
+
*/
|
|
17
|
+
export declare function insertRenderOptions(op: PdfInsertOperation, options?: Record<string, any>, pageLayout?: Record<string, unknown>): Record<string, any>;
|
|
7
18
|
/**
|
|
8
19
|
* Edit an existing PDF by deleting or inserting pages
|
|
9
20
|
* @param pdfPath Path to the PDF file to edit
|
|
10
21
|
* @param operations List of operations to perform
|
|
11
22
|
* @returns The modified PDF as a Uint8Array
|
|
12
23
|
*/
|
|
13
|
-
export declare function editPdf(pdfPath: string, operations: PdfOperations[]): Promise<Uint8Array>;
|
|
24
|
+
export declare function editPdf(pdfPath: string, operations: PdfOperations[], options?: Record<string, any>): Promise<Uint8Array>;
|