@wonderwhy-er/desktop-commander 0.3.2-alpha.1 → 0.3.2-alpha.3
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 +200 -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/file-preview/preview-runtime.js +145 -138
- package/dist/utils/brace-expansion.d.ts +25 -0
- package/dist/utils/brace-expansion.js +171 -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 +322 -0
- package/dist/utils/command-reading.d.ts +78 -0
- package/dist/utils/command-reading.js +7 -0
- package/dist/utils/command-wrappers.d.ts +45 -0
- package/dist/utils/command-wrappers.js +941 -0
- package/dist/utils/inline-shells.d.ts +64 -0
- package/dist/utils/inline-shells.js +290 -0
- package/dist/utils/posix-commands.d.ts +3 -0
- package/dist/utils/posix-commands.js +201 -0
- package/dist/utils/powershell-commands.d.ts +60 -0
- package/dist/utils/powershell-commands.js +420 -0
- package/dist/utils/process-tree.js +4 -4
- package/dist/utils/shell-script-files.d.ts +4 -0
- package/dist/utils/shell-script-files.js +121 -0
- package/dist/utils/shell.d.ts +36 -0
- package/dist/utils/shell.js +69 -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/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,420 @@
|
|
|
1
|
+
import { spawn } from 'child_process';
|
|
2
|
+
import { randomBytes } from 'crypto';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { fileURLToPath } from 'url';
|
|
5
|
+
import { getShellEnvironment, resolveProgramPath } from './shell.js';
|
|
6
|
+
/**
|
|
7
|
+
* The command check's reader for PowerShell. No JavaScript parser reads
|
|
8
|
+
* PowerShell correctly (here-strings, @{ } tables, & $var), so a helper
|
|
9
|
+
* PowerShell process reads each command with PowerShell's own parser. It
|
|
10
|
+
* starts at the first PowerShell check, so nothing runs for users who never
|
|
11
|
+
* run PowerShell commands, and it is kept running: a check then takes a few
|
|
12
|
+
* milliseconds instead of PowerShell's start (about a second for Windows
|
|
13
|
+
* PowerShell). It is not a terminal session, so list_sessions never shows it.
|
|
14
|
+
* It starts as the PowerShell a command runs in starts: with the user's
|
|
15
|
+
* profile (start_process starts it without -NoProfile), without
|
|
16
|
+
* -NonInteractive, with -Login for PowerShell 7, and with the commands'
|
|
17
|
+
* environment. So a profile sets the same aliases for both. Only its working
|
|
18
|
+
* folder is its own (see start()).
|
|
19
|
+
*/
|
|
20
|
+
/** How long a check waits for a running helper's answer. A helper that doesn't answer is stopped, and the check fails. */
|
|
21
|
+
export const HELPER_TIMEOUT_MS = 5000;
|
|
22
|
+
/**
|
|
23
|
+
* How long the first check waits after a helper starts, PowerShell's start
|
|
24
|
+
* and the user's profile included: about a second for Windows PowerShell,
|
|
25
|
+
* longer on a busy machine or with a slow profile
|
|
26
|
+
*/
|
|
27
|
+
export const HELPER_START_TIMEOUT_MS = 15000;
|
|
28
|
+
/** The folder Desktop Commander is installed in, where its own node:local process runs too */
|
|
29
|
+
const mcpRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
30
|
+
/**
|
|
31
|
+
* The helper, run with -EncodedCommand. It reads one JSON request per line
|
|
32
|
+
* ({ id, token, command }) and writes one JSON answer per line. It only
|
|
33
|
+
* parses the command and looks names up with Get-Command; it never runs the
|
|
34
|
+
* command.
|
|
35
|
+
* Module autoloading is off so that looking up a name never imports a module.
|
|
36
|
+
* Each CommandAst is a command, also inside script blocks and functions. Its
|
|
37
|
+
* name is what it means in this PowerShell: an alias gives its target, a
|
|
38
|
+
* program or script its file name as found (net.exe). A name Get-Command
|
|
39
|
+
* doesn't know stays as written. A name from a variable or expression
|
|
40
|
+
* (& $tool) is known only at run time. Each word's text is its value, or
|
|
41
|
+
* where that is known only at run time the word as written, a "..." string
|
|
42
|
+
* without its quotes.
|
|
43
|
+
* For a command that means Start-Process, filePaths are the programs it may
|
|
44
|
+
* start: the word its FilePath parameter takes as this PowerShell binds the
|
|
45
|
+
* command (with the Management module, imported the first time), and a
|
|
46
|
+
* splatted @params, which may hold FilePath. The binder can't see into
|
|
47
|
+
* @params and doesn't know -- (the end of the parameters), so the command is
|
|
48
|
+
* also bound with those words left out.
|
|
49
|
+
* The functions are the definitions among the script's own statements, with
|
|
50
|
+
* the offset where each ends. There are none when the text has a { } script
|
|
51
|
+
* block written as a value, which may run where the functions don't exist
|
|
52
|
+
* (Start-Job runs it in another process), or something that may remove a
|
|
53
|
+
* function or hide it behind an alias, which comes before a function: a
|
|
54
|
+
* $function: or $alias: variable ($function:net = $null), Set-Alias, New-Alias
|
|
55
|
+
* or Import-Alias, a word naming the function or alias drive or provider
|
|
56
|
+
* (Remove-Item function:net, New-Item alias:net, New-PSDrive -PSProvider
|
|
57
|
+
* Function), or an item or content cmdlet whose path is known only at run
|
|
58
|
+
* time or comes from the pipeline ('function:net' | Remove-Item; Set-Content
|
|
59
|
+
* gives a function a new body). Nor when it runs code the helper doesn't
|
|
60
|
+
* read: Invoke-Expression, Import-Module, Add-Type, a script file, a name
|
|
61
|
+
* known only at run time, a method call ([scriptblock]::Create(...).Invoke())
|
|
62
|
+
* or ForEach-Object calling one. Nor is a function the session has an alias
|
|
63
|
+
* of, such as one the user's profile sets.
|
|
64
|
+
* Offsets are .NET string indexes, the same as JavaScript's.
|
|
65
|
+
* The profile runs first, and may print anything and define functions and
|
|
66
|
+
* aliases with any name. So the helper writes an empty line before its first
|
|
67
|
+
* answer (text the profile printed without a newline ends there), puts the
|
|
68
|
+
* request's token in each answer (the reader takes no other line for one),
|
|
69
|
+
* calls each cmdlet by its module's name, which no function or alias
|
|
70
|
+
* replaces, and keeps its own functions in variables ($getMeaning), which no
|
|
71
|
+
* alias replaces either.
|
|
72
|
+
*/
|
|
73
|
+
const HELPER_SCRIPT = `
|
|
74
|
+
$ErrorActionPreference = 'Stop'
|
|
75
|
+
$ProgressPreference = 'SilentlyContinue'
|
|
76
|
+
Microsoft.PowerShell.Core\\Import-Module Microsoft.PowerShell.Utility
|
|
77
|
+
$PSModuleAutoLoadingPreference = 'None'
|
|
78
|
+
$utf8 = Microsoft.PowerShell.Utility\\New-Object System.Text.UTF8Encoding $false
|
|
79
|
+
$reader = Microsoft.PowerShell.Utility\\New-Object System.IO.StreamReader ([Console]::OpenStandardInput()), $utf8
|
|
80
|
+
$writer = Microsoft.PowerShell.Utility\\New-Object System.IO.StreamWriter ([Console]::OpenStandardOutput()), $utf8
|
|
81
|
+
$writer.AutoFlush = $true
|
|
82
|
+
$writer.WriteLine()
|
|
83
|
+
# 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
|
|
84
|
+
$getMeaning = {
|
|
85
|
+
param([string]$name)
|
|
86
|
+
$found = @(Microsoft.PowerShell.Core\\Get-Command -Name ([Management.Automation.WildcardPattern]::Escape($name)) -ErrorAction SilentlyContinue)
|
|
87
|
+
if ($found.Count -eq 0) { return $name }
|
|
88
|
+
if ($found[0].CommandType -eq 'Alias') { return $found[0].Definition }
|
|
89
|
+
return $found[0].Name
|
|
90
|
+
}
|
|
91
|
+
$getWordValue = {
|
|
92
|
+
param($element)
|
|
93
|
+
if ($element -is [Management.Automation.Language.StringConstantExpressionAst]) { return $element.Value }
|
|
94
|
+
if ($element -is [Management.Automation.Language.CommandParameterAst]) { return $element.Extent.Text }
|
|
95
|
+
if ($element -is [Management.Automation.Language.ConstantExpressionAst]) { return $element.Extent.Text }
|
|
96
|
+
return $null
|
|
97
|
+
}
|
|
98
|
+
# The word's value, else as written; a "..." string's value keeps its variables as written ("net user $name")
|
|
99
|
+
$getWordText = {
|
|
100
|
+
param($element)
|
|
101
|
+
$value = & $getWordValue $element
|
|
102
|
+
if ($null -ne $value) { return $value }
|
|
103
|
+
if ($element -is [Management.Automation.Language.ExpandableStringExpressionAst]) { return $element.Value }
|
|
104
|
+
return $element.Extent.Text
|
|
105
|
+
}
|
|
106
|
+
$managementImported = $false
|
|
107
|
+
$getFilePaths = {
|
|
108
|
+
param($command)
|
|
109
|
+
if (-not $script:managementImported) {
|
|
110
|
+
Microsoft.PowerShell.Core\\Import-Module Microsoft.PowerShell.Management
|
|
111
|
+
$script:managementImported = $true
|
|
112
|
+
}
|
|
113
|
+
$programs = @()
|
|
114
|
+
$text = $command.Extent.Text
|
|
115
|
+
foreach ($element in $command.CommandElements) {
|
|
116
|
+
$splatted = $element -is [Management.Automation.Language.VariableExpressionAst] -and $element.Splatted
|
|
117
|
+
if ($splatted) { $programs += @{ word = $null; written = $element.Extent.Text } }
|
|
118
|
+
if ($splatted -or $element.Extent.Text -eq '--') {
|
|
119
|
+
$at = $element.Extent.StartOffset - $command.Extent.StartOffset
|
|
120
|
+
$text = $text.Remove($at, $element.Extent.Text.Length).Insert($at, ' ' * $element.Extent.Text.Length)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
$bindings = @($command)
|
|
124
|
+
if ($text -ne $command.Extent.Text) {
|
|
125
|
+
$bindings += [Management.Automation.Language.Parser]::ParseInput($text, [ref]$null, [ref]$null).Find({ $args[0] -is [Management.Automation.Language.CommandAst] }, $true)
|
|
126
|
+
}
|
|
127
|
+
foreach ($binding in $bindings) {
|
|
128
|
+
# A command PowerShell can't bind is one it refuses to run
|
|
129
|
+
try { $filePath = [Management.Automation.Language.StaticParameterBinder]::BindCommand($binding, $true).BoundParameters['FilePath'] } catch { continue }
|
|
130
|
+
if ($null -eq $filePath -or ($filePath.Value -is [Management.Automation.Language.VariableExpressionAst] -and $filePath.Value.Splatted)) { continue }
|
|
131
|
+
$asWritten = $filePath.Value.Extent.Text
|
|
132
|
+
if (-not ($programs | Microsoft.PowerShell.Core\\Where-Object { $_.written -eq $asWritten })) { $programs += @{ word = (& $getWordValue $filePath.Value); written = $asWritten } }
|
|
133
|
+
}
|
|
134
|
+
return $programs
|
|
135
|
+
}
|
|
136
|
+
$testRemovesFunction = {
|
|
137
|
+
param($found)
|
|
138
|
+
if ($found.name -in 'Set-Alias', 'New-Alias', 'Import-Alias') { return $true }
|
|
139
|
+
$pathAtRunTime = $false
|
|
140
|
+
$knownPaths = 0
|
|
141
|
+
for ($i = 1; $i -lt $found.words.Count; $i++) {
|
|
142
|
+
$word = $found.words[$i]
|
|
143
|
+
if ($null -eq $word) { $pathAtRunTime = $true }
|
|
144
|
+
elseif ($word -match '\\b(function|alias)\\b') { return $true }
|
|
145
|
+
elseif (-not $word.StartsWith('-')) { $knownPaths++ }
|
|
146
|
+
}
|
|
147
|
+
return ($found.name -like '*-Item' -or $found.name -like '*-Content') -and ($pathAtRunTime -or $knownPaths -eq 0)
|
|
148
|
+
}
|
|
149
|
+
$testRunsUnreadCode = {
|
|
150
|
+
param($found)
|
|
151
|
+
if ($found.nameAtRunTime -or $found.name -in 'Invoke-Expression', 'Import-Module', 'Add-Type') { return $true }
|
|
152
|
+
# ForEach-Object InvokeScript 'text' calls each object's method
|
|
153
|
+
if ($found.name -eq 'ForEach-Object') {
|
|
154
|
+
$values = 0
|
|
155
|
+
for ($i = 1; $i -lt $found.words.Count; $i++) { if (-not "$($found.words[$i])".StartsWith('-')) { $values++ } }
|
|
156
|
+
if ($values -gt 1) { return $true }
|
|
157
|
+
}
|
|
158
|
+
# A script file: .ps1 or .psm1, or a path without an extension (. ./lib runs lib.ps1)
|
|
159
|
+
$leaf = $found.name.Substring($found.name.LastIndexOfAny([char[]]'\\/') + 1)
|
|
160
|
+
return $leaf -like '*.ps1' -or $leaf -like '*.psm1' -or ($leaf -ne $found.name -and $leaf -notlike '*.*')
|
|
161
|
+
}
|
|
162
|
+
while ($true) {
|
|
163
|
+
$line = $reader.ReadLine()
|
|
164
|
+
if ($null -eq $line) { break }
|
|
165
|
+
$request = Microsoft.PowerShell.Utility\\ConvertFrom-Json $line
|
|
166
|
+
$answer = @{ id = $request.id; token = $request.token }
|
|
167
|
+
try {
|
|
168
|
+
$tokens = $null
|
|
169
|
+
$errors = $null
|
|
170
|
+
$ast = [Management.Automation.Language.Parser]::ParseInput([string]$request.command, [ref]$tokens, [ref]$errors)
|
|
171
|
+
if ($errors.Count -gt 0) {
|
|
172
|
+
$answer.parseError = $errors[0].Message
|
|
173
|
+
} else {
|
|
174
|
+
$answer.commands = @(foreach ($command in $ast.FindAll({ $args[0] -is [Management.Automation.Language.CommandAst] }, $true)) {
|
|
175
|
+
$first = $command.CommandElements[0]
|
|
176
|
+
# & { ... } runs a script block, not a program: the commands inside it are found on their own
|
|
177
|
+
if ($first -is [Management.Automation.Language.ScriptBlockExpressionAst]) { continue }
|
|
178
|
+
$words = @(foreach ($element in $command.CommandElements) { ,(& $getWordValue $element) })
|
|
179
|
+
$written = @(foreach ($element in $command.CommandElements) { $element.Extent.Text })
|
|
180
|
+
$wordTexts = @(foreach ($element in $command.CommandElements) { & $getWordText $element })
|
|
181
|
+
$name = $command.GetCommandName()
|
|
182
|
+
if ($null -eq $name) {
|
|
183
|
+
@{ name = $first.Extent.Text; words = $words; written = $written; wordTexts = $wordTexts; start = $command.Extent.StartOffset; nameAtRunTime = $true }
|
|
184
|
+
} else {
|
|
185
|
+
$found = @{ name = (& $getMeaning $name); words = $words; written = $written; wordTexts = $wordTexts; start = $command.Extent.StartOffset; nameAtRunTime = $false }
|
|
186
|
+
if ($found.name -eq 'Start-Process') { $found.filePaths = @(& $getFilePaths $command) }
|
|
187
|
+
$found
|
|
188
|
+
}
|
|
189
|
+
})
|
|
190
|
+
$isBlockValue = { $args[0] -is [Management.Automation.Language.ScriptBlockExpressionAst] }
|
|
191
|
+
$isFunctionOrAliasVariable = {
|
|
192
|
+
$args[0] -is [Management.Automation.Language.VariableExpressionAst] -and
|
|
193
|
+
$args[0].VariablePath.DriveName -in 'function', 'alias'
|
|
194
|
+
}
|
|
195
|
+
$isMethodCall = { $args[0] -is [Management.Automation.Language.InvokeMemberExpressionAst] }
|
|
196
|
+
$removers = @($answer.commands | Microsoft.PowerShell.Core\\Where-Object { (& $testRemovesFunction $_) -or (& $testRunsUnreadCode $_) })
|
|
197
|
+
$functionsMayGo = $removers.Count -gt 0 -or $ast.Find($isBlockValue, $true) -or $ast.Find($isFunctionOrAliasVariable, $true) -or $ast.Find($isMethodCall, $true)
|
|
198
|
+
$statements = if ($ast.EndBlock -and -not $functionsMayGo) { $ast.EndBlock.Statements } else { @() }
|
|
199
|
+
$answer.functions = @(foreach ($statement in $statements) {
|
|
200
|
+
if ($statement -isnot [Management.Automation.Language.FunctionDefinitionAst]) { continue }
|
|
201
|
+
# An alias of its name, such as one the profile sets, comes before the function
|
|
202
|
+
$alias = Microsoft.PowerShell.Utility\\Get-Alias -Name ([Management.Automation.WildcardPattern]::Escape($statement.Name)) -ErrorAction SilentlyContinue
|
|
203
|
+
if (-not $alias) { @{ name = $statement.Name; end = $statement.Extent.EndOffset } }
|
|
204
|
+
})
|
|
205
|
+
}
|
|
206
|
+
} catch {
|
|
207
|
+
$answer.error = $_.Exception.Message
|
|
208
|
+
}
|
|
209
|
+
$writer.WriteLine((Microsoft.PowerShell.Utility\\ConvertTo-Json $answer -Compress -Depth 6))
|
|
210
|
+
}
|
|
211
|
+
`;
|
|
212
|
+
/**
|
|
213
|
+
* The helper's arguments for a PowerShell program: its script, and -Login for
|
|
214
|
+
* PowerShell 7, as getShellSpawnArgs() starts it, which off Windows runs the
|
|
215
|
+
* login shell's profile first. No -NonInteractive, which start_process
|
|
216
|
+
* doesn't pass either: a profile that prompts reads the first request
|
|
217
|
+
* instead, and that check fails.
|
|
218
|
+
*/
|
|
219
|
+
function helperArgs(program) {
|
|
220
|
+
const login = ['pwsh', 'pwsh.exe'].includes(path.basename(program).toLowerCase()) ? ['-Login'] : [];
|
|
221
|
+
return [...login, '-EncodedCommand', Buffer.from(HELPER_SCRIPT, 'utf16le').toString('base64')];
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* A command's words after --%, PowerShell's stop-parsing token. Its parser
|
|
225
|
+
* gives the rest of the line as one word, as written; PowerShell passes it to
|
|
226
|
+
* the program so, with %NAME% filled in at run time, and the program splits
|
|
227
|
+
* it into its words: so env --% sudo ls runs sudo.
|
|
228
|
+
*/
|
|
229
|
+
function withStopParsing(command) {
|
|
230
|
+
const at = command.written.indexOf('--%');
|
|
231
|
+
if (at < 1)
|
|
232
|
+
return command;
|
|
233
|
+
const split = commandLineWords(command.written[at + 1] ?? '');
|
|
234
|
+
return { ...command, words: [...command.words.slice(0, at), ...split.words], written: [...command.written.slice(0, at), ...split.written] };
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* The words a Windows program makes of its command line, as the C runtime
|
|
238
|
+
* splits it: at spaces and tabs outside "…"; backslashes before a " are
|
|
239
|
+
* halved, and an odd one left makes the " a character. A word with %NAME% in
|
|
240
|
+
* it is known only at run time.
|
|
241
|
+
*/
|
|
242
|
+
function commandLineWords(text) {
|
|
243
|
+
const split = { words: [], written: [] };
|
|
244
|
+
let i = 0;
|
|
245
|
+
for (;;) {
|
|
246
|
+
while (text[i] === ' ' || text[i] === '\t')
|
|
247
|
+
i++;
|
|
248
|
+
if (i >= text.length)
|
|
249
|
+
return split;
|
|
250
|
+
const start = i;
|
|
251
|
+
let word = '';
|
|
252
|
+
let quoted = false;
|
|
253
|
+
while (i < text.length && (quoted || (text[i] !== ' ' && text[i] !== '\t'))) {
|
|
254
|
+
let backslashes = 0;
|
|
255
|
+
while (text[i + backslashes] === '\\')
|
|
256
|
+
backslashes++;
|
|
257
|
+
if (text[i + backslashes] === '"') {
|
|
258
|
+
word += '\\'.repeat(backslashes >> 1);
|
|
259
|
+
if (backslashes % 2 === 1)
|
|
260
|
+
word += '"';
|
|
261
|
+
else
|
|
262
|
+
quoted = !quoted;
|
|
263
|
+
i += backslashes + 1;
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
word += text.slice(i, i + Math.max(backslashes, 1));
|
|
267
|
+
i += Math.max(backslashes, 1);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const written = text.slice(start, i);
|
|
271
|
+
split.words.push(/%[^%\s]+%/.test(written) ? null : word);
|
|
272
|
+
split.written.push(written);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/** One helper process for one PowerShell program, started at its first read and again after it ended */
|
|
276
|
+
export class PowerShellHelper {
|
|
277
|
+
/** args replace the helper's arguments, for a stand-in in tests */
|
|
278
|
+
constructor(program, args = helperArgs(program)) {
|
|
279
|
+
this.program = program;
|
|
280
|
+
this.args = args;
|
|
281
|
+
this.output = '';
|
|
282
|
+
this.nextId = 1;
|
|
283
|
+
this.pending = new Map();
|
|
284
|
+
/** Whether the running helper process has answered yet: until then its start counts in the time limit */
|
|
285
|
+
this.answered = false;
|
|
286
|
+
/** Made at each start and sent with every request; an answer has it, a line the profile printed doesn't */
|
|
287
|
+
this.token = '';
|
|
288
|
+
}
|
|
289
|
+
/** The running helper's process id: undefined before the first read and after the process ended */
|
|
290
|
+
get pid() {
|
|
291
|
+
return this.child?.pid;
|
|
292
|
+
}
|
|
293
|
+
/** Reads one command. It rejects when the helper doesn't answer in time, can't start, or ends first. */
|
|
294
|
+
read(command) {
|
|
295
|
+
const child = this.child ?? this.start();
|
|
296
|
+
const id = this.nextId++;
|
|
297
|
+
return new Promise((resolve, reject) => {
|
|
298
|
+
this.pending.set(id, { resolve, reject });
|
|
299
|
+
// One time limit for every request waiting: the helper answers in order, so the oldest is due first
|
|
300
|
+
this.timer ?? (this.timer = this.startTimeLimit());
|
|
301
|
+
child.stdin?.write(JSON.stringify({ id, token: this.token, command }) + '\n');
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
/** The time limit for the oldest waiting request: longer while the helper hasn't answered since it started */
|
|
305
|
+
startTimeLimit() {
|
|
306
|
+
const limitMs = this.answered ? HELPER_TIMEOUT_MS : HELPER_START_TIMEOUT_MS;
|
|
307
|
+
return setTimeout(() => this.fail(`PowerShell did not answer in ${limitMs / 1000} seconds`), limitMs);
|
|
308
|
+
}
|
|
309
|
+
/** Ends the helper process. The next read starts a new one. */
|
|
310
|
+
stop() {
|
|
311
|
+
this.fail('the PowerShell helper was stopped');
|
|
312
|
+
}
|
|
313
|
+
start() {
|
|
314
|
+
// The environment the command's shell gets, so the profile and the names are as the command will see them.
|
|
315
|
+
// PowerShell's module analysis cache is off, so the helper doesn't write it (with a home
|
|
316
|
+
// that has no AppData folder, PowerShell would write it into the working folder).
|
|
317
|
+
const env = {
|
|
318
|
+
...getShellEnvironment(),
|
|
319
|
+
PSModuleAnalysisCachePath: process.platform === 'win32' ? 'NUL' : '/dev/null'
|
|
320
|
+
};
|
|
321
|
+
// Not in the caller's working folder: the helper keeps running, and Windows can't delete a folder a process is
|
|
322
|
+
// in, though the server may leave it (a profile that looks at the folder isn't matched)
|
|
323
|
+
const child = spawn(this.program, this.args, {
|
|
324
|
+
cwd: mcpRoot, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true
|
|
325
|
+
});
|
|
326
|
+
this.child = child;
|
|
327
|
+
this.output = '';
|
|
328
|
+
this.answered = false;
|
|
329
|
+
this.token = randomBytes(16).toString('hex');
|
|
330
|
+
child.stdout?.setEncoding('utf8');
|
|
331
|
+
child.stdout?.on('data', (chunk) => this.onOutput(child, chunk));
|
|
332
|
+
// Its error text isn't needed: a failed read says what happened. Read so the pipe never fills.
|
|
333
|
+
child.stderr?.resume();
|
|
334
|
+
// Writing to a helper that just ended fails; the 'exit' event below rejects that read
|
|
335
|
+
child.stdin?.on('error', () => { });
|
|
336
|
+
child.on('error', (error) => this.ended(child, `PowerShell could not start: ${error.message}`));
|
|
337
|
+
child.on('exit', (code, signal) => this.ended(child, `PowerShell ended before it answered (${signal ?? `exit code ${code}`})`));
|
|
338
|
+
// The helper never keeps Desktop Commander running; a waiting read's timer does until it's answered
|
|
339
|
+
child.unref();
|
|
340
|
+
// The pipes are sockets: unref() keeps them from holding Desktop Commander open
|
|
341
|
+
child.stdin.unref();
|
|
342
|
+
child.stdout.unref();
|
|
343
|
+
child.stderr.unref();
|
|
344
|
+
return child;
|
|
345
|
+
}
|
|
346
|
+
onOutput(child, chunk) {
|
|
347
|
+
if (child !== this.child)
|
|
348
|
+
return;
|
|
349
|
+
this.output += chunk;
|
|
350
|
+
let newline;
|
|
351
|
+
while ((newline = this.output.indexOf('\n')) >= 0) {
|
|
352
|
+
const line = this.output.slice(0, newline).trim();
|
|
353
|
+
this.output = this.output.slice(newline + 1);
|
|
354
|
+
if (line)
|
|
355
|
+
this.onAnswer(line);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
onAnswer(line) {
|
|
359
|
+
let answer;
|
|
360
|
+
try {
|
|
361
|
+
answer = JSON.parse(line);
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
// Not an answer: PowerShell can print other lines; the read's time limit still applies
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
// Only the helper has this start's token: the profile ran before the helper read a request
|
|
368
|
+
const request = answer?.token === this.token ? this.pending.get(answer.id) : undefined;
|
|
369
|
+
if (!request)
|
|
370
|
+
return;
|
|
371
|
+
this.pending.delete(answer.id);
|
|
372
|
+
this.answered = true;
|
|
373
|
+
clearTimeout(this.timer);
|
|
374
|
+
this.timer = this.pending.size > 0 ? this.startTimeLimit() : undefined;
|
|
375
|
+
if (typeof answer.error === 'string') {
|
|
376
|
+
request.reject(new Error(`PowerShell could not read the command: ${answer.error}`));
|
|
377
|
+
}
|
|
378
|
+
else if (typeof answer.parseError === 'string') {
|
|
379
|
+
request.resolve({ commands: [], functions: [], parseError: answer.parseError });
|
|
380
|
+
}
|
|
381
|
+
else {
|
|
382
|
+
request.resolve({ commands: answer.commands.map(withStopParsing), functions: answer.functions });
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/** The helper process ended or failed to start: every waiting read fails, and the next read starts a new one */
|
|
386
|
+
ended(child, reason) {
|
|
387
|
+
if (child === this.child)
|
|
388
|
+
this.fail(reason);
|
|
389
|
+
}
|
|
390
|
+
fail(reason) {
|
|
391
|
+
const child = this.child;
|
|
392
|
+
this.child = undefined;
|
|
393
|
+
clearTimeout(this.timer);
|
|
394
|
+
this.timer = undefined;
|
|
395
|
+
child?.kill();
|
|
396
|
+
const waiting = [...this.pending.values()];
|
|
397
|
+
this.pending.clear();
|
|
398
|
+
for (const request of waiting)
|
|
399
|
+
request.reject(new Error(reason));
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
/** One helper per PowerShell program (Windows PowerShell and PowerShell 7 read some names differently) */
|
|
403
|
+
const helpers = new Map();
|
|
404
|
+
/**
|
|
405
|
+
* Reads a command for a PowerShell shell ("powershell.exe", "pwsh" or a path),
|
|
406
|
+
* with the same program as the helper. checkCommand() has made sure it's there.
|
|
407
|
+
*/
|
|
408
|
+
export function readPowerShellCommands(command, shell) {
|
|
409
|
+
const program = path.resolve(resolveProgramPath(shell));
|
|
410
|
+
let helper = helpers.get(program);
|
|
411
|
+
if (!helper) {
|
|
412
|
+
helper = new PowerShellHelper(program);
|
|
413
|
+
helpers.set(program, helper);
|
|
414
|
+
}
|
|
415
|
+
return helper.read(command);
|
|
416
|
+
}
|
|
417
|
+
/** The process ids of the helpers running now, for tests */
|
|
418
|
+
export function runningPowerShellHelpers() {
|
|
419
|
+
return [...helpers.values()].map((helper) => helper.pid).filter((pid) => pid !== undefined);
|
|
420
|
+
}
|
|
@@ -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,121 @@
|
|
|
1
|
+
import { getShellType, POSIX_SHELLS } from './shell.js';
|
|
2
|
+
const POSIX_VALUE_OPTIONS = new Set(['-o', '+o', '-O', '+O', '--rcfile', '--init-file']);
|
|
3
|
+
const BASH_STARTUP_OPTIONS = new Set(['--rcfile', '--init-file']);
|
|
4
|
+
// Minimum spellings and aliases follow the PowerShell host's option precedence.
|
|
5
|
+
const POWERSHELL_VALUE_OPTIONS = [
|
|
6
|
+
['-executionpolicy', '-ex'], ['-inputformat', '-inp'], ['-outputformat', '-o'],
|
|
7
|
+
['-configurationname', '-config'], ['-configurationfile', '-configurationfile'],
|
|
8
|
+
['-custompipename', '-cus'], ['-workingdirectory', '-wo'], ['-settingsfile', '-settings'],
|
|
9
|
+
['-windowstyle', '-w'], ['-encodedarguments', '-encodeda'],
|
|
10
|
+
];
|
|
11
|
+
const POWERSHELL_VALUE_ALIASES = new Set(['-ep', '-if', '-of', '-wd', '-ea']);
|
|
12
|
+
/** Option values must not be mistaken for the shell's script filename. */
|
|
13
|
+
function posixValueOption(arg) {
|
|
14
|
+
return POSIX_VALUE_OPTIONS.has(arg) || /^[-+][a-zA-Z]*[oO]/.test(arg);
|
|
15
|
+
}
|
|
16
|
+
/** Command/stdin mode owns later words, so only a positional file before that boundary is a script. */
|
|
17
|
+
function posixScriptFile(args) {
|
|
18
|
+
for (let i = 0; i < args.length; i++) {
|
|
19
|
+
const arg = args[i];
|
|
20
|
+
if (arg === null)
|
|
21
|
+
return arg;
|
|
22
|
+
if (/^-[a-zA-Z]*[cs]/.test(arg) || arg === '--command')
|
|
23
|
+
return undefined;
|
|
24
|
+
if (posixValueOption(arg)) {
|
|
25
|
+
i++;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (!arg.startsWith('-') && !arg.startsWith('+'))
|
|
29
|
+
return arg;
|
|
30
|
+
}
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
/** A custom rcfile needs a note only when the explicit host options cause Bash to read it. */
|
|
34
|
+
function bashStartupFile(args) {
|
|
35
|
+
let file;
|
|
36
|
+
let interactive = false;
|
|
37
|
+
let login = false;
|
|
38
|
+
let noRc = false;
|
|
39
|
+
let posix = false;
|
|
40
|
+
for (let i = 0; i < args.length; i++) {
|
|
41
|
+
const arg = args[i];
|
|
42
|
+
if (arg === null || arg === '--')
|
|
43
|
+
break;
|
|
44
|
+
if (BASH_STARTUP_OPTIONS.has(arg)) {
|
|
45
|
+
file = args[++i];
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (arg === '--norc')
|
|
49
|
+
noRc = true;
|
|
50
|
+
if (arg === '--login')
|
|
51
|
+
login = true;
|
|
52
|
+
if (arg === '--posix')
|
|
53
|
+
posix = true;
|
|
54
|
+
if (/^[-+][a-zA-Z]+$/.test(arg)) {
|
|
55
|
+
if (arg.includes('i'))
|
|
56
|
+
interactive = arg[0] === '-';
|
|
57
|
+
if (arg.includes('l'))
|
|
58
|
+
login = arg[0] === '-';
|
|
59
|
+
}
|
|
60
|
+
if (posixValueOption(arg)) {
|
|
61
|
+
if (args[++i] === 'posix' && /^[-+][a-zA-Z]*o/.test(arg))
|
|
62
|
+
posix = arg[0] === '-';
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (!arg.startsWith('-') && !arg.startsWith('+'))
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
// Bash reads the custom rcfile only in interactive, non-login Bash mode.
|
|
69
|
+
if (!interactive || login || noRc || posix || file === '')
|
|
70
|
+
return undefined;
|
|
71
|
+
return file;
|
|
72
|
+
}
|
|
73
|
+
/** Host mode determines whether a later word is command text, a version value or a script path. */
|
|
74
|
+
function powershellScriptFile(program, args) {
|
|
75
|
+
for (let i = 0; i < args.length; i++) {
|
|
76
|
+
const arg = args[i];
|
|
77
|
+
if (arg === null)
|
|
78
|
+
return arg;
|
|
79
|
+
const option = arg.toLowerCase();
|
|
80
|
+
if (arg === '-' || arg === '')
|
|
81
|
+
return undefined;
|
|
82
|
+
if ('-command'.startsWith(option) || ['-commandwithargs', '-cwa', '-ec'].includes(option)
|
|
83
|
+
|| '-encodedcommand'.startsWith(option))
|
|
84
|
+
return undefined;
|
|
85
|
+
if (['-f', '-fi', '-fil', '-file'].includes(option)) {
|
|
86
|
+
return args[i + 1] === '-' ? undefined : args[i + 1];
|
|
87
|
+
}
|
|
88
|
+
if ('-version'.startsWith(option)) {
|
|
89
|
+
if (program === 'pwsh' || program === 'pwsh.exe')
|
|
90
|
+
return undefined;
|
|
91
|
+
i++;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (POWERSHELL_VALUE_ALIASES.has(option) || POWERSHELL_VALUE_OPTIONS.some(([name, minimum]) => option.length >= minimum.length && name.startsWith(option))) {
|
|
95
|
+
i++;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (!arg.startsWith('-'))
|
|
99
|
+
return arg;
|
|
100
|
+
}
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
/** File arguments are found before command/script arguments can be mistaken for more host options. */
|
|
104
|
+
export function shellScriptFiles(program, args) {
|
|
105
|
+
if (POSIX_SHELLS.has(program)) {
|
|
106
|
+
const files = [];
|
|
107
|
+
const startup = program === 'bash' ? bashStartupFile(args) : undefined;
|
|
108
|
+
const script = posixScriptFile(args);
|
|
109
|
+
if (startup !== undefined)
|
|
110
|
+
files.push(startup);
|
|
111
|
+
if (script !== undefined)
|
|
112
|
+
files.push(script);
|
|
113
|
+
return files;
|
|
114
|
+
}
|
|
115
|
+
if (getShellType(program) === 'powershell') {
|
|
116
|
+
const script = powershellScriptFile(program, args);
|
|
117
|
+
if (script !== undefined)
|
|
118
|
+
return [script];
|
|
119
|
+
}
|
|
120
|
+
return [];
|
|
121
|
+
}
|
package/dist/utils/shell.d.ts
CHANGED
|
@@ -26,6 +26,12 @@ export declare function resolveProgramPath(program: string): string;
|
|
|
26
26
|
* drive); with neither it stays unset.
|
|
27
27
|
*/
|
|
28
28
|
export declare function getCommandEnvironment(): NodeJS.ProcessEnv;
|
|
29
|
+
/**
|
|
30
|
+
* The environment of the shell start_process runs a command in: the
|
|
31
|
+
* command environment, with TERM for better terminal compatibility. The
|
|
32
|
+
* PowerShell helper starts with it too, so the user's profile sees the same.
|
|
33
|
+
*/
|
|
34
|
+
export declare function getShellEnvironment(): NodeJS.ProcessEnv;
|
|
29
35
|
/**
|
|
30
36
|
* The shell used when the user hasn't configured one.
|
|
31
37
|
* Windows: Windows PowerShell, falling back to %ComSpec%.
|
|
@@ -37,6 +43,36 @@ export declare function getDefaultShell(): string;
|
|
|
37
43
|
* resolve to an executable are returned.
|
|
38
44
|
*/
|
|
39
45
|
export declare function detectAvailableShells(): string[];
|
|
46
|
+
/**
|
|
47
|
+
* A program's name without its folder or extension, lowercased:
|
|
48
|
+
* C:\Windows\System32\NET.EXE is "net". The folder goes as Windows writes it
|
|
49
|
+
* (\ or /, or a drive, as in C:sc.exe). POSIX shells outside Windows use
|
|
50
|
+
* only / as a folder separator. The extension is .ps1
|
|
51
|
+
* (PowerShell runs deploy.ps1 for deploy), or on Windows one of PATHEXT's as
|
|
52
|
+
* commands run with it (repaired, #481). WSL runs Windows programs from Linux
|
|
53
|
+
* (sc.exe stop Spooler), so there too. The command check compares the names it
|
|
54
|
+
* finds and the blockedCommands entries in this form. POSIX shells on
|
|
55
|
+
* Windows still accept Windows paths, as Git Bash does.
|
|
56
|
+
*/
|
|
57
|
+
export declare function programName(name: string, shellType?: ShellType): string;
|
|
58
|
+
/** The kinds of shell a command can run in. The command check has a reader for each. */
|
|
59
|
+
export type ShellType = 'posix' | 'powershell' | 'cmd';
|
|
60
|
+
/**
|
|
61
|
+
* Which kind of shell a shell program is, by its name without folder and
|
|
62
|
+
* lowercased, as getShellSpawnArgs() reads it: pwsh and powershell (with or
|
|
63
|
+
* without .exe) are PowerShell, cmd and cmd.exe are cmd, and every other shell
|
|
64
|
+
* (bash, zsh, sh, dash, ksh, fish) is POSIX. getShellSpawnArgs() starts each
|
|
65
|
+
* kind its own way.
|
|
66
|
+
*/
|
|
67
|
+
export declare function getShellType(shell: string): ShellType;
|
|
68
|
+
/** The POSIX shells (and fish) by programName(): each runs a script file it's given (bash deploy.sh) */
|
|
69
|
+
export declare const POSIX_SHELLS: Set<string>;
|
|
70
|
+
/**
|
|
71
|
+
* The shell start_process runs a command in: the one asked for, else the
|
|
72
|
+
* defaultShell setting, else this machine's default. The command check reads
|
|
73
|
+
* the command with the same shell.
|
|
74
|
+
*/
|
|
75
|
+
export declare function getCommandShell(shell: string | undefined, defaultShell: string | undefined): string;
|
|
40
76
|
/**
|
|
41
77
|
* Configuration for spawning a shell with appropriate flags
|
|
42
78
|
*/
|