@wonderwhy-er/desktop-commander 0.3.2-alpha.1 → 0.3.2

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 (194) hide show
  1. package/dist/bootstrap.js +7 -7
  2. package/dist/command-manager.d.ts +98 -1
  3. package/dist/command-manager.js +237 -16
  4. package/dist/remote-device/desktop-commander-integration.js +3 -1
  5. package/dist/remote-device/diagnostics/redact.js +30 -8
  6. package/dist/remote-device/diagnostics/report.js +30 -13
  7. package/dist/remote-device/mqtt/mqtt-enrollment.js +1 -1
  8. package/dist/remote-device/mqtt/mqtt-transport.js +2 -2
  9. package/dist/remote-device/remote-channel.d.ts +1 -1
  10. package/dist/remote-device/remote-channel.js +1 -1
  11. package/dist/remote-device/transport-telemetry.js +5 -4
  12. package/dist/server.js +2 -0
  13. package/dist/terminal-manager.js +4 -6
  14. package/dist/tools/improved-process-tools.d.ts +2 -0
  15. package/dist/tools/improved-process-tools.js +68 -40
  16. package/dist/tools/pdf/markdown.js +7 -3
  17. package/dist/tools/process.js +10 -2
  18. package/dist/track-installation.js +2 -2
  19. package/dist/ui/config-editor/config-editor-runtime.js +80 -61
  20. package/dist/ui/file-preview/preview-runtime.js +225 -207
  21. package/dist/utils/brace-expansion.d.ts +30 -0
  22. package/dist/utils/brace-expansion.js +192 -0
  23. package/dist/utils/capture.d.ts +8 -2
  24. package/dist/utils/capture.js +1 -1
  25. package/dist/utils/cmd-commands.d.ts +3 -0
  26. package/dist/utils/cmd-commands.js +370 -0
  27. package/dist/utils/command-reading.d.ts +92 -0
  28. package/dist/utils/command-reading.js +14 -0
  29. package/dist/utils/command-wrappers.d.ts +45 -0
  30. package/dist/utils/command-wrappers.js +964 -0
  31. package/dist/utils/inline-shells.d.ts +67 -0
  32. package/dist/utils/inline-shells.js +310 -0
  33. package/dist/utils/posix-commands.d.ts +6 -0
  34. package/dist/utils/posix-commands.js +237 -0
  35. package/dist/utils/posix-shell-capabilities.d.ts +8 -0
  36. package/dist/utils/posix-shell-capabilities.js +120 -0
  37. package/dist/utils/powershell-commands.d.ts +61 -0
  38. package/dist/utils/powershell-commands.js +468 -0
  39. package/dist/utils/process-tree.js +4 -4
  40. package/dist/utils/shell-script-files.d.ts +8 -0
  41. package/dist/utils/shell-script-files.js +140 -0
  42. package/dist/utils/shell.d.ts +37 -0
  43. package/dist/utils/shell.js +73 -0
  44. package/dist/utils/system-info.d.ts +2 -0
  45. package/dist/utils/system-info.js +5 -1
  46. package/dist/utils/threadpool-size.d.ts +36 -0
  47. package/dist/utils/threadpool-size.js +143 -0
  48. package/dist/version.d.ts +1 -1
  49. package/dist/version.js +1 -1
  50. package/package.json +11 -9
  51. package/dist/bootstrap.js.map +0 -1
  52. package/dist/command-manager.js.map +0 -1
  53. package/dist/config-field-definitions.js.map +0 -1
  54. package/dist/config-manager.js.map +0 -1
  55. package/dist/config-recovery.js.map +0 -1
  56. package/dist/config.js.map +0 -1
  57. package/dist/custom-stdio.js.map +0 -1
  58. package/dist/error-handlers.js.map +0 -1
  59. package/dist/handlers/edit-search-handlers.js.map +0 -1
  60. package/dist/handlers/filesystem-handlers.js.map +0 -1
  61. package/dist/handlers/history-handlers.js.map +0 -1
  62. package/dist/handlers/index.js.map +0 -1
  63. package/dist/handlers/process-handlers.js.map +0 -1
  64. package/dist/handlers/search-answers.js.map +0 -1
  65. package/dist/handlers/search-handlers.js.map +0 -1
  66. package/dist/handlers/terminal-handlers.js.map +0 -1
  67. package/dist/index.js.map +0 -1
  68. package/dist/npm-scripts/remote.js.map +0 -1
  69. package/dist/npm-scripts/setup.js.map +0 -1
  70. package/dist/npm-scripts/uninstall.js.map +0 -1
  71. package/dist/npm-scripts/verify-ripgrep.js.map +0 -1
  72. package/dist/remote-device/desktop-commander-integration.js.map +0 -1
  73. package/dist/remote-device/device-authenticator.js.map +0 -1
  74. package/dist/remote-device/device.js.map +0 -1
  75. package/dist/remote-device/diagnostics/device-log.js.map +0 -1
  76. package/dist/remote-device/diagnostics/redact.js.map +0 -1
  77. package/dist/remote-device/diagnostics/report.js.map +0 -1
  78. package/dist/remote-device/diagnostics/upload.js.map +0 -1
  79. package/dist/remote-device/mqtt/config.js.map +0 -1
  80. package/dist/remote-device/mqtt/mqtt-enrollment.js.map +0 -1
  81. package/dist/remote-device/mqtt/mqtt-transport.js.map +0 -1
  82. package/dist/remote-device/realtime-health-telemetry.js.map +0 -1
  83. package/dist/remote-device/remote-channel.js.map +0 -1
  84. package/dist/remote-device/remote-utils.js.map +0 -1
  85. package/dist/remote-device/rollouts.js.map +0 -1
  86. package/dist/remote-device/transport-telemetry.js.map +0 -1
  87. package/dist/search-manager.js.map +0 -1
  88. package/dist/server.js.map +0 -1
  89. package/dist/terminal-manager.js.map +0 -1
  90. package/dist/tools/config.js.map +0 -1
  91. package/dist/tools/edit.js.map +0 -1
  92. package/dist/tools/feedback.js.map +0 -1
  93. package/dist/tools/filesystem.js.map +0 -1
  94. package/dist/tools/fuzzySearch.js.map +0 -1
  95. package/dist/tools/fuzzySearchCore.js.map +0 -1
  96. package/dist/tools/improved-process-tools.js.map +0 -1
  97. package/dist/tools/mime-types.js.map +0 -1
  98. package/dist/tools/pdf/extract-images.js.map +0 -1
  99. package/dist/tools/pdf/index.js.map +0 -1
  100. package/dist/tools/pdf/lib/pdf2md.js.map +0 -1
  101. package/dist/tools/pdf/manipulations.js.map +0 -1
  102. package/dist/tools/pdf/markdown.js.map +0 -1
  103. package/dist/tools/pdf/utils.js.map +0 -1
  104. package/dist/tools/process.js.map +0 -1
  105. package/dist/tools/prompts.js.map +0 -1
  106. package/dist/tools/schemas.js.map +0 -1
  107. package/dist/tools/usage.js.map +0 -1
  108. package/dist/types.js.map +0 -1
  109. package/dist/ui/config-editor/src/app.js.map +0 -1
  110. package/dist/ui/config-editor/src/array-modal.js.map +0 -1
  111. package/dist/ui/config-editor/src/main.js.map +0 -1
  112. package/dist/ui/contracts.js.map +0 -1
  113. package/dist/ui/file-preview/shared/preview-file-types.js.map +0 -1
  114. package/dist/ui/file-preview/src/app.js.map +0 -1
  115. package/dist/ui/file-preview/src/components/code-viewer.js.map +0 -1
  116. package/dist/ui/file-preview/src/components/highlighting.js.map +0 -1
  117. package/dist/ui/file-preview/src/components/html-renderer.js.map +0 -1
  118. package/dist/ui/file-preview/src/components/markdown-renderer.js.map +0 -1
  119. package/dist/ui/file-preview/src/directory-controller.js.map +0 -1
  120. package/dist/ui/file-preview/src/document-layout.js.map +0 -1
  121. package/dist/ui/file-preview/src/document-outline.js.map +0 -1
  122. package/dist/ui/file-preview/src/document-workspace.js.map +0 -1
  123. package/dist/ui/file-preview/src/file-type-handlers.js.map +0 -1
  124. package/dist/ui/file-preview/src/host/external-actions.js.map +0 -1
  125. package/dist/ui/file-preview/src/host/selection-context.js.map +0 -1
  126. package/dist/ui/file-preview/src/image-preview.js.map +0 -1
  127. package/dist/ui/file-preview/src/main.js.map +0 -1
  128. package/dist/ui/file-preview/src/markdown/conflict-dialog.js.map +0 -1
  129. package/dist/ui/file-preview/src/markdown/controller.js.map +0 -1
  130. package/dist/ui/file-preview/src/markdown/editor.js.map +0 -1
  131. package/dist/ui/file-preview/src/markdown/linking.js.map +0 -1
  132. package/dist/ui/file-preview/src/markdown/outline.js.map +0 -1
  133. package/dist/ui/file-preview/src/markdown/parser.js.map +0 -1
  134. package/dist/ui/file-preview/src/markdown/preview.js.map +0 -1
  135. package/dist/ui/file-preview/src/markdown/slugify.js.map +0 -1
  136. package/dist/ui/file-preview/src/markdown/utils.js.map +0 -1
  137. package/dist/ui/file-preview/src/model.js.map +0 -1
  138. package/dist/ui/file-preview/src/panel-actions.js.map +0 -1
  139. package/dist/ui/file-preview/src/path-utils.js.map +0 -1
  140. package/dist/ui/file-preview/src/payload-utils.js.map +0 -1
  141. package/dist/ui/file-preview/src/types.js.map +0 -1
  142. package/dist/ui/resources.js.map +0 -1
  143. package/dist/ui/shared/compact-row.js.map +0 -1
  144. package/dist/ui/shared/escape-html.js.map +0 -1
  145. package/dist/ui/shared/host-context.js.map +0 -1
  146. package/dist/ui/shared/tool-bridge.js.map +0 -1
  147. package/dist/ui/shared/tool-shell.js.map +0 -1
  148. package/dist/ui/shared/ui-event-tracker.js.map +0 -1
  149. package/dist/ui/shared/widget-state.js.map +0 -1
  150. package/dist/utils/ab-test.js.map +0 -1
  151. package/dist/utils/atomic-write.js.map +0 -1
  152. package/dist/utils/capture.js.map +0 -1
  153. package/dist/utils/dockerPrompt.js.map +0 -1
  154. package/dist/utils/exit-process.js.map +0 -1
  155. package/dist/utils/feature-flags.js.map +0 -1
  156. package/dist/utils/files/base.js.map +0 -1
  157. package/dist/utils/files/binary.js.map +0 -1
  158. package/dist/utils/files/docx.js.map +0 -1
  159. package/dist/utils/files/excel.js.map +0 -1
  160. package/dist/utils/files/factory.js.map +0 -1
  161. package/dist/utils/files/image.js.map +0 -1
  162. package/dist/utils/files/index.js.map +0 -1
  163. package/dist/utils/files/pdf.js.map +0 -1
  164. package/dist/utils/files/text.js.map +0 -1
  165. package/dist/utils/fuzzySearchLogger.js.map +0 -1
  166. package/dist/utils/internal-facts.js.map +0 -1
  167. package/dist/utils/lazy-package.js.map +0 -1
  168. package/dist/utils/lineEndingHandler.js.map +0 -1
  169. package/dist/utils/logger.js.map +0 -1
  170. package/dist/utils/mcp-ui-ab-test.js.map +0 -1
  171. package/dist/utils/open-browser.js.map +0 -1
  172. package/dist/utils/process-detection.js.map +0 -1
  173. package/dist/utils/process-tree.js.map +0 -1
  174. package/dist/utils/rename.js.map +0 -1
  175. package/dist/utils/ripgrep-resolver.js.map +0 -1
  176. package/dist/utils/shell.js.map +0 -1
  177. package/dist/utils/system-info.js.map +0 -1
  178. package/dist/utils/terminal-timestamps.js.map +0 -1
  179. package/dist/utils/toolHistory.js.map +0 -1
  180. package/dist/utils/trackTools.js.map +0 -1
  181. package/dist/utils/unsupportedParams.js.map +0 -1
  182. package/dist/utils/usageTracker.js.map +0 -1
  183. package/dist/utils/welcome-onboarding.js.map +0 -1
  184. package/dist/utils/withTimeout.js.map +0 -1
  185. package/dist/version.js.map +0 -1
  186. package/node_modules/@desktop-commander/telemetry-contract/README.md +0 -56
  187. package/node_modules/@desktop-commander/telemetry-contract/package.json +0 -32
  188. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +0 -39
  189. package/node_modules/@desktop-commander/telemetry-contract/transport.js +0 -167
  190. package/vendor/telemetry-contract/README.md +0 -56
  191. package/vendor/telemetry-contract/package.json +0 -32
  192. package/vendor/telemetry-contract/transport.d.ts +0 -38
  193. package/vendor/telemetry-contract/transport.js +0 -164
  194. package/vendor/telemetry-contract/transport.test.js +0 -39
