@wonderwhy-er/desktop-commander 0.2.52 → 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 (113) hide show
  1. package/dist/command-manager.d.ts +7 -2
  2. package/dist/command-manager.js +16 -11
  3. package/dist/config-manager.d.ts +49 -3
  4. package/dist/config-manager.js +329 -87
  5. package/dist/config-recovery.d.ts +28 -0
  6. package/dist/config-recovery.js +81 -0
  7. package/dist/config.d.ts +1 -0
  8. package/dist/config.js +9 -0
  9. package/dist/handlers/filesystem-handlers.d.ts +1 -1
  10. package/dist/handlers/filesystem-handlers.js +26 -16
  11. package/dist/handlers/search-answers.d.ts +58 -0
  12. package/dist/handlers/search-answers.js +172 -0
  13. package/dist/handlers/search-handlers.js +4 -92
  14. package/dist/index.js +14 -7
  15. package/dist/npm-scripts/remote.js +2 -3
  16. package/dist/remote-device/broadcast-analytics.d.ts +28 -0
  17. package/dist/remote-device/broadcast-analytics.js +41 -0
  18. package/dist/remote-device/desktop-commander-integration.js +19 -25
  19. package/dist/remote-device/device.d.ts +14 -0
  20. package/dist/remote-device/device.js +137 -30
  21. package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
  22. package/dist/remote-device/mqtt-enrollment.js +162 -0
  23. package/dist/remote-device/mqtt-transport.d.ts +44 -0
  24. package/dist/remote-device/mqtt-transport.js +197 -0
  25. package/dist/remote-device/remote-channel.d.ts +12 -0
  26. package/dist/remote-device/remote-channel.js +55 -8
  27. package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
  28. package/dist/remote-device/transport-analytics.d.ts +29 -0
  29. package/dist/remote-device/transport-analytics.js +44 -0
  30. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  31. package/dist/remote-device/transport-telemetry.js +48 -0
  32. package/dist/search-manager.d.ts +239 -27
  33. package/dist/search-manager.js +746 -312
  34. package/dist/server.js +44 -11
  35. package/dist/terminal-manager.d.ts +138 -21
  36. package/dist/terminal-manager.js +300 -215
  37. package/dist/tools/config.d.ts +1 -1
  38. package/dist/tools/config.js +21 -70
  39. package/dist/tools/edit.js +12 -4
  40. package/dist/tools/filesystem.d.ts +30 -6
  41. package/dist/tools/filesystem.js +246 -140
  42. package/dist/tools/improved-process-tools.d.ts +9 -3
  43. package/dist/tools/improved-process-tools.js +171 -68
  44. package/dist/tools/pdf/extract-images.d.ts +2 -0
  45. package/dist/tools/pdf/extract-images.js +4 -1
  46. package/dist/tools/pdf/index.d.ts +5 -3
  47. package/dist/tools/pdf/index.js +4 -3
  48. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  49. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  50. package/dist/tools/pdf/manipulations.d.ts +12 -1
  51. package/dist/tools/pdf/manipulations.js +17 -4
  52. package/dist/tools/pdf/markdown.d.ts +96 -0
  53. package/dist/tools/pdf/markdown.js +485 -20
  54. package/dist/tools/pdf/utils.d.ts +2 -2
  55. package/dist/tools/pdf/utils.js +4 -4
  56. package/dist/tools/process.js +8 -5
  57. package/dist/tools/schemas.d.ts +1 -1
  58. package/dist/tools/schemas.js +15 -6
  59. package/dist/tools/search.d.ts +32 -0
  60. package/dist/tools/search.js +202 -0
  61. package/dist/types.d.ts +1 -1
  62. package/dist/ui/config-editor/config-editor-runtime.js +6 -6
  63. package/dist/ui/config-editor/src/app.js +2 -15
  64. package/dist/utils/ab-test.js +27 -9
  65. package/dist/utils/atomic-write.d.ts +14 -0
  66. package/dist/utils/atomic-write.js +80 -0
  67. package/dist/utils/capture.d.ts +17 -1
  68. package/dist/utils/capture.js +177 -68
  69. package/dist/utils/exit-process.d.ts +24 -0
  70. package/dist/utils/exit-process.js +31 -0
  71. package/dist/utils/feature-flags.js +2 -1
  72. package/dist/utils/files/base.d.ts +3 -1
  73. package/dist/utils/files/docx.d.ts +3 -0
  74. package/dist/utils/files/docx.js +24 -9
  75. package/dist/utils/files/excel.d.ts +10 -0
  76. package/dist/utils/files/excel.js +93 -33
  77. package/dist/utils/files/factory.d.ts +22 -1
  78. package/dist/utils/files/factory.js +59 -4
  79. package/dist/utils/files/image.d.ts +12 -4
  80. package/dist/utils/files/image.js +19 -8
  81. package/dist/utils/files/index.d.ts +5 -3
  82. package/dist/utils/files/index.js +4 -3
  83. package/dist/utils/files/pdf.js +18 -36
  84. package/dist/utils/files/text.d.ts +21 -5
  85. package/dist/utils/files/text.js +90 -86
  86. package/dist/utils/internal-facts.d.ts +3 -0
  87. package/dist/utils/internal-facts.js +23 -0
  88. package/dist/utils/lazy-package.d.ts +23 -0
  89. package/dist/utils/lazy-package.js +42 -0
  90. package/dist/utils/open-browser.js +2 -1
  91. package/dist/utils/process-detection.d.ts +24 -5
  92. package/dist/utils/process-detection.js +199 -89
  93. package/dist/utils/process-tree.d.ts +14 -0
  94. package/dist/utils/process-tree.js +223 -0
  95. package/dist/utils/rename.d.ts +9 -0
  96. package/dist/utils/rename.js +74 -0
  97. package/dist/utils/ripgrep-resolver.js +9 -14
  98. package/dist/utils/shell.d.ts +42 -0
  99. package/dist/utils/shell.js +187 -0
  100. package/dist/utils/system-info.js +9 -7
  101. package/dist/utils/trackTools.js +2 -1
  102. package/dist/version.d.ts +1 -1
  103. package/dist/version.js +1 -1
  104. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  105. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  106. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  107. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  108. package/package.json +8 -2
  109. package/vendor/telemetry-contract/README.md +56 -0
  110. package/vendor/telemetry-contract/package.json +32 -0
  111. package/vendor/telemetry-contract/transport.d.ts +38 -0
  112. package/vendor/telemetry-contract/transport.js +164 -0
  113. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -1,10 +1,14 @@
