@wonderwhy-er/desktop-commander 0.3.1-alpha.2 → 0.3.1

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 (80) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +1152 -1152
  3. package/dist/bootstrap.js +0 -0
  4. package/dist/command-manager.js +0 -0
  5. package/dist/config-field-definitions.js +0 -0
  6. package/dist/config-manager.js +0 -0
  7. package/dist/config-recovery.js +0 -0
  8. package/dist/config.js +0 -0
  9. package/dist/custom-stdio.js +0 -0
  10. package/dist/data/onboarding-prompts.json +70 -70
  11. package/dist/error-handlers.js +0 -0
  12. package/dist/handlers/filesystem-handlers.js +2 -2
  13. package/dist/index.js +0 -0
  14. package/dist/npm-scripts/remote.js +25 -23
  15. package/dist/remote-device/desktop-commander-integration.d.ts +1 -0
  16. package/dist/remote-device/device.js +14 -2
  17. package/dist/remote-device/realtime-health-telemetry.d.ts +35 -0
  18. package/dist/remote-device/realtime-health-telemetry.js +110 -0
  19. package/dist/remote-device/remote-channel.d.ts +66 -55
  20. package/dist/remote-device/remote-channel.js +336 -389
  21. package/dist/remote-device/rollouts.d.ts +48 -0
  22. package/dist/remote-device/rollouts.js +105 -0
  23. package/dist/remote-device/scripts/blocking-offline-update.js +135 -133
  24. package/dist/search-manager.js +0 -0
  25. package/dist/server.js +581 -712
  26. package/dist/setup-claude-server.js +942 -942
  27. package/dist/terminal-manager.js +0 -0
  28. package/dist/tools/edit.js +2 -2
  29. package/dist/tools/fuzzySearch.js +9 -9
  30. package/dist/tools/improved-process-tools.js +10 -10
  31. package/dist/tools/pdf/extract-images.js +2 -6
  32. package/dist/tools/pdf/lib/pdf2md.js +28 -33
  33. package/dist/tools/pdf/utils.d.ts +10 -0
  34. package/dist/tools/pdf/utils.js +11 -0
  35. package/dist/tools/prompts.js +1 -1
  36. package/dist/tools/schemas.d.ts +0 -10
  37. package/dist/tools/schemas.js +0 -8
  38. package/dist/track-installation.js +387 -387
  39. package/dist/types.js +0 -0
  40. package/dist/ui/config-editor/config-editor-runtime.js +53 -53
  41. package/dist/ui/config-editor/index.html +13 -13
  42. package/dist/ui/config-editor/src/app.js +30 -30
  43. package/dist/ui/config-editor/src/array-modal.js +32 -32
  44. package/dist/ui/config-editor/styles.css +586 -586
  45. package/dist/ui/contracts.d.ts +27 -0
  46. package/dist/ui/contracts.js +36 -0
  47. package/dist/ui/file-preview/index.html +16 -16
  48. package/dist/ui/file-preview/preview-runtime.js +190 -182
  49. package/dist/ui/file-preview/src/app.js +8 -8
  50. package/dist/ui/file-preview/src/components/html-renderer.js +4 -2
  51. package/dist/ui/file-preview/src/document-layout.js +31 -31
  52. package/dist/ui/file-preview/src/document-outline.js +8 -8
  53. package/dist/ui/file-preview/src/markdown/conflict-dialog.js +33 -33
  54. package/dist/ui/file-preview/src/markdown/controller.js +9 -9
  55. package/dist/ui/file-preview/src/markdown/editor.js +31 -31
  56. package/dist/ui/file-preview/styles.css +1630 -1630
  57. package/dist/ui/resources.js +11 -4
  58. package/dist/uninstall-claude-server.js +745 -745
  59. package/dist/utils/files/binary.js +4 -4
  60. package/dist/utils/files/excel.js +3 -3
  61. package/dist/utils/files/text.d.ts +7 -0
  62. package/dist/utils/files/text.js +40 -21
  63. package/dist/utils/system-info.d.ts +1 -0
  64. package/dist/utils/system-info.js +110 -97
  65. package/dist/utils/terminal-timestamps.d.ts +2 -0
  66. package/dist/utils/terminal-timestamps.js +18 -0
  67. package/dist/utils/usageTracker.d.ts +0 -39
  68. package/dist/utils/usageTracker.js +16 -176
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -56
  72. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -32
  73. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -38
  74. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -164
  75. package/package.json +6 -10
  76. package/vendor/telemetry-contract/README.md +56 -56
  77. package/vendor/telemetry-contract/package.json +32 -32
  78. package/vendor/telemetry-contract/transport.d.ts +38 -38
  79. package/vendor/telemetry-contract/transport.js +164 -164
  80. package/vendor/telemetry-contract/transport.test.js +39 -39
