@wonderwhy-er/desktop-commander 0.2.51 → 0.3.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +14 -24
  2. package/dist/command-manager.d.ts +7 -2
  3. package/dist/command-manager.js +16 -11
  4. package/dist/config-manager.d.ts +49 -3
  5. package/dist/config-manager.js +329 -87
  6. package/dist/config-recovery.d.ts +28 -0
  7. package/dist/config-recovery.js +81 -0
  8. package/dist/config.d.ts +1 -0
  9. package/dist/config.js +9 -0
  10. package/dist/handlers/filesystem-handlers.d.ts +1 -1
  11. package/dist/handlers/filesystem-handlers.js +26 -16
  12. package/dist/handlers/search-answers.d.ts +58 -0
  13. package/dist/handlers/search-answers.js +172 -0
  14. package/dist/handlers/search-handlers.js +4 -92
  15. package/dist/index.js +14 -7
  16. package/dist/npm-scripts/remote.js +32 -4
  17. package/dist/remote-device/broadcast-analytics.d.ts +28 -0
  18. package/dist/remote-device/broadcast-analytics.js +41 -0
  19. package/dist/remote-device/desktop-commander-integration.d.ts +20 -0
  20. package/dist/remote-device/desktop-commander-integration.js +121 -40
  21. package/dist/remote-device/device-authenticator.d.ts +13 -1
  22. package/dist/remote-device/device-authenticator.js +87 -47
  23. package/dist/remote-device/device.d.ts +14 -0
  24. package/dist/remote-device/device.js +244 -51
  25. package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
  26. package/dist/remote-device/mqtt-enrollment.js +162 -0
  27. package/dist/remote-device/mqtt-transport.d.ts +44 -0
  28. package/dist/remote-device/mqtt-transport.js +197 -0
  29. package/dist/remote-device/remote-channel.d.ts +64 -3
  30. package/dist/remote-device/remote-channel.js +317 -48
  31. package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
  32. package/dist/remote-device/transport-analytics.d.ts +29 -0
  33. package/dist/remote-device/transport-analytics.js +44 -0
  34. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  35. package/dist/remote-device/transport-telemetry.js +48 -0
  36. package/dist/search-manager.d.ts +239 -27
  37. package/dist/search-manager.js +746 -312
  38. package/dist/server.js +77 -92
  39. package/dist/terminal-manager.d.ts +138 -21
  40. package/dist/terminal-manager.js +300 -215
  41. package/dist/tools/config.d.ts +1 -1
  42. package/dist/tools/config.js +21 -70
  43. package/dist/tools/edit.js +12 -4
  44. package/dist/tools/filesystem.d.ts +30 -6
  45. package/dist/tools/filesystem.js +246 -140
  46. package/dist/tools/improved-process-tools.d.ts +9 -3
  47. package/dist/tools/improved-process-tools.js +171 -68
  48. package/dist/tools/pdf/extract-images.d.ts +2 -0
  49. package/dist/tools/pdf/extract-images.js +4 -1
  50. package/dist/tools/pdf/index.d.ts +5 -3
  51. package/dist/tools/pdf/index.js +4 -3
  52. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  53. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  54. package/dist/tools/pdf/manipulations.d.ts +12 -1
  55. package/dist/tools/pdf/manipulations.js +17 -4
  56. package/dist/tools/pdf/markdown.d.ts +96 -0
  57. package/dist/tools/pdf/markdown.js +485 -20
  58. package/dist/tools/pdf/utils.d.ts +2 -2
  59. package/dist/tools/pdf/utils.js +4 -4
  60. package/dist/tools/process.js +8 -5
  61. package/dist/tools/schemas.d.ts +1 -1
  62. package/dist/tools/schemas.js +15 -6
  63. package/dist/tools/search.d.ts +32 -0
  64. package/dist/tools/search.js +202 -0
  65. package/dist/types.d.ts +1 -1
  66. package/dist/ui/config-editor/config-editor-runtime.js +6 -6
  67. package/dist/ui/config-editor/src/app.js +2 -15
  68. package/dist/utils/ab-test.js +27 -9
  69. package/dist/utils/atomic-write.d.ts +14 -0
  70. package/dist/utils/atomic-write.js +80 -0
  71. package/dist/utils/capture.d.ts +17 -1
  72. package/dist/utils/capture.js +177 -68
  73. package/dist/utils/exit-process.d.ts +24 -0
  74. package/dist/utils/exit-process.js +31 -0
  75. package/dist/utils/feature-flags.js +2 -1
  76. package/dist/utils/files/base.d.ts +3 -1
  77. package/dist/utils/files/docx.d.ts +3 -0
  78. package/dist/utils/files/docx.js +24 -9
  79. package/dist/utils/files/excel.d.ts +10 -0
  80. package/dist/utils/files/excel.js +93 -33
  81. package/dist/utils/files/factory.d.ts +22 -1
  82. package/dist/utils/files/factory.js +59 -4
  83. package/dist/utils/files/image.d.ts +12 -4
  84. package/dist/utils/files/image.js +19 -8
  85. package/dist/utils/files/index.d.ts +5 -3
  86. package/dist/utils/files/index.js +4 -3
  87. package/dist/utils/files/pdf.js +18 -36
  88. package/dist/utils/files/text.d.ts +21 -5
  89. package/dist/utils/files/text.js +90 -86
  90. package/dist/utils/internal-facts.d.ts +3 -0
  91. package/dist/utils/internal-facts.js +23 -0
  92. package/dist/utils/lazy-package.d.ts +23 -0
  93. package/dist/utils/lazy-package.js +42 -0
  94. package/dist/utils/open-browser.js +2 -1
  95. package/dist/utils/process-detection.d.ts +24 -5
  96. package/dist/utils/process-detection.js +199 -89
  97. package/dist/utils/process-tree.d.ts +14 -0
  98. package/dist/utils/process-tree.js +223 -0
  99. package/dist/utils/rename.d.ts +9 -0
  100. package/dist/utils/rename.js +74 -0
  101. package/dist/utils/ripgrep-resolver.js +9 -14
  102. package/dist/utils/shell.d.ts +42 -0
  103. package/dist/utils/shell.js +187 -0
  104. package/dist/utils/system-info.js +9 -7
  105. package/dist/utils/trackTools.js +2 -1
  106. package/dist/version.d.ts +1 -1
  107. package/dist/version.js +1 -1
  108. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  109. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  110. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  111. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  112. package/package.json +8 -2
  113. package/vendor/telemetry-contract/README.md +56 -0
  114. package/vendor/telemetry-contract/package.json +32 -0
  115. package/vendor/telemetry-contract/transport.d.ts +38 -0
  116. package/vendor/telemetry-contract/transport.js +164 -0
  117. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -1,12 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { RemoteChannel, observeServerDate } from './remote-channel.js';
