@wonderwhy-er/desktop-commander 0.2.52 → 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.
Files changed (113) hide show
  1. package/dist/command-manager.d.ts +7 -2
  2. package/dist/command-manager.js +16 -11
  3. package/dist/config-manager.d.ts +49 -3
  4. package/dist/config-manager.js +329 -87
  5. package/dist/config-recovery.d.ts +28 -0
  6. package/dist/config-recovery.js +81 -0
  7. package/dist/config.d.ts +1 -0
  8. package/dist/config.js +9 -0
  9. package/dist/handlers/filesystem-handlers.d.ts +1 -1
  10. package/dist/handlers/filesystem-handlers.js +26 -16
  11. package/dist/handlers/search-answers.d.ts +58 -0
  12. package/dist/handlers/search-answers.js +172 -0
  13. package/dist/handlers/search-handlers.js +4 -92
  14. package/dist/index.js +14 -7
  15. package/dist/npm-scripts/remote.js +2 -3
  16. package/dist/remote-device/broadcast-analytics.d.ts +28 -0
  17. package/dist/remote-device/broadcast-analytics.js +41 -0
  18. package/dist/remote-device/desktop-commander-integration.js +19 -25
  19. package/dist/remote-device/device.d.ts +14 -0
  20. package/dist/remote-device/device.js +137 -30
  21. package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
  22. package/dist/remote-device/mqtt-enrollment.js +162 -0
  23. package/dist/remote-device/mqtt-transport.d.ts +44 -0
  24. package/dist/remote-device/mqtt-transport.js +197 -0
  25. package/dist/remote-device/remote-channel.d.ts +12 -0
  26. package/dist/remote-device/remote-channel.js +55 -8
  27. package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
  28. package/dist/remote-device/transport-analytics.d.ts +29 -0
  29. package/dist/remote-device/transport-analytics.js +44 -0
  30. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  31. package/dist/remote-device/transport-telemetry.js +48 -0
  32. package/dist/search-manager.d.ts +239 -27
  33. package/dist/search-manager.js +746 -312
  34. package/dist/server.js +44 -11
  35. package/dist/terminal-manager.d.ts +138 -21
  36. package/dist/terminal-manager.js +300 -215
  37. package/dist/tools/config.d.ts +1 -1
  38. package/dist/tools/config.js +21 -70
  39. package/dist/tools/edit.js +12 -4
  40. package/dist/tools/filesystem.d.ts +30 -6
  41. package/dist/tools/filesystem.js +246 -140
  42. package/dist/tools/improved-process-tools.d.ts +9 -3
  43. package/dist/tools/improved-process-tools.js +171 -68
  44. package/dist/tools/pdf/extract-images.d.ts +2 -0
  45. package/dist/tools/pdf/extract-images.js +4 -1
  46. package/dist/tools/pdf/index.d.ts +5 -3
  47. package/dist/tools/pdf/index.js +4 -3
  48. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  49. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  50. package/dist/tools/pdf/manipulations.d.ts +12 -1
  51. package/dist/tools/pdf/manipulations.js +17 -4
  52. package/dist/tools/pdf/markdown.d.ts +96 -0
  53. package/dist/tools/pdf/markdown.js +485 -20
  54. package/dist/tools/pdf/utils.d.ts +2 -2
  55. package/dist/tools/pdf/utils.js +4 -4
  56. package/dist/tools/process.js +8 -5
  57. package/dist/tools/schemas.d.ts +1 -1
  58. package/dist/tools/schemas.js +15 -6
  59. package/dist/tools/search.d.ts +32 -0
  60. package/dist/tools/search.js +202 -0
  61. package/dist/types.d.ts +1 -1
  62. package/dist/ui/config-editor/config-editor-runtime.js +6 -6
  63. package/dist/ui/config-editor/src/app.js +2 -15
  64. package/dist/utils/ab-test.js +27 -9
  65. package/dist/utils/atomic-write.d.ts +14 -0
  66. package/dist/utils/atomic-write.js +80 -0
  67. package/dist/utils/capture.d.ts +17 -1
  68. package/dist/utils/capture.js +177 -68
  69. package/dist/utils/exit-process.d.ts +24 -0
  70. package/dist/utils/exit-process.js +31 -0
  71. package/dist/utils/feature-flags.js +2 -1
  72. package/dist/utils/files/base.d.ts +3 -1
  73. package/dist/utils/files/docx.d.ts +3 -0
  74. package/dist/utils/files/docx.js +24 -9
  75. package/dist/utils/files/excel.d.ts +10 -0
  76. package/dist/utils/files/excel.js +93 -33
  77. package/dist/utils/files/factory.d.ts +22 -1
  78. package/dist/utils/files/factory.js +59 -4
  79. package/dist/utils/files/image.d.ts +12 -4
  80. package/dist/utils/files/image.js +19 -8
  81. package/dist/utils/files/index.d.ts +5 -3
  82. package/dist/utils/files/index.js +4 -3
  83. package/dist/utils/files/pdf.js +18 -36
  84. package/dist/utils/files/text.d.ts +21 -5
  85. package/dist/utils/files/text.js +90 -86
  86. package/dist/utils/internal-facts.d.ts +3 -0
  87. package/dist/utils/internal-facts.js +23 -0
  88. package/dist/utils/lazy-package.d.ts +23 -0
  89. package/dist/utils/lazy-package.js +42 -0
  90. package/dist/utils/open-browser.js +2 -1
  91. package/dist/utils/process-detection.d.ts +24 -5
  92. package/dist/utils/process-detection.js +199 -89
  93. package/dist/utils/process-tree.d.ts +14 -0
  94. package/dist/utils/process-tree.js +223 -0
  95. package/dist/utils/rename.d.ts +9 -0
  96. package/dist/utils/rename.js +74 -0
  97. package/dist/utils/ripgrep-resolver.js +9 -14
  98. package/dist/utils/shell.d.ts +42 -0
  99. package/dist/utils/shell.js +187 -0
  100. package/dist/utils/system-info.js +9 -7
  101. package/dist/utils/trackTools.js +2 -1
  102. package/dist/version.d.ts +1 -1
  103. package/dist/version.js +1 -1
  104. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  105. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  106. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  107. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  108. package/package.json +8 -2
  109. package/vendor/telemetry-contract/README.md +56 -0
  110. package/vendor/telemetry-contract/package.json +32 -0
  111. package/vendor/telemetry-contract/transport.d.ts +38 -0
  112. package/vendor/telemetry-contract/transport.js +164 -0
  113. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -1,13 +1,153 @@
