starmux 0.11.0 → 0.13.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 (136) hide show
  1. package/CONTRIBUTING.md +1 -1
  2. package/README.md +169 -97
  3. package/SECURITY.md +3 -3
  4. package/dist/src/access-control.js +23 -20
  5. package/dist/src/access-control.js.map +1 -1
  6. package/dist/src/access-dashboard.js +8 -2
  7. package/dist/src/access-dashboard.js.map +1 -1
  8. package/dist/src/cli/instances.js +87 -14
  9. package/dist/src/cli/instances.js.map +1 -1
  10. package/dist/src/cli/mac-mcp-gateway.js +4 -3
  11. package/dist/src/cli/mac-mcp-gateway.js.map +1 -1
  12. package/dist/src/cli/starmux-status.js +122 -0
  13. package/dist/src/cli/starmux-status.js.map +1 -0
  14. package/dist/src/cli/starmux.js +222 -49
  15. package/dist/src/cli/starmux.js.map +1 -1
  16. package/dist/src/deny-dashboard.js +2 -2
  17. package/dist/src/deny-dashboard.js.map +1 -1
  18. package/dist/src/instance-runtime.js +11 -2
  19. package/dist/src/instance-runtime.js.map +1 -1
  20. package/dist/src/instance-store.js +3 -1
  21. package/dist/src/instance-store.js.map +1 -1
  22. package/dist/src/ops-dashboard.js +4 -4
  23. package/dist/src/ops-dashboard.js.map +1 -1
  24. package/dist/src/permissions-dashboard.js +2 -2
  25. package/dist/src/permissions-dashboard.js.map +1 -1
  26. package/dist/src/runtime-paths.js +3 -3
  27. package/dist/src/runtime-paths.js.map +1 -1
  28. package/dist/src/starmux-migration.js +1 -1
  29. package/dist/src/starmux-migration.js.map +1 -1
  30. package/dist/vendor/desktop-commander/LICENSE +21 -0
  31. package/dist/vendor/desktop-commander/dist/bootstrap.js +22 -0
  32. package/dist/vendor/desktop-commander/dist/command-manager.js +246 -0
  33. package/dist/vendor/desktop-commander/dist/config-field-definitions.js +37 -0
  34. package/dist/vendor/desktop-commander/dist/config-manager.js +634 -0
  35. package/dist/vendor/desktop-commander/dist/config-recovery.js +81 -0
  36. package/dist/vendor/desktop-commander/dist/config.js +19 -0
  37. package/dist/vendor/desktop-commander/dist/custom-stdio.js +358 -0
  38. package/dist/vendor/desktop-commander/dist/error-handlers.js +15 -0
  39. package/dist/vendor/desktop-commander/dist/handlers/edit-search-handlers.js +6 -0
  40. package/dist/vendor/desktop-commander/dist/handlers/filesystem-handlers.js +450 -0
  41. package/dist/vendor/desktop-commander/dist/handlers/history-handlers.js +67 -0
  42. package/dist/vendor/desktop-commander/dist/handlers/index.js +7 -0
  43. package/dist/vendor/desktop-commander/dist/handlers/process-handlers.js +15 -0
  44. package/dist/vendor/desktop-commander/dist/handlers/search-answers.js +172 -0
  45. package/dist/vendor/desktop-commander/dist/handlers/search-handlers.js +136 -0
  46. package/dist/vendor/desktop-commander/dist/handlers/terminal-handlers.js +35 -0
  47. package/dist/vendor/desktop-commander/dist/index.js +88 -0
  48. package/dist/vendor/desktop-commander/dist/search-manager.js +1262 -0
  49. package/dist/vendor/desktop-commander/dist/server.js +1414 -0
  50. package/dist/vendor/desktop-commander/dist/terminal-manager.js +757 -0
  51. package/dist/vendor/desktop-commander/dist/tools/config.js +211 -0
  52. package/dist/vendor/desktop-commander/dist/tools/edit.js +455 -0
  53. package/dist/vendor/desktop-commander/dist/tools/feedback.js +10 -0
  54. package/dist/vendor/desktop-commander/dist/tools/filesystem.js +1047 -0
  55. package/dist/vendor/desktop-commander/dist/tools/fuzzySearch.js +74 -0
  56. package/dist/vendor/desktop-commander/dist/tools/fuzzySearchCore.js +125 -0
  57. package/dist/vendor/desktop-commander/dist/tools/improved-process-tools.js +726 -0
  58. package/dist/vendor/desktop-commander/dist/tools/mime-types.js +28 -0
  59. package/dist/vendor/desktop-commander/dist/tools/pdf/extract-images.js +131 -0
  60. package/dist/vendor/desktop-commander/dist/tools/pdf/index.js +4 -0
  61. package/dist/vendor/desktop-commander/dist/tools/pdf/lib/pdf2md.js +78 -0
  62. package/dist/vendor/desktop-commander/dist/tools/pdf/manipulations.js +112 -0
  63. package/dist/vendor/desktop-commander/dist/tools/pdf/markdown.js +30 -0
  64. package/dist/vendor/desktop-commander/dist/tools/pdf/utils.js +45 -0
  65. package/dist/vendor/desktop-commander/dist/tools/process.js +90 -0
  66. package/dist/vendor/desktop-commander/dist/tools/prompts.js +259 -0
  67. package/dist/vendor/desktop-commander/dist/tools/schemas.js +242 -0
  68. package/dist/vendor/desktop-commander/dist/tools/usage.js +24 -0
  69. package/dist/vendor/desktop-commander/dist/types.js +1 -0
  70. package/dist/vendor/desktop-commander/dist/ui/config-editor/config-editor-runtime.js +150 -0
  71. package/dist/vendor/desktop-commander/dist/ui/config-editor/index.html +13 -0
  72. package/dist/vendor/desktop-commander/dist/ui/config-editor/styles.css +587 -0
  73. package/dist/vendor/desktop-commander/dist/ui/contracts.js +57 -0
  74. package/dist/vendor/desktop-commander/dist/ui/file-preview/index.html +16 -0
  75. package/dist/vendor/desktop-commander/dist/ui/file-preview/preview-runtime.js +471 -0
  76. package/dist/vendor/desktop-commander/dist/ui/file-preview/shared/preview-file-types.js +59 -0
  77. package/dist/vendor/desktop-commander/dist/ui/file-preview/styles.css +1631 -0
  78. package/dist/vendor/desktop-commander/dist/ui/resources.js +93 -0
  79. package/dist/vendor/desktop-commander/dist/utils/ab-test.js +122 -0
  80. package/dist/vendor/desktop-commander/dist/utils/atomic-write.js +80 -0
  81. package/dist/vendor/desktop-commander/dist/utils/capture.js +40 -0
  82. package/dist/vendor/desktop-commander/dist/utils/dockerPrompt.js +9 -0
  83. package/dist/vendor/desktop-commander/dist/utils/exit-process.js +31 -0
  84. package/dist/vendor/desktop-commander/dist/utils/feature-flags.js +18 -0
  85. package/dist/vendor/desktop-commander/dist/utils/files/base.js +5 -0
  86. package/dist/vendor/desktop-commander/dist/utils/files/binary.js +65 -0
  87. package/dist/vendor/desktop-commander/dist/utils/files/docx.js +694 -0
  88. package/dist/vendor/desktop-commander/dist/utils/files/excel.js +497 -0
  89. package/dist/vendor/desktop-commander/dist/utils/files/factory.js +168 -0
  90. package/dist/vendor/desktop-commander/dist/utils/files/image.js +89 -0
  91. package/dist/vendor/desktop-commander/dist/utils/files/index.js +14 -0
  92. package/dist/vendor/desktop-commander/dist/utils/files/pdf.js +124 -0
  93. package/dist/vendor/desktop-commander/dist/utils/files/text.js +423 -0
  94. package/dist/vendor/desktop-commander/dist/utils/fuzzySearchLogger.js +126 -0
  95. package/dist/vendor/desktop-commander/dist/utils/internal-facts.js +23 -0
  96. package/dist/vendor/desktop-commander/dist/utils/lazy-package.js +44 -0
  97. package/dist/vendor/desktop-commander/dist/utils/lineEndingHandler.js +77 -0
  98. package/dist/vendor/desktop-commander/dist/utils/logger.js +72 -0
  99. package/dist/vendor/desktop-commander/dist/utils/mcp-ui-ab-test.js +62 -0
  100. package/dist/vendor/desktop-commander/dist/utils/open-browser.js +2 -0
  101. package/dist/vendor/desktop-commander/dist/utils/process-detection.js +260 -0
  102. package/dist/vendor/desktop-commander/dist/utils/process-tree.js +223 -0
  103. package/dist/vendor/desktop-commander/dist/utils/rename.js +74 -0
  104. package/dist/vendor/desktop-commander/dist/utils/ripgrep-resolver.js +69 -0
  105. package/dist/vendor/desktop-commander/dist/utils/shell.js +187 -0
  106. package/dist/vendor/desktop-commander/dist/utils/system-info.js +727 -0
  107. package/dist/vendor/desktop-commander/dist/utils/terminal-timestamps.js +18 -0
  108. package/dist/vendor/desktop-commander/dist/utils/toolHistory.js +309 -0
  109. package/dist/vendor/desktop-commander/dist/utils/trackTools.js +55 -0
  110. package/dist/vendor/desktop-commander/dist/utils/unsupportedParams.js +66 -0
  111. package/dist/vendor/desktop-commander/dist/utils/usageTracker.js +225 -0
  112. package/dist/vendor/desktop-commander/dist/utils/welcome-onboarding.js +2 -0
  113. package/dist/vendor/desktop-commander/dist/utils/withTimeout.js +85 -0
  114. package/dist/vendor/desktop-commander/dist/version.js +1 -0
  115. package/dist/vendor/desktop-commander/package.json +15 -0
  116. package/docs/ACCESS_CONTROL.md +5 -5
  117. package/docs/CLIENTS.md +11 -19
  118. package/docs/CONNECT_CHATGPT.md +4 -6
  119. package/docs/INSTALL.md +9 -5
  120. package/docs/INSTANCES.md +5 -2
  121. package/docs/OAUTH.md +6 -14
  122. package/docs/PLATFORMS.md +4 -4
  123. package/docs/README.md +2 -11
  124. package/docs/REMOTE_SETUP.md +13 -13
  125. package/docs/SECURITY.md +5 -5
  126. package/docs/assets/starmux-architecture.svg +315 -0
  127. package/package.json +14 -2
  128. package/docs/ARCHITECTURE.md +0 -51
  129. package/docs/MIGRATION.md +0 -37
  130. package/docs/RELEASE_STATUS.md +0 -31
  131. package/docs/TYPESCRIPT_MIGRATION.md +0 -56
  132. package/docs/VALIDATION_OAUTH.md +0 -79
  133. package/docs/VALIDATION_TUNNEL.md +0 -39
  134. package/docs/VALIDATION_WORKBUDDY.md +0 -59
  135. package/docs/assets/mcp-connection-route.svg +0 -104
  136. package/docs/assets/mcp-gateway-simple.svg +0 -62
