@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.
Files changed (117) hide show
  1. package/README.md +14 -24
  2. package/dist/command-manager.d.ts +7 -2
  3. package/dist/command-manager.js +16 -11
  4. package/dist/config-manager.d.ts +49 -3
  5. package/dist/config-manager.js +329 -87
  6. package/dist/config-recovery.d.ts +28 -0
  7. package/dist/config-recovery.js +81 -0
  8. package/dist/config.d.ts +1 -0
  9. package/dist/config.js +9 -0
  10. package/dist/handlers/filesystem-handlers.d.ts +1 -1
  11. package/dist/handlers/filesystem-handlers.js +26 -16
  12. package/dist/handlers/search-answers.d.ts +58 -0
  13. package/dist/handlers/search-answers.js +172 -0
  14. package/dist/handlers/search-handlers.js +4 -92
  15. package/dist/index.js +14 -7
  16. package/dist/npm-scripts/remote.js +32 -4
  17. package/dist/remote-device/broadcast-analytics.d.ts +28 -0
  18. package/dist/remote-device/broadcast-analytics.js +41 -0
  19. package/dist/remote-device/desktop-commander-integration.d.ts +20 -0
  20. package/dist/remote-device/desktop-commander-integration.js +121 -40
  21. package/dist/remote-device/device-authenticator.d.ts +13 -1
  22. package/dist/remote-device/device-authenticator.js +87 -47
  23. package/dist/remote-device/device.d.ts +14 -0
  24. package/dist/remote-device/device.js +244 -51
  25. package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
  26. package/dist/remote-device/mqtt-enrollment.js +162 -0
  27. package/dist/remote-device/mqtt-transport.d.ts +44 -0
  28. package/dist/remote-device/mqtt-transport.js +197 -0
  29. package/dist/remote-device/remote-channel.d.ts +64 -3
  30. package/dist/remote-device/remote-channel.js +317 -48
  31. package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
  32. package/dist/remote-device/transport-analytics.d.ts +29 -0
  33. package/dist/remote-device/transport-analytics.js +44 -0
  34. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  35. package/dist/remote-device/transport-telemetry.js +48 -0
  36. package/dist/search-manager.d.ts +239 -27
  37. package/dist/search-manager.js +746 -312
  38. package/dist/server.js +77 -92
  39. package/dist/terminal-manager.d.ts +138 -21
  40. package/dist/terminal-manager.js +300 -215
  41. package/dist/tools/config.d.ts +1 -1
  42. package/dist/tools/config.js +21 -70
  43. package/dist/tools/edit.js +12 -4
  44. package/dist/tools/filesystem.d.ts +30 -6
  45. package/dist/tools/filesystem.js +246 -140
  46. package/dist/tools/improved-process-tools.d.ts +9 -3
  47. package/dist/tools/improved-process-tools.js +171 -68
  48. package/dist/tools/pdf/extract-images.d.ts +2 -0
  49. package/dist/tools/pdf/extract-images.js +4 -1
  50. package/dist/tools/pdf/index.d.ts +5 -3
  51. package/dist/tools/pdf/index.js +4 -3
  52. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  53. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  54. package/dist/tools/pdf/manipulations.d.ts +12 -1
  55. package/dist/tools/pdf/manipulations.js +17 -4
  56. package/dist/tools/pdf/markdown.d.ts +96 -0
  57. package/dist/tools/pdf/markdown.js +485 -20
  58. package/dist/tools/pdf/utils.d.ts +2 -2
  59. package/dist/tools/pdf/utils.js +4 -4
  60. package/dist/tools/process.js +8 -5
  61. package/dist/tools/schemas.d.ts +1 -1
  62. package/dist/tools/schemas.js +15 -6
  63. package/dist/tools/search.d.ts +32 -0
  64. package/dist/tools/search.js +202 -0
  65. package/dist/types.d.ts +1 -1
  66. package/dist/ui/config-editor/config-editor-runtime.js +6 -6
  67. package/dist/ui/config-editor/src/app.js +2 -15
  68. package/dist/utils/ab-test.js +27 -9
  69. package/dist/utils/atomic-write.d.ts +14 -0
  70. package/dist/utils/atomic-write.js +80 -0
  71. package/dist/utils/capture.d.ts +17 -1
  72. package/dist/utils/capture.js +177 -68
  73. package/dist/utils/exit-process.d.ts +24 -0
  74. package/dist/utils/exit-process.js +31 -0
  75. package/dist/utils/feature-flags.js +2 -1
  76. package/dist/utils/files/base.d.ts +3 -1
  77. package/dist/utils/files/docx.d.ts +3 -0
  78. package/dist/utils/files/docx.js +24 -9
  79. package/dist/utils/files/excel.d.ts +10 -0
  80. package/dist/utils/files/excel.js +93 -33
  81. package/dist/utils/files/factory.d.ts +22 -1
  82. package/dist/utils/files/factory.js +59 -4
  83. package/dist/utils/files/image.d.ts +12 -4
  84. package/dist/utils/files/image.js +19 -8
  85. package/dist/utils/files/index.d.ts +5 -3
  86. package/dist/utils/files/index.js +4 -3
  87. package/dist/utils/files/pdf.js +18 -36
  88. package/dist/utils/files/text.d.ts +21 -5
  89. package/dist/utils/files/text.js +90 -86
  90. package/dist/utils/internal-facts.d.ts +3 -0
  91. package/dist/utils/internal-facts.js +23 -0
  92. package/dist/utils/lazy-package.d.ts +23 -0
  93. package/dist/utils/lazy-package.js +42 -0
  94. package/dist/utils/open-browser.js +2 -1
  95. package/dist/utils/process-detection.d.ts +24 -5
  96. package/dist/utils/process-detection.js +199 -89
  97. package/dist/utils/process-tree.d.ts +14 -0
  98. package/dist/utils/process-tree.js +223 -0
  99. package/dist/utils/rename.d.ts +9 -0
  100. package/dist/utils/rename.js +74 -0
  101. package/dist/utils/ripgrep-resolver.js +9 -14
  102. package/dist/utils/shell.d.ts +42 -0
  103. package/dist/utils/shell.js +187 -0
  104. package/dist/utils/system-info.js +9 -7
  105. package/dist/utils/trackTools.js +2 -1
  106. package/dist/version.d.ts +1 -1
  107. package/dist/version.js +1 -1
  108. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  109. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  110. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  111. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  112. package/package.json +8 -2
  113. package/vendor/telemetry-contract/README.md +56 -0
  114. package/vendor/telemetry-contract/package.json +32 -0
  115. package/vendor/telemetry-contract/transport.d.ts +38 -0
  116. package/vendor/telemetry-contract/transport.js +164 -0
  117. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -1,59 +1,106 @@