@@ -1,942 +1,942 @@
1
- import { homedir, platform } from 'os';
2
- import fs from 'fs/promises';
3
- import path from 'path';
4
- import { join } from 'path';
5
- import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from 'fs';
6
- import { fileURLToPath } from 'url';
7
- import { dirname } from 'path';
8
- import { exec } from "node:child_process";
9
- import { version as nodeVersion } from 'process';
10
- import * as https from 'https';
11
- import { randomUUID } from 'crypto';
12
-
13
- // Telemetry proxy configuration
14
- const TELEMETRY_PROXY_URL = 'https://telemetry.desktopcommander.app/mp/collect';
15
- const TELEMETRY_PROXY_FALLBACK_URL = 'https://dc-telemetry-proxy-83847352264.europe-west1.run.app/mp/collect';
16
-
17
- // Generate a unique anonymous ID using UUID - consistent with privacy policy
18
- let uniqueUserId = 'unknown';
19
-
20
- try {
21
- // Use randomUUID from crypto module instead of machine-id
22
- // This generates a truly random identifier not tied to hardware
23
- uniqueUserId = randomUUID();
24
- } catch (error) {
25
- // Fall back to a semi-unique identifier if UUID generation fails
26
- uniqueUserId = `random-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
27
- }
28
-
29
- // Setup tracking
30
- let setupSteps = []; // Track setup progress
31
- let setupStartTime = Date.now();
32
-
33
- /**
34
- * Initialize configuration - load from disk or create default
35
- */
36
- async function initConfigFile() {
37
- const USER_HOME = homedir();
38
- const CONFIG_DIR = path.join(USER_HOME, '.claude-server-commander');
39
-
40
- // Paths relative to the config directory
41
- const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
42
- try {
43
- // Ensure config directory exists
44
- const configDir = path.dirname(CONFIG_FILE);
45
- if (!existsSync(configDir)) {
46
- mkdirSync(configDir, { recursive: true });
47
- }
48
-
49
- // Check if config file exists
50
- try {
51
- await fs.access(CONFIG_FILE);
52
- // Load existing config
53
- const configData = await fs.readFile(CONFIG_FILE, 'utf8');
54
- } catch (error) {
55
- const defaultConfig = {
56
- blockedCommands: [
57
-
58
- // Disk and partition management
59
- "mkfs", // Create a filesystem on a device
60
- "format", // Format a storage device (cross-platform)
61
- "mount", // Mount a filesystem
62
- "umount", // Unmount a filesystem
63
- "fdisk", // Manipulate disk partition tables
64
- "dd", // Convert and copy files, can write directly to disks
65
- "parted", // Disk partition manipulator
66
- "diskpart", // Windows disk partitioning utility
67
-
68
- // System administration and user management
69
- "sudo", // Execute command as superuser
70
- "su", // Substitute user identity
71
- "passwd", // Change user password
72
- "adduser", // Add a user to the system
73
- "useradd", // Create a new user
74
- "usermod", // Modify user account
75
- "groupadd", // Create a new group
76
- "chsh", // Change login shell
77
- "visudo", // Edit the sudoers file
78
-
79
- // System control
80
- "shutdown", // Shutdown the system
81
- "reboot", // Restart the system
82
- "halt", // Stop the system
83
- "poweroff", // Power off the system
84
- "init", // Change system runlevel
85
-
86
- // Network and security
87
- "iptables", // Linux firewall administration
88
- "firewall", // Generic firewall command
89
- "netsh", // Windows network configuration
90
-
91
- // Windows system commands
92
- "sfc", // System File Checker
93
- "bcdedit", // Boot Configuration Data editor
94
- "reg", // Windows registry editor
95
- "net", // Network/user/service management
96
- "sc", // Service Control manager
97
- "runas", // Execute command as another user
98
- "cipher", // Encrypt/decrypt files or wipe data
99
- "takeown" // Take ownership of files
100
- ],
101
- clientId: uniqueUserId, // Use the generated UUID as client ID
102
- defaultShell: platform() === 'win32' ? 'powershell.exe' : '/bin/sh',
103
- allowedDirectories: [],
104
- telemetryEnabled: true, // Default to opt-out approach (telemetry on by default)
105
- fileWriteLineLimit: 50, // Default line limit for file write operations (changed from 100)
106
- fileReadLineLimit: 1000 // Default line limit for file read operations (changed from character-based)
107
- };
108
- logToFile('User id ' + uniqueUserId);
109
- try {
110
- await fs.writeFile(CONFIG_FILE, JSON.stringify(defaultConfig, null, 2), 'utf8');
111
- } catch (error) {
112
- console.error('Failed to save config:', error);
113
- throw error;
114
- }
115
- }
116
-
117
- } catch (error) {
118
- console.error('Failed to initialize config:', error);
119
- }
120
- }
121
-
122
-
123
-
124
- // Function to get npm version
125
- async function getNpmVersion() {
126
- try {
127
- return new Promise((resolve, reject) => {
128
- exec('npm --version', (error, stdout, stderr) => {
129
- if (error) {
130
- resolve('unknown');
131
- return;
132
- }
133
- resolve(stdout.trim());
134
- });
135
- });
136
- } catch (error) {
137
- return 'unknown';
138
- }
139
- }
140
- const getVersion = async () => {
141
- try {
142
- if (process.env.npm_package_version) {
143
- return process.env.npm_package_version;
144
- }
145
-
146
- // Check if version.js exists in dist directory (when running from root)
147
- const versionPath = join(__dirname, 'version.js');
148
- if (existsSync(versionPath)) {
149
- const { VERSION } = await import(versionPath);
150
- return VERSION;
151
- }
152
-
153
- const packageJsonPath = join(__dirname, 'package.json');
154
- if (existsSync(packageJsonPath)) {
155
- const packageJsonContent = readFileSync(packageJsonPath, 'utf8');
156
- const packageJson = JSON.parse(packageJsonContent);
157
- if (packageJson.version) {
158
- return packageJson.version;
159
- }
160
- }
161
-
162
-
163
- return 'unknown';
164
- } catch (error) {
165
- return 'unknown';
166
- }
167
- };
168
-
169
- // Function to detect shell environment
170
- function detectShell() {
171
- // Check for Windows shells
172
- if (process.platform === 'win32') {
173
- if (process.env.TERM_PROGRAM === 'vscode') return 'vscode-terminal';
174
- if (process.env.WT_SESSION) return 'windows-terminal';
175
- if (process.env.SHELL?.includes('bash')) return 'git-bash';
176
- if (process.env.TERM?.includes('xterm')) return 'xterm-on-windows';
177
- if (process.env.ComSpec?.toLowerCase().includes('powershell')) return 'powershell';
178
- if (process.env.PROMPT) return 'cmd';
179
-
180
- // WSL detection
181
- if (process.env.WSL_DISTRO_NAME || process.env.WSLENV) {
182
- return `wsl-${process.env.WSL_DISTRO_NAME || 'unknown'}`;
183
- }
184
-
185
- return 'windows-unknown';
186
- }
187
-
188
- // Unix-based shells
189
- if (process.env.SHELL) {
190
- const shellPath = process.env.SHELL.toLowerCase();
191
- if (shellPath.includes('bash')) return 'bash';
192
- if (shellPath.includes('zsh')) return 'zsh';
193
- if (shellPath.includes('fish')) return 'fish';
194
- if (shellPath.includes('ksh')) return 'ksh';
195
- if (shellPath.includes('csh')) return 'csh';
196
- if (shellPath.includes('dash')) return 'dash';
197
- return `other-unix-${shellPath.split('/').pop()}`;
198
- }
199
-
200
- // Terminal emulators and IDE terminals
201
- if (process.env.TERM_PROGRAM) {
202
- return process.env.TERM_PROGRAM.toLowerCase();
203
- }
204
-
205
- return 'unknown-shell';
206
- }
207
-
208
- // Function to get the package spec that was used to run this script
209
- function getPackageSpec(versionArg = null) {
210
- // If explicit version/tag argument provided, use it
211
- // Usage: npx @wonderwhy-er/desktop-commander setup alpha
212
- if (versionArg) {
213
- return `@wonderwhy-er/desktop-commander@${versionArg}`;
214
- }
215
-
216
- // Check if running via npx - look for the package spec in process.argv
217
- // e.g., npx @wonderwhy-er/desktop-commander@0.2.18-alpha setup
218
- const argv = process.argv;
219
-
220
- // Look for the package name in argv
221
- for (let i = 0; i < argv.length; i++) {
222
- const arg = argv[i];
223
- if (arg.includes('@wonderwhy-er/desktop-commander')) {
224
- // Extract just the package spec (e.g., @wonderwhy-er/desktop-commander@0.2.18-alpha)
225
- const match = arg.match(/(@wonderwhy-er\/desktop-commander(@[^\/\s]+)?)/);
226
- if (match) {
227
- return match[1];
228
- }
229
- }
230
- }
231
-
232
- // Fallback to @latest if we can't detect
233
- return '@wonderwhy-er/desktop-commander@latest';
234
- }
235
-
236
- function isNPX() {
237
- return process.env.npm_lifecycle_event === 'npx' ||
238
- process.env.npm_execpath?.includes('npx') ||
239
- process.env._?.includes('npx') ||
240
- import.meta.url.includes('node_modules');
241
- }
242
- // Function to determine execution context
243
- function getExecutionContext() {
244
- // Check if running from npx
245
- const isNpx = isNPX();
246
-
247
- // Check if installed globally
248
- const isGlobal = process.env.npm_config_global === 'true' ||
249
- process.argv[1]?.includes('node_modules/.bin');
250
-
251
- // Check if it's run from a script in package.json
252
- const isNpmScript = !!process.env.npm_lifecycle_script;
253
-
254
- return {
255
- runMethod: isNpx ? 'npx' : (isGlobal ? 'global' : (isNpmScript ? 'npm_script' : 'direct')),
256
- isCI: !!process.env.CI || !!process.env.GITHUB_ACTIONS || !!process.env.TRAVIS || !!process.env.CIRCLECI,
257
- shell: detectShell()
258
- };
259
- }
260
-
261
- // Helper function to get standard environment properties for tracking
262
- let npmVersionCache = null;
263
-
264
- // Enhanced version with step tracking - will replace the original after initialization
265
- async function enhancedGetTrackingProperties(additionalProps = {}) {
266
- const propertiesStep = addSetupStep('get_tracking_properties');
267
- try {
268
- if (npmVersionCache === null) {
269
- npmVersionCache = await getNpmVersion();
270
- }
271
-
272
- const context = getExecutionContext();
273
- const version = await getVersion();
274
-
275
- updateSetupStep(propertiesStep, 'completed');
276
- return {
277
- platform: platform(),
278
- node_version: nodeVersion,
279
- npm_version: npmVersionCache,
280
- execution_context: context.runMethod,
281
- is_ci: context.isCI,
282
- shell: context.shell,
283
- app_version: version,
284
- engagement_time_msec: "100",
285
- ...additionalProps
286
- };
287
- } catch (error) {
288
- updateSetupStep(propertiesStep, 'failed', error);
289
- return {
290
- platform: platform(),
291
- node_version: nodeVersion,
292
- error: error.message,
293
- engagement_time_msec: "100",
294
- ...additionalProps
295
- };
296
- }
297
- }
298
-
299
- // Enhanced tracking function with retries and better error handling
300
- // This replaces the basic implementation for all tracking after initialization
301
- async function trackEvent(eventName, additionalProps = {}) {
302
- const trackingStep = addSetupStep(`track_event_${eventName}`);
303
-
304
- // Add retry capability
305
- const maxRetries = 2;
306
- let attempt = 0;
307
- let lastError = null;
308
-
309
- while (attempt <= maxRetries) {
310
- try {
311
- attempt++;
312
-
313
- // Get enriched properties
314
- const eventProperties = await enhancedGetTrackingProperties(additionalProps);
315
-
316
- // Prepare telemetry payload
317
- const payload = {
318
- client_id: uniqueUserId,
319
- non_personalized_ads: false,
320
- timestamp_micros: Date.now() * 1000,
321
- events: [{
322
- name: eventName,
323
- params: eventProperties
324
- }]
325
- };
326
-
327
- // Send to telemetry proxy
328
- const postData = JSON.stringify(payload);
329
-
330
- const options = {
331
- method: 'POST',
332
- headers: {
333
- 'Content-Type': 'application/json',
334
- 'Content-Length': Buffer.byteLength(postData)
335
- }
336
- };
337
-
338
- const result = await postTelemetryPayload(postData, options);
339
- if (!result.success) throw new Error('Telemetry proxy request failed');
340
-
341
- updateSetupStep(trackingStep, 'completed');
342
- return result;
343
-
344
- } catch (error) {
345
- lastError = error;
346
- if (attempt <= maxRetries) {
347
- // Wait before retry (exponential backoff)
348
- await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
349
- }
350
- }
351
- }
352
-
353
- // All retries failed
354
- updateSetupStep(trackingStep, 'failed', lastError);
355
- return false;
356
- }
357
-
358
- async function postTelemetryPayload(postData, options) {
359
- for (const endpoint of [TELEMETRY_PROXY_URL, TELEMETRY_PROXY_FALLBACK_URL]) {
360
- const result = await new Promise((resolve) => {
361
- let settled = false;
362
- let timeoutId;
363
- const finish = (result) => {
364
- if (settled) return;
365
- settled = true;
366
- clearTimeout(timeoutId);
367
- resolve(result);
368
- };
369
- const req = https.request(endpoint, options);
370
-
371
- timeoutId = setTimeout(() => {
372
- req.destroy();
373
- finish({ success: false, data: '' });
374
- }, 5000);
375
-
376
- req.on('error', () => {
377
- finish({ success: false, data: '' });
378
- });
379
-
380
- req.on('response', (res) => {
381
- let data = '';
382
- res.on('data', (chunk) => {
383
- data += chunk;
384
- });
385
- res.on('error', () => {
386
- finish({ success: false, data: '' });
387
- });
388
- res.on('end', () => {
389
- finish({ success: res.statusCode >= 200 && res.statusCode < 300, data });
390
- });
391
- res.on('close', () => {
392
- finish({ success: false, data: '' });
393
- });
394
- });
395
-
396
- req.write(postData);
397
- req.end();
398
- });
399
-
400
- if (result.success) return result;
401
- }
402
-
403
- return { success: false, data: '' };
404
- }
405
-
406
- // Ensure tracking completes before process exits
407
- async function ensureTrackingCompleted(eventName, additionalProps = {}, timeoutMs = 6000) {
408
- return new Promise(async (resolve) => {
409
- const timeoutId = setTimeout(() => {
410
- resolve(false);
411
- }, timeoutMs);
412
-
413
- try {
414
- await trackEvent(eventName, additionalProps);
415
- clearTimeout(timeoutId);
416
- resolve(true);
417
- } catch (error) {
418
- clearTimeout(timeoutId);
419
- resolve(false);
420
- }
421
- });
422
- }
423
-
424
-
425
- // Fix for Windows ESM path resolution
426
- const __filename = fileURLToPath(import.meta.url);
427
- const __dirname = dirname(__filename);
428
-
429
- // Setup logging early to capture everything
430
- const LOG_FILE = join(__dirname, 'setup.log');
431
-
432
- function logToFile(message, isError = false) {
433
- const timestamp = new Date().toISOString();
434
- const logMessage = `${timestamp} - ${isError ? 'ERROR: ' : ''}${message}\n`;
435
- try {
436
- appendFileSync(LOG_FILE, logMessage);
437
- // For setup script, we'll still output to console but in JSON forma
438
- const jsonOutput = {
439
- type: isError ? 'error' : 'info',
440
- timestamp,
441
- message
442
- };
443
- process.stdout.write(`${message}\n`);
444
- } catch (err) {
445
- // Last resort error handling
446
- process.stderr.write(`${JSON.stringify({
447
- type: 'error',
448
- timestamp: new Date().toISOString(),
449
- message: `Failed to write to log file: ${err.message}`
450
- })}\n`);
451
- }
452
- }
453
-
454
- // Setup global error handlers
455
- process.on('uncaughtException', async (error) => {
456
- await trackEvent('npx_setup_uncaught_exception', { error: error.message });
457
- setTimeout(() => {
458
- process.exit(1);
459
- }, 1000);
460
- });
461
-
462
- process.on('unhandledRejection', async (reason, promise) => {
463
- await trackEvent('npx_setup_unhandled_rejection', { error: String(reason) });
464
- setTimeout(() => {
465
- process.exit(1);
466
- }, 1000);
467
- });
468
-
469
- // Track when the process is about to exi
470
- let isExiting = false;
471
- process.on('exit', () => {
472
- if (!isExiting) {
473
- isExiting = true;
474
- }
475
- });
476
-
477
-
478
- // Function to check for debug mode argument
479
- function isDebugMode() {
480
- return process.argv.includes('--debug');
481
- }
482
-
483
- // Initial tracking - ensure it completes before continuing
484
- await ensureTrackingCompleted('npx_setup_start', {
485
- argv: process.argv.join(' '),
486
- start_time: new Date().toISOString()
487
- });
488
-
489
- // Determine OS and set appropriate config path
490
- const os = platform();
491
- const isWindows = os === 'win32';
492
- let claudeConfigPath;
493
-
494
- switch (os) {
495
- case 'win32':
496
- claudeConfigPath = join(process.env.APPDATA, 'Claude', 'claude_desktop_config.json');
497
- break;
498
- case 'darwin':
499
- claudeConfigPath = join(homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
500
- break;
501
- case 'linux':
502
- claudeConfigPath = join(homedir(), '.config', 'Claude', 'claude_desktop_config.json');
503
- break;
504
- default:
505
- // Fallback for other platforms
506
- claudeConfigPath = join(homedir(), '.claude_desktop_config.json');
507
- }
508
-
509
-
510
-
511
- // Tracking step functions
512
- function addSetupStep(step, status = 'started', error = null) {
513
- const timestamp = Date.now();
514
- setupSteps.push({
515
- step,
516
- status,
517
- timestamp,
518
- timeFromStart: timestamp - setupStartTime,
519
- error: error ? error.message || String(error) : null
520
- });
521
- return setupSteps.length - 1; // Return the index for later updates
522
- }
523
-
524
- function updateSetupStep(index, status, error = null) {
525
- if (setupSteps[index]) {
526
- const timestamp = Date.now();
527
- setupSteps[index].status = status;
528
- setupSteps[index].completionTime = timestamp;
529
- setupSteps[index].timeFromStart = timestamp - setupStartTime;
530
- if (error) {
531
- setupSteps[index].error = error.message || String(error);
532
- }
533
- }
534
- }
535
-
536
- async function execAsync(command) {
537
- const execStep = addSetupStep(`exec_${command.substring(0, 20)}...`);
538
- return new Promise((resolve, reject) => {
539
- // Use PowerShell on Windows for better Unicode support and consistency
540
- const actualCommand = isWindows
541
- ? `cmd.exe /c ${command}`
542
- : command;
543
-
544
- exec(actualCommand, { timeout: 10000 }, (error, stdout, stderr) => {
545
- if (error) {
546
- updateSetupStep(execStep, 'failed', error);
547
- reject(error);
548
- return;
549
- }
550
- updateSetupStep(execStep, 'completed');
551
- resolve({ stdout, stderr });
552
- });
553
- });
554
- }
555
-
556
- async function restartClaude() {
557
- const restartStep = addSetupStep('restart_claude');
558
- try {
559
- const platform = process.platform;
560
- // Track restart attempt
561
- await trackEvent('npx_setup_restart_claude_attempt', { platform });
562
-
563
- // Try to kill Claude process first
564
- const killStep = addSetupStep('kill_claude_process');
565
- try {
566
- switch (platform) {
567
- case "win32":
568
- await execAsync(
569
- `taskkill /F /IM "Claude.exe"`,
570
- );
571
- break;
572
- case "darwin":
573
- await execAsync(
574
- `killall "Claude"`,
575
- );
576
- break;
577
- case "linux":
578
- await execAsync(
579
- `pkill -f "claude"`,
580
- );
581
- break;
582
- }
583
- updateSetupStep(killStep, 'completed');
584
- await trackEvent('npx_setup_kill_claude_success', { platform });
585
- } catch (killError) {
586
- // It's okay if Claude isn't running - update step but continue
587
- updateSetupStep(killStep, 'no_process_found', killError);
588
- await trackEvent('npx_setup_kill_claude_not_needed', { platform });
589
- }
590
-
591
- // Wait a bit to ensure process termination
592
- await new Promise((resolve) => setTimeout(resolve, 3000));
593
-
594
- // Try to start Claude
595
- const startStep = addSetupStep('start_claude_process');
596
- try {
597
- if (platform === "win32") {
598
- // Windows - note it won't actually start Claude
599
- logToFile("Windows: Claude restart skipped - requires manual restart");
600
- updateSetupStep(startStep, 'skipped');
601
- await trackEvent('npx_setup_start_claude_skipped', { platform });
602
- } else if (platform === "darwin") {
603
- await execAsync(`open -a "Claude"`);
604
- updateSetupStep(startStep, 'completed');
605
- logToFile("\n✅ Claude has been restarted automatically!");
606
- await trackEvent('npx_setup_start_claude_success', { platform });
607
- } else if (platform === "linux") {
608
- await execAsync(`claude`);
609
- logToFile("\n✅ Claude has been restarted automatically!");
610
- updateSetupStep(startStep, 'completed');
611
- await trackEvent('npx_setup_start_claude_success', { platform });
612
- } else {
613
- logToFile('\nTo use the server restart Claude if it\'s currently running\n');
614
- }
615
-
616
- logToFile("\n✅ Installation successfully completed! Thank you for using Desktop Commander!\n");
617
- logToFile('\nThe server is available as "desktop-commander" in Claude\'s MCP server list');
618
-
619
- logToFile("Future updates will install automatically — no need to run this setup again.\n\n");
620
- logToFile("🤔 Need help or have feedback? Happy to jump on a quick call: \n\n")
621
- logToFile("https://calendar.app.google/SHMNZN5MJznJWC5A7 \n\n")
622
- logToFile("or join our community: https://discord.com/invite/kQ27sNnZr7\n\n")
623
-
624
-
625
-
626
-
627
-
628
-
629
-
630
-
631
- updateSetupStep(restartStep, 'completed');
632
- await trackEvent('npx_setup_restart_claude_success', { platform });
633
- } catch (startError) {
634
- updateSetupStep(startStep, 'failed', startError);
635
- await trackEvent('npx_setup_start_claude_error', {
636
- platform,
637
- error: startError.message
638
- });
639
- throw startError; // Re-throw to handle in the outer catch
640
- }
641
- } catch (error) {
642
- updateSetupStep(restartStep, 'failed', error);
643
- await trackEvent('npx_setup_restart_claude_error', { error: error.message });
644
- logToFile(`Failed to restart Claude: ${error}. Please restart it manually.`, true);
645
- logToFile(`If Claude Desktop is not installed use this link to download https://claude.ai/download`, true);
646
- }
647
- }
648
-
649
-
650
- // Main function to export for ESM compatibility
651
- export default async function setup() {
652
- // Parse command line arguments for version/tag
653
- const versionArg = process.argv[3]; // argv[0]=node, argv[1]=script, argv[2]=version/tag
654
-
655
- // Add tracking for setup function entry
656
- await trackEvent('npx_setup_function_started');
657
-
658
- const setupStep = addSetupStep('main_setup');
659
- const debugMode = isDebugMode();
660
-
661
- // Print ASCII art for DESKTOP COMMANDER
662
- console.log('\n');
663
- console.log('██████╗ ███████╗███████╗██╗ ██╗████████╗ ██████╗ ██████╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗ █████╗ ███╗ ██╗██████╗ ███████╗██████╗ ');
664
- console.log('██╔══██╗██╔════╝██╔════╝██║ ██╔╝╚══██╔══╝██╔═══██╗██╔══██╗ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔══██╗████╗ ██║██╔══██╗██╔════╝██╔══██╗');
665
- console.log('██║ ██║█████╗ ███████╗█████╔╝ ██║ ██║ ██║██████╔╝ ██║ ██║ ██║██╔████╔██║██╔████╔██║███████║██╔██╗ ██║██║ ██║█████╗ ██████╔╝');
666
- console.log('██║ ██║██╔══╝ ╚════██║██╔═██╗ ██║ ██║ ██║██╔═══╝ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║ ██║██╔══╝ ██╔══██╗');
667
- console.log('██████╔╝███████╗███████║██║ ██╗ ██║ ╚██████╔╝██║ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║██║ ██║██║ ╚████║██████╔╝███████╗██║ ██║');
668
- console.log('╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝');
669
- console.log('\n');
670
-
671
- if (debugMode) {
672
- logToFile('Debug mode enabled. Will configure with Node.js inspector options.');
673
- await trackEvent('npx_setup_debug_mode', { enabled: true });
674
- }
675
-
676
- try {
677
- await initConfigFile();
678
- // Check if config directory exists and create it if necessary
679
- const configDirStep = addSetupStep('check_config_directory');
680
- const configDir = dirname(claudeConfigPath);
681
-
682
- try {
683
- if (!existsSync(configDir)) {
684
- logToFile(`Creating config directory: ${configDir}`);
685
- mkdirSync(configDir, { recursive: true });
686
- await trackEvent('npx_setup_create_config_dir', { path: configDir });
687
- }
688
- updateSetupStep(configDirStep, 'completed');
689
- } catch (dirError) {
690
- updateSetupStep(configDirStep, 'failed', dirError);
691
- await trackEvent('npx_setup_create_config_dir_error', {
692
- path: configDir,
693
- error: dirError.message
694
- });
695
- throw new Error(`Failed to create config directory: ${dirError.message}`);
696
- }
697
-
698
- // Check if config file exists and create default if no
699
- const configFileStep = addSetupStep('check_config_file');
700
- let config;
701
-
702
- if (!existsSync(claudeConfigPath)) {
703
- logToFile(`Claude config file not found at: ${claudeConfigPath}`);
704
- logToFile('Creating default config file...');
705
-
706
- // Track new installation
707
- await trackEvent('npx_setup_create_default_config');
708
-
709
- // Create default config with shell based on platform
710
- const defaultConfig = {
711
- "serverConfig": isWindows
712
- ? {
713
- "command": "cmd.exe",
714
- "args": ["/c"]
715
- }
716
- : {
717
- "command": "/bin/sh",
718
- "args": ["-c"]
719
- }
720
- };
721
-
722
- try {
723
- writeFileSync(claudeConfigPath, JSON.stringify(defaultConfig, null, 2));
724
- logToFile('Default config file created.');
725
- config = defaultConfig;
726
- updateSetupStep(configFileStep, 'created');
727
- await trackEvent('npx_setup_config_file_created');
728
- } catch (writeError) {
729
- updateSetupStep(configFileStep, 'create_failed', writeError);
730
- await trackEvent('npx_setup_config_file_create_error', { error: writeError.message });
731
- throw new Error(`Failed to create config file: ${writeError.message}`);
732
- }
733
- } else {
734
- // Read existing config
735
- const readConfigStep = addSetupStep('read_config_file');
736
- try {
737
- const configData = readFileSync(claudeConfigPath, 'utf8');
738
- config = JSON.parse(configData);
739
- updateSetupStep(readConfigStep, 'completed');
740
- updateSetupStep(configFileStep, 'exists');
741
- await trackEvent('npx_setup_config_file_read');
742
- } catch (readError) {
743
- updateSetupStep(readConfigStep, 'failed', readError);
744
- await trackEvent('npx_setup_config_file_read_error', { error: readError.message });
745
- throw new Error(`Failed to read config file: ${readError.message}`);
746
- }
747
- }
748
-
749
- // Prepare the new server config based on OS
750
- const configPrepStep = addSetupStep('prepare_server_config');
751
-
752
- // Determine if running through npx or locally
753
- const isNpx = isNPX();
754
- await trackEvent('npx_setup_execution_mode', { isNpx });
755
-
756
- // Fix Windows path handling for npx execution
757
- let serverConfig;
758
-
759
- try {
760
- if (debugMode) {
761
- // Use Node.js with inspector flag for debugging
762
- if (isNpx) {
763
- // Debug with npx
764
- logToFile('Setting up debug configuration with npx. The process will pause on start until a debugger connects.');
765
- // Add environment variables to help with debugging
766
- // Inspector flag must be in NODE_OPTIONS, not passed as npx argument
767
- const debugEnv = {
768
- "NODE_OPTIONS": "--inspect-brk=9229 --trace-warnings --trace-exit",
769
- "DEBUG": "*"
770
- };
771
-
772
- const packageSpec = getPackageSpec(versionArg);
773
-
774
- // Windows requires cmd /c wrapper for npx
775
- if (isWindows) {
776
- serverConfig = {
777
- "command": "cmd",
778
- "args": [
779
- "/c",
780
- "npx",
781
- packageSpec
782
- ],
783
- "env": debugEnv
784
- };
785
- } else {
786
- serverConfig = {
787
- "command": "npx",
788
- "args": [
789
- packageSpec
790
- ],
791
- "env": debugEnv
792
- };
793
- }
794
- await trackEvent('npx_setup_config_debug_npx', { packageSpec });
795
- } else {
796
- // Debug with local installation path
797
- const indexPath = join(__dirname, 'dist', 'index.js');
798
- logToFile('Setting up debug configuration with local path. The process will pause on start until a debugger connects.');
799
- // Add environment variables to help with debugging
800
- const debugEnv = {
801
- "NODE_OPTIONS": "--trace-warnings --trace-exit",
802
- "DEBUG": "*"
803
- };
804
-
805
- serverConfig = {
806
- "command": isWindows ? "node.exe" : "node",
807
- "args": [
808
- "--inspect-brk=9229",
809
- indexPath.replace(/\\/g, '\\\\') // Double escape backslashes for JSON
810
- ],
811
- "env": debugEnv
812
- };
813
- await trackEvent('npx_setup_config_debug_local');
814
- }
815
- } else {
816
- // Standard configuration without debug
817
- if (isNpx) {
818
- const packageSpec = getPackageSpec(versionArg);
819
-
820
- // Windows requires cmd /c wrapper for npx
821
- if (isWindows) {
822
- serverConfig = {
823
- "command": "cmd",
824
- "args": [
825
- "/c",
826
- "npx",
827
- "-y",
828
- packageSpec
829
- ]
830
- };
831
- } else {
832
- serverConfig = {
833
- "command": "npx",
834
- "args": [
835
- "-y",
836
- packageSpec
837
- ]
838
- };
839
- }
840
- await trackEvent('npx_setup_config_standard_npx', { packageSpec });
841
- } else {
842
- // For local installation, use absolute path to handle Windows properly
843
- const indexPath = join(__dirname, 'dist', 'index.js');
844
- serverConfig = {
845
- "command": "node",
846
- "args": [
847
- indexPath.replace(/\\/g, '\\\\') // Double escape backslashes for JSON
848
- ]
849
- };
850
- await trackEvent('npx_setup_config_standard_local');
851
- }
852
- }
853
- updateSetupStep(configPrepStep, 'completed');
854
- } catch (prepError) {
855
- updateSetupStep(configPrepStep, 'failed', prepError);
856
- await trackEvent('npx_setup_config_prep_error', { error: prepError.message });
857
- throw new Error(`Failed to prepare server config: ${prepError.message}`);
858
- }
859
-
860
- // Update the config
861
- const updateConfigStep = addSetupStep('update_config');
862
- try {
863
- // Initialize mcpServers if it doesn't exist
864
- if (!config.mcpServers) {
865
- config.mcpServers = {};
866
- }
867
-
868
- // Check if the old "desktopCommander" exists and remove i
869
- if (config.mcpServers.desktopCommander) {
870
- delete config.mcpServers.desktopCommander;
871
- await trackEvent('npx_setup_remove_old_config');
872
- }
873
-
874
- // Add or update the terminal server config with the proper name "desktop-commander"
875
- config.mcpServers["desktop-commander"] = serverConfig;
876
-
877
- // Write the updated config back
878
- writeFileSync(claudeConfigPath, JSON.stringify(config, null, 2), 'utf8');
879
- updateSetupStep(updateConfigStep, 'completed');
880
- await trackEvent('npx_setup_update_config');
881
- } catch (updateError) {
882
- updateSetupStep(updateConfigStep, 'failed', updateError);
883
- await trackEvent('npx_setup_update_config_error', { error: updateError.message });
884
- throw new Error(`Failed to update config: ${updateError.message}`);
885
- }
886
- const appVersion = await getVersion()
887
- logToFile(`✅ Desktop Commander MCP v${appVersion} successfully added to Claude’s configuration.`);
888
- logToFile(`Configuration location: ${claudeConfigPath}`);
889
-
890
- if (debugMode) {
891
- logToFile('\nTo use the debug server:\n1. Restart Claude if it\'s currently running\n2. The server will be available as "desktop-commander-debug" in Claude\'s MCP server list\n3. Connect your debugger to port 9229');
892
- }
893
-
894
- // Try to restart Claude
895
- await restartClaude();
896
-
897
- // Mark the main setup as completed
898
- updateSetupStep(setupStep, 'completed');
899
-
900
- // Ensure final tracking event is sent before exi
901
- await ensureTrackingCompleted('npx_setup_complete', {
902
- total_steps: setupSteps.length,
903
- total_time_ms: Date.now() - setupStartTime
904
- });
905
-
906
-
907
-
908
- return true;
909
- } catch (error) {
910
- updateSetupStep(setupStep, 'failed', error);
911
- // Send detailed info about the failure
912
- await ensureTrackingCompleted('npx_setup_final_error', {
913
- error: error.message,
914
- error_stack: error.stack,
915
- total_steps: setupSteps.length,
916
- last_successful_step: setupSteps.filter(s => s.status === 'completed').pop()?.step || 'none'
917
- });
918
-
919
- logToFile(`Error updating Claude configuration: ${error}`, true);
920
- return false;
921
- }
922
- }
923
-
924
- // Allow direct execution
925
- if (process.argv.length >= 2 && process.argv[1] === fileURLToPath(import.meta.url)) {
926
- setup().then(success => {
927
- if (!success) {
928
- setTimeout(() => {
929
- process.exit(1);
930
- }, 1000);
931
- }
932
- }).catch(async error => {
933
- await ensureTrackingCompleted('npx_setup_fatal_error', {
934
- error: error.message,
935
- error_stack: error.stack
936
- });
937
- logToFile(`Fatal error: ${error}`, true);
938
- setTimeout(() => {
939
- process.exit(1);
940
- }, 1000);
941
- });
942
- }
1
+ import { homedir, platform } from 'os';
2
+ import fs from 'fs/promises';
3
+ import path from 'path';
4
+ import { join } from 'path';
5
+ import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from 'fs';
6
+ import { fileURLToPath } from 'url';
7
+ import { dirname } from 'path';
8
+ import { exec } from "node:child_process";
9
+ import { version as nodeVersion } from 'process';
10
+ import * as https from 'https';
11
+ import { randomUUID } from 'crypto';
12
+
13
+ // Telemetry proxy configuration
14
+ const TELEMETRY_PROXY_URL = 'https://telemetry.desktopcommander.app/mp/collect';
15
+ const TELEMETRY_PROXY_FALLBACK_URL = 'https://dc-telemetry-proxy-83847352264.europe-west1.run.app/mp/collect';
16
+
17
+ // Generate a unique anonymous ID using UUID - consistent with privacy policy
18
+ let uniqueUserId = 'unknown';
19
+
20
+ try {
21
+ // Use randomUUID from crypto module instead of machine-id
22
+ // This generates a truly random identifier not tied to hardware
23
+ uniqueUserId = randomUUID();
24
+ } catch (error) {
25
+ // Fall back to a semi-unique identifier if UUID generation fails
26
+ uniqueUserId = `random-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
27
+ }
28
+
29
+ // Setup tracking
30
+ let setupSteps = []; // Track setup progress
31
+ let setupStartTime = Date.now();
32
+
33
+ /**
34
+ * Initialize configuration - load from disk or create default
35
+ */
36
+ async function initConfigFile() {
37
+ const USER_HOME = homedir();
38
+ const CONFIG_DIR = path.join(USER_HOME, '.claude-server-commander');
39
+
40
+ // Paths relative to the config directory
41
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
42
+ try {
43
+ // Ensure config directory exists
44
+ const configDir = path.dirname(CONFIG_FILE);
45
+ if (!existsSync(configDir)) {
46
+ mkdirSync(configDir, { recursive: true });
47
+ }
48
+
49
+ // Check if config file exists
50
+ try {
51
+ await fs.access(CONFIG_FILE);
52
+ // Load existing config
53
+ const configData = await fs.readFile(CONFIG_FILE, 'utf8');
54
+ } catch (error) {
55
+ const defaultConfig = {
56
+ blockedCommands: [
57
+
58
+ // Disk and partition management
59
+ "mkfs", // Create a filesystem on a device
60
+ "format", // Format a storage device (cross-platform)
61
+ "mount", // Mount a filesystem
62
+ "umount", // Unmount a filesystem
63
+ "fdisk", // Manipulate disk partition tables
64
+ "dd", // Convert and copy files, can write directly to disks
65
+ "parted", // Disk partition manipulator
66
+ "diskpart", // Windows disk partitioning utility
67
+
68
+ // System administration and user management
69
+ "sudo", // Execute command as superuser
70
+ "su", // Substitute user identity
71
+ "passwd", // Change user password
72
+ "adduser", // Add a user to the system
73
+ "useradd", // Create a new user
74
+ "usermod", // Modify user account
75
+ "groupadd", // Create a new group
76
+ "chsh", // Change login shell
77
+ "visudo", // Edit the sudoers file
78
+
79
+ // System control
80
+ "shutdown", // Shutdown the system
81
+ "reboot", // Restart the system
82
+ "halt", // Stop the system
83
+ "poweroff", // Power off the system
84
+ "init", // Change system runlevel
85
+
86
+ // Network and security
87
+ "iptables", // Linux firewall administration
88
+ "firewall", // Generic firewall command
89
+ "netsh", // Windows network configuration
90
+
91
+ // Windows system commands
92
+ "sfc", // System File Checker
93
+ "bcdedit", // Boot Configuration Data editor
94
+ "reg", // Windows registry editor
95
+ "net", // Network/user/service management
96
+ "sc", // Service Control manager
97
+ "runas", // Execute command as another user
98
+ "cipher", // Encrypt/decrypt files or wipe data
99
+ "takeown" // Take ownership of files
100
+ ],
101
+ clientId: uniqueUserId, // Use the generated UUID as client ID
102
+ defaultShell: platform() === 'win32' ? 'powershell.exe' : '/bin/sh',
103
+ allowedDirectories: [],
104
+ telemetryEnabled: true, // Default to opt-out approach (telemetry on by default)
105
+ fileWriteLineLimit: 50, // Default line limit for file write operations (changed from 100)
106
+ fileReadLineLimit: 1000 // Default line limit for file read operations (changed from character-based)
107
+ };
108
+ logToFile('User id ' + uniqueUserId);
109
+ try {
110
+ await fs.writeFile(CONFIG_FILE, JSON.stringify(defaultConfig, null, 2), 'utf8');
111
+ } catch (error) {
112
+ console.error('Failed to save config:', error);
113
+ throw error;
114
+ }
115
+ }
116
+
117
+ } catch (error) {
118
+ console.error('Failed to initialize config:', error);
119
+ }
120
+ }
121
+
122
+
123
+
124
+ // Function to get npm version
125
+ async function getNpmVersion() {
126
+ try {
127
+ return new Promise((resolve, reject) => {
128
+ exec('npm --version', (error, stdout, stderr) => {
129
+ if (error) {
130
+ resolve('unknown');
131
+ return;
132
+ }
133
+ resolve(stdout.trim());
134
+ });
135
+ });
136
+ } catch (error) {
137
+ return 'unknown';
138
+ }
139
+ }
140
+ const getVersion = async () => {
141
+ try {
142
+ if (process.env.npm_package_version) {
143
+ return process.env.npm_package_version;
144
+ }
145
+
146
+ // Check if version.js exists in dist directory (when running from root)
147
+ const versionPath = join(__dirname, 'version.js');
148
+ if (existsSync(versionPath)) {
149
+ const { VERSION } = await import(versionPath);
150
+ return VERSION;
151
+ }
152
+
153
+ const packageJsonPath = join(__dirname, 'package.json');
154
+ if (existsSync(packageJsonPath)) {
155
+ const packageJsonContent = readFileSync(packageJsonPath, 'utf8');
156
+ const packageJson = JSON.parse(packageJsonContent);
157
+ if (packageJson.version) {
158
+ return packageJson.version;
159
+ }
160
+ }
161
+
162
+
163
+ return 'unknown';
164
+ } catch (error) {
165
+ return 'unknown';
166
+ }
167
+ };
168
+
169
+ // Function to detect shell environment
170
+ function detectShell() {
171
+ // Check for Windows shells
172
+ if (process.platform === 'win32') {
173
+ if (process.env.TERM_PROGRAM === 'vscode') return 'vscode-terminal';
174
+ if (process.env.WT_SESSION) return 'windows-terminal';
175
+ if (process.env.SHELL?.includes('bash')) return 'git-bash';
176
+ if (process.env.TERM?.includes('xterm')) return 'xterm-on-windows';
177
+ if (process.env.ComSpec?.toLowerCase().includes('powershell')) return 'powershell';
178
+ if (process.env.PROMPT) return 'cmd';
179
+
180
+ // WSL detection
181
+ if (process.env.WSL_DISTRO_NAME || process.env.WSLENV) {
182
+ return `wsl-${process.env.WSL_DISTRO_NAME || 'unknown'}`;
183
+ }
184
+
185
+ return 'windows-unknown';
186
+ }
187
+
188
+ // Unix-based shells
189
+ if (process.env.SHELL) {
190
+ const shellPath = process.env.SHELL.toLowerCase();
191
+ if (shellPath.includes('bash')) return 'bash';
192
+ if (shellPath.includes('zsh')) return 'zsh';
193
+ if (shellPath.includes('fish')) return 'fish';
194
+ if (shellPath.includes('ksh')) return 'ksh';
195
+ if (shellPath.includes('csh')) return 'csh';
196
+ if (shellPath.includes('dash')) return 'dash';
197
+ return `other-unix-${shellPath.split('/').pop()}`;
198
+ }
199
+
200
+ // Terminal emulators and IDE terminals
201
+ if (process.env.TERM_PROGRAM) {
202
+ return process.env.TERM_PROGRAM.toLowerCase();
203
+ }
204
+
205
+ return 'unknown-shell';
206
+ }
207
+
208
+ // Function to get the package spec that was used to run this script
209
+ function getPackageSpec(versionArg = null) {
210
+ // If explicit version/tag argument provided, use it
211
+ // Usage: npx @wonderwhy-er/desktop-commander setup alpha
212
+ if (versionArg) {
213
+ return `@wonderwhy-er/desktop-commander@${versionArg}`;
214
+ }
215
+
216
+ // Check if running via npx - look for the package spec in process.argv
217
+ // e.g., npx @wonderwhy-er/desktop-commander@0.2.18-alpha setup
218
+ const argv = process.argv;
219
+
220
+ // Look for the package name in argv
221
+ for (let i = 0; i < argv.length; i++) {
222
+ const arg = argv[i];
223
+ if (arg.includes('@wonderwhy-er/desktop-commander')) {
224
+ // Extract just the package spec (e.g., @wonderwhy-er/desktop-commander@0.2.18-alpha)
225
+ const match = arg.match(/(@wonderwhy-er\/desktop-commander(@[^\/\s]+)?)/);
226
+ if (match) {
227
+ return match[1];
228
+ }
229
+ }
230
+ }
231
+
232
+ // Fallback to @latest if we can't detect
233
+ return '@wonderwhy-er/desktop-commander@latest';
234
+ }
235
+
236
+ function isNPX() {
237
+ return process.env.npm_lifecycle_event === 'npx' ||
238
+ process.env.npm_execpath?.includes('npx') ||
239
+ process.env._?.includes('npx') ||
240
+ import.meta.url.includes('node_modules');
241
+ }
242
+ // Function to determine execution context
243
+ function getExecutionContext() {
244
+ // Check if running from npx
245
+ const isNpx = isNPX();
246
+
247
+ // Check if installed globally
248
+ const isGlobal = process.env.npm_config_global === 'true' ||
249
+ process.argv[1]?.includes('node_modules/.bin');
250
+
251
+ // Check if it's run from a script in package.json
252
+ const isNpmScript = !!process.env.npm_lifecycle_script;
253
+
254
+ return {
255
+ runMethod: isNpx ? 'npx' : (isGlobal ? 'global' : (isNpmScript ? 'npm_script' : 'direct')),
256
+ isCI: !!process.env.CI || !!process.env.GITHUB_ACTIONS || !!process.env.TRAVIS || !!process.env.CIRCLECI,
257
+ shell: detectShell()
258
+ };
259
+ }
260
+
261
+ // Helper function to get standard environment properties for tracking
262
+ let npmVersionCache = null;
263
+
264
+ // Enhanced version with step tracking - will replace the original after initialization
265
+ async function enhancedGetTrackingProperties(additionalProps = {}) {
266
+ const propertiesStep = addSetupStep('get_tracking_properties');
267
+ try {
268
+ if (npmVersionCache === null) {
269
+ npmVersionCache = await getNpmVersion();
270
+ }
271
+
272
+ const context = getExecutionContext();
273
+ const version = await getVersion();
274
+
275
+ updateSetupStep(propertiesStep, 'completed');
276
+ return {
277
+ platform: platform(),
278
+ node_version: nodeVersion,
279
+ npm_version: npmVersionCache,
280
+ execution_context: context.runMethod,
281
+ is_ci: context.isCI,
282
+ shell: context.shell,
283
+ app_version: version,
284
+ engagement_time_msec: "100",
285
+ ...additionalProps
286
+ };
287
+ } catch (error) {
288
+ updateSetupStep(propertiesStep, 'failed', error);
289
+ return {
290
+ platform: platform(),
291
+ node_version: nodeVersion,
292
+ error: error.message,
293
+ engagement_time_msec: "100",
294
+ ...additionalProps
295
+ };
296
+ }
297
+ }
298
+
299
+ // Enhanced tracking function with retries and better error handling
300
+ // This replaces the basic implementation for all tracking after initialization
301
+ async function trackEvent(eventName, additionalProps = {}) {
302
+ const trackingStep = addSetupStep(`track_event_${eventName}`);
303
+
304
+ // Add retry capability
305
+ const maxRetries = 2;
306
+ let attempt = 0;
307
+ let lastError = null;
308
+
309
+ while (attempt <= maxRetries) {
310
+ try {
311
+ attempt++;
312
+
313
+ // Get enriched properties
314
+ const eventProperties = await enhancedGetTrackingProperties(additionalProps);
315
+
316
+ // Prepare telemetry payload
317
+ const payload = {
318
+ client_id: uniqueUserId,
319
+ non_personalized_ads: false,
320
+ timestamp_micros: Date.now() * 1000,
321
+ events: [{
322
+ name: eventName,
323
+ params: eventProperties
324
+ }]
325
+ };
326
+
327
+ // Send to telemetry proxy
328
+ const postData = JSON.stringify(payload);
329
+
330
+ const options = {
331
+ method: 'POST',
332
+ headers: {
333
+ 'Content-Type': 'application/json',
334
+ 'Content-Length': Buffer.byteLength(postData)
335
+ }
336
+ };
337
+
338
+ const result = await postTelemetryPayload(postData, options);
339
+ if (!result.success) throw new Error('Telemetry proxy request failed');
340
+
341
+ updateSetupStep(trackingStep, 'completed');
342
+ return result;
343
+
344
+ } catch (error) {
345
+ lastError = error;
346
+ if (attempt <= maxRetries) {
347
+ // Wait before retry (exponential backoff)
348
+ await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
349
+ }
350
+ }
351
+ }
352
+
353
+ // All retries failed
354
+ updateSetupStep(trackingStep, 'failed', lastError);
355
+ return false;
356
+ }
357
+
358
+ async function postTelemetryPayload(postData, options) {
359
+ for (const endpoint of [TELEMETRY_PROXY_URL, TELEMETRY_PROXY_FALLBACK_URL]) {
360
+ const result = await new Promise((resolve) => {
361
+ let settled = false;
362
+ let timeoutId;
363
+ const finish = (result) => {
364
+ if (settled) return;
365
+ settled = true;
366
+ clearTimeout(timeoutId);
367
+ resolve(result);
368
+ };
369
+ const req = https.request(endpoint, options);
370
+
371
+ timeoutId = setTimeout(() => {
372
+ req.destroy();
373
+ finish({ success: false, data: '' });
374
+ }, 5000);
375
+
376
+ req.on('error', () => {
377
+ finish({ success: false, data: '' });
378
+ });
379
+
380
+ req.on('response', (res) => {
381
+ let data = '';
382
+ res.on('data', (chunk) => {
383
+ data += chunk;
384
+ });
385
+ res.on('error', () => {
386
+ finish({ success: false, data: '' });
387
+ });
388
+ res.on('end', () => {
389
+ finish({ success: res.statusCode >= 200 && res.statusCode < 300, data });
390
+ });
391
+ res.on('close', () => {
392
+ finish({ success: false, data: '' });
393
+ });
394
+ });
395
+
396
+ req.write(postData);
397
+ req.end();
398
+ });
399
+
400
+ if (result.success) return result;
401
+ }
402
+
403
+ return { success: false, data: '' };
404
+ }
405
+
406
+ // Ensure tracking completes before process exits
407
+ async function ensureTrackingCompleted(eventName, additionalProps = {}, timeoutMs = 6000) {
408
+ return new Promise(async (resolve) => {
409
+ const timeoutId = setTimeout(() => {
410
+ resolve(false);
411
+ }, timeoutMs);
412
+
413
+ try {
414
+ await trackEvent(eventName, additionalProps);
415
+ clearTimeout(timeoutId);
416
+ resolve(true);
417
+ } catch (error) {
418
+ clearTimeout(timeoutId);
419
+ resolve(false);
420
+ }
421
+ });
422
+ }
423
+
424
+
425
+ // Fix for Windows ESM path resolution
426
+ const __filename = fileURLToPath(import.meta.url);
427
+ const __dirname = dirname(__filename);
428
+
429
+ // Setup logging early to capture everything
430
+ const LOG_FILE = join(__dirname, 'setup.log');
431
+
432
+ function logToFile(message, isError = false) {
433
+ const timestamp = new Date().toISOString();
434
+ const logMessage = `${timestamp} - ${isError ? 'ERROR: ' : ''}${message}\n`;
435
+ try {
436
+ appendFileSync(LOG_FILE, logMessage);
437
+ // For setup script, we'll still output to console but in JSON forma
438
+ const jsonOutput = {
439
+ type: isError ? 'error' : 'info',
440
+ timestamp,
441
+ message
442
+ };
443
+ process.stdout.write(`${message}\n`);
444
+ } catch (err) {
445
+ // Last resort error handling
446
+ process.stderr.write(`${JSON.stringify({
447
+ type: 'error',
448
+ timestamp: new Date().toISOString(),
449
+ message: `Failed to write to log file: ${err.message}`
450
+ })}\n`);
451
+ }
452
+ }
453
+
454
+ // Setup global error handlers
455
+ process.on('uncaughtException', async (error) => {
456
+ await trackEvent('npx_setup_uncaught_exception', { error: error.message });
457
+ setTimeout(() => {
458
+ process.exit(1);
459
+ }, 1000);
460
+ });
461
+
462
+ process.on('unhandledRejection', async (reason, promise) => {
463
+ await trackEvent('npx_setup_unhandled_rejection', { error: String(reason) });
464
+ setTimeout(() => {
465
+ process.exit(1);
466
+ }, 1000);
467
+ });
468
+
469
+ // Track when the process is about to exi
470
+ let isExiting = false;
471
+ process.on('exit', () => {
472
+ if (!isExiting) {
473
+ isExiting = true;
474
+ }
475
+ });
476
+
477
+
478
+ // Function to check for debug mode argument
479
+ function isDebugMode() {
480
+ return process.argv.includes('--debug');
481
+ }
482
+
483
+ // Initial tracking - ensure it completes before continuing
484
+ await ensureTrackingCompleted('npx_setup_start', {
485
+ argv: process.argv.join(' '),
486
+ start_time: new Date().toISOString()
487
+ });
488
+
489
+ // Determine OS and set appropriate config path
490
+ const os = platform();
491
+ const isWindows = os === 'win32';
492
+ let claudeConfigPath;
493
+
494
+ switch (os) {
495
+ case 'win32':
496
+ claudeConfigPath = join(process.env.APPDATA, 'Claude', 'claude_desktop_config.json');
497
+ break;
498
+ case 'darwin':
499
+ claudeConfigPath = join(homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
500
+ break;
501
+ case 'linux':
502
+ claudeConfigPath = join(homedir(), '.config', 'Claude', 'claude_desktop_config.json');
503
+ break;
504
+ default:
505
+ // Fallback for other platforms
506
+ claudeConfigPath = join(homedir(), '.claude_desktop_config.json');
507
+ }
508
+
509
+
510
+
511
+ // Tracking step functions
512
+ function addSetupStep(step, status = 'started', error = null) {
513
+ const timestamp = Date.now();
514
+ setupSteps.push({
515
+ step,
516
+ status,
517
+ timestamp,
518
+ timeFromStart: timestamp - setupStartTime,
519
+ error: error ? error.message || String(error) : null
520
+ });
521
+ return setupSteps.length - 1; // Return the index for later updates
522
+ }
523
+
524
+ function updateSetupStep(index, status, error = null) {
525
+ if (setupSteps[index]) {
526
+ const timestamp = Date.now();
527
+ setupSteps[index].status = status;
528
+ setupSteps[index].completionTime = timestamp;
529
+ setupSteps[index].timeFromStart = timestamp - setupStartTime;
530
+ if (error) {
531
+ setupSteps[index].error = error.message || String(error);
532
+ }
533
+ }
534
+ }
535
+
536
+ async function execAsync(command) {
537
+ const execStep = addSetupStep(`exec_${command.substring(0, 20)}...`);
538
+ return new Promise((resolve, reject) => {
539
+ // Use PowerShell on Windows for better Unicode support and consistency
540
+ const actualCommand = isWindows
541
+ ? `cmd.exe /c ${command}`
542
+ : command;
543
+
544
+ exec(actualCommand, { timeout: 10000 }, (error, stdout, stderr) => {
545
+ if (error) {
546
+ updateSetupStep(execStep, 'failed', error);
547
+ reject(error);
548
+ return;
549
+ }
550
+ updateSetupStep(execStep, 'completed');
551
+ resolve({ stdout, stderr });
552
+ });
553
+ });
554
+ }
555
+
556
+ async function restartClaude() {
557
+ const restartStep = addSetupStep('restart_claude');
558
+ try {
559
+ const platform = process.platform;
560
+ // Track restart attempt
561
+ await trackEvent('npx_setup_restart_claude_attempt', { platform });
562
+
563
+ // Try to kill Claude process first
564
+ const killStep = addSetupStep('kill_claude_process');
565
+ try {
566
+ switch (platform) {
567
+ case "win32":
568
+ await execAsync(
569
+ `taskkill /F /IM "Claude.exe"`,
570
+ );
571
+ break;
572
+ case "darwin":
573
+ await execAsync(
574
+ `killall "Claude"`,
575
+ );
576
+ break;
577
+ case "linux":
578
+ await execAsync(
579
+ `pkill -f "claude"`,
580
+ );
581
+ break;
582
+ }
583
+ updateSetupStep(killStep, 'completed');
584
+ await trackEvent('npx_setup_kill_claude_success', { platform });
585
+ } catch (killError) {
586
+ // It's okay if Claude isn't running - update step but continue
587
+ updateSetupStep(killStep, 'no_process_found', killError);
588
+ await trackEvent('npx_setup_kill_claude_not_needed', { platform });
589
+ }
590
+
591
+ // Wait a bit to ensure process termination
592
+ await new Promise((resolve) => setTimeout(resolve, 3000));
593
+
594
+ // Try to start Claude
595
+ const startStep = addSetupStep('start_claude_process');
596
+ try {
597
+ if (platform === "win32") {
598
+ // Windows - note it won't actually start Claude
599
+ logToFile("Windows: Claude restart skipped - requires manual restart");
600
+ updateSetupStep(startStep, 'skipped');
601
+ await trackEvent('npx_setup_start_claude_skipped', { platform });
602
+ } else if (platform === "darwin") {
603
+ await execAsync(`open -a "Claude"`);
604
+ updateSetupStep(startStep, 'completed');
605
+ logToFile("\n✅ Claude has been restarted automatically!");
606
+ await trackEvent('npx_setup_start_claude_success', { platform });
607
+ } else if (platform === "linux") {
608
+ await execAsync(`claude`);
609
+ logToFile("\n✅ Claude has been restarted automatically!");
610
+ updateSetupStep(startStep, 'completed');
611
+ await trackEvent('npx_setup_start_claude_success', { platform });
612
+ } else {
613
+ logToFile('\nTo use the server restart Claude if it\'s currently running\n');
614
+ }
615
+
616
+ logToFile("\n✅ Installation successfully completed! Thank you for using Desktop Commander!\n");
617
+ logToFile('\nThe server is available as "desktop-commander" in Claude\'s MCP server list');
618
+
619
+ logToFile("Future updates will install automatically — no need to run this setup again.\n\n");
620
+ logToFile("🤔 Need help or have feedback? Happy to jump on a quick call: \n\n")
621
+ logToFile("https://calendar.app.google/SHMNZN5MJznJWC5A7 \n\n")
622
+ logToFile("or join our community: https://discord.com/invite/kQ27sNnZr7\n\n")
623
+
624
+
625
+
626
+
627
+
628
+
629
+
630
+
631
+ updateSetupStep(restartStep, 'completed');
632
+ await trackEvent('npx_setup_restart_claude_success', { platform });
633
+ } catch (startError) {
634
+ updateSetupStep(startStep, 'failed', startError);
635
+ await trackEvent('npx_setup_start_claude_error', {
636
+ platform,
637
+ error: startError.message
638
+ });
639
+ throw startError; // Re-throw to handle in the outer catch
640
+ }
641
+ } catch (error) {
642
+ updateSetupStep(restartStep, 'failed', error);
643
+ await trackEvent('npx_setup_restart_claude_error', { error: error.message });
644
+ logToFile(`Failed to restart Claude: ${error}. Please restart it manually.`, true);
645
+ logToFile(`If Claude Desktop is not installed use this link to download https://claude.ai/download`, true);
646
+ }
647
+ }
648
+
649
+
650
+ // Main function to export for ESM compatibility
651
+ export default async function setup() {
652
+ // Parse command line arguments for version/tag
653
+ const versionArg = process.argv[3]; // argv[0]=node, argv[1]=script, argv[2]=version/tag
654
+
655
+ // Add tracking for setup function entry
656
+ await trackEvent('npx_setup_function_started');
657
+
658
+ const setupStep = addSetupStep('main_setup');
659
+ const debugMode = isDebugMode();
660
+
661
+ // Print ASCII art for DESKTOP COMMANDER
662
+ console.log('\n');
663
+ console.log('██████╗ ███████╗███████╗██╗ ██╗████████╗ ██████╗ ██████╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗ █████╗ ███╗ ██╗██████╗ ███████╗██████╗ ');
664
+ console.log('██╔══██╗██╔════╝██╔════╝██║ ██╔╝╚══██╔══╝██╔═══██╗██╔══██╗ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔══██╗████╗ ██║██╔══██╗██╔════╝██╔══██╗');
665
+ console.log('██║ ██║█████╗ ███████╗█████╔╝ ██║ ██║ ██║██████╔╝ ██║ ██║ ██║██╔████╔██║██╔████╔██║███████║██╔██╗ ██║██║ ██║█████╗ ██████╔╝');
666
+ console.log('██║ ██║██╔══╝ ╚════██║██╔═██╗ ██║ ██║ ██║██╔═══╝ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║ ██║██╔══╝ ██╔══██╗');
667
+ console.log('██████╔╝███████╗███████║██║ ██╗ ██║ ╚██████╔╝██║ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║██║ ██║██║ ╚████║██████╔╝███████╗██║ ██║');
668
+ console.log('╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝');
669
+ console.log('\n');
670
+
671
+ if (debugMode) {
672
+ logToFile('Debug mode enabled. Will configure with Node.js inspector options.');
673
+ await trackEvent('npx_setup_debug_mode', { enabled: true });
674
+ }
675
+
676
+ try {
677
+ await initConfigFile();
678
+ // Check if config directory exists and create it if necessary
679
+ const configDirStep = addSetupStep('check_config_directory');
680
+ const configDir = dirname(claudeConfigPath);
681
+
682
+ try {
683
+ if (!existsSync(configDir)) {
684
+ logToFile(`Creating config directory: ${configDir}`);
685
+ mkdirSync(configDir, { recursive: true });
686
+ await trackEvent('npx_setup_create_config_dir', { path: configDir });
687
+ }
688
+ updateSetupStep(configDirStep, 'completed');
689
+ } catch (dirError) {
690
+ updateSetupStep(configDirStep, 'failed', dirError);
691
+ await trackEvent('npx_setup_create_config_dir_error', {
692
+ path: configDir,
693
+ error: dirError.message
694
+ });
695
+ throw new Error(`Failed to create config directory: ${dirError.message}`);
696
+ }
697
+
698
+ // Check if config file exists and create default if no
699
+ const configFileStep = addSetupStep('check_config_file');
700
+ let config;
701
+
702
+ if (!existsSync(claudeConfigPath)) {
703
+ logToFile(`Claude config file not found at: ${claudeConfigPath}`);
704
+ logToFile('Creating default config file...');
705
+
706
+ // Track new installation
707
+ await trackEvent('npx_setup_create_default_config');
708
+
709
+ // Create default config with shell based on platform
710
+ const defaultConfig = {
711
+ "serverConfig": isWindows
712
+ ? {
713
+ "command": "cmd.exe",
714
+ "args": ["/c"]
715
+ }
716
+ : {
717
+ "command": "/bin/sh",
718
+ "args": ["-c"]
719
+ }
720
+ };
721
+
722
+ try {
723
+ writeFileSync(claudeConfigPath, JSON.stringify(defaultConfig, null, 2));
724
+ logToFile('Default config file created.');
725
+ config = defaultConfig;
726
+ updateSetupStep(configFileStep, 'created');
727
+ await trackEvent('npx_setup_config_file_created');
728
+ } catch (writeError) {
729
+ updateSetupStep(configFileStep, 'create_failed', writeError);
730
+ await trackEvent('npx_setup_config_file_create_error', { error: writeError.message });
731
+ throw new Error(`Failed to create config file: ${writeError.message}`);
732
+ }
733
+ } else {
734
+ // Read existing config
735
+ const readConfigStep = addSetupStep('read_config_file');
736
+ try {
737
+ const configData = readFileSync(claudeConfigPath, 'utf8');
738
+ config = JSON.parse(configData);
739
+ updateSetupStep(readConfigStep, 'completed');
740
+ updateSetupStep(configFileStep, 'exists');
741
+ await trackEvent('npx_setup_config_file_read');
742
+ } catch (readError) {
743
+ updateSetupStep(readConfigStep, 'failed', readError);
744
+ await trackEvent('npx_setup_config_file_read_error', { error: readError.message });
745
+ throw new Error(`Failed to read config file: ${readError.message}`);
746
+ }
747
+ }
748
+
749
+ // Prepare the new server config based on OS
750
+ const configPrepStep = addSetupStep('prepare_server_config');
751
+
752
+ // Determine if running through npx or locally
753
+ const isNpx = isNPX();
754
+ await trackEvent('npx_setup_execution_mode', { isNpx });
755
+
756
+ // Fix Windows path handling for npx execution
757
+ let serverConfig;
758
+
759
+ try {
760
+ if (debugMode) {
761
+ // Use Node.js with inspector flag for debugging
762
+ if (isNpx) {
763
+ // Debug with npx
764
+ logToFile('Setting up debug configuration with npx. The process will pause on start until a debugger connects.');
765
+ // Add environment variables to help with debugging
766
+ // Inspector flag must be in NODE_OPTIONS, not passed as npx argument
767
+ const debugEnv = {
768
+ "NODE_OPTIONS": "--inspect-brk=9229 --trace-warnings --trace-exit",
769
+ "DEBUG": "*"
770
+ };
771
+
772
+ const packageSpec = getPackageSpec(versionArg);
773
+
774
+ // Windows requires cmd /c wrapper for npx
775
+ if (isWindows) {
776
+ serverConfig = {
777
+ "command": "cmd",
778
+ "args": [
779
+ "/c",
780
+ "npx",
781
+ packageSpec
782
+ ],
783
+ "env": debugEnv
784
+ };
785
+ } else {
786
+ serverConfig = {
787
+ "command": "npx",
788
+ "args": [
789
+ packageSpec
790
+ ],
791
+ "env": debugEnv
792
+ };
793
+ }
794
+ await trackEvent('npx_setup_config_debug_npx', { packageSpec });
795
+ } else {
796
+ // Debug with local installation path
797
+ const indexPath = join(__dirname, 'dist', 'index.js');
798
+ logToFile('Setting up debug configuration with local path. The process will pause on start until a debugger connects.');
799
+ // Add environment variables to help with debugging
800
+ const debugEnv = {
801
+ "NODE_OPTIONS": "--trace-warnings --trace-exit",
802
+ "DEBUG": "*"
803
+ };
804
+
805
+ serverConfig = {
806
+ "command": isWindows ? "node.exe" : "node",
807
+ "args": [
808
+ "--inspect-brk=9229",
809
+ indexPath.replace(/\\/g, '\\\\') // Double escape backslashes for JSON
810
+ ],
811
+ "env": debugEnv
812
+ };
813
+ await trackEvent('npx_setup_config_debug_local');
814
+ }
815
+ } else {
816
+ // Standard configuration without debug
817
+ if (isNpx) {
818
+ const packageSpec = getPackageSpec(versionArg);
819
+
820
+ // Windows requires cmd /c wrapper for npx
821
+ if (isWindows) {
822
+ serverConfig = {
823
+ "command": "cmd",
824
+ "args": [
825
+ "/c",
826
+ "npx",
827
+ "-y",
828
+ packageSpec
829
+ ]
830
+ };
831
+ } else {
832
+ serverConfig = {
833
+ "command": "npx",
834
+ "args": [
835
+ "-y",
836
+ packageSpec
837
+ ]
838
+ };
839
+ }
840
+ await trackEvent('npx_setup_config_standard_npx', { packageSpec });
841
+ } else {
842
+ // For local installation, use absolute path to handle Windows properly
843
+ const indexPath = join(__dirname, 'dist', 'index.js');
844
+ serverConfig = {
845
+ "command": "node",
846
+ "args": [
847
+ indexPath.replace(/\\/g, '\\\\') // Double escape backslashes for JSON
848
+ ]
849
+ };
850
+ await trackEvent('npx_setup_config_standard_local');
851
+ }
852
+ }
853
+ updateSetupStep(configPrepStep, 'completed');
854
+ } catch (prepError) {
855
+ updateSetupStep(configPrepStep, 'failed', prepError);
856
+ await trackEvent('npx_setup_config_prep_error', { error: prepError.message });
857
+ throw new Error(`Failed to prepare server config: ${prepError.message}`);
858
+ }
859
+
860
+ // Update the config
861
+ const updateConfigStep = addSetupStep('update_config');
862
+ try {
863
+ // Initialize mcpServers if it doesn't exist
864
+ if (!config.mcpServers) {
865
+ config.mcpServers = {};
866
+ }
867
+
868
+ // Check if the old "desktopCommander" exists and remove i
869
+ if (config.mcpServers.desktopCommander) {
870
+ delete config.mcpServers.desktopCommander;
871
+ await trackEvent('npx_setup_remove_old_config');
872
+ }
873
+
874
+ // Add or update the terminal server config with the proper name "desktop-commander"
875
+ config.mcpServers["desktop-commander"] = serverConfig;
876
+
877
+ // Write the updated config back
878
+ writeFileSync(claudeConfigPath, JSON.stringify(config, null, 2), 'utf8');
879
+ updateSetupStep(updateConfigStep, 'completed');
880
+ await trackEvent('npx_setup_update_config');
881
+ } catch (updateError) {
882
+ updateSetupStep(updateConfigStep, 'failed', updateError);
883
+ await trackEvent('npx_setup_update_config_error', { error: updateError.message });
884
+ throw new Error(`Failed to update config: ${updateError.message}`);
885
+ }
886
+ const appVersion = await getVersion()
887
+ logToFile(`✅ Desktop Commander MCP v${appVersion} successfully added to Claude’s configuration.`);
888
+ logToFile(`Configuration location: ${claudeConfigPath}`);
889
+
890
+ if (debugMode) {
891
+ logToFile('\nTo use the debug server:\n1. Restart Claude if it\'s currently running\n2. The server will be available as "desktop-commander-debug" in Claude\'s MCP server list\n3. Connect your debugger to port 9229');
892
+ }
893
+
894
+ // Try to restart Claude
895
+ await restartClaude();
896
+
897
+ // Mark the main setup as completed
898
+ updateSetupStep(setupStep, 'completed');
899
+
900
+ // Ensure final tracking event is sent before exi
901
+ await ensureTrackingCompleted('npx_setup_complete', {
902
+ total_steps: setupSteps.length,
903
+ total_time_ms: Date.now() - setupStartTime
904
+ });
905
+
906
+
907
+
908
+ return true;
909
+ } catch (error) {
910
+ updateSetupStep(setupStep, 'failed', error);
911
+ // Send detailed info about the failure
912
+ await ensureTrackingCompleted('npx_setup_final_error', {
913
+ error: error.message,
914
+ error_stack: error.stack,
915
+ total_steps: setupSteps.length,
916
+ last_successful_step: setupSteps.filter(s => s.status === 'completed').pop()?.step || 'none'
917
+ });
918
+
919
+ logToFile(`Error updating Claude configuration: ${error}`, true);
920
+ return false;
921
+ }
922
+ }
923
+
924
+ // Allow direct execution
925
+ if (process.argv.length >= 2 && process.argv[1] === fileURLToPath(import.meta.url)) {
926
+ setup().then(success => {
927
+ if (!success) {
928
+ setTimeout(() => {
929
+ process.exit(1);
930
+ }, 1000);
931
+ }
932
+ }).catch(async error => {
933
+ await ensureTrackingCompleted('npx_setup_fatal_error', {
934
+ error: error.message,
935
+ error_stack: error.stack
936
+ });
937
+ logToFile(`Fatal error: ${error}`, true);
938
+ setTimeout(() => {
939
+ process.exit(1);
940
+ }, 1000);
941
+ });
942
+ }