1
1
  import fs from 'fs/promises';
2
+ import { randomBytes } from 'crypto';
3
+ import { channel } from 'diagnostics_channel';
2
4
  import { existsSync, readdirSync } from 'fs';
3
- import { dirname, isAbsolute, join, relative, resolve, sep } from 'path';
4
- import { mdToPdf } from 'md-to-pdf';
5
+ import { createServer } from 'http';
6
+ import { createRequire } from 'module';
7
+ import { tmpdir, userInfo } from 'os';
8
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';
5
9
  import { pdf2md } from './lib/pdf2md.js';
6
10
  import { CONFIG_FILE } from '../../config.js';
11
+ import { LazyPackage } from '../../utils/lazy-package.js';
7
12
  const isUrl = (source) => source.startsWith('http://') || source.startsWith('https://');
8
13
  // Cached Chrome path to avoid repeated lookups
9
14
  let cachedChromePath = null; // null = not checked yet
10
15
  let chromeCheckPromise = null;
16
+ /** Name prefix of the temporary Chrome profile folder each PDF render gets */
17
+ const CHROME_PROFILE_PREFIX = 'desktop-commander-chrome-profile-';
18
+ /** Longest the removal of a render's Chrome profile waits for Chrome to let go of it */
19
+ const CHROME_PROFILE_REMOVAL_BUDGET_MS = 60000;
20
+ const CHROME_PROFILE_REMOVAL_RETRY_MS = 250;
21
+ /** Node announces every child process it creates on this channel */
22
+ const childProcessChannel = channel('child_process');
23
+ /** Longest a render waits for its Chrome to exit once it has been told to stop */
24
+ const CHROME_EXIT_WAIT_MS = 10000;
25
+ /** Cookie a render's Chrome sends to its web server; nothing else gets in */
26
+ const RENDER_COOKIE_NAME = 'desktop-commander-pdf-render';
27
+ const require = createRequire(import.meta.url);
28
+ // md-to-pdf, with its own Puppeteer, file server and front matter parser, loaded the
29
+ // way md-to-pdf loads them (they are its dependencies, not Desktop Commander's)
30
+ export const mdToPdfPackage = new LazyPackage('md-to-pdf', 'PDF writing support', () => {
31
+ const requireFromMdToPdf = createRequire(require.resolve('md-to-pdf'));
32
+ const { convertMdToPdf } = require('md-to-pdf/dist/lib/md-to-pdf.js');
33
+ const { defaultConfig } = require('md-to-pdf/dist/lib/config.js');
34
+ const puppeteer = requireFromMdToPdf('puppeteer');
35
+ const serveHandler = requireFromMdToPdf('serve-handler');
36
+ const grayMatter = requireFromMdToPdf('gray-matter');
37
+ return { convertMdToPdf, defaultConfig, puppeteer, serveHandler, grayMatter };
38
+ });
39
+ const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
40
+ /**
41
+ * The md-to-pdf options Desktop Commander ignores, and why. Every other option
42
+ * from write_pdf's `options` and from the markdown's front matter applies as
43
+ * md-to-pdf normally applies it. These few are ignored because they would let
44
+ * the markdown or the caller write the PDF somewhere other than the requested
45
+ * path (dest, pdf_options.path), run a different program as the renderer
46
+ * (launch_options.executablePath), pass their own flags to it
47
+ * (launch_options.args), change the browser process in other ways (every
48
+ * launch option but ALLOWED_LAUNCH_OPTIONS), or hold the browser open forever
49
+ * (devtools). Desktop Commander writes the PDF itself, to the validated path,
50
+ * and runs the renderer on a browser and profile it controls.
51
+ */
52
+ const IGNORED_RENDER_OPTIONS = {
53
+ 'dest': 'Desktop Commander writes the PDF only to the path you requested',
54
+ 'devtools': 'Desktop Commander does not open the renderer with devtools (it would never finish)',
55
+ 'pdf_options.path': 'Desktop Commander writes the PDF only to the path you requested',
56
+ 'launch_options.executablePath': 'Desktop Commander chooses the browser used to render',
57
+ 'launch_options.args': 'Desktop Commander controls the arguments the browser is launched with',
58
+ };
59
+ /**
60
+ * The launch_options (Puppeteer's LaunchOptions) that apply: they only change
61
+ * how the page renders or how long Desktop Commander waits. Every other launch
62
+ * option is ignored. Those set what runs and how: the browser's environment
63
+ * (env, which could preload a library into it or undo the Windows profile
64
+ * fix), where its output goes (dumpio pipes it to stdout, the MCP
65
+ * connection), how Desktop Commander connects to it (pipe, debuggingPort,
66
+ * protocol), its arguments and extensions (ignoreDefaultArgs,
67
+ * enableExtensions), where it saves downloads (downloadBehavior), which browser
68
+ * runs (browser, channel), or how this process handles signals (handleSIGINT,
69
+ * ...). An allowlist, so an option a later Puppeteer adds is ignored too.
70
+ */
71
+ const ALLOWED_LAUNCH_OPTIONS = new Set([
72
+ 'headless', 'timeout', 'protocolTimeout', 'slowMo', 'defaultViewport',
73
+ 'acceptInsecureCerts', 'networkEnabled', 'waitForInitialPage',
74
+ ]);
75
+ const LAUNCH_OPTION_REASON = `Desktop Commander controls how the browser is launched; of launch_options, only ${[...ALLOWED_LAUNCH_OPTIONS].join(', ')} apply`;
76
+ /**
77
+ * The caller's gray_matter_options over md-to-pdf's defaults, with the
78
+ * JavaScript engine off whatever the caller says: a caller's settings (even
79
+ * `{}` or null) replaced the defaults and switched it back on, so a `---js`
80
+ * header, or any header with `language: 'javascript'`, ran in the server.
81
+ * gray-matter finds an engine by name, then by alias (js -> javascript), so
82
+ * both names are switched off.
83
+ */
84
+ function safeGrayMatterOptions(callerOptions) {
85
+ const { defaultConfig } = mdToPdfPackage.load();
86
+ // md-to-pdf's switch-off of gray-matter's JavaScript engine, which evaluates the header's code
87
+ const disabledJsEngine = defaultConfig.gray_matter_options.engines.javascript;
88
+ const caller = isPlainObject(callerOptions) ? callerOptions : {};
89
+ const callerEngines = isPlainObject(caller.engines) ? caller.engines : {};
90
+ return {
91
+ ...defaultConfig.gray_matter_options,
92
+ ...caller,
93
+ engines: { ...callerEngines, js: disabledJsEngine, javascript: disabledJsEngine },
94
+ };
95
+ }
96
+ /**
97
+ * The single place write_pdf's `options` and the markdown's front matter are
98
+ * merged. Front matter wins (as in md-to-pdf), pdf_options is merged key by
99
+ * key, and the options Desktop Commander ignores are removed from the merged
100
+ * result AFTER the merge, so neither source can re-add them. Returns the
101
+ * markdown body without its front matter, so the caller can render it without
102
+ * md-to-pdf merging the front matter a second time.
103
+ */
104
+ export function resolveRender(markdown, options = {}) {
105
+ const { grayMatter } = mdToPdfPackage.load();
106
+ const fromOptions = isPlainObject(options) ? options : {};
107
+ // Parse the front matter the way md-to-pdf would, with the caller's
108
+ // gray_matter_options, but never with gray-matter's JavaScript engine
109
+ const grayMatterOptions = safeGrayMatterOptions(fromOptions.gray_matter_options);
110
+ const { content, data } = grayMatter(markdown, grayMatterOptions);
111
+ const frontMatter = isPlainObject(data) ? data : {};
112
+ // md-to-pdf's merge: front matter over options, with pdf_options merged key by key
113
+ const merged = { ...fromOptions, ...frontMatter };
114
+ // md-to-pdf's own parse (it finds no front matter in the body) gets the same settings
115
+ if ('gray_matter_options' in merged) {
116
+ merged.gray_matter_options = grayMatterOptions;
117
+ }
118
+ const optionsPdf = isPlainObject(fromOptions.pdf_options) ? fromOptions.pdf_options : {};
119
+ const frontMatterPdf = isPlainObject(frontMatter.pdf_options) ? frontMatter.pdf_options : {};
120
+ if ('pdf_options' in fromOptions || 'pdf_options' in frontMatter) {
121
+ merged.pdf_options = { ...optionsPdf, ...frontMatterPdf };
122
+ }
123
+ if (isPlainObject(merged.launch_options)) {
124
+ merged.launch_options = { ...merged.launch_options };
125
+ }
126
+ const ignoredOptions = [];
127
+ const ignore = (option) => ignoredOptions.push({ option, reason: IGNORED_RENDER_OPTIONS[option] ?? LAUNCH_OPTION_REASON });
128
+ if ('dest' in merged) {
129
+ ignore('dest');
130
+ delete merged.dest;
131
+ }
132
+ if ('devtools' in merged) {
133
+ ignore('devtools');
134
+ delete merged.devtools;
135
+ }
136
+ if (isPlainObject(merged.pdf_options) && 'path' in merged.pdf_options) {
137
+ ignore('pdf_options.path');
138
+ delete merged.pdf_options.path;
139
+ }
140
+ if (isPlainObject(merged.launch_options)) {
141
+ const launchOptions = merged.launch_options;
142
+ for (const key of Object.keys(launchOptions)) {
143
+ if (ALLOWED_LAUNCH_OPTIONS.has(key))
144
+ continue;
145
+ ignore(`launch_options.${key}`);
146
+ delete launchOptions[key];
147
+ }
148
+ }
149
+ return { body: content, options: merged, ignoredOptions };
150
+ }
11
151
  /**
12
152
  * Get Desktop Commander's private Puppeteer cache directory.
13
153
  */
