@wonderwhy-er/desktop-commander 0.2.48 → 0.2.51

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 CHANGED
@@ -84,10 +84,10 @@ Execute long-running terminal commands on your computer and manage processes thr
84
84
  - Multiple file support
85
85
  - Pattern-based replacements
86
86
  - vscode-ripgrep based recursive code or text search in folders
87
- - Comprehensive audit logging:
88
- - All tool calls are automatically logged
89
- - Log rotation with 10MB size limit
90
- - Detailed timestamps and arguments
87
+ - Local tool-call history and audit logs:
88
+ - Tool calls and arguments are recorded locally on the machine running Desktop Commander
89
+ - Recent call history with bounded output previews is available through `get_recent_tool_calls`
90
+ - Size-based rotation/trimming keeps the active history files bounded
91
91
  - Safety guardrails (not a sandbox — see [SECURITY.md](SECURITY.md)):
92
92
  - Symlink traversal prevention on file operations
93
93
  - Command blocklist for accidental execution
@@ -792,20 +792,40 @@ The fuzzy search logs help you understand:
792
792
  3. **File type issues**: Which file extensions commonly have matching problems
793
793
  4. **Character encoding problems**: Specific character codes that cause diffs
794
794
 
795
- ## Audit Logging
795
+ ## Local Tool History and Audit Logs
796
796
 
797
- Desktop Commander now includes comprehensive logging for all tool calls:
797
+ Desktop Commander keeps tool-call records **locally on the machine running the MCP server**. These local files are separate from optional telemetry and are not a server-side historical audit log.
798
798
 
799
- ### What Gets Logged
800
- - Every tool call is logged with timestamp, tool name, and arguments (sanitized for privacy)
801
- - Logs are rotated automatically when they reach 10MB in size
799
+ ### `claude_tool_call.log` — local argument log
802
800
 
803
- ### Log Location
804
- Logs are saved to:
801
+ Every tool call handled by the local MCP server is appended as a text line containing an ISO timestamp, the tool name, and the JSON-serialized arguments. Arguments are **not redacted or sanitized before being written to this local file**, so it may contain command text, file paths, or other sensitive values passed to tools. Tool outputs are not written to this file.
802
+
803
+ The active file rotates when it reaches 10 MB. The previous file is renamed using a timestamp, for example `claude_tool_call_2026-09-07_14-32-10.log`, and a new `claude_tool_call.log` is created. Rotated files are not automatically deleted by the logger.
804
+
805
+ Locations:
805
806
  - **macOS/Linux**: `~/.claude-server-commander/claude_tool_call.log`
806
807
  - **Windows**: `%USERPROFILE%\.claude-server-commander\claude_tool_call.log`
807
808
 
808
- This audit trail helps with debugging, security monitoring, and understanding how Claude is interacting with your system.
809
+ ### `tool-history.jsonl` — recent tool-call history
810
+
811
+ Desktop Commander also keeps a JSON Lines history used by `get_recent_tool_calls`. Each record contains the timestamp, tool name, arguments, duration, and the returned result. This history is loaded from disk on startup, so recent history can survive an MCP server restart.
812
+
813
+ To keep this history bounded:
814
+ - At most the most recent 1,000 calls are kept in memory.
815
+ - Stored output is capped at 4 KiB per record; larger outputs are replaced with an omission marker.
816
+ - The on-disk file is trimmed when it grows beyond 5 MiB, keeping roughly the newest 4 MiB.
817
+ - On startup, a history with more than 2,000 records is rewritten to the most recent 1,000 records.
818
+ - `get_recent_tool_calls` and `track_ui_event` are excluded from this JSONL history.
819
+
820
+ Locations:
821
+ - **macOS/Linux**: `~/.claude-server-commander/tool-history.jsonl`
822
+ - **Windows**: `%USERPROFILE%\.claude-server-commander\tool-history.jsonl`
823
+
824
+ ### Remote calls and server-side retention
825
+
826
+ Calls executed through Remote Desktop Commander are still handled by the local MCP server and use the same local history files above. The Remote Desktop Commander service does **not currently retain command arguments or command results as a historical server-side audit trail after execution is complete**.
827
+
828
+ These local history files are also separate from Desktop Commander's optional telemetry. The files themselves are not uploaded as telemetry. See [Data Collection & Privacy](#data-collection--privacy) and [PRIVACY.md](PRIVACY.md) for telemetry details.
809
829
 
