@wonderwhy-er/desktop-commander 0.2.51 → 0.3.1-alpha.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/README.md +14 -24
- package/dist/command-manager.d.ts +7 -2
- package/dist/command-manager.js +16 -11
- package/dist/config-manager.d.ts +49 -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 +32 -4
- package/dist/remote-device/broadcast-analytics.d.ts +28 -0
- package/dist/remote-device/broadcast-analytics.js +41 -0
- package/dist/remote-device/desktop-commander-integration.d.ts +20 -0
- package/dist/remote-device/desktop-commander-integration.js +121 -40
- package/dist/remote-device/device-authenticator.d.ts +13 -1
- package/dist/remote-device/device-authenticator.js +87 -47
- package/dist/remote-device/device.d.ts +14 -0
- package/dist/remote-device/device.js +244 -51
- package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
- package/dist/remote-device/mqtt-enrollment.js +162 -0
- package/dist/remote-device/mqtt-transport.d.ts +44 -0
- package/dist/remote-device/mqtt-transport.js +197 -0
- package/dist/remote-device/remote-channel.d.ts +64 -3
- package/dist/remote-device/remote-channel.js +317 -48
- package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
- package/dist/remote-device/transport-analytics.d.ts +29 -0
- package/dist/remote-device/transport-analytics.js +44 -0
- 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 +77 -92
- 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 -1
- package/dist/tools/schemas.js +15 -6
- package/dist/tools/search.d.ts +32 -0
- package/dist/tools/search.js +202 -0
- package/dist/types.d.ts +1 -1
- package/dist/ui/config-editor/config-editor-runtime.js +6 -6
- package/dist/ui/config-editor/src/app.js +2 -15
- 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 +23 -0
- package/dist/utils/lazy-package.js +42 -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.js +9 -7
- package/dist/utils/trackTools.js +2 -1
- 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 +8 -2
- 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/tools/filesystem.js
CHANGED
|
@@ -4,12 +4,13 @@ import os from 'os';
|
|
|
4
4
|
import fetch from 'cross-fetch';
|
|
5
5
|
import { execFile } from 'child_process';
|
|
6
6
|
import { promisify } from 'util';
|
|
7
|
-
import { capture } from '../utils/capture.js';
|
|
7
|
+
import { addToolCallPaths, capture } from '../utils/capture.js';
|
|
8
8
|
import { withTimeout, runWithAbortableTimeout } from '../utils/withTimeout.js';
|
|
9
9
|
import { configManager } from '../config-manager.js';
|
|
10
|
-
import { getFileHandler, TextFileHandler } from '../utils/files/index.js';
|
|
10
|
+
import { getFileHandler, TextFileHandler, isImageAnswer } from '../utils/files/index.js';
|
|
11
11
|
import { isPdfFile } from "./mime-types.js";
|
|
12
|
-
import { parsePdfToMarkdown, editPdf, parseMarkdownToPdf } from './pdf/index.js';
|
|
12
|
+
import { parsePdfToMarkdown, editPdf, insertRenderOptions, parseMarkdownToPdf, resolveRender } from './pdf/index.js';
|
|
13
|
+
import { movePath } from '../utils/rename.js';
|
|
13
14
|
// CONSTANTS SECTION - Consolidate all timeouts and thresholds
|
|
14
15
|
const FILE_OPERATION_TIMEOUTS = {
|
|
15
16
|
PATH_VALIDATION: 10000, // 10 seconds
|
|
@@ -152,6 +153,107 @@ async function validateParentDirectories(directoryPath) {
|
|
|
152
153
|
return validateParentDirectories(parentDir);
|
|
153
154
|
}
|
|
154
155
|
}
|
|
156
|
+
// Most links followed while resolving one path before it counts as a loop (Linux's limit)
|
|
157
|
+
const MAX_LINKS_FOLLOWED = 40;
|
|
158
|
+
/**
|
|
159
|
+
* Resolves a path to where file operations on it land, like fs.realpath, but
|
|
160
|
+
* also for paths that don't exist yet (e.g. a file about to be written).
|
|
161
|
+
*
|
|
162
|
+
* Missing names are kept under their resolved parent. A dangling link (a
|
|
163
|
+
* symlink or Windows junction - Node reports both as symlinks - whose target
|
|
164
|
+
* doesn't exist) is followed to its target, because writing through it creates
|
|
165
|
+
* the target. Relative targets resolve against the link's real directory,
|
|
166
|
+
* chains are followed link by link, and loops fail with ELOOP.
|
|
167
|
+
*
|
|
168
|
+
* @param absolutePath Absolute path to resolve
|
|
169
|
+
* @returns Promise<string> The real path, or where the path would be created
|
|
170
|
+
* @throws Filesystem errors other than ENOENT, or ELOOP for a link loop
|
|
171
|
+
*/
|
|
172
|
+
async function resolveRealPath(absolutePath) {
|
|
173
|
+
let linksFollowed = 0;
|
|
174
|
+
const resolveFrom = async (currentPath) => {
|
|
175
|
+
try {
|
|
176
|
+
return await fs.realpath(currentPath, { encoding: 'utf8' });
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
if (error.code !== 'ENOENT')
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
const parent = path.dirname(currentPath);
|
|
183
|
+
if (parent === currentPath) {
|
|
184
|
+
return currentPath; // a root that doesn't exist, e.g. an unmapped drive
|
|
185
|
+
}
|
|
186
|
+
// Resolve the parent first so links along the way are followed, and a
|
|
187
|
+
// relative link target is read against the link's real directory
|
|
188
|
+
const resolvedParent = await resolveFrom(parent);
|
|
189
|
+
const candidate = path.join(resolvedParent, path.basename(currentPath));
|
|
190
|
+
let isLink;
|
|
191
|
+
try {
|
|
192
|
+
isLink = (await fs.lstat(candidate)).isSymbolicLink();
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
if (error.code !== 'ENOENT')
|
|
196
|
+
throw error;
|
|
197
|
+
return candidate; // doesn't exist yet: this is where it would be created
|
|
198
|
+
}
|
|
199
|
+
if (!isLink) {
|
|
200
|
+
return candidate;
|
|
201
|
+
}
|
|
202
|
+
// Dangling link: a write through it lands on its target, so resolve that instead
|
|
203
|
+
if (++linksFollowed > MAX_LINKS_FOLLOWED) {
|
|
204
|
+
throw Object.assign(new Error(`ELOOP: too many symbolic links encountered, resolving '${absolutePath}'`), { code: 'ELOOP' });
|
|
205
|
+
}
|
|
206
|
+
const target = await fs.readlink(candidate, { encoding: 'utf8' });
|
|
207
|
+
return resolveFrom(path.resolve(resolvedParent, target));
|
|
208
|
+
};
|
|
209
|
+
return resolveFrom(absolutePath);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Resolves the folder an entry is in, like resolveRealPath, and keeps the
|
|
213
|
+
* entry's own name as written: the entry itself (a link, not what it points
|
|
214
|
+
* to), in the letter case given.
|
|
215
|
+
*/
|
|
216
|
+
async function resolveEntryPath(absolutePath) {
|
|
217
|
+
const parent = path.dirname(absolutePath);
|
|
218
|
+
if (parent === absolutePath) {
|
|
219
|
+
return resolveRealPath(absolutePath); // a root has no folder above it
|
|
220
|
+
}
|
|
221
|
+
return path.join(await resolveRealPath(parent), path.basename(absolutePath));
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* An allowed directory's real path, or null when it can't be read. validatePath
|
|
225
|
+
* checks real paths, so an allowed directory reached through a symlink or
|
|
226
|
+
* junction (macOS: /var -> /private/var) must match by its real path too.
|
|
227
|
+
* When the real path can't be read, only the written form matches, which can
|
|
228
|
+
* only deny, never widen, access.
|
|
229
|
+
*/
|
|
230
|
+
async function getAllowedDirRealPath(allowedDir) {
|
|
231
|
+
try {
|
|
232
|
+
return await fs.realpath(expandHome(allowedDir));
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Whether a normalized path is an allowed directory or inside it
|
|
240
|
+
*/
|
|
241
|
+
function isWithinAllowedDir(normalizedPathToCheck, allowedDir) {
|
|
242
|
+
let normalizedAllowedDir = normalizePath(allowedDir);
|
|
243
|
+
if (normalizedAllowedDir.slice(-1) === path.sep) {
|
|
244
|
+
normalizedAllowedDir = normalizedAllowedDir.slice(0, -1);
|
|
245
|
+
}
|
|
246
|
+
// Check if path is exactly the allowed directory
|
|
247
|
+
if (normalizedPathToCheck === normalizedAllowedDir) {
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
// Check if path is a subdirectory of the allowed directory
|
|
251
|
+
// Make sure to add a separator to prevent partial directory name matches
|
|
252
|
+
// e.g. /home/user vs /home/username
|
|
253
|
+
// An allowed drive root (D:\, normalized to d:) allows its whole drive this
|
|
254
|
+
// way, whatever the letter: the paths checked here are always absolute (d:\...)
|
|
255
|
+
return normalizedPathToCheck.startsWith(normalizedAllowedDir + path.sep);
|
|
256
|
+
}
|
|
155
257
|
/**
|
|
156
258
|
* Checks if a path is within any of the allowed directories
|
|
157
259
|
*
|
|
@@ -168,41 +270,43 @@ async function isPathAllowed(pathToCheck) {
|
|
|
168
270
|
if (normalizedPathToCheck.slice(-1) === path.sep) {
|
|
169
271
|
normalizedPathToCheck = normalizedPathToCheck.slice(0, -1);
|
|
170
272
|
}
|
|
171
|
-
//
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
if (normalizedAllowedDir === 'c:' && process.platform === 'win32') {
|
|
190
|
-
return normalizedPathToCheck.startsWith('c:');
|
|
273
|
+
// As written first: no filesystem call, so an allowed directory on an
|
|
274
|
+
// unresponsive mount can't hold up a path inside another one
|
|
275
|
+
if (allowedDirectories.some((allowedDir) => isWithinAllowedDir(normalizedPathToCheck, allowedDir))) {
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
// Then by real path: the first match answers, so a real path that never
|
|
279
|
+
// resolves only holds up a path that no other allowed directory contains
|
|
280
|
+
return new Promise((resolve) => {
|
|
281
|
+
let pending = allowedDirectories.length;
|
|
282
|
+
for (const allowedDir of allowedDirectories) {
|
|
283
|
+
void getAllowedDirRealPath(allowedDir).then((realPath) => {
|
|
284
|
+
if (realPath !== null && isWithinAllowedDir(normalizedPathToCheck, realPath)) {
|
|
285
|
+
resolve(true);
|
|
286
|
+
}
|
|
287
|
+
if (--pending === 0) {
|
|
288
|
+
resolve(false);
|
|
289
|
+
}
|
|
290
|
+
});
|
|
191
291
|
}
|
|
192
|
-
return false;
|
|
193
292
|
});
|
|
194
|
-
return isAllowed;
|
|
195
293
|
}
|
|
196
294
|
/**
|
|
197
295
|
* Validates a path to ensure it can be accessed or created.
|
|
198
296
|
* For existing paths, returns the real path (resolving symlinks).
|
|
199
|
-
* For non-existent paths,
|
|
297
|
+
* For non-existent paths, returns where they would be created (resolving the
|
|
298
|
+
* existing ancestors and any dangling link), and validates parent directories.
|
|
299
|
+
*
|
|
300
|
+
* With `entry`, the path names an entry to rename (move_file): links are
|
|
301
|
+
* followed up to its folder, and its own name is kept as written, so a link
|
|
302
|
+
* is renamed as a link and a change of letter case is kept. A rename only
|
|
303
|
+
* ever touches that entry, never what a link at that name points to.
|
|
200
304
|
*
|
|
201
305
|
* @param requestedPath The path to validate
|
|
202
306
|
* @returns Promise<string> The validated path
|
|
203
307
|
* @throws Error if the path or its parent directories don't exist or if the path is not allowed
|
|
204
308
|
*/
|
|
205
|
-
export async function validatePath(requestedPath) {
|
|
309
|
+
export async function validatePath(requestedPath, { entry = false } = {}) {
|
|
206
310
|
const validationOperation = async () => {
|
|
207
311
|
// Expand home directory if present
|
|
208
312
|
const expandedPath = expandHome(requestedPath);
|
|
@@ -210,59 +314,29 @@ export async function validatePath(requestedPath) {
|
|
|
210
314
|
const absoluteOriginal = path.isAbsolute(expandedPath)
|
|
211
315
|
? path.resolve(expandedPath)
|
|
212
316
|
: path.resolve(process.cwd(), expandedPath);
|
|
213
|
-
//
|
|
214
|
-
|
|
215
|
-
//
|
|
216
|
-
//
|
|
217
|
-
//
|
|
218
|
-
|
|
317
|
+
// Every form of this path an error text may name, so telemetry replaces it whole
|
|
318
|
+
addToolCallPaths(requestedPath, expandedPath, absoluteOriginal);
|
|
319
|
+
// SECURITY: Resolve symlinks (and Windows junctions) to where file operations
|
|
320
|
+
// on this path actually land, and check that location. This covers paths that
|
|
321
|
+
// don't exist yet (a new file under a linked directory) and dangling links:
|
|
322
|
+
// otherwise a link inside an allowed directory pointing to a missing file
|
|
323
|
+
// elsewhere would let a write create that file outside the allowed directories.
|
|
324
|
+
let pathForNextCheck;
|
|
219
325
|
try {
|
|
220
|
-
|
|
326
|
+
pathForNextCheck = entry
|
|
327
|
+
? await resolveEntryPath(absoluteOriginal)
|
|
328
|
+
: await resolveRealPath(absoluteOriginal);
|
|
221
329
|
}
|
|
222
330
|
catch (error) {
|
|
331
|
+
// Permission denied, I/O errors, link loops, ...
|
|
223
332
|
const err = error;
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
});
|
|
230
|
-
throw new Error(`Failed to resolve symlink for path: ${absoluteOriginal}. Error: ${err.message}`);
|
|
231
|
-
}
|
|
232
|
-
// SECURITY FIX: When the full path doesn't exist (e.g., writing a new file),
|
|
233
|
-
// resolve the parent directory to detect symlinks in the path chain.
|
|
234
|
-
// Without this, an attacker could create a symlink inside an allowed directory
|
|
235
|
-
// pointing to a restricted location, then write to a non-existent file through
|
|
236
|
-
// that symlink — bypassing the directory restriction check.
|
|
237
|
-
try {
|
|
238
|
-
const parentDir = path.dirname(absoluteOriginal);
|
|
239
|
-
const resolvedParent = await fs.realpath(parentDir, { encoding: 'utf8' });
|
|
240
|
-
const basename = path.basename(absoluteOriginal);
|
|
241
|
-
resolvedRealPath = path.join(resolvedParent, basename);
|
|
242
|
-
}
|
|
243
|
-
catch {
|
|
244
|
-
// Parent also doesn't exist — walk up the tree to find
|
|
245
|
-
// the deepest existing ancestor and resolve it
|
|
246
|
-
let current = absoluteOriginal;
|
|
247
|
-
let remaining = [];
|
|
248
|
-
while (true) {
|
|
249
|
-
const parent = path.dirname(current);
|
|
250
|
-
if (parent === current)
|
|
251
|
-
break; // reached filesystem root
|
|
252
|
-
remaining.unshift(path.basename(current));
|
|
253
|
-
current = parent;
|
|
254
|
-
try {
|
|
255
|
-
const resolvedAncestor = await fs.realpath(current, { encoding: 'utf8' });
|
|
256
|
-
resolvedRealPath = path.join(resolvedAncestor, ...remaining);
|
|
257
|
-
break;
|
|
258
|
-
}
|
|
259
|
-
catch {
|
|
260
|
-
// keep walking up
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
}
|
|
333
|
+
capture('server_path_realpath_error', {
|
|
334
|
+
error: err.message,
|
|
335
|
+
path: absoluteOriginal
|
|
336
|
+
});
|
|
337
|
+
throw new Error(`Failed to resolve symlink for path: ${absoluteOriginal}. Error: ${err.message}`);
|
|
264
338
|
}
|
|
265
|
-
|
|
339
|
+
addToolCallPaths(pathForNextCheck);
|
|
266
340
|
// Check if path is allowed
|
|
267
341
|
if (!(await isPathAllowed(pathForNextCheck))) {
|
|
268
342
|
capture('server_path_validation_error', {
|
|
@@ -274,7 +348,7 @@ export async function validatePath(requestedPath) {
|
|
|
274
348
|
// SECURITY: Always return the resolved path (with symlinks resolved) so that
|
|
275
349
|
// all subsequent file operations (read, write, mkdir, etc.) operate on the
|
|
276
350
|
// canonical target, not on a symlink that could point outside allowed directories.
|
|
277
|
-
// pathForNextCheck already holds
|
|
351
|
+
// pathForNextCheck already holds that resolved path from above.
|
|
278
352
|
// Check if path exists
|
|
279
353
|
try {
|
|
280
354
|
// fs.stat() will automatically follow symlinks, so we get existence info
|
|
@@ -307,11 +381,10 @@ export async function validatePath(requestedPath) {
|
|
|
307
381
|
/**
|
|
308
382
|
* Read file content from a URL
|
|
309
383
|
* @param url URL to fetch content from
|
|
384
|
+
* @param svgAsImage An SVG is answered as an image, for the file preview widget; otherwise as text
|
|
310
385
|
* @returns File content or file result with metadata
|
|
311
386
|
*/
|
|
312
|
-
export async function readFileFromUrl(url) {
|
|
313
|
-
// Import the MIME type utilities
|
|
314
|
-
const { isImageFile } = await import('./mime-types.js');
|
|
387
|
+
export async function readFileFromUrl(url, svgAsImage = false) {
|
|
315
388
|
// Set up fetch with timeout
|
|
316
389
|
const controller = new AbortController();
|
|
317
390
|
const timeoutId = setTimeout(() => controller.abort(), FILE_OPERATION_TIMEOUTS.URL_FETCH);
|
|
@@ -326,7 +399,7 @@ export async function readFileFromUrl(url) {
|
|
|
326
399
|
}
|
|
327
400
|
// Get MIME type from Content-Type header or infer from URL
|
|
328
401
|
const contentType = response.headers.get('content-type') || 'text/plain';
|
|
329
|
-
const isImage =
|
|
402
|
+
const isImage = isImageAnswer(contentType, svgAsImage);
|
|
330
403
|
const isPdf = isPdfFile(contentType) || url.toLowerCase().endsWith('.pdf');
|
|
331
404
|
// NEW: Add PDF handling before image check
|
|
332
405
|
if (isPdf) {
|
|
@@ -374,7 +447,7 @@ export async function readFileFromUrl(url) {
|
|
|
374
447
|
* @returns File content or file result with metadata
|
|
375
448
|
*/
|
|
376
449
|
export async function readFileFromDisk(filePath, options) {
|
|
377
|
-
const { offset = 0, sheet, range } = options ?? {};
|
|
450
|
+
const { offset = 0, sheet, range, svgAsImage } = options ?? {};
|
|
378
451
|
let { length } = options ?? {};
|
|
379
452
|
// Add validation for required parameters
|
|
380
453
|
if (!filePath || typeof filePath !== 'string') {
|
|
@@ -437,7 +510,7 @@ export async function readFileFromDisk(filePath, options) {
|
|
|
437
510
|
// (fd/thread freed) rather than leaked until the OS call returns.
|
|
438
511
|
const readOperation = async (signal) => {
|
|
439
512
|
// Get appropriate handler for this file type (async - includes binary detection)
|
|
440
|
-
const handler = await getFileHandler(validPath);
|
|
513
|
+
const handler = await getFileHandler(validPath, { svgAsImage });
|
|
441
514
|
// Use handler to read the file
|
|
442
515
|
const result = await handler.read(validPath, {
|
|
443
516
|
offset,
|
|
@@ -494,10 +567,10 @@ export async function readFileFromDisk(filePath, options) {
|
|
|
494
567
|
* @returns File content or file result with metadata
|
|
495
568
|
*/
|
|
496
569
|
export async function readFile(filePath, options) {
|
|
497
|
-
const { isUrl, offset, length, sheet, range } = options ?? {};
|
|
570
|
+
const { isUrl, offset, length, sheet, range, svgAsImage } = options ?? {};
|
|
498
571
|
return isUrl
|
|
499
|
-
? readFileFromUrl(filePath)
|
|
500
|
-
: readFileFromDisk(filePath, { offset, length, sheet, range });
|
|
572
|
+
? readFileFromUrl(filePath, svgAsImage)
|
|
573
|
+
: readFileFromDisk(filePath, { offset, length, sheet, range, svgAsImage });
|
|
501
574
|
}
|
|
502
575
|
/**
|
|
503
576
|
* Read file content without status messages for internal operations
|
|
@@ -558,8 +631,17 @@ export async function writeFile(filePath, content, mode = 'rewrite') {
|
|
|
558
631
|
// Use handler to write the file
|
|
559
632
|
await handler.write(validPath, content, mode);
|
|
560
633
|
}
|
|
561
|
-
|
|
634
|
+
/**
|
|
635
|
+
* Reads each file; a failure is that file's `error`. `stillLoadingError` (the
|
|
636
|
+
* server's) gives the error for a file whose package is still loading, which
|
|
637
|
+
* is then not read (utils/files/factory.ts).
|
|
638
|
+
*/
|
|
639
|
+
export async function readMultipleFiles(paths, stillLoadingError) {
|
|
562
640
|
return Promise.all(paths.map(async (filePath) => {
|
|
641
|
+
const stillLoading = stillLoadingError?.(filePath);
|
|
642
|
+
if (stillLoading) {
|
|
643
|
+
return { path: filePath, error: stillLoading };
|
|
644
|
+
}
|
|
563
645
|
try {
|
|
564
646
|
const validPath = await validatePath(filePath);
|
|
565
647
|
const fileResult = await readFile(validPath);
|
|
@@ -640,14 +722,19 @@ export async function listDirectory(dirPath, depth = 2) {
|
|
|
640
722
|
for (const entry of entriesToShow) {
|
|
641
723
|
const fullPath = path.join(currentPath, entry.name);
|
|
642
724
|
const displayPath = relativePath ? path.join(relativePath, entry.name) : entry.name;
|
|
725
|
+
// A link (a junction on Windows) to a folder is a folder. A link whose
|
|
726
|
+
// target can't be read stays a [FILE], as every link was before.
|
|
727
|
+
const isDirectory = entry.isDirectory()
|
|
728
|
+
|| (entry.isSymbolicLink() && await fs.stat(fullPath).then((stats) => stats.isDirectory(), () => false));
|
|
643
729
|
// Add this entry to results
|
|
644
|
-
results.push(`${
|
|
730
|
+
results.push(`${isDirectory ? "[DIR]" : "[FILE]"} ${displayPath}`);
|
|
645
731
|
// If it's a directory and we have depth remaining, recurse
|
|
646
|
-
if (
|
|
732
|
+
if (isDirectory && currentDepth > 1) {
|
|
647
733
|
try {
|
|
648
|
-
// Validate the path before recursing
|
|
649
|
-
|
|
650
|
-
await
|
|
734
|
+
// Validate the path before recursing, and list the folder that was
|
|
735
|
+
// checked: a link can be retargeted between the check and the read
|
|
736
|
+
const validatedPath = await validatePath(fullPath);
|
|
737
|
+
await listRecursive(validatedPath, currentDepth - 1, displayPath, false);
|
|
651
738
|
}
|
|
652
739
|
catch (error) {
|
|
653
740
|
// If validation fails or we can't access it, it will be marked as denied
|
|
@@ -662,20 +749,29 @@ export async function listDirectory(dirPath, depth = 2) {
|
|
|
662
749
|
results.push(`[WARNING] ${displayPath}: ${filteredCount} items hidden (showing first ${MAX_NESTED_ITEMS} of ${totalEntries} total)`);
|
|
663
750
|
}
|
|
664
751
|
}
|
|
752
|
+
// A path that is a file lists as that file. Any other path goes on to the
|
|
753
|
+
// listing, which reports why it can't be read ([NOT_FOUND], [DENIED]).
|
|
754
|
+
const stats = await fs.stat(validPath).catch(() => undefined);
|
|
755
|
+
if (stats?.isFile()) {
|
|
756
|
+
return [`[FILE] ${path.basename(validPath)}`];
|
|
757
|
+
}
|
|
665
758
|
await listRecursive(validPath, depth, '', true);
|
|
666
759
|
return results;
|
|
667
760
|
}
|
|
668
761
|
export async function moveFile(sourcePath, destinationPath) {
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
await
|
|
762
|
+
// The entries themselves: a link moves as a link, and a rename that only
|
|
763
|
+
// changes letter case keeps the new case
|
|
764
|
+
const validSourcePath = await validatePath(sourcePath, { entry: true });
|
|
765
|
+
const validDestPath = await validatePath(destinationPath, { entry: true });
|
|
766
|
+
// Across volumes, a copy and then removing the source
|
|
767
|
+
await movePath(validSourcePath, validDestPath);
|
|
672
768
|
}
|
|
673
769
|
export async function searchFiles(rootPath, pattern) {
|
|
674
770
|
// Use the new search manager for better performance
|
|
675
771
|
// This provides a temporary compatibility layer until we fully migrate to search sessions
|
|
676
772
|
const { searchManager } = await import('../search-manager.js');
|
|
677
773
|
try {
|
|
678
|
-
const
|
|
774
|
+
const { sessionId } = await searchManager.startSearch({
|
|
679
775
|
rootPath,
|
|
680
776
|
pattern,
|
|
681
777
|
searchType: 'files',
|
|
@@ -683,33 +779,14 @@ export async function searchFiles(rootPath, pattern) {
|
|
|
683
779
|
maxResults: 5000, // Higher limit for compatibility
|
|
684
780
|
earlyTermination: true, // Use early termination for better performance
|
|
685
781
|
});
|
|
686
|
-
|
|
687
|
-
//
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
allResults.push(searchResult.file);
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
while (!isComplete) {
|
|
698
|
-
await new Promise(resolve => setTimeout(resolve, 100)); // Wait 100ms
|
|
699
|
-
const results = searchManager.readSearchResults(sessionId);
|
|
700
|
-
isComplete = results.isComplete;
|
|
701
|
-
// Add new file paths to results
|
|
702
|
-
for (const searchResult of results.results) {
|
|
703
|
-
if (searchResult.file !== '__LAST_READ_MARKER__' && searchResult.type === 'file') {
|
|
704
|
-
allResults.push(searchResult.file);
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
// Safety check to prevent infinite loops (30 second timeout)
|
|
708
|
-
if (Date.now() - startTime > 30000) {
|
|
709
|
-
searchManager.terminateSearch(sessionId);
|
|
710
|
-
break;
|
|
711
|
-
}
|
|
712
|
-
}
|
|
782
|
+
// Every result of the session once it is complete - each exactly once.
|
|
783
|
+
// Stop a search still running after 30 seconds; it then completes with what it found
|
|
784
|
+
const stopTimer = setTimeout(() => searchManager.terminateSearch(sessionId), 30000);
|
|
785
|
+
const results = await searchManager.waitForCompletion(sessionId)
|
|
786
|
+
.finally(() => clearTimeout(stopTimer));
|
|
787
|
+
const allResults = results
|
|
788
|
+
.filter(searchResult => searchResult.type === 'file')
|
|
789
|
+
.map(searchResult => searchResult.file);
|
|
713
790
|
// Log only the count of found files, not their paths
|
|
714
791
|
capture('server_search_files_complete', {
|
|
715
792
|
resultsCount: allResults.length,
|
|
@@ -788,15 +865,16 @@ export async function getFileInfo(filePath) {
|
|
|
788
865
|
isDirectory: stats.isDirectory(),
|
|
789
866
|
isFile: stats.isFile(),
|
|
790
867
|
permissions: stats.mode.toString(8).slice(-3),
|
|
791
|
-
fileType: 'text',
|
|
868
|
+
fileType: (stats.isDirectory() ? 'directory' : 'text'),
|
|
792
869
|
metadata: undefined,
|
|
793
870
|
};
|
|
794
|
-
// Get appropriate handler for this file type (async - includes binary detection)
|
|
795
|
-
|
|
871
|
+
// Get appropriate handler for this file type (async - includes binary detection).
|
|
872
|
+
// A folder has none: one chosen by its name or content would call it text, or an image.
|
|
873
|
+
const handler = stats.isDirectory() ? null : await getFileHandler(validPath);
|
|
796
874
|
// Use handler to get file info, with fallback
|
|
797
875
|
let fileInfo;
|
|
798
876
|
try {
|
|
799
|
-
fileInfo = await handler.getInfo(validPath);
|
|
877
|
+
fileInfo = handler ? await handler.getInfo(validPath) : fallbackInfo;
|
|
800
878
|
}
|
|
801
879
|
catch (error) {
|
|
802
880
|
// If handler fails, use fallback stats
|
|
@@ -844,9 +922,34 @@ export async function getFileInfo(filePath) {
|
|
|
844
922
|
if (fileInfo.metadata.isBinary) {
|
|
845
923
|
info.isBinary = true;
|
|
846
924
|
}
|
|
925
|
+
// A file its handler couldn't read (e.g. a workbook Excel can't open): say why
|
|
926
|
+
if (fileInfo.metadata.error && fileInfo.metadata.errorMessage) {
|
|
927
|
+
info.errorMessage = fileInfo.metadata.errorMessage;
|
|
928
|
+
}
|
|
847
929
|
}
|
|
848
930
|
return info;
|
|
849
931
|
}
|
|
932
|
+
/**
|
|
933
|
+
* Validate the paths a PDF's page operations use besides the PDF itself: the
|
|
934
|
+
* output path and each inserted PDF. write_pdf and edit_block both modify PDFs,
|
|
935
|
+
* so both check here. An inserted PDF's path is replaced by its validated path.
|
|
936
|
+
*
|
|
937
|
+
* @param validPath The PDF the operations apply to, already validated
|
|
938
|
+
* @returns Where to write the result: outputPath if provided, otherwise the PDF itself
|
|
939
|
+
*/
|
|
940
|
+
export async function validatePdfOperationPaths(validPath, operations, outputPath) {
|
|
941
|
+
// Use outputPath if provided, otherwise overwrite input file
|
|
942
|
+
const targetPath = outputPath ? await validatePath(outputPath) : validPath;
|
|
943
|
+
// Validate paths in operations
|
|
944
|
+
for (const o of operations) {
|
|
945
|
+
if (o.type === 'insert') {
|
|
946
|
+
if (o.sourcePdfPath) {
|
|
947
|
+
o.sourcePdfPath = await validatePath(o.sourcePdfPath);
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
return targetPath;
|
|
952
|
+
}
|
|
850
953
|
/**
|
|
851
954
|
* Write content to a PDF file.
|
|
852
955
|
* Can create a new PDF from Markdown string, or modify an existing PDF using operations.
|
|
@@ -854,6 +957,7 @@ export async function getFileInfo(filePath) {
|
|
|
854
957
|
* @param filePath Path to the output PDF file
|
|
855
958
|
* @param content Markdown string (for creation) or array of operations (for modification)
|
|
856
959
|
* @param options Options for PDF generation or modification. For modification, can include `sourcePdf`.
|
|
960
|
+
* @returns The render options Desktop Commander ignored (see resolveRender), so the caller can report them.
|
|
857
961
|
*/
|
|
858
962
|
export async function writePdf(filePath, content, outputPath, options = {}) {
|
|
859
963
|
const validPath = await validatePath(filePath);
|
|
@@ -869,20 +973,12 @@ export async function writePdf(filePath, content, outputPath, options = {}) {
|
|
|
869
973
|
// Use outputPath if provided, otherwise overwrite input file
|
|
870
974
|
const targetPath = outputPath ? await validatePath(outputPath) : validPath;
|
|
871
975
|
await fs.writeFile(targetPath, pdfBuffer);
|
|
976
|
+
// The render succeeded; report which of the caller's/front matter's options were ignored
|
|
977
|
+
return resolveRender(content, options).ignoredOptions;
|
|
872
978
|
}
|
|
873
979
|
else if (Array.isArray(content)) {
|
|
874
|
-
|
|
875
|
-
const
|
|
876
|
-
const operations = [];
|
|
877
|
-
// Validate paths in operations
|
|
878
|
-
for (const o of content) {
|
|
879
|
-
if (o.type === 'insert') {
|
|
880
|
-
if (o.sourcePdfPath) {
|
|
881
|
-
o.sourcePdfPath = await validatePath(o.sourcePdfPath);
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
operations.push(o);
|
|
885
|
-
}
|
|
980
|
+
const targetPath = await validatePdfOperationPaths(validPath, content, outputPath);
|
|
981
|
+
const operations = [...content];
|
|
886
982
|
capture('server_write_pdf', {
|
|
887
983
|
fileExtension: fileExtension,
|
|
888
984
|
operationCount: operations.length,
|
|
@@ -890,10 +986,20 @@ export async function writePdf(filePath, content, outputPath, options = {}) {
|
|
|
890
986
|
deleteCount: operations.filter(op => op.type === 'delete').length,
|
|
891
987
|
insertCount: operations.filter(op => op.type === 'insert').length
|
|
892
988
|
});
|
|
893
|
-
// Perform the PDF editing
|
|
894
|
-
const modifiedPdfBuffer = await editPdf(validPath, operations);
|
|
989
|
+
// Perform the PDF editing (options render the inserted markdown pages)
|
|
990
|
+
const modifiedPdfBuffer = await editPdf(validPath, operations, options);
|
|
895
991
|
// Write the modified PDF to the output path
|
|
896
992
|
await fs.writeFile(targetPath, modifiedPdfBuffer);
|
|
993
|
+
// Report the options ignored in any inserted page's render options or front matter (once per option)
|
|
994
|
+
const ignored = new Map();
|
|
995
|
+
for (const op of operations) {
|
|
996
|
+
if (op.type === 'insert' && op.markdown !== undefined) {
|
|
997
|
+
for (const ignoredOption of resolveRender(op.markdown, insertRenderOptions(op, options)).ignoredOptions) {
|
|
998
|
+
ignored.set(ignoredOption.option, ignoredOption);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
return [...ignored.values()];
|
|
897
1003
|
}
|
|
898
1004
|
else {
|
|
899
1005
|
throw new Error('Invalid content type for writePdf. Expected string (markdown) or array of operations.');
|
|
@@ -2,18 +2,24 @@ import { ServerResult } from '../types.js';
|
|
|
2
2
|
/**
|
|
3
3
|
* Start a new process (renamed from execute_command)
|
|
4
4
|
* Includes early detection of process waiting for input
|
|
5
|
+
* maxWaitMs: ceiling for this call's wait. The tools always use MAX_PROCESS_WAIT_MS;
|
|
6
|
+
* only in-process callers (tests) pass a smaller one. Not part of the tool schema.
|
|
5
7
|
*/
|
|
6
|
-
export declare function startProcess(args: unknown): Promise<ServerResult>;
|
|
8
|
+
export declare function startProcess(args: unknown, maxWaitMs?: number): Promise<ServerResult>;
|
|
7
9
|
/**
|
|
8
10
|
* Read output from a running process with file-like pagination
|
|
9
11
|
* Supports offset/length parameters for controlled reading
|
|
12
|
+
* maxWaitMs: ceiling for this call's wait. The tools always use MAX_PROCESS_WAIT_MS;
|
|
13
|
+
* only in-process callers (tests) pass a smaller one. Not part of the tool schema.
|
|
10
14
|
*/
|
|
11
|
-
export declare function readProcessOutput(args: unknown): Promise<ServerResult>;
|
|
15
|
+
export declare function readProcessOutput(args: unknown, maxWaitMs?: number): Promise<ServerResult>;
|
|
12
16
|
/**
|
|
13
17
|
* Interact with a running process (renamed from send_input)
|
|
14
18
|
* Automatically detects when process is ready and returns output
|
|
19
|
+
* maxWaitMs: ceiling for this call's wait. The tools always use MAX_PROCESS_WAIT_MS;
|
|
20
|
+
* only in-process callers (tests) pass a smaller one. Not part of the tool schema.
|
|
15
21
|
*/
|
|
16
|
-
export declare function interactWithProcess(args: unknown): Promise<ServerResult>;
|
|
22
|
+
export declare function interactWithProcess(args: unknown, maxWaitMs?: number): Promise<ServerResult>;
|
|
17
23
|
/**
|
|
18
24
|
* Force terminate a process
|
|
19
25
|
*/
|