@@ -110,19 +250,28 @@ export async function pruneOldPuppeteerChromeBuilds(activeExecutablePath, cacheD
110
250
  }
111
251
  }));
112
252
  }
253
+ /**
254
+ * Where Chrome and Chromium install on Windows. Windows is not always on C:,
255
+ * so the Program Files and local app data folders come from Windows' own
256
+ * settings. ProgramW6432 is the 64-bit Program Files seen from a 32-bit Node.
257
+ */
258
+ function windowsChromePaths() {
259
+ const env = process.env;
260
+ const programFiles = [...new Set([env.ProgramFiles, env.ProgramW6432, env['ProgramFiles(x86)']])]
261
+ .filter((dir) => Boolean(dir));
262
+ return [
263
+ ...programFiles.map(dir => join(dir, 'Google', 'Chrome', 'Application', 'chrome.exe')),
264
+ ...(env.LOCALAPPDATA ? [join(env.LOCALAPPDATA, 'Google', 'Chrome', 'Application', 'chrome.exe')] : []),
265
+ ...programFiles.map(dir => join(dir, 'Chromium', 'Application', 'chrome.exe')),
266
+ ];
267
+ }
113
268
  /**
114
269
  * Find system-installed Chrome/Chromium browser
115
270
  * Returns the executable path if found, undefined otherwise
116
271
  */