2
+ import { ChannelUnreachableError, RemoteChannel, observeServerDate } from './remote-channel.js';
3
3
  import { DeviceAuthenticator } from './device-authenticator.js';
4
4
  import { DesktopCommanderIntegration } from './desktop-commander-integration.js';
5
5
  import { fileURLToPath } from 'url';
6
6
  import os from 'os';
7
7
  import fs from 'fs/promises';
8
8
  import path from 'path';
9
+ import lockfile from 'proper-lockfile';
9
10
  import { captureRemote } from '../utils/capture.js';
11
+ import { writeFileAtomic } from '../utils/atomic-write.js';
12
+ import { exitProcess } from '../utils/exit-process.js';
13
+ import { observeTransport } from './transport-telemetry.js';
10
14
  /**
11
15
  * How many recently-handled call ids to remember for duplicate-delivery
12
16
  * suppression. The two transports deliver a call within MILLISECONDS of each
@@ -17,9 +21,49 @@ import { captureRemote } from '../utils/capture.js';
17
21
  const SEEN_CALL_IDS_MAX = 100;
18
22
  const PERSISTED_DEVICE_LOOKUP_ATTEMPTS = 3;
19
23
  const PERSISTED_DEVICE_LOOKUP_RETRY_MS = 250;
24
+ /**
25
+ * Floor between recovery attempts. ensureReady()'s own backoff covers a child
26
+ * that fails to start; this covers one that starts and then fails verification,
27
+ * where no restart backoff was armed and the loop would otherwise spin.
28
+ */
29
+ const RECOVERY_MIN_DELAY_MS = 1000;
20
30
  export function getRemoteDeviceConfigPath() {
21
31
  return path.join(os.homedir(), '.desktop-commander-device', 'device.json');
22
32
  }
