@wonderwhy-er/desktop-commander 0.3.1-alpha.1 → 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 (82) 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 +3 -7
  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/lazy-package.d.ts +5 -3
  64. package/dist/utils/lazy-package.js +6 -4
  65. package/dist/utils/system-info.d.ts +1 -0
  66. package/dist/utils/system-info.js +110 -97
  67. package/dist/utils/terminal-timestamps.d.ts +2 -0
  68. package/dist/utils/terminal-timestamps.js +18 -0
  69. package/dist/utils/usageTracker.d.ts +0 -39
  70. package/dist/utils/usageTracker.js +16 -176
  71. package/dist/version.d.ts +1 -1
  72. package/dist/version.js +1 -1
  73. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -56
  74. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -32
  75. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -38
  76. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -164
  77. package/package.json +24 -15
  78. package/vendor/telemetry-contract/README.md +56 -56
  79. package/vendor/telemetry-contract/package.json +32 -32
  80. package/vendor/telemetry-contract/transport.d.ts +38 -38
  81. package/vendor/telemetry-contract/transport.js +164 -164
  82. package/vendor/telemetry-contract/transport.test.js +39 -39
@@ -1,745 +1,745 @@
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
- // Read clientId and telemetry settings from existing config
18
- let uniqueUserId = 'unknown';
19
- let telemetryEnabled = false; // Default to disabled for privacy
20
-
21
- async function getConfigSettings() {
22
- try {
23
- const USER_HOME = homedir();
24
- const CONFIG_DIR = path.join(USER_HOME, '.claude-server-commander');
25
- const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
26
-
27
- if (existsSync(CONFIG_FILE)) {
28
- const configData = readFileSync(CONFIG_FILE, 'utf8');
29
- const config = JSON.parse(configData);
30
-
31
- return {
32
- clientId: config.clientId || randomUUID(),
33
- telemetryEnabled: config.telemetryEnabled === true // Explicit check for true
34
- };
35
- }
36
-
37
- // Fallback: generate new ID and default telemetry to false if config doesn't exist
38
- return {
39
- clientId: `unknown-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`,
40
- telemetryEnabled: false
41
- };
42
- } catch (error) {
43
- // Final fallback
44
- return {
45
- clientId: `random-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`,
46
- telemetryEnabled: false
47
- };
48
- }
49
- }
50
-
51
- // Uninstall tracking
52
- let uninstallSteps = [];
53
- let uninstallStartTime = Date.now();
54
-
55
- // Fix for Windows ESM path resolution
56
- const __filename = fileURLToPath(import.meta.url);
57
- const __dirname = dirname(__filename);
58
-
59
- // Setup logging
60
- const LOG_FILE = join(__dirname, 'setup.log');
61
-
62
- function logToFile(message, isError = false) {
63
- const timestamp = new Date().toISOString();
64
- const logMessage = `${timestamp} - ${isError ? 'ERROR: ' : ''}${message}\n`;
65
- try {
66
- appendFileSync(LOG_FILE, logMessage);
67
- const jsonOutput = {
68
- type: isError ? 'error' : 'info',
69
- timestamp,
70
- message
71
- };
72
- process.stdout.write(`${message}\n`);
73
- } catch (err) {
74
- process.stderr.write(`${JSON.stringify({
75
- type: 'error',
76
- timestamp: new Date().toISOString(),
77
- message: `Failed to write to log file: ${err.message}`
78
- })}\n`);
79
- }
80
- }
81
-
82
- // Function to get npm version
83
- async function getNpmVersion() {
84
- try {
85
- return new Promise((resolve, reject) => {
86
- exec('npm --version', (error, stdout, stderr) => {
87
- if (error) {
88
- resolve('unknown');
89
- return;
90
- }
91
- resolve(stdout.trim());
92
- });
93
- });
94
- } catch (error) {
95
- return 'unknown';
96
- }
97
- }
98
-
99
- // Get Desktop Commander version
100
- const getVersion = async () => {
101
- try {
102
- if (process.env.npm_package_version) {
103
- return process.env.npm_package_version;
104
- }
105
-
106
- const versionPath = join(__dirname, 'version.js');
107
- if (existsSync(versionPath)) {
108
- const { VERSION } = await import(versionPath);
109
- return VERSION;
110
- }
111
-
112
- const packageJsonPath = join(__dirname, 'package.json');
113
- if (existsSync(packageJsonPath)) {
114
- const packageJsonContent = readFileSync(packageJsonPath, 'utf8');
115
- const packageJson = JSON.parse(packageJsonContent);
116
- if (packageJson.version) {
117
- return packageJson.version;
118
- }
119
- }
120
-
121
- return 'unknown';
122
- } catch (error) {
123
- return 'unknown';
124
- }
125
- };
126
- // Function to detect shell environment
127
- function detectShell() {
128
- if (process.platform === 'win32') {
129
- if (process.env.TERM_PROGRAM === 'vscode') return 'vscode-terminal';
130
- if (process.env.WT_SESSION) return 'windows-terminal';
131
- if (process.env.SHELL?.includes('bash')) return 'git-bash';
132
- if (process.env.TERM?.includes('xterm')) return 'xterm-on-windows';
133
- if (process.env.ComSpec?.toLowerCase().includes('powershell')) return 'powershell';
134
- if (process.env.PROMPT) return 'cmd';
135
-
136
- if (process.env.WSL_DISTRO_NAME || process.env.WSLENV) {
137
- return `wsl-${process.env.WSL_DISTRO_NAME || 'unknown'}`;
138
- }
139
-
140
- return 'windows-unknown';
141
- }
142
-
143
- if (process.env.SHELL) {
144
- const shellPath = process.env.SHELL.toLowerCase();
145
- if (shellPath.includes('bash')) return 'bash';
146
- if (shellPath.includes('zsh')) return 'zsh';
147
- if (shellPath.includes('fish')) return 'fish';
148
- if (shellPath.includes('ksh')) return 'ksh';
149
- if (shellPath.includes('csh')) return 'csh';
150
- if (shellPath.includes('dash')) return 'dash';
151
- return `other-unix-${shellPath.split('/').pop()}`;
152
- }
153
-
154
- if (process.env.TERM_PROGRAM) {
155
- return process.env.TERM_PROGRAM.toLowerCase();
156
- }
157
-
158
- return 'unknown-shell';
159
- }
160
-
161
- // Function to determine execution context
162
- function getExecutionContext() {
163
- const isNpx = process.env.npm_lifecycle_event === 'npx' ||
164
- process.env.npm_execpath?.includes('npx') ||
165
- process.env._?.includes('npx') ||
166
- import.meta.url.includes('node_modules');
167
-
168
- const isGlobal = process.env.npm_config_global === 'true' ||
169
- process.argv[1]?.includes('node_modules/.bin');
170
-
171
- const isNpmScript = !!process.env.npm_lifecycle_script;
172
-
173
- return {
174
- runMethod: isNpx ? 'npx' : (isGlobal ? 'global' : (isNpmScript ? 'npm_script' : 'direct')),
175
- isCI: !!process.env.CI || !!process.env.GITHUB_ACTIONS || !!process.env.TRAVIS || !!process.env.CIRCLECI,
176
- shell: detectShell()
177
- };
178
- }
179
- // Enhanced tracking properties
180
- let npmVersionCache = null;
181
-
182
- async function getTrackingProperties(additionalProps = {}) {
183
- const propertiesStep = addUninstallStep('get_tracking_properties');
184
- try {
185
- if (npmVersionCache === null) {
186
- npmVersionCache = await getNpmVersion();
187
- }
188
-
189
- const context = getExecutionContext();
190
- const version = await getVersion();
191
-
192
- updateUninstallStep(propertiesStep, 'completed');
193
- return {
194
- platform: platform(),
195
- node_version: nodeVersion,
196
- npm_version: npmVersionCache,
197
- execution_context: context.runMethod,
198
- is_ci: context.isCI,
199
- shell: context.shell,
200
- app_version: version,
201
- engagement_time_msec: "100",
202
- ...additionalProps
203
- };
204
- } catch (error) {
205
- updateUninstallStep(propertiesStep, 'failed', error);
206
- return {
207
- platform: platform(),
208
- node_version: nodeVersion,
209
- error: error.message,
210
- ...additionalProps
211
- };
212
- }
213
- }
214
- // Enhanced tracking function with retries
215
- async function trackEvent(eventName, additionalProps = {}) {
216
- const trackingStep = addUninstallStep(`track_event_${eventName}`);
217
-
218
- // Check if telemetry is disabled
219
- if (!telemetryEnabled) {
220
- updateUninstallStep(trackingStep, 'skipped_telemetry_disabled');
221
- return true; // Return success since this is expected behavior
222
- }
223
-
224
- const maxRetries = 2;
225
- let attempt = 0;
226
- let lastError = null;
227
-
228
- while (attempt <= maxRetries) {
229
- try {
230
- attempt++;
231
-
232
- const eventProperties = await getTrackingProperties(additionalProps);
233
-
234
- const payload = {
235
- client_id: uniqueUserId,
236
- non_personalized_ads: false,
237
- timestamp_micros: Date.now() * 1000,
238
- events: [{
239
- name: eventName,
240
- params: eventProperties
241
- }]
242
- };
243
-
244
- const postData = JSON.stringify(payload);
245
-
246
- const options = {
247
- method: 'POST',
248
- headers: {
249
- 'Content-Type': 'application/json',
250
- 'Content-Length': Buffer.byteLength(postData)
251
- }
252
- };
253
-
254
- const result = await postTelemetryPayload(postData, options);
255
- if (!result.success) throw new Error('Telemetry proxy request failed');
256
-
257
- updateUninstallStep(trackingStep, 'completed');
258
- return result;
259
-
260
- } catch (error) {
261
- lastError = error;
262
- if (attempt <= maxRetries) {
263
- await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
264
- }
265
- }
266
- }
267
-
268
- updateUninstallStep(trackingStep, 'failed', lastError);
269
- return false;
270
- }
271
-
272
- async function postTelemetryPayload(postData, options) {
273
- for (const endpoint of [TELEMETRY_PROXY_URL, TELEMETRY_PROXY_FALLBACK_URL]) {
274
- const result = await new Promise((resolve) => {
275
- let settled = false;
276
- let timeoutId;
277
- const finish = (result) => {
278
- if (settled) return;
279
- settled = true;
280
- clearTimeout(timeoutId);
281
- resolve(result);
282
- };
283
- const req = https.request(endpoint, options);
284
-
285
- timeoutId = setTimeout(() => {
286
- req.destroy();
287
- finish({ success: false, data: '' });
288
- }, 5000);
289
-
290
- req.on('error', () => {
291
- finish({ success: false, data: '' });
292
- });
293
-
294
- req.on('response', (res) => {
295
- let data = '';
296
- res.on('data', (chunk) => {
297
- data += chunk;
298
- });
299
- res.on('error', () => {
300
- finish({ success: false, data: '' });
301
- });
302
- res.on('end', () => {
303
- finish({ success: res.statusCode >= 200 && res.statusCode < 300, data });
304
- });
305
- res.on('close', () => {
306
- finish({ success: false, data: '' });
307
- });
308
- });
309
-
310
- req.write(postData);
311
- req.end();
312
- });
313
-
314
- if (result.success) return result;
315
- }
316
-
317
- return { success: false, data: '' };
318
- }
319
- // Ensure tracking completes before process exits
320
- async function ensureTrackingCompleted(eventName, additionalProps = {}, timeoutMs = 6000) {
321
- return new Promise(async (resolve) => {
322
- const timeoutId = setTimeout(() => {
323
- resolve(false);
324
- }, timeoutMs);
325
-
326
- try {
327
- await trackEvent(eventName, additionalProps);
328
- clearTimeout(timeoutId);
329
- resolve(true);
330
- } catch (error) {
331
- clearTimeout(timeoutId);
332
- resolve(false);
333
- }
334
- });
335
- }
336
-
337
- // Setup global error handlers (will be initialized after config is loaded)
338
- let errorHandlersInitialized = false;
339
-
340
- function initializeErrorHandlers() {
341
- if (errorHandlersInitialized) return;
342
-
343
- process.on('uncaughtException', async (error) => {
344
- if (telemetryEnabled) {
345
- await trackEvent('uninstall_uncaught_exception', { error: error.message });
346
- }
347
- setTimeout(() => {
348
- process.exit(1);
349
- }, 1000);
350
- });
351
-
352
- process.on('unhandledRejection', async (reason, promise) => {
353
- if (telemetryEnabled) {
354
- await trackEvent('uninstall_unhandled_rejection', { error: String(reason) });
355
- }
356
- setTimeout(() => {
357
- process.exit(1);
358
- }, 1000);
359
- });
360
-
361
- errorHandlersInitialized = true;
362
- }
363
-
364
- // Track when the process is about to exit
365
- let isExiting = false;
366
- process.on('exit', () => {
367
- if (!isExiting) {
368
- isExiting = true;
369
- }
370
- });
371
-
372
- // Determine OS and set appropriate config path
373
- const os = platform();
374
- const isWindows = os === 'win32';
375
- let claudeConfigPath;
376
-
377
- switch (os) {
378
- case 'win32':
379
- claudeConfigPath = join(process.env.APPDATA, 'Claude', 'claude_desktop_config.json');
380
- break;
381
- case 'darwin':
382
- claudeConfigPath = join(homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
383
- break;
384
- case 'linux':
385
- claudeConfigPath = join(homedir(), '.config', 'Claude', 'claude_desktop_config.json');
386
- break;
387
- default:
388
- claudeConfigPath = join(homedir(), '.claude_desktop_config.json');
389
- }
390
- // Step tracking functions
391
- function addUninstallStep(step, status = 'started', error = null) {
392
- const timestamp = Date.now();
393
- uninstallSteps.push({
394
- step,
395
- status,
396
- timestamp,
397
- timeFromStart: timestamp - uninstallStartTime,
398
- error: error ? error.message || String(error) : null
399
- });
400
- return uninstallSteps.length - 1;
401
- }
402
-
403
- function updateUninstallStep(index, status, error = null) {
404
- if (uninstallSteps[index]) {
405
- const timestamp = Date.now();
406
- uninstallSteps[index].status = status;
407
- uninstallSteps[index].completionTime = timestamp;
408
- uninstallSteps[index].timeFromStart = timestamp - uninstallStartTime;
409
- if (error) {
410
- uninstallSteps[index].error = error.message || String(error);
411
- }
412
- }
413
- }
414
-
415
- async function execAsync(command) {
416
- const execStep = addUninstallStep(`exec_${command.substring(0, 20)}...`);
417
- return new Promise((resolve, reject) => {
418
- const actualCommand = isWindows
419
- ? `cmd.exe /c ${command}`
420
- : command;
421
-
422
- exec(actualCommand, { timeout: 10000 }, (error, stdout, stderr) => {
423
- if (error) {
424
- updateUninstallStep(execStep, 'failed', error);
425
- reject(error);
426
- return;
427
- }
428
- updateUninstallStep(execStep, 'completed');
429
- resolve({ stdout, stderr });
430
- });
431
- });
432
- }
433
- // Backup configuration before removal
434
- async function createConfigBackup(configPath) {
435
- const backupStep = addUninstallStep('create_config_backup');
436
- try {
437
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
438
- const backupPath = `${configPath}.backup.${timestamp}`;
439
-
440
- if (existsSync(configPath)) {
441
- const configData = readFileSync(configPath, 'utf8');
442
- writeFileSync(backupPath, configData, 'utf8');
443
- updateUninstallStep(backupStep, 'completed');
444
- logToFile(`Configuration backup created: ${backupPath}`);
445
- await trackEvent('uninstall_backup_created');
446
- return backupPath;
447
- } else {
448
- updateUninstallStep(backupStep, 'no_config_file');
449
- return null;
450
- }
451
- } catch (error) {
452
- updateUninstallStep(backupStep, 'failed', error);
453
- await trackEvent('uninstall_backup_failed', { error: error.message });
454
- logToFile(`Failed to create backup: ${error.message}`, true);
455
- return null;
456
- }
457
- }
458
-
459
- // Restore configuration from backup
460
- async function restoreFromBackup(backupPath) {
461
- if (!backupPath || !existsSync(backupPath)) {
462
- return false;
463
- }
464
-
465
- try {
466
- const backupData = readFileSync(backupPath, 'utf8');
467
- writeFileSync(claudeConfigPath, backupData, 'utf8');
468
- logToFile(`Configuration restored from backup: ${backupPath}`);
469
- await trackEvent('uninstall_backup_restored');
470
- return true;
471
- } catch (error) {
472
- logToFile(`Failed to restore from backup: ${error.message}`, true);
473
- await trackEvent('uninstall_backup_restore_failed', { error: error.message });
474
- return false;
475
- }
476
- }
477
-
478
- async function restartClaude() {
479
- const restartStep = addUninstallStep('restart_claude');
480
- try {
481
- const platform = process.platform;
482
- logToFile('Attempting to restart Claude...');
483
- await trackEvent('uninstall_restart_claude_attempt');
484
-
485
- // Try to kill Claude process first
486
- const killStep = addUninstallStep('kill_claude_process');
487
- try {
488
- switch (platform) {
489
- case "win32":
490
- await execAsync(`taskkill /F /IM "Claude.exe"`);
491
- break;
492
- case "darwin":
493
- await execAsync(`killall "Claude"`);
494
- break;
495
- case "linux":
496
- await execAsync(`pkill -f "claude"`);
497
- break;
498
- }
499
- updateUninstallStep(killStep, 'completed');
500
- logToFile("Claude process terminated successfully");
501
- await trackEvent('uninstall_kill_claude_success');
502
- } catch (killError) {
503
- updateUninstallStep(killStep, 'no_process_found', killError);
504
- logToFile("Claude process not found or already terminated");
505
- await trackEvent('uninstall_kill_claude_not_needed');
506
- }
507
-
508
- // Wait a bit to ensure process termination
509
- await new Promise((resolve) => setTimeout(resolve, 2000));
510
-
511
- // Try to start Claude
512
- const startStep = addUninstallStep('start_claude_process');
513
- try {
514
- if (platform === "win32") {
515
- logToFile("Windows: Claude restart skipped - please restart Claude manually");
516
- updateUninstallStep(startStep, 'skipped');
517
- await trackEvent('uninstall_start_claude_skipped');
518
- } else if (platform === "darwin") {
519
- await execAsync(`open -a "Claude"`);
520
- updateUninstallStep(startStep, 'completed');
521
- logToFile("✅ Claude has been restarted automatically!");
522
- await trackEvent('uninstall_start_claude_success');
523
- } else if (platform === "linux") {
524
- await execAsync(`claude`);
525
- updateUninstallStep(startStep, 'completed');
526
- logToFile("✅ Claude has been restarted automatically!");
527
- await trackEvent('uninstall_start_claude_success');
528
- } else {
529
- logToFile('To complete uninstallation, restart Claude if it\'s currently running');
530
- updateUninstallStep(startStep, 'manual_required');
531
- }
532
-
533
- updateUninstallStep(restartStep, 'completed');
534
- await trackEvent('uninstall_restart_claude_success');
535
- } catch (startError) {
536
- updateUninstallStep(startStep, 'failed', startError);
537
- await trackEvent('uninstall_start_claude_error', {
538
- error: startError.message
539
- });
540
- logToFile(`Could not automatically restart Claude: ${startError.message}. Please restart it manually.`);
541
- }
542
- } catch (error) {
543
- updateUninstallStep(restartStep, 'failed', error);
544
- await trackEvent('uninstall_restart_claude_error', { error: error.message });
545
- logToFile(`Failed to restart Claude: ${error.message}. Please restart it manually.`, true);
546
- }
547
- }
548
- async function removeDesktopCommanderConfig() {
549
- const configStep = addUninstallStep('remove_mcp_config');
550
- let backupPath = null;
551
-
552
- try {
553
- // Check if config file exists
554
- if (!existsSync(claudeConfigPath)) {
555
- updateUninstallStep(configStep, 'no_config_file');
556
- logToFile(`Claude config file not found at: ${claudeConfigPath}`);
557
- logToFile('✅ Desktop Commander was not configured or already removed.');
558
- await trackEvent('uninstall_config_not_found');
559
- return true;
560
- }
561
-
562
- // Create backup before making changes
563
- backupPath = await createConfigBackup(claudeConfigPath);
564
-
565
- // Read existing config
566
- let config;
567
- const readStep = addUninstallStep('read_config_file');
568
- try {
569
- const configData = readFileSync(claudeConfigPath, 'utf8');
570
- config = JSON.parse(configData);
571
- updateUninstallStep(readStep, 'completed');
572
- } catch (readError) {
573
- updateUninstallStep(readStep, 'failed', readError);
574
- await trackEvent('uninstall_config_read_error', { error: readError.message });
575
- throw new Error(`Failed to read config file: ${readError.message}`);
576
- }
577
-
578
- // Check if mcpServers exists
579
- if (!config.mcpServers) {
580
- updateUninstallStep(configStep, 'no_mcp_servers');
581
- logToFile('No MCP servers configured in Claude.');
582
- logToFile('✅ Desktop Commander was not configured or already removed.');
583
- await trackEvent('uninstall_no_mcp_servers');
584
- return true;
585
- }
586
- // Track what we're removing
587
- const serversToRemove = [];
588
-
589
- if (config.mcpServers["desktop-commander"]) {
590
- serversToRemove.push("desktop-commander");
591
- }
592
-
593
- if (serversToRemove.length === 0) {
594
- updateUninstallStep(configStep, 'not_found');
595
- logToFile('Desktop Commander MCP server not found in configuration.');
596
- logToFile('✅ Desktop Commander was not configured or already removed.');
597
- await trackEvent('uninstall_server_not_found');
598
- return true;
599
- }
600
-
601
- // Remove the server configurations
602
- const removeStep = addUninstallStep('remove_server_configs');
603
- try {
604
- serversToRemove.forEach(serverName => {
605
- delete config.mcpServers[serverName];
606
- logToFile(`Removed "${serverName}" from Claude configuration`);
607
- });
608
-
609
- updateUninstallStep(removeStep, 'completed');
610
- await trackEvent('uninstall_servers_removed');
611
- } catch (removeError) {
612
- updateUninstallStep(removeStep, 'failed', removeError);
613
- await trackEvent('uninstall_servers_remove_error', { error: removeError.message });
614
- throw new Error(`Failed to remove server configs: ${removeError.message}`);
615
- } // Write the updated config back
616
- const writeStep = addUninstallStep('write_updated_config');
617
- try {
618
- writeFileSync(claudeConfigPath, JSON.stringify(config, null, 2), 'utf8');
619
- updateUninstallStep(writeStep, 'completed');
620
- updateUninstallStep(configStep, 'completed');
621
- logToFile('✅ Desktop Commander successfully removed from Claude configuration');
622
- logToFile(`Configuration updated at: ${claudeConfigPath}`);
623
- await trackEvent('uninstall_config_updated');
624
- } catch (writeError) {
625
- updateUninstallStep(writeStep, 'failed', writeError);
626
- await trackEvent('uninstall_config_write_error', { error: writeError.message });
627
-
628
- // Try to restore from backup
629
- if (backupPath) {
630
- logToFile('Attempting to restore configuration from backup...');
631
- const restored = await restoreFromBackup(backupPath);
632
- if (restored) {
633
- throw new Error(`Failed to write updated config, but backup was restored: ${writeError.message}`);
634
- } else {
635
- throw new Error(`Failed to write updated config and backup restoration failed: ${writeError.message}`);
636
- }
637
- } else {
638
- throw new Error(`Failed to write updated config: ${writeError.message}`);
639
- }
640
- }
641
-
642
- return true;
643
- } catch (error) {
644
- updateUninstallStep(configStep, 'failed', error);
645
- await trackEvent('uninstall_config_error', { error: error.message });
646
- logToFile(`Error removing Desktop Commander configuration: ${error.message}`, true);
647
-
648
- // Try to restore from backup if we have one
649
- if (backupPath) {
650
- logToFile('Attempting to restore configuration from backup...');
651
- await restoreFromBackup(backupPath);
652
- }
653
-
654
- return false;
655
- }
656
- }
657
- // Main uninstall function
658
- export default async function uninstall() {
659
- // Initialize clientId and telemetry settings from existing config
660
- const configSettings = await getConfigSettings();
661
- uniqueUserId = configSettings.clientId;
662
- telemetryEnabled = configSettings.telemetryEnabled;
663
-
664
- // Initialize error handlers now that telemetry setting is known
665
- initializeErrorHandlers();
666
-
667
- // Log telemetry status for transparency
668
- if (!telemetryEnabled) {
669
- logToFile('Telemetry disabled - no analytics will be sent');
670
- }
671
-
672
- // Initial tracking (only if telemetry enabled)
673
- await ensureTrackingCompleted('uninstall_start');
674
-
675
- const mainStep = addUninstallStep('main_uninstall');
676
-
677
- try {
678
- logToFile('Starting Desktop Commander uninstallation...');
679
-
680
- // Remove the server configuration from Claude
681
- const configRemoved = await removeDesktopCommanderConfig();
682
-
683
- if (configRemoved) {
684
- // Try to restart Claude
685
- // await restartClaude();
686
-
687
- updateUninstallStep(mainStep, 'completed');
688
-
689
- const appVersion = await getVersion();
690
- logToFile(`\n✅ Desktop Commander has been successfully uninstalled!`);
691
- logToFile('The MCP server has been removed from Claude\'s configuration.');
692
-
693
- logToFile('\nIf you want to reinstall later, you can run:');
694
- logToFile('npx @wonderwhy-er/desktop-commander@latest setup');
695
-
696
- logToFile('\nThank you for using Desktop Commander! 👋\n');
697
-
698
- // Send final tracking event
699
- await ensureTrackingCompleted('uninstall_complete');
700
-
701
- return true;
702
- } else {
703
- updateUninstallStep(mainStep, 'failed_config_removal');
704
-
705
- logToFile('\n❌ Uninstallation completed with errors.');
706
- logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.');
707
- logToFile(`Configuration file location: ${claudeConfigPath}\n`);
708
-
709
- await ensureTrackingCompleted('uninstall_partial_failure');
710
-
711
- return false;
712
- }
713
- } catch (error) {
714
- updateUninstallStep(mainStep, 'fatal_error', error);
715
-
716
- await ensureTrackingCompleted('uninstall_fatal_error', {
717
- error: error.message,
718
- error_stack: error.stack,
719
- last_successful_step: uninstallSteps.filter(s => s.status === 'completed').pop()?.step || 'none'
720
- });
721
-
722
- logToFile(`Fatal error during uninstallation: ${error.message}`, true);
723
- logToFile('\n❌ Uninstallation failed.');
724
- logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.');
725
- logToFile(`Configuration file location: ${claudeConfigPath}\n`);
726
-
727
- return false;
728
- }
729
- }
730
-
731
- // Allow direct execution
732
- if (process.argv.length >= 2 && process.argv[1] === fileURLToPath(import.meta.url)) {
733
- uninstall().then(success => {
734
- if (!success) {
735
- process.exit(1);
736
- }
737
- }).catch(async error => {
738
- await ensureTrackingCompleted('uninstall_execution_error', {
739
- error: error.message,
740
- error_stack: error.stack
741
- });
742
- logToFile(`Fatal error: ${error}`, true);
743
- process.exit(1);
744
- });
745
- }
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
+ // Read clientId and telemetry settings from existing config
18
+ let uniqueUserId = 'unknown';
19
+ let telemetryEnabled = false; // Default to disabled for privacy
20
+
21
+ async function getConfigSettings() {
22
+ try {
23
+ const USER_HOME = homedir();
24
+ const CONFIG_DIR = path.join(USER_HOME, '.claude-server-commander');
25
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
26
+
27
+ if (existsSync(CONFIG_FILE)) {
28
+ const configData = readFileSync(CONFIG_FILE, 'utf8');
29
+ const config = JSON.parse(configData);
30
+
31
+ return {
32
+ clientId: config.clientId || randomUUID(),
33
+ telemetryEnabled: config.telemetryEnabled === true // Explicit check for true
34
+ };
35
+ }
36
+
37
+ // Fallback: generate new ID and default telemetry to false if config doesn't exist
38
+ return {
39
+ clientId: `unknown-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`,
40
+ telemetryEnabled: false
41
+ };
42
+ } catch (error) {
43
+ // Final fallback
44
+ return {
45
+ clientId: `random-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`,
46
+ telemetryEnabled: false
47
+ };
48
+ }
49
+ }
50
+
51
+ // Uninstall tracking
52
+ let uninstallSteps = [];
53
+ let uninstallStartTime = Date.now();
54
+
55
+ // Fix for Windows ESM path resolution
56
+ const __filename = fileURLToPath(import.meta.url);
57
+ const __dirname = dirname(__filename);
58
+
59
+ // Setup logging
60
+ const LOG_FILE = join(__dirname, 'setup.log');
61
+
62
+ function logToFile(message, isError = false) {
63
+ const timestamp = new Date().toISOString();
64
+ const logMessage = `${timestamp} - ${isError ? 'ERROR: ' : ''}${message}\n`;
65
+ try {
66
+ appendFileSync(LOG_FILE, logMessage);
67
+ const jsonOutput = {
68
+ type: isError ? 'error' : 'info',
69
+ timestamp,
70
+ message
71
+ };
72
+ process.stdout.write(`${message}\n`);
73
+ } catch (err) {
74
+ process.stderr.write(`${JSON.stringify({
75
+ type: 'error',
76
+ timestamp: new Date().toISOString(),
77
+ message: `Failed to write to log file: ${err.message}`
78
+ })}\n`);
79
+ }
80
+ }
81
+
82
+ // Function to get npm version
83
+ async function getNpmVersion() {
84
+ try {
85
+ return new Promise((resolve, reject) => {
86
+ exec('npm --version', (error, stdout, stderr) => {
87
+ if (error) {
88
+ resolve('unknown');
89
+ return;
90
+ }
91
+ resolve(stdout.trim());
92
+ });
93
+ });
94
+ } catch (error) {
95
+ return 'unknown';
96
+ }
97
+ }
98
+
99
+ // Get Desktop Commander version
100
+ const getVersion = async () => {
101
+ try {
102
+ if (process.env.npm_package_version) {
103
+ return process.env.npm_package_version;
104
+ }
105
+
106
+ const versionPath = join(__dirname, 'version.js');
107
+ if (existsSync(versionPath)) {
108
+ const { VERSION } = await import(versionPath);
109
+ return VERSION;
110
+ }
111
+
112
+ const packageJsonPath = join(__dirname, 'package.json');
113
+ if (existsSync(packageJsonPath)) {
114
+ const packageJsonContent = readFileSync(packageJsonPath, 'utf8');
115
+ const packageJson = JSON.parse(packageJsonContent);
116
+ if (packageJson.version) {
117
+ return packageJson.version;
118
+ }
119
+ }
120
+
121
+ return 'unknown';
122
+ } catch (error) {
123
+ return 'unknown';
124
+ }
125
+ };
126
+ // Function to detect shell environment
127
+ function detectShell() {
128
+ if (process.platform === 'win32') {
129
+ if (process.env.TERM_PROGRAM === 'vscode') return 'vscode-terminal';
130
+ if (process.env.WT_SESSION) return 'windows-terminal';
131
+ if (process.env.SHELL?.includes('bash')) return 'git-bash';
132
+ if (process.env.TERM?.includes('xterm')) return 'xterm-on-windows';
133
+ if (process.env.ComSpec?.toLowerCase().includes('powershell')) return 'powershell';
134
+ if (process.env.PROMPT) return 'cmd';
135
+
136
+ if (process.env.WSL_DISTRO_NAME || process.env.WSLENV) {
137
+ return `wsl-${process.env.WSL_DISTRO_NAME || 'unknown'}`;
138
+ }
139
+
140
+ return 'windows-unknown';
141
+ }
142
+
143
+ if (process.env.SHELL) {
144
+ const shellPath = process.env.SHELL.toLowerCase();
145
+ if (shellPath.includes('bash')) return 'bash';
146
+ if (shellPath.includes('zsh')) return 'zsh';
147
+ if (shellPath.includes('fish')) return 'fish';
148
+ if (shellPath.includes('ksh')) return 'ksh';
149
+ if (shellPath.includes('csh')) return 'csh';
150
+ if (shellPath.includes('dash')) return 'dash';
151
+ return `other-unix-${shellPath.split('/').pop()}`;
152
+ }
153
+
154
+ if (process.env.TERM_PROGRAM) {
155
+ return process.env.TERM_PROGRAM.toLowerCase();
156
+ }
157
+
158
+ return 'unknown-shell';
159
+ }
160
+
161
+ // Function to determine execution context
162
+ function getExecutionContext() {
163
+ const isNpx = process.env.npm_lifecycle_event === 'npx' ||
164
+ process.env.npm_execpath?.includes('npx') ||
165
+ process.env._?.includes('npx') ||
166
+ import.meta.url.includes('node_modules');
167
+
168
+ const isGlobal = process.env.npm_config_global === 'true' ||
169
+ process.argv[1]?.includes('node_modules/.bin');
170
+
171
+ const isNpmScript = !!process.env.npm_lifecycle_script;
172
+
173
+ return {
174
+ runMethod: isNpx ? 'npx' : (isGlobal ? 'global' : (isNpmScript ? 'npm_script' : 'direct')),
175
+ isCI: !!process.env.CI || !!process.env.GITHUB_ACTIONS || !!process.env.TRAVIS || !!process.env.CIRCLECI,
176
+ shell: detectShell()
177
+ };
178
+ }
179
+ // Enhanced tracking properties
180
+ let npmVersionCache = null;
181
+
182
+ async function getTrackingProperties(additionalProps = {}) {
183
+ const propertiesStep = addUninstallStep('get_tracking_properties');
184
+ try {
185
+ if (npmVersionCache === null) {
186
+ npmVersionCache = await getNpmVersion();
187
+ }
188
+
189
+ const context = getExecutionContext();
190
+ const version = await getVersion();
191
+
192
+ updateUninstallStep(propertiesStep, 'completed');
193
+ return {
194
+ platform: platform(),
195
+ node_version: nodeVersion,
196
+ npm_version: npmVersionCache,
197
+ execution_context: context.runMethod,
198
+ is_ci: context.isCI,
199
+ shell: context.shell,
200
+ app_version: version,
201
+ engagement_time_msec: "100",
202
+ ...additionalProps
203
+ };
204
+ } catch (error) {
205
+ updateUninstallStep(propertiesStep, 'failed', error);
206
+ return {
207
+ platform: platform(),
208
+ node_version: nodeVersion,
209
+ error: error.message,
210
+ ...additionalProps
211
+ };
212
+ }
213
+ }
214
+ // Enhanced tracking function with retries
215
+ async function trackEvent(eventName, additionalProps = {}) {
216
+ const trackingStep = addUninstallStep(`track_event_${eventName}`);
217
+
218
+ // Check if telemetry is disabled
219
+ if (!telemetryEnabled) {
220
+ updateUninstallStep(trackingStep, 'skipped_telemetry_disabled');
221
+ return true; // Return success since this is expected behavior
222
+ }
223
+
224
+ const maxRetries = 2;
225
+ let attempt = 0;
226
+ let lastError = null;
227
+
228
+ while (attempt <= maxRetries) {
229
+ try {
230
+ attempt++;
231
+
232
+ const eventProperties = await getTrackingProperties(additionalProps);
233
+
234
+ const payload = {
235
+ client_id: uniqueUserId,
236
+ non_personalized_ads: false,
237
+ timestamp_micros: Date.now() * 1000,
238
+ events: [{
239
+ name: eventName,
240
+ params: eventProperties
241
+ }]
242
+ };
243
+
244
+ const postData = JSON.stringify(payload);
245
+
246
+ const options = {
247
+ method: 'POST',
248
+ headers: {
249
+ 'Content-Type': 'application/json',
250
+ 'Content-Length': Buffer.byteLength(postData)
251
+ }
252
+ };
253
+
254
+ const result = await postTelemetryPayload(postData, options);
255
+ if (!result.success) throw new Error('Telemetry proxy request failed');
256
+
257
+ updateUninstallStep(trackingStep, 'completed');
258
+ return result;
259
+
260
+ } catch (error) {
261
+ lastError = error;
262
+ if (attempt <= maxRetries) {
263
+ await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
264
+ }
265
+ }
266
+ }
267
+
268
+ updateUninstallStep(trackingStep, 'failed', lastError);
269
+ return false;
270
+ }
271
+
272
+ async function postTelemetryPayload(postData, options) {
273
+ for (const endpoint of [TELEMETRY_PROXY_URL, TELEMETRY_PROXY_FALLBACK_URL]) {
274
+ const result = await new Promise((resolve) => {
275
+ let settled = false;
276
+ let timeoutId;
277
+ const finish = (result) => {
278
+ if (settled) return;
279
+ settled = true;
280
+ clearTimeout(timeoutId);
281
+ resolve(result);
282
+ };
283
+ const req = https.request(endpoint, options);
284
+
285
+ timeoutId = setTimeout(() => {
286
+ req.destroy();
287
+ finish({ success: false, data: '' });
288
+ }, 5000);
289
+
290
+ req.on('error', () => {
291
+ finish({ success: false, data: '' });
292
+ });
293
+
294
+ req.on('response', (res) => {
295
+ let data = '';
296
+ res.on('data', (chunk) => {
297
+ data += chunk;
298
+ });
299
+ res.on('error', () => {
300
+ finish({ success: false, data: '' });
301
+ });
302
+ res.on('end', () => {
303
+ finish({ success: res.statusCode >= 200 && res.statusCode < 300, data });
304
+ });
305
+ res.on('close', () => {
306
+ finish({ success: false, data: '' });
307
+ });
308
+ });
309
+
310
+ req.write(postData);
311
+ req.end();
312
+ });
313
+
314
+ if (result.success) return result;
315
+ }
316
+
317
+ return { success: false, data: '' };
318
+ }
319
+ // Ensure tracking completes before process exits
320
+ async function ensureTrackingCompleted(eventName, additionalProps = {}, timeoutMs = 6000) {
321
+ return new Promise(async (resolve) => {
322
+ const timeoutId = setTimeout(() => {
323
+ resolve(false);
324
+ }, timeoutMs);
325
+
326
+ try {
327
+ await trackEvent(eventName, additionalProps);
328
+ clearTimeout(timeoutId);
329
+ resolve(true);
330
+ } catch (error) {
331
+ clearTimeout(timeoutId);
332
+ resolve(false);
333
+ }
334
+ });
335
+ }
336
+
337
+ // Setup global error handlers (will be initialized after config is loaded)
338
+ let errorHandlersInitialized = false;
339
+
340
+ function initializeErrorHandlers() {
341
+ if (errorHandlersInitialized) return;
342
+
343
+ process.on('uncaughtException', async (error) => {
344
+ if (telemetryEnabled) {
345
+ await trackEvent('uninstall_uncaught_exception', { error: error.message });
346
+ }
347
+ setTimeout(() => {
348
+ process.exit(1);
349
+ }, 1000);
350
+ });
351
+
352
+ process.on('unhandledRejection', async (reason, promise) => {
353
+ if (telemetryEnabled) {
354
+ await trackEvent('uninstall_unhandled_rejection', { error: String(reason) });
355
+ }
356
+ setTimeout(() => {
357
+ process.exit(1);
358
+ }, 1000);
359
+ });
360
+
361
+ errorHandlersInitialized = true;
362
+ }
363
+
364
+ // Track when the process is about to exit
365
+ let isExiting = false;
366
+ process.on('exit', () => {
367
+ if (!isExiting) {
368
+ isExiting = true;
369
+ }
370
+ });
371
+
372
+ // Determine OS and set appropriate config path
373
+ const os = platform();
374
+ const isWindows = os === 'win32';
375
+ let claudeConfigPath;
376
+
377
+ switch (os) {
378
+ case 'win32':
379
+ claudeConfigPath = join(process.env.APPDATA, 'Claude', 'claude_desktop_config.json');
380
+ break;
381
+ case 'darwin':
382
+ claudeConfigPath = join(homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
383
+ break;
384
+ case 'linux':
385
+ claudeConfigPath = join(homedir(), '.config', 'Claude', 'claude_desktop_config.json');
386
+ break;
387
+ default:
388
+ claudeConfigPath = join(homedir(), '.claude_desktop_config.json');
389
+ }
390
+ // Step tracking functions
391
+ function addUninstallStep(step, status = 'started', error = null) {
392
+ const timestamp = Date.now();
393
+ uninstallSteps.push({
394
+ step,
395
+ status,
396
+ timestamp,
397
+ timeFromStart: timestamp - uninstallStartTime,
398
+ error: error ? error.message || String(error) : null
399
+ });
400
+ return uninstallSteps.length - 1;
401
+ }
402
+
403
+ function updateUninstallStep(index, status, error = null) {
404
+ if (uninstallSteps[index]) {
405
+ const timestamp = Date.now();
406
+ uninstallSteps[index].status = status;
407
+ uninstallSteps[index].completionTime = timestamp;
408
+ uninstallSteps[index].timeFromStart = timestamp - uninstallStartTime;
409
+ if (error) {
410
+ uninstallSteps[index].error = error.message || String(error);
411
+ }
412
+ }
413
+ }
414
+
415
+ async function execAsync(command) {
416
+ const execStep = addUninstallStep(`exec_${command.substring(0, 20)}...`);
417
+ return new Promise((resolve, reject) => {
418
+ const actualCommand = isWindows
419
+ ? `cmd.exe /c ${command}`
420
+ : command;
421
+
422
+ exec(actualCommand, { timeout: 10000 }, (error, stdout, stderr) => {
423
+ if (error) {
424
+ updateUninstallStep(execStep, 'failed', error);
425
+ reject(error);
426
+ return;
427
+ }
428
+ updateUninstallStep(execStep, 'completed');
429
+ resolve({ stdout, stderr });
430
+ });
431
+ });
432
+ }
433
+ // Backup configuration before removal
434
+ async function createConfigBackup(configPath) {
435
+ const backupStep = addUninstallStep('create_config_backup');
436
+ try {
437
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
438
+ const backupPath = `${configPath}.backup.${timestamp}`;
439
+
440
+ if (existsSync(configPath)) {
441
+ const configData = readFileSync(configPath, 'utf8');
442
+ writeFileSync(backupPath, configData, 'utf8');
443
+ updateUninstallStep(backupStep, 'completed');
444
+ logToFile(`Configuration backup created: ${backupPath}`);
445
+ await trackEvent('uninstall_backup_created');
446
+ return backupPath;
447
+ } else {
448
+ updateUninstallStep(backupStep, 'no_config_file');
449
+ return null;
450
+ }
451
+ } catch (error) {
452
+ updateUninstallStep(backupStep, 'failed', error);
453
+ await trackEvent('uninstall_backup_failed', { error: error.message });
454
+ logToFile(`Failed to create backup: ${error.message}`, true);
455
+ return null;
456
+ }
457
+ }
458
+
459
+ // Restore configuration from backup
460
+ async function restoreFromBackup(backupPath) {
461
+ if (!backupPath || !existsSync(backupPath)) {
462
+ return false;
463
+ }
464
+
465
+ try {
466
+ const backupData = readFileSync(backupPath, 'utf8');
467
+ writeFileSync(claudeConfigPath, backupData, 'utf8');
468
+ logToFile(`Configuration restored from backup: ${backupPath}`);
469
+ await trackEvent('uninstall_backup_restored');
470
+ return true;
471
+ } catch (error) {
472
+ logToFile(`Failed to restore from backup: ${error.message}`, true);
473
+ await trackEvent('uninstall_backup_restore_failed', { error: error.message });
474
+ return false;
475
+ }
476
+ }
477
+
478
+ async function restartClaude() {
479
+ const restartStep = addUninstallStep('restart_claude');
480
+ try {
481
+ const platform = process.platform;
482
+ logToFile('Attempting to restart Claude...');
483
+ await trackEvent('uninstall_restart_claude_attempt');
484
+
485
+ // Try to kill Claude process first
486
+ const killStep = addUninstallStep('kill_claude_process');
487
+ try {
488
+ switch (platform) {
489
+ case "win32":
490
+ await execAsync(`taskkill /F /IM "Claude.exe"`);
491
+ break;
492
+ case "darwin":
493
+ await execAsync(`killall "Claude"`);
494
+ break;
495
+ case "linux":
496
+ await execAsync(`pkill -f "claude"`);
497
+ break;
498
+ }
499
+ updateUninstallStep(killStep, 'completed');
500
+ logToFile("Claude process terminated successfully");
501
+ await trackEvent('uninstall_kill_claude_success');
502
+ } catch (killError) {
503
+ updateUninstallStep(killStep, 'no_process_found', killError);
504
+ logToFile("Claude process not found or already terminated");
505
+ await trackEvent('uninstall_kill_claude_not_needed');
506
+ }
507
+
508
+ // Wait a bit to ensure process termination
509
+ await new Promise((resolve) => setTimeout(resolve, 2000));
510
+
511
+ // Try to start Claude
512
+ const startStep = addUninstallStep('start_claude_process');
513
+ try {
514
+ if (platform === "win32") {
515
+ logToFile("Windows: Claude restart skipped - please restart Claude manually");
516
+ updateUninstallStep(startStep, 'skipped');
517
+ await trackEvent('uninstall_start_claude_skipped');
518
+ } else if (platform === "darwin") {
519
+ await execAsync(`open -a "Claude"`);
520
+ updateUninstallStep(startStep, 'completed');
521
+ logToFile("✅ Claude has been restarted automatically!");
522
+ await trackEvent('uninstall_start_claude_success');
523
+ } else if (platform === "linux") {
524
+ await execAsync(`claude`);
525
+ updateUninstallStep(startStep, 'completed');
526
+ logToFile("✅ Claude has been restarted automatically!");
527
+ await trackEvent('uninstall_start_claude_success');
528
+ } else {
529
+ logToFile('To complete uninstallation, restart Claude if it\'s currently running');
530
+ updateUninstallStep(startStep, 'manual_required');
531
+ }
532
+
533
+ updateUninstallStep(restartStep, 'completed');
534
+ await trackEvent('uninstall_restart_claude_success');
535
+ } catch (startError) {
536
+ updateUninstallStep(startStep, 'failed', startError);
537
+ await trackEvent('uninstall_start_claude_error', {
538
+ error: startError.message
539
+ });
540
+ logToFile(`Could not automatically restart Claude: ${startError.message}. Please restart it manually.`);
541
+ }
542
+ } catch (error) {
543
+ updateUninstallStep(restartStep, 'failed', error);
544
+ await trackEvent('uninstall_restart_claude_error', { error: error.message });
545
+ logToFile(`Failed to restart Claude: ${error.message}. Please restart it manually.`, true);
546
+ }
547
+ }
548
+ async function removeDesktopCommanderConfig() {
549
+ const configStep = addUninstallStep('remove_mcp_config');
550
+ let backupPath = null;
551
+
552
+ try {
553
+ // Check if config file exists
554
+ if (!existsSync(claudeConfigPath)) {
555
+ updateUninstallStep(configStep, 'no_config_file');
556
+ logToFile(`Claude config file not found at: ${claudeConfigPath}`);
557
+ logToFile('✅ Desktop Commander was not configured or already removed.');
558
+ await trackEvent('uninstall_config_not_found');
559
+ return true;
560
+ }
561
+
562
+ // Create backup before making changes
563
+ backupPath = await createConfigBackup(claudeConfigPath);
564
+
565
+ // Read existing config
566
+ let config;
567
+ const readStep = addUninstallStep('read_config_file');
568
+ try {
569
+ const configData = readFileSync(claudeConfigPath, 'utf8');
570
+ config = JSON.parse(configData);
571
+ updateUninstallStep(readStep, 'completed');
572
+ } catch (readError) {
573
+ updateUninstallStep(readStep, 'failed', readError);
574
+ await trackEvent('uninstall_config_read_error', { error: readError.message });
575
+ throw new Error(`Failed to read config file: ${readError.message}`);
576
+ }
577
+
578
+ // Check if mcpServers exists
579
+ if (!config.mcpServers) {
580
+ updateUninstallStep(configStep, 'no_mcp_servers');
581
+ logToFile('No MCP servers configured in Claude.');
582
+ logToFile('✅ Desktop Commander was not configured or already removed.');
583
+ await trackEvent('uninstall_no_mcp_servers');
584
+ return true;
585
+ }
586
+ // Track what we're removing
587
+ const serversToRemove = [];
588
+
589
+ if (config.mcpServers["desktop-commander"]) {
590
+ serversToRemove.push("desktop-commander");
591
+ }
592
+
593
+ if (serversToRemove.length === 0) {
594
+ updateUninstallStep(configStep, 'not_found');
595
+ logToFile('Desktop Commander MCP server not found in configuration.');
596
+ logToFile('✅ Desktop Commander was not configured or already removed.');
597
+ await trackEvent('uninstall_server_not_found');
598
+ return true;
599
+ }
600
+
601
+ // Remove the server configurations
602
+ const removeStep = addUninstallStep('remove_server_configs');
603
+ try {
604
+ serversToRemove.forEach(serverName => {
605
+ delete config.mcpServers[serverName];
606
+ logToFile(`Removed "${serverName}" from Claude configuration`);
607
+ });
608
+
609
+ updateUninstallStep(removeStep, 'completed');
610
+ await trackEvent('uninstall_servers_removed');
611
+ } catch (removeError) {
612
+ updateUninstallStep(removeStep, 'failed', removeError);
613
+ await trackEvent('uninstall_servers_remove_error', { error: removeError.message });
614
+ throw new Error(`Failed to remove server configs: ${removeError.message}`);
615
+ } // Write the updated config back
616
+ const writeStep = addUninstallStep('write_updated_config');
617
+ try {
618
+ writeFileSync(claudeConfigPath, JSON.stringify(config, null, 2), 'utf8');
619
+ updateUninstallStep(writeStep, 'completed');
620
+ updateUninstallStep(configStep, 'completed');
621
+ logToFile('✅ Desktop Commander successfully removed from Claude configuration');
622
+ logToFile(`Configuration updated at: ${claudeConfigPath}`);
623
+ await trackEvent('uninstall_config_updated');
624
+ } catch (writeError) {
625
+ updateUninstallStep(writeStep, 'failed', writeError);
626
+ await trackEvent('uninstall_config_write_error', { error: writeError.message });
627
+
628
+ // Try to restore from backup
629
+ if (backupPath) {
630
+ logToFile('Attempting to restore configuration from backup...');
631
+ const restored = await restoreFromBackup(backupPath);
632
+ if (restored) {
633
+ throw new Error(`Failed to write updated config, but backup was restored: ${writeError.message}`);
634
+ } else {
635
+ throw new Error(`Failed to write updated config and backup restoration failed: ${writeError.message}`);
636
+ }
637
+ } else {
638
+ throw new Error(`Failed to write updated config: ${writeError.message}`);
639
+ }
640
+ }
641
+
642
+ return true;
643
+ } catch (error) {
644
+ updateUninstallStep(configStep, 'failed', error);
645
+ await trackEvent('uninstall_config_error', { error: error.message });
646
+ logToFile(`Error removing Desktop Commander configuration: ${error.message}`, true);
647
+
648
+ // Try to restore from backup if we have one
649
+ if (backupPath) {
650
+ logToFile('Attempting to restore configuration from backup...');
651
+ await restoreFromBackup(backupPath);
652
+ }
653
+
654
+ return false;
655
+ }
656
+ }
657
+ // Main uninstall function
658
+ export default async function uninstall() {
659
+ // Initialize clientId and telemetry settings from existing config
660
+ const configSettings = await getConfigSettings();
661
+ uniqueUserId = configSettings.clientId;
662
+ telemetryEnabled = configSettings.telemetryEnabled;
663
+
664
+ // Initialize error handlers now that telemetry setting is known
665
+ initializeErrorHandlers();
666
+
667
+ // Log telemetry status for transparency
668
+ if (!telemetryEnabled) {
669
+ logToFile('Telemetry disabled - no analytics will be sent');
670
+ }
671
+
672
+ // Initial tracking (only if telemetry enabled)
673
+ await ensureTrackingCompleted('uninstall_start');
674
+
675
+ const mainStep = addUninstallStep('main_uninstall');
676
+
677
+ try {
678
+ logToFile('Starting Desktop Commander uninstallation...');
679
+
680
+ // Remove the server configuration from Claude
681
+ const configRemoved = await removeDesktopCommanderConfig();
682
+
683
+ if (configRemoved) {
684
+ // Try to restart Claude
685
+ // await restartClaude();
686
+
687
+ updateUninstallStep(mainStep, 'completed');
688
+
689
+ const appVersion = await getVersion();
690
+ logToFile(`\n✅ Desktop Commander has been successfully uninstalled!`);
691
+ logToFile('The MCP server has been removed from Claude\'s configuration.');
692
+
693
+ logToFile('\nIf you want to reinstall later, you can run:');
694
+ logToFile('npx @wonderwhy-er/desktop-commander@latest setup');
695
+
696
+ logToFile('\nThank you for using Desktop Commander! 👋\n');
697
+
698
+ // Send final tracking event
699
+ await ensureTrackingCompleted('uninstall_complete');
700
+
701
+ return true;
702
+ } else {
703
+ updateUninstallStep(mainStep, 'failed_config_removal');
704
+
705
+ logToFile('\n❌ Uninstallation completed with errors.');
706
+ logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.');
707
+ logToFile(`Configuration file location: ${claudeConfigPath}\n`);
708
+
709
+ await ensureTrackingCompleted('uninstall_partial_failure');
710
+
711
+ return false;
712
+ }
713
+ } catch (error) {
714
+ updateUninstallStep(mainStep, 'fatal_error', error);
715
+
716
+ await ensureTrackingCompleted('uninstall_fatal_error', {
717
+ error: error.message,
718
+ error_stack: error.stack,
719
+ last_successful_step: uninstallSteps.filter(s => s.status === 'completed').pop()?.step || 'none'
720
+ });
721
+
722
+ logToFile(`Fatal error during uninstallation: ${error.message}`, true);
723
+ logToFile('\n❌ Uninstallation failed.');
724
+ logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.');
725
+ logToFile(`Configuration file location: ${claudeConfigPath}\n`);
726
+
727
+ return false;
728
+ }
729
+ }
730
+
731
+ // Allow direct execution
732
+ if (process.argv.length >= 2 && process.argv[1] === fileURLToPath(import.meta.url)) {
733
+ uninstall().then(success => {
734
+ if (!success) {
735
+ process.exit(1);
736
+ }
737
+ }).catch(async error => {
738
+ await ensureTrackingCompleted('uninstall_execution_error', {
739
+ error: error.message,
740
+ error_stack: error.stack
741
+ });
742
+ logToFile(`Fatal error: ${error}`, true);
743
+ process.exit(1);
744
+ });
745
+ }