@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.
- package/README.md +14 -24
- package/dist/command-manager.d.ts +7 -2
- package/dist/command-manager.js +16 -11
- package/dist/config-manager.d.ts +55 -3
- package/dist/config-manager.js +329 -87
- package/dist/config-recovery.d.ts +28 -0
- package/dist/config-recovery.js +81 -0
- package/dist/config.d.ts +1 -0
- package/dist/config.js +9 -0
- package/dist/handlers/filesystem-handlers.d.ts +1 -1
- package/dist/handlers/filesystem-handlers.js +26 -16
- package/dist/handlers/search-answers.d.ts +58 -0
- package/dist/handlers/search-answers.js +172 -0
- package/dist/handlers/search-handlers.js +4 -92
- package/dist/index.js +14 -7
- package/dist/npm-scripts/remote.js +47 -4
- package/dist/remote-device/desktop-commander-integration.d.ts +21 -0
- package/dist/remote-device/desktop-commander-integration.js +121 -40
- package/dist/remote-device/device-authenticator.d.ts +13 -1
- package/dist/remote-device/device-authenticator.js +87 -47
- package/dist/remote-device/device.d.ts +14 -0
- package/dist/remote-device/device.js +244 -51
- package/dist/remote-device/diagnostics/device-log.d.ts +63 -0
- package/dist/remote-device/diagnostics/device-log.js +219 -0
- package/dist/remote-device/diagnostics/redact.d.ts +1 -0
- package/dist/remote-device/diagnostics/redact.js +76 -0
- package/dist/remote-device/diagnostics/report.d.ts +118 -0
- package/dist/remote-device/diagnostics/report.js +748 -0
- package/dist/remote-device/diagnostics/upload.d.ts +11 -0
- package/dist/remote-device/diagnostics/upload.js +59 -0
- package/dist/remote-device/realtime-health-telemetry.d.ts +35 -0
- package/dist/remote-device/realtime-health-telemetry.js +110 -0
- package/dist/remote-device/remote-channel.d.ts +86 -5
- package/dist/remote-device/remote-channel.js +470 -68
- package/dist/remote-device/scripts/blocking-offline-update.js +108 -69
- package/dist/remote-device/transport-telemetry.d.ts +32 -0
- package/dist/remote-device/transport-telemetry.js +48 -0
- package/dist/search-manager.d.ts +239 -27
- package/dist/search-manager.js +746 -312
- package/dist/server.js +157 -303
- package/dist/terminal-manager.d.ts +138 -21
- package/dist/terminal-manager.js +300 -215
- package/dist/tools/config.d.ts +1 -1
- package/dist/tools/config.js +21 -70
- package/dist/tools/edit.js +12 -4
- package/dist/tools/filesystem.d.ts +30 -6
- package/dist/tools/filesystem.js +246 -140
- package/dist/tools/improved-process-tools.d.ts +9 -3
- package/dist/tools/improved-process-tools.js +171 -68
- package/dist/tools/pdf/extract-images.d.ts +2 -0
- package/dist/tools/pdf/extract-images.js +4 -1
- package/dist/tools/pdf/index.d.ts +5 -3
- package/dist/tools/pdf/index.js +4 -3
- package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
- package/dist/tools/pdf/lib/pdf2md.js +12 -5
- package/dist/tools/pdf/manipulations.d.ts +12 -1
- package/dist/tools/pdf/manipulations.js +17 -4
- package/dist/tools/pdf/markdown.d.ts +96 -0
- package/dist/tools/pdf/markdown.js +485 -20
- package/dist/tools/pdf/utils.d.ts +2 -2
- package/dist/tools/pdf/utils.js +4 -4
- package/dist/tools/process.js +8 -5
- package/dist/tools/schemas.d.ts +1 -11
- package/dist/tools/schemas.js +15 -14
- package/dist/types.d.ts +1 -1
- package/dist/ui/config-editor/config-editor-runtime.js +53 -53
- package/dist/ui/config-editor/src/app.js +2 -15
- package/dist/ui/file-preview/preview-runtime.js +190 -182
- package/dist/utils/ab-test.js +27 -9
- package/dist/utils/atomic-write.d.ts +14 -0
- package/dist/utils/atomic-write.js +80 -0
- package/dist/utils/capture.d.ts +17 -1
- package/dist/utils/capture.js +177 -68
- package/dist/utils/exit-process.d.ts +24 -0
- package/dist/utils/exit-process.js +31 -0
- package/dist/utils/feature-flags.js +2 -1
- package/dist/utils/files/base.d.ts +3 -1
- package/dist/utils/files/docx.d.ts +3 -0
- package/dist/utils/files/docx.js +24 -9
- package/dist/utils/files/excel.d.ts +10 -0
- package/dist/utils/files/excel.js +93 -33
- package/dist/utils/files/factory.d.ts +22 -1
- package/dist/utils/files/factory.js +59 -4
- package/dist/utils/files/image.d.ts +12 -4
- package/dist/utils/files/image.js +19 -8
- package/dist/utils/files/index.d.ts +5 -3
- package/dist/utils/files/index.js +4 -3
- package/dist/utils/files/pdf.js +18 -36
- package/dist/utils/files/text.d.ts +21 -5
- package/dist/utils/files/text.js +90 -86
- package/dist/utils/internal-facts.d.ts +3 -0
- package/dist/utils/internal-facts.js +23 -0
- package/dist/utils/lazy-package.d.ts +25 -0
- package/dist/utils/lazy-package.js +44 -0
- package/dist/utils/open-browser.js +2 -1
- package/dist/utils/process-detection.d.ts +24 -5
- package/dist/utils/process-detection.js +199 -89
- package/dist/utils/process-tree.d.ts +14 -0
- package/dist/utils/process-tree.js +223 -0
- package/dist/utils/rename.d.ts +9 -0
- package/dist/utils/rename.js +74 -0
- package/dist/utils/ripgrep-resolver.js +9 -14
- package/dist/utils/shell.d.ts +42 -0
- package/dist/utils/shell.js +187 -0
- package/dist/utils/system-info.d.ts +1 -0
- package/dist/utils/system-info.js +40 -25
- package/dist/utils/trackTools.js +2 -1
- package/dist/utils/usageTracker.d.ts +0 -39
- package/dist/utils/usageTracker.js +1 -161
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
- package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
- package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
- package/package.json +32 -16
- package/vendor/telemetry-contract/README.md +56 -0
- package/vendor/telemetry-contract/package.json +32 -0
- package/vendor/telemetry-contract/transport.d.ts +38 -0
- package/vendor/telemetry-contract/transport.js +164 -0
- 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
|
-
|
|
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
|
-
|
|
116
|
+
exitProcess(1);
|
|
67
117
|
}, 5000);
|
|
68
118
|
try {
|
|
69
119
|
await this.shutdown();
|
|
70
120
|
clearTimeout(forceExit);
|
|
71
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
174
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
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
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
//
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
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
|
-
|
|
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
|
-
|
|
431
|
-
|
|
432
|
-
|
|
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
|
|
435
|
-
await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
|
|
611
|
+
await this.remoteChannel.updateCallResult(call_id, 'completed', result);
|
|
436
612
|
}
|
|
437
|
-
|
|
438
|
-
|
|
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,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The remote device log: ~/.desktop-commander-device/remote-<day>.log, the
|
|
3
|
+
* device's history that `remote --report` packs for support.
|
|
4
|
+
*
|
|
5
|
+
* `remote` passes the device's console output through startDeviceLog(). Every
|
|
6
|
+
* line is written, masked by redact() and timestamped in UTC; only the private
|
|
7
|
+
* kinds below are dropped. Each UTC weekday has its own files: remote-mon.log
|
|
8
|
+
* rotates at 1 MB into remote-mon.1.log and remote-mon.2.log. The first write
|
|
9
|
+
* on a weekday whose file is over a day old (last week's) removes that day's
|
|
10
|
+
* files first, so the log keeps at most 7 days × 3 files, 21 MB.
|
|
11
|
+
*/
|
|
12
|
+
export declare const DEVICE_LOG_MAX_BYTES: number;
|
|
13
|
+
/** How many files the log keeps per day: remote-<day>.log and its rotated older copies. */
|
|
14
|
+
export declare const DEVICE_LOG_FILES = 3;
|
|
15
|
+
/** remote-mon.log, then remote-mon.1.log, remote-mon.2.log (older); `day` is the UTC weekday, 0 = Sunday. */
|
|
16
|
+
export declare const deviceLogName: (day: number, i: number) => string;
|
|
17
|
+
/** Every name the log can use: 7 days × DEVICE_LOG_FILES. */
|
|
18
|
+
export declare const deviceLogNames: () => string[];
|
|
19
|
+
export declare function getDeviceLogDir(): string;
|
|
20
|
+
/**
|
|
21
|
+
* One line as the log keeps it: masked, or null for a private one. The report
|
|
22
|
+
* runs every stored line through this again.
|
|
23
|
+
*/
|
|
24
|
+
export declare function cleanLine(line: string): string | null;
|
|
25
|
+
export interface DeviceLogOptions {
|
|
26
|
+
/** The folder for the log files; ~/.desktop-commander-device by default. */
|
|
27
|
+
dir?: string;
|
|
28
|
+
/** The clock (ms), for the timestamps and the day; Date.now by default. Tests set it. */
|
|
29
|
+
now?: () => number;
|
|
30
|
+
/** The size at which a file rotates; DEVICE_LOG_MAX_BYTES by default. Tests set it. */
|
|
31
|
+
maxBytes?: number;
|
|
32
|
+
}
|
|
33
|
+
export declare class DeviceLog {
|
|
34
|
+
private readonly dir;
|
|
35
|
+
private readonly now;
|
|
36
|
+
private readonly maxBytes;
|
|
37
|
+
/** The UTC weekday being written; -1 before the first write. */
|
|
38
|
+
private day;
|
|
39
|
+
private size;
|
|
40
|
+
private failures;
|
|
41
|
+
/** The next printed line is the sign-in link or code. */
|
|
42
|
+
private skipNextLine;
|
|
43
|
+
constructor(options?: DeviceLogOptions);
|
|
44
|
+
private file;
|
|
45
|
+
/** One console call's arguments: each of its lines, cleaned. */
|
|
46
|
+
record(args: unknown[]): void;
|
|
47
|
+
/** Appends one line as is: callers pass text that is already masked. */
|
|
48
|
+
write(text: string): void;
|
|
49
|
+
/**
|
|
50
|
+
* The first write of a UTC weekday: if that weekday's file is over a day
|
|
51
|
+
* old, it is last week's, and its files go before today's lines start.
|
|
52
|
+
*/
|
|
53
|
+
private startDay;
|
|
54
|
+
/** Drops the day's oldest file and moves each other one a step older: remote-mon.log becomes remote-mon.1.log. */
|
|
55
|
+
private rotate;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Passes console output through the device log for this `remote` run. Each
|
|
59
|
+
* method still does what it did (so a console.debug that `remote` silenced
|
|
60
|
+
* stays silent), then the log records the call. Returns a function that puts
|
|
61
|
+
* the console back.
|
|
62
|
+
*/
|
|
63
|
+
export declare function startDeviceLog(options?: DeviceLogOptions): () => void;
|