117
- function findSystemChrome() {
272
+ export function findSystemChrome() {
118
273
  const paths = process.platform === 'win32'
119
- ? [
120
- 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
121
- 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
122
- `${process.env.LOCALAPPDATA}\\Google\\Chrome\\Application\\chrome.exe`,
123
- 'C:\\Program Files\\Chromium\\Application\\chrome.exe',
124
- 'C:\\Program Files (x86)\\Chromium\\Application\\chrome.exe',
125
- ]
274
+ ? windowsChromePaths()
126
275
  : process.platform === 'darwin'
127
276
  ? [
128
277
  '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
@@ -139,6 +288,269 @@ function findSystemChrome() {
139
288
  ];
140
289
  return paths.find(p => existsSync(p));
141
290
  }
291
+ /**
292
+ * Environment for the Chrome process that renders PDFs.
293
+ *
294
+ * Google Chrome (136+) refuses remote debugging, which Puppeteer needs to
295
+ * drive it, whenever it cannot resolve its default profile directory, even
296
+ * though Puppeteer runs it on a separate temporary profile. On Windows Chrome
297
+ * resolves that directory under %USERPROFILE%\AppData\Local and fails if the
298
+ * folder is missing, so when Desktop Commander runs with USERPROFILE pointing
299
+ * at any other folder (e.g. a relocated home), Chrome starts without a
300
+ * DevTools endpoint and Puppeteer times out with a misleading "The browser is
301
+ * already running" error. Chrome gets the account's real profile folder,
302
+ * which Windows reports from the logon token regardless of environment
303
+ * overrides; the rest of the environment is passed through unchanged.
304
+ */
305
+ function getChromeEnvironment() {
306
+ if (process.platform !== 'win32') {
307
+ return undefined;
308
+ }
309
+ let profileDir;
310
+ try {
311
+ profileDir = userInfo().homedir;
312
+ }
313
+ catch (error) {
314
+ console.error("Could not read the account's profile folder for Chrome:", error);
315
+ return undefined;
316
+ }
317
+ // Windows env names are case-insensitive: drop every spelling before setting ours
318
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toUpperCase() !== 'USERPROFILE'));
319
+ return { ...env, USERPROFILE: profileDir };
320
+ }
321
+ /**
322
+ * Temporary Chrome profile folder for one PDF render.
323
+ *
324
+ * Chrome gets a profile folder we create and remove instead of Puppeteer's
325
+ * own: Puppeteer deletes a profile it created itself, and after a failed
326
+ * launch it does so before stopping Chrome, in a promise nobody awaits. On
327
+ * Windows the delete fails with EBUSY and the unhandled rejection takes the
328
+ * whole server down. Puppeteer leaves a userDataDir it was given alone.
329
+ *
330
+ * The folder can only be removed once that Chrome has exited: Windows refuses
331
+ * to delete files a running process holds open, and a Chrome that is still
332
+ * starting up recreates a folder deleted under it. Puppeteer does not hand out the Chrome
333
+ * process when the launch fails (it stops it itself about 5 seconds later),
334
+ * so the process is picked up from Node's child_process diagnostics channel
335
+ * by its --user-data-dir argument, and release() stops it right away.
336
+ *
337
+ * Chrome gets the folder as an argument rather than as Puppeteer's userDataDir
338
+ * option: Puppeteer turns that option into one of its default arguments, and a
339
+ * caller's ignoreDefaultArgs: true drops those, after which Puppeteer creates
340
+ * a profile of its own again.
341
+ */
342
+ async function createChromeProfile() {
343
+ const dir = await fs.mkdtemp(join(tmpdir(), CHROME_PROFILE_PREFIX));
344
+ const userDataDirArg = `--user-data-dir=${resolve(dir)}`;
345
+ let chrome;
346
+ const onChildProcess = (message) => {
347
+ const child = message.process;
348
+ // The channel announces a child before spawning it; its arguments are set in the same tick
349
+ queueMicrotask(() => {
350
+ if (child.spawnargs?.includes(userDataDirArg)) {
351
+ chrome = child;
352
+ }
353
+ });
354
+ };
355
+ childProcessChannel.subscribe(onChildProcess);
356
+ return {
357
+ arg: userDataDirArg,
358
+ release: async () => {
359
+ childProcessChannel.unsubscribe(onChildProcess);
360
+ await stopChrome(chrome);
361
+ void removeChromeProfile(dir, chrome);
362
+ },
363
+ };
364
+ }
365
+ /**
366
+ * Stops a render's Chrome if it still runs and waits for it to exit, for at
367
+ * most CHROME_EXIT_WAIT_MS. Once a render is over only a failed launch (or a
368
+ * browser that could not be closed) leaves Chrome running.
369
+ */
370
+ async function stopChrome(chrome) {
371
+ if (!chrome || chrome.pid === undefined || chrome.exitCode !== null || chrome.signalCode !== null) {
372
+ return;
373
+ }
374
+ const exited = new Promise((resolve) => {
375
+ setTimeout(resolve, CHROME_EXIT_WAIT_MS).unref();
376
+ chrome.once('exit', () => resolve());
377
+ });
378
+ chrome.kill();
379
+ await exited;
380
+ }
381
+ /**
382
+ * Removes a render's Chrome profile once its Chrome (if one was started) has
383
+ * exited. Never throws, and its timers do not keep the process alive: a
384
+ * profile that cannot be removed within the budget is left in the temp folder.
385
+ */
386
+ async function removeChromeProfile(profileDir, chrome) {
387
+ const deadline = Date.now() + CHROME_PROFILE_REMOVAL_BUDGET_MS;
388
+ if (chrome && chrome.exitCode === null && chrome.signalCode === null) {
389
+ await new Promise((resolve) => {
390
+ setTimeout(resolve, CHROME_PROFILE_REMOVAL_BUDGET_MS).unref();
391
+ chrome.once('exit', () => resolve());
392
+ // A process error means it's gone too: stop waiting
393
+ chrome.once('error', () => resolve());
394
+ });
395
+ }
396
+ for (;;) {
397
+ try {
398
+ await fs.rm(profileDir, { recursive: true, force: true });
399
+ return;
400
+ }
401
+ catch (error) {
402
+ // Chrome's helper processes can hold files a moment longer than the browser process
403
+ if (Date.now() >= deadline) {
404
+ console.error(`Could not remove Chrome profile ${profileDir}:`, error);
405
+ return;
406
+ }
407
+ await new Promise((resolve) => setTimeout(resolve, CHROME_PROFILE_REMOVAL_RETRY_MS).unref());
408
+ }
409
+ }
410
+ }
411
+ /** A stylesheet md-to-pdf loads as a URL; anything else it reads from disk (md-to-pdf's isHttpUrl) */
412
+ const isHttpUrl = (input) => {
413
+ try {
414
+ return new URL(input).protocol.startsWith('http');
415
+ }
416
+ catch {
417
+ // Not a URL: a path
418
+ return false;
419
+ }
420
+ };
421
+ /**
422
+ * The files md-to-pdf reads from disk into the page it renders, from write_pdf's
423
+ * options or the front matter: stylesheet paths, script paths, and the
424
+ * highlight style (a file name in highlight.js's styles folder). Each must be
425
+ * inside the allowed folders, checked as every file tool checks a path, and is
426
+ * replaced in `render` by the path the check resolved (links followed): md-to-pdf
427
+ * then reads the file that was checked, even if a link on the way is changed
428
+ * after the check. md-to-pdf's own stylesheet and highlight styles are not the
429
+ * caller's files and stay allowed.
430
+ *
431
+ * Returns the paths as the caller gave them, by the checked path read instead,
432
+ * for the errors (nameGivenPaths).
433
+ */
434
+ async function validateRenderFiles(render, validatePath) {
435
+ const givenPaths = new Map();
436
+ const check = async (file) => {
437
+ const checked = await validatePath(file);
438
+ if (checked !== file && !givenPaths.has(checked))
439
+ givenPaths.set(checked, file);
440
+ return checked;
441
+ };
442
+ // md-to-pdf takes one value or a list
443
+ const eachOf = async (value, checkItem) => Array.isArray(value) ? Promise.all(value.map(checkItem)) : checkItem(value);
444
+ if ('stylesheet' in render) {
445
+ render.stylesheet = await eachOf(render.stylesheet, async (stylesheet) => typeof stylesheet === 'string' && stylesheet !== '' && !isHttpUrl(stylesheet) ? check(stylesheet) : stylesheet);
446
+ }
447
+ if ('script' in render) {
448
+ render.script = await eachOf(render.script, async (script) => isPlainObject(script) && typeof script.path === 'string' ? { ...script, path: await check(script.path) } : script);
449
+ }
450
+ if (typeof render.highlight_style === 'string') {
451
+ // Where md-to-pdf looks for it
452
+ const stylesFolder = resolve(dirname(createRequire(createRequire(import.meta.url).resolve('md-to-pdf')).resolve('highlight.js')), '..', 'styles');
453
+ const style = resolve(stylesFolder, `${render.highlight_style}.css`);
454
+ const inStylesFolder = relative(stylesFolder, style);
455
+ if (inStylesFolder === '..' || inStylesFolder.startsWith(`..${sep}`) || isAbsolute(inStylesFolder)) {
456
+ const checked = await check(style);
457
+ // md-to-pdf reads <styles folder>/<highlight_style>.css: name the checked file that way
458
+ if (!checked.endsWith('.css')) {
459
+ throw new Error(`highlight_style ${render.highlight_style} (${style}) is a link to a file that is not a .css file`);
460
+ }
461
+ render.highlight_style = relative(stylesFolder, checked.slice(0, -'.css'.length));
462
+ }
463
+ }
464
+ return givenPaths;
465
+ }
466
+ /**
467
+ * The render reads the checked paths (links resolved: on macOS a temporary file
468
+ * given as /var/... is read as /private/var/...). An error from it names each
469
+ * file as the caller gave it instead, as it did before the render read the
470
+ * checked paths.
471
+ */
472
+ function nameGivenPaths(error, givenPaths) {
473
+ if (!(error instanceof Error) || givenPaths.size === 0)
474
+ return;
475
+ // Longest first, so a checked path that starts a longer one isn't replaced inside it
476
+ const pairs = [...givenPaths].sort(([a], [b]) => b.length - a.length);
477
+ const asGiven = (text) => pairs.reduce((named, [checked, given]) => named.split(checked).join(given), text);
478
+ error.message = asGiven(error.message);
479
+ if (error.stack)
480
+ error.stack = asGiven(error.stack);
481
+ const withPath = error;
482
+ if (typeof withPath.path === 'string')
483
+ withPath.path = asGiven(withPath.path);
484
+ }
485
+ /**
486
+ * Serve a file of the render's base folder only if it is inside the allowed
487
+ * folders, checked as every file tool checks it (links resolved): markdown must
488
+ * not embed a file from outside them, whether the base folder is the working
489
+ * folder or reaches outside through a linked folder. The file served is the one
490
+ * the check resolved, not the URL's path looked up again, so a link on the way
491
+ * that is changed after the check doesn't lead elsewhere.
492
+ */
493
+ async function serveAllowedFile(request, response, basedir) {
494
+ // Imported when used: tools/filesystem.js loads this module
495
+ const { validatePath } = await import('../filesystem.js');
496
+ let file;
497
+ try {
498
+ // The file the URL names in the base folder
499
+ const pathname = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname);
500
+ file = await validatePath(join(basedir, pathname));
501
+ }
502
+ catch {
503
+ // Outside the allowed folders (or not a file path): refused, not served
504
+ response.writeHead(403, { 'Content-Type': 'text/plain' }).end('Forbidden');
505
+ return;
506
+ }
507
+ // serve-handler serves exactly that file (no .html redirects, which would name it from another folder).
508
+ // It reads only the request's url and headers; the request itself keeps its URL.
509
+ const forFile = { url: `/${encodeURIComponent(basename(file))}`, headers: request.headers };
510
+ await mdToPdfPackage.load().serveHandler(forFile, response, { public: dirname(file), directoryListing: false, cleanUrls: false });
511
+ }
512
+ /**
513
+ * Local web server for one PDF render.
514
+ *
515
+ * md-to-pdf loads the page it renders from http://localhost:<port>/, served
516
+ * from the markdown's base folder (Desktop Commander's working folder unless
517
+ * the caller passes basedir), so relative and absolute image paths in the
518
+ * markdown load. md-to-pdf's own server listens on every network interface,
519
+ * answers anyone, and is closed only after a successful render: after a
520
+ * failed one it kept serving the working folder until Desktop Commander
521
+ * restarted. This one listens on 127.0.0.1 only, answers only requests that
522
+ * carry a random cookie set in the render's own Chrome, and serves files, not
523
+ * folder listings, only from inside the allowed folders (serveAllowedFile).
524
+ */
525
+ async function startRenderServer(basedir) {
526
+ const cookie = { name: RENDER_COOKIE_NAME, value: randomBytes(32).toString('hex') };
527
+ const expected = `${cookie.name}=${cookie.value}`;
528
+ const server = createServer((request, response) => {
529
+ if (!request.headers.cookie?.split(/;\s*/).includes(expected)) {
530
+ response.writeHead(403, { 'Content-Type': 'text/plain' }).end('Forbidden');
531
+ return;
532
+ }
533
+ serveAllowedFile(request, response, basedir).catch((error) => {
534
+ console.error('The PDF render server could not serve a file:', error);
535
+ if (!response.headersSent)
536
+ response.writeHead(500);
537
+ response.end();
538
+ });
539
+ });
540
+ await new Promise((resolve, reject) => {
541
+ server.once('error', reject);
542
+ server.listen(0, '127.0.0.1', resolve);
543
+ });
544
+ return {
545
+ port: server.address().port,
546
+ cookie,
547
+ close: () => new Promise((resolve) => {
548
+ server.close(() => resolve());
549
+ // Chrome's keep-alive connections would hold close() open
550
+ server.closeAllConnections();
551
+ }),
552
+ };
553
+ }
142
554
  /**
143
555
  * Download and install Chrome using @puppeteer/browsers
144
556
  * Returns the executable path after installation
@@ -245,23 +657,70 @@ export async function parsePdfToMarkdown(source, pageNumbers = []) {
245
657
  throw error;
246
658
  }
247
659
  }
660
+ /**
661
+ * Render markdown to PDF with md-to-pdf's converter in a Chrome of our own.
662
+ *
663
+ * md-to-pdf's mdToPdf() starts its web server and Chrome and stops them only
664
+ * after a successful render. So each render starts its own Chrome profile,
665
+ * web server (startRenderServer) and Chrome here, hands the converter the
666
+ * browser, and releases all of them on every path: when this returns or
667
+ * throws, the server is closed and Chrome, with the page it rendered, has
668
+ * exited.
669
+ *
670
+ * Options are md-to-pdf's, from `options` and the markdown's front matter
671
+ * (resolveRender merges them and drops the few Desktop Commander ignores).
672
+ * The PDF is only returned: Desktop Commander writes it, so the config forces
673
+ * dest to '' (md-to-pdf would otherwise write it to dest, or to stdout - the
674
+ * MCP connection - when dest is undefined).
675
+ */
248
676
  export async function parseMarkdownToPdf(markdown, options = {}) {
677
+ let profile;
678
+ let server;
679
+ let browser;
680
+ // The render files as the caller gave them, by the checked paths the render reads
681
+ let givenPaths = new Map();
249
682
  try {
683
+ const { convertMdToPdf, defaultConfig, puppeteer } = mdToPdfPackage.load();
684
+ // The folder the markdown's files are served from must be inside the allowed folders
685
+ const { validatePath } = await import('../filesystem.js');
686
+ const basedir = options.basedir ? await validatePath(options.basedir) : process.cwd();
687
+ // Merge options and front matter, and drop the ignored ones, in one place
688
+ const { body, options: render } = resolveRender(markdown, options);
689
+ givenPaths = await validateRenderFiles(render, validatePath);
690
+ const launchOptions = isPlainObject(render.launch_options) ? render.launch_options : {};
250
691
  // Find Chrome: puppeteer cache -> system Chrome -> install
251
692
  const chromePath = await getChromePath();
252
- if (chromePath) {
253
- options = {
254
- ...options,
255
- launch_options: {
256
- ...options.launch_options,
257
- executablePath: chromePath,
258
- }
259
- };
260
- }
261
- const pdf = await mdToPdf({ content: markdown }, options);
693
+ const chromeEnv = getChromeEnvironment();
694
+ profile = await createChromeProfile();
695
+ server = await startRenderServer(basedir);
696
+ browser = await puppeteer.launch({
697
+ // Only the launch options resolveRender allows (ALLOWED_LAUNCH_OPTIONS);
698
+ // Desktop Commander's own settings below come after them
699
+ ...launchOptions,
700
+ ...(chromeEnv ? { env: chromeEnv } : {}),
701
+ // Desktop Commander chooses the browser (launch_options.executablePath is dropped by resolveRender)
702
+ ...(chromePath ? { executablePath: chromePath } : {}),
703
+ // Chrome runs on the render's own profile whatever the caller asked for
704
+ // (launch_options.args is dropped by resolveRender; userDataDir is overridden here)
705
+ userDataDir: undefined,
706
+ args: [profile.arg],
707
+ });
708
+ await browser.setCookie({ ...server.cookie, domain: 'localhost', path: '/', httpOnly: true });
709
+ // The config mdToPdf() would build, on our server's port
710
+ const config = {
711
+ ...defaultConfig,
712
+ ...render,
713
+ pdf_options: { ...defaultConfig.pdf_options, ...(isPlainObject(render.pdf_options) ? render.pdf_options : {}) },
714
+ basedir,
715
+ dest: '',
716
+ port: server.port,
717
+ };
718
+ // After a blank line, so the converter finds no front matter of its own to merge
719
+ const pdf = await convertMdToPdf({ content: `\n${body}` }, config, { browser });
262
720
  return pdf.content;
263
721
  }
264
722
  catch (error) {
723
+ nameGivenPaths(error, givenPaths);
265
724
  // Provide helpful error message if Chrome is not found
266
725
  const errorMessage = error instanceof Error ? error.message : String(error);
267
726
  if (errorMessage.includes('Could not find Chrome')) {
@@ -272,4 +731,10 @@ export async function parseMarkdownToPdf(markdown, options = {}) {
272
731
  console.error('Error creating PDF:', error);
273
732
  throw error;
274
733
  }
734
+ finally {
735
+ await server?.close();
736
+ await browser?.close().catch((error) => console.error('Error closing the PDF browser:', error));
737
+ // Also stops a Chrome whose launch failed, which Puppeteer would leave running for 5 more seconds
738
+ await profile?.release();
739
+ }
275
740
  }
@@ -4,9 +4,9 @@
4
4
  export declare const normalizePageIndexes: (pageIndexes: number[], pageCount: number) => number[];
5
5
  /**
6
6
  * Generate page numbers based on offset and length
7
- * @param offset Zero-based offset or negative for counting from end
7
+ * @param offset Zero-based offset or negative for the last pages (length is then ignored, as for lines)
8
8
  * @param length Number of pages to generate
9
9
  * @param totalPages Total number of pages in the document
10
- * @returns Array of page numbers
10
+ * @returns Array of page numbers (empty when the offset is past the last page or length is 0)
11
11
  */
12
12
  export declare function generatePageNumbers(offset: number, length: number, totalPages: number): number[];
@@ -10,10 +10,10 @@ export const normalizePageIndexes = (pageIndexes, pageCount) => {
10
10
  };
11
11
  /**
12
12
  * Generate page numbers based on offset and length
13
- * @param offset Zero-based offset or negative for counting from end
13
+ * @param offset Zero-based offset or negative for the last pages (length is then ignored, as for lines)
14
14
  * @param length Number of pages to generate
15
15
  * @param totalPages Total number of pages in the document
16
- * @returns Array of page numbers
16
+ * @returns Array of page numbers (empty when the offset is past the last page or length is 0)
17
17
  */
18
18
  export function generatePageNumbers(offset, length, totalPages) {
19
19
  // Compute 1-based start page
@@ -24,8 +24,8 @@ export function generatePageNumbers(offset, length, totalPages) {
24
24
  if (startPage > totalPages)
25
25
  return [];
26
26
  const safeStart = Math.max(1, startPage);
27
- // Compute final page (inclusive), truncated by totalPages
28
- const endPage = Math.min(safeStart + length - 1, totalPages);
27
+ // Compute final page (inclusive), truncated by totalPages; a negative offset reads to the last page
28
+ const endPage = offset < 0 ? totalPages : Math.min(safeStart + length - 1, totalPages);
29
29
  const count = endPage - safeStart + 1;
30
30
  if (count <= 0)
31
31
  return [];
@@ -1,8 +1,10 @@
1
- import { exec } from 'child_process';
1
+ import { execFile } from 'child_process';
2
2
  import { promisify } from 'util';
3
3
  import os from 'os';
4
4
  import { KillProcessArgsSchema } from './schemas.js';
5
- const execAsync = promisify(exec);
5
+ import { resolveProgramPath } from '../utils/shell.js';
6
+ import { terminatePid } from '../utils/process-tree.js';
7
+ const execFileAsync = promisify(execFile);
6
8
  /**
7
9
  * Parse `tasklist /FO CSV /NH` output (#662). Fields per row, all quoted:
8
10
  * [Image Name, PID, Session Name, Session#, Mem Usage]. CSV instead of the
@@ -46,9 +48,9 @@ export function parsePsAux(stdout) {
46
48
  }
47
49
  export async function listProcesses() {
48
50
  const isWindows = os.platform() === 'win32';
49
- const command = isWindows ? 'tasklist /FO CSV /NH' : 'ps aux';
51
+ const [program, args] = isWindows ? ['tasklist', ['/FO', 'CSV', '/NH']] : ['ps', ['aux']];
50
52
  try {
51
- const { stdout } = await execAsync(command);
53
+ const { stdout } = await execFileAsync(resolveProgramPath(program), args);
52
54
  const processes = isWindows ? parseWindowsTasklistCsv(stdout) : parsePsAux(stdout);
53
55
  return {
54
56
  content: [{
@@ -73,7 +75,8 @@ export async function killProcess(args) {
73
75
  };
74
76
  }
75
77
  try {
76
- process.kill(parsed.data.pid);
78
+ // Returns once the process is gone, so a success means it no longer runs
79
+ await terminatePid(parsed.data.pid);
77
80
  return {
78
81
  content: [{ type: "text", text: `Successfully terminated process ${parsed.data.pid}` }],
79
82
  };
@@ -67,7 +67,7 @@ export declare const ForceTerminateArgsSchema: z.ZodObject<{
67
67
  }>;
68
68
  export declare const ListSessionsArgsSchema: z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>;
69
69
  export declare const KillProcessArgsSchema: z.ZodObject<{
70
- pid: z.ZodNumber;
70
+ pid: z.ZodEffects<z.ZodNumber, number, number>;
71
71
  }, "strip", z.ZodTypeAny, {
72
72
  pid: number;
73
73
  }, {