1
- import { spawn } from 'child_process';
2
1
  import path from 'path';
3
2
  import fs from 'fs/promises';
4
3
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
5
- import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/sdk/client/stdio.js';
4
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
6
5
  import { fileURLToPath } from 'url';
7
6
  import { captureRemote } from '../utils/capture.js';
7
+ import { resolveShellPath } from '../utils/shell.js';
8
+ /** The device's environment, as the string map a child process gets */
9
+ function deviceEnvironment() {
10
+ return Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== undefined));
11
+ }
8
12
  // Restart pacing: grows with consecutive failures, caps, and jitters so a
9
13
  // fleet-wide fault does not stampede.
10
14
  //
@@ -76,12 +80,17 @@ export class DesktopCommanderIntegration {
76
80
  console.debug('[DEBUG] MCP config:', JSON.stringify(config, null, 2));
77
81
  try {
78
82
  console.debug('[DEBUG] Creating StdioClientTransport');
83
+ // The server gets the device's whole environment, as a Desktop
84
+ // Commander started directly would: what the user set for the
85
+ // device (telemetry opt-out, container variables, what commands
86
+ // need) must reach the tools. The SDK's default passes only a
87
+ // minimal set, meant for starting untrusted servers.
79
88
  // DC_REMOTE_DEVICE tells the spawned server it is serving remote
80
89
  // services, so it suppresses local-only behavior like opening the
81
90
  // welcome page in a browser the remote user would never see.
82
91
  this.mcpTransport = new StdioClientTransport({
83
92
  ...config,
84
- env: { ...getDefaultEnvironment(), ...config.env, DC_REMOTE_DEVICE: 'true' }
93
+ env: { ...deviceEnvironment(), ...config.env, DC_REMOTE_DEVICE: 'true' }
85
94
  });
86
95
  // Create MCP client
87
96
  console.debug('[DEBUG] Creating MCP Client');
@@ -239,32 +248,17 @@ export class DesktopCommanderIntegration {
239
248
  // Option 2: Global Installation
240
249
  const commandName = 'desktop-commander';
241
250
  console.debug('[DEBUG] Checking for global command:', commandName);
242
- try {
243
- await new Promise((resolve, reject) => {
244
- // Use platform-appropriate command to check if the command exists in PATH
245
- // We can't run it directly as it's an stdio MCP server that waits for input
246
- const whichCommand = process.platform === 'win32' ? 'where' : 'which';
247
- console.debug('[DEBUG] Using platform command:', whichCommand, 'on platform:', process.platform);
248
- const check = spawn(whichCommand, [commandName], { windowsHide: true }); // Prevent visible console windows on Windows
249
- check.on('error', (err) => {
250
- console.debug('[DEBUG] Spawn error for', whichCommand, ':', err.message);
251
- reject(err);
252
- });
253
- check.on('close', (code) => {
254
- console.debug('[DEBUG]', whichCommand, 'exited with code:', code);
255
- return code === 0 ? resolve() : reject(new Error('Command not found'));
256
- });
257
- });
258
- console.debug(' - Found global desktop-commander CLI');
251
+ // Looked up in PATH's folders, never the working folder (which 'where'
252
+ // searched first on Windows), and started by that full path
253
+ const globalCommand = resolveShellPath(commandName);
254
+ if (globalCommand) {
255
+ console.debug(' - Found global desktop-commander CLI:', globalCommand);
259
256
  return {
260
- command: commandName,
257
+ command: globalCommand,
261
258
  args: []
262
259
  };
263
260
  }
264
- catch (err) {
265
- console.debug('[DEBUG] Global command not found:', err);
266
- // Global command not found
267
- }
261
+ console.debug('[DEBUG] Global command not found on PATH');
268
262
  console.debug('[DEBUG] No MCP config resolved');
269
263
  return null;
270
264
  }
@@ -4,6 +4,8 @@ export interface MCPDeviceOptions {
4
4
  persistSession?: boolean;
5
5
  }
6
6
  export declare function getRemoteDeviceConfigPath(): string;
7
+ /** `remote --logout`: removes device.json, under the lock a running device's save takes. */
8
+ export declare function removeRemoteDeviceConfig(configPath?: string): Promise<void>;
7
9
  export declare class MCPDevice {
8
10
  private baseServerUrl;
9
11
  private remoteChannel;
@@ -19,6 +21,14 @@ export declare class MCPDevice {
19
21
  * whatever is still in flight.
20
22
  */
21
23
  private configWriteChain;
24
+ /**
25
+ * device.json's text when this run last loaded or saved it. From then on, a
26
+ * file that is gone or holds other text was removed (`remote --logout`) or
27
+ * replaced (a login after it) by someone else.
28
+ */
29
+ private configTextOnDisk?;
30
+ /** device.json was removed or replaced after this run loaded or saved it: nothing is saved again this run. */
31
+ private loggedOutLocally;
22
32
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
23
33
  private seenCallIds;
24
34
  constructor(options?: MCPDeviceOptions);
@@ -26,6 +36,8 @@ export declare class MCPDevice {
26
36
  start(): Promise<void>;
27
37
  private findPersistedDeviceWithRetry;
28
38
  loadPersistedConfig(): Promise<any>;
39
+ /** device.json's text, or undefined when there is none. Errors other than "not found" go to the caller, which logs them. */
40
+ private readConfigText;
29
41
  clearPersistedConfig(): Promise<void>;
30
42
  /**
31
43
  * Queue a config write. Returns the queued write, so a caller that must not
@@ -47,5 +59,7 @@ export declare class MCPDevice {
47
59
  /** Record a handled call id, evicting the oldest once the cap is reached. */
48
60
  private rememberCallId;
49
61
  handleNewToolCall(payload: any): Promise<void>;
62
+ /** Reports a tool call that failed, or whose result couldn't be saved, and writes its "failed" row. */
63
+ private reportToolCallFailure;
50
64
  shutdown(): Promise<void>;
51
65
  }
@@ -6,7 +6,11 @@ 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
@@ -26,6 +30,40 @@ const RECOVERY_MIN_DELAY_MS = 1000;
26
30
  export function getRemoteDeviceConfigPath() {
27
31
  return path.join(os.homedir(), '.desktop-commander-device', 'device.json');
28
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
+ }
29
67
  export class MCPDevice {
30
68
  constructor(options = {}) {
31
69
  /**
@@ -35,6 +73,8 @@ export class MCPDevice {
35
73
  * whatever is still in flight.
36
74
  */
37
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;
38
78
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
39
79
  this.seenCallIds = new Set();
40
80
  this.baseServerUrl = process.env.MCP_SERVER_URL || 'https://mcp.desktopcommander.app';
@@ -66,24 +106,24 @@ export class MCPDevice {
66
106
  if (this.isShuttingDown) {
67
107
  console.log(`\n${signal} received, but already shutting down...`);
68
108
  // Force exit if we get multiple signals
69
- process.exit(1);
109
+ exitProcess(1);
70
110
  return;
71
111
  }
72
112
  console.log(`\n${signal} received, initiating graceful shutdown...`);
73
113
  // Force exit after 5 seconds if graceful shutdown hangs
74
114
  const forceExit = setTimeout(() => {
75
115
  console.error('\n⚠️ Graceful shutdown timed out, forcing exit...');
76
- process.exit(1);
116
+ exitProcess(1);
77
117
  }, 5000);
78
118
  try {
79
119
  await this.shutdown();
80
120
  clearTimeout(forceExit);
81
- process.exit(0);
121
+ exitProcess(0);
82
122
  }
83
123
  catch (error) {
84
124
  console.error('Error during shutdown:', error);
85
125
  await captureRemote('remote_device_shutdown_handler_error', { error });
86
- process.exit(1);
126
+ exitProcess(1);
87
127
  }
88
128
  };
89
129
  // Remove any existing SIGINT/SIGTERM listeners to prevent default behavior
@@ -94,14 +134,14 @@ export class MCPDevice {
94
134
  handleShutdown('SIGINT').catch((error) => {
95
135
  console.error('Fatal error during shutdown:', error);
96
136
  captureRemote('remote_device_shutdown_handler_error', { error, signal: 'SIGINT' }).catch(() => { });
97
- process.exit(1);
137
+ exitProcess(1);
98
138
  });
99
139
  });
100
140
  process.on('SIGTERM', () => {
101
141
  handleShutdown('SIGTERM').catch((error) => {
102
142
  console.error('Fatal error during shutdown:', error);
103
143
  captureRemote('remote_device_shutdown_handler_error', { error, signal: 'SIGTERM' }).catch(() => { });
104
- process.exit(1);
144
+ exitProcess(1);
105
145
  });
106
146
  });
107
147
  }
@@ -247,7 +287,7 @@ export class MCPDevice {
247
287
  }
248
288
  await captureRemote('remote_device_startup_failed', { error });
249
289
  await this.shutdown();
250
- process.exit(1);
290
+ exitProcess(1);
251
291
  }
252
292
  }
253
293
  async findPersistedDeviceWithRetry(deviceId) {
@@ -270,9 +310,18 @@ export class MCPDevice {
270
310
  try {
271
311
  console.debug('[DEBUG] Loading persisted config from:', this.configPath);
272
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;
273
315
  const config = JSON.parse(data);
274
316
  this.deviceId = config?.deviceId;
275
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
+ }
276
325
  if (config.session && this.persistSession) {
277
326
  console.log('💾 Found persisted session for device ' + this.deviceId);
278
327
  console.debug('[DEBUG] Session found in config, returning session');
@@ -304,7 +353,20 @@ export class MCPDevice {
304
353
  // No need to ensure device ID here
305
354
  }
306
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
+ }
307
367
  async clearPersistedConfig() {
368
+ // Removed by this run itself, not by a logout
369
+ this.configTextOnDisk = undefined;
308
370
  try {
309
371
  await fs.rm(this.configPath, { force: true });
310
372
  console.debug('[DEBUG] Cleared stale persisted config:', this.configPath);
@@ -324,6 +386,8 @@ export class MCPDevice {
324
386
  }
325
387
  async writePersistedConfig(rotated) {
326
388
  try {
389
+ if (this.loggedOutLocally)
390
+ return;
327
391
  console.debug('[DEBUG] Saving persisted config, persistSession:', this.persistSession);
328
392
  // Prefer the session TOKEN_REFRESHED handed us over re-reading it. A
329
393
  // sign-out landing in that gap answers null, and the write below would
@@ -347,17 +411,37 @@ export class MCPDevice {
347
411
  // Ensure the config directory exists
348
412
  console.debug('[DEBUG] Creating config directory:', path.dirname(this.configPath));
349
413
  await fs.mkdir(path.dirname(this.configPath), { recursive: true });
350
- // Write then rename: the rename is the commit boundary, so a write
351
- // cut short leaves the previous complete session rather than a
352
- // truncated file. loadPersistedConfig() answers a JSON.parse
353
- // failure with null, which costs a full browser reauthorization.
354
- // Same shape as ConfigManager's atomic save; the pid keeps two
355
- // processes off each other's temp file, and configWriteChain keeps
356
- // this one off its own.
357
- const tempPath = `${this.configPath}.${process.pid}.tmp`;
358
- await fs.writeFile(tempPath, JSON.stringify(config, null, 2), { mode: 0o600 });
359
- await fs.rename(tempPath, this.configPath);
360
- 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
+ }
361
445
  }
362
446
  catch (error) {
363
447
  console.error(' - ❌ Failed to save config:', error.message);
@@ -456,6 +540,9 @@ export class MCPDevice {
456
540
  console.debug('[DEBUG] Ignoring tool call for different device');
457
541
  return;
458
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 });
459
546
  console.log(`🔧 Received tool call ${call_id}: ${tool_name} ${JSON.stringify(tool_args)} metadata: ${JSON.stringify(metadata)}`);
460
547
  // LOCAL claim first — this is the authoritative guard against executing
461
548
  // a call twice. During the transition both transports deliver every call
@@ -468,6 +555,9 @@ export class MCPDevice {
468
555
  return;
469
556
  }
470
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;
471
561
  try {
472
562
  // DB claim second — keeps the row state machine honest, gives
473
563
  // cross-restart/cross-process protection, and is observable. It may
@@ -479,7 +569,6 @@ export class MCPDevice {
479
569
  // markCallExecuting already logged the duplicate-delivery skip.
480
570
  return;
481
571
  }
482
- let result;
483
572
  // Handle 'ping' tool specially
484
573
  if (tool_name === 'ping') {
485
574
  result = {
@@ -500,30 +589,48 @@ export class MCPDevice {
500
589
  setTimeout(async () => {
501
590
  console.log('🛑 Remote shutdown requested. Exiting...');
502
591
  await this.shutdown();
503
- process.exit(0);
592
+ exitProcess(0);
504
593
  }, 1000);
505
594
  }
506
595
  else {
507
596
  // Execute other tools using desktop integration
508
597
  result = await this.desktop.callClientTool(tool_name, tool_args, metadata);
509
598
  }
510
- console.log(`✅ Tool call ${tool_name} completed:\r\n ${JSON.stringify(result)}`);
511
- // The result write itself notifies the server (a DB trigger).
512
- await this.remoteChannel.updateCallResult(call_id, 'completed', result);
513
599
  }
514
600
  catch (error) {
515
601
  console.error(`❌ Tool call ${tool_name} failed:`, error.message);
516
- // The failure path must not fail: this method's promise is discarded
517
- // at every call site, so a throw here becomes an unhandled rejection
518
- // 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 {
519
610
  try {
520
- await captureRemote('remote_device_tool_call_failed', { error, tool_name });
521
- await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
611
+ await this.remoteChannel.updateCallResult(call_id, 'completed', result);
522
612
  }
523
- catch (reportError) {
524
- console.error(`❌ Could not report failure for ${call_id}:`, reportError?.message);
613
+ finally {
614
+ observeTransport({ stage: 'tool_call_completed', ...observation });
525
615
  }
526
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
+ }
527
634
  }
528
635
  async shutdown() {
529
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
+ }
@@ -0,0 +1,44 @@
1
+ import { type IClientOptions } from 'mqtt';
2
+ /** The server publishes identifiers only; RemoteChannel fetches the durable command row. */
3
+ export interface MqttDoorbell {
4
+ call_id: string;
5
+ user_id: string;
6
+ device_id: string;
7
+ expires_at: string;
8
+ }
9
+ export interface MqttConfig {
10
+ url: string;
11
+ options: IClientOptions;
12
+ }
13
+ /**
14
+ * Read opt-in connector settings for RemoteChannel registration/restoration.
15
+ * Return null for legacy installs; only explicit loopback development may bypass mutual TLS.
16
+ */
17
+ export declare function readMqttConfig(env?: NodeJS.ProcessEnv, credentials?: {
18
+ cert: string;
19
+ key: string;
20
+ }): MqttConfig | null;
21
+ /** Match the server publisher's exact device topic without granting wildcard subscriptions. */
22
+ export declare function mqttDoorbellTopic(userId: string, deviceId: string): string;
23
+ /** A per-device subscription; payload validation precedes all database access. */
24
+ export declare class MqttDoorbellReceiver {
25
+ private readonly config;
26
+ private readonly userId;
27
+ private readonly deviceId;
28
+ private readonly onDoorbell;
29
+ private readonly onReady;
30
+ private client;
31
+ private stopped;
32
+ private ready;
33
+ private cancelStart;
34
+ private readonly topic;
35
+ /** Bind verified registration identity and RemoteChannel's delivery/readiness callbacks once. */
36
+ constructor(config: MqttConfig, userId: string, deviceId: string, onDoorbell: (payload: MqttDoorbell) => Promise<void>, onReady: (ready: boolean) => Promise<void>);
37
+ /**
38
+ * Connect once and resolve after QoS 1 SUBACK plus the readiness callback.
39
+ * MQTT.js owns socket reconnects; this receiver owns resubscription and admission.
40
+ */
41
+ start(): Promise<void>;
42
+ /** Stop reconnects, reject pending startup and withdraw readiness on sign-out/shutdown. */
43
+ stop(): Promise<void>;
44
+ }