1
1
  /**
2
2
  * REPL and Process State Detection Utilities
3
- * Detects when processes are waiting for input vs finished vs running
3
+ * Detects from its output whether a running process is waiting for input.
4
+ * Whether it has finished is known from its exit, never from its output
5
+ * (see TerminalManager.getProcessState).
4
6
  */
5
- // Common REPL prompt patterns
7
+ // Common REPL prompts. Most are generic ("... ", "> ", "+ ", "| "): inside or
8
+ // at the end of a longer line they are ordinary text (pytest -v's "collecting
9
+ // ... ", #196; a markdown table's "| a | b |"), so they count only in a last
10
+ // line made of prompts alone: the prompt itself, the prompts a REPL that
11
+ // doesn't echo input printed one after another ("> | " from node -i), or,
12
+ // from a REPL that writes its prompts to stderr (python -i, bash -i), the
13
+ // prompts it wrote there (">>> ... ").
6
14
  const REPL_PROMPTS = {
7
15
  python: ['>>> ', '... '],
8
- node: ['> ', '... '],
16
+ node: ['> ', '... ', '| '], // "| ": Node 24's continuation, "... " before it
9
17
  r: ['> ', '+ '],
10
18
  julia: ['julia> ', ' '], // julia continuation is spaces
11
- shell: ['$ ', '# ', '% ', 'bash-', 'zsh-'],
19
+ shell: ['$ ', '# ', '% '],
12
20
  mysql: ['mysql> ', ' -> '],
13
21
  postgres: ['=# ', '-# '],
14
22
  redis: ['redis> '],
15
- mongo: ['> ', '... ']
23
+ mongo: ['> ', '... '],
24
+ powershell: ['>> '] // continuation; after "> ", so it is reported as "> ", as before
16
25
  };
