@wonderwhy-er/desktop-commander 0.2.52 → 0.3.1-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -20
- package/README.md +1152 -1152
- package/dist/bootstrap.js +0 -0
- package/dist/command-manager.d.ts +7 -2
- package/dist/command-manager.js +16 -11
- package/dist/config-field-definitions.js +0 -0
- 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/custom-stdio.js +0 -0
- package/dist/data/onboarding-prompts.json +70 -70
- package/dist/error-handlers.js +0 -0
- package/dist/handlers/filesystem-handlers.d.ts +1 -1
- package/dist/handlers/filesystem-handlers.js +28 -18
- 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 +36 -22
- package/dist/remote-device/desktop-commander-integration.js +19 -25
- package/dist/remote-device/device.d.ts +14 -0
- package/dist/remote-device/device.js +137 -30
- 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/remote-channel.d.ts +12 -0
- package/dist/remote-device/remote-channel.js +55 -8
- package/dist/remote-device/scripts/blocking-offline-update.js +133 -96
- 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 +654 -621
- package/dist/setup-claude-server.js +942 -942
- 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 +14 -6
- package/dist/tools/filesystem.d.ts +30 -6
- package/dist/tools/filesystem.js +246 -140
- package/dist/tools/fuzzySearch.js +9 -9
- package/dist/tools/improved-process-tools.d.ts +9 -3
- package/dist/tools/improved-process-tools.js +181 -78
- 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/prompts.js +1 -1
- package/dist/tools/schemas.d.ts +1 -1
- package/dist/tools/schemas.js +15 -6
- package/dist/track-installation.js +387 -387
- package/dist/types.d.ts +1 -1
- package/dist/types.js +0 -0
- package/dist/ui/config-editor/config-editor-runtime.js +6 -6
- package/dist/ui/config-editor/index.html +13 -13
- package/dist/ui/config-editor/src/app.js +32 -45
- package/dist/ui/config-editor/src/array-modal.js +32 -32
- package/dist/ui/config-editor/styles.css +586 -586
- package/dist/ui/file-preview/index.html +16 -16
- package/dist/ui/file-preview/src/app.js +8 -8
- package/dist/ui/file-preview/src/document-layout.js +31 -31
- package/dist/ui/file-preview/src/document-outline.js +8 -8
- package/dist/ui/file-preview/src/markdown/conflict-dialog.js +33 -33
- package/dist/ui/file-preview/src/markdown/controller.js +9 -9
- package/dist/ui/file-preview/src/markdown/editor.js +31 -31
- package/dist/ui/file-preview/styles.css +1630 -1630
- package/dist/uninstall-claude-server.js +745 -745
- 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/binary.js +4 -4
- 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 +96 -36
- 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 +23 -0
- package/dist/utils/lazy-package.js +42 -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.js +99 -97
- package/dist/utils/trackTools.js +2 -1
- package/dist/utils/usageTracker.js +49 -49
- 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 +10 -3
- 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
package/dist/index.js
CHANGED
|
@@ -10,8 +10,10 @@ import { runSetup } from './npm-scripts/setup.js';
|
|
|
10
10
|
import { runUninstall } from './npm-scripts/uninstall.js';
|
|
11
11
|
import { capture } from './utils/capture.js';
|
|
12
12
|
import { logToStderr, logger } from './utils/logger.js';
|
|
13
|
+
import { exitProcess } from './utils/exit-process.js';
|
|
13
14
|
import { runRemote } from './npm-scripts/remote.js';
|
|
14
15
|
import { ensureChromeAvailable } from './tools/pdf/markdown.js';
|
|
16
|
+
import { preloadFileSupport } from './utils/files/index.js';
|
|
15
17
|
// Store messages to defer until after initialization
|
|
16
18
|
const deferredMessages = [];
|
|
17
19
|
function deferLog(level, message) {
|
|
@@ -74,21 +76,23 @@ async function runServer() {
|
|
|
74
76
|
error: errorMessage
|
|
75
77
|
});
|
|
76
78
|
logger.error(`Uncaught exception: ${errorMessage}`);
|
|
77
|
-
|
|
79
|
+
exitProcess(1);
|
|
78
80
|
});
|
|
79
|
-
// Handle unhandled rejections
|
|
81
|
+
// Handle unhandled rejections: log and keep serving. The code that created
|
|
82
|
+
// the promise has already moved on (often a library's detached cleanup, as
|
|
83
|
+
// with puppeteer's profile removal), so the server's state is intact, and
|
|
84
|
+
// exiting would drop every running process, session and search.
|
|
80
85
|
process.on('unhandledRejection', async (reason) => {
|
|
81
86
|
const errorMessage = reason instanceof Error ? reason.message : String(reason);
|
|
82
|
-
//
|
|
87
|
+
// A JSON parsing error is logged as before, and not sent to telemetry
|
|
83
88
|
if (errorMessage.includes('JSON') && errorMessage.includes('Unexpected token')) {
|
|
84
89
|
logger.error(`JSON parsing rejection: ${errorMessage}`);
|
|
85
|
-
return;
|
|
90
|
+
return;
|
|
86
91
|
}
|
|
87
92
|
capture('run_server_unhandled_rejection', {
|
|
88
93
|
error: errorMessage
|
|
89
94
|
});
|
|
90
95
|
logger.error(`Unhandled rejection: ${errorMessage}`);
|
|
91
|
-
process.exit(1);
|
|
92
96
|
});
|
|
93
97
|
capture('run_server_start');
|
|
94
98
|
deferLog('info', 'Connecting server...');
|
|
@@ -108,6 +112,9 @@ async function runServer() {
|
|
|
108
112
|
transport.sendLog('info', 'MCP fully initialized, all startup messages sent');
|
|
109
113
|
// Preemptively check/download Chrome for PDF generation (runs in background)
|
|
110
114
|
ensureChromeAvailable();
|
|
115
|
+
// Load the Excel, DOCX and PDF packages, one at a time, now that initialize
|
|
116
|
+
// has been answered; until then the calls that need them answer at once
|
|
117
|
+
preloadFileSupport();
|
|
111
118
|
};
|
|
112
119
|
await server.connect(transport);
|
|
113
120
|
}
|
|
@@ -131,7 +138,7 @@ async function runServer() {
|
|
|
131
138
|
capture('run_server_failed_start_error', {
|
|
132
139
|
error: errorMessage
|
|
133
140
|
});
|
|
134
|
-
|
|
141
|
+
exitProcess(1);
|
|
135
142
|
}
|
|
136
143
|
}
|
|
137
144
|
runServer().catch(async (error) => {
|
|
@@ -146,5 +153,5 @@ runServer().catch(async (error) => {
|
|
|
146
153
|
capture('run_server_fatal_error', {
|
|
147
154
|
error: errorMessage
|
|
148
155
|
});
|
|
149
|
-
|
|
156
|
+
exitProcess(1);
|
|
150
157
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { MCPDevice, getRemoteDeviceConfigPath } from '../remote-device/device.js';
|
|
2
|
-
import fs from 'fs/promises';
|
|
1
|
+
import { MCPDevice, getRemoteDeviceConfigPath, removeRemoteDeviceConfig } from '../remote-device/device.js';
|
|
3
2
|
import os from 'os';
|
|
4
3
|
import { captureRemote } from '../utils/capture.js';
|
|
4
|
+
import { startDeviceLog } from '../remote-device/diagnostics/device-log.js';
|
|
5
5
|
const BLUE = '\x1b[34m';
|
|
6
6
|
const RESET = '\x1b[0m';
|
|
7
7
|
function printRemoteHeader() {
|
|
@@ -18,32 +18,36 @@ function printRemoteHeader() {
|
|
|
18
18
|
}
|
|
19
19
|
export async function runRemote() {
|
|
20
20
|
if (process.argv.includes('--help') || process.argv.includes('-h')) {
|
|
21
|
-
console.log(`Desktop Commander Remote MCP device
|
|
22
|
-
|
|
23
|
-
Usage:
|
|
24
|
-
desktop-commander remote [options]
|
|
25
|
-
|
|
26
|
-
Options:
|
|
27
|
-
--logout Remove saved local Remote MCP credentials and exit
|
|
28
|
-
--
|
|
29
|
-
|
|
30
|
-
--
|
|
31
|
-
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
21
|
+
console.log(`Desktop Commander Remote MCP device
|
|
22
|
+
|
|
23
|
+
Usage:
|
|
24
|
+
desktop-commander remote [options]
|
|
25
|
+
|
|
26
|
+
Options:
|
|
27
|
+
--logout Remove saved local Remote MCP credentials and exit
|
|
28
|
+
--report Save a diagnostics zip for support, send it, and exit
|
|
29
|
+
(the device doesn't start and nothing signs in)
|
|
30
|
+
--no-upload With --report: only save the zip, don't send it
|
|
31
|
+
--no-persist-session Do not reuse or save authentication for this run
|
|
32
|
+
--disable-no-sleep Do not prevent sleep while the remote device is running
|
|
33
|
+
--debug Enable verbose debug logging
|
|
34
|
+
-h, --help Show this help
|
|
35
|
+
|
|
36
|
+
Examples:
|
|
37
|
+
npx @wonderwhy-er/desktop-commander@latest remote
|
|
38
|
+
npx @wonderwhy-er/desktop-commander@latest remote --debug
|
|
39
|
+
npx @wonderwhy-er/desktop-commander@latest remote --logout
|
|
40
|
+
npx @wonderwhy-er/desktop-commander@latest remote --report
|
|
41
|
+
|
|
42
|
+
Note:
|
|
43
|
+
--logout removes local credentials only. Revoke the device in the Remote MCP
|
|
40
44
|
dashboard if you also want to invalidate its server-side authorization.`);
|
|
41
45
|
return;
|
|
42
46
|
}
|
|
43
47
|
if (process.argv.includes('--logout')) {
|
|
44
48
|
const configPath = getRemoteDeviceConfigPath();
|
|
45
49
|
try {
|
|
46
|
-
await
|
|
50
|
+
await removeRemoteDeviceConfig(configPath);
|
|
47
51
|
console.log('🔓 Logged out locally. Saved Remote MCP device credentials were removed.');
|
|
48
52
|
console.log(` ${configPath}`);
|
|
49
53
|
}
|
|
@@ -53,6 +57,12 @@ Note:
|
|
|
53
57
|
}
|
|
54
58
|
return;
|
|
55
59
|
}
|
|
60
|
+
if (process.argv.includes('--report')) {
|
|
61
|
+
// Before the device: the report works when sign-in is broken, and never opens it
|
|
62
|
+
const { runReport } = await import('../remote-device/diagnostics/report.js');
|
|
63
|
+
await runReport();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
56
66
|
printRemoteHeader();
|
|
57
67
|
// --persist-session is kept as an accepted no-op so existing invocations
|
|
58
68
|
// and docs keep working; --no-persist-session opts back out.
|
|
@@ -68,6 +78,10 @@ Note:
|
|
|
68
78
|
if (!verbose) {
|
|
69
79
|
console.debug = () => { };
|
|
70
80
|
}
|
|
81
|
+
// The device's status history for `remote --report`. Wraps the console as
|
|
82
|
+
// it is now, so the terminal stays the same, but debug status lines are
|
|
83
|
+
// kept even without --debug.
|
|
84
|
+
startDeviceLog();
|
|
71
85
|
console.debug('[DEBUG] Platform:', os.platform());
|
|
72
86
|
await captureRemote('remote_device_command_started', {
|
|
73
87
|
node_version: process.version,
|
|
@@ -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
|
|
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: { ...
|
|
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
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
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:
|
|
257
|
+
command: globalCommand,
|
|
261
258
|
args: []
|
|
262
259
|
};
|
|
263
260
|
}
|
|
264
|
-
|
|
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
|
-
|
|
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
|
-
|
|
116
|
+
exitProcess(1);
|
|
77
117
|
}, 5000);
|
|
78
118
|
try {
|
|
79
119
|
await this.shutdown();
|
|
80
120
|
clearTimeout(forceExit);
|
|
81
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
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
|
-
|
|
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
|
-
|
|
517
|
-
|
|
518
|
-
|
|
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
|
|
521
|
-
await this.remoteChannel.updateCallResult(call_id, 'failed', null, error.message);
|
|
611
|
+
await this.remoteChannel.updateCallResult(call_id, 'completed', result);
|
|
522
612
|
}
|
|
523
|
-
|
|
524
|
-
|
|
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,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;
|