810
830
  ## Handling Long-Running Commands
811
831
 
@@ -1126,7 +1146,9 @@ Please create a [GitHub Issue](https://github.com/wonderwhy-er/DesktopCommanderM
1126
1146
 
1127
1147
  ## Data Collection & Privacy
1128
1148
 
1129
- Desktop Commander collects limited, pseudonymous telemetry to improve the tool. We do not collect file contents, file paths, or command arguments.
1149
+ Desktop Commander collects limited, pseudonymous telemetry to improve the tool. We do not collect file contents, file paths, or command arguments as telemetry.
1150
+
1151
+ This is separate from the [local tool history and audit logs](#local-tool-history-and-audit-logs), which stay on the machine running Desktop Commander and may contain tool arguments and bounded result previews.
1130
1152
 
1131
1153
  **Opt-out:** Ask Claude to "disable Desktop Commander telemetry" or set `"telemetryEnabled": false` in your config.
1132
1154
 
@@ -25,9 +25,14 @@ declare class ConfigManager {
25
25
  private _isFirstRun;
26
26
  private writeChain;
27
27
  private saveScheduled;
28
+ private pendingMutations;
29
+ private watcher;
30
+ private reloadTimer;
28
31
  constructor();
29
32
  /**
30
- * Initialize configuration - load from disk or create default
33
+ * Initialize configuration - load from disk or create default.
34
+ * Creation and legacy migration use the same cross-process mutation path as
35
+ * normal writes so two processes starting together cannot clobber each other.
31
36
  */
32
37
  init(): Promise<void>;
33
38
  /**
@@ -38,27 +43,15 @@ declare class ConfigManager {
38
43
  * Create default configuration
39
44
  */
40
45
  private getDefaultConfig;
41
- /**
42
- * Write the current in-memory config to disk. All writes funnel through
43
- * writeChain (see saveConfig / scheduleSave) so overlapping saves can never
44
- * interleave and corrupt the file. Previously every tool call could fire its
45
- * own independent fs.writeFile of the same path.
46
- */
47
- private writeConfigToDisk;
48
- /**
49
- * Awaitable save, serialized on writeChain. Use for explicit, user-driven
50
- * config changes where the caller wants on-disk confirmation.
51
- */
52
- private saveConfig;
53
- /**
54
- * Non-blocking, coalesced save. Returns immediately; the write runs in the
55
- * background. A burst of calls collapses to at most one queued write behind
56
- * the in-flight one, so a storm of tool calls can't storm the disk — and,
57
- * critically, can't pile up behind a saturated libuv threadpool and gate the
58
- * tool-call response path. Used for high-frequency, non-critical persistence
59
- * such as usage stats.
60
- */
46
+ private readConfigFromDisk;
47
+ private writeConfigAtomically;
48
+ private acquireConfigLock;
49
+ private performConfigMutation;
50
+ private queueMutation;
51
+ /** Non-blocking, coalesced persistence for high-frequency state updates. */
61
52
  scheduleSave(): void;
53
+ private startConfigWatcher;
54
+ private reloadConfigFromDisk;
62
55
  /**
63
56
  * Get the entire config
64
57
  */
@@ -67,27 +60,24 @@ declare class ConfigManager {
67
60
  * Get a specific configuration value
68
61
  */
69
62
  getValue(key: string): Promise<any>;
70
- /**
71
- * Set a specific configuration value
72
- */
63
+ /** Set a specific configuration value and wait for durable persistence. */
73
64
  setValue(key: string, value: any): Promise<void>;
65
+ /** Update one value under the cross-process lock and return the durable value. */
66
+ updateValue(key: string, updater: (current: any) => any): Promise<any>;
74
67
  /**
75
- * Update a value in memory and persist it WITHOUT blocking the caller.
76
- * The tool-call response path must never wait on a disk write: when the libuv
77
- * threadpool is saturated (e.g. many parallel reads stalled on a slow/cloud
78
- * filesystem) an awaited write can't get a thread and would hang the response
79
- * of even pure-memory tools. The in-memory value is updated synchronously so
80
- * subsequent reads see it immediately; the write is coalesced in the
81
- * background. Callers needing on-disk confirmation should use setValue.
68
+ * Set a value without waiting on disk. The queued operation is applied to the
69
+ * latest on-disk config while holding the cross-process lock.
82
70
  */
83
71
  setValueNonBlocking(key: string, value: any): Promise<void>;
84
72
  /**
85
- * Update multiple configuration values at once
73
+ * Atomically update one value without blocking the caller on persistence.
74
+ * The updater is replayed against the latest disk value under the lock, which
75
+ * makes counter-style updates safe across multiple Desktop Commander processes.
86
76
  */
77
+ updateValueNonBlocking(key: string, updater: (current: any) => any): Promise<any>;
78
+ /** Update multiple configuration values at once. */
87
79
  updateConfig(updates: Partial<ServerConfig>): Promise<ServerConfig>;
88
- /**
89
- * Reset configuration to defaults
90
- */
80
+ /** Reset configuration to defaults. This intentionally replaces all keys. */
91
81
  resetConfig(): Promise<ServerConfig>;
92
82
  /**
93
83
  * Check if this is the first run (config file was just created)
@@ -1,8 +1,9 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
- import { existsSync } from 'fs';
3
+ import { existsSync, watch } from 'fs';
4
4
  import { mkdir } from 'fs/promises';
5
5
  import os from 'os';
6
+ import lockfile from 'proper-lockfile';
6
7
  import { VERSION } from './version.js';
7
8
  import { CONFIG_FILE } from './config.js';
8
9
  export function normalizeTelemetryEnabledValue(value) {
@@ -33,53 +34,59 @@ class ConfigManager {
33
34
  this.writeChain = Promise.resolve();
34
35
  // True while a coalesced background write is already queued (see scheduleSave).
35
36
  this.saveScheduled = false;
37
+ this.pendingMutations = [];
38
+ this.watcher = null;
39
+ this.reloadTimer = null;
36
40
  // Get user's home directory
37
41
  // Define config directory and file paths
38
42
  this.configPath = CONFIG_FILE;
39
43
  }
40
44
  /**
41
- * Initialize configuration - load from disk or create default
45
+ * Initialize configuration - load from disk or create default.
46
+ * Creation and legacy migration use the same cross-process mutation path as
47
+ * normal writes so two processes starting together cannot clobber each other.
42
48
  */
43
49
  async init() {
44
50
  if (this.initialized)
45
51
  return;
46
52
  try {
47
- // Ensure config directory exists
48
53
  const configDir = path.dirname(this.configPath);
49
54
  if (!existsSync(configDir)) {
50
55
  await mkdir(configDir, { recursive: true });
51
56
  }
52
- // Check if config file exists
53
57
  try {
54
- await fs.access(this.configPath);
55
- // Load existing config
56
- const configData = await fs.readFile(this.configPath, 'utf8');
57
- this.config = JSON.parse(configData);
58
+ this.config = await this.readConfigFromDisk();
58
59
  this._isFirstRun = false;
59
- // Configs created before this marker existed must not receive the
60
- // welcome page retroactively when client eligibility changes later.
61
- // New configs get this field from getDefaultConfig() and remain
62
- // eligible across restarts until their first initialization.
63
60
  if (this.config['welcomeOnboardingEligible'] === undefined) {
64
- this.config['welcomeOnboardingEligible'] = false;
65
- this.config['pendingWelcomeOnboarding'] = false;
66
- await this.saveConfig();
61
+ await this.performConfigMutation((latest) => {
62
+ if (latest['welcomeOnboardingEligible'] === undefined) {
63
+ latest['welcomeOnboardingEligible'] = false;
64
+ latest['pendingWelcomeOnboarding'] = false;
65
+ }
66
+ });
67
67
  }
68
68
  }
69
69
  catch (error) {
70
- // Config file doesn't exist, create default
71
- this.config = this.getDefaultConfig();
72
- this._isFirstRun = true; // This is a first run!
73
- await this.saveConfig();
70
+ if (error?.code !== 'ENOENT')
71
+ throw error;
72
+ let created = false;
73
+ await this.performConfigMutation((latest, existed) => {
74
+ if (!existed) {
75
+ Object.assign(latest, this.getDefaultConfig());
76
+ created = true;
77
+ }
78
+ });
79
+ this._isFirstRun = created;
74
80
  }
75
81
  this.config['version'] = VERSION;
76
82
  this.initialized = true;
83
+ this.startConfigWatcher();
77
84
  }
78
85
  catch (error) {
79
86
  console.error('Failed to initialize config:', error);
80
- // Fall back to default config in memory
81
87
  this.config = this.getDefaultConfig();
82
88
  this.initialized = true;
89
+ this.startConfigWatcher();
83
90
  }
84
91
  }
85
92
  /**
@@ -153,46 +160,132 @@ class ConfigManager {
153
160
  welcomeOnboardingEligible: true // Distinguishes new installs from migrated legacy configs
154
161
  };
155
162
  }
156
- /**
157
- * Write the current in-memory config to disk. All writes funnel through
158
- * writeChain (see saveConfig / scheduleSave) so overlapping saves can never
159
- * interleave and corrupt the file. Previously every tool call could fire its
160
- * own independent fs.writeFile of the same path.
161
- */
162
- async writeConfigToDisk() {
163
- await fs.writeFile(this.configPath, JSON.stringify(this.config, null, 2), 'utf8');
163
+ async readConfigFromDisk() {
164
+ let lastError;
165
+ for (let attempt = 0; attempt < 5; attempt++) {
166
+ try {
167
+ return JSON.parse(await fs.readFile(this.configPath, 'utf8'));
168
+ }
169
+ catch (error) {
170
+ lastError = error;
171
+ if (error?.code === 'ENOENT')
172
+ throw error;
173
+ if (!(error instanceof SyntaxError) || attempt === 4)
174
+ throw error;
175
+ await new Promise((resolve) => setTimeout(resolve, 10));
176
+ }
177
+ }
178
+ throw lastError;
164
179
  }
165
- /**
166
- * Awaitable save, serialized on writeChain. Use for explicit, user-driven
167
- * config changes where the caller wants on-disk confirmation.
168
- */
169
- async saveConfig() {
170
- const write = this.writeChain.then(() => this.writeConfigToDisk());
171
- // Keep the chain alive even if this write rejects, so later writes still run.
172
- this.writeChain = write.catch(() => { });
173
- return write;
180
+ async writeConfigAtomically(config) {
181
+ const tempPath = `${this.configPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
182
+ try {
183
+ await fs.writeFile(tempPath, JSON.stringify(config, null, 2), 'utf8');
184
+ await fs.rename(tempPath, this.configPath);
185
+ }
186
+ finally {
187
+ await fs.unlink(tempPath).catch(() => { });
188
+ }
174
189
  }
175
- /**
176
- * Non-blocking, coalesced save. Returns immediately; the write runs in the
177
- * background. A burst of calls collapses to at most one queued write behind
178
- * the in-flight one, so a storm of tool calls can't storm the disk — and,
179
- * critically, can't pile up behind a saturated libuv threadpool and gate the
180
- * tool-call response path. Used for high-frequency, non-critical persistence
181
- * such as usage stats.
182
- */
190
+ async acquireConfigLock() {
191
+ return lockfile.lock(this.configPath, {
192
+ realpath: false,
193
+ stale: 30000,
194
+ update: 10000,
195
+ retries: { retries: 100, factor: 1.2, minTimeout: 10, maxTimeout: 100 }
196
+ });
197
+ }
198
+ async performConfigMutation(mutate) {
199
+ const release = await this.acquireConfigLock();
200
+ try {
201
+ let latest;
202
+ let existed = true;
203
+ try {
204
+ latest = await this.readConfigFromDisk();
205
+ }
206
+ catch (error) {
207
+ if (error?.code !== 'ENOENT')
208
+ throw error;
209
+ latest = {};
210
+ existed = false;
211
+ }
212
+ mutate(latest, existed);
213
+ await this.writeConfigAtomically(latest);
214
+ this.config = { ...latest, version: VERSION };
215
+ return latest;
216
+ }
217
+ finally {
218
+ try {
219
+ await release();
220
+ }
221
+ catch (error) {
222
+ // The atomic rename is the commit boundary. A release failure after it
223
+ // must not make callers replay a mutation that already persisted.
224
+ console.error('Failed to release config lock:', error);
225
+ }
226
+ }
227
+ }
228
+ queueMutation(mutate) {
229
+ this.pendingMutations.push(mutate);
230
+ this.scheduleSave();
231
+ }
232
+ /** Non-blocking, coalesced persistence for high-frequency state updates. */
183
233
  scheduleSave() {
184
234
  if (this.saveScheduled)
185
- return; // a queued write will capture the latest config
235
+ return;
186
236
  this.saveScheduled = true;
187
- this.writeChain = this.writeChain.then(async () => {
188
- this.saveScheduled = false; // let the next burst queue a fresh write
237
+ const write = this.writeChain.then(async () => {
238
+ this.saveScheduled = false;
239
+ const mutations = this.pendingMutations.splice(0);
240
+ if (mutations.length === 0)
241
+ return;
189
242
  try {
190
- await this.writeConfigToDisk();
243
+ await this.performConfigMutation((latest) => {
244
+ for (const mutate of mutations)
245
+ mutate(latest);
246
+ });
191
247
  }
192
248
  catch (error) {
193
- console.error('Failed to save config (background):', error);
249
+ // Persistence failed before commit, so keep these mutations for a later retry.
250
+ this.pendingMutations.unshift(...mutations);
251
+ console.error('Failed to save config (background), will retry:', error);
252
+ const retry = setTimeout(() => this.scheduleSave(), 250);
253
+ retry.unref?.();
194
254
  }
195
255
  });
256
+ this.writeChain = write.catch(() => { });
257
+ }
258
+ startConfigWatcher() {
259
+ if (this.watcher)
260
+ return;
261
+ try {
262
+ const dir = path.dirname(this.configPath);
263
+ const filename = path.basename(this.configPath);
264
+ this.watcher = watch(dir, { persistent: false }, (_event, changed) => {
265
+ if (changed && changed.toString() !== filename)
266
+ return;
267
+ if (this.reloadTimer)
268
+ clearTimeout(this.reloadTimer);
269
+ this.reloadTimer = setTimeout(() => void this.reloadConfigFromDisk(), 20);
270
+ });
271
+ this.watcher.on('error', (error) => console.error('Config watcher error:', error));
272
+ }
273
+ catch (error) {
274
+ console.error('Failed to watch config:', error);
275
+ }
276
+ }
277
+ async reloadConfigFromDisk() {
278
+ try {
279
+ const latest = await this.readConfigFromDisk();
280
+ for (const mutate of this.pendingMutations)
281
+ mutate(latest);
282
+ latest['version'] = VERSION;
283
+ this.config = latest;
284
+ }
285
+ catch (error) {
286
+ if (error?.code !== 'ENOENT')
287
+ console.error('Failed to reload config:', error);
288
+ }
196
289
  }
197
290
  /**
198
291
  * Get the entire config
@@ -208,65 +301,78 @@ class ConfigManager {
208
301
  await this.init();
209
302
  return this.config[key];
210
303
  }
211
- /**
212
- * Set a specific configuration value
213
- */
304
+ /** Set a specific configuration value and wait for durable persistence. */
214
305
  async setValue(key, value) {
215
306
  await this.init();
216
- if (key === 'telemetryEnabled') {
307
+ if (key === 'telemetryEnabled')
217
308
  value = normalizeTelemetryEnabledValue(value);
218
- }
219
- // Special handling for telemetry opt-out
220
309
  if (key === 'telemetryEnabled' && isTelemetryDisabledValue(value)) {
221
- // Get the current value before changing it
222
310
  const currentValue = this.config[key];
223
- const telemetryAlreadyDisabled = isTelemetryDisabledValue(currentValue);
224
- // Only capture the opt-out event if telemetry was previously enabled
225
- if (!telemetryAlreadyDisabled) {
226
- // Import the capture function dynamically to avoid circular dependencies
311
+ if (!isTelemetryDisabledValue(currentValue)) {
227
312
  const { capture } = await import('./utils/capture.js');
228
- // Send a final telemetry event noting that the user has opted out
229
- // This helps us track opt-out rates while respecting the user's choice
230
- await capture('server_telemetry_opt_out', {
231
- reason: 'user_disabled',
232
- prev_value: currentValue
233
- });
313
+ await capture('server_telemetry_opt_out', { reason: 'user_disabled', prev_value: currentValue });
234
314
  }
235
315
  }
236
- // Update the value
237
- this.config[key] = value;
238
- await this.saveConfig();
316
+ const nextValue = value;
317
+ const write = this.writeChain.then(() => this.performConfigMutation((latest) => {
318
+ latest[key] = nextValue;
319
+ }));
320
+ this.writeChain = write.then(() => { }, () => { });
321
+ await write;
322
+ }
323
+ /** Update one value under the cross-process lock and return the durable value. */
324
+ async updateValue(key, updater) {
325
+ await this.init();
326
+ let updatedValue;
327
+ const write = this.writeChain.then(() => this.performConfigMutation((latest) => {
328
+ updatedValue = updater(latest[key]);
329
+ latest[key] = updatedValue;
330
+ }));
331
+ this.writeChain = write.then(() => { }, () => { });
332
+ await write;
333
+ return updatedValue;
239
334
  }
240
335
  /**
241
- * Update a value in memory and persist it WITHOUT blocking the caller.
242
- * The tool-call response path must never wait on a disk write: when the libuv
243
- * threadpool is saturated (e.g. many parallel reads stalled on a slow/cloud
244
- * filesystem) an awaited write can't get a thread and would hang the response
245
- * of even pure-memory tools. The in-memory value is updated synchronously so
246
- * subsequent reads see it immediately; the write is coalesced in the
247
- * background. Callers needing on-disk confirmation should use setValue.
336
+ * Set a value without waiting on disk. The queued operation is applied to the
337
+ * latest on-disk config while holding the cross-process lock.
248
338
  */
249
339
  async setValueNonBlocking(key, value) {
250
340
  await this.init();
251
341
  this.config[key] = value;
252
- this.scheduleSave();
342
+ this.queueMutation((latest) => { latest[key] = value; });
253
343
  }
254
344
  /**
255
- * Update multiple configuration values at once
345
+ * Atomically update one value without blocking the caller on persistence.
346
+ * The updater is replayed against the latest disk value under the lock, which
347
+ * makes counter-style updates safe across multiple Desktop Commander processes.
256
348
  */
349
+ async updateValueNonBlocking(key, updater) {
350
+ await this.init();
351
+ const next = updater(this.config[key]);
352
+ this.config[key] = next;
353
+ this.queueMutation((latest) => { latest[key] = updater(latest[key]); });
354
+ return next;
355
+ }
356
+ /** Update multiple configuration values at once. */
257
357
  async updateConfig(updates) {
258
358
  await this.init();
259
- this.config = { ...this.config, ...updates };
260
- await this.saveConfig();
261
- return { ...this.config };
359
+ const write = this.writeChain.then(() => this.performConfigMutation((latest) => {
360
+ Object.assign(latest, updates);
361
+ }));
362
+ this.writeChain = write.then(() => { }, () => { });
363
+ return { ...(await write) };
262
364
  }
263
- /**
264
- * Reset configuration to defaults
265
- */
365
+ /** Reset configuration to defaults. This intentionally replaces all keys. */
266
366
  async resetConfig() {
267
- this.config = this.getDefaultConfig();
268
- await this.saveConfig();
269
- return { ...this.config };
367
+ await this.init();
368
+ const defaults = this.getDefaultConfig();
369
+ const write = this.writeChain.then(() => this.performConfigMutation((latest) => {
370
+ for (const key of Object.keys(latest))
371
+ delete latest[key];
372
+ Object.assign(latest, defaults);
373
+ }));
374
+ this.writeChain = write.then(() => { }, () => { });
375
+ return { ...(await write) };
270
376
  }
271
377
  /**
272
378
  * Check if this is the first run (config file was just created)
@@ -278,13 +384,8 @@ class ConfigManager {
278
384
  * Get or create a persistent client ID for analytics and A/B tests
279
385
  */
280
386
  async getOrCreateClientId() {
281
- let clientId = await this.getValue('clientId');
282
- if (!clientId) {
283
- const { randomUUID } = await import('crypto');
284
- clientId = randomUUID();
285
- await this.setValue('clientId', clientId);
286
- }
287
- return clientId;
387
+ const { randomUUID } = await import('crypto');
388
+ return await this.updateValue('clientId', (current) => current || randomUUID());
288
389
  }
289
390
  }
290
391
  // Export singleton instance
@@ -1,6 +1,34 @@
1
- import { MCPDevice } from '../remote-device/device.js';
1
+ import { MCPDevice, getRemoteDeviceConfigPath } from '../remote-device/device.js';
2
+ import fs from 'fs/promises';
2
3
  import os from 'os';
3
4
  export async function runRemote() {
5
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
6
+ console.log(`Desktop Commander Remote MCP device
7
+
8
+ Usage:
9
+ desktop-commander remote [options]
10
+
11
+ Options:
12
+ --logout Remove saved local Remote MCP credentials and exit
13
+ --no-persist-session Do not reuse or save authentication for this run
14
+ --disable-no-sleep Do not prevent sleep while the remote device is running
15
+ --debug Enable verbose debug logging
16
+ -h, --help Show this help`);
17
+ return;
18
+ }
19
+ if (process.argv.includes('--logout')) {
20
+ const configPath = getRemoteDeviceConfigPath();
21
+ try {
22
+ await fs.rm(configPath, { force: true });
23
+ console.log('🔓 Logged out locally. Saved Remote MCP device credentials were removed.');
24
+ console.log(` ${configPath}`);
25
+ }
26
+ catch (error) {
27
+ console.error('❌ Failed to remove saved Remote MCP credentials:', error.message);
28
+ process.exitCode = 1;
29
+ }
30
+ return;
31
+ }
4
32
  // --persist-session is kept as an accepted no-op so existing invocations
5
33
  // and docs keep working; --no-persist-session opts back out.
6
34
  const persistSession = !process.argv.includes('--no-persist-session');
@@ -8,7 +8,33 @@ export declare class DesktopCommanderIntegration {
8
8
  private mcpClient;
9
9
  private mcpTransport;
10
10
  private isReady;
11
+ private isShuttingDown;
12
+ private disconnectHandler;
13
+ private reinitPromise;
14
+ /** True only while the local stdio child is actually reachable. */
15
+ get ready(): boolean;
16
+ /**
17
+ * Register a callback fired when the local MCP child dies unexpectedly.
18
+ * The device uses this to stop advertising itself as online — the remote
19
+ * channel staying healthy says nothing about the local half being alive.
20
+ */
21
+ onDisconnect(handler: (reason: string) => void): void;
22
+ /**
23
+ * The local child exited or its pipe broke. Previously nothing observed this:
24
+ * `isReady` was a one-shot latch set in initialize() and cleared only by
25
+ * shutdown(), so every later callClientTool() sailed past the readiness guard
26
+ * and died inside the SDK with a bare "Not connected", forever, while the
27
+ * device still reported itself online.
28
+ */
29
+ private handleLocalDisconnect;
11
30
  initialize(): Promise<void>;
31
+ /**
32
+ * Guarantee a live local child before proxying a call, restarting it if the
33
+ * previous one died. Restart is lazy (on demand) rather than a retry loop:
34
+ * if the child is crashing on startup, each tool call fails with the real
35
+ * reason instead of spinning respawns in the background.
36
+ */
37
+ ensureReady(): Promise<void>;
12
38
  resolveMcpConfig(): Promise<McpConfig | null>;
13
39
  callClientTool(toolName: string, args: any, metadata?: any): Promise<{
14
40
  [x: string]: unknown;