@wonderwhy-er/desktop-commander 0.2.52 → 0.3.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/command-manager.d.ts +7 -2
  2. package/dist/command-manager.js +16 -11
  3. package/dist/config-manager.d.ts +49 -3
  4. package/dist/config-manager.js +329 -87
  5. package/dist/config-recovery.d.ts +28 -0
  6. package/dist/config-recovery.js +81 -0
  7. package/dist/config.d.ts +1 -0
  8. package/dist/config.js +9 -0
  9. package/dist/handlers/filesystem-handlers.d.ts +1 -1
  10. package/dist/handlers/filesystem-handlers.js +26 -16
  11. package/dist/handlers/search-answers.d.ts +58 -0
  12. package/dist/handlers/search-answers.js +172 -0
  13. package/dist/handlers/search-handlers.js +4 -92
  14. package/dist/index.js +14 -7
  15. package/dist/npm-scripts/remote.js +2 -3
  16. package/dist/remote-device/broadcast-analytics.d.ts +28 -0
  17. package/dist/remote-device/broadcast-analytics.js +41 -0
  18. package/dist/remote-device/desktop-commander-integration.js +19 -25
  19. package/dist/remote-device/device.d.ts +14 -0
  20. package/dist/remote-device/device.js +137 -30
  21. package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
  22. package/dist/remote-device/mqtt-enrollment.js +162 -0
  23. package/dist/remote-device/mqtt-transport.d.ts +44 -0
  24. package/dist/remote-device/mqtt-transport.js +197 -0
  25. package/dist/remote-device/remote-channel.d.ts +12 -0
  26. package/dist/remote-device/remote-channel.js +55 -8
  27. package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
  28. package/dist/remote-device/transport-analytics.d.ts +29 -0
  29. package/dist/remote-device/transport-analytics.js +44 -0
  30. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  31. package/dist/remote-device/transport-telemetry.js +48 -0
  32. package/dist/search-manager.d.ts +239 -27
  33. package/dist/search-manager.js +746 -312
  34. package/dist/server.js +44 -11
  35. package/dist/terminal-manager.d.ts +138 -21
  36. package/dist/terminal-manager.js +300 -215
  37. package/dist/tools/config.d.ts +1 -1
  38. package/dist/tools/config.js +21 -70
  39. package/dist/tools/edit.js +12 -4
  40. package/dist/tools/filesystem.d.ts +30 -6
  41. package/dist/tools/filesystem.js +246 -140
  42. package/dist/tools/improved-process-tools.d.ts +9 -3
  43. package/dist/tools/improved-process-tools.js +171 -68
  44. package/dist/tools/pdf/extract-images.d.ts +2 -0
  45. package/dist/tools/pdf/extract-images.js +4 -1
  46. package/dist/tools/pdf/index.d.ts +5 -3
  47. package/dist/tools/pdf/index.js +4 -3
  48. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  49. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  50. package/dist/tools/pdf/manipulations.d.ts +12 -1
  51. package/dist/tools/pdf/manipulations.js +17 -4
  52. package/dist/tools/pdf/markdown.d.ts +96 -0
  53. package/dist/tools/pdf/markdown.js +485 -20
  54. package/dist/tools/pdf/utils.d.ts +2 -2
  55. package/dist/tools/pdf/utils.js +4 -4
  56. package/dist/tools/process.js +8 -5
  57. package/dist/tools/schemas.d.ts +1 -1
  58. package/dist/tools/schemas.js +15 -6
  59. package/dist/tools/search.d.ts +32 -0
  60. package/dist/tools/search.js +202 -0
  61. package/dist/types.d.ts +1 -1
  62. package/dist/ui/config-editor/config-editor-runtime.js +6 -6
  63. package/dist/ui/config-editor/src/app.js +2 -15
  64. package/dist/utils/ab-test.js +27 -9
  65. package/dist/utils/atomic-write.d.ts +14 -0
  66. package/dist/utils/atomic-write.js +80 -0
  67. package/dist/utils/capture.d.ts +17 -1
  68. package/dist/utils/capture.js +177 -68
  69. package/dist/utils/exit-process.d.ts +24 -0
  70. package/dist/utils/exit-process.js +31 -0
  71. package/dist/utils/feature-flags.js +2 -1
  72. package/dist/utils/files/base.d.ts +3 -1
  73. package/dist/utils/files/docx.d.ts +3 -0
  74. package/dist/utils/files/docx.js +24 -9
  75. package/dist/utils/files/excel.d.ts +10 -0
  76. package/dist/utils/files/excel.js +93 -33
  77. package/dist/utils/files/factory.d.ts +22 -1
  78. package/dist/utils/files/factory.js +59 -4
  79. package/dist/utils/files/image.d.ts +12 -4
  80. package/dist/utils/files/image.js +19 -8
  81. package/dist/utils/files/index.d.ts +5 -3
  82. package/dist/utils/files/index.js +4 -3
  83. package/dist/utils/files/pdf.js +18 -36
  84. package/dist/utils/files/text.d.ts +21 -5
  85. package/dist/utils/files/text.js +90 -86
  86. package/dist/utils/internal-facts.d.ts +3 -0
  87. package/dist/utils/internal-facts.js +23 -0
  88. package/dist/utils/lazy-package.d.ts +23 -0
  89. package/dist/utils/lazy-package.js +42 -0
  90. package/dist/utils/open-browser.js +2 -1
  91. package/dist/utils/process-detection.d.ts +24 -5
  92. package/dist/utils/process-detection.js +199 -89
  93. package/dist/utils/process-tree.d.ts +14 -0
  94. package/dist/utils/process-tree.js +223 -0
  95. package/dist/utils/rename.d.ts +9 -0
  96. package/dist/utils/rename.js +74 -0
  97. package/dist/utils/ripgrep-resolver.js +9 -14
  98. package/dist/utils/shell.d.ts +42 -0
  99. package/dist/utils/shell.js +187 -0
  100. package/dist/utils/system-info.js +9 -7
  101. package/dist/utils/trackTools.js +2 -1
  102. package/dist/version.d.ts +1 -1
  103. package/dist/version.js +1 -1
  104. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  105. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  106. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  107. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  108. package/package.json +8 -2
  109. package/vendor/telemetry-contract/README.md +56 -0
  110. package/vendor/telemetry-contract/package.json +32 -0
  111. package/vendor/telemetry-contract/transport.d.ts +38 -0
  112. package/vendor/telemetry-contract/transport.js +164 -0
  113. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -2,10 +2,33 @@ import fs from 'fs/promises';