17
- // Error patterns that indicate completion (even with errors)
18
- const ERROR_COMPLETION_PATTERNS = [
19
- /Error:/i,
20
- /Exception:/i,
21
- /Traceback/i,
22
- /SyntaxError/i,
23
- /NameError/i,
24
- /TypeError/i,
25
- /ValueError/i,
26
- /ReferenceError/i,
27
- /Uncaught/i,
28
- /at Object\./i, // Node.js stack traces
29
- /^\s*\^/m // Syntax error indicators
30
- ];
31
- // Process completion indicators
32
- const COMPLETION_INDICATORS = [
33
- /Process finished/i,
34
- /Command completed/i,
35
- /\[Process completed\]/i,
36
- /Program terminated/i,
37
- /Exit code:/i
38
- ];
26
+ const PROMPTS = [...new Set(Object.values(REPL_PROMPTS).flat())];
27
+ const PROMPTS_ONLY = new RegExp(`^(?:${PROMPTS.map(escapeRegExp).join('|')})+$`);
28
+ // Prompts that also count at the end of a longer line: named ones, after
29
+ // output that didn't end in a newline ("done>>> "), and a shell or psql
30
+ // prompt's end ("bash-5.2$ ", "user@host dir % ", "postgres=# ")
31
+ const LINE_END_PROMPTS = ['>>> ', 'julia> ', 'mysql> ', 'redis> ', '$ ', '# ', '% '];
32
+ // PowerShell's prompt (powershell.exe, pwsh), at the end of a line: "PS ", a
33
+ // location (a drive, provider or path: "C:\Users\me", "/Users/me", "HKLM:\"),
34
+ // then "> " (">> " in a nested or debugger prompt, "[DBG]: PS C:\>> ")
35
+ const POWERSHELL_PROMPT_TEXT = String.raw `PS [^<>|\n]*[\\/:][^<>|\n]*>>? `;
36
+ const POWERSHELL_PROMPT = new RegExp(`${POWERSHELL_PROMPT_TEXT}$`);
37
+ // cmd.exe's prompt: the whole last line is a path and ">", with nothing after
38
+ // it ("C:\Users\me>"); output lines end in a newline, a prompt doesn't
39
+ const CMD_PROMPT_TEXT = String.raw `[A-Za-z]:\\[^<>|"*?\n]*>`;
40
+ const CMD_PROMPT = new RegExp(`^${CMD_PROMPT_TEXT}$`);
41
+ // The same shell prompts at the start of a line, where the shell echoes the
42
+ // next input line after them ("PS C:\Users\me> echo b", "C:\Users\me>echo b")
43
+ const SHELL_PROMPTS_AT_START = [new RegExp(`^${POWERSHELL_PROMPT_TEXT}`), new RegExp(`^${CMD_PROMPT_TEXT}`)];
44
+ // The REPL prompts output cleaning removes, one or more in a row at the start
45
+ // of a line (">>> ... " from a REPL that reads several lines at once)
46
+ const REPL_PROMPT = String.raw `(?:>>> |\.\.\. |>> |> |\| |\+ )`;
47
+ const REPL_PROMPT_RUN = new RegExp(`^${REPL_PROMPT}+`);
48
+ const REPL_PROMPTS_ALONE = new RegExp(`^${REPL_PROMPT}+$`);
49
+ const REPL_PROMPT_TOKEN = new RegExp(REPL_PROMPT, 'g');
50
+ // The prompts of a REPL waiting for more of a statement (Python, Node, PowerShell, R)
51
+ const CONTINUATION_PROMPTS = ['... ', '| ', '>> ', '+ '];
52
+ /** The prompt the last line of output is, or ends in, if any */
53
+ function findPrompt(lastLine) {
54
+ if (PROMPTS_ONLY.test(lastLine)) {
55
+ return PROMPTS.find(prompt => lastLine.endsWith(prompt));
56
+ }
57
+ const lineEnd = LINE_END_PROMPTS.find(prompt => lastLine.endsWith(prompt));
58
+ if (lineEnd)
59
+ return lineEnd;
60
+ // Reported as "> ", which a PowerShell prompt was reported as before #196
61
+ if (POWERSHELL_PROMPT.test(lastLine) || CMD_PROMPT.test(lastLine))
62
+ return '> ';
63
+ return undefined;
64
+ }
39
65
  /**
40
- * Analyze process output to determine current state
66
+ * How much of the end of the output state detection examines. A prompt is
67
+ * the last thing a process writes before it waits for input, so the end of
68
+ * the output decides the state; examining only this much keeps detection's
69
+ * cost the same however much output there is.
70
+ */
71
+ export const STATE_DETECTION_TAIL_CHARS = 4096;
72
+ /**
73
+ * Analyze a running process's output to determine whether it is waiting for
74
+ * input. Output text never makes a process finished: a line such as
75
+ * "Error: retrying" doesn't end it.
76
+ *
77
+ * `output` is what the process wrote most recently. For a process writing to
78
+ * both stdout and stderr it can be the recent output of each stream that may
79
+ * have written last (see TerminalManager.getProcessState): their relative
80
+ * order is unknown, so the process is waiting for input if any of them ends
81
+ * in a prompt. Only the last STATE_DETECTION_TAIL_CHARS of each are examined.
41
82
  */
