@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.
- package/dist/bootstrap.js +7 -7
- package/dist/command-manager.d.ts +98 -1
- package/dist/command-manager.js +237 -16
- package/dist/remote-device/desktop-commander-integration.js +3 -1
- package/dist/remote-device/diagnostics/redact.js +30 -8
- package/dist/remote-device/diagnostics/report.js +30 -13
- package/dist/remote-device/mqtt/mqtt-enrollment.js +1 -1
- package/dist/remote-device/mqtt/mqtt-transport.js +2 -2
- package/dist/remote-device/remote-channel.d.ts +1 -1
- package/dist/remote-device/remote-channel.js +1 -1
- package/dist/remote-device/transport-telemetry.js +5 -4
- package/dist/server.js +2 -0
- package/dist/terminal-manager.js +4 -6
- package/dist/tools/improved-process-tools.d.ts +2 -0
- package/dist/tools/improved-process-tools.js +68 -40
- package/dist/tools/pdf/markdown.js +7 -3
- package/dist/tools/process.js +10 -2
- package/dist/track-installation.js +2 -2
- package/dist/ui/config-editor/config-editor-runtime.js +80 -61
- package/dist/ui/file-preview/preview-runtime.js +225 -207
- package/dist/utils/brace-expansion.d.ts +30 -0
- package/dist/utils/brace-expansion.js +192 -0
- package/dist/utils/capture.d.ts +8 -2
- package/dist/utils/capture.js +1 -1
- package/dist/utils/cmd-commands.d.ts +3 -0
- package/dist/utils/cmd-commands.js +370 -0
- package/dist/utils/command-reading.d.ts +92 -0
- package/dist/utils/command-reading.js +14 -0
- package/dist/utils/command-wrappers.d.ts +45 -0
- package/dist/utils/command-wrappers.js +964 -0
- package/dist/utils/inline-shells.d.ts +67 -0
- package/dist/utils/inline-shells.js +310 -0
- package/dist/utils/posix-commands.d.ts +6 -0
- package/dist/utils/posix-commands.js +237 -0
- package/dist/utils/posix-shell-capabilities.d.ts +8 -0
- package/dist/utils/posix-shell-capabilities.js +120 -0
- package/dist/utils/powershell-commands.d.ts +61 -0
- package/dist/utils/powershell-commands.js +468 -0
- package/dist/utils/process-tree.js +4 -4
- package/dist/utils/shell-script-files.d.ts +8 -0
- package/dist/utils/shell-script-files.js +140 -0
- package/dist/utils/shell.d.ts +37 -0
- package/dist/utils/shell.js +73 -0
- package/dist/utils/system-info.d.ts +2 -0
- package/dist/utils/system-info.js +5 -1
- package/dist/utils/threadpool-size.d.ts +36 -0
- package/dist/utils/threadpool-size.js +143 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +11 -9
- package/dist/bootstrap.js.map +0 -1
- package/dist/command-manager.js.map +0 -1
- package/dist/config-field-definitions.js.map +0 -1
- package/dist/config-manager.js.map +0 -1
- package/dist/config-recovery.js.map +0 -1
- package/dist/config.js.map +0 -1
- package/dist/custom-stdio.js.map +0 -1
- package/dist/error-handlers.js.map +0 -1
- package/dist/handlers/edit-search-handlers.js.map +0 -1
- package/dist/handlers/filesystem-handlers.js.map +0 -1
- package/dist/handlers/history-handlers.js.map +0 -1
- package/dist/handlers/index.js.map +0 -1
- package/dist/handlers/process-handlers.js.map +0 -1
- package/dist/handlers/search-answers.js.map +0 -1
- package/dist/handlers/search-handlers.js.map +0 -1
- package/dist/handlers/terminal-handlers.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/npm-scripts/remote.js.map +0 -1
- package/dist/npm-scripts/setup.js.map +0 -1
- package/dist/npm-scripts/uninstall.js.map +0 -1
- package/dist/npm-scripts/verify-ripgrep.js.map +0 -1
- package/dist/remote-device/desktop-commander-integration.js.map +0 -1
- package/dist/remote-device/device-authenticator.js.map +0 -1
- package/dist/remote-device/device.js.map +0 -1
- package/dist/remote-device/diagnostics/device-log.js.map +0 -1
- package/dist/remote-device/diagnostics/redact.js.map +0 -1
- package/dist/remote-device/diagnostics/report.js.map +0 -1
- package/dist/remote-device/diagnostics/upload.js.map +0 -1
- package/dist/remote-device/mqtt/config.js.map +0 -1
- package/dist/remote-device/mqtt/mqtt-enrollment.js.map +0 -1
- package/dist/remote-device/mqtt/mqtt-transport.js.map +0 -1
- package/dist/remote-device/realtime-health-telemetry.js.map +0 -1
- package/dist/remote-device/remote-channel.js.map +0 -1
- package/dist/remote-device/remote-utils.js.map +0 -1
- package/dist/remote-device/rollouts.js.map +0 -1
- package/dist/remote-device/transport-telemetry.js.map +0 -1
- package/dist/search-manager.js.map +0 -1
- package/dist/server.js.map +0 -1
- package/dist/terminal-manager.js.map +0 -1
- package/dist/tools/config.js.map +0 -1
- package/dist/tools/edit.js.map +0 -1
- package/dist/tools/feedback.js.map +0 -1
- package/dist/tools/filesystem.js.map +0 -1
- package/dist/tools/fuzzySearch.js.map +0 -1
- package/dist/tools/fuzzySearchCore.js.map +0 -1
- package/dist/tools/improved-process-tools.js.map +0 -1
- package/dist/tools/mime-types.js.map +0 -1
- package/dist/tools/pdf/extract-images.js.map +0 -1
- package/dist/tools/pdf/index.js.map +0 -1
- package/dist/tools/pdf/lib/pdf2md.js.map +0 -1
- package/dist/tools/pdf/manipulations.js.map +0 -1
- package/dist/tools/pdf/markdown.js.map +0 -1
- package/dist/tools/pdf/utils.js.map +0 -1
- package/dist/tools/process.js.map +0 -1
- package/dist/tools/prompts.js.map +0 -1
- package/dist/tools/schemas.js.map +0 -1
- package/dist/tools/usage.js.map +0 -1
- package/dist/types.js.map +0 -1
- package/dist/ui/config-editor/src/app.js.map +0 -1
- package/dist/ui/config-editor/src/array-modal.js.map +0 -1
- package/dist/ui/config-editor/src/main.js.map +0 -1
- package/dist/ui/contracts.js.map +0 -1
- package/dist/ui/file-preview/shared/preview-file-types.js.map +0 -1
- package/dist/ui/file-preview/src/app.js.map +0 -1
- package/dist/ui/file-preview/src/components/code-viewer.js.map +0 -1
- package/dist/ui/file-preview/src/components/highlighting.js.map +0 -1
- package/dist/ui/file-preview/src/components/html-renderer.js.map +0 -1
- package/dist/ui/file-preview/src/components/markdown-renderer.js.map +0 -1
- package/dist/ui/file-preview/src/directory-controller.js.map +0 -1
- package/dist/ui/file-preview/src/document-layout.js.map +0 -1
- package/dist/ui/file-preview/src/document-outline.js.map +0 -1
- package/dist/ui/file-preview/src/document-workspace.js.map +0 -1
- package/dist/ui/file-preview/src/file-type-handlers.js.map +0 -1
- package/dist/ui/file-preview/src/host/external-actions.js.map +0 -1
- package/dist/ui/file-preview/src/host/selection-context.js.map +0 -1
- package/dist/ui/file-preview/src/image-preview.js.map +0 -1
- package/dist/ui/file-preview/src/main.js.map +0 -1
- package/dist/ui/file-preview/src/markdown/conflict-dialog.js.map +0 -1
- package/dist/ui/file-preview/src/markdown/controller.js.map +0 -1
- package/dist/ui/file-preview/src/markdown/editor.js.map +0 -1
- package/dist/ui/file-preview/src/markdown/linking.js.map +0 -1
- package/dist/ui/file-preview/src/markdown/outline.js.map +0 -1
- package/dist/ui/file-preview/src/markdown/parser.js.map +0 -1
- package/dist/ui/file-preview/src/markdown/preview.js.map +0 -1
- package/dist/ui/file-preview/src/markdown/slugify.js.map +0 -1
- package/dist/ui/file-preview/src/markdown/utils.js.map +0 -1
- package/dist/ui/file-preview/src/model.js.map +0 -1
- package/dist/ui/file-preview/src/panel-actions.js.map +0 -1
- package/dist/ui/file-preview/src/path-utils.js.map +0 -1
- package/dist/ui/file-preview/src/payload-utils.js.map +0 -1
- package/dist/ui/file-preview/src/types.js.map +0 -1
- package/dist/ui/resources.js.map +0 -1
- package/dist/ui/shared/compact-row.js.map +0 -1
- package/dist/ui/shared/escape-html.js.map +0 -1
- package/dist/ui/shared/host-context.js.map +0 -1
- package/dist/ui/shared/tool-bridge.js.map +0 -1
- package/dist/ui/shared/tool-shell.js.map +0 -1
- package/dist/ui/shared/ui-event-tracker.js.map +0 -1
- package/dist/ui/shared/widget-state.js.map +0 -1
- package/dist/utils/ab-test.js.map +0 -1
- package/dist/utils/atomic-write.js.map +0 -1
- package/dist/utils/capture.js.map +0 -1
- package/dist/utils/dockerPrompt.js.map +0 -1
- package/dist/utils/exit-process.js.map +0 -1
- package/dist/utils/feature-flags.js.map +0 -1
- package/dist/utils/files/base.js.map +0 -1
- package/dist/utils/files/binary.js.map +0 -1
- package/dist/utils/files/docx.js.map +0 -1
- package/dist/utils/files/excel.js.map +0 -1
- package/dist/utils/files/factory.js.map +0 -1
- package/dist/utils/files/image.js.map +0 -1
- package/dist/utils/files/index.js.map +0 -1
- package/dist/utils/files/pdf.js.map +0 -1
- package/dist/utils/files/text.js.map +0 -1
- package/dist/utils/fuzzySearchLogger.js.map +0 -1
- package/dist/utils/internal-facts.js.map +0 -1
- package/dist/utils/lazy-package.js.map +0 -1
- package/dist/utils/lineEndingHandler.js.map +0 -1
- package/dist/utils/logger.js.map +0 -1
- package/dist/utils/mcp-ui-ab-test.js.map +0 -1
- package/dist/utils/open-browser.js.map +0 -1
- package/dist/utils/process-detection.js.map +0 -1
- package/dist/utils/process-tree.js.map +0 -1
- package/dist/utils/rename.js.map +0 -1
- package/dist/utils/ripgrep-resolver.js.map +0 -1
- package/dist/utils/shell.js.map +0 -1
- package/dist/utils/system-info.js.map +0 -1
- package/dist/utils/terminal-timestamps.js.map +0 -1
- package/dist/utils/toolHistory.js.map +0 -1
- package/dist/utils/trackTools.js.map +0 -1
- package/dist/utils/unsupportedParams.js.map +0 -1
- package/dist/utils/usageTracker.js.map +0 -1
- package/dist/utils/welcome-onboarding.js.map +0 -1
- package/dist/utils/withTimeout.js.map +0 -1
- package/dist/version.js.map +0 -1
- package/node_modules/@desktop-commander/telemetry-contract/README.md +0 -56
- package/node_modules/@desktop-commander/telemetry-contract/package.json +0 -32
- package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +0 -39
- package/node_modules/@desktop-commander/telemetry-contract/transport.js +0 -167
- package/vendor/telemetry-contract/README.md +0 -56
- package/vendor/telemetry-contract/package.json +0 -32
- package/vendor/telemetry-contract/transport.d.ts +0 -38
- package/vendor/telemetry-contract/transport.js +0 -164
- package/vendor/telemetry-contract/transport.test.js +0 -39
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { execFile } from 'child_process';
|
|
4
|
+
/** Captured at server import, before a command can change cwd, PATH or startup variables. */
|
|
5
|
+
const launchCwd = fs.realpathSync(process.cwd());
|
|
6
|
+
const launchPathValue = process.env.PATH ?? '';
|
|
7
|
+
const launchEnv = { ...process.env };
|
|
8
|
+
const launchPath = launchPathValue.split(path.delimiter)
|
|
9
|
+
.map((folder) => path.resolve(launchCwd, folder));
|
|
10
|
+
// process.env is case-insensitive on Windows; its plain-object copy is not.
|
|
11
|
+
for (const name of Object.keys(launchEnv))
|
|
12
|
+
if (name.toLowerCase() === 'path')
|
|
13
|
+
delete launchEnv[name];
|
|
14
|
+
launchEnv.PATH = launchPath.join(path.delimiter);
|
|
15
|
+
delete launchEnv.BASH_ENV;
|
|
16
|
+
delete launchEnv.ENV;
|
|
17
|
+
delete launchEnv.ZDOTDIR;
|
|
18
|
+
const endpoints = new Map();
|
|
19
|
+
const aliases = new Map();
|
|
20
|
+
const names = process.platform === 'win32' ? ['bash.exe', 'zsh.exe'] : ['bash', 'zsh'];
|
|
21
|
+
const key = (file) => process.platform === 'win32' ? file.toLowerCase() : file;
|
|
22
|
+
/** A script named bash is not a native capability endpoint, even on the launch PATH. */
|
|
23
|
+
function nativeFile(file) {
|
|
24
|
+
let descriptor;
|
|
25
|
+
try {
|
|
26
|
+
const real = fs.realpathSync(file);
|
|
27
|
+
if (!isLaunchExecutable(real))
|
|
28
|
+
return undefined;
|
|
29
|
+
descriptor = fs.openSync(real, 'r');
|
|
30
|
+
const header = Buffer.alloc(4);
|
|
31
|
+
if (fs.readSync(descriptor, header, 0, 4, 0) !== 4)
|
|
32
|
+
return undefined;
|
|
33
|
+
const magic = header.toString('hex');
|
|
34
|
+
return magic.startsWith('4d5a') || ['7f454c46', 'feedface', 'feedfacf', 'cefaedfe',
|
|
35
|
+
'cffaedfe', 'cafebabe', 'bebafeca', 'cafebabf', 'bfbafeca'].includes(magic) ? real : undefined;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// Missing or unreadable endpoints cannot supply a native capability; preserve the legacy reading.
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
if (descriptor !== undefined)
|
|
43
|
+
fs.closeSync(descriptor);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function capture(file) {
|
|
47
|
+
const real = nativeFile(file);
|
|
48
|
+
if (real === undefined)
|
|
49
|
+
return undefined;
|
|
50
|
+
let endpoint = endpoints.get(key(real));
|
|
51
|
+
if (endpoint === undefined) {
|
|
52
|
+
if (endpoints.size >= 32)
|
|
53
|
+
return undefined;
|
|
54
|
+
endpoint = { file: real };
|
|
55
|
+
endpoints.set(key(real), endpoint);
|
|
56
|
+
}
|
|
57
|
+
aliases.set(key(file), endpoint);
|
|
58
|
+
aliases.set(key(real), endpoint);
|
|
59
|
+
return endpoint;
|
|
60
|
+
}
|
|
61
|
+
function isLaunchExecutable(file) {
|
|
62
|
+
try {
|
|
63
|
+
fs.accessSync(file, process.platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);
|
|
64
|
+
return fs.statSync(file).isFile();
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
// A missing or inaccessible PATH entry cannot be the executable selected at launch.
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// Bare names bind to the FIRST launch-PATH executable, including an unsupported script.
|
|
72
|
+
for (const name of names) {
|
|
73
|
+
let first = true;
|
|
74
|
+
for (const folder of launchPath) {
|
|
75
|
+
const file = path.join(folder, name);
|
|
76
|
+
if (!isLaunchExecutable(file))
|
|
77
|
+
continue;
|
|
78
|
+
const endpoint = capture(file);
|
|
79
|
+
if (first)
|
|
80
|
+
aliases.set(key(name), endpoint);
|
|
81
|
+
first = false;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const standards = process.platform === 'win32'
|
|
85
|
+
? [path.join(launchEnv.ProgramFiles ?? 'C:\\Program Files', 'Git', 'bin', 'bash.exe'),
|
|
86
|
+
path.join(launchEnv.ProgramFiles ?? 'C:\\Program Files', 'Git', 'usr', 'bin', 'bash.exe')]
|
|
87
|
+
: ['/bin/bash', '/usr/bin/bash', '/usr/local/bin/bash', '/opt/homebrew/bin/bash',
|
|
88
|
+
'/bin/zsh', '/usr/bin/zsh', '/usr/local/bin/zsh', '/opt/homebrew/bin/zsh'];
|
|
89
|
+
for (const file of standards)
|
|
90
|
+
capture(file);
|
|
91
|
+
/**
|
|
92
|
+
* Fixed --version only, on a matching precaptured native endpoint; never caller code or a profile.
|
|
93
|
+
* Native Bash5.2 retains the backslash slot that Bash5.3 omits; other Bash4/5 calls keep legacy rules.
|
|
94
|
+
* Bash3.2 and Zsh5.9 defaults remain supported; startup options and profiles are not evaluated.
|
|
95
|
+
* One bounded query per endpoint (at most 32); unknown, unavailable or other versions retain legacy behavior.
|
|
96
|
+
*/
|
|
97
|
+
export function posixBraceSemantics(shell) {
|
|
98
|
+
const bare = !shell.includes('/') && !shell.includes('\\');
|
|
99
|
+
const endpoint = aliases.get(key(bare ? shell : path.resolve(launchCwd, shell)));
|
|
100
|
+
if (endpoint === undefined)
|
|
101
|
+
return Promise.resolve(undefined);
|
|
102
|
+
endpoint.semantics ?? (endpoint.semantics = new Promise((resolve) => {
|
|
103
|
+
execFile(endpoint.file, ['--version'], { cwd: launchCwd, env: launchEnv, timeout: 1000,
|
|
104
|
+
maxBuffer: 4096, windowsHide: true, encoding: 'utf8' }, (error, stdout) => {
|
|
105
|
+
if (error)
|
|
106
|
+
return resolve(undefined);
|
|
107
|
+
const version = /^GNU bash, version (\d+)\.(\d+)(?:\D|$)/.exec(stdout);
|
|
108
|
+
if (version?.[1] === '3' && version[2] === '2')
|
|
109
|
+
return resolve('bash3');
|
|
110
|
+
if (version?.[1] === '5' && version[2] === '2')
|
|
111
|
+
return resolve('bash5.2');
|
|
112
|
+
if (version && ['4', '5'].includes(version[1]))
|
|
113
|
+
return resolve('legacy');
|
|
114
|
+
if (/^zsh 5\.9(?:\D|$)/.test(stdout))
|
|
115
|
+
return resolve('zsh');
|
|
116
|
+
resolve(undefined);
|
|
117
|
+
});
|
|
118
|
+
}));
|
|
119
|
+
return endpoint.semantics;
|
|
120
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { CommandReading } from './command-reading.js';
|
|
2
|
+
/**
|
|
3
|
+
* The command check's reader for PowerShell. No JavaScript parser reads
|
|
4
|
+
* PowerShell correctly (here-strings, @{ } tables, & $var), so a helper
|
|
5
|
+
* PowerShell process reads each command with PowerShell's own parser. It
|
|
6
|
+
* starts at the first PowerShell check, so nothing runs for users who never
|
|
7
|
+
* run PowerShell commands, and it is kept running: a check then takes a few
|
|
8
|
+
* milliseconds instead of PowerShell's start (about a second for Windows
|
|
9
|
+
* PowerShell). It is not a terminal session, so list_sessions never shows it.
|
|
10
|
+
* It starts as the PowerShell a command runs in starts: with the user's
|
|
11
|
+
* profile (start_process starts it without -NoProfile), without
|
|
12
|
+
* -NonInteractive, with -Login for PowerShell 7, and with the commands'
|
|
13
|
+
* environment. So a profile sets the same aliases for both. Only its working
|
|
14
|
+
* folder is its own (see start()).
|
|
15
|
+
*/
|
|
16
|
+
/** How long a check waits for a running helper's answer. A helper that doesn't answer is stopped, and the check fails. */
|
|
17
|
+
export declare const HELPER_TIMEOUT_MS = 5000;
|
|
18
|
+
/**
|
|
19
|
+
* How long the first check waits after a helper starts, PowerShell's start
|
|
20
|
+
* and the user's profile included: about a second for Windows PowerShell,
|
|
21
|
+
* longer on a busy machine or with a slow profile
|
|
22
|
+
*/
|
|
23
|
+
export declare const HELPER_START_TIMEOUT_MS = 15000;
|
|
24
|
+
/** One helper process for one PowerShell program, started at its first read and again after it ended */
|
|
25
|
+
export declare class PowerShellHelper {
|
|
26
|
+
private readonly program;
|
|
27
|
+
private readonly args;
|
|
28
|
+
private child;
|
|
29
|
+
private output;
|
|
30
|
+
private nextId;
|
|
31
|
+
private readonly pending;
|
|
32
|
+
private timer;
|
|
33
|
+
/** Whether the running helper process has answered yet: until then its start counts in the time limit */
|
|
34
|
+
private answered;
|
|
35
|
+
/** Made at each start and sent with every request; an answer has it, a line the profile printed doesn't */
|
|
36
|
+
private token;
|
|
37
|
+
/** args replace the helper's arguments, for a stand-in in tests */
|
|
38
|
+
constructor(program: string, args?: string[]);
|
|
39
|
+
/** The running helper's process id: undefined before the first read and after the process ended */
|
|
40
|
+
get pid(): number | undefined;
|
|
41
|
+
/** Reads one command. It rejects when the helper doesn't answer in time, can't start, or ends first. */
|
|
42
|
+
read(command: string): Promise<CommandReading>;
|
|
43
|
+
/** The time limit for the oldest waiting request: longer while the helper hasn't answered since it started */
|
|
44
|
+
private startTimeLimit;
|
|
45
|
+
/** Ends the helper process. The next read starts a new one. */
|
|
46
|
+
stop(): void;
|
|
47
|
+
private start;
|
|
48
|
+
private onOutput;
|
|
49
|
+
private onAnswer;
|
|
50
|
+
/** The helper process ended or failed to start: every waiting read fails, and the next read starts a new one */
|
|
51
|
+
private ended;
|
|
52
|
+
private fail;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Reads a command for a PowerShell shell ("powershell.exe", "pwsh" or a path),
|
|
56
|
+
* only when its filesystem identity matches a launch-PATH parser. Custom
|
|
57
|
+
* executables are refused before startup, rather than used to validate themselves.
|
|
58
|
+
*/
|
|
59
|
+
export declare function readPowerShellCommands(command: string, shell: string): Promise<CommandReading>;
|
|
60
|
+
/** The process ids of the helpers running now, for tests */
|
|
61
|
+
export declare function runningPowerShellHelpers(): number[];
|
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
import { spawn } from 'child_process';
|
|
2
|
+
import { randomBytes } from 'crypto';
|
|
3
|
+
import fs from 'fs';
|
|
4
|
+
import path from 'path';
|
|
5
|
+
import { fileURLToPath } from 'url';
|
|
6
|
+
import { getShellEnvironment, resolveShellPath } from './shell.js';
|
|
7
|
+
/**
|
|
8
|
+
* The command check's reader for PowerShell. No JavaScript parser reads
|
|
9
|
+
* PowerShell correctly (here-strings, @{ } tables, & $var), so a helper
|
|
10
|
+
* PowerShell process reads each command with PowerShell's own parser. It
|
|
11
|
+
* starts at the first PowerShell check, so nothing runs for users who never
|
|
12
|
+
* run PowerShell commands, and it is kept running: a check then takes a few
|
|
13
|
+
* milliseconds instead of PowerShell's start (about a second for Windows
|
|
14
|
+
* PowerShell). It is not a terminal session, so list_sessions never shows it.
|
|
15
|
+
* It starts as the PowerShell a command runs in starts: with the user's
|
|
16
|
+
* profile (start_process starts it without -NoProfile), without
|
|
17
|
+
* -NonInteractive, with -Login for PowerShell 7, and with the commands'
|
|
18
|
+
* environment. So a profile sets the same aliases for both. Only its working
|
|
19
|
+
* folder is its own (see start()).
|
|
20
|
+
*/
|
|
21
|
+
/** How long a check waits for a running helper's answer. A helper that doesn't answer is stopped, and the check fails. */
|
|
22
|
+
export const HELPER_TIMEOUT_MS = 5000;
|
|
23
|
+
/**
|
|
24
|
+
* How long the first check waits after a helper starts, PowerShell's start
|
|
25
|
+
* and the user's profile included: about a second for Windows PowerShell,
|
|
26
|
+
* longer on a busy machine or with a slow profile
|
|
27
|
+
*/
|
|
28
|
+
export const HELPER_START_TIMEOUT_MS = 15000;
|
|
29
|
+
/** The folder Desktop Commander is installed in, where its own node:local process runs too */
|
|
30
|
+
const mcpRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
31
|
+
/**
|
|
32
|
+
* The helper, run with -EncodedCommand. It reads one JSON request per line
|
|
33
|
+
* ({ id, token, command }) and writes one JSON answer per line. It only
|
|
34
|
+
* parses the command and looks names up with Get-Command; it never runs the
|
|
35
|
+
* command.
|
|
36
|
+
* Module autoloading is off so that looking up a name never imports a module.
|
|
37
|
+
* Each CommandAst is a command, also inside script blocks and functions. Its
|
|
38
|
+
* name is what it means in this PowerShell: an alias gives its target, a
|
|
39
|
+
* program or script its file name as found (net.exe). A name Get-Command
|
|
40
|
+
* doesn't know stays as written. A name from a variable or expression
|
|
41
|
+
* (& $tool) is known only at run time. Each word's text is its value, or
|
|
42
|
+
* where that is known only at run time the word as written, a "..." string
|
|
43
|
+
* without its quotes.
|
|
44
|
+
* For a command that means Start-Process, filePaths are the programs it may
|
|
45
|
+
* start: the word its FilePath parameter takes as this PowerShell binds the
|
|
46
|
+
* command (with the Management module, imported the first time), and a
|
|
47
|
+
* splatted @params, which may hold FilePath. The binder can't see into
|
|
48
|
+
* @params and doesn't know -- (the end of the parameters), so the command is
|
|
49
|
+
* also bound with those words left out.
|
|
50
|
+
* The functions are the definitions among the script's own statements, with
|
|
51
|
+
* the offset where each ends. There are none when the text has a { } script
|
|
52
|
+
* block written as a value, which may run where the functions don't exist
|
|
53
|
+
* (Start-Job runs it in another process), or something that may remove a
|
|
54
|
+
* function or hide it behind an alias, which comes before a function: a
|
|
55
|
+
* $function: or $alias: variable ($function:net = $null), Set-Alias, New-Alias
|
|
56
|
+
* or Import-Alias, a word naming the function or alias drive or provider
|
|
57
|
+
* (Remove-Item function:net, New-Item alias:net, New-PSDrive -PSProvider
|
|
58
|
+
* Function), or an item or content cmdlet whose path is known only at run
|
|
59
|
+
* time or comes from the pipeline ('function:net' | Remove-Item; Set-Content
|
|
60
|
+
* gives a function a new body). Nor when it runs code the helper doesn't
|
|
61
|
+
* read: Invoke-Expression, Import-Module, Add-Type, a script file, a name
|
|
62
|
+
* known only at run time, a method call ([scriptblock]::Create(...).Invoke())
|
|
63
|
+
* or ForEach-Object calling one. Nor is a function the session has an alias
|
|
64
|
+
* of, such as one the user's profile sets.
|
|
65
|
+
* Offsets are .NET string indexes, the same as JavaScript's.
|
|
66
|
+
* The profile runs first, and may print anything and define functions and
|
|
67
|
+
* aliases with any name. So the helper writes an empty line before its first
|
|
68
|
+
* answer (text the profile printed without a newline ends there), puts the
|
|
69
|
+
* request's token in each answer (the reader takes no other line for one),
|
|
70
|
+
* calls each cmdlet by its module's name, which no function or alias
|
|
71
|
+
* replaces, and keeps its own functions in variables ($getMeaning), which no
|
|
72
|
+
* alias replaces either.
|
|
73
|
+
*/
|
|
74
|
+
const HELPER_SCRIPT = `
|
|
75
|
+
$ErrorActionPreference = 'Stop'
|
|
76
|
+
$ProgressPreference = 'SilentlyContinue'
|
|
77
|
+
Microsoft.PowerShell.Core\\Import-Module Microsoft.PowerShell.Utility
|
|
78
|
+
$PSModuleAutoLoadingPreference = 'None'
|
|
79
|
+
$utf8 = Microsoft.PowerShell.Utility\\New-Object System.Text.UTF8Encoding $false
|
|
80
|
+
$reader = Microsoft.PowerShell.Utility\\New-Object System.IO.StreamReader ([Console]::OpenStandardInput()), $utf8
|
|
81
|
+
$writer = Microsoft.PowerShell.Utility\\New-Object System.IO.StreamWriter ([Console]::OpenStandardOutput()), $utf8
|
|
82
|
+
$writer.AutoFlush = $true
|
|
83
|
+
$writer.WriteLine()
|
|
84
|
+
# The helper's own functions are script blocks in variables: an alias with a function's name, such as one the profile sets, comes before the function
|
|
85
|
+
$getMeaning = {
|
|
86
|
+
param([string]$name)
|
|
87
|
+
$found = @(Microsoft.PowerShell.Core\\Get-Command -Name ([Management.Automation.WildcardPattern]::Escape($name)) -ErrorAction SilentlyContinue)
|
|
88
|
+
if ($found.Count -eq 0) { return $name }
|
|
89
|
+
if ($found[0].CommandType -eq 'Alias') { return $found[0].Definition }
|
|
90
|
+
return $found[0].Name
|
|
91
|
+
}
|
|
92
|
+
$getWordValue = {
|
|
93
|
+
param($element)
|
|
94
|
+
if ($element -is [Management.Automation.Language.StringConstantExpressionAst]) { return $element.Value }
|
|
95
|
+
if ($element -is [Management.Automation.Language.CommandParameterAst]) { return $element.Extent.Text }
|
|
96
|
+
if ($element -is [Management.Automation.Language.ConstantExpressionAst]) { return $element.Extent.Text }
|
|
97
|
+
return $null
|
|
98
|
+
}
|
|
99
|
+
# The word's value, else as written; a "..." string's value keeps its variables as written ("net user $name")
|
|
100
|
+
$getWordText = {
|
|
101
|
+
param($element)
|
|
102
|
+
$value = & $getWordValue $element
|
|
103
|
+
if ($null -ne $value) { return $value }
|
|
104
|
+
if ($element -is [Management.Automation.Language.ExpandableStringExpressionAst]) { return $element.Value }
|
|
105
|
+
return $element.Extent.Text
|
|
106
|
+
}
|
|
107
|
+
$managementImported = $false
|
|
108
|
+
$getFilePaths = {
|
|
109
|
+
param($command)
|
|
110
|
+
if (-not $script:managementImported) {
|
|
111
|
+
Microsoft.PowerShell.Core\\Import-Module Microsoft.PowerShell.Management
|
|
112
|
+
$script:managementImported = $true
|
|
113
|
+
}
|
|
114
|
+
$programs = @()
|
|
115
|
+
$text = $command.Extent.Text
|
|
116
|
+
foreach ($element in $command.CommandElements) {
|
|
117
|
+
$splatted = $element -is [Management.Automation.Language.VariableExpressionAst] -and $element.Splatted
|
|
118
|
+
if ($splatted) { $programs += @{ word = $null; written = $element.Extent.Text } }
|
|
119
|
+
if ($splatted -or $element.Extent.Text -eq '--') {
|
|
120
|
+
$at = $element.Extent.StartOffset - $command.Extent.StartOffset
|
|
121
|
+
$text = $text.Remove($at, $element.Extent.Text.Length).Insert($at, ' ' * $element.Extent.Text.Length)
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
$bindings = @($command)
|
|
125
|
+
if ($text -ne $command.Extent.Text) {
|
|
126
|
+
$bindings += [Management.Automation.Language.Parser]::ParseInput($text, [ref]$null, [ref]$null).Find({ $args[0] -is [Management.Automation.Language.CommandAst] }, $true)
|
|
127
|
+
}
|
|
128
|
+
foreach ($binding in $bindings) {
|
|
129
|
+
# A command PowerShell can't bind is one it refuses to run
|
|
130
|
+
try { $filePath = [Management.Automation.Language.StaticParameterBinder]::BindCommand($binding, $true).BoundParameters['FilePath'] } catch { continue }
|
|
131
|
+
if ($null -eq $filePath -or ($filePath.Value -is [Management.Automation.Language.VariableExpressionAst] -and $filePath.Value.Splatted)) { continue }
|
|
132
|
+
$asWritten = $filePath.Value.Extent.Text
|
|
133
|
+
if (-not ($programs | Microsoft.PowerShell.Core\\Where-Object { $_.written -eq $asWritten })) { $programs += @{ word = (& $getWordValue $filePath.Value); written = $asWritten } }
|
|
134
|
+
}
|
|
135
|
+
return $programs
|
|
136
|
+
}
|
|
137
|
+
$testRemovesFunction = {
|
|
138
|
+
param($found)
|
|
139
|
+
if ($found.name -in 'Set-Alias', 'New-Alias', 'Import-Alias') { return $true }
|
|
140
|
+
$pathAtRunTime = $false
|
|
141
|
+
$knownPaths = 0
|
|
142
|
+
for ($i = 1; $i -lt $found.words.Count; $i++) {
|
|
143
|
+
$word = $found.words[$i]
|
|
144
|
+
if ($null -eq $word) { $pathAtRunTime = $true }
|
|
145
|
+
elseif ($word -match '\\b(function|alias)\\b') { return $true }
|
|
146
|
+
elseif (-not $word.StartsWith('-')) { $knownPaths++ }
|
|
147
|
+
}
|
|
148
|
+
return ($found.name -like '*-Item' -or $found.name -like '*-Content') -and ($pathAtRunTime -or $knownPaths -eq 0)
|
|
149
|
+
}
|
|
150
|
+
$testRunsUnreadCode = {
|
|
151
|
+
param($found)
|
|
152
|
+
if ($found.nameAtRunTime -or $found.name -in 'Invoke-Expression', 'Import-Module', 'Add-Type') { return $true }
|
|
153
|
+
# ForEach-Object InvokeScript 'text' calls each object's method
|
|
154
|
+
if ($found.name -eq 'ForEach-Object') {
|
|
155
|
+
$values = 0
|
|
156
|
+
for ($i = 1; $i -lt $found.words.Count; $i++) { if (-not "$($found.words[$i])".StartsWith('-')) { $values++ } }
|
|
157
|
+
if ($values -gt 1) { return $true }
|
|
158
|
+
}
|
|
159
|
+
# A script file: .ps1 or .psm1, or a path without an extension (. ./lib runs lib.ps1)
|
|
160
|
+
$leaf = $found.name.Substring($found.name.LastIndexOfAny([char[]]'\\/') + 1)
|
|
161
|
+
return $leaf -like '*.ps1' -or $leaf -like '*.psm1' -or ($leaf -ne $found.name -and $leaf -notlike '*.*')
|
|
162
|
+
}
|
|
163
|
+
while ($true) {
|
|
164
|
+
$line = $reader.ReadLine()
|
|
165
|
+
if ($null -eq $line) { break }
|
|
166
|
+
$request = Microsoft.PowerShell.Utility\\ConvertFrom-Json $line
|
|
167
|
+
$answer = @{ id = $request.id; token = $request.token }
|
|
168
|
+
try {
|
|
169
|
+
$tokens = $null
|
|
170
|
+
$errors = $null
|
|
171
|
+
$ast = [Management.Automation.Language.Parser]::ParseInput([string]$request.command, [ref]$tokens, [ref]$errors)
|
|
172
|
+
if ($errors.Count -gt 0) {
|
|
173
|
+
$answer.parseError = $errors[0].Message
|
|
174
|
+
} else {
|
|
175
|
+
$answer.commands = @(foreach ($command in $ast.FindAll({ $args[0] -is [Management.Automation.Language.CommandAst] }, $true)) {
|
|
176
|
+
$first = $command.CommandElements[0]
|
|
177
|
+
# & { ... } runs a script block, not a program: the commands inside it are found on their own
|
|
178
|
+
if ($first -is [Management.Automation.Language.ScriptBlockExpressionAst]) { continue }
|
|
179
|
+
$words = @(foreach ($element in $command.CommandElements) { ,(& $getWordValue $element) })
|
|
180
|
+
$written = @(foreach ($element in $command.CommandElements) { $element.Extent.Text })
|
|
181
|
+
$wordTexts = @(foreach ($element in $command.CommandElements) { & $getWordText $element })
|
|
182
|
+
$name = $command.GetCommandName()
|
|
183
|
+
if ($null -eq $name) {
|
|
184
|
+
@{ name = $first.Extent.Text; words = $words; written = $written; wordTexts = $wordTexts; start = $command.Extent.StartOffset; nameAtRunTime = $true }
|
|
185
|
+
} else {
|
|
186
|
+
$found = @{ name = (& $getMeaning $name); words = $words; written = $written; wordTexts = $wordTexts; start = $command.Extent.StartOffset; nameAtRunTime = $false }
|
|
187
|
+
if ($found.name -eq 'Start-Process') { $found.filePaths = @(& $getFilePaths $command) }
|
|
188
|
+
$found
|
|
189
|
+
}
|
|
190
|
+
})
|
|
191
|
+
$isBlockValue = { $args[0] -is [Management.Automation.Language.ScriptBlockExpressionAst] }
|
|
192
|
+
$isFunctionOrAliasVariable = {
|
|
193
|
+
$args[0] -is [Management.Automation.Language.VariableExpressionAst] -and
|
|
194
|
+
$args[0].VariablePath.DriveName -in 'function', 'alias'
|
|
195
|
+
}
|
|
196
|
+
$isMethodCall = { $args[0] -is [Management.Automation.Language.InvokeMemberExpressionAst] }
|
|
197
|
+
$removers = @($answer.commands | Microsoft.PowerShell.Core\\Where-Object { (& $testRemovesFunction $_) -or (& $testRunsUnreadCode $_) })
|
|
198
|
+
$functionsMayGo = $removers.Count -gt 0 -or $ast.Find($isBlockValue, $true) -or $ast.Find($isFunctionOrAliasVariable, $true) -or $ast.Find($isMethodCall, $true)
|
|
199
|
+
$statements = if ($ast.EndBlock -and -not $functionsMayGo) { $ast.EndBlock.Statements } else { @() }
|
|
200
|
+
$answer.functions = @(foreach ($statement in $statements) {
|
|
201
|
+
if ($statement -isnot [Management.Automation.Language.FunctionDefinitionAst]) { continue }
|
|
202
|
+
# An alias of its name, such as one the profile sets, comes before the function
|
|
203
|
+
$alias = Microsoft.PowerShell.Utility\\Get-Alias -Name ([Management.Automation.WildcardPattern]::Escape($statement.Name)) -ErrorAction SilentlyContinue
|
|
204
|
+
if (-not $alias) { @{ name = $statement.Name; end = $statement.Extent.EndOffset } }
|
|
205
|
+
})
|
|
206
|
+
}
|
|
207
|
+
} catch {
|
|
208
|
+
$answer.error = $_.Exception.Message
|
|
209
|
+
}
|
|
210
|
+
$writer.WriteLine((Microsoft.PowerShell.Utility\\ConvertTo-Json $answer -Compress -Depth 6))
|
|
211
|
+
}
|
|
212
|
+
`;
|
|
213
|
+
/**
|
|
214
|
+
* The helper's arguments for a PowerShell program: its script, and -Login for
|
|
215
|
+
* PowerShell 7, as getShellSpawnArgs() starts it, which off Windows runs the
|
|
216
|
+
* login shell's profile first. No -NonInteractive, which start_process
|
|
217
|
+
* doesn't pass either: a profile that prompts reads the first request
|
|
218
|
+
* instead, and that check fails.
|
|
219
|
+
*/
|
|
220
|
+
function helperArgs(program) {
|
|
221
|
+
const login = ['pwsh', 'pwsh.exe'].includes(path.basename(program).toLowerCase()) ? ['-Login'] : [];
|
|
222
|
+
return [...login, '-EncodedCommand', Buffer.from(HELPER_SCRIPT, 'utf16le').toString('base64')];
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* A command's words after --%, PowerShell's stop-parsing token. Its parser
|
|
226
|
+
* gives the rest of the line as one word, as written; PowerShell passes it to
|
|
227
|
+
* the program so, with %NAME% filled in at run time, and the program splits
|
|
228
|
+
* it into its words: so env --% sudo ls runs sudo.
|
|
229
|
+
*/
|
|
230
|
+
function withStopParsing(command) {
|
|
231
|
+
const at = command.written.indexOf('--%');
|
|
232
|
+
if (at < 1)
|
|
233
|
+
return command;
|
|
234
|
+
const split = commandLineWords(command.written[at + 1] ?? '');
|
|
235
|
+
return { ...command, words: [...command.words.slice(0, at), ...split.words], written: [...command.written.slice(0, at), ...split.written] };
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The words a Windows program makes of its command line, as the C runtime
|
|
239
|
+
* splits it: at spaces and tabs outside "…"; backslashes before a " are
|
|
240
|
+
* halved, and an odd one left makes the " a character. A word with %NAME% in
|
|
241
|
+
* it is known only at run time.
|
|
242
|
+
*/
|
|
243
|
+
function commandLineWords(text) {
|
|
244
|
+
const split = { words: [], written: [] };
|
|
245
|
+
let i = 0;
|
|
246
|
+
for (;;) {
|
|
247
|
+
while (text[i] === ' ' || text[i] === '\t')
|
|
248
|
+
i++;
|
|
249
|
+
if (i >= text.length)
|
|
250
|
+
return split;
|
|
251
|
+
const start = i;
|
|
252
|
+
let word = '';
|
|
253
|
+
let quoted = false;
|
|
254
|
+
while (i < text.length && (quoted || (text[i] !== ' ' && text[i] !== '\t'))) {
|
|
255
|
+
let backslashes = 0;
|
|
256
|
+
while (text[i + backslashes] === '\\')
|
|
257
|
+
backslashes++;
|
|
258
|
+
if (text[i + backslashes] === '"') {
|
|
259
|
+
word += '\\'.repeat(backslashes >> 1);
|
|
260
|
+
if (backslashes % 2 === 1)
|
|
261
|
+
word += '"';
|
|
262
|
+
else
|
|
263
|
+
quoted = !quoted;
|
|
264
|
+
i += backslashes + 1;
|
|
265
|
+
}
|
|
266
|
+
else {
|
|
267
|
+
word += text.slice(i, i + Math.max(backslashes, 1));
|
|
268
|
+
i += Math.max(backslashes, 1);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const written = text.slice(start, i);
|
|
272
|
+
split.words.push(/%[^%\s]+%/.test(written) ? null : word);
|
|
273
|
+
split.written.push(written);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/** One helper process for one PowerShell program, started at its first read and again after it ended */
|
|
277
|
+
export class PowerShellHelper {
|
|
278
|
+
/** args replace the helper's arguments, for a stand-in in tests */
|
|
279
|
+
constructor(program, args = helperArgs(program)) {
|
|
280
|
+
this.program = program;
|
|
281
|
+
this.args = args;
|
|
282
|
+
this.output = '';
|
|
283
|
+
this.nextId = 1;
|
|
284
|
+
this.pending = new Map();
|
|
285
|
+
/** Whether the running helper process has answered yet: until then its start counts in the time limit */
|
|
286
|
+
this.answered = false;
|
|
287
|
+
/** Made at each start and sent with every request; an answer has it, a line the profile printed doesn't */
|
|
288
|
+
this.token = '';
|
|
289
|
+
}
|
|
290
|
+
/** The running helper's process id: undefined before the first read and after the process ended */
|
|
291
|
+
get pid() {
|
|
292
|
+
return this.child?.pid;
|
|
293
|
+
}
|
|
294
|
+
/** Reads one command. It rejects when the helper doesn't answer in time, can't start, or ends first. */
|
|
295
|
+
read(command) {
|
|
296
|
+
const child = this.child ?? this.start();
|
|
297
|
+
const id = this.nextId++;
|
|
298
|
+
return new Promise((resolve, reject) => {
|
|
299
|
+
this.pending.set(id, { resolve, reject });
|
|
300
|
+
// One time limit for every request waiting: the helper answers in order, so the oldest is due first
|
|
301
|
+
this.timer ?? (this.timer = this.startTimeLimit());
|
|
302
|
+
child.stdin?.write(JSON.stringify({ id, token: this.token, command }) + '\n');
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
/** The time limit for the oldest waiting request: longer while the helper hasn't answered since it started */
|
|
306
|
+
startTimeLimit() {
|
|
307
|
+
const limitMs = this.answered ? HELPER_TIMEOUT_MS : HELPER_START_TIMEOUT_MS;
|
|
308
|
+
return setTimeout(() => this.fail(`PowerShell did not answer in ${limitMs / 1000} seconds`), limitMs);
|
|
309
|
+
}
|
|
310
|
+
/** Ends the helper process. The next read starts a new one. */
|
|
311
|
+
stop() {
|
|
312
|
+
this.fail('the PowerShell helper was stopped');
|
|
313
|
+
}
|
|
314
|
+
start() {
|
|
315
|
+
// The environment the command's shell gets, so the profile and the names are as the command will see them.
|
|
316
|
+
// PowerShell's module analysis cache is off, so the helper doesn't write it (with a home
|
|
317
|
+
// that has no AppData folder, PowerShell would write it into the working folder).
|
|
318
|
+
const env = {
|
|
319
|
+
...getShellEnvironment(),
|
|
320
|
+
PSModuleAnalysisCachePath: process.platform === 'win32' ? 'NUL' : '/dev/null'
|
|
321
|
+
};
|
|
322
|
+
// Not in the caller's working folder: the helper keeps running, and Windows can't delete a folder a process is
|
|
323
|
+
// in, though the server may leave it (a profile that looks at the folder isn't matched)
|
|
324
|
+
const child = spawn(this.program, this.args, {
|
|
325
|
+
cwd: mcpRoot, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true
|
|
326
|
+
});
|
|
327
|
+
this.child = child;
|
|
328
|
+
this.output = '';
|
|
329
|
+
this.answered = false;
|
|
330
|
+
this.token = randomBytes(16).toString('hex');
|
|
331
|
+
child.stdout?.setEncoding('utf8');
|
|
332
|
+
child.stdout?.on('data', (chunk) => this.onOutput(child, chunk));
|
|
333
|
+
// Its error text isn't needed: a failed read says what happened. Read so the pipe never fills.
|
|
334
|
+
child.stderr?.resume();
|
|
335
|
+
// Writing to a helper that just ended fails; the 'exit' event below rejects that read
|
|
336
|
+
child.stdin?.on('error', () => { });
|
|
337
|
+
child.on('error', (error) => this.ended(child, `PowerShell could not start: ${error.message}`));
|
|
338
|
+
child.on('exit', (code, signal) => this.ended(child, `PowerShell ended before it answered (${signal ?? `exit code ${code}`})`));
|
|
339
|
+
// The helper never keeps Desktop Commander running; a waiting read's timer does until it's answered
|
|
340
|
+
child.unref();
|
|
341
|
+
// The pipes are sockets: unref() keeps them from holding Desktop Commander open
|
|
342
|
+
child.stdin.unref();
|
|
343
|
+
child.stdout.unref();
|
|
344
|
+
child.stderr.unref();
|
|
345
|
+
return child;
|
|
346
|
+
}
|
|
347
|
+
onOutput(child, chunk) {
|
|
348
|
+
if (child !== this.child)
|
|
349
|
+
return;
|
|
350
|
+
this.output += chunk;
|
|
351
|
+
let newline;
|
|
352
|
+
while ((newline = this.output.indexOf('\n')) >= 0) {
|
|
353
|
+
const line = this.output.slice(0, newline).trim();
|
|
354
|
+
this.output = this.output.slice(newline + 1);
|
|
355
|
+
if (line)
|
|
356
|
+
this.onAnswer(line);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
onAnswer(line) {
|
|
360
|
+
let answer;
|
|
361
|
+
try {
|
|
362
|
+
answer = JSON.parse(line);
|
|
363
|
+
}
|
|
364
|
+
catch {
|
|
365
|
+
// Not an answer: PowerShell can print other lines; the read's time limit still applies
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
// Only the helper has this start's token: the profile ran before the helper read a request
|
|
369
|
+
const request = answer?.token === this.token ? this.pending.get(answer.id) : undefined;
|
|
370
|
+
if (!request)
|
|
371
|
+
return;
|
|
372
|
+
this.pending.delete(answer.id);
|
|
373
|
+
this.answered = true;
|
|
374
|
+
clearTimeout(this.timer);
|
|
375
|
+
this.timer = this.pending.size > 0 ? this.startTimeLimit() : undefined;
|
|
376
|
+
if (typeof answer.error === 'string') {
|
|
377
|
+
request.reject(new Error(`PowerShell could not read the command: ${answer.error}`));
|
|
378
|
+
}
|
|
379
|
+
else if (typeof answer.parseError === 'string') {
|
|
380
|
+
request.resolve({ commands: [], functions: [], parseError: answer.parseError });
|
|
381
|
+
}
|
|
382
|
+
else {
|
|
383
|
+
request.resolve({ commands: answer.commands.map(withStopParsing), functions: answer.functions });
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
/** The helper process ended or failed to start: every waiting read fails, and the next read starts a new one */
|
|
387
|
+
ended(child, reason) {
|
|
388
|
+
if (child === this.child)
|
|
389
|
+
this.fail(reason);
|
|
390
|
+
}
|
|
391
|
+
fail(reason) {
|
|
392
|
+
const child = this.child;
|
|
393
|
+
this.child = undefined;
|
|
394
|
+
clearTimeout(this.timer);
|
|
395
|
+
this.timer = undefined;
|
|
396
|
+
child?.kill();
|
|
397
|
+
const waiting = [...this.pending.values()];
|
|
398
|
+
this.pending.clear();
|
|
399
|
+
for (const request of waiting)
|
|
400
|
+
request.reject(new Error(reason));
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/** One helper per PowerShell program (Windows PowerShell and PowerShell 7 read some names differently) */
|
|
404
|
+
const helpers = new Map();
|
|
405
|
+
function parserIdentity(program) {
|
|
406
|
+
const identity = fs.realpathSync(program);
|
|
407
|
+
return process.platform === 'win32' ? identity.toLowerCase() : identity;
|
|
408
|
+
}
|
|
409
|
+
// The server's launch PATH is the operator's authority for parser endpoints. Capture it
|
|
410
|
+
// before a request can select a shell; finding a candidate must never execute it.
|
|
411
|
+
const nativeParsers = (process.platform === 'win32' ? ['powershell', 'pwsh'] : ['pwsh'])
|
|
412
|
+
.flatMap((name) => {
|
|
413
|
+
const program = resolveShellPath(name);
|
|
414
|
+
if (program === null)
|
|
415
|
+
return [];
|
|
416
|
+
// Relative PATH entries belong to the launch cwd, not the helper's mcpRoot cwd.
|
|
417
|
+
try {
|
|
418
|
+
return [{ name, program: path.resolve(program), identity: parserIdentity(program) }];
|
|
419
|
+
}
|
|
420
|
+
catch {
|
|
421
|
+
// An endpoint may disappear or become unreadable after lookup. Omitting it denies approval.
|
|
422
|
+
return [];
|
|
423
|
+
}
|
|
424
|
+
});
|
|
425
|
+
function launchParserForBareName(shell) {
|
|
426
|
+
const requestedName = shell.trim();
|
|
427
|
+
if (requestedName.includes('/') || requestedName.includes('\\'))
|
|
428
|
+
return undefined;
|
|
429
|
+
const name = process.platform === 'win32'
|
|
430
|
+
? requestedName.toLowerCase().replace(/\.exe$/, '')
|
|
431
|
+
: requestedName;
|
|
432
|
+
return nativeParsers.find((parser) => parser.name === name);
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Reads a command for a PowerShell shell ("powershell.exe", "pwsh" or a path),
|
|
436
|
+
* only when its filesystem identity matches a launch-PATH parser. Custom
|
|
437
|
+
* executables are refused before startup, rather than used to validate themselves.
|
|
438
|
+
*/
|
|
439
|
+
export function readPowerShellCommands(command, shell) {
|
|
440
|
+
const requested = resolveShellPath(shell);
|
|
441
|
+
// A bare native name can retain its launch binding when relative PATH entries
|
|
442
|
+
// stop resolving after chdir. A currently resolved different program is never replaced.
|
|
443
|
+
let identity = requested === null ? launchParserForBareName(shell)?.identity : undefined;
|
|
444
|
+
try {
|
|
445
|
+
if (requested !== null)
|
|
446
|
+
identity = parserIdentity(requested);
|
|
447
|
+
}
|
|
448
|
+
catch { /* A missing or unreadable identity cannot approve a parser. */ }
|
|
449
|
+
const native = nativeParsers.find((parser) => parser.identity === identity);
|
|
450
|
+
if (!native) {
|
|
451
|
+
throw new Error(`No trusted PowerShell parser matches "${shell}"; ` +
|
|
452
|
+
'use a PowerShell executable from the server\'s launch PATH');
|
|
453
|
+
}
|
|
454
|
+
// An alias keeps the launch flags its requested name uses for execution. A
|
|
455
|
+
// PowerShell 7 login helper must not share state with a non-login alias.
|
|
456
|
+
const args = helperArgs(shell);
|
|
457
|
+
const key = `${identity}\0${args.includes('-Login')}`;
|
|
458
|
+
let helper = helpers.get(key);
|
|
459
|
+
if (!helper) {
|
|
460
|
+
helper = new PowerShellHelper(native.program, args);
|
|
461
|
+
helpers.set(key, helper);
|
|
462
|
+
}
|
|
463
|
+
return helper.read(command);
|
|
464
|
+
}
|
|
465
|
+
/** The process ids of the helpers running now, for tests */
|
|
466
|
+
export function runningPowerShellHelpers() {
|
|
467
|
+
return [...helpers.values()].map((helper) => helper.pid).filter((pid) => pid !== undefined);
|
|
468
|
+
}
|
|
@@ -24,10 +24,10 @@ import { logger } from './logger.js';
|
|
|
24
24
|
* Limit: a process whose parent exited before a walk has been reparented (to
|
|
25
25
|
* init or a subreaper) and can no longer be found through its parent.
|
|
26
26
|
*
|
|
27
|
-
* Every path that ends a command DC runs for the client (force_terminate
|
|
28
|
-
* start_process session, the node:local timeout) goes
|
|
29
|
-
* kill_process
|
|
30
|
-
* period and SIGKILL (terminatePid).
|
|
27
|
+
* Every path that ends a command DC runs for the client (force_terminate or
|
|
28
|
+
* kill_process on a start_process session, the node:local timeout) goes
|
|
29
|
+
* through terminateProcessTree. kill_process on any other PID ends just that
|
|
30
|
+
* PID, with the same SIGTERM, grace period and SIGKILL (terminatePid).
|
|
31
31
|
*/
|
|
32
32
|
/** How long a process tree gets to exit after SIGTERM before SIGKILL (macOS/Linux) */
|
|
33
33
|
const TERMINATE_GRACE_MS = 1000;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type ArgumentInspection } from './command-reading.js';
|
|
2
|
+
type FileWord = string | null;
|
|
3
|
+
interface FileWordSource extends ArgumentInspection {
|
|
4
|
+
written?: readonly string[];
|
|
5
|
+
}
|
|
6
|
+
/** File arguments are found before command/script arguments can be mistaken for more host options. */
|
|
7
|
+
export declare function shellScriptFiles(program: string, args: FileWord[], source?: FileWordSource): FileWord[];
|
|
8
|
+
export {};
|