2
2
  import path from 'path';
3
3
  import { existsSync, watch } from 'fs';
4
4
  import { mkdir } from 'fs/promises';
5
- import os from 'os';
6
5
  import lockfile from 'proper-lockfile';
7
6
  import { VERSION } from './version.js';
8
7
  import { CONFIG_FILE } from './config.js';
8
+ import { getDefaultShell } from './utils/shell.js';
9
+ import { writeFileAtomic } from './utils/atomic-write.js';
10
+ import { backupCorruptConfig, buildRecoveredConfig } from './config-recovery.js';
11
+ // Desktop Commander 0.2.48 and older write config.json in place, so while such
12
+ // a version runs alongside, the file can be empty or partly written for a
13
+ // moment: up to ~260ms measured on Windows (#697). A file that does not parse
14
+ // is read again until it does, for up to this long and at least this many
15
+ // reads (a start that freezes spends the time without reading); then it counts
16
+ // as corrupt. 30 reads 10 ms apart span longer than any empty moment measured.
17
+ const PARTIAL_CONFIG_WAIT_MS = 1000;
18
+ const PARTIAL_CONFIG_MIN_FAILED_READS = 30;
19
+ // A failed background save is tried again after SAVE_RETRY_MS. If it fails again
20
+ // (a read-only file system, a full disk), it is tried every HELD_SAVE_RETRY_MS.
21
+ const SAVE_RETRY_MS = 250;
22
+ const HELD_SAVE_RETRY_MS = 5000;
23
+ // How many times a config write runs again when its lock was lost, or
24
+ // config.json changed, before it committed
25
+ const MAX_CONFIG_WRITE_ATTEMPTS = 3;
26
+ /** Thrown when the lock was lost, or config.json changed, before a config write committed */
27
+ class ConfigChangedError extends Error {
28
+ constructor() {
29
+ super('config.json changed, or its lock was lost, before this write committed');
30
+ }
31
+ }
9
32
  export function normalizeTelemetryEnabledValue(value) {
10
33
  if (typeof value !== 'string') {
11
34
  return value;
@@ -22,6 +45,32 @@ export function normalizeTelemetryEnabledValue(value) {
22
45
  export function isTelemetryDisabledValue(value) {
23
46
  return normalizeTelemetryEnabledValue(value) === false;
24
47
  }
48
+ /**
49
+ * Parses config.json's text. Editors saving "UTF-8 with BOM" (Notepad,
50
+ * PowerShell 5's Set-Content -Encoding UTF8) put U+FEFF first, which
51
+ * JSON.parse rejects although the config is complete.
52
+ */
53
+ function parseConfig(text) {
54
+ return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
55
+ }
56
+ /** Marks a config written before the welcome page existed as an existing install, which never gets it */
57
+ function migrateLegacyConfig(config) {
58
+ if (config['welcomeOnboardingEligible'] === undefined) {
59
+ config['welcomeOnboardingEligible'] = false;
60
+ config['pendingWelcomeOnboarding'] = false;
61
+ }
62
+ }
63
+ /**
64
+ * Shows the user a warning, as a log notification (console.warn in the MCP
65
+ * server) and on stderr, which `remote` shows in its terminal.
66
+ */
67
+ function warnUser(message) {
68
+ console.warn(message);
69
+ process.stderr.write(`[WARNING] Desktop Commander: ${message}\n`);
70
+ }
71
+ function messageOf(error) {
72
+ return error instanceof Error ? error.message : String(error);
73
+ }
25
74
  /**
26
75
  * Singleton config manager for the server
27
76
  */
@@ -37,6 +86,11 @@ class ConfigManager {
37
86
  this.pendingMutations = [];
38
87
  this.watcher = null;
39
88
  this.reloadTimer = null;
89
+ // Background saves that failed in a row, and the timer that tries them again (see scheduleSave)
90
+ this.failedSaves = 0;
91
+ this.saveRetry = null;
92
+ // Recovery events from before init() finished, sent when it does (see reportRecovery)
93
+ this.heldRecoveryEvents = [];
40
94
  // Get user's home directory
41
95
  // Define config directory and file paths
42
96
  this.configPath = CONFIG_FILE;
@@ -54,30 +108,7 @@ class ConfigManager {
54
108
  if (!existsSync(configDir)) {
55
109
  await mkdir(configDir, { recursive: true });
56
110
  }
57
- try {
58
- this.config = await this.readConfigFromDisk();
59
- this._isFirstRun = false;
60
- if (this.config['welcomeOnboardingEligible'] === undefined) {
61
- await this.performConfigMutation((latest) => {
62
- if (latest['welcomeOnboardingEligible'] === undefined) {
63
- latest['welcomeOnboardingEligible'] = false;
64
- latest['pendingWelcomeOnboarding'] = false;
65
- }
66
- });
67
- }
68
- }
69
- catch (error) {
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;
80
- }
111
+ this.config = await this.loadStartupConfig();
81
112
  this.config['version'] = VERSION;
82
113
  this.initialized = true;
83
114
  this.startConfigWatcher();
@@ -88,6 +119,71 @@ class ConfigManager {
88
119
  this.initialized = true;
89
120
  this.startConfigWatcher();
90
121
  }
122
+ for (const event of this.heldRecoveryEvents.splice(0))
123
+ void this.emitCorruptConfigTelemetry(event);
124
+ }
125
+ /**
126
+ * Reads config.json at start. A missing one is created (a first run), a corrupt
127
+ * one is recovered, and one written before the welcome page existed is marked
128
+ * as an existing install. If it can't be read, recovered or saved, the session
129
+ * starts without saving it.
130
+ */
131
+ async loadStartupConfig() {
132
+ let config;
133
+ try {
134
+ config = await this.readConfigFromDisk();
135
+ }
136
+ catch (error) {
137
+ if (error?.code === 'ENOENT') {
138
+ let created = false;
139
+ config = await this.performConfigMutation((latest, existed) => {
140
+ if (!existed) {
141
+ Object.assign(latest, this.getDefaultConfig());
142
+ created = true;
143
+ }
144
+ });
145
+ this._isFirstRun = created;
146
+ }
147
+ else if (error instanceof SyntaxError) {
148
+ try {
149
+ config = await this.withConfigLock(() => this.recoverCorruptConfig('startup'));
150
+ }
151
+ catch (recoveryError) {
152
+ // Left as it is, the next start recovers it
153
+ const text = await fs.readFile(this.configPath, 'utf8').catch(() => '');
154
+ return this.startWithoutSaving(buildRecoveredConfig(this.getDefaultConfig(), null, text), `config.json could not be parsed, and replacing it failed (${messageOf(recoveryError)}). For this session Desktop Commander uses the settings still readable in it and the defaults for the rest; config.json is left as it is.`);
155
+ }
156
+ }
157
+ else {
158
+ // There, but it can't be read (e.g. no permission): an existing install,
159
+ // so the welcome page stays off, and initialize has nothing to save for it
160
+ return this.startWithoutSaving(buildRecoveredConfig(this.getDefaultConfig(), null, ''), `config.json could not be read (${messageOf(error)}). For this session Desktop Commander uses the default settings; config.json is left as it is.`);
161
+ }
162
+ }
163
+ if (!this._isFirstRun && config['welcomeOnboardingEligible'] === undefined) {
164
+ try {
165
+ config = await this.performConfigMutation(migrateLegacyConfig);
166
+ }
167
+ catch (error) {
168
+ // The settings read stay in effect, not the defaults, which allow every folder
169
+ migrateLegacyConfig(config);
170
+ this.pendingMutations.push(migrateLegacyConfig);
171
+ return this.startWithoutSaving(config, `config.json was read, but saving to it failed (${messageOf(error)}). ` +
172
+ `Desktop Commander uses the settings it read; changes to them can't be saved until config.json is writable.`);
173
+ }
174
+ }
175
+ return config;
176
+ }
177
+ /**
178
+ * Starts the session on `config` and leaves config.json as it is. `warning`
179
+ * tells the user why; saves are tried again every HELD_SAVE_RETRY_MS.
180
+ */
181
+ startWithoutSaving(config, warning) {
182
+ // As after a second failed save, whose log line the warning stands for
183
+ this.failedSaves = 2;
184
+ this.retrySaves(HELD_SAVE_RETRY_MS);
185
+ warnUser(warning);
186
+ return config;
91
187
  }
92
188
  /**
93
189
  * Alias for init() to maintain backward compatibility
@@ -140,18 +236,7 @@ class ConfigManager {
140
236
  "cipher", // Encrypt/decrypt files or wipe data
141
237
  "takeown" // Take ownership of files
142
238
  ],
143
- defaultShell: (() => {
144
- if (os.platform() === 'win32') {
145
- return 'powershell.exe';
146
- }
147
- // Use user's actual shell from environment
148
- // On macOS, default to zsh (default since Catalina) since process.env.SHELL
149
- // may not be set when running inside Claude Desktop
150
- const fallbackShell = os.platform() === 'darwin' ? '/bin/zsh' : '/bin/sh';
151
- const userShell = process.env.SHELL || fallbackShell;
152
- // Return just the shell path - we'll handle login shell flag elsewhere
153
- return userShell;
154
- })(),
239
+ defaultShell: getDefaultShell(),
155
240
  allowedDirectories: [],
156
241
  telemetryEnabled: true, // Default to opt-out approach (telemetry on by default)
157
242
  fileWriteLineLimit: 50, // Default line limit for file write operations (changed from 100)
@@ -161,58 +246,103 @@ class ConfigManager {
161
246
  };
162
247
  }
163
248
  async readConfigFromDisk() {
164
- let lastError;
165
- for (let attempt = 0; attempt < 5; attempt++) {
249
+ const deadline = Date.now() + PARTIAL_CONFIG_WAIT_MS;
250
+ for (let failedReads = 1;; failedReads++) {
166
251
  try {
167
- return JSON.parse(await fs.readFile(this.configPath, 'utf8'));
252
+ return parseConfig(await fs.readFile(this.configPath, 'utf8'));
168
253
  }
169
254
  catch (error) {
170
- lastError = error;
171
- if (error?.code === 'ENOENT')
255
+ if (!(error instanceof SyntaxError))
172
256
  throw error;
173
- if (!(error instanceof SyntaxError) || attempt === 4)
257
+ if (Date.now() >= deadline && failedReads >= PARTIAL_CONFIG_MIN_FAILED_READS)
174
258
  throw error;
175
259
  await new Promise((resolve) => setTimeout(resolve, 10));
176
260
  }
177
261
  }
178
- throw lastError;
179
262
  }
180
- async writeConfigAtomically(config) {
181
- const tempPath = `${this.configPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
263
+ /**
264
+ * Recovers a corrupt config.json; the caller holds the config lock. It is backed
265
+ * up once, then rewritten as buildRecoveredConfig(). Returns the config now on disk.
266
+ */
267
+ async recoverCorruptConfig(phase) {
268
+ const bytes = await fs.readFile(this.configPath).catch((error) => {
269
+ if (error?.code === 'ENOENT')
270
+ return Buffer.alloc(0);
271
+ throw error;
272
+ });
273
+ const text = bytes.toString('utf8');
274
+ let parseError;
182
275
  try {
183
- await fs.writeFile(tempPath, JSON.stringify(config, null, 2), 'utf8');
184
- await fs.rename(tempPath, this.configPath);
276
+ const config = parseConfig(text);
277
+ // Another process recovered it while this one waited for the lock
278
+ this.reportRecovery({ phase, config_bytes: null, backup_created: false, recovered_by_other_process: true });
279
+ return config;
185
280
  }
186
- finally {
187
- await fs.unlink(tempPath).catch(() => { });
281
+ catch (error) {
282
+ parseError = error;
188
283
  }
284
+ const backupName = await backupCorruptConfig(this.configPath, bytes);
285
+ const config = buildRecoveredConfig(this.getDefaultConfig(), this.initialized ? this.config : null, text);
286
+ await this.writeConfigAtomically(config);
287
+ this.config = { ...config, version: VERSION };
288
+ console.error(`config.json could not be parsed (${parseError.message})${backupName ? `; kept as ${backupName}` : ''}; ` +
289
+ 'replaced with the settings still readable in it and the defaults for the rest.');
290
+ this.reportRecovery({ phase, config_bytes: bytes.length, backup_created: backupName !== null, recovered_by_other_process: false });
291
+ return config;
292
+ }
293
+ /** Sends a recovery event. Telemetry reads the config, so events from before init() is done wait for it. */
294
+ reportRecovery(event) {
295
+ if (this.initialized)
296
+ void this.emitCorruptConfigTelemetry(event);
297
+ else
298
+ this.heldRecoveryEvents.push(event);
189
299
  }
190
- async acquireConfigLock() {
300
+ async emitCorruptConfigTelemetry(event) {
301
+ try {
302
+ const { capture } = await import('./utils/capture.js');
303
+ await capture('config_parse_error_recovered', event);
304
+ }
305
+ catch {
306
+ // Recovery never depends on telemetry
307
+ }
308
+ }
309
+ async writeConfigAtomically(config, beforeCommit) {
310
+ await writeFileAtomic(this.configPath, JSON.stringify(config, null, 2), { beforeCommit });
311
+ }
312
+ /** config.json's text, or null when there is none */
313
+ async readConfigText() {
314
+ try {
315
+ return await fs.readFile(this.configPath, 'utf8');
316
+ }
317
+ catch (error) {
318
+ if (error?.code === 'ENOENT')
319
+ return null;
320
+ throw error;
321
+ }
322
+ }
323
+ async acquireConfigLock(onLost) {
191
324
  return lockfile.lock(this.configPath, {
192
325
  realpath: false,
193
326
  stale: 30000,
194
327
  update: 10000,
195
- retries: { retries: 100, factor: 1.2, minTimeout: 10, maxTimeout: 100 }
328
+ retries: { retries: 100, factor: 1.2, minTimeout: 10, maxTimeout: 100 },
329
+ // This process couldn't refresh the lock for 30 s (frozen: machine sleep, a
330
+ // suspended process, a blocked event loop) and another one took it over or
331
+ // removed it. The default throws from a timer, which ends the server; here it
332
+ // is logged, and a write not yet committed runs again under a new lock
333
+ // (performConfigMutation). Its release then fails (logged).
334
+ onCompromised: (error) => {
335
+ console.error(`The config lock was lost while held: ${error.message} (${error.code})`);
336
+ onLost?.();
337
+ },
196
338
  });
197
339
  }
198
- async performConfigMutation(mutate) {
199
- const release = await this.acquireConfigLock();
340
+ /** Runs `fn` holding the config lock; `lockLost()` tells whether the lock was lost meanwhile. */
341
+ async withConfigLock(fn) {
342
+ let lost = false;
343
+ const release = await this.acquireConfigLock(() => { lost = true; });
200
344
  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;
345
+ return await fn(() => lost);
216
346
  }
217
347
  finally {
218
348
  try {
@@ -225,36 +355,120 @@ class ConfigManager {
225
355
  }
226
356
  }
227
357
  }
358
+ /**
359
+ * Read config.json, apply `mutate`, write it back, all under the cross-process
360
+ * lock. If the lock was lost, or config.json changed, before the write
361
+ * committed, nothing was written: it runs again under a new lock, so the
362
+ * change lands on what the other process saved.
363
+ */
364
+ async performConfigMutation(mutate) {
365
+ for (let attempt = 1;; attempt++) {
366
+ try {
367
+ return await this.withConfigLock((lockLost) => this.mutateLockedConfig(mutate, lockLost));
368
+ }
369
+ catch (error) {
370
+ if (!(error instanceof ConfigChangedError) || attempt >= MAX_CONFIG_WRITE_ATTEMPTS)
371
+ throw error;
372
+ }
373
+ }
374
+ }
375
+ async mutateLockedConfig(mutate, lockLost) {
376
+ let latest;
377
+ let existed = true;
378
+ try {
379
+ latest = await this.readConfigFromDisk();
380
+ }
381
+ catch (error) {
382
+ if (error instanceof SyntaxError) {
383
+ latest = await this.recoverCorruptConfig('mutation');
384
+ }
385
+ else if (error?.code === 'ENOENT') {
386
+ // Missing (a first start, or removed while running): start from the
387
+ // defaults, as `{}` would leave blockedCommands empty, blocking nothing
388
+ latest = this.getDefaultConfig();
389
+ existed = false;
390
+ if (this.initialized) {
391
+ // Removed while running: still an existing install, which never gets the welcome page
392
+ latest['welcomeOnboardingEligible'] = false;
393
+ latest['pendingWelcomeOnboarding'] = false;
394
+ }
395
+ }
396
+ else {
397
+ throw error;
398
+ }
399
+ }
400
+ // What config.json holds now. If it holds anything else when the write is
401
+ // about to commit, another process saved meanwhile.
402
+ const readText = await this.readConfigText();
403
+ // Queued changes are older than this one, so they apply first; if this
404
+ // write fails, they are queued again
405
+ const queued = this.pendingMutations.splice(0);
406
+ try {
407
+ for (const apply of queued)
408
+ apply(latest);
409
+ mutate(latest, existed);
410
+ await this.writeConfigAtomically(latest, async () => {
411
+ if (lockLost() || await this.readConfigText() !== readText)
412
+ throw new ConfigChangedError();
413
+ });
414
+ }
415
+ catch (error) {
416
+ this.pendingMutations.unshift(...queued);
417
+ throw error;
418
+ }
419
+ this.config = { ...latest, version: VERSION };
420
+ // Saves work again, so queued changes needn't wait for a retry
421
+ this.failedSaves = 0;
422
+ if (this.saveRetry)
423
+ this.retrySaves(0);
424
+ return latest;
425
+ }
228
426
  queueMutation(mutate) {
229
427
  this.pendingMutations.push(mutate);
230
428
  this.scheduleSave();
231
429
  }
232
430
  /** Non-blocking, coalesced persistence for high-frequency state updates. */
233
431
  scheduleSave() {
234
- if (this.saveScheduled)
432
+ if (this.saveScheduled || this.saveRetry)
235
433
  return;
236
434
  this.saveScheduled = true;
237
435
  const write = this.writeChain.then(async () => {
238
436
  this.saveScheduled = false;
239
- const mutations = this.pendingMutations.splice(0);
240
- if (mutations.length === 0)
437
+ // A write in between may have saved them already
438
+ if (this.pendingMutations.length === 0)
241
439
  return;
242
440
  try {
243
- await this.performConfigMutation((latest) => {
244
- for (const mutate of mutations)
245
- mutate(latest);
246
- });
441
+ // Every config write applies the queued changes first
442
+ await this.performConfigMutation(() => { });
247
443
  }
248
444
  catch (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?.();
445
+ // The changes stay queued. A brief failure (a lock, a file scanner) is
446
+ // tried again soon, a lasting one (a read-only file system, a full disk)
447
+ // every few seconds, and logged once.
448
+ this.failedSaves++;
449
+ if (this.failedSaves === 1) {
450
+ console.error('Failed to save config (background), will retry:', error);
451
+ this.retrySaves(SAVE_RETRY_MS);
452
+ }
453
+ else {
454
+ if (this.failedSaves === 2)
455
+ console.error("config.json can't be written, so changes are kept and saved once it can:", error);
456
+ this.retrySaves(HELD_SAVE_RETRY_MS);
457
+ }
254
458
  }
255
459
  });
256
460
  this.writeChain = write.catch(() => { });
257
461
  }
462
+ /** Saves the queued changes in `ms`; until then scheduleSave() waits for it */
463
+ retrySaves(ms) {
464
+ if (this.saveRetry)
465
+ clearTimeout(this.saveRetry);
466
+ this.saveRetry = setTimeout(() => {
467
+ this.saveRetry = null;
468
+ this.scheduleSave();
469
+ }, ms);
470
+ this.saveRetry.unref?.();
471
+ }
258
472
  startConfigWatcher() {
259
473
  if (this.watcher)
260
474
  return;
@@ -276,11 +490,18 @@ class ConfigManager {
276
490
  }
277
491
  async reloadConfigFromDisk() {
278
492
  try {
279
- const latest = await this.readConfigFromDisk();
493
+ let latest;
494
+ try {
495
+ latest = await this.readConfigFromDisk();
496
+ }
497
+ catch (error) {
498
+ if (!(error instanceof SyntaxError))
499
+ throw error;
500
+ latest = await this.withConfigLock(() => this.recoverCorruptConfig('watcher'));
501
+ }
280
502
  for (const mutate of this.pendingMutations)
281
503
  mutate(latest);
282
- latest['version'] = VERSION;
283
- this.config = latest;
504
+ this.config = { ...latest, version: VERSION };
284
505
  }
285
506
  catch (error) {
286
507
  if (error?.code !== 'ENOENT')
@@ -301,8 +522,13 @@ class ConfigManager {
301
522
  await this.init();
302
523
  return this.config[key];
303
524
  }
304
- /** Set a specific configuration value and wait for durable persistence. */
305
- async setValue(key, value) {
525
+ /**
526
+ * Set a specific configuration value and wait until it is saved: the data is
527
+ * flushed to disk before the rename; the folder flush after it is best effort.
528
+ * With holdIfNotSaved, a value whose save fails is still in effect, and is
529
+ * queued to be saved with later writes (the call still rejects).
530
+ */
531
+ async setValue(key, value, options = {}) {
306
532
  await this.init();
307
533
  if (key === 'telemetryEnabled')
308
534
  value = normalizeTelemetryEnabledValue(value);
@@ -316,11 +542,22 @@ class ConfigManager {
316
542
  const nextValue = value;
317
543
  const write = this.writeChain.then(() => this.performConfigMutation((latest) => {
318
544
  latest[key] = nextValue;
545
+ }).catch((error) => {
546
+ // Queued before the next write in the chain starts, so a later value of the
547
+ // same key is applied after it and wins
548
+ if (options.holdIfNotSaved) {
549
+ this.config[key] = nextValue;
550
+ this.queueMutation((latest) => { latest[key] = nextValue; });
551
+ }
552
+ throw error;
319
553
  }));
320
554
  this.writeChain = write.then(() => { }, () => { });
321
555
  await write;
322
556
  }
323
- /** Update one value under the cross-process lock and return the durable value. */
557
+ /**
558
+ * Update one value under the cross-process lock and return it once saved: the
559
+ * data is flushed to disk before the rename; the folder flush after it is best effort.
560
+ */
324
561
  async updateValue(key, updater) {
325
562
  await this.init();
326
563
  let updatedValue;
@@ -385,6 +622,11 @@ class ConfigManager {
385
622
  */
386
623
  async getOrCreateClientId() {
387
624
  const { randomUUID } = await import('crypto');
625
+ if (this.failedSaves > 0) {
626
+ // Saves fail until a write succeeds, so keep one for the session, saved with the queued changes
627
+ const clientId = this.config.clientId || randomUUID();
628
+ return await this.updateValueNonBlocking('clientId', (current) => current || clientId);
629
+ }
388
630
  return await this.updateValue('clientId', (current) => current || randomUUID());
389
631
  }
390
632
  }
@@ -0,0 +1,28 @@
1
+ import type { ServerConfig } from './config-manager.js';
2
+ /** Where a corrupt config.json was found: at start, by a write, or by the file watcher */
3
+ export type RecoveryPhase = 'startup' | 'mutation' | 'watcher';
4
+ /** The config_parse_error_recovered event */
5
+ export interface RecoveryEvent {
6
+ phase: RecoveryPhase;
7
+ config_bytes: number | null;
8
+ backup_created: boolean;
9
+ recovered_by_other_process: boolean;
10
+ }
11
+ /**
12
+ * The settings still readable in a corrupt config.json: the longest beginning
13
+ * of it that is a JSON object once closed, so every complete top-level setting
14
+ * before the first error. {} when there is none.
15
+ */
16
+ export declare function salvageSettings(text: string): ServerConfig;
17
+ /**
18
+ * What a corrupt config.json is recovered as: the defaults, then the settings
19
+ * last read (while running), then the settings salvaged from it. The welcome
20
+ * page stays off, as for any existing install.
21
+ */
22
+ export declare function buildRecoveredConfig(defaults: ServerConfig, lastRead: ServerConfig | null, text: string): ServerConfig;
23
+ /**
24
+ * Backs up a corrupt config.json as config.json.corrupt.<ms>.<pid>, unless the
25
+ * newest backup already holds `bytes` (a recovery tried again after its write
26
+ * failed). Returns the backup's name, or null when there is no config.json.
27
+ */
28
+ export declare function backupCorruptConfig(configPath: string, bytes: Buffer): Promise<string | null>;
@@ -0,0 +1,81 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { existsSync } from 'fs';
4
+ /**
5
+ * The settings still readable in a corrupt config.json: the longest beginning
6
+ * of it that is a JSON object once closed, so every complete top-level setting
7
+ * before the first error. {} when there is none.
8
+ */
9
+ export function salvageSettings(text) {
10
+ const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
11
+ // A readable beginning can end at each comma between top-level settings, or at
12
+ // the brace that closes the object (anything after it is ignored)
13
+ const ends = [];
14
+ let depth = 0;
15
+ let inString = false;
16
+ let escaped = false;
17
+ for (let i = 0; i < body.length; i++) {
18
+ const char = body[i];
19
+ if (inString) {
20
+ if (escaped)
21
+ escaped = false;
22
+ else if (char === '\\')
23
+ escaped = true;
24
+ else if (char === '"')
25
+ inString = false;
26
+ }
27
+ else if (char === '"') {
28
+ inString = true;
29
+ }
30
+ else if (char === '{' || char === '[') {
31
+ depth++;
32
+ }
33
+ else if (char === '}' || char === ']') {
34
+ if (--depth === 0) {
35
+ ends.push(i);
36
+ break;
37
+ }
38
+ }
39
+ else if (char === ',' && depth === 1) {
40
+ ends.push(i);
41
+ }
42
+ }
43
+ for (const end of ends.reverse()) {
44
+ try {
45
+ return JSON.parse(body.slice(0, end) + '}');
46
+ }
47
+ catch {
48
+ // Not valid JSON up to here either, so try a shorter beginning
49
+ }
50
+ }
51
+ return {};
52
+ }
53
+ /**
54
+ * What a corrupt config.json is recovered as: the defaults, then the settings
55
+ * last read (while running), then the settings salvaged from it. The welcome
56
+ * page stays off, as for any existing install.
57
+ */
58
+ export function buildRecoveredConfig(defaults, lastRead, text) {
59
+ const { version: _version, ...settings } = lastRead ?? {};
60
+ return { ...defaults, ...settings, ...salvageSettings(text), welcomeOnboardingEligible: false, pendingWelcomeOnboarding: false };
61
+ }
62
+ /**
63
+ * Backs up a corrupt config.json as config.json.corrupt.<ms>.<pid>, unless the
64
+ * newest backup already holds `bytes` (a recovery tried again after its write
65
+ * failed). Returns the backup's name, or null when there is no config.json.
66
+ */
67
+ export async function backupCorruptConfig(configPath, bytes) {
68
+ if (!existsSync(configPath))
69
+ return null;
70
+ const folder = path.dirname(configPath);
71
+ const prefix = `${path.basename(configPath)}.corrupt.`;
72
+ const newest = (await fs.readdir(folder).catch(() => []))
73
+ .filter((name) => name.startsWith(prefix))
74
+ .sort((a, b) => parseInt(a.slice(prefix.length), 10) - parseInt(b.slice(prefix.length), 10))
75
+ .pop();
76
+ if (newest && (await fs.readFile(path.join(folder, newest)).catch(() => null))?.equals(bytes))
77
+ return newest;
78
+ const name = `${prefix}${Date.now()}.${process.pid}`;
79
+ await fs.copyFile(configPath, path.join(folder, name));
80
+ return name;
81
+ }
package/dist/config.d.ts CHANGED
@@ -3,3 +3,4 @@ export declare const CONFIG_FILE: string;
3
3
  export declare const TOOL_CALL_FILE: string;
4
4
  export declare const TOOL_CALL_FILE_MAX_SIZE: number;
5
5
  export declare const DEFAULT_COMMAND_TIMEOUT = 1000;
6
+ export declare const MAX_PROCESS_WAIT_MS = 50000;
package/dist/config.js CHANGED
@@ -8,3 +8,12 @@ export const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
8
8
  export const TOOL_CALL_FILE = path.join(CONFIG_DIR, 'claude_tool_call.log');
9
9
  export const TOOL_CALL_FILE_MAX_SIZE = 1024 * 1024 * 10; // 10 MB
10
10
  export const DEFAULT_COMMAND_TIMEOUT = 1000; // milliseconds
11
+ // Longest one process call (start_process, interact_with_process,
12
+ // read_process_output) blocks, whatever timeout_ms asks for; the process keeps
13
+ // running and the caller reads the rest with read_process_output. It stays well
14
+ // under 60 s: that is the MCP SDK's default request timeout
15
+ // (DEFAULT_REQUEST_TIMEOUT_MSEC), which Claude Desktop and the remote device's
16
+ // own client use, and an answer capped at 60 s arrived just after the client had
17
+ // given up (-32001 "Request timed out", #447). The margin leaves time to build
18
+ // and deliver the answer.
19
+ export const MAX_PROCESS_WAIT_MS = 50000;