42
83
  export function analyzeProcessState(output, pid) {
43
- if (!output || output.trim().length === 0) {
44
- return {
84
+ const tails = (typeof output === 'string' ? [output] : output)
85
+ .map(text => text.slice(-STATE_DETECTION_TAIL_CHARS))
86
+ .filter(text => text.trim().length > 0);
87
+ const states = tails.map(analyzeOutputTail);
88
+ return states.find(state => state.isWaitingForInput)
89
+ ?? {
45
90
  isWaitingForInput: false,
46
91
  isFinished: false,
47
92
  isRunning: true,
48
- lastOutput: output
93
+ lastOutput: tails.join('\n')
49
94
  };
50
- }
95
+ }
96
+ /**
97
+ * The state the end of one stream's output shows (see analyzeProcessState).
98
+ */
99
+ function analyzeOutputTail(output) {
51
100
  const lines = output.split('\n');
52
101
  const lastLine = lines[lines.length - 1] || '';
53
- const lastFewLines = lines.slice(-3).join('\n');
54
102
  // Check for REPL prompts (waiting for input)
55
- const allPrompts = Object.values(REPL_PROMPTS).flat();
56
- const detectedPrompt = allPrompts.find(prompt => lastLine.endsWith(prompt) || lastLine.includes(prompt));
103
+ const detectedPrompt = findPrompt(lastLine);
57
104
  if (detectedPrompt) {
58
105
  return {
59
106
  isWaitingForInput: true,
@@ -63,39 +110,7 @@ export function analyzeProcessState(output, pid) {
63
110
  lastOutput: output
64
111
  };
65
112
  }
66
- // Check for completion indicators
67
- const hasCompletionIndicator = COMPLETION_INDICATORS.some(pattern => pattern.test(output));
68
- if (hasCompletionIndicator) {
69
- return {
70
- isWaitingForInput: false,
71
- isFinished: true,
72
- isRunning: false,
73
- lastOutput: output
74
- };
75
- }
76
- // Check for error completion (errors usually end with prompts, but let's be thorough)
77
- const hasErrorCompletion = ERROR_COMPLETION_PATTERNS.some(pattern => pattern.test(lastFewLines));
78
- if (hasErrorCompletion) {
79
- // Errors can indicate completion, but check if followed by prompt
80
- if (detectedPrompt) {
81
- return {
82
- isWaitingForInput: true,
83
- isFinished: false,
84
- isRunning: true,
85
- detectedPrompt,
86
- lastOutput: output
87
- };
88
- }
89
- else {
90
- return {
91
- isWaitingForInput: false,
92
- isFinished: true,
93
- isRunning: false,
94
- lastOutput: output
95
- };
96
- }
97
- }
98
- // Default: process is running, not clearly waiting or finished
113
+ // Default: process is running, not waiting for input
99
114
  return {
100
115
  isWaitingForInput: false,
101
116
  isFinished: false,
@@ -104,29 +119,124 @@ export function analyzeProcessState(output, pid) {
104
119
  };
105
120
  }
106
121
  /**
107
- * Clean output by removing prompts and input echoes
122
+ * Clean output by removing prompts and input echoes. `readAtPrompt`: whether
123
+ * the process was waiting at a prompt when the input was sent; one that
124
+ * wasn't (a shell reading commands without a prompt) prints none for it.
125
+ */
126
+ export function cleanProcessOutput(output, inputSent, readAtPrompt = true) {
127
+ // A process at a prompt prints one prompt for each input line it reads
128
+ const printed = readAtPrompt && inputSent !== undefined ? inputLinesSent(inputSent).length : 0;
129
+ const withoutEcho = removeInputEcho(output, inputSent);
130
+ const cleaned = removePrompts(withoutEcho.output, printed - withoutEcho.prompts);
131
+ // A line repeating the input is the answer, not an echo, when nothing else
132
+ // came back: node -i answers `10` with "10", which was removed as the echo.
133
+ // Not at a continuation prompt: the process waits for more of the input,
134
+ // so it hasn't answered it
135
+ if (!cleaned && withoutEcho.output !== output && !waitsAtContinuationPrompt(output)) {
136
+ return removePrompts(output, printed);
137
+ }
138
+ return cleaned;
139
+ }
140
+ /** Whether the output ends at a continuation prompt (">> " after "if ($true) {") */
141
+ function waitsAtContinuationPrompt(output) {
142
+ const lastLine = output.slice(output.lastIndexOf('\n') + 1);
143
+ if (!REPL_PROMPTS_ALONE.test(lastLine))
144
+ return false;
145
+ const prompts = lastLine.match(REPL_PROMPT_TOKEN) ?? [];
146
+ return CONTINUATION_PROMPTS.includes(prompts[prompts.length - 1]);
147
+ }
148
+ /**
149
+ * The output without the process's echo of the input, if it echoed it. A
150
+ * process that echoes (powershell.exe, cmd.exe, a terminal over ssh -t)
151
+ * repeats each input line where the output for it starts: the first line at
152
+ * the start of the output, each later one after the prompt it was read at
153
+ * ("PS C:\project> echo b", "C:\project>echo b", ">> }"). A line the process
154
+ * has read (it printed a prompt for it) that isn't repeated there means the
155
+ * process doesn't echo, and a line equal to an input line is output (node -i
156
+ * answers `1` with "1"): the output is kept as it is. Lines not read yet (the
157
+ * call answered at an earlier prompt) have no echo yet. Also returns how many
158
+ * prompts went with the echoes.
159
+ */
160
+ function removeInputEcho(output, inputSent) {
161
+ if (!inputSent)
162
+ return { output, prompts: 0 };
163
+ const lines = output.split('\n');
164
+ const echoes = new Set();
165
+ let next = 0;
166
+ for (const [i, inputLine] of inputLinesSent(inputSent).entries()) {
167
+ const echo = inputLine.trim();
168
+ if (!echo)
169
+ continue; // An empty line's echo can't be told from an empty output line
170
+ const at = i === 0
171
+ ? (isEchoLine(lines, 0, echo, true) ? 0 : -1)
172
+ : lines.findIndex((_, index) => index >= next && isEchoLine(lines, index, echo, false));
173
+ if (at < 0) {
174
+ // A process prints one prompt for each line it reads
175
+ const linesRead = lines.reduce((count, line) => count + promptsAtStart(line), 0);
176
+ if (linesRead > i)
177
+ return { output, prompts: 0 };
178
+ break;
179
+ }
180
+ echoes.add(at);
181
+ next = at + 1;
182
+ }
183
+ return {
184
+ output: lines.filter((_, index) => !echoes.has(index)).join('\n'),
185
+ prompts: [...echoes].reduce((count, index) => count + promptsAtStart(lines[index]), 0),
186
+ };
187
+ }
188
+ /** How many prompts `line` starts with: REPL prompts, one or more in a row, or a shell's prompt */
189
+ function promptsAtStart(line) {
190
+ const run = REPL_PROMPT_RUN.exec(line)?.[0];
191
+ if (run)
192
+ return run.match(REPL_PROMPT_TOKEN)?.length ?? 0;
193
+ return SHELL_PROMPTS_AT_START.some(prompt => prompt.test(line)) ? 1 : 0;
194
+ }
195
+ /** The lines of an input as the process reads them (sendInputToProcess ends it with a newline) */
196
+ function inputLinesSent(input) {
197
+ return (input.endsWith('\n') ? input.slice(0, -1) : input).split('\n');
198
+ }
199
+ /**
200
+ * Whether lines[index] is the echo of an input line: alone on the line (the
201
+ * first input line's, at the start of the output) or after a prompt (a later
202
+ * line's), and ended by the newline that was sent with it
108
203
  */
109
- export function cleanProcessOutput(output, inputSent) {
110
- let cleaned = output;
111
- // Remove input echo if provided
112
- if (inputSent) {
113
- const inputLines = inputSent.split('\n');
114
- inputLines.forEach(line => {
115
- if (line.trim()) {
116
- cleaned = cleaned.replace(new RegExp(`^${escapeRegExp(line.trim())}\\s*\n?`, 'm'), '');
117
- }
118
- });
204
+ function isEchoLine(lines, index, echo, alone) {
205
+ if (index >= lines.length - 1)
206
+ return false;
207
+ const line = lines[index].trimEnd();
208
+ if (!line.endsWith(echo))
209
+ return false;
210
+ const before = line.slice(0, line.length - echo.length).trimEnd();
211
+ if (alone)
212
+ return before === '';
213
+ return before !== '' && (findPrompt(before) !== undefined || findPrompt(`${before} `) !== undefined);
214
+ }
215
+ /**
216
+ * The output without the REPL prompts the process printed for the input (at
217
+ * most `printed`), and nothing that only looks like one. The last line, when
218
+ * it is a prompt, is where the process waits now (a REPL's is removed; a
219
+ * shell's, "PS C:\project> ", stays in the output as before). The others
220
+ * start a line: the one where the output for the next input line begins
221
+ * ("1\n> 2\n> " for `1` and `2` sent to node -i). More prompt-like line starts
222
+ * than that means some are output ("+ added" in a diff, "> quoted"), and
223
+ * those lines are all kept as they are.
224
+ */
225
+ function removePrompts(output, printed) {
226
+ const lines = output.split('\n');
227
+ const last = lines.length - 1;
228
+ let left = printed;
229
+ if (findPrompt(lines[last]) !== undefined) {
230
+ left -= Math.max(1, promptsAtStart(lines[last]));
231
+ if (REPL_PROMPTS_ALONE.test(lines[last]))
232
+ lines[last] = '';
233
+ }
234
+ const runs = lines.map((line, index) => (index < last ? REPL_PROMPT_RUN.exec(line)?.[0] ?? '' : ''));
235
+ const found = runs.reduce((count, run) => count + (run.match(REPL_PROMPT_TOKEN)?.length ?? 0), 0);
236
+ if (found <= left) {
237
+ runs.forEach((run, index) => { lines[index] = lines[index].slice(run.length); });
119
238
  }
120
- // Remove common prompt patterns from output
121
- cleaned = cleaned.replace(/^>>>\s*/gm, ''); // Python >>>
122
- cleaned = cleaned.replace(/^>\s*/gm, ''); // Node.js/Shell >
123
- cleaned = cleaned.replace(/^\.{3}\s*/gm, ''); // Python ...
124
- cleaned = cleaned.replace(/^\+\s*/gm, ''); // R +
125
- // Remove trailing prompts
126
- cleaned = cleaned.replace(/\n>>>\s*$/, '');
127
- cleaned = cleaned.replace(/\n>\s*$/, '');
128
- cleaned = cleaned.replace(/\n\+\s*$/, '');
129
- return cleaned.trim();
239
+ return lines.join('\n').trim();
130
240
  }
131
241
  /**
132
242
  * Escape special regex characters
@@ -0,0 +1,14 @@
1
+ import { type ChildProcess } from 'child_process';
2
+ /**
3
+ * Ends the process `pid` alone, forcefully: SIGTERM, then SIGKILL if it still
4
+ * runs after the grace period (on Windows either signal ends it outright).
5
+ * Resolves once it is gone; throws what process.kill threw (ESRCH, EPERM), or
6
+ * that it still runs.
7
+ */
8
+ export declare function terminatePid(pid: number): Promise<void>;
9
+ /**
10
+ * Ends `child` and every process it started. Resolves once they are gone:
11
+ * true, or false if some could not be ended (why is logged, and the root is
12
+ * then killed on its own if it still runs). Never rejects.
13
+ */
14
+ export declare function terminateProcessTree(child: ChildProcess): Promise<boolean>;
@@ -0,0 +1,223 @@
1
+ import { spawn } from 'child_process';
2
+ import path from 'path';
3
+ import { logger } from './logger.js';
4
+ /**
5
+ * Ending a process together with every process it started.
6
+ *
7
+ * Desktop Commander runs commands through a shell (start_process) or a fresh
8
+ * Node process (node:local), so the process it holds is only the root of what
9
+ * the command runs: the shell starts the program, which may start more
10
+ * (npm -> node -> a dev server holding a port). Killing the root alone ends
11
+ * none of those. Windows never ends a process's children with it, and on
12
+ * macOS/Linux a signal sent to one PID reaches only that process, so the
13
+ * program kept running, orphaned, while the session was reported terminated.
14
+ *
15
+ * Both platforms find the tree the same way, through each process's parent
16
+ * PID, so processes are spawned exactly as before: on macOS/Linux they stay
17
+ * in the server's process group and session, and Ctrl+C, closing the
18
+ * terminal and password prompts behave as they always did.
19
+ * - Windows: taskkill /T /F ends the root and its descendants.
20
+ * - macOS/Linux: a ps snapshot gives every process's parent. The root and its
21
+ * descendants get SIGTERM; after a grace period the tree is walked again,
22
+ * from the root and from every process found the first time (children
23
+ * started meanwhile), and whatever still runs gets SIGKILL.
24
+ * Limit: a process whose parent exited before a walk has been reparented (to
25
+ * init or a subreaper) and can no longer be found through its parent.
26
+ *
27
+ * Every path that ends a command DC runs for the client (force_terminate on a
28
+ * start_process session, the node:local timeout) goes through terminateProcessTree.
29
+ * kill_process ends just the PID it is given, with the same SIGTERM, grace
30
+ * period and SIGKILL (terminatePid).
31
+ */
32
+ /** How long a process tree gets to exit after SIGTERM before SIGKILL (macOS/Linux) */
33
+ const TERMINATE_GRACE_MS = 1000;
34
+ /** How long the root gets to report its exit once it has been killed */
35
+ const EXIT_WAIT_MS = 2000;
36
+ /** Longest taskkill or ps may run */
37
+ const COMMAND_TIMEOUT_MS = 10000;
38
+ const POLL_MS = 50;
39
+ const isWindows = () => process.platform === 'win32';
40
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
41
+ function hasExited(child) {
42
+ return child.exitCode !== null || child.signalCode !== null;
43
+ }
44
+ /** Resolves true once `child` has exited, false if it still runs after `timeoutMs` */
45
+ function waitForExit(child, timeoutMs) {
46
+ if (hasExited(child))
47
+ return Promise.resolve(true);
48
+ return new Promise((resolve) => {
49
+ const onExit = () => {
50
+ clearTimeout(timer);
51
+ resolve(true);
52
+ };
53
+ const timer = setTimeout(() => {
54
+ child.off('exit', onExit);
55
+ resolve(false);
56
+ }, timeoutMs);
57
+ child.once('exit', onExit);
58
+ });
59
+ }
60
+ /** Runs a system command to completion: resolves its stdout, rejects with why it failed */
61
+ function runCommand(file, args) {
62
+ const command = [file, ...args].join(' ');
63
+ return new Promise((resolve, reject) => {
64
+ const child = spawn(file, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
65
+ let stdout = '';
66
+ let stderr = '';
67
+ const timer = setTimeout(() => {
68
+ child.kill();
69
+ reject(new Error(`${command} did not finish within ${COMMAND_TIMEOUT_MS}ms`));
70
+ }, COMMAND_TIMEOUT_MS);
71
+ child.stdout.on('data', (data) => { stdout += data; });
72
+ child.stderr.on('data', (data) => { stderr += data; });
73
+ // After a spawn error 'close' follows too; the promise keeps the first reason
74
+ child.once('error', (error) => {
75
+ clearTimeout(timer);
76
+ reject(new Error(`${command}: ${error.message}`));
77
+ });
78
+ child.once('close', (code, signal) => {
79
+ clearTimeout(timer);
80
+ if (code === 0) {
81
+ resolve(stdout);
82
+ }
83
+ else {
84
+ const how = signal ? `was killed by ${signal}` : `exited with code ${code}`;
85
+ reject(new Error(`${command} ${how}${stderr.trim() ? `: ${stderr.trim()}` : ''}`));
86
+ }
87
+ });
88
+ });
89
+ }
90
+ /** macOS/Linux: every running process's children, from one ps snapshot */
91
+ async function snapshotChildren() {
92
+ // -A: all processes; -o pid=,ppid=: just those columns, no header. The same on macOS and Linux ps.
93
+ const output = await runCommand('ps', ['-A', '-o', 'pid=,ppid=']);
94
+ const children = new Map();
95
+ for (const line of output.split('\n')) {
96
+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);
97
+ if (!Number.isInteger(pid) || !Number.isInteger(ppid))
98
+ continue;
99
+ const siblings = children.get(ppid);
100
+ if (siblings) {
101
+ siblings.push(pid);
102
+ }
103
+ else {
104
+ children.set(ppid, [pid]);
105
+ }
106
+ }
107
+ return children;
108
+ }
109
+ /** `roots` and every process descended from them in `children` */
110
+ function withDescendants(roots, children) {
111
+ const found = new Set(roots);
112
+ // Iterating a Set also visits the entries added during the iteration
113
+ for (const pid of found) {
114
+ for (const child of children.get(pid) ?? [])
115
+ found.add(child);
116
+ }
117
+ return found;
118
+ }
119
+ function isRunning(pid) {
120
+ try {
121
+ process.kill(pid, 0);
122
+ return true;
123
+ }
124
+ catch (error) {
125
+ return error.code === 'EPERM'; // Runs, but as another user
126
+ }
127
+ }
128
+ /** Sends `signal` to each of `pids`. Returns why it failed for any that had not exited already. */
129
+ function signalAll(pids, signal) {
130
+ const failures = [];
131
+ for (const pid of pids) {
132
+ try {
133
+ process.kill(pid, signal);
134
+ }
135
+ catch (error) {
136
+ if (error.code !== 'ESRCH') {
137
+ failures.push(`${signal} to PID ${pid}: ${error.message}`);
138
+ }
139
+ }
140
+ }
141
+ return failures;
142
+ }
143
+ /** Resolves true once none of `pids` runs, false if some still run after `timeoutMs` */
144
+ async function waitUntilGone(pids, timeoutMs) {
145
+ const list = [...pids];
146
+ const deadline = Date.now() + timeoutMs;
147
+ while (list.some(isRunning)) {
148
+ if (Date.now() >= deadline)
149
+ return false;
150
+ await sleep(POLL_MS);
151
+ }
152
+ return true;
153
+ }
154
+ /** macOS/Linux: SIGTERM to `root` and its descendants, then SIGKILL to whatever of the tree still runs */
155
+ async function endPosixTree(root) {
156
+ const tree = withDescendants([root], await snapshotChildren());
157
+ const failures = signalAll(tree, 'SIGTERM');
158
+ if (!(await waitUntilGone(tree, TERMINATE_GRACE_MS))) {
159
+ const current = withDescendants(tree, await snapshotChildren());
160
+ failures.push(...signalAll([...current].filter(isRunning), 'SIGKILL'));
161
+ }
162
+ if (failures.length > 0) {
163
+ throw new Error(failures.join('; '));
164
+ }
165
+ }
166
+ /**
167
+ * Ends the process `pid` alone, forcefully: SIGTERM, then SIGKILL if it still
168
+ * runs after the grace period (on Windows either signal ends it outright).
169
+ * Resolves once it is gone; throws what process.kill threw (ESRCH, EPERM), or
170
+ * that it still runs.
171
+ */
172
+ export async function terminatePid(pid) {
173
+ process.kill(pid, 'SIGTERM');
174
+ if (await waitUntilGone([pid], TERMINATE_GRACE_MS))
175
+ return;
176
+ try {
177
+ process.kill(pid, 'SIGKILL');
178
+ }
179
+ catch (error) {
180
+ if (error.code === 'ESRCH')
181
+ return; // Exited in the meantime
182
+ throw error;
183
+ }
184
+ if (!(await waitUntilGone([pid], EXIT_WAIT_MS))) {
185
+ throw new Error(`PID ${pid} still runs ${EXIT_WAIT_MS}ms after being killed`);
186
+ }
187
+ }
188
+ /** Windows: taskkill from the Windows directory rather than PATH, which a client may launch us with broken (see #481) */
189
+ function taskkillPath() {
190
+ return path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'taskkill.exe');
191
+ }
192
+ /**
193
+ * Ends `child` and every process it started. Resolves once they are gone:
194
+ * true, or false if some could not be ended (why is logged, and the root is
195
+ * then killed on its own if it still runs). Never rejects.
196
+ */
197
+ export async function terminateProcessTree(child) {
198
+ const pid = child.pid;
199
+ if (pid === undefined || hasExited(child))
200
+ return true;
201
+ let failure;
202
+ try {
203
+ if (isWindows()) {
204
+ await runCommand(taskkillPath(), ['/PID', String(pid), '/T', '/F']);
205
+ }
206
+ else {
207
+ await endPosixTree(pid);
208
+ }
209
+ }
210
+ catch (error) {
211
+ failure = error instanceof Error ? error.message : String(error);
212
+ if (!hasExited(child))
213
+ child.kill('SIGKILL');
214
+ }
215
+ if (!(await waitForExit(child, EXIT_WAIT_MS))) {
216
+ failure = [failure, `PID ${pid} still runs ${EXIT_WAIT_MS}ms after being killed`].filter(Boolean).join('; ');
217
+ }
218
+ if (failure) {
219
+ logger.error(`Could not end every process of PID ${pid}: ${failure}`);
220
+ return false;
221
+ }
222
+ return true;
223
+ }
@@ -0,0 +1,9 @@
1
+ export declare function renameWithRetry(from: string, to: string): Promise<void>;
2
+ /**
3
+ * Moves `from` to `to`, a file or a folder with everything in it, as mv does.
4
+ * A rename can't reach another volume (EXDEV): the entry is then copied, next
5
+ * to `to` under a temporary name, renamed onto `to` once the whole copy is
6
+ * there, and only then is the source removed. A copy that fails removes what
7
+ * it wrote, leaves the source as it was and throws its error.
8
+ */
9
+ export declare function movePath(from: string, to: string): Promise<void>;
@@ -0,0 +1,74 @@
1
+ import fs from 'fs/promises';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { logger } from './logger.js';
5
+ /**
6
+ * Single place for renaming files. Use this instead of fs.rename.
7
+ *
8
+ * Windows refuses to rename a file, or replace a destination, while another
9
+ * process has it open (readers, antivirus and search indexers hold such
10
+ * handles briefly) and reports EPERM, EACCES or EBUSY. Those errors are
11
+ * retried with a short backoff. Any other error, one onto an existing
12
+ * directory or a read-only file (Windows answers those with EPERM too, and
13
+ * they never succeed), and every error on macOS/Linux, is thrown immediately.
14
+ */
15
+ const WINDOWS_TRANSIENT_RENAME_ERRORS = new Set(['EPERM', 'EACCES', 'EBUSY']);
16
+ const RENAME_RETRY_BUDGET_MS = 5000;
17
+ export async function renameWithRetry(from, to) {
18
+ const deadline = Date.now() + RENAME_RETRY_BUDGET_MS;
19
+ for (let attempt = 1;; attempt++) {
20
+ try {
21
+ await fs.rename(from, to);
22
+ return;
23
+ }
24
+ catch (error) {
25
+ const transient = os.platform() === 'win32' && WINDOWS_TRANSIENT_RENAME_ERRORS.has(error?.code)
26
+ && !(await cannotBeReplaced(to));
27
+ if (!transient || Date.now() >= deadline)
28
+ throw error;
29
+ await new Promise((resolve) => setTimeout(resolve, Math.min(10 * attempt, 100)));
30
+ }
31
+ }
32
+ }
33
+ /**
34
+ * Moves `from` to `to`, a file or a folder with everything in it, as mv does.
35
+ * A rename can't reach another volume (EXDEV): the entry is then copied, next
36
+ * to `to` under a temporary name, renamed onto `to` once the whole copy is
37
+ * there, and only then is the source removed. A copy that fails removes what
38
+ * it wrote, leaves the source as it was and throws its error.
39
+ */
40
+ export async function movePath(from, to) {
41
+ try {
42
+ await renameWithRetry(from, to);
43
+ return;
44
+ }
45
+ catch (error) {
46
+ if (error?.code !== 'EXDEV')
47
+ throw error;
48
+ }
49
+ const copy = path.join(path.dirname(to), `.${path.basename(to)}.${process.pid}-${Date.now()}.moving`);
50
+ try {
51
+ // A link is copied as a link, as a rename moves it
52
+ await fs.cp(from, copy, { recursive: true, errorOnExist: true, force: false, preserveTimestamps: true, verbatimSymlinks: true });
53
+ await renameWithRetry(copy, to);
54
+ }
55
+ catch (error) {
56
+ await fs.rm(copy, { recursive: true, force: true }).catch((cleanupError) => {
57
+ // The copy's error says why the move failed; this one is only logged
58
+ logger.error(`Could not remove the partial copy ${copy}: ${cleanupError}`);
59
+ });
60
+ throw error;
61
+ }
62
+ await fs.rm(from, { recursive: true });
63
+ }
64
+ /** Whether `filePath` is what a rename never replaces on Windows: a directory, or a read-only file */
65
+ async function cannotBeReplaced(filePath) {
66
+ try {
67
+ const stats = await fs.lstat(filePath);
68
+ return stats.isDirectory() || (stats.mode & 0o200) === 0;
69
+ }
70
+ catch {
71
+ // Missing or unreadable: nothing says the rename can't succeed, so keep treating it as a held file
72
+ return false;
73
+ }
74
+ }