33
+ /**
34
+ * Cross-process lock on device.json. A device's save holds it from its check
35
+ * that the file is still there to its write, and `remote --logout` holds it to
36
+ * remove the file, so a logout cannot land between the two and be written
37
+ * over. Settings as for the server's config.json lock (config-manager.ts).
38
+ */
39
+ function lockRemoteDeviceConfig(configPath) {
40
+ return lockfile.lock(configPath, {
41
+ realpath: false,
42
+ stale: 30000,
43
+ update: 10000,
44
+ retries: { retries: 100, factor: 1.2, minTimeout: 10, maxTimeout: 100 },
45
+ // The default throws from a timer, which ends the process
46
+ onCompromised: (error) => console.error(`The device.json lock was lost while held: ${error.message}`),
47
+ });
48
+ }
49
+ /** `remote --logout`: removes device.json, under the lock a running device's save takes. */
50
+ export async function removeRemoteDeviceConfig(configPath = getRemoteDeviceConfigPath()) {
51
+ let release;
52
+ try {
53
+ release = await lockRemoteDeviceConfig(configPath);
54
+ }
55
+ catch (error) {
56
+ // No config folder: nothing was saved
57
+ if (error.code !== 'ENOENT')
58
+ throw error;
59
+ }
60
+ try {
61
+ await fs.rm(configPath, { force: true });
62
+ }
63
+ finally {
64
+ await release?.();
65
+ }
66
+ }
23
67
  export class MCPDevice {
24
68
  constructor(options = {}) {
25
69
  /**
@@ -29,6 +73,8 @@ export class MCPDevice {
29
73
  * whatever is still in flight.
30
74
  */
31
75
  this.configWriteChain = Promise.resolve();
76
+ /** device.json was removed or replaced after this run loaded or saved it: nothing is saved again this run. */
77
+ this.loggedOutLocally = false;
32
78
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
33
79
  this.seenCallIds = new Set();
34
80
  this.baseServerUrl = process.env.MCP_SERVER_URL || 'https://mcp.desktopcommander.app';
@@ -48,6 +94,10 @@ export class MCPDevice {
48
94
  this.remoteChannel.onSessionRefreshed((session) => void this.savePersistedConfig(session));
49
95
  // Initialize desktop integration
50
96
  this.desktop = new DesktopCommanderIntegration();
97
+ // Readiness is a claim about executing, so it has to consult the local
98
+ // executor too. Read through a probe rather than a cached flag: there
99
+ // is then no state to keep in step, and `desktop` can be replaced.
100
+ this.remoteChannel.setLocalExecutorProbe(() => this.desktop.ready);
51
101
  // Graceful shutdown handlers (only set once)
52
102
  this.setupShutdownHandlers();
53
103
  }
@@ -56,24 +106,24 @@ export class MCPDevice {
56
106
  if (this.isShuttingDown) {
57
107
  console.log(`\n${signal} received, but already shutting down...`);
58
108
  // Force exit if we get multiple signals
59
- process.exit(1);
109
+ exitProcess(1);
60
110
  return;
61
111
  }
62
112
  console.log(`\n${signal} received, initiating graceful shutdown...`);
63
113
  // Force exit after 5 seconds if graceful shutdown hangs
64
114
  const forceExit = setTimeout(() => {
65
115
  console.error('\n⚠️ Graceful shutdown timed out, forcing exit...');
66
- process.exit(1);
116
+ exitProcess(1);
67
117
  }, 5000);
68
118
  try {
69
119
  await this.shutdown();
70
120
  clearTimeout(forceExit);
71
- process.exit(0);
121
+ exitProcess(0);
72
122
  }
73
123
  catch (error) {
74
124
  console.error('Error during shutdown:', error);
75
125
  await captureRemote('remote_device_shutdown_handler_error', { error });
76
- process.exit(1);
126
+ exitProcess(1);
77
127
  }
78
128
  };
79
129
  // Remove any existing SIGINT/SIGTERM listeners to prevent default behavior
@@ -84,14 +134,14 @@ export class MCPDevice {
84
134
  handleShutdown('SIGINT').catch((error) => {
85
135
  console.error('Fatal error during shutdown:', error);
86
136
  captureRemote('remote_device_shutdown_handler_error', { error, signal: 'SIGINT' }).catch(() => { });
87
- process.exit(1);
137
+ exitProcess(1);
88
138
  });
89
139
  });
90
140
  process.on('SIGTERM', () => {
91
141
  handleShutdown('SIGTERM').catch((error) => {
92
142
  console.error('Fatal error during shutdown:', error);
93
143
  captureRemote('remote_device_shutdown_handler_error', { error, signal: 'SIGTERM' }).catch(() => { });
94
- process.exit(1);
144
+ exitProcess(1);
95
145
  });
96
146
  });
97
147
  }