package/dist/bootstrap.js CHANGED
@@ -11,12 +11,12 @@
11
11
  *
12
12
  * Raising the pool size gives enough headroom that a burst of slow reads no
13
13
  * longer starves the rest. libuv reads UV_THREADPOOL_SIZE only when the pool is
14
- * first initialized (on first submitted work), so this assignment has to happen
15
- * before ANY threadpool work — hence "first import". A user-provided value is
16
- * always respected.
14
+ * first initialized (on first submitted work), so this has to happen before
15
+ * ANY threadpool work — hence "first import". On Windows with Node 22, libuv
16
+ * doesn't see a value set inside the process at all, so setThreadpoolSize()
17
+ * starts the server again with it (src/utils/threadpool-size.ts). A
18
+ * user-provided value is always respected.
17
19
  */
20
+ import { setThreadpoolSize } from './utils/threadpool-size.js';
18
21
  const DEFAULT_THREADPOOL_SIZE = 16;
19
- if (!process.env.UV_THREADPOOL_SIZE) {
20
- process.env.UV_THREADPOOL_SIZE = String(DEFAULT_THREADPOOL_SIZE);
21
- }
22
- export {};
22
+ setThreadpoolSize(process.env.UV_THREADPOOL_SIZE || String(DEFAULT_THREADPOOL_SIZE));
@@ -1,3 +1,33 @@
1
+ import { type CommandReadOptions, type CommandReading } from './utils/command-reading.js';
2
+ /**
3
+ * The check's answer for one command.
4
+ * - allowed: no blocked program runs.
5
+ * - blocked: `name` is the blockedCommands entry that one of the programs matched.
6
+ * - unseen: allowed, but some program is chosen only when the command runs
7
+ * (eval "$CMD", Invoke-Expression $cmd, & $tool) or is in a script file
8
+ * (bash deploy.sh). Each entry of `unseen` says what hides one of them.
9
+ * - failed: the check couldn't read the command or the settings, and
10
+ * `reason` holds the error's message.
11
+ */
12
+ export type CommandCheck = {
13
+ verdict: 'allowed';
14
+ } | {
15
+ verdict: 'blocked';
16
+ name: string;
17
+ } | {
18
+ verdict: 'unseen';
19
+ unseen: UnseenProgram[];
20
+ } | {
21
+ verdict: 'failed';
22
+ reason: string;
23
+ };
24
+ /** Something in a command that hides the program it runs from the check */
25
+ export interface UnseenProgram {
26
+ /** What hides it, as the shell reads it (in PowerShell, an alias's target): "eval", "Invoke-Expression", "$tool" or "deploy.sh" */
27
+ what: string;
28
+ /** True for a script/startup file given to a shell; false for a program chosen at runtime. */
29
+ inFile: boolean;
30
+ }
1
31
  declare class CommandManager {
2
32
  getBaseCommand(command: string): string;
3
33
  /**
@@ -7,7 +37,74 @@ declare class CommandManager {
7
37
  */
8
38
  extractCommands(commandString: string, asTyped?: boolean): string[];
9
39
  extractBaseCommand(commandStr: string, asTyped?: boolean): string | null;
10
- validateCommand(command: string): Promise<boolean>;
40
+ /**
41
+ * Reads a command with the grammar of the shell that will run it: POSIX
42
+ * shells (bash, zsh, sh, …), PowerShell, or cmd. fish is read with the
43
+ * bash reader, and where that can't parse fish's own syntax (for … end,
44
+ * echo (date)), as main reads it: by the names extractCommands() finds.
45
+ */
46
+ readCommands(command: string, shell: string, options?: CommandReadOptions): Promise<CommandReading>;
47
+ /**
48
+ * The commands of a reading that run a program: the calls to the script's
49
+ * own functions are left out. A script can define a function with a
50
+ * program's name, such as an error helper named halt, and the shell then
51
+ * runs the function, not the program. A call is the function's when it
52
+ * comes after the definition, its name as written has no folder
53
+ * (/sbin/halt is the program), and the reader lists the function, so not
54
+ * one the text may remove. PowerShell finds a function whatever the case
55
+ * of its name, POSIX shells only by its exact name. The function's body is
56
+ * read as commands of its own, so a blocked program inside it is still
57
+ * found.
58
+ */
59
+ private withoutOwnFunctionCalls;
60
+ /**
61
+ * What hides a program from the check among the commands that run
62
+ * (CommandCheck's `unseen`), in the order the commands start:
63
+ * - a program chosen only when the command runs: a name that is a variable
64
+ * or another command's output (& $tool), or eval and Invoke-Expression,
65
+ * which run text the command builds (eval "$CMD");
66
+ * - a script file given to a shell (bash deploy.sh, or forwarded by runuser): the commands in it
67
+ * aren't in the text. A file named only when the command runs ("$SCRIPT")
68
+ * counts as a program chosen at run time, named by the shell.
69
+ */
70
+ private findUnseen;
71
+ /**
72
+ * What hides the program when a command gives a shell a script or startup file to run
73
+ * (bash deploy.sh, pwsh -File deploy.ps1, source deploy.sh), or when
74
+ * PowerShell runs one named as the command (./deploy.ps1): the file, or the
75
+ * shell when the file is named only when the command runs ("$SCRIPT").
76
+ * A shell's command text or standard input adds no file. An explicit Bash
77
+ * startup file can still run beside command text in interactive mode.
78
+ */
79
+ private scriptFiles;
80
+ /**
81
+ * The check's answer for `command` run by `shell`:
82
+ * - allowed: no program it runs is blocked.
83
+ * - blocked: a program it runs is in blockedCommands, both compared in the
84
+ * form programName() gives; the answer names the entry as written (a call
85
+ * to the script's own function is not the program: see withoutOwnFunctionCalls).
86
+ * - unseen: allowed, but a program is chosen only when the command runs or
87
+ * is in a script file (see findUnseen), so start_process can say the
88
+ * blocklist couldn't check it.
89
+ * - failed: the command or the settings can't be read. In PowerShell a parse
90
+ * error or a missing PowerShell is allowed instead: nothing runs, and
91
+ * PowerShell or start_process answers.
92
+ */
93
+ checkCommand(command: string, shell: string, options?: CommandReadOptions): Promise<CommandCheck>;
94
+ /**
95
+ * checkCommand() for a command, or for a command text in it: each text is
96
+ * checked once per command in each shell, however many readings give it.
97
+ * In pwsh $a pwsh $a … each text gives every later one again, so without
98
+ * this the work doubled with each pair.
99
+ */
100
+ private checkText;
101
+ private checkOnce;
102
+ /** Whether a check's answer refuses the command */
103
+ isRefused(check: CommandCheck): check is Extract<CommandCheck, {
104
+ verdict: 'blocked' | 'failed';
105
+ }>;
106
+ /** Whether the command may run in `shell`: the check doesn't refuse it */
107
+ validateCommand(command: string, shell: string): Promise<boolean>;
11
108
  }