@@ -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,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
+ }
@@ -0,0 +1,69 @@
1
+ import { existsSync, chmodSync } from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { resolveShellPath } from './shell.js';
5
+ let cachedRgPath = null;
6
+ /**
7
+ * Resolve ripgrep binary path with multiple fallback strategies
8
+ * This handles cases where @vscode/ripgrep postinstall fails in npx environments
9
+ */
10
+ export async function getRipgrepPath() {
11
+ if (cachedRgPath) {
12
+ return cachedRgPath;
13
+ }
14
+ // Strategy 1: Try @vscode/ripgrep package
15
+ try {
16
+ const { rgPath } = await import('@vscode/ripgrep');
17
+ if (existsSync(rgPath)) {
18
+ // Ensure executable permissions on Unix systems
19
+ if (process.platform !== 'win32') {
20
+ try {
21
+ chmodSync(rgPath, 0o755);
22
+ }
23
+ catch (e) {
24
+ // Ignore chmod errors - might not have write access
25
+ }
26
+ }
27
+ cachedRgPath = rgPath;
28
+ return rgPath;
29
+ }
30
+ }
31
+ catch (e) {
32
+ // @vscode/ripgrep import or binary resolution failed, continue to fallbacks
33
+ }
34
+ // Strategy 2: system ripgrep on PATH (never the working folder, which
35
+ // 'where' searched first on Windows)
36
+ const systemRg = resolveShellPath(process.platform === 'win32' ? 'rg.exe' : 'rg');
37
+ if (systemRg) {
38
+ cachedRgPath = systemRg;
39
+ return systemRg;
40
+ }
41
+ // Strategy 3: Try common installation paths
42
+ const commonPaths = [];
43
+ if (process.platform === 'win32') {
44
+ // Windows' own Program Files folders, which aren't always on C:
45
+ commonPaths.push(path.join(process.env.ProgramFiles ?? 'C:\\Program Files', 'Ripgrep', 'rg.exe'), path.join(process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)', 'Ripgrep', 'rg.exe'), path.join(os.homedir(), 'scoop', 'apps', 'ripgrep', 'current', 'rg.exe'), path.join(os.homedir(), '.cargo', 'bin', 'rg.exe'));
46
+ }
47
+ else {
48
+ commonPaths.push('/usr/local/bin/rg', '/usr/bin/rg', path.join(os.homedir(), '.cargo', 'bin', 'rg'), '/opt/homebrew/bin/rg' // Apple Silicon Homebrew
49
+ );
50
+ }
51
+ for (const possiblePath of commonPaths) {
52
+ if (existsSync(possiblePath)) {
53
+ cachedRgPath = possiblePath;
54
+ return possiblePath;
55
+ }
56
+ }
57
+ // No ripgrep found - provide helpful error message
58
+ throw new Error('ripgrep binary not found. Desktop Commander requires ripgrep to perform searches. ' +
59
+ 'Please install ripgrep:\n' +
60
+ ' macOS: brew install ripgrep\n' +
61
+ ' Linux: See https://github.com/BurntSushi/ripgrep#installation\n' +
62
+ ' Windows: choco install ripgrep or download from https://github.com/BurntSushi/ripgrep/releases');
63
+ }
64
+ /**
65
+ * Clear the cached ripgrep path (useful for testing)
66
+ */
67
+ export function clearRipgrepCache() {
68
+ cachedRgPath = null;
69
+ }
@@ -0,0 +1,187 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ /**
5
+ * Single source of truth for shells: which shell is the default on this
6
+ * machine, which shells are installed, and how to invoke each of them.
7
+ * Config defaults, system info, process tools, the terminal manager and the
8
+ * config editor all derive their shell choices from here.
9
+ */
10
+ // Shell executables Windows can host. Which of them exist is resolved on PATH.
11
+ const WINDOWS_SHELLS = ['powershell.exe', 'pwsh.exe', 'cmd.exe', 'bash.exe'];
12
+ function isWindows() {
13
+ return os.platform() === 'win32';
14
+ }
15
+ function isExecutableFile(filePath) {
16
+ try {
17
+ fs.accessSync(filePath, isWindows() ? fs.constants.F_OK : fs.constants.X_OK);
18
+ return fs.statSync(filePath).isFile();
19
+ }
20
+ catch {
21
+ // Missing or not executable: this candidate isn't a usable shell, the next one is tried
22
+ return false;
23
+ }
24
+ }
25
+ function windowsExecutableExtensions() {
26
+ const fromEnv = (process.env.PATHEXT ?? '').split(';').map((ext) => ext.trim()).filter(Boolean);
27
+ return [...new Set(['.EXE', ...fromEnv])];
28
+ }
29
+ /**
30
+ * Resolves a shell or other program name ("pwsh", "bash.exe", "where") or path
31
+ * ("/bin/zsh") to an executable file. Bare names are searched in PATH's
32
+ * folders only, never the working folder. Returns null when it can't be found.
33
+ */
34
+ export function resolveShellPath(shell) {
35
+ const name = shell.trim();
36
+ if (!name)
37
+ return null;
38
+ if (path.isAbsolute(name) || name.includes('/') || name.includes('\\')) {
39
+ return isExecutableFile(name) ? name : null;
40
+ }
41
+ const extensions = isWindows() && !path.extname(name) ? windowsExecutableExtensions() : [''];
42
+ const pathDirs = (process.env.PATH ?? '').split(path.delimiter)
43
+ .map((dir) => dir.trim().replace(/^"(.*)"$/, '$1'))
44
+ .filter(Boolean);
45
+ for (const dir of pathDirs) {
46
+ for (const ext of extensions) {
47
+ const candidate = path.join(dir, name + ext);
48
+ if (isExecutableFile(candidate))
49
+ return candidate;
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ export function isShellAvailable(shell) {
55
+ return resolveShellPath(shell) !== null;
56
+ }
57
+ /**
58
+ * The full path to start a program by: the one found on PATH. Windows looks
59
+ * for a bare name ("powershell.exe", "cmd", "tasklist") in the working folder
60
+ * before PATH, so a file of that name there would run instead; every program
61
+ * Desktop Commander starts by name goes through here. On Windows a bare name
62
+ * not found on PATH is an error rather than a name Windows would look up in
63
+ * the working folder. A path (absolute, or with a folder in it) is kept as
64
+ * given, and so is a bare name elsewhere, where the working folder isn't searched.
65
+ */
66
+ export function resolveProgramPath(program) {
67
+ const resolved = resolveShellPath(program);
68
+ if (resolved)
69
+ return resolved;
70
+ const name = program.trim();
71
+ if (isWindows() && !name.includes('/') && !name.includes('\\')) {
72
+ throw new Error(`${name} was not found on PATH`);
73
+ }
74
+ return program;
75
+ }
76
+ /**
77
+ * The shell used when the user hasn't configured one.
78
+ * Windows: Windows PowerShell, falling back to %ComSpec%.
79
+ * macOS/Linux: $SHELL, falling back to the OS default shell.
80
+ */
81
+ export function getDefaultShell() {
82
+ if (isWindows()) {
83
+ if (isShellAvailable('powershell.exe'))
84
+ return 'powershell.exe';
85
+ return process.env.ComSpec || 'cmd.exe';
86
+ }
87
+ const userShell = process.env.SHELL;
88
+ if (userShell && isShellAvailable(userShell))
89
+ return userShell;
90
+ // $SHELL may be unset when launched from a GUI app such as Claude Desktop.
91
+ // zsh is the macOS default since Catalina; /bin/sh is guaranteed by POSIX.
92
+ return os.platform() === 'darwin' ? '/bin/zsh' : '/bin/sh';
93
+ }
94
+ // Login programs /etc/shells can list that don't run a command given with -c,
95
+ // the way every command here starts: terminal multiplexers (screen, tmux),
96
+ // git-shell (git commands only), and programs that refuse a login
97
+ const NOT_COMMAND_SHELLS = new Set(['nologin', 'false', 'true', 'sync', 'git-shell', 'screen', 'tmux']);
98
+ function readEtcShells() {
99
+ try {
100
+ return fs.readFileSync('/etc/shells', 'utf8')
101
+ .split(/\r?\n/)
102
+ .map((line) => line.trim())
103
+ .filter((line) => line.length > 0 && !line.startsWith('#'))
104
+ .filter((line) => !NOT_COMMAND_SHELLS.has(path.basename(line)));
105
+ }
106
+ catch {
107
+ // Best-effort discovery only: no readable /etc/shells means no extra shells to list
108
+ return [];
109
+ }
110
+ }
111
+ /**
112
+ * Shells installed on this machine, default shell first. Only shells that
113
+ * resolve to an executable are returned.
114
+ */
115
+ export function detectAvailableShells() {
116
+ const shells = new Set();
117
+ const add = (shell) => {
118
+ const value = shell?.trim();
119
+ if (value && isShellAvailable(value))
120
+ shells.add(value);
121
+ };
122
+ add(getDefaultShell());
123
+ if (isWindows()) {
124
+ WINDOWS_SHELLS.forEach(add);
125
+ }
126
+ else {
127
+ add(process.env.SHELL);
128
+ readEtcShells().forEach(add);
129
+ }
130
+ return [...shells];
131
+ }
132
+ /**
133
+ * Get the appropriate spawn configuration for a given shell
134
+ * This handles login shell flags for different shell types
135
+ */
136
+ export function getShellSpawnArgs(shellPath, command) {
137
+ const shellName = path.basename(shellPath).toLowerCase();
138
+ const executable = resolveProgramPath(shellPath);
139
+ // Unix shells with login flag support
140
+ if (shellName.includes('bash') || shellName.includes('zsh')) {
141
+ return {
142
+ executable,
143
+ args: ['-l', '-c', command],
144
+ useShellOption: false
145
+ };
146
+ }
147
+ // PowerShell Core (cross-platform, supports -Login)
148
+ if (shellName === 'pwsh' || shellName === 'pwsh.exe') {
149
+ return {
150
+ executable,
151
+ args: ['-Login', '-Command', command],
152
+ useShellOption: false
153
+ };
154
+ }
155
+ // Windows PowerShell 5.1 (no login flag support)
156
+ if (shellName === 'powershell' || shellName === 'powershell.exe') {
157
+ return {
158
+ executable,
159
+ args: ['-Command', command],
160
+ useShellOption: false
161
+ };
162
+ }
163
+ // CMD
164
+ if (shellName === 'cmd' || shellName === 'cmd.exe') {
165
+ return {
166
+ executable,
167
+ args: ['/c', command],
168
+ windowsVerbatim: true,
169
+ useShellOption: false
170
+ };
171
+ }
172
+ // Fish shell (uses -l for login, -c for command)
173
+ if (shellName.includes('fish')) {
174
+ return {
175
+ executable,
176
+ args: ['-l', '-c', command],
177
+ useShellOption: false
178
+ };
179
+ }
180
+ // Unknown/other shells - use shell option for safety
181
+ // This provides a fallback for shells we don't explicitly handle
182
+ return {
183
+ executable: command,
184
+ args: [],
185
+ useShellOption: executable
186
+ };
187
+ }