@wonderwhy-er/desktop-commander 0.2.51 → 0.3.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 (121) 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 +55 -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 +47 -4
  17. package/dist/remote-device/desktop-commander-integration.d.ts +21 -0
  18. package/dist/remote-device/desktop-commander-integration.js +121 -40
  19. package/dist/remote-device/device-authenticator.d.ts +13 -1
  20. package/dist/remote-device/device-authenticator.js +87 -47
  21. package/dist/remote-device/device.d.ts +14 -0
  22. package/dist/remote-device/device.js +244 -51
  23. package/dist/remote-device/diagnostics/device-log.d.ts +63 -0
  24. package/dist/remote-device/diagnostics/device-log.js +219 -0
  25. package/dist/remote-device/diagnostics/redact.d.ts +1 -0
  26. package/dist/remote-device/diagnostics/redact.js +76 -0
  27. package/dist/remote-device/diagnostics/report.d.ts +118 -0
  28. package/dist/remote-device/diagnostics/report.js +748 -0
  29. package/dist/remote-device/diagnostics/upload.d.ts +11 -0
  30. package/dist/remote-device/diagnostics/upload.js +59 -0
  31. package/dist/remote-device/realtime-health-telemetry.d.ts +35 -0
  32. package/dist/remote-device/realtime-health-telemetry.js +110 -0
  33. package/dist/remote-device/remote-channel.d.ts +86 -5
  34. package/dist/remote-device/remote-channel.js +470 -68
  35. package/dist/remote-device/scripts/blocking-offline-update.js +108 -69
  36. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  37. package/dist/remote-device/transport-telemetry.js +48 -0
  38. package/dist/search-manager.d.ts +239 -27
  39. package/dist/search-manager.js +746 -312
  40. package/dist/server.js +157 -303
  41. package/dist/terminal-manager.d.ts +138 -21
  42. package/dist/terminal-manager.js +300 -215
  43. package/dist/tools/config.d.ts +1 -1
  44. package/dist/tools/config.js +21 -70
  45. package/dist/tools/edit.js +12 -4
  46. package/dist/tools/filesystem.d.ts +30 -6
  47. package/dist/tools/filesystem.js +246 -140
  48. package/dist/tools/improved-process-tools.d.ts +9 -3
  49. package/dist/tools/improved-process-tools.js +171 -68
  50. package/dist/tools/pdf/extract-images.d.ts +2 -0
  51. package/dist/tools/pdf/extract-images.js +4 -1
  52. package/dist/tools/pdf/index.d.ts +5 -3
  53. package/dist/tools/pdf/index.js +4 -3
  54. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  55. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  56. package/dist/tools/pdf/manipulations.d.ts +12 -1
  57. package/dist/tools/pdf/manipulations.js +17 -4
  58. package/dist/tools/pdf/markdown.d.ts +96 -0
  59. package/dist/tools/pdf/markdown.js +485 -20
  60. package/dist/tools/pdf/utils.d.ts +2 -2
  61. package/dist/tools/pdf/utils.js +4 -4
  62. package/dist/tools/process.js +8 -5
  63. package/dist/tools/schemas.d.ts +1 -11
  64. package/dist/tools/schemas.js +15 -14
  65. package/dist/types.d.ts +1 -1
  66. package/dist/ui/config-editor/config-editor-runtime.js +53 -53
  67. package/dist/ui/config-editor/src/app.js +2 -15
  68. package/dist/ui/file-preview/preview-runtime.js +190 -182
  69. package/dist/utils/ab-test.js +27 -9
  70. package/dist/utils/atomic-write.d.ts +14 -0
  71. package/dist/utils/atomic-write.js +80 -0
  72. package/dist/utils/capture.d.ts +17 -1
  73. package/dist/utils/capture.js +177 -68
  74. package/dist/utils/exit-process.d.ts +24 -0
  75. package/dist/utils/exit-process.js +31 -0
  76. package/dist/utils/feature-flags.js +2 -1
  77. package/dist/utils/files/base.d.ts +3 -1
  78. package/dist/utils/files/docx.d.ts +3 -0
  79. package/dist/utils/files/docx.js +24 -9
  80. package/dist/utils/files/excel.d.ts +10 -0
  81. package/dist/utils/files/excel.js +93 -33
  82. package/dist/utils/files/factory.d.ts +22 -1
  83. package/dist/utils/files/factory.js +59 -4
  84. package/dist/utils/files/image.d.ts +12 -4
  85. package/dist/utils/files/image.js +19 -8
  86. package/dist/utils/files/index.d.ts +5 -3
  87. package/dist/utils/files/index.js +4 -3
  88. package/dist/utils/files/pdf.js +18 -36
  89. package/dist/utils/files/text.d.ts +21 -5
  90. package/dist/utils/files/text.js +90 -86
  91. package/dist/utils/internal-facts.d.ts +3 -0
  92. package/dist/utils/internal-facts.js +23 -0
  93. package/dist/utils/lazy-package.d.ts +25 -0
  94. package/dist/utils/lazy-package.js +44 -0
  95. package/dist/utils/open-browser.js +2 -1
  96. package/dist/utils/process-detection.d.ts +24 -5
  97. package/dist/utils/process-detection.js +199 -89
  98. package/dist/utils/process-tree.d.ts +14 -0
  99. package/dist/utils/process-tree.js +223 -0
  100. package/dist/utils/rename.d.ts +9 -0
  101. package/dist/utils/rename.js +74 -0
  102. package/dist/utils/ripgrep-resolver.js +9 -14
  103. package/dist/utils/shell.d.ts +42 -0
  104. package/dist/utils/shell.js +187 -0
  105. package/dist/utils/system-info.d.ts +1 -0
  106. package/dist/utils/system-info.js +40 -25
  107. package/dist/utils/trackTools.js +2 -1
  108. package/dist/utils/usageTracker.d.ts +0 -39
  109. package/dist/utils/usageTracker.js +1 -161
  110. package/dist/version.d.ts +1 -1
  111. package/dist/version.js +1 -1
  112. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  113. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  114. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  115. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  116. package/package.json +32 -16
  117. package/vendor/telemetry-contract/README.md +56 -0
  118. package/vendor/telemetry-contract/package.json +32 -0
  119. package/vendor/telemetry-contract/transport.d.ts +38 -0
  120. package/vendor/telemetry-contract/transport.js +164 -0
  121. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -11,6 +11,10 @@ export declare class DesktopCommanderIntegration {
11
11
  private isShuttingDown;
12
12
  private disconnectHandler;
13
13
  private reinitPromise;
14
+ /** Consecutive failed restarts; reset by a successful one. */
15
+ private restartAttempts;
16
+ /** Before this, ensureReady() refuses rather than spawning again. */
17
+ private nextRestartAt;
14
18
  /** True only while the local stdio child is actually reachable. */
15
19
  get ready(): boolean;
16
20
  /**
@@ -34,7 +38,15 @@ export declare class DesktopCommanderIntegration {
34
38
  * if the child is crashing on startup, each tool call fails with the real
35
39
  * reason instead of spinning respawns in the background.
36
40
  */
41
+ /** Same refusal ensureReady() makes up front, for an attempt already running. */
42
+ private abortIfShuttingDown;
37
43
  ensureReady(): Promise<void>;
44
+ /** One restart, with the pacing bookkeeping around it. */
45
+ private restartChild;
46
+ /** Drop an unusable child so `ready` is false and the next attempt rebuilds. */
47
+ private discardChild;
48
+ /** How long ensureReady() will refuse for. 0 when it will try immediately. */
49
+ get msUntilRestartAllowed(): number;
38
50
  resolveMcpConfig(): Promise<McpConfig | null>;
39
51
  callClientTool(toolName: string, args: any, metadata?: any): Promise<{
40
52
  [x: string]: unknown;
@@ -92,6 +104,7 @@ export declare class DesktopCommanderIntegration {
92
104
  type: "resource_link";
93
105
  description?: string | undefined;
94
106
  mimeType?: string | undefined;
107
+ size?: number | undefined;
95
108
  annotations?: {
96
109
  audience?: ("user" | "assistant")[] | undefined;
97
110
  priority?: number | undefined;
@@ -128,6 +141,14 @@ export declare class DesktopCommanderIntegration {
128
141
  } | undefined;
129
142
  } | undefined;
130
143
  }>;
144
+ /**
145
+ * Prove the child can serve a request, not merely that it completed the
146
+ * handshake. connect() only exchanges `initialize`, which says the process
147
+ * is up and speaks MCP - the same substitution issue #4 is about, one level
148
+ * down. Throws so initialize() can withhold readiness; listClientTools()
149
+ * keeps swallowing, because registerDevice() wants a tool list or nothing.
150
+ */
151
+ private verifyExecution;
131
152
  listClientTools(): Promise<{
132
153
  tools: {
133
154
  inputSchema: {
@@ -1,10 +1,28 @@
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
+ }
12
+ // Restart pacing: grows with consecutive failures, caps, and jitters so a
13
+ // fleet-wide fault does not stampede.
14
+ //
15
+ // The cap is what a user waits after fixing whatever broke the child, so it is
16
+ // deliberately short. It can be: readiness now keeps an unusable device out of
17
+ // the server's selection, so no routed calls arrive to spawn anything, and the
18
+ // only thing asking for a restart is this connector's own recovery loop. The
19
+ // cost of the short cap is one short-lived spawn every few seconds while a
20
+ // child stays broken; the cost of a long one is a device that sits dead for
21
+ // most a minute after it could have come back.
22
+ const RESTART_BACKOFF_CAP_MS = 5000;
23
+ const restartBackoffMs = (attempt) =>
24
+ // Cap AFTER jitter, so the cap is the wait this comment claims it is.
25
+ Math.min(RESTART_BACKOFF_CAP_MS, 250 * 2 ** Math.min(attempt, 5) * (0.5 + Math.random()));
8
26
  const __filename = fileURLToPath(import.meta.url);
9
27
  const __dirname = path.dirname(__filename);
10
28
  export class DesktopCommanderIntegration {
@@ -15,6 +33,10 @@ export class DesktopCommanderIntegration {
15
33
  this.isShuttingDown = false;
16
34
  this.disconnectHandler = null;
17
35
  this.reinitPromise = null;
36
+ /** Consecutive failed restarts; reset by a successful one. */
37
+ this.restartAttempts = 0;
38
+ /** Before this, ensureReady() refuses rather than spawning again. */
39
+ this.nextRestartAt = 0;
18
40
  }
19
41
  /** True only while the local stdio child is actually reachable. */
20
42
  get ready() {
@@ -58,12 +80,17 @@ export class DesktopCommanderIntegration {
58
80
  console.debug('[DEBUG] MCP config:', JSON.stringify(config, null, 2));
59
81
  try {
60
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.
61
88
  // DC_REMOTE_DEVICE tells the spawned server it is serving remote
62
89
  // services, so it suppresses local-only behavior like opening the
63
90
  // welcome page in a browser the remote user would never see.
64
91
  this.mcpTransport = new StdioClientTransport({
65
92
  ...config,
66
- env: { ...getDefaultEnvironment(), ...config.env, DC_REMOTE_DEVICE: 'true' }
93
+ env: { ...deviceEnvironment(), ...config.env, DC_REMOTE_DEVICE: 'true' }
67
94
  });
68
95
  // Create MCP client
69
96
  console.debug('[DEBUG] Creating MCP Client');
@@ -75,8 +102,14 @@ export class DesktopCommanderIntegration {
75
102
  });
76
103
  // Connect to Desktop Commander
77
104
  console.debug('[DEBUG] Connecting MCP client to transport');
105
+ // shutdown() sets the flag and tears down what exists; it cannot
106
+ // reach back into a restart already in flight. Without these
107
+ // checks that restart carries on past the teardown, connects a
108
+ // child nobody will close and sets `ready` behind it. The catch
109
+ // below discards whatever this attempt built.
110
+ this.abortIfShuttingDown();
78
111
  await this.mcpClient.connect(this.mcpTransport);
79
- this.isReady = true;
112
+ this.abortIfShuttingDown();
80
113
  // Supervise the local half. Without these, a child crash is silent:
81
114
  // the SDK clears its transport and every subsequent call throws
82
115
  // "Not connected" with nothing tying it back to the death.
@@ -99,23 +132,24 @@ export class DesktopCommanderIntegration {
99
132
  // respawns a live child. Real death arrives through onclose, which
100
133
  // only fires once the transport has actually closed.
101
134
  this.mcpClient.onerror = (err) => console.error(` - ⚠️ Local Desktop Commander MCP error: ${err?.message ?? String(err)}`);
135
+ // Ready means the child has served a request, not that it
136
+ // completed the handshake — one definition, whichever path
137
+ // started the child, so no caller has to remember a second
138
+ // step to get the stronger meaning. A failure here lands in
139
+ // the catch below and leaves nothing half-built behind.
140
+ await this.verifyExecution();
141
+ this.abortIfShuttingDown();
142
+ this.isReady = true;
102
143
  console.log(' - 🔌 Connected to Desktop Commander MCP');
103
144
  console.debug('[DEBUG] Desktop Commander MCP connection successful');
104
145
  }
105
146
  catch (error) {
106
- console.error(' - ❌ Failed to connect to Desktop Commander MCP:', error);
107
- console.debug('[DEBUG] MCP connection error:', error);
108
- // Leave no half-built client behind, or ensureReady() would treat the
109
- // corpse as live on the next attempt.
110
- this.isReady = false;
111
- this.mcpClient = null;
112
- if (this.mcpTransport) {
113
- try {
114
- await this.mcpTransport.close();
115
- }
116
- catch { /* already dead — nothing to salvage */ }
117
- this.mcpTransport = null;
118
- }
147
+ console.error(' - ❌ Failed to start Desktop Commander MCP:', error);
148
+ console.debug('[DEBUG] MCP startup error:', error);
149
+ // Leave no half-built child behind, or ensureReady() would treat
150
+ // the corpse as live on the next attempt. Covers a child that
151
+ // connected and then failed verification, too.
152
+ await this.discardChild();
119
153
  await captureRemote('desktop_integration_init_failed', { error });
120
154
  throw error;
121
155
  }
@@ -126,6 +160,12 @@ export class DesktopCommanderIntegration {
126
160
  * if the child is crashing on startup, each tool call fails with the real
127
161
  * reason instead of spinning respawns in the background.
128
162
  */
163
+ /** Same refusal ensureReady() makes up front, for an attempt already running. */
164
+ abortIfShuttingDown() {
165
+ if (this.isShuttingDown) {
166
+ throw new Error('Desktop Commander integration is shutting down');
167
+ }
168
+ }
129
169
  async ensureReady() {
130
170
  if (this.ready)
131
171
  return;
@@ -133,14 +173,58 @@ export class DesktopCommanderIntegration {
133
173
  throw new Error('Desktop Commander integration is shutting down');
134
174
  }
135
175
  if (!this.reinitPromise) {
176
+ // A child that crashes on start would otherwise be respawned once
177
+ // per routed tool call. Refuse inside the window instead, so the
178
+ // caller gets the real reason and the machine is left alone.
179
+ const waitMs = this.nextRestartAt - Date.now();
180
+ if (waitMs > 0) {
181
+ throw new Error(`Local Desktop Commander MCP failed to start ${this.restartAttempts} time(s); ` +
182
+ `next attempt in ${Math.ceil(waitMs / 1000)}s`);
183
+ }
136
184
  console.log(' - ♻️ Local Desktop Commander MCP is not running; restarting it...');
137
- this.reinitPromise = this.initialize().finally(() => {
185
+ this.reinitPromise = this.restartChild().finally(() => {
138
186
  this.reinitPromise = null;
139
187
  });
140
188
  }
141
189
  // Concurrent calls share the single in-flight restart.
142
190
  await this.reinitPromise;
143
191
  }
192
+ /** One restart, with the pacing bookkeeping around it. */
193
+ async restartChild() {
194
+ try {
195
+ // initialize() resolves only once the child has served a request,
196
+ // so there is nothing further to prove here.
197
+ await this.initialize();
198
+ this.restartAttempts = 0;
199
+ this.nextRestartAt = 0;
200
+ }
201
+ catch (error) {
202
+ await this.discardChild();
203
+ this.restartAttempts++;
204
+ this.nextRestartAt = Date.now() + restartBackoffMs(this.restartAttempts);
205
+ throw error;
206
+ }
207
+ }
208
+ /** Drop an unusable child so `ready` is false and the next attempt rebuilds. */
209
+ async discardChild() {
210
+ this.isReady = false;
211
+ const client = this.mcpClient;
212
+ const transport = this.mcpTransport;
213
+ this.mcpClient = null;
214
+ this.mcpTransport = null;
215
+ try {
216
+ await client?.close();
217
+ }
218
+ catch { /* already dead */ }
219
+ try {
220
+ await transport?.close();
221
+ }
222
+ catch { /* already dead */ }
223
+ }
224
+ /** How long ensureReady() will refuse for. 0 when it will try immediately. */
225
+ get msUntilRestartAllowed() {
226
+ return Math.max(0, this.nextRestartAt - Date.now());
227
+ }
144
228
  async resolveMcpConfig() {
145
229
  console.debug('[DEBUG] Resolving MCP config...');
146
230
  // Option 1: Development/Local Build
@@ -164,32 +248,17 @@ export class DesktopCommanderIntegration {
164
248
  // Option 2: Global Installation
165
249
  const commandName = 'desktop-commander';
166
250
  console.debug('[DEBUG] Checking for global command:', commandName);
167
- try {
168
- await new Promise((resolve, reject) => {
169
- // Use platform-appropriate command to check if the command exists in PATH
170
- // We can't run it directly as it's an stdio MCP server that waits for input
171
- const whichCommand = process.platform === 'win32' ? 'where' : 'which';
172
- console.debug('[DEBUG] Using platform command:', whichCommand, 'on platform:', process.platform);
173
- const check = spawn(whichCommand, [commandName], { windowsHide: true }); // Prevent visible console windows on Windows
174
- check.on('error', (err) => {
175
- console.debug('[DEBUG] Spawn error for', whichCommand, ':', err.message);
176
- reject(err);
177
- });
178
- check.on('close', (code) => {
179
- console.debug('[DEBUG]', whichCommand, 'exited with code:', code);
180
- return code === 0 ? resolve() : reject(new Error('Command not found'));
181
- });
182
- });
183
- 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);
184
256
  return {
185
- command: commandName,
257
+ command: globalCommand,
186
258
  args: []
187
259
  };
188
260
  }
189
- catch (err) {
190
- console.debug('[DEBUG] Global command not found:', err);
191
- // Global command not found
192
- }
261
+ console.debug('[DEBUG] Global command not found on PATH');
193
262
  console.debug('[DEBUG] No MCP config resolved');
194
263
  return null;
195
264
  }
@@ -216,6 +285,18 @@ export class DesktopCommanderIntegration {
216
285
  throw error;
217
286
  }
218
287
  }
288
+ /**
289
+ * Prove the child can serve a request, not merely that it completed the
290
+ * handshake. connect() only exchanges `initialize`, which says the process
291
+ * is up and speaks MCP - the same substitution issue #4 is about, one level
292
+ * down. Throws so initialize() can withhold readiness; listClientTools()
293
+ * keeps swallowing, because registerDevice() wants a tool list or nothing.
294
+ */
295
+ async verifyExecution() {
296
+ if (!this.mcpClient)
297
+ throw new Error('Local Desktop Commander MCP is not connected');
298
+ await this.mcpClient.listTools();
299
+ }
219
300
  async listClientTools() {
220
301
  if (!this.mcpClient)
221
302
  return { tools: [] };
@@ -1,11 +1,23 @@
1
+ import open from 'open';
2
+ import { captureRemote } from '../utils/capture.js';
1
3
  interface AuthSession {
2
4
  access_token: string;
3
5
  refresh_token: string | null;
4
6
  device_id?: string;
5
7
  }
8
+ type DeviceAuthenticatorDeps = {
9
+ fetch?: typeof fetch;
10
+ open?: typeof open;
11
+ capture?: typeof captureRemote;
12
+ monotonicNow?: () => number;
13
+ };
6
14
  export declare class DeviceAuthenticator {
7
15
  private baseServerUrl;
8
- constructor(baseServerUrl: string);
16
+ private fetchFn;
17
+ private openFn;
18
+ private captureFn;
19
+ private monotonicNow;
20
+ constructor(baseServerUrl: string, deps?: DeviceAuthenticatorDeps);
9
21
  authenticate(deviceId?: string): Promise<AuthSession>;
10
22
  private generatePKCE;
11
23
  private requestDeviceCode;
@@ -5,11 +5,15 @@ import { captureRemote } from '../utils/capture.js';
5
5
  import { observeServerDate } from './remote-channel.js';
6
6
  const CLIENT_ID = 'mcp-device';
7
7
  export class DeviceAuthenticator {
8
- constructor(baseServerUrl) {
8
+ constructor(baseServerUrl, deps = {}) {
9
9
  this.baseServerUrl = baseServerUrl;
10
+ this.fetchFn = deps.fetch ?? fetch;
11
+ this.openFn = deps.open ?? open;
12
+ this.captureFn = deps.capture ?? captureRemote;
13
+ this.monotonicNow = deps.monotonicNow ?? performance.now.bind(performance);
10
14
  }
11
15
  async authenticate(deviceId) {
12
- console.log('🔐 Starting device authorization flow...\n');
16
+ console.log('🔐 Connecting this computer...\n');
13
17
  // Generate PKCE
14
18
  const pkce = this.generatePKCE();
15
19
  // Step 1: Request device code
@@ -18,7 +22,7 @@ export class DeviceAuthenticator {
18
22
  this.displayUserInstructions(deviceAuth);
19
23
  // Step 3: Poll for authorization
20
24
  const tokens = await this.pollForAuthorization(deviceAuth, pkce.verifier);
21
- console.log(' - ✅ Authorization successful!\n');
25
+ console.log('✅ Device verified\n');
22
26
  return tokens;
23
27
  }
24
28
  generatePKCE() {
@@ -28,27 +32,50 @@ export class DeviceAuthenticator {
28
32
  }
29
33
  async requestDeviceCode(codeChallenge, deviceId) {
30
34
  console.log(' - 📡 Requesting device code...');
31
- const response = await fetch(`${this.baseServerUrl}/device/start`, {
32
- method: 'POST',
33
- headers: { 'Content-Type': 'application/json' },
34
- body: JSON.stringify({
35
- client_id: CLIENT_ID,
36
- scope: 'mcp:tools',
37
- device_name: os.hostname(),
38
- device_type: 'mcp',
39
- device_id: deviceId,
40
- code_challenge: codeChallenge,
41
- code_challenge_method: 'S256',
42
- }),
35
+ const startedAt = this.monotonicNow();
36
+ await this.captureFn('remote_device_auth_request_started', {
37
+ has_existing_device_id: Boolean(deviceId),
43
38
  });
39
+ let response;
40
+ try {
41
+ response = await this.fetchFn(`${this.baseServerUrl}/device/start`, {
42
+ method: 'POST',
43
+ headers: { 'Content-Type': 'application/json' },
44
+ body: JSON.stringify({
45
+ client_id: CLIENT_ID,
46
+ scope: 'mcp:tools',
47
+ device_name: os.hostname(),
48
+ device_type: 'mcp',
49
+ device_id: deviceId,
50
+ code_challenge: codeChallenge,
51
+ code_challenge_method: 'S256',
52
+ }),
53
+ });
54
+ }
55
+ catch (error) {
56
+ await this.captureFn('remote_device_auth_request_network_error', {
57
+ error,
58
+ duration_ms: Math.round(this.monotonicNow() - startedAt),
59
+ has_existing_device_id: Boolean(deviceId),
60
+ });
61
+ throw error;
62
+ }
44
63
  observeServerDate(response.headers.get('date'));
45
64
  if (!response.ok) {
46
65
  const error = await response.json().catch(() => ({ error: 'Unknown error' }));
47
66
  const errorMessage = error.error_description || 'Failed to start device flow';
48
- await captureRemote('remote_device_auth_request_failed', { error: errorMessage });
67
+ await this.captureFn('remote_device_auth_request_failed', {
68
+ error: errorMessage,
69
+ duration_ms: Math.round(this.monotonicNow() - startedAt),
70
+ has_existing_device_id: Boolean(deviceId),
71
+ });
49
72
  throw new Error(errorMessage);
50
73
  }
51
74
  const data = await response.json();
75
+ await this.captureFn('remote_device_auth_code_received', {
76
+ duration_ms: Math.round(this.monotonicNow() - startedAt),
77
+ has_existing_device_id: Boolean(deviceId),
78
+ });
52
79
  console.log(' - ✅ Device code received\n');
53
80
  return data;
54
81
  }
@@ -59,8 +86,12 @@ export class DeviceAuthenticator {
59
86
  console.log(' 2. Make sure the code matches:');
60
87
  console.log(` ${deviceAuth.user_code}\n`);
61
88
  console.log(` Code expires in ${Math.floor(deviceAuth.expires_in / 60)} minutes.\n`);
62
- // Try to open browser automatically
63
- open(deviceAuth.verification_uri_complete).catch(() => {
89
+ // Try to open browser automatically. This only confirms the OS accepted
90
+ // the launch request; page-load completion is measured by the web event.
91
+ void this.openFn(deviceAuth.verification_uri_complete)
92
+ .then(() => this.captureFn('remote_device_browser_launch_succeeded'))
93
+ .catch(async (error) => {
94
+ await this.captureFn('remote_device_browser_launch_failed', { error });
64
95
  console.log(' - Could not open browser automatically.');
65
96
  console.log(` - Please visit: ${deviceAuth.verification_uri}\n`);
66
97
  });
@@ -74,8 +105,16 @@ export class DeviceAuthenticator {
74
105
  attempt++;
75
106
  // Wait before polling
76
107
  await this.sleep(interval);
108
+ // Only transport problems are retried here. The request, and a body
109
+ // we cannot read, are the transient part; an answer the server
110
+ // actually gave (access_denied, expired_token, ...) is final. Before,
111
+ // the terminal throw sat inside this try and its own catch swallowed
112
+ // it, so a denied or expired code kept the terminal on "Waiting for
113
+ // authorization" until the whole code lifetime ran out.
114
+ let response;
115
+ let data;
77
116
  try {
78
- const response = await fetch(`${this.baseServerUrl}/device/poll`, {
117
+ response = await this.fetchFn(`${this.baseServerUrl}/device/poll`, {
79
118
  method: 'POST',
80
119
  headers: { 'Content-Type': 'application/json' },
81
120
  body: JSON.stringify({
@@ -87,43 +126,44 @@ export class DeviceAuthenticator {
87
126
  // The response that delivers the session states the server's
88
127
  // time; correct the clock before that session is used.
89
128
  observeServerDate(response.headers.get('date'));
90
- // Parse response body exactly once
91
- const data = await response.json().catch(() => ({ error: 'unknown' }));
92
- // Successful authentication
93
- if (response.ok && data.access_token) {
94
- return {
95
- device_id: data.device_id,
96
- access_token: data.access_token,
97
- refresh_token: data.refresh_token || null,
98
- };
99
- }
100
- // Check error type
101
- if (data.error === 'authorization_pending') {
102
- // Still waiting - continue polling
103
- continue;
104
- }
105
- if (data.error === 'slow_down') {
106
- // Server requested slower polling
107
- await this.sleep(interval);
108
- continue;
109
- }
110
- // Terminal error
111
- const errorMessage = data.error_description || data.error || 'Authorization failed';
112
- await captureRemote('remote_device_auth_failed', { error: errorMessage });
113
- throw new Error(errorMessage);
129
+ // Parse response body exactly once. null = not a JSON answer
130
+ // (e.g. a proxy's HTML 502), which is not a verdict on the code.
131
+ data = await response.json().catch(() => null);
114
132
  }
115
133
  catch (fetchError) {
116
- // Network error - retry unless we're out of attempts
117
134
  if (attempt >= maxAttempts) {
118
- await captureRemote('remote_device_auth_network_error', { error: fetchError });
135
+ await this.captureFn('remote_device_auth_network_error', { error: fetchError });
119
136
  throw fetchError;
120
137
  }
121
- // Continue polling on network errors
122
138
  continue;
123
139
  }
140
+ // Successful authentication
141
+ if (response.ok && data?.access_token) {
142
+ return {
143
+ device_id: data.device_id,
144
+ access_token: data.access_token,
145
+ refresh_token: data.refresh_token || null,
146
+ };
147
+ }
148
+ // Server-side trouble or an unreadable body: transient, keep polling.
149
+ if (!data || response.status >= 500) {
150
+ continue;
151
+ }
152
+ if (data.error === 'authorization_pending') {
153
+ continue;
154
+ }
155
+ if (data.error === 'slow_down') {
156
+ // Server requested slower polling
157
+ await this.sleep(interval);
158
+ continue;
159
+ }
160
+ // Terminal error: the server answered, and the answer is no.
161
+ const errorMessage = data.error_description || data.error || 'Authorization failed';
162
+ await this.captureFn('remote_device_auth_failed', { error: errorMessage, error_code: data.error ?? null });
163
+ throw new Error(errorMessage);
124
164
  }
125
165
  const timeoutError = 'Authorization timeout - user did not authorize within the time limit';
126
- await captureRemote('remote_device_auth_timeout', { error: timeoutError });
166
+ await this.captureFn('remote_device_auth_timeout', { error: timeoutError });
127
167
  throw new Error(timeoutError);
128
168
  }
129
169
  sleep(ms) {
@@ -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
  }