@wonderwhy-er/desktop-commander 0.2.52 → 0.3.1-alpha.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 (137) 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.d.ts +7 -2
  5. package/dist/command-manager.js +16 -11
  6. package/dist/config-field-definitions.js +0 -0
  7. package/dist/config-manager.d.ts +55 -3
  8. package/dist/config-manager.js +329 -87
  9. package/dist/config-recovery.d.ts +28 -0
  10. package/dist/config-recovery.js +81 -0
  11. package/dist/config.d.ts +1 -0
  12. package/dist/config.js +9 -0
  13. package/dist/custom-stdio.js +0 -0
  14. package/dist/data/onboarding-prompts.json +70 -70
  15. package/dist/error-handlers.js +0 -0
  16. package/dist/handlers/filesystem-handlers.d.ts +1 -1
  17. package/dist/handlers/filesystem-handlers.js +28 -18
  18. package/dist/handlers/search-answers.d.ts +58 -0
  19. package/dist/handlers/search-answers.js +172 -0
  20. package/dist/handlers/search-handlers.js +4 -92
  21. package/dist/index.js +14 -7
  22. package/dist/npm-scripts/remote.js +36 -22
  23. package/dist/remote-device/desktop-commander-integration.js +19 -25
  24. package/dist/remote-device/device.d.ts +14 -0
  25. package/dist/remote-device/device.js +137 -30
  26. package/dist/remote-device/diagnostics/device-log.d.ts +63 -0
  27. package/dist/remote-device/diagnostics/device-log.js +219 -0
  28. package/dist/remote-device/diagnostics/redact.d.ts +1 -0
  29. package/dist/remote-device/diagnostics/redact.js +76 -0
  30. package/dist/remote-device/diagnostics/report.d.ts +118 -0
  31. package/dist/remote-device/diagnostics/report.js +748 -0
  32. package/dist/remote-device/diagnostics/upload.d.ts +11 -0
  33. package/dist/remote-device/diagnostics/upload.js +59 -0
  34. package/dist/remote-device/remote-channel.d.ts +12 -0
  35. package/dist/remote-device/remote-channel.js +55 -8
  36. package/dist/remote-device/scripts/blocking-offline-update.js +133 -96
  37. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  38. package/dist/remote-device/transport-telemetry.js +48 -0
  39. package/dist/search-manager.d.ts +239 -27
  40. package/dist/search-manager.js +746 -312
  41. package/dist/server.js +654 -621
  42. package/dist/setup-claude-server.js +942 -942
  43. package/dist/terminal-manager.d.ts +138 -21
  44. package/dist/terminal-manager.js +300 -215
  45. package/dist/tools/config.d.ts +1 -1
  46. package/dist/tools/config.js +21 -70
  47. package/dist/tools/edit.js +14 -6
  48. package/dist/tools/filesystem.d.ts +30 -6
  49. package/dist/tools/filesystem.js +246 -140
  50. package/dist/tools/fuzzySearch.js +9 -9
  51. package/dist/tools/improved-process-tools.d.ts +9 -3
  52. package/dist/tools/improved-process-tools.js +181 -78
  53. package/dist/tools/pdf/extract-images.d.ts +2 -0
  54. package/dist/tools/pdf/extract-images.js +4 -1
  55. package/dist/tools/pdf/index.d.ts +5 -3
  56. package/dist/tools/pdf/index.js +4 -3
  57. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  58. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  59. package/dist/tools/pdf/manipulations.d.ts +12 -1
  60. package/dist/tools/pdf/manipulations.js +17 -4
  61. package/dist/tools/pdf/markdown.d.ts +96 -0
  62. package/dist/tools/pdf/markdown.js +485 -20
  63. package/dist/tools/pdf/utils.d.ts +2 -2
  64. package/dist/tools/pdf/utils.js +4 -4
  65. package/dist/tools/process.js +8 -5
  66. package/dist/tools/prompts.js +1 -1
  67. package/dist/tools/schemas.d.ts +1 -1
  68. package/dist/tools/schemas.js +15 -6
  69. package/dist/track-installation.js +387 -387
  70. package/dist/types.d.ts +1 -1
  71. package/dist/types.js +0 -0
  72. package/dist/ui/config-editor/config-editor-runtime.js +6 -6
  73. package/dist/ui/config-editor/index.html +13 -13
  74. package/dist/ui/config-editor/src/app.js +32 -45
  75. package/dist/ui/config-editor/src/array-modal.js +32 -32
  76. package/dist/ui/config-editor/styles.css +586 -586
  77. package/dist/ui/file-preview/index.html +16 -16
  78. package/dist/ui/file-preview/src/app.js +8 -8
  79. package/dist/ui/file-preview/src/document-layout.js +31 -31
  80. package/dist/ui/file-preview/src/document-outline.js +8 -8
  81. package/dist/ui/file-preview/src/markdown/conflict-dialog.js +33 -33
  82. package/dist/ui/file-preview/src/markdown/controller.js +9 -9
  83. package/dist/ui/file-preview/src/markdown/editor.js +31 -31
  84. package/dist/ui/file-preview/styles.css +1630 -1630
  85. package/dist/uninstall-claude-server.js +745 -745
  86. package/dist/utils/ab-test.js +27 -9
  87. package/dist/utils/atomic-write.d.ts +14 -0
  88. package/dist/utils/atomic-write.js +80 -0
  89. package/dist/utils/capture.d.ts +17 -1
  90. package/dist/utils/capture.js +177 -68
  91. package/dist/utils/exit-process.d.ts +24 -0
  92. package/dist/utils/exit-process.js +31 -0
  93. package/dist/utils/feature-flags.js +2 -1
  94. package/dist/utils/files/base.d.ts +3 -1
  95. package/dist/utils/files/binary.js +4 -4
  96. package/dist/utils/files/docx.d.ts +3 -0
  97. package/dist/utils/files/docx.js +24 -9
  98. package/dist/utils/files/excel.d.ts +10 -0
  99. package/dist/utils/files/excel.js +96 -36
  100. package/dist/utils/files/factory.d.ts +22 -1
  101. package/dist/utils/files/factory.js +59 -4
  102. package/dist/utils/files/image.d.ts +12 -4
  103. package/dist/utils/files/image.js +19 -8
  104. package/dist/utils/files/index.d.ts +5 -3
  105. package/dist/utils/files/index.js +4 -3
  106. package/dist/utils/files/pdf.js +18 -36
  107. package/dist/utils/files/text.d.ts +21 -5
  108. package/dist/utils/files/text.js +90 -86
  109. package/dist/utils/internal-facts.d.ts +3 -0
  110. package/dist/utils/internal-facts.js +23 -0
  111. package/dist/utils/lazy-package.d.ts +23 -0
  112. package/dist/utils/lazy-package.js +42 -0
  113. package/dist/utils/open-browser.js +2 -1
  114. package/dist/utils/process-detection.d.ts +24 -5
  115. package/dist/utils/process-detection.js +199 -89
  116. package/dist/utils/process-tree.d.ts +14 -0
  117. package/dist/utils/process-tree.js +223 -0
  118. package/dist/utils/rename.d.ts +9 -0
  119. package/dist/utils/rename.js +74 -0
  120. package/dist/utils/ripgrep-resolver.js +9 -14
  121. package/dist/utils/shell.d.ts +42 -0
  122. package/dist/utils/shell.js +187 -0
  123. package/dist/utils/system-info.js +99 -97
  124. package/dist/utils/trackTools.js +2 -1
  125. package/dist/utils/usageTracker.js +49 -49
  126. package/dist/version.d.ts +1 -1
  127. package/dist/version.js +1 -1
  128. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  129. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  130. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  131. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  132. package/package.json +10 -3
  133. package/vendor/telemetry-contract/README.md +56 -0
  134. package/vendor/telemetry-contract/package.json +32 -0
  135. package/vendor/telemetry-contract/transport.d.ts +38 -0
  136. package/vendor/telemetry-contract/transport.js +164 -0
  137. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -1,387 +1,387 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Installation Source Tracking Script