@@ -111,6 +161,10 @@ export class MCPDevice {
111
161
  this.remoteChannel.initialize(supabaseUrl, anonKey);
112
162
  // Load persisted configuration (deviceId, session)
113
163
  let session = await this.loadPersistedConfig();
164
+ await captureRemote('remote_device_session_state', {
165
+ has_persisted_session: Boolean(session),
166
+ has_persisted_device_id: Boolean(this.deviceId),
167
+ });
114
168
  // 2. Set Session or Authenticate
115
169
  if (session) {
116
170
  const { error } = await this.remoteChannel.setSession(session);
@@ -120,7 +174,6 @@ export class MCPDevice {
120
174
  }
121
175
  else {
122
176
  console.log(' - ✅ Session restored');
123
- console.log(' - ℹ️ To log out locally: npx @wonderwhy-er/desktop-commander@latest remote --logout');
124
177
  // Revoking a device removes its server-side mcp_devices row, but the
125
178
  // local config can still hold a valid user session + the now-deleted
126
179
  // device ID. Do not silently recreate the revoked device with that
@@ -137,6 +190,7 @@ export class MCPDevice {
137
190
  }
138
191
  }
139
192
  if (!session) {
193
+ await captureRemote('remote_device_auth_flow_started');
140
194
  console.log('\n🔐 Authenticating with Remote MCP server...');
141
195
  const authenticator = new DeviceAuthenticator(this.baseServerUrl);
142
196
  session = await authenticator.authenticate(this.deviceId);
@@ -169,12 +223,60 @@ export class MCPDevice {
169
223
  // Force save the current session immediately to ensure it's persisted
170
224
  await this.savePersistedConfig();
171
225
  const deviceName = os.hostname();
172
- // Register as device
173
- await this.remoteChannel.registerDevice(await this.desktop.listClientTools(), this.deviceId, deviceName, (payload) => this.handleNewToolCall(payload));
174
- console.log('✅ Device ready:');
226
+ // Register as device. registerDevice() resolves only once the
227
+ // realtime channel is joined and presence is published, which is
228
+ // exactly what the hosted service needs to deliver a call — so a
229
+ // rejection means "running, but nothing can reach this device", and
230
+ // that has to be said instead of "Device ready".
231
+ //
232
+ // Deliberately not fatal, and deliberately not rethrown into the
233
+ // outer catch, which exits the process: the socket watchdog keeps
234
+ // retrying and announces "✅ Channel subscribed" when it gets
235
+ // through, so quitting here would remove the only way back.
236
+ let reachable = true;
237
+ try {
238
+ await this.remoteChannel.registerDevice(await this.desktop.listClientTools(), this.deviceId, deviceName, (payload) => this.handleNewToolCall(payload));
239
+ }
240
+ catch (error) {
241
+ // Only a channel fault is recoverable here. A failed lookup or a
242
+ // missing device row happens before registerDevice() stores the
243
+ // recreation parameters, and both checkConnectionHealth() and
244
+ // recreateChannel() return early without them — so nothing in
245
+ // this process could repair it, and swallowing it would promise
246
+ // a retry that can never happen. Those stay fatal, as before.
247
+ if (!(error instanceof ChannelUnreachableError))
248
+ throw error;
249
+ reachable = false;
250
+ console.error(` - ❌ Realtime channel is not open: ${error.message}`);
251
+ await captureRemote('remote_device_registered_unreachable', { error });
252
+ }
253
+ console.log(reachable
254
+ ? '✅ Device ready:'
255
+ : '⚠️ Device registered, but NOT reachable — no command can arrive yet:');
175
256
  console.log(` - User: ${this.remoteChannel.user.email}`);
176
257
  console.log(` - Device ID: ${this.deviceId}`);
177
258
  console.log(` - Device Name: ${deviceName}`);
259
+ if (!reachable) {
260
+ console.log(' - Retrying in the background; commands start working once you see "✅ Channel subscribed".');
261
+ }
262
+ else {
263
+ console.log('');
264
+ console.log('✅ Desktop Commander Remote is connected');
265
+ console.log('');
266
+ console.log(` Device: ${deviceName}`);
267
+ console.log(' Status: Online');
268
+ console.log('');
269
+ console.log('┌─ Next');
270
+ console.log('│ Return to ChatGPT or Claude and continue your conversation.');
271
+ console.log('│ Keep this Terminal running. You can minimize it.');
272
+ console.log('└─ Press Ctrl+C to disconnect.');
273
+ console.log('');
274
+ console.log('┌─ Commands');
275
+ console.log('│ Help: npx @wonderwhy-er/desktop-commander@latest remote --help');
276
+ console.log('│ Log out: npx @wonderwhy-er/desktop-commander@latest remote --logout');
277
+ console.log('└─ Run these in a new Terminal, or after disconnecting.');
278
+ console.log('');
279
+ }
178
280
  // Keep process alive
179
281
  this.remoteChannel.startHeartbeat(this.deviceId);
180
282
  }
@@ -185,7 +287,7 @@ export class MCPDevice {
185
287
  }
186
288
  await captureRemote('remote_device_startup_failed', { error });
187
289
  await this.shutdown();
188
- process.exit(1);
290
+ exitProcess(1);
189
291
  }
190
292
  }
191
293
  async findPersistedDeviceWithRetry(deviceId) {
@@ -208,9 +310,18 @@ export class MCPDevice {
208
310
  try {
209
311
  console.debug('[DEBUG] Loading persisted config from:', this.configPath);
210
312
  const data = await fs.readFile(this.configPath, 'utf8');
313
+ // A logout from here on, before this run's first save, removes it
314
+ this.configTextOnDisk = data;
211
315
  const config = JSON.parse(data);
212
316
  this.deviceId = config?.deviceId;
213
317
  console.debug('[DEBUG] Loaded device ID:', this.deviceId);
318
+ // A session without its device id is not a login: restoring it
319
+ // skips the revoked-device check below, and registration then fails
320
+ // with "Device not found: undefined" on every start. Authorize again.
321
+ if (config.session && this.persistSession && !this.deviceId) {
322
+ console.debug('[DEBUG] Ignoring persisted session without a device ID');
323
+ return null;
324
+ }
214
325
  if (config.session && this.persistSession) {
215
326
  console.log('💾 Found persisted session for device ' + this.deviceId);
216
327
  console.debug('[DEBUG] Session found in config, returning session');
@@ -242,7 +353,20 @@ export class MCPDevice {
242
353
  // No need to ensure device ID here
243
354
  }
244
355
  }
356
+ /** device.json's text, or undefined when there is none. Errors other than "not found" go to the caller, which logs them. */
357
+ async readConfigText() {
358
+ try {
359
+ return await fs.readFile(this.configPath, 'utf8');
360
+ }
361
+ catch (error) {
362
+ if (error.code === 'ENOENT')
363
+ return undefined;
364
+ throw error;
365
+ }
366
+ }
245
367
  async clearPersistedConfig() {
368
+ // Removed by this run itself, not by a logout
369
+ this.configTextOnDisk = undefined;
246
370
  try {
247
371
  await fs.rm(this.configPath, { force: true });
248
372
  console.debug('[DEBUG] Cleared stale persisted config:', this.configPath);
@@ -262,6 +386,8 @@ export class MCPDevice {
262
386
  }
263
387
  async writePersistedConfig(rotated) {
264
388
  try {
389
+ if (this.loggedOutLocally)
390
+ return;
265
391
  console.debug('[DEBUG] Saving persisted config, persistSession:', this.persistSession);
266
392
  // Prefer the session TOKEN_REFRESHED handed us over re-reading it. A
267
393
  // sign-out landing in that gap answers null, and the write below would
@@ -285,17 +411,37 @@ export class MCPDevice {
285
411
  // Ensure the config directory exists
286
412
  console.debug('[DEBUG] Creating config directory:', path.dirname(this.configPath));
287
413
  await fs.mkdir(path.dirname(this.configPath), { recursive: true });
288
- // Write then rename: the rename is the commit boundary, so a write
289
- // cut short leaves the previous complete session rather than a
290
- // truncated file. loadPersistedConfig() answers a JSON.parse
291
- // failure with null, which costs a full browser reauthorization.
292
- // Same shape as ConfigManager's atomic save; the pid keeps two
293
- // processes off each other's temp file, and configWriteChain keeps
294
- // this one off its own.
295
- const tempPath = `${this.configPath}.${process.pid}.tmp`;
296
- await fs.writeFile(tempPath, JSON.stringify(config, null, 2), { mode: 0o600 });
297
- await fs.rename(tempPath, this.configPath);
298
- console.debug('[DEBUG] Config saved to:', this.configPath);
414
+ // From the check to the write, `remote --logout` waits for this lock
415
+ const release = await lockRemoteDeviceConfig(this.configPath);
416
+ try {
417
+ // `remote --logout` removes device.json from another process, and
418
+ // the docs say that removes the saved credentials. Writing them back
419
+ // at the next rotation or at shutdown would undo it: this run keeps
420
+ // its session in memory (the logout is local only) and saves nothing.
421
+ // A login after the logout saves its own device.json, which this
422
+ // run's credentials must not replace either.
423
+ if (this.configTextOnDisk !== undefined) {
424
+ const onDisk = await this.readConfigText();
425
+ if (onDisk !== this.configTextOnDisk) {
426
+ this.loggedOutLocally = true;
427
+ console.log(onDisk === undefined
428
+ ? '🔓 Saved Remote MCP device credentials were removed (remote --logout): this run keeps its session in memory and won\'t save it again'
429
+ : '🔓 Saved Remote MCP device credentials were replaced (a login after remote --logout): this run keeps its session in memory and won\'t save it again');
430
+ return;
431
+ }
432
+ }
433
+ // Atomic write: a save cut short leaves the previous complete
434
+ // session rather than a truncated file. loadPersistedConfig()
435
+ // answers a JSON.parse failure with null, which costs a full
436
+ // browser reauthorization.
437
+ const text = JSON.stringify(config, null, 2);
438
+ await writeFileAtomic(this.configPath, text, { mode: 0o600 });
439
+ this.configTextOnDisk = text;
440
+ console.debug('[DEBUG] Config saved to:', this.configPath);
441
+ }
442
+ finally {
443
+ await release().catch((error) => console.error(' - ❌ Failed to release the device.json lock:', error.message));
444
+ }
299
445
  }
300
446
  catch (error) {
301
447
  console.error(' - ❌ Failed to save config:', error.message);
@@ -331,23 +477,47 @@ export class MCPDevice {
331
477
  * connected" until someone restarted the process by hand.
332
478
  */
333
479
  async handleLocalMcpLoss(reason) {
334
- if (this.deviceId) {
335
- await this.remoteChannel.setOnlineStatus(this.deviceId, 'offline')
336
- .catch((e) => console.error('Failed to mark device offline:', e.message));
337
- }
338
- // Recover proactively rather than waiting for the next tool call to
339
- // trigger the lazy restart: we just went offline, so no further calls
340
- // would be routed here and that wait would never end.
341
- try {
342
- await this.desktop.ensureReady();
343
- if (this.deviceId) {
344
- await this.remoteChannel.setOnlineStatus(this.deviceId, 'online');
480
+ // Through the predicate and its queue, not a direct write: the probe
481
+ // already reads false by the time this runs, and a direct write can be
482
+ // overtaken by an 'online' still sitting in the queue — which would put
483
+ // a device with a dead executor back into the server's selection pool.
484
+ await this.remoteChannel.syncReachabilityStatus()
485
+ .catch((e) => console.error('Failed to mark device offline:', e.message));
486
+ // Keep trying, rather than attempting once. The lazy restart in
487
+ // ensureReady() fires on an incoming tool call, and this device is now
488
+ // offline — the hosted service answers a call for an offline device
489
+ // with "No devices available" (confirmed live on 0.2.50), so no call
490
+ // will ever arrive to trigger it. One failed attempt used to mean the
491
+ // device stayed dead until a human restarted the connector.
492
+ let reported = false;
493
+ while (!this.isShuttingDown) {
494
+ try {
495
+ // ensureReady() only reports success once the child has served a
496
+ // request, so reaching here is proof of execution, not just of a
497
+ // completed handshake.
498
+ await this.desktop.ensureReady();
499
+ // Not setOnlineStatus('online'): the executor recovering says
500
+ // nothing about the channel. Let the predicate decide, or this
501
+ // repeats the one-sided claim this whole change removes.
502
+ this.remoteChannel.syncReachabilityStatus();
503
+ console.log('♻️ Local Desktop Commander MCP restarted; device is online again');
504
+ return;
505
+ }
506
+ catch (error) {
507
+ console.error(`❌ Could not restart local Desktop Commander MCP: ${error.message}`);
508
+ // Once per outage, not once per attempt: a device that never
509
+ // recovers would otherwise emit this every backoff window for
510
+ // as long as it runs.
511
+ if (!reported) {
512
+ reported = true;
513
+ await captureRemote('remote_device_local_mcp_restart_failed', { error, reason });
514
+ }
515
+ // ensureReady() refuses inside its backoff window; wait it out.
516
+ // The floor covers a child that starts but fails verification,
517
+ // where no restart backoff was armed.
518
+ const waitMs = Math.max(this.desktop.msUntilRestartAllowed, RECOVERY_MIN_DELAY_MS);
519
+ await new Promise((resolve) => setTimeout(resolve, waitMs));
345
520
  }
346
- console.log('♻️ Local Desktop Commander MCP restarted; device is online again');
347
- }
348
- catch (error) {
349
- console.error(`❌ Could not restart local Desktop Commander MCP: ${error.message}`);
350
- await captureRemote('remote_device_local_mcp_restart_failed', { error, reason });
351
521
  }
352
522
  }
353
523
  /** Record a handled call id, evicting the oldest once the cap is reached. */
@@ -370,6 +540,9 @@ export class MCPDevice {
370
540
  console.debug('[DEBUG] Ignoring tool call for different device');
371
541
  return;
372
542
  }
543
+ const observation = { callId: call_id, deviceId: this.deviceId, toolName: tool_name };
544
+ // Count every targeted delivery, including duplicates, before the local claim.
545
+ observeTransport({ stage: 'device_call_received', ...observation });
373
546
  console.log(`🔧 Received tool call ${call_id}: ${tool_name} ${JSON.stringify(tool_args)} metadata: ${JSON.stringify(metadata)}`);
374
547
  // LOCAL claim first — this is the authoritative guard against executing
375
548
  // a call twice. During the transition both transports deliver every call
@@ -382,6 +555,9 @@ export class MCPDevice {
382
555
  return;
383
556
  }
384
557
  this.rememberCallId(call_id);
558
+ // Running the tool and saving its result fail separately: only a tool
559
+ // that didn't run is "tool_call_failed"
560
+ let result;
385
561
  try {
386
562
  // DB claim second — keeps the row state machine honest, gives
387
563
  // cross-restart/cross-process protection, and is observable. It may
@@ -393,7 +569,6 @@ export class MCPDevice {
393
569
  // markCallExecuting already logged the duplicate-delivery skip.
394
570
  return;
395
571
  }
396
- let result;
397
572
  // Handle 'ping' tool specially
398
573
  if (tool_name === 'ping') {
399
574
  result = {
@@ -414,30 +589,48 @@ export class MCPDevice {
414
589
  setTimeout(async () => {
415
590
  console.log('🛑 Remote shutdown requested. Exiting...');
416
591
  await this.shutdown();
417
- process.exit(0);
592
+ exitProcess(0);
418
593
  }, 1000);
419
594
  }
420
595
  else {
421
596
  // Execute other tools using desktop integration
422
597
  result = await this.desktop.callClientTool(tool_name, tool_args, metadata);
423
598
  }
424
- console.log(`✅ Tool call ${tool_name} completed:\r\n ${JSON.stringify(result)}`);
425
- // The result write itself notifies the server (a DB trigger).
426
- await this.remoteChannel.updateCallResult(call_id, 'completed', result);
427
599
  }
428
600
  catch (error) {
429
601
  console.error(`❌ Tool call ${tool_name} failed:`, error.message);
430
- // The failure path must not fail: this method's promise is discarded
431
- // at every call site, so a throw here becomes an unhandled rejection
432
- // and takes the device process down.
602
+ observeTransport({ stage: 'tool_call_failed', ...observation });
603
+ await this.reportToolCallFailure(call_id, tool_name, error);
604
+ return;
605
+ }
606
+ console.log(`✅ Tool call ${tool_name} completed:\r\n ${JSON.stringify(result)}`);
607
+ // The tool ran. A result that can't be saved is reported and written as
608
+ // failed, as before, but its telemetry stays "tool_call_completed"
609
+ try {
433
610
  try {
434
- await captureRemote('remote_device_tool_call_failed', { error, tool_name });
435
- await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
611
+ await this.remoteChannel.updateCallResult(call_id, 'completed', result);
436
612
  }
437
- catch (reportError) {
438
- console.error(`❌ Could not report failure for ${call_id}:`, reportError?.message);
613
+ finally {
614
+ observeTransport({ stage: 'tool_call_completed', ...observation });
439
615
  }
440
616
  }
617
+ catch (error) {
618
+ console.error(`❌ Tool call ${tool_name} failed:`, error.message);
619
+ await this.reportToolCallFailure(call_id, tool_name, error);
620
+ }
621
+ }
622
+ /** Reports a tool call that failed, or whose result couldn't be saved, and writes its "failed" row. */
623
+ async reportToolCallFailure(call_id, tool_name, error) {
624
+ // The failure path must not fail: handleNewToolCall's promise is discarded
625
+ // at every call site, so a throw here becomes an unhandled rejection
626
+ // and takes the device process down.
627
+ try {
628
+ await captureRemote('remote_device_tool_call_failed', { error, tool_name });
629
+ await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
630
+ }
631
+ catch (reportError) {
632
+ console.error(`❌ Could not report failure for ${call_id}:`, reportError?.message);
633
+ }
441
634
  }
442
635
  async shutdown() {
443
636
  if (this.isShuttingDown) {
@@ -0,0 +1,16 @@
1
+ import { type MqttConfig } from './mqtt-transport.js';
2
+ interface EnrollmentOptions {
3
+ serverUrl: string;
4
+ profilePath: string;
5
+ userId: string;
6
+ deviceId: string;
7
+ accessToken: string;
8
+ /** RemoteChannel invalidates asynchronous enrollment when sign-out or shutdown occurs. */
9
+ assertCurrent?: () => void;
10
+ }
11
+ /**
12
+ * Enroll once using the existing authenticated session, or reuse this profile's credentials.
13
+ * Only the CSR leaves the device. The backend owns authorization and AWS policy attachment.
14
+ */
15
+ export declare function enrollMqttDevice(options: EnrollmentOptions, env?: NodeJS.ProcessEnv): Promise<MqttConfig>;
16
+ export {};
@@ -0,0 +1,162 @@
1
+ import { createPrivateKey, generateKeyPair, X509Certificate } from 'node:crypto';
2
+ import { mkdir, open, readFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ import forge from 'node-forge';
6
+ import { readMqttConfig } from './mqtt-transport.js';
7
+ const generateRsaKeyPair = promisify(generateKeyPair);
8
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
9
+ // Leave network headroom above the backend's 20-second AWS setup deadline.
10
+ const ENROLLMENT_TIMEOUT_MS = 30000;
11
+ /** Read only existing credentials; a damaged file must never trigger silent key replacement. */
12
+ async function readCache(file) {
13
+ try {
14
+ const value = JSON.parse(await readFile(file, 'utf8'));
15
+ if (!value || typeof value !== 'object' || Array.isArray(value))
16
+ throw new Error();
17
+ return value;
18
+ }
19
+ catch (error) {
20
+ if (error.code === 'ENOENT')
21
+ return null;
22
+ throw new Error('MQTT credential cache cannot be read; inspect the profile MQTT folder before restarting');
23
+ }
24
+ }
25
+ /** Exclusive creation preserves the winner's private key if two processes use the same profile. */
26
+ async function writePrivateCache(file, value) {
27
+ try {
28
+ const handle = await open(file, 'wx', 0o600);
29
+ try {
30
+ await handle.writeFile(JSON.stringify(value));
31
+ }
32
+ finally {
33
+ await handle.close();
34
+ }
35
+ }
36
+ catch {
37
+ // Do not include filesystem/provider errors: startup errors also go to telemetry.
38
+ throw new Error('MQTT credentials could not be saved; use one connector process per profile and check folder permissions');
39
+ }
40
+ }
41
+ /** Validate issued/cached material before it can authenticate this device to the broker. */
42
+ function validateCertificate(value, privateKey) {
43
+ try {
44
+ if (!value || typeof value.certificate_pem !== 'string' || value.certificate_pem.length > 16384 ||
45
+ typeof value.certificate_id !== 'string' || !/^[a-fA-F0-9]{64}$/.test(value.certificate_id) ||
46
+ typeof value.broker_url !== 'string')
47
+ throw new Error();
48
+ const broker = new URL(value.broker_url);
49
+ if (broker.protocol !== 'mqtts:' || !broker.hostname || broker.username || broker.password ||
50
+ broker.search || broker.hash || (broker.pathname && broker.pathname !== '/'))
51
+ throw new Error();
52
+ const certificate = new X509Certificate(value.certificate_pem);
53
+ const now = Date.now();
54
+ if (certificate.ca || !certificate.checkPrivateKey(createPrivateKey(privateKey)) ||
55
+ !Number.isFinite(Date.parse(certificate.validFrom)) || !Number.isFinite(Date.parse(certificate.validTo)) ||
56
+ Date.parse(certificate.validFrom) > now || Date.parse(certificate.validTo) <= now)
57
+ throw new Error();
58
+ }
59
+ catch {
60
+ throw new Error('MQTT certificate is invalid, expired, or does not match this device private key');
61
+ }
62
+ }
63
+ /**
64
+ * Enroll once using the existing authenticated session, or reuse this profile's credentials.
65
+ * Only the CSR leaves the device. The backend owns authorization and AWS policy attachment.
66
+ */
67
+ export async function enrollMqttDevice(options, env = process.env) {
68
+ const { serverUrl, profilePath, userId, deviceId, accessToken } = options;
69
+ if (!ID.test(userId) || !ID.test(deviceId) || !accessToken) {
70
+ throw new Error('MQTT enrollment requires an authenticated device');
71
+ }
72
+ let backend;
73
+ try {
74
+ backend = new URL(serverUrl);
75
+ }
76
+ catch {
77
+ throw new Error('MQTT enrollment requires a valid MCP_SERVER_URL');
78
+ }
79
+ const localHttp = backend.protocol === 'http:' && env.MQTT_ALLOW_INSECURE_LOCAL === 'true' &&
80
+ ['localhost', 'mcp.localhost', 'mcp.localhost.localdomain', '127.0.0.1', '[::1]'].includes(backend.hostname);
81
+ if ((backend.protocol !== 'https:' && !localHttp) || backend.username || backend.password ||
82
+ backend.search || backend.hash || (backend.pathname && backend.pathname !== '/')) {
83
+ throw new Error('MQTT enrollment requires HTTPS; explicit local testing may use a loopback HTTP backend');
84
+ }
85
+ options.assertCurrent?.();
86
+ const folder = `${path.resolve(profilePath)}.mqtt`;
87
+ await mkdir(folder, { recursive: true, mode: 0o700 });
88
+ const identityFile = path.join(folder, 'identity.json');
89
+ const certificateFile = path.join(folder, 'certificate.json');
90
+ let identity = await readCache(identityFile);
91
+ let certificate = await readCache(certificateFile);
92
+ if (!identity) {
93
+ if (certificate)
94
+ throw new Error('MQTT certificate exists without its device private key');
95
+ // Node generates RSA asynchronously; forge only encodes and signs the CSR below.
96
+ const keys = await generateRsaKeyPair('rsa', {
97
+ modulusLength: 2048,
98
+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
99
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
100
+ });
101
+ identity = {
102
+ backend_origin: backend.origin,
103
+ user_id: userId,
104
+ device_id: deviceId,
105
+ private_key: keys.privateKey,
106
+ };
107
+ options.assertCurrent?.();
108
+ await writePrivateCache(identityFile, identity);
109
+ }
110
+ // A profile switched to another account/backend cannot reuse its previous AWS identity.
111
+ if (identity.backend_origin !== backend.origin || identity.user_id !== userId ||
112
+ identity.device_id !== deviceId || typeof identity.private_key !== 'string') {
113
+ throw new Error('MQTT credentials belong to a different backend, user, or device; use a separate profile');
114
+ }
115
+ let privateKey;
116
+ try {
117
+ const key = createPrivateKey(identity.private_key);
118
+ if (key.asymmetricKeyType !== 'rsa' || key.asymmetricKeyDetails?.modulusLength !== 2048)
119
+ throw new Error();
120
+ privateKey = forge.pki.privateKeyFromPem(identity.private_key);
121
+ }
122
+ catch {
123
+ throw new Error('MQTT device private key is invalid; inspect the profile MQTT folder before restarting');
124
+ }
125
+ if (!certificate) {
126
+ const csr = forge.pki.createCertificationRequest();
127
+ csr.publicKey = forge.pki.setRsaPublicKey(privateKey.n, privateKey.e);
128
+ csr.setSubject([{ name: 'commonName', value: `dc-device-${deviceId}` }]);
129
+ csr.sign(privateKey, forge.md.sha256.create());
130
+ options.assertCurrent?.();
131
+ try {
132
+ // One bounded request: redirects are forbidden so the bearer token cannot follow another origin.
133
+ const response = await fetch(new URL('/device/mqtt/enroll', backend), {
134
+ method: 'POST',
135
+ headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
136
+ body: JSON.stringify({ device_id: deviceId, csr: forge.pki.certificationRequestToPem(csr) }),
137
+ redirect: 'error',
138
+ signal: AbortSignal.timeout(ENROLLMENT_TIMEOUT_MS),
139
+ });
140
+ if (!response.ok) {
141
+ throw new Error(`MQTT enrollment was refused (HTTP ${response.status}); check backend configuration and device access, then restart`);
142
+ }
143
+ certificate = await response.json();
144
+ }
145
+ catch (error) {
146
+ if (error.message?.startsWith('MQTT enrollment was refused'))
147
+ throw error;
148
+ throw new Error('MQTT enrollment request failed or timed out; check connectivity and restart the connector');
149
+ }
150
+ validateCertificate(certificate, identity.private_key);
151
+ options.assertCurrent?.();
152
+ // ponytail: a lost AWS response can orphan a certificate; pilot cleanup is manual, with no retries or renewal worker.
153
+ await writePrivateCache(certificateFile, certificate);
154
+ }
155
+ validateCertificate(certificate, identity.private_key);
156
+ options.assertCurrent?.();
157
+ // Pass credentials to this connection only; another profile in the process must not inherit them via env.
158
+ return readMqttConfig({ ...env, MQTT_BROKER_URL: certificate.broker_url }, {
159
+ cert: certificate.certificate_pem,
160
+ key: identity.private_key,
161
+ });
162
+ }