12
109
  export declare const commandManager: CommandManager;
13
110
  export {};
@@ -1,6 +1,15 @@
1
1
  import path from 'path';
2
+ import fs from 'fs';
2
3
  import { configManager } from './config-manager.js';
3
4
  import { capture } from "./utils/capture.js";
5
+ import { getShellType, isShellAvailable, programName, resolveShellPath } from './utils/shell.js';
6
+ import { sameShellTexts, shellRuns } from './utils/inline-shells.js';
7
+ import { shellScriptFiles } from './utils/shell-script-files.js';
8
+ import { readPosixCommands } from './utils/posix-commands.js';
9
+ import { readPowerShellCommands } from './utils/powershell-commands.js';
10
+ import { readCmdCommands } from './utils/cmd-commands.js';
11
+ import { withStartedPrograms } from './utils/command-wrappers.js';
12
+ import { IncompleteArgumentsError, requireCompleteArguments } from './utils/command-reading.js';
4
13
  class CommandManager {
5
14
  getBaseCommand(command) {
6
15
  return command.split(' ')[0].toLowerCase().trim();
@@ -211,36 +220,248 @@ class CommandManager {
211
220
  return null;
212
221
  }
213
222
  }
214
- async validateCommand(command) {
223
+ /**
224
+ * Reads a command with the grammar of the shell that will run it: POSIX
225
+ * shells (bash, zsh, sh, …), PowerShell, or cmd. fish is read with the
226
+ * bash reader, and where that can't parse fish's own syntax (for … end,
227
+ * echo (date)), as main reads it: by the names extractCommands() finds.
228
+ */
229
+ async readCommands(command, shell, options = {}) {
230
+ switch (getShellType(shell)) {
231
+ case 'powershell':
232
+ return readPowerShellCommands(command, shell);
233
+ case 'cmd':
234
+ return readCmdCommands(command, options);
235
+ }
236
+ // Resolve the actual caller selection, not the adapter's anchored launch alias.
237
+ // Only filesystem identity is read here; unknown endpoints keep the legacy reading.
238
+ let selectedEndpoint;
239
+ const selected = resolveShellPath(shell);
240
+ if (selected !== null) {
241
+ try {
242
+ selectedEndpoint = fs.realpathSync(selected);
243
+ }
244
+ catch { /* Missing identity stays unsupported. */ }
245
+ }
246
+ const reading = await readPosixCommands(command, selectedEndpoint);
247
+ // fish's name, as getShellSpawnArgs() finds it
248
+ if (reading.parseError === undefined || !path.basename(shell).toLowerCase().includes('fish'))
249
+ return reading;
250
+ const { parseError, ...read } = reading;
251
+ const names = this.extractCommands(command);
252
+ return {
253
+ ...read,
254
+ commands: (names.length > 0 ? names : [this.getBaseCommand(command)])
255
+ .map((name, start) => ({
256
+ name, words: [name], written: [name], wordTexts: [name], start, nameAtRunTime: false
257
+ })),
258
+ };
259
+ }
260
+ /**
261
+ * The commands of a reading that run a program: the calls to the script's
262
+ * own functions are left out. A script can define a function with a
263
+ * program's name, such as an error helper named halt, and the shell then
264
+ * runs the function, not the program. A call is the function's when it
265
+ * comes after the definition, its name as written has no folder
266
+ * (/sbin/halt is the program), and the reader lists the function, so not
267
+ * one the text may remove. PowerShell finds a function whatever the case
268
+ * of its name, POSIX shells only by its exact name. The function's body is
269
+ * read as commands of its own, so a blocked program inside it is still
270
+ * found.
271
+ */
272
+ withoutOwnFunctionCalls(reading, shellType) {
273
+ const sameName = (a, b) => shellType === 'powershell' ? a.toLowerCase() === b.toLowerCase() : a === b;
274
+ return reading.commands.filter((cmd) => {
275
+ const written = cmd.words[0];
276
+ if (written === null || written.includes('/') || written.includes('\\'))
277
+ return true;
278
+ return !reading.functions.some((fn) => sameName(fn.name, written) && cmd.start >= fn.end);
279
+ });
280
+ }
281
+ /**
282
+ * What hides a program from the check among the commands that run
283
+ * (CommandCheck's `unseen`), in the order the commands start:
284
+ * - a program chosen only when the command runs: a name that is a variable
285
+ * or another command's output (& $tool), or eval and Invoke-Expression,
286
+ * which run text the command builds (eval "$CMD");
287
+ * - a script file given to a shell (bash deploy.sh, or forwarded by runuser): the commands in it
288
+ * aren't in the text. A file named only when the command runs ("$SCRIPT")
289
+ * counts as a program chosen at run time, named by the shell.
290
+ */
291
+ findUnseen(commands, shellType) {
292
+ const unseen = [];
293
+ for (const cmd of commands) {
294
+ if (cmd.nameAtRunTime) {
295
+ unseen.push({ what: cmd.name, inFile: false });
296
+ continue;
297
+ }
298
+ const files = this.scriptFiles(cmd, shellType);
299
+ unseen.push(...files);
300
+ const run = shellRuns(cmd, shellType);
301
+ // A text-program shell can identify a script that the ordinary file reader does not handle.
302
+ if (files.length === 0 && run.shell !== undefined && typeof run.file === 'string') {
303
+ unseen.push({ what: run.file, inFile: true });
304
+ }
305
+ const unknown = sameShellTexts(cmd, shellType).file === null || run.file === null;
306
+ if (unknown && !unseen.some((item) => item.what === cmd.name && !item.inFile)) {
307
+ unseen.push({ what: cmd.name, inFile: false });
308
+ }
309
+ }
310
+ return unseen;
311
+ }
312
+ /**
313
+ * What hides the program when a command gives a shell a script or startup file to run
314
+ * (bash deploy.sh, pwsh -File deploy.ps1, source deploy.sh), or when
315
+ * PowerShell runs one named as the command (./deploy.ps1): the file, or the
316
+ * shell when the file is named only when the command runs ("$SCRIPT").
317
+ * A shell's command text or standard input adds no file. An explicit Bash
318
+ * startup file can still run beside command text in interactive mode.
319
+ */
320
+ scriptFiles(cmd, shellType) {
321
+ const program = programName(cmd.name, shellType);
322
+ const args = cmd.words.slice(1);
323
+ const hidden = (file) => {
324
+ return file === null ? { what: cmd.name, inFile: false } : { what: file, inFile: true };
325
+ };
326
+ if (shellType === 'posix' && (program === 'source' || program === '.')) {
327
+ requireCompleteArguments(cmd);
328
+ return args[0] === undefined ? [] : [hidden(args[0])];
329
+ }
330
+ // PowerShell runs a .ps1 named as the command (./deploy.ps1, & ./deploy.ps1) as a script file
331
+ if (shellType === 'powershell' && /\.ps1$/i.test(cmd.name)) {
332
+ requireCompleteArguments(cmd);
333
+ return [hidden(cmd.name)];
334
+ }
335
+ // PowerShell text and file modes use the same host-option readings.
336
+ if (getShellType(cmd.name) === 'powershell') {
337
+ const file = shellRuns(cmd, shellType).file;
338
+ return file === undefined ? [] : [hidden(file)];
339
+ }
340
+ return shellScriptFiles(program, args, {
341
+ written: cmd.written.slice(1),
342
+ ...(cmd.argumentError === undefined ? {} : { argumentError: cmd.argumentError }),
343
+ }).map(hidden);
344
+ }
345
+ /**
346
+ * The check's answer for `command` run by `shell`:
347
+ * - allowed: no program it runs is blocked.
348
+ * - blocked: a program it runs is in blockedCommands, both compared in the
349
+ * form programName() gives; the answer names the entry as written (a call
350
+ * to the script's own function is not the program: see withoutOwnFunctionCalls).
351
+ * - unseen: allowed, but a program is chosen only when the command runs or
352
+ * is in a script file (see findUnseen), so start_process can say the
353
+ * blocklist couldn't check it.
354
+ * - failed: the command or the settings can't be read. In PowerShell a parse
355
+ * error or a missing PowerShell is allowed instead: nothing runs, and
356
+ * PowerShell or start_process answers.
357
+ */
358
+ checkCommand(command, shell, options = {}) {
359
+ return this.checkText(command, shell, new Map(), options);
360
+ }
361
+ /**
362
+ * checkCommand() for a command, or for a command text in it: each text is
363
+ * checked once per command in each shell, however many readings give it.
364
+ * In pwsh $a pwsh $a … each text gives every later one again, so without
365
+ * this the work doubled with each pair.
366
+ */
367
+ checkText(command, shell, checked, options) {
368
+ const optionsForShell = {
369
+ cmdDelayedExpansion: getShellType(shell) === 'cmd' ? options.cmdDelayedExpansion ?? 'unknown' : 'unknown',
370
+ };
371
+ const key = `${shell}\0${optionsForShell.cmdDelayedExpansion}\0${command}`;
372
+ let check = checked.get(key);
373
+ if (check === undefined) {
374
+ check = this.checkOnce(command, shell, checked, optionsForShell);
375
+ checked.set(key, check);
376
+ }
377
+ return check;
378
+ }
379
+ async checkOnce(command, shell, checked, options) {
215
380
  try {
216
- // Get blocked commands from config
217
381
  const config = await configManager.getConfig();
218
382
  const blockedCommands = config.blockedCommands || [];
219
- // Extract all commands from the command string
220
- const allCommands = this.extractCommands(command);
221
- // If there are no commands extracted, fall back to base command
222
- if (allCommands.length === 0) {
223
- const baseCommand = this.getBaseCommand(command);
224
- return !blockedCommands.includes(baseCommand);
383
+ const shellType = getShellType(shell);
384
+ // PowerShell runs nothing when it isn't there or can't parse the command: it, or start_process, answers
385
+ if (shellType === 'powershell' && !isShellAvailable(shell))
386
+ return { verdict: 'allowed' };
387
+ const { cmdDelayedExpansion } = options;
388
+ const reading = await this.readCommands(command, shell, options);
389
+ // A parse error is the command's fault, not the server's, so it isn't logged or sent
390
+ if (reading.parseError !== undefined) {
391
+ return shellType === 'powershell'
392
+ ? { verdict: 'allowed' }
393
+ : { verdict: 'failed', reason: reading.parseError };
225
394
  }
226
- // Check if any of the extracted commands are in the blocked list
227
- for (const cmd of allCommands) {
228
- if (blockedCommands.includes(cmd)) {
229
- return false; // Command is blocked
395
+ const running = withStartedPrograms(this.withoutOwnFunctionCalls(reading, shellType), shell);
396
+ // set_config_value checks only that the list is an array
397
+ const entries = blockedCommands.filter((entry) => typeof entry === 'string');
398
+ for (const found of running) {
399
+ // A name known only at run time ($tool) names no program the list could match
400
+ if (found.nameAtRunTime)
401
+ continue;
402
+ const program = programName(found.name, shellType);
403
+ const entry = entries.find((candidate) => programName(candidate, shellType) === program);
404
+ if (entry !== undefined)
405
+ return { verdict: 'blocked', name: entry };
406
+ }
407
+ const unseen = [];
408
+ let unreadable;
409
+ for (const found of running) {
410
+ unseen.push(...this.findUnseen([found], shellType));
411
+ const run = shellRuns(found, shellType);
412
+ const texts = [
413
+ ...sameShellTexts(found, shellType).texts.map((text) => ({
414
+ text,
415
+ runs: shell,
416
+ cmdDelayedExpansion,
417
+ })),
418
+ // su -c's text runs in sh, runas's command line as cmd reads it
419
+ ...run.texts.map((text) => ({
420
+ text,
421
+ runs: run.shell ?? found.name,
422
+ cmdDelayedExpansion: run.cmdDelayedExpansion ?? 'unknown',
423
+ })),
424
+ ];
425
+ for (const { text, runs, cmdDelayedExpansion: innerMode } of texts) {
426
+ // The shell that runs the command looks a PowerShell's name up itself, in its working folder
427
+ // too: one the check can't find is read by the PowerShell running the command, when that is one
428
+ const reader = getShellType(runs) !== 'powershell' ? runs
429
+ : [runs, shell].find((candidate) => getShellType(candidate) === 'powershell' && isShellAvailable(candidate));
430
+ const inner = reader === undefined
431
+ ? { verdict: 'failed', reason: `${runs} isn't installed here, so the command given to it can't be read` }
432
+ : await this.checkText(text, reader, checked, { cmdDelayedExpansion: innerMode });
433
+ if (inner.verdict === 'blocked')
434
+ return inner;
435
+ if (inner.verdict === 'failed')
436
+ unreadable ?? (unreadable = inner);
437
+ if (inner.verdict === 'unseen')
438
+ unseen.push(...inner.unseen);
230
439
  }
231
440
  }
232
- // No commands were blocked
233
- return true;
441
+ if (unreadable)
442
+ return unreadable;
443
+ return unseen.length > 0 ? { verdict: 'unseen', unseen } : { verdict: 'allowed' };
234
444
  }
235
445
  catch (error) {
446
+ if (error instanceof IncompleteArgumentsError)
447
+ return { verdict: 'failed', reason: error.message };
448
+ const reason = error instanceof Error ? error.message : String(error);
236
449
  console.error('Error validating command:', error);
237
450
  capture('server_validate_command_error', {
238
- error: error instanceof Error ? error.message : String(error)
451
+ error: reason
239
452
  });
240
453
  // Fail closed: deny the command if validation encounters an error.
241
454
  // This prevents a config read failure from bypassing all command filtering.
242
- return false;
455
+ return { verdict: 'failed', reason };
243
456
  }
244
457
  }
458
+ /** Whether a check's answer refuses the command */
459
+ isRefused(check) {
460
+ return check.verdict === 'blocked' || check.verdict === 'failed';
461
+ }
462
+ /** Whether the command may run in `shell`: the check doesn't refuse it */
463
+ async validateCommand(command, shell) {
464
+ return !this.isRefused(await this.checkCommand(command, shell));
465
+ }
245
466
  }
246
467
  export const commandManager = new CommandManager();
@@ -23,6 +23,8 @@ const RESTART_BACKOFF_CAP_MS = 5000;
23
23
  const restartBackoffMs = (attempt) =>
24
24
  // Cap AFTER jitter, so the cap is the wait this comment claims it is.
25
25
  Math.min(RESTART_BACKOFF_CAP_MS, 250 * 2 ** Math.min(attempt, 5) * (0.5 + Math.random()));
26
+ // As long as the server waits: it fails a call still running in the background 30 minutes after the device claims it, at its next 30-second sweep
27
+ const TOOL_CALL_TIMEOUT_MS = 30 * 60000 + 30000;
26
28
  const __filename = fileURLToPath(import.meta.url);
27
29
  const __dirname = path.dirname(__filename);
28
30
  export class DesktopCommanderIntegration {
@@ -274,7 +276,7 @@ export class DesktopCommanderIntegration {
274
276
  name: toolName,
275
277
  arguments: args,
276
278
  _meta: { remote: true, ...metadata || {} }
277
- });
279
+ }, undefined, { timeout: TOOL_CALL_TIMEOUT_MS });
278
280
  console.debug('[DEBUG] Tool call successful:', toolName);
279
281
  return result;
280
282
  }
@@ -52,6 +52,35 @@ function safeUserName() {
52
52
  return '';
53
53
  }
54
54
  }
55
+ /** Mask overlapping private values together so one replacement cannot expose another's fragments. */
56
+ function maskHostnamesAndUuids(text) {
57
+ const hostname = os.hostname();
58
+ const hosts = [...new Set([hostname, hostname.split('.')[0]])]
59
+ .map(wordPattern).filter((pattern) => pattern !== null);
60
+ const patterns = [
61
+ { pattern: UUID, placeholder: '<id>' },
62
+ ...hosts.map((pattern) => ({ pattern, placeholder: '<host>' })),
63
+ ];
64
+ const matches = patterns.flatMap(({ pattern, placeholder }) => Array.from(text.matchAll(pattern), (match) => ({
65
+ start: match.index, end: match.index + match[0].length, placeholder,
66
+ }))).sort((a, b) => a.start - b.start || b.end - a.end);
67
+ const ranges = [];
68
+ for (const match of matches) {
69
+ const previous = ranges.at(-1);
70
+ if (previous && match.start < previous.end)
71
+ previous.end = Math.max(previous.end, match.end);
72
+ else
73
+ ranges.push({ ...match });
74
+ }
75
+ const pieces = [];
76
+ let cursor = 0;
77
+ for (const range of ranges) {
78
+ pieces.push(text.slice(cursor, range.start), range.placeholder);
79
+ cursor = range.end;
80
+ }
81
+ pieces.push(text.slice(cursor));
82
+ return pieces.join('');
83
+ }
55
84
  export function redact(text) {
56
85
  let out = text;
57
86
  const home = homePattern(os.homedir());
@@ -61,14 +90,7 @@ export function redact(text) {
61
90
  out = out.replace(BEARER, '$1<redacted>');
62
91
  out = out.replace(JWT, '<jwt>');
63
92
  out = out.replace(EMAIL, '<email>');
64
- out = out.replace(UUID, '<id>');
65
- // "name.local" and the bare "name" a Mac also goes by
66
- const hostname = os.hostname();
67
- for (const name of new Set([hostname, hostname.split('.')[0]])) {
68
- const host = wordPattern(name);
69
- if (host)
70
- out = out.replace(host, '<host>');
71
- }
93
+ out = maskHostnamesAndUuids(out);
72
94
  const user = wordPattern(safeUserName());
73
95
  if (user)
74
96
  out = out.replace(user, '<user>');
@@ -10,6 +10,7 @@ import { fileURLToPath } from 'url';
10
10
  import PizZip from 'pizzip';
11
11
  import { parseConfig } from '../../config-manager.js';
12
12
  import { VERSION } from '../../version.js';
13
+ import { LAUNCHER_PID_ARGUMENT } from '../../utils/threadpool-size.js';
13
14
  import { deviceLogNames, getDeviceLogDir, cleanLine } from './device-log.js';
14
15
  import { redact } from './redact.js';
15
16
  import { savedUserId, uploadReport } from './upload.js';
@@ -317,7 +318,7 @@ function elapsedSeconds(etime) {
317
318
  return Number(days) * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2];
318
319
  }
319
320
  /**
320
- * Every process with its command line and start time. process.ts's list uses
321
+ * Every process with its parent, command line and start time. process.ts's list uses
321
322
  * tasklist on Windows, which has no command lines, hence Win32_Process here.
322
323
  */
323
324
  function listProcesses() {
@@ -325,24 +326,24 @@ function listProcesses() {
325
326
  return new Promise((resolve, reject) => {
326
327
  if (process.platform === 'win32') {
327
328
  const script = '[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance Win32_Process | ForEach-Object { ' +
328
- '"$($_.ProcessId)`t$(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString(\'o\') })`t$($_.CommandLine)" }';
329
+ '"$($_.ProcessId)`t$($_.ParentProcessId)`t$(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString(\'o\') })`t$($_.CommandLine)" }';
329
330
  execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], options, (error, stdout) => {
330
331
  if (error)
331
332
  return reject(error);
332
333
  resolve(String(stdout).split(/\r?\n/).map((line) => {
333
- const [pid, created, ...command] = line.split('\t');
334
- return { pid: Number(pid), startedAt: Date.parse(created), command: command.join('\t') };
334
+ const [pid, parentPid, created, ...command] = line.split('\t');
335
+ return { pid: Number(pid), parentPid: Number(parentPid), startedAt: Date.parse(created), command: command.join('\t') };
335
336
  }).filter((p) => p.pid > 0 && p.command));
336
337
  });
337
338
  return;
338
339
  }
339
- execFile('ps', ['-A', '-ww', '-o', 'pid=,etime=,command='], options, (error, stdout) => {
340
+ execFile('ps', ['-A', '-ww', '-o', 'pid=,ppid=,etime=,command='], options, (error, stdout) => {
340
341
  if (error)
341
342
  return reject(error);
342
343
  const now = Date.now();
343
344
  resolve(String(stdout).split('\n').flatMap((line) => {
344
- const match = line.match(/^\s*(\d+)\s+(\S+)\s+(.*)$/);
345
- return match ? [{ pid: Number(match[1]), startedAt: now - elapsedSeconds(match[2]) * 1000, command: match[3] }] : [];
345
+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
346
+ return match ? [{ pid: Number(match[1]), parentPid: Number(match[2]), startedAt: now - elapsedSeconds(match[3]) * 1000, command: match[4] }] : [];
346
347
  }));
347
348
  });
348
349
  });
@@ -374,7 +375,10 @@ function isDesktopCommanderEntry(file, packageNames) {
374
375
  * dist/index.js (started by an MCP client, npx, or `remote`'s local MCP), not
375
376
  * followed by `remote` / `setup` / `remove`, and not this report. A shell
376
377
  * wrapping it names only a bin, which doesn't resolve, so it isn't counted
377
- * twice. Only the count and the earliest start leave this function.
378
+ * twice. The thread-pool bootstrap marks its child with the launcher's PID,
379
+ * so only that recognized pair counts once. An unmarked nested server counts
380
+ * separately; older unmarked bootstrap pairs cannot be distinguished from it.
381
+ * Only the count and the earliest start leave this function.
378
382
  */
379
383
  async function desktopCommanderMcp() {
380
384
  let processes;
@@ -385,18 +389,31 @@ async function desktopCommanderMcp() {
385
389
  return { running: null, since: null, error: `could not list processes (${errorText(error)})` };
386
390
  }
387
391
  const packageNames = new Map();
388
- const servers = processes.filter(({ pid, command }) => {
392
+ const servers = processes.flatMap(({ pid, parentPid, startedAt, command }) => {
389
393
  if (pid === process.pid)
390
- return false;
394
+ return [];
391
395
  const tokens = (command.match(/"[^"]*"|\S+/g) ?? []).map((token) => token.replace(/^"|"$/g, ''));
392
396
  // The first token is the executable; the entry is any later one
393
397
  const at = tokens.findIndex((token, i) => i > 0 && /(\.js|desktop-commander(\.cmd)?)$/i.test(token) &&
394
398
  isDesktopCommanderEntry(token, packageNames));
395
- return at > 0 && !NOT_THE_SERVER.has(tokens[at + 1] ?? '');
399
+ if (at < 0 || NOT_THE_SERVER.has(tokens[at + 1] ?? ''))
400
+ return [];
401
+ const launcherPid = tokens.at(-1) === `${LAUNCHER_PID_ARGUMENT}${parentPid}` ? parentPid : null;
402
+ return [{ pid, parentPid, startedAt, launcherPid }];
403
+ });
404
+ const serversByPid = new Map(servers.map((p) => [p.pid, p]));
405
+ const counted = servers.filter((p) => {
406
+ const launcher = p.launcherPid === null ? undefined : serversByPid.get(p.launcherPid);
407
+ if (!launcher)
408
+ return true;
409
+ // A process that started later cannot have launched this child; its PID was reused.
410
+ return Number.isFinite(launcher.startedAt) && Number.isFinite(p.startedAt) &&
411
+ launcher.startedAt > p.startedAt;
396
412
  });
397
- const starts = servers.map((p) => p.startedAt).filter((t) => !Number.isNaN(t));
413
+ // A grouped child may have the only known start time when its launcher has no timestamp.
414
+ const starts = servers.map((p) => p.startedAt).filter(Number.isFinite);
398
415
  return {
399
- running: servers.length,
416
+ running: counted.length,
400
417
  since: starts.length ? new Date(Math.min(...starts)).toISOString() : null,
401
418
  };
402
419
  }
@@ -183,7 +183,7 @@ export async function enrollMqttDevice(options) {
183
183
  }
184
184
  }
185
185
  else {
186
- console.warn("[MQTT] Previous credentials cannot be identified on this backend; continuing with fresh enrollment. The old certificate may remain active.");
186
+ console.debug("[MQTT] Previous credentials cannot be identified on this backend; continuing with fresh enrollment. The old certificate may remain active.");
187
187
  }
188
188
  assertCurrent();
189
189
  try {
@@ -214,7 +214,7 @@ export class MqttTransport {
214
214
  }
215
215
  const topic = `dc/mqtt/v1/users/${this.userId}/devices/${this.deviceId}/result-${originInstance}`;
216
216
  // Buffer identity keeps concurrent publishes of the same call separate locally.
217
- // need to verify that payload is correct and this is what expected on otehr side.
217
+ // need to verify that payload is correct and this is what expected on other side.
218
218
  const payload = Buffer.from(JSON.stringify({ call_id: callId }));
219
219
  try {
220
220
  await new Promise((resolve, reject) => {
@@ -245,7 +245,7 @@ export class MqttTransport {
245
245
  messageId = packet.messageId;
246
246
  };
247
247
  //TODO will it stop whole mqtt transport or just this message?
248
- // we should stop inly this message if timeout, not the other messages.
248
+ // we should stop only this message if timeout, not the other messages.
249
249
  const timer = setTimeout(() => finish(new Error("MQTT result acknowledgement timed out")), 5000);
250
250
  client.once("close", onClose);
251
251
  client.on("packetsend", onPacket);
@@ -154,7 +154,7 @@ export declare class RemoteChannel {
154
154
  } | null>;
155
155
  updateDevice(deviceId: string, updates: any): Promise<{
156
156
  data: any[] | null;
157
- error: import("@supabase/supabase-js").PostgrestError | null;
157
+ error: import("@supabase/postgrest-js").PostgrestError | null;
158
158
  }>;
159
159
  createDevice(deviceData: DeviceData): Promise<{
160
160
  data: any;
@@ -588,7 +588,7 @@ export class RemoteChannel {
588
588
  throw new Error('Device session changed during MQTT startup; restart the connector');
589
589
  }
590
590
  };
591
- void this.startMqtt(assertSessionStillActive).catch(() => console.warn('[MQTT] Transport unavailable; Broadcast continues'));
591
+ void this.startMqtt(assertSessionStillActive).catch(() => console.debug('[MQTT] Transport unavailable; Broadcast continues'));
592
592
  await this.createChannel();
593
593
  }
594
594
  else {