5
- * Runs during npm install to detect how Desktop Commander was installed
6
- *
7
- * Debug logging can be enabled with:
8
- * - DEBUG=desktop-commander npm install
9
- * - DEBUG=* npm install
10
- * - NODE_ENV=development npm install
11
- * - DC_DEBUG=true npm install
12
- */
13
-
14
- import { randomUUID } from 'crypto';
15
- import * as https from 'https';
16
- import { platform } from 'os';
17
- import path from 'path';
18
- import { fileURLToPath } from 'url';
19
-
20
- // Get current file directory
21
- const __filename = fileURLToPath(import.meta.url);
22
- const __dirname = path.dirname(__filename);
23
-
24
- // Debug logging utility - configurable via environment variables
25
- const DEBUG_ENABLED = process.env.DEBUG === 'desktop-commander' ||
26
- process.env.DEBUG === '*' ||
27
- process.env.NODE_ENV === 'development' ||
28
- process.env.DC_DEBUG === 'true';
29
-
30
- const debug = (...args) => {
31
- if (DEBUG_ENABLED) {
32
- console.log('[Desktop Commander Debug]', ...args);
33
- }
34
- };
35
-
36
- const log = (...args) => {
37
- // Always show important messages, but prefix differently for debug vs production
38
- if (DEBUG_ENABLED) {
39
- console.log('[Desktop Commander]', ...args);
40
- }
41
- };
42
-
43
- /**
44
- * Get the client ID from the Desktop Commander config file, or generate a new one
45
- */
46
- async function getClientId() {
47
- try {
48
- const { homedir } = await import('os');
49
- const { join } = await import('path');
50
- const fs = await import('fs');
51
-
52
- const USER_HOME = homedir();
53
- const CONFIG_DIR = join(USER_HOME, '.claude-server-commander');
54
- const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
55
-
56
- // Try to read existing config
57
- if (fs.existsSync(CONFIG_FILE)) {
58
- const configData = fs.readFileSync(CONFIG_FILE, 'utf8');
59
- const config = JSON.parse(configData);
60
- if (config.clientId) {
61
- debug(`Using existing clientId from config: ${config.clientId.substring(0, 8)}...`);
62
- return config.clientId;
63
- }
64
- }
65
-
66
- debug('No existing clientId found, generating new one');
67
- // Fallback to random UUID if config doesn't exist or lacks clientId
68
- return randomUUID();
69
- } catch (error) {
70
- debug(`Error reading config file: ${error.message}, using random UUID`);
71
- // If anything goes wrong, fall back to random UUID
72
- return randomUUID();
73
- }
74
- }
75
-
76
- // Telemetry proxy configuration (same as setup script)
77
- const TELEMETRY_PROXY_URL = 'https://telemetry.desktopcommander.app/mp/collect';
78
- const TELEMETRY_PROXY_FALLBACK_URL = 'https://dc-telemetry-proxy-83847352264.europe-west1.run.app/mp/collect';
79
-
80
- /**
81
- * Detect installation source from environment and process context
82
- */
83
- async function detectInstallationSource() {
84
- // Check npm environment variables for clues
85
- const npmConfigUserAgent = process.env.npm_config_user_agent || '';
86
- const npmExecpath = process.env.npm_execpath || '';
87
- const npmCommand = process.env.npm_command || '';
88
- const npmLifecycleEvent = process.env.npm_lifecycle_event || '';
89
-
90
- // Check process arguments and parent commands
91
- const processArgs = process.argv.join(' ');
92
- const processTitle = process.title || '';
93
-
94
- debug('Installation source detection...');
95
- debug(`npm_config_user_agent: ${npmConfigUserAgent}`);
96
- debug(`npm_execpath: ${npmExecpath}`);
97
- debug(`npm_command: ${npmCommand}`);
98
- debug(`npm_lifecycle_event: ${npmLifecycleEvent}`);
99
- debug(`process.argv: ${processArgs}`);
100
- debug(`process.title: ${processTitle}`);
101
-
102
- // Try to get parent process information
103
- let parentProcessInfo = null;
104
- try {
105
- const { execSync } = await import('child_process');
106
- const ppid = process.ppid;
107
- if (ppid && process.platform !== 'win32') {
108
- // Get parent process command line on Unix systems
109
- const parentCmd = execSync(`ps -p ${ppid} -o command=`, { encoding: 'utf8' }).trim();
110
- parentProcessInfo = parentCmd;
111
- debug(`parent process: ${parentCmd}`);
112
- }
113
- } catch (error) {
114
- debug(`Could not get parent process info: ${error.message}`);
115
- }
116
-
117
- // Smithery detection - look for smithery in the process chain
118
- const smitheryIndicators = [
119
- npmConfigUserAgent.includes('smithery'),
120
- npmExecpath.includes('smithery'),
121
- processArgs.includes('smithery'),
122
- processArgs.includes('@smithery/cli'),
123
- processTitle.includes('smithery'),
124
- parentProcessInfo && parentProcessInfo.includes('smithery'),
125
- parentProcessInfo && parentProcessInfo.includes('@smithery/cli')
126
- ];
127
-
128
- if (smitheryIndicators.some(indicator => indicator)) {
129
- return {
130
- source: 'smithery',
131
- details: {
132
- detection_method: 'process_chain',
133
- user_agent: npmConfigUserAgent,
134
- exec_path: npmExecpath,
135
- command: npmCommand,
136
- parent_process: parentProcessInfo || 'unknown',
137
- process_args: processArgs
138
- }
139
- };
140
- }
141
-
142
- // Direct NPX usage
143
- if (npmCommand === 'exec' || processArgs.includes('npx')) {
144
- return {
145
- source: 'npx-direct',
146
- details: {
147
- user_agent: npmConfigUserAgent,
148
- command: npmCommand,
149
- lifecycle_event: npmLifecycleEvent
150
- }
151
- };
152
- }
153
-
154
- // Regular npm install
155
- if (npmCommand === 'install' || npmLifecycleEvent === 'postinstall') {
156
- return {
157
- source: 'npm-install',
158
- details: {
159
- user_agent: npmConfigUserAgent,
160
- command: npmCommand,
161
- lifecycle_event: npmLifecycleEvent
162
- }
163
- };
164
- }
165
-
166
- // GitHub Codespaces
167
- if (process.env.CODESPACES) {
168
- return {
169
- source: 'github-codespaces',
170
- details: {
171
- codespace: process.env.CODESPACE_NAME || 'unknown'
172
- }
173
- };
174
- }
175
-
176
- // VS Code
177
- if (process.env.VSCODE_PID || process.env.TERM_PROGRAM === 'vscode') {
178
- return {
179
- source: 'vscode',
180
- details: {
181
- term_program: process.env.TERM_PROGRAM,
182
- vscode_pid: process.env.VSCODE_PID
183
- }
184
- };
185
- }
186
-
187
- // GitPod
188
- if (process.env.GITPOD_WORKSPACE_ID) {
189
- return {
190
- source: 'gitpod',
191
- details: {
192
- workspace_id: process.env.GITPOD_WORKSPACE_ID.substring(0, 8) + '...' // Truncate for privacy
193
- }
194
- };
195
- }
196
-
197
- // CI/CD environments
198
- if (process.env.CI) {
199
- if (process.env.GITHUB_ACTIONS) {
200
- return {
201
- source: 'github-actions',
202
- details: {
203
- repository: process.env.GITHUB_REPOSITORY,
204
- workflow: process.env.GITHUB_WORKFLOW
205
- }
206
- };
207
- }
208
- if (process.env.GITLAB_CI) {
209
- return {
210
- source: 'gitlab-ci',
211
- details: {
212
- project: process.env.CI_PROJECT_NAME
213
- }
214
- };
215
- }
216
- if (process.env.JENKINS_URL) {
217
- return {
218
- source: 'jenkins',
219
- details: {
220
- job: process.env.JOB_NAME
221
- }
222
- };
223
- }
224
- return {
225
- source: 'ci-cd-other',
226
- details: {
227
- ci_env: 'unknown'
228
- }
229
- };
230
- }
231
-
232
- // Docker detection
233
- if (process.env.DOCKER_CONTAINER) {
234
- return {
235
- source: 'docker',
236
- details: {
237
- container_id: process.env.HOSTNAME?.substring(0, 8) + '...' || 'unknown'
238
- }
239
- };
240
- }
241
-
242
- // Check for .dockerenv file (need to use fs import)
243
- try {
244
- const fs = await import('fs');
245
- if (fs.existsSync('/.dockerenv')) {
246
- return {
247
- source: 'docker',
248
- details: {
249
- container_id: process.env.HOSTNAME?.substring(0, 8) + '...' || 'unknown'
250
- }
251
- };
252
- }
253
- } catch (error) {
254
- // Ignore fs errors
255
- }
256
-
257
- // Default fallback
258
- return {
259
- source: 'unknown',
260
- details: {
261
- user_agent: npmConfigUserAgent || 'none',
262
- command: npmCommand || 'none',
263
- lifecycle: npmLifecycleEvent || 'none'
264
- }
265
- };
266
- }
267
-
268
- /**
269
- * Send installation tracking to telemetry proxy
270
- */
271
- async function trackInstallation(installationData) {
272
- try {
273
- const uniqueUserId = await getClientId();
274
- log("user id", uniqueUserId)
275
- // Prepare telemetry payload
276
- const payload = {
277
- client_id: uniqueUserId,
278
- non_personalized_ads: false,
279
- timestamp_micros: Date.now() * 1000,
280
- events: [{
281
- name: 'package_installed',
282
- params: {
283
- timestamp: new Date().toISOString(),
284
- platform: platform(),
285
- installation_source: installationData.source,
286
- installation_details: JSON.stringify(installationData.details),
287
- package_name: '@wonderwhy-er/desktop-commander',
288
- install_method: 'npm-lifecycle',
289
- node_version: process.version,
290
- npm_version: process.env.npm_version || 'unknown'
291
- }
292
- }]
293
- };
294
-
295
- const postData = JSON.stringify(payload);
296
-
297
- const options = {
298
- method: 'POST',
299
- headers: {
300
- 'Content-Type': 'application/json',
301
- 'Content-Length': Buffer.byteLength(postData)
302
- }
303
- };
304
-
305
- const sent = await postTelemetryPayload(TELEMETRY_PROXY_URL, postData, options);
306
- if (!sent) {
307
- await postTelemetryPayload(TELEMETRY_PROXY_FALLBACK_URL, postData, options);
308
- }
309
- log(`Installation tracked: ${installationData.source}`);
310
-
311
- } catch (error) {
312
- debug(`Failed to track installation: ${error.message}`);
313
- // Don't fail the installation process
314
- }
315
- }
316
-
317
- // TODO(dedup): postTelemetryPayload is copy-pasted across setup/uninstall/track
318
- // scripts + a variant in src/utils/capture.ts. Consolidate into one shared module.
319
- // TODO(timeout): per-endpoint timeout here is 5s, but ensureTrackingCompleted caps
320
- // the whole flow at 6s — so if the primary times out, the fallback gets ~1s and
321
- // almost never completes. Lower per-endpoint timeout (capture.ts uses 3s) or raise
322
- // the overall budget so the fallback is actually usable.
323
- async function postTelemetryPayload(endpoint, postData, options) {
324
- return await new Promise((resolve) => {
325
- let settled = false;
326
- let timeoutId;
327
- const finish = (result) => {
328
- if (settled) return;
329
- settled = true;
330
- clearTimeout(timeoutId);
331
- resolve(result);
332
- };
333
- const req = https.request(endpoint, options);
334
-
335
- timeoutId = setTimeout(() => {
336
- req.destroy();
337
- finish(false);
338
- }, 5000);
339
-
340
- req.on('error', (error) => {
341
- debug(`Telemetry error: ${error.message}`);
342
- finish(false);
343
- });
344
-
345
- req.on('response', (res) => {
346
- res.on('data', () => {});
347
- res.on('error', (error) => {
348
- debug(`Telemetry response error: ${error.message}`);
349
- finish(false);
350
- });
351
- res.on('end', () => {
352
- finish(res.statusCode >= 200 && res.statusCode < 300);
353
- });
354
- res.on('close', () => {
355
- finish(false);
356
- });
357
- });
358
-
359
- req.write(postData);
360
- req.end();
361
- });
362
- }
363
-
364
- /**
365
- * Main execution
366
- */
367
- async function main() {
368
- try {
369
- log('Package installation detected');
370
-
371
- const installationData = await detectInstallationSource();
372
- log(`Installation source: ${installationData.source}`);
373
-
374
- await trackInstallation(installationData);
375
-
376
- } catch (error) {
377
- debug(`Installation tracking error: ${error.message}`);
378
- // Don't fail the installation
379
- }
380
- }
381
-
382
- // Only run if this script is executed directly (not imported)
383
- if (import.meta.url === `file://${process.argv[1]}`) {
384
- main();
385
- }
386
-
387
- export { detectInstallationSource, trackInstallation };
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Installation Source Tracking Script
5
+ * Runs during npm install to detect how Desktop Commander was installed
6
+ *
7
+ * Debug logging can be enabled with:
8
+ * - DEBUG=desktop-commander npm install
9
+ * - DEBUG=* npm install
10
+ * - NODE_ENV=development npm install
11
+ * - DC_DEBUG=true npm install
12
+ */
13
+
14
+ import { randomUUID } from 'crypto';
15
+ import * as https from 'https';
16
+ import { platform } from 'os';
17
+ import path from 'path';
18
+ import { fileURLToPath } from 'url';
19
+
20
+ // Get current file directory
21
+ const __filename = fileURLToPath(import.meta.url);
22
+ const __dirname = path.dirname(__filename);
23
+
24
+ // Debug logging utility - configurable via environment variables
25
+ const DEBUG_ENABLED = process.env.DEBUG === 'desktop-commander' ||
26
+ process.env.DEBUG === '*' ||
27
+ process.env.NODE_ENV === 'development' ||
28
+ process.env.DC_DEBUG === 'true';
29
+
30
+ const debug = (...args) => {
31
+ if (DEBUG_ENABLED) {
32
+ console.log('[Desktop Commander Debug]', ...args);
33
+ }
34
+ };
35
+
36
+ const log = (...args) => {
37
+ // Always show important messages, but prefix differently for debug vs production
38
+ if (DEBUG_ENABLED) {
39
+ console.log('[Desktop Commander]', ...args);
40
+ }
41
+ };
42
+
43
+ /**
44
+ * Get the client ID from the Desktop Commander config file, or generate a new one
45
+ */
46
+ async function getClientId() {
47
+ try {
48
+ const { homedir } = await import('os');
49
+ const { join } = await import('path');
50
+ const fs = await import('fs');
51
+
52
+ const USER_HOME = homedir();
53
+ const CONFIG_DIR = join(USER_HOME, '.claude-server-commander');
54
+ const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
55
+
56
+ // Try to read existing config
57
+ if (fs.existsSync(CONFIG_FILE)) {
58
+ const configData = fs.readFileSync(CONFIG_FILE, 'utf8');
59
+ const config = JSON.parse(configData);
60
+ if (config.clientId) {
61
+ debug(`Using existing clientId from config: ${config.clientId.substring(0, 8)}...`);
62
+ return config.clientId;
63
+ }
64
+ }
65
+
66
+ debug('No existing clientId found, generating new one');
67
+ // Fallback to random UUID if config doesn't exist or lacks clientId
68
+ return randomUUID();
69
+ } catch (error) {
70
+ debug(`Error reading config file: ${error.message}, using random UUID`);
71
+ // If anything goes wrong, fall back to random UUID
72
+ return randomUUID();
73
+ }
74
+ }
75
+
76
+ // Telemetry proxy configuration (same as setup script)
77
+ const TELEMETRY_PROXY_URL = 'https://telemetry.desktopcommander.app/mp/collect';
78
+ const TELEMETRY_PROXY_FALLBACK_URL = 'https://dc-telemetry-proxy-83847352264.europe-west1.run.app/mp/collect';
79
+
80
+ /**
81
+ * Detect installation source from environment and process context
82
+ */
83
+ async function detectInstallationSource() {
84
+ // Check npm environment variables for clues
85
+ const npmConfigUserAgent = process.env.npm_config_user_agent || '';
86
+ const npmExecpath = process.env.npm_execpath || '';
87
+ const npmCommand = process.env.npm_command || '';
88
+ const npmLifecycleEvent = process.env.npm_lifecycle_event || '';
89
+
90
+ // Check process arguments and parent commands
91
+ const processArgs = process.argv.join(' ');
92
+ const processTitle = process.title || '';
93
+
94
+ debug('Installation source detection...');
95
+ debug(`npm_config_user_agent: ${npmConfigUserAgent}`);
96
+ debug(`npm_execpath: ${npmExecpath}`);
97
+ debug(`npm_command: ${npmCommand}`);
98
+ debug(`npm_lifecycle_event: ${npmLifecycleEvent}`);
99
+ debug(`process.argv: ${processArgs}`);
100
+ debug(`process.title: ${processTitle}`);
101
+
102
+ // Try to get parent process information
103
+ let parentProcessInfo = null;
104
+ try {
105
+ const { execSync } = await import('child_process');
106
+ const ppid = process.ppid;
107
+ if (ppid && process.platform !== 'win32') {
108
+ // Get parent process command line on Unix systems
109
+ const parentCmd = execSync(`ps -p ${ppid} -o command=`, { encoding: 'utf8' }).trim();
110
+ parentProcessInfo = parentCmd;
111
+ debug(`parent process: ${parentCmd}`);
112
+ }
113
+ } catch (error) {
114
+ debug(`Could not get parent process info: ${error.message}`);
115
+ }
116
+
117
+ // Smithery detection - look for smithery in the process chain
118
+ const smitheryIndicators = [
119
+ npmConfigUserAgent.includes('smithery'),
120
+ npmExecpath.includes('smithery'),
121
+ processArgs.includes('smithery'),
122
+ processArgs.includes('@smithery/cli'),
123
+ processTitle.includes('smithery'),
124
+ parentProcessInfo && parentProcessInfo.includes('smithery'),
125
+ parentProcessInfo && parentProcessInfo.includes('@smithery/cli')
126
+ ];
127
+
128
+ if (smitheryIndicators.some(indicator => indicator)) {
129
+ return {
130
+ source: 'smithery',
131
+ details: {
132
+ detection_method: 'process_chain',
133
+ user_agent: npmConfigUserAgent,
134
+ exec_path: npmExecpath,
135
+ command: npmCommand,
136
+ parent_process: parentProcessInfo || 'unknown',
137
+ process_args: processArgs
138
+ }
139
+ };
140
+ }
141
+
142
+ // Direct NPX usage
143
+ if (npmCommand === 'exec' || processArgs.includes('npx')) {
144
+ return {
145
+ source: 'npx-direct',
146
+ details: {
147
+ user_agent: npmConfigUserAgent,
148
+ command: npmCommand,
149
+ lifecycle_event: npmLifecycleEvent
150
+ }
151
+ };
152
+ }
153
+
154
+ // Regular npm install
155
+ if (npmCommand === 'install' || npmLifecycleEvent === 'postinstall') {
156
+ return {
157
+ source: 'npm-install',
158
+ details: {
159
+ user_agent: npmConfigUserAgent,
160
+ command: npmCommand,
161
+ lifecycle_event: npmLifecycleEvent
162
+ }
163
+ };
164
+ }
165
+
166
+ // GitHub Codespaces
167
+ if (process.env.CODESPACES) {
168
+ return {
169
+ source: 'github-codespaces',
170
+ details: {
171
+ codespace: process.env.CODESPACE_NAME || 'unknown'
172
+ }
173
+ };
174
+ }
175
+
176
+ // VS Code
177
+ if (process.env.VSCODE_PID || process.env.TERM_PROGRAM === 'vscode') {
178
+ return {
179
+ source: 'vscode',
180
+ details: {
181
+ term_program: process.env.TERM_PROGRAM,
182
+ vscode_pid: process.env.VSCODE_PID
183
+ }
184
+ };
185
+ }
186
+
187
+ // GitPod
188
+ if (process.env.GITPOD_WORKSPACE_ID) {
189
+ return {
190
+ source: 'gitpod',
191
+ details: {
192
+ workspace_id: process.env.GITPOD_WORKSPACE_ID.substring(0, 8) + '...' // Truncate for privacy
193
+ }
194
+ };
195
+ }
196
+
197
+ // CI/CD environments
198
+ if (process.env.CI) {
199
+ if (process.env.GITHUB_ACTIONS) {
200
+ return {
201
+ source: 'github-actions',
202
+ details: {
203
+ repository: process.env.GITHUB_REPOSITORY,
204
+ workflow: process.env.GITHUB_WORKFLOW
205
+ }
206
+ };
207
+ }
208
+ if (process.env.GITLAB_CI) {
209
+ return {
210
+ source: 'gitlab-ci',
211
+ details: {
212
+ project: process.env.CI_PROJECT_NAME
213
+ }
214
+ };
215
+ }
216
+ if (process.env.JENKINS_URL) {
217
+ return {
218
+ source: 'jenkins',
219
+ details: {
220
+ job: process.env.JOB_NAME
221
+ }
222
+ };
223
+ }
224
+ return {
225
+ source: 'ci-cd-other',
226
+ details: {
227
+ ci_env: 'unknown'
228
+ }
229
+ };
230
+ }
231
+
232
+ // Docker detection
233
+ if (process.env.DOCKER_CONTAINER) {
234
+ return {
235
+ source: 'docker',
236
+ details: {
237
+ container_id: process.env.HOSTNAME?.substring(0, 8) + '...' || 'unknown'
238
+ }
239
+ };
240
+ }
241
+
242
+ // Check for .dockerenv file (need to use fs import)
243
+ try {
244
+ const fs = await import('fs');
245
+ if (fs.existsSync('/.dockerenv')) {
246
+ return {
247
+ source: 'docker',
248
+ details: {
249
+ container_id: process.env.HOSTNAME?.substring(0, 8) + '...' || 'unknown'
250
+ }
251
+ };
252
+ }
253
+ } catch (error) {
254
+ // Ignore fs errors
255
+ }
256
+
257
+ // Default fallback
258
+ return {
259
+ source: 'unknown',
260
+ details: {
261
+ user_agent: npmConfigUserAgent || 'none',
262
+ command: npmCommand || 'none',
263
+ lifecycle: npmLifecycleEvent || 'none'
264
+ }
265
+ };
266
+ }
267
+
268
+ /**
269
+ * Send installation tracking to telemetry proxy
270
+ */
271
+ async function trackInstallation(installationData) {
272
+ try {
273
+ const uniqueUserId = await getClientId();
274
+ log("user id", uniqueUserId)
275
+ // Prepare telemetry payload
276
+ const payload = {
277
+ client_id: uniqueUserId,
278
+ non_personalized_ads: false,
279
+ timestamp_micros: Date.now() * 1000,
280
+ events: [{
281
+ name: 'package_installed',
282
+ params: {
283
+ timestamp: new Date().toISOString(),
284
+ platform: platform(),
285
+ installation_source: installationData.source,
286
+ installation_details: JSON.stringify(installationData.details),
287
+ package_name: '@wonderwhy-er/desktop-commander',
288
+ install_method: 'npm-lifecycle',
289
+ node_version: process.version,
290
+ npm_version: process.env.npm_version || 'unknown'
291
+ }
292
+ }]
293
+ };
294
+
295
+ const postData = JSON.stringify(payload);
296
+
297
+ const options = {
298
+ method: 'POST',
299
+ headers: {
300
+ 'Content-Type': 'application/json',
301
+ 'Content-Length': Buffer.byteLength(postData)
302
+ }
303
+ };
304
+
305
+ const sent = await postTelemetryPayload(TELEMETRY_PROXY_URL, postData, options);
306
+ if (!sent) {
307
+ await postTelemetryPayload(TELEMETRY_PROXY_FALLBACK_URL, postData, options);
308
+ }
309
+ log(`Installation tracked: ${installationData.source}`);
310
+
311
+ } catch (error) {
312
+ debug(`Failed to track installation: ${error.message}`);
313
+ // Don't fail the installation process
314
+ }
315
+ }
316
+
317
+ // TODO(dedup): postTelemetryPayload is copy-pasted across setup/uninstall/track
318
+ // scripts + a variant in src/utils/capture.ts. Consolidate into one shared module.
319
+ // TODO(timeout): per-endpoint timeout here is 5s, but ensureTrackingCompleted caps
320
+ // the whole flow at 6s — so if the primary times out, the fallback gets ~1s and
321
+ // almost never completes. Lower per-endpoint timeout (capture.ts uses 3s) or raise
322
+ // the overall budget so the fallback is actually usable.
323
+ async function postTelemetryPayload(endpoint, postData, options) {
324
+ return await new Promise((resolve) => {
325
+ let settled = false;
326
+ let timeoutId;
327
+ const finish = (result) => {
328
+ if (settled) return;
329
+ settled = true;
330
+ clearTimeout(timeoutId);
331
+ resolve(result);
332
+ };
333
+ const req = https.request(endpoint, options);
334
+
335
+ timeoutId = setTimeout(() => {
336
+ req.destroy();
337
+ finish(false);
338
+ }, 5000);
339
+
340
+ req.on('error', (error) => {
341
+ debug(`Telemetry error: ${error.message}`);
342
+ finish(false);
343
+ });
344
+
345
+ req.on('response', (res) => {
346
+ res.on('data', () => {});
347
+ res.on('error', (error) => {
348
+ debug(`Telemetry response error: ${error.message}`);
349
+ finish(false);
350
+ });
351
+ res.on('end', () => {
352
+ finish(res.statusCode >= 200 && res.statusCode < 300);
353
+ });
354
+ res.on('close', () => {
355
+ finish(false);
356
+ });
357
+ });
358
+
359
+ req.write(postData);
360
+ req.end();
361
+ });
362
+ }
363
+
364
+ /**
365
+ * Main execution
366
+ */
367
+ async function main() {
368
+ try {
369
+ log('Package installation detected');
370
+
371
+ const installationData = await detectInstallationSource();
372
+ log(`Installation source: ${installationData.source}`);
373
+
374
+ await trackInstallation(installationData);
375
+
376
+ } catch (error) {
377
+ debug(`Installation tracking error: ${error.message}`);
378
+ // Don't fail the installation
379
+ }
380
+ }
381
+
382
+ // Only run if this script is executed directly (not imported)
383
+ if (import.meta.url === `file://${process.argv[1]}`) {
384
+ main();
385
+ }
386
+
387
+ export { detectInstallationSource, trackInstallation };