@wonderwhy-er/desktop-commander 0.2.48 → 0.2.50

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.
@@ -12,6 +12,40 @@ export class DesktopCommanderIntegration {
12
12
  this.mcpClient = null;
13
13
  this.mcpTransport = null;
14
14
  this.isReady = false;
15
+ this.isShuttingDown = false;
16
+ this.disconnectHandler = null;
17
+ this.reinitPromise = null;
18
+ }
19
+ /** True only while the local stdio child is actually reachable. */
20
+ get ready() {
21
+ return this.isReady && this.mcpClient !== null;
22
+ }
23
+ /**
24
+ * Register a callback fired when the local MCP child dies unexpectedly.
25
+ * The device uses this to stop advertising itself as online — the remote
26
+ * channel staying healthy says nothing about the local half being alive.
27
+ */
28
+ onDisconnect(handler) {
29
+ this.disconnectHandler = handler;
30
+ }
31
+ /**
32
+ * The local child exited or its pipe broke. Previously nothing observed this:
33
+ * `isReady` was a one-shot latch set in initialize() and cleared only by
34
+ * shutdown(), so every later callClientTool() sailed past the readiness guard
35
+ * and died inside the SDK with a bare "Not connected", forever, while the
36
+ * device still reported itself online.
37
+ */
38
+ handleLocalDisconnect(reason) {
39
+ if (this.isShuttingDown)
40
+ return; // expected teardown, not a fault
41
+ if (!this.isReady)
42
+ return; // already handled; don't double-fire
43
+ this.isReady = false;
44
+ this.mcpClient = null;
45
+ this.mcpTransport = null;
46
+ console.error(` - ❌ Local Desktop Commander MCP went away (${reason}); will restart on next tool call`);
47
+ void captureRemote('desktop_integration_local_disconnected', { reason });
48
+ this.disconnectHandler?.(reason);
15
49
  }
16
50
  async initialize() {
17
51
  console.debug('[DEBUG] DesktopCommanderIntegration.initialize() called');
@@ -43,16 +77,53 @@ export class DesktopCommanderIntegration {
43
77
  console.debug('[DEBUG] Connecting MCP client to transport');
44
78
  await this.mcpClient.connect(this.mcpTransport);
45
79
  this.isReady = true;
80
+ // Supervise the local half. Without these, a child crash is silent:
81
+ // the SDK clears its transport and every subsequent call throws
82
+ // "Not connected" with nothing tying it back to the death.
83
+ this.mcpTransport.onclose = () => this.handleLocalDisconnect('stdio transport closed');
84
+ this.mcpTransport.onerror = (err) => this.handleLocalDisconnect(`stdio transport error: ${err?.message ?? String(err)}`);
46
85
  console.log(' - 🔌 Connected to Desktop Commander MCP');
47
86
  console.debug('[DEBUG] Desktop Commander MCP connection successful');
48
87
  }
49
88
  catch (error) {
50
89
  console.error(' - ❌ Failed to connect to Desktop Commander MCP:', error);
51
90
  console.debug('[DEBUG] MCP connection error:', error);
91
+ // Leave no half-built client behind, or ensureReady() would treat the
92
+ // corpse as live on the next attempt.
93
+ this.isReady = false;
94
+ this.mcpClient = null;
95
+ if (this.mcpTransport) {
96
+ try {
97
+ await this.mcpTransport.close();
98
+ }
99
+ catch { /* already dead — nothing to salvage */ }
100
+ this.mcpTransport = null;
101
+ }
52
102
  await captureRemote('desktop_integration_init_failed', { error });
53
103
  throw error;
54
104
  }
55
105
  }
106
+ /**
107
+ * Guarantee a live local child before proxying a call, restarting it if the
108
+ * previous one died. Restart is lazy (on demand) rather than a retry loop:
109
+ * if the child is crashing on startup, each tool call fails with the real
110
+ * reason instead of spinning respawns in the background.
111
+ */
112
+ async ensureReady() {
113
+ if (this.ready)
114
+ return;
115
+ if (this.isShuttingDown) {
116
+ throw new Error('Desktop Commander integration is shutting down');
117
+ }
118
+ if (!this.reinitPromise) {
119
+ console.log(' - ♻️ Local Desktop Commander MCP is not running; restarting it...');
120
+ this.reinitPromise = this.initialize().finally(() => {
121
+ this.reinitPromise = null;
122
+ });
123
+ }
124
+ // Concurrent calls share the single in-flight restart.
125
+ await this.reinitPromise;
126
+ }
56
127
  async resolveMcpConfig() {
57
128
  console.debug('[DEBUG] Resolving MCP config...');
58
129
  // Option 1: Development/Local Build
@@ -106,10 +177,10 @@ export class DesktopCommanderIntegration {
106
177
  return null;
107
178
  }
108
179
  async callClientTool(toolName, args, metadata) {
109
- if (!this.isReady || !this.mcpClient) {
110
- console.debug('[DEBUG] callClientTool() failed - not ready or no client');
111
- throw new Error('DesktopIntegration not initialized');
112
- }
180
+ // Restart the child if it died since the last call, so a one-off crash
181
+ // costs one failed call instead of wedging the device until a human
182
+ // restarts `desktop-commander remote`.
183
+ await this.ensureReady();
113
184
  // Proxy other tools to MCP server
114
185
  try {
115
186
  console.debug('[DEBUG] Calling MCP tool:', toolName, 'args:', JSON.stringify(args).substring(0, 100));
@@ -150,6 +221,9 @@ export class DesktopCommanderIntegration {
150
221
  }
151
222
  async shutdown() {
152
223
  console.debug('[DEBUG] DesktopCommanderIntegration.shutdown() called');
224
+ // Closing the transport fires onclose; flag this as intentional so it is
225
+ // not reported as a crash.
226
+ this.isShuttingDown = true;
153
227
  const closeWithTimeout = async (operation, name, timeoutMs = 3000) => {
154
228
  return Promise.race([
155
229
  operation(),
@@ -2,6 +2,7 @@
2
2
  export interface MCPDeviceOptions {
3
3
  persistSession?: boolean;
4
4
  }
5
+ export declare function getRemoteDeviceConfigPath(): string;
5
6
  export declare class MCPDevice {
6
7
  private baseServerUrl;
7
8
  private remoteChannel;
@@ -15,12 +16,21 @@ export declare class MCPDevice {
15
16
  constructor(options?: MCPDeviceOptions);
16
17
  private setupShutdownHandlers;
17
18
  start(): Promise<void>;
19
+ private findPersistedDeviceWithRetry;
18
20
  loadPersistedConfig(): Promise<any>;
21
+ clearPersistedConfig(): Promise<void>;
19
22
  savePersistedConfig(): Promise<void>;
20
23
  fetchSupabaseConfig(): Promise<{
21
24
  supabaseUrl: any;
22
25
  anonKey: any;
23
26
  }>;
27
+ /**
28
+ * The local Desktop Commander child died. A healthy remote channel says
29
+ * nothing about the local half being alive, so without this the device kept
30
+ * reporting itself online and every routed tool call came back "Not
31
+ * connected" until someone restarted the process by hand.
32
+ */
33
+ private handleLocalMcpLoss;
24
34
  /** Record a handled call id, evicting the oldest once the cap is reached. */
25
35
  private rememberCallId;
26
36
  handleNewToolCall(payload: any): Promise<void>;
@@ -15,6 +15,11 @@ import { captureRemote } from '../utils/capture.js';
15
15
  * (the device process, not the shared server).
16
16
  */
17
17
  const SEEN_CALL_IDS_MAX = 100;
18
+ const PERSISTED_DEVICE_LOOKUP_ATTEMPTS = 3;
19
+ const PERSISTED_DEVICE_LOOKUP_RETRY_MS = 250;
20
+ export function getRemoteDeviceConfigPath() {
21
+ return path.join(os.homedir(), '.desktop-commander-device', 'device.json');
22
+ }
18
23
  export class MCPDevice {
19
24
  constructor(options = {}) {
20
25
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
@@ -23,7 +28,7 @@ export class MCPDevice {
23
28
  this.remoteChannel = new RemoteChannel();
24
29
  this.deviceId = undefined;
25
30
  this.isShuttingDown = false;
26
- this.configPath = path.join(os.homedir(), '.desktop-commander-device', 'device.json');
31
+ this.configPath = getRemoteDeviceConfigPath();
27
32
  // Default ON. Off meant a full re-authorization on every start, and each
28
33
  // one mints a fresh GoTrue session that nothing ever revokes; the orphaned
29
34
  // refresh-token families get replayed, trip GoTrue's reuse detection, and
@@ -86,6 +91,7 @@ export class MCPDevice {
86
91
  }
87
92
  // Initialize desktop integration
88
93
  await this.desktop.initialize();
94
+ this.desktop.onDisconnect((reason) => void this.handleLocalMcpLoss(reason));
89
95
  console.log(`⏳ Connecting to Remote MCP ${this.baseServerUrl}`);
90
96
  const { supabaseUrl, anonKey } = await this.fetchSupabaseConfig();
91
97
  console.log(` - 🔌 Connected to Remote MCP`);
@@ -102,6 +108,20 @@ export class MCPDevice {
102
108
  }
103
109
  else {
104
110
  console.log(' - ✅ Session restored');
111
+ console.log(' - ℹ️ To log out locally: npx @wonderwhy-er/desktop-commander@latest remote --logout');
112
+ // Revoking a device removes its server-side mcp_devices row, but the
113
+ // local config can still hold a valid user session + the now-deleted
114
+ // device ID. Do not silently recreate the revoked device with that
115
+ // old session: revocation must require a fresh browser authorization.
116
+ if (this.deviceId) {
117
+ const persistedDevice = await this.findPersistedDeviceWithRetry(this.deviceId);
118
+ if (!persistedDevice) {
119
+ console.log(` - ⚠️ Persisted device ${this.deviceId} was revoked or removed`);
120
+ await this.clearPersistedConfig();
121
+ this.deviceId = undefined;
122
+ session = null;
123
+ }
124
+ }
105
125
  }
106
126
  }
107
127
  if (!session) {
@@ -156,6 +176,22 @@ export class MCPDevice {
156
176
  process.exit(1);
157
177
  }
158
178
  }
179
+ async findPersistedDeviceWithRetry(deviceId) {
180
+ let lastError;
181
+ for (let attempt = 1; attempt <= PERSISTED_DEVICE_LOOKUP_ATTEMPTS; attempt++) {
182
+ try {
183
+ return await this.remoteChannel.findDevice(deviceId);
184
+ }
185
+ catch (error) {
186
+ lastError = error;
187
+ if (attempt === PERSISTED_DEVICE_LOOKUP_ATTEMPTS)
188
+ break;
189
+ console.warn(` - ⚠️ Device lookup failed (${attempt}/${PERSISTED_DEVICE_LOOKUP_ATTEMPTS}); retrying...`);
190
+ await new Promise((resolve) => setTimeout(resolve, PERSISTED_DEVICE_LOOKUP_RETRY_MS * attempt));
191
+ }
192
+ }
193
+ throw lastError;
194
+ }
159
195
  async loadPersistedConfig() {
160
196
  try {
161
197
  console.debug('[DEBUG] Loading persisted config from:', this.configPath);
@@ -194,6 +230,16 @@ export class MCPDevice {
194
230
  // No need to ensure device ID here
195
231
  }
196
232
  }
233
+ async clearPersistedConfig() {
234
+ try {
235
+ await fs.rm(this.configPath, { force: true });
236
+ console.debug('[DEBUG] Cleared stale persisted config:', this.configPath);
237
+ }
238
+ catch (error) {
239
+ console.warn('⚠️ Failed to clear stale config:', error.message);
240
+ await captureRemote('remote_device_config_clear_error', { error });
241
+ }
242
+ }
197
243
  async savePersistedConfig() {
198
244
  try {
199
245
  console.debug('[DEBUG] Saving persisted config, persistSession:', this.persistSession);
@@ -235,6 +281,32 @@ export class MCPDevice {
235
281
  };
236
282
  }
237
283
  // Methods moved to RemoteChannel
284
+ /**
285
+ * The local Desktop Commander child died. A healthy remote channel says
286
+ * nothing about the local half being alive, so without this the device kept
287
+ * reporting itself online and every routed tool call came back "Not
288
+ * connected" until someone restarted the process by hand.
289
+ */
290
+ async handleLocalMcpLoss(reason) {
291
+ if (this.deviceId) {
292
+ await this.remoteChannel.setOnlineStatus(this.deviceId, 'offline')
293
+ .catch((e) => console.error('Failed to mark device offline:', e.message));
294
+ }
295
+ // Recover proactively rather than waiting for the next tool call to
296
+ // trigger the lazy restart: we just went offline, so no further calls
297
+ // would be routed here and that wait would never end.
298
+ try {
299
+ await this.desktop.ensureReady();
300
+ if (this.deviceId) {
301
+ await this.remoteChannel.setOnlineStatus(this.deviceId, 'online');
302
+ }
303
+ console.log('♻️ Local Desktop Commander MCP restarted; device is online again');
304
+ }
305
+ catch (error) {
306
+ console.error(`❌ Could not restart local Desktop Commander MCP: ${error.message}`);
307
+ await captureRemote('remote_device_local_mcp_restart_failed', { error, reason });
308
+ }
309
+ }
238
310
  /** Record a handled call id, evicting the oldest once the cap is reached. */
239
311
  rememberCallId(callId) {
240
312
  this.seenCallIds.add(callId);
package/dist/server.js CHANGED
@@ -1051,16 +1051,18 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
1051
1051
  {
1052
1052
  name: "get_recent_tool_calls",
1053
1053
  description: `
1054
- Get recent tool call history with their arguments and outputs.
1055
- Returns chronological list of tool calls made during this session.
1054
+ Get recent local tool call history with arguments and outputs.
1055
+ Returns a chronological list of recent calls loaded from the local history file.
1056
1056
 
1057
1057
  Useful for:
1058
1058
  - Onboarding new chats about work already done
1059
1059
  - Recovering context after chat history loss
1060
1060
  - Debugging tool call sequences
1061
1061
 
1062
- Note: Does not track its own calls or other meta/query tools.
1063
- History kept in memory (last 1000 calls, lost on restart).
1062
+ Note: Does not track its own calls or track_ui_event.
1063
+ History is persisted locally in tool-history.jsonl, keeps up to the last 1000
1064
+ calls in memory, and trims older on-disk history. Stored outputs over 4 KiB
1065
+ are replaced with an omission marker.
1064
1066
 
1065
1067
  ${CMD_PREFIX_DESCRIPTION}`,
1066
1068
  inputSchema: zodToJsonSchema(GetRecentToolCallsArgsSchema),
@@ -203,6 +203,28 @@ export class TerminalManager {
203
203
  // Spawn the process with appropriate arguments
204
204
  const childProcess = spawn(spawnConfig.executable, spawnConfig.args, spawnOptions);
205
205
  let output = '';
206
+ // spawn() reports failure asynchronously via an 'error' event; it does not
207
+ // throw. Node rethrows an 'error' that has no listener as an uncaught
208
+ // exception, and our process-level handler (src/index.ts) turns that into
209
+ // process.exit(1). So an unresolvable executable — e.g. shell: "/usr/bin/bash"
210
+ // on Windows — used to kill the entire MCP server one tick AFTER this
211
+ // function had already returned "Failed to get process ID", making the crash
212
+ // look unrelated to the command that caused it. Under `remote` the parent
213
+ // then kept accepting tool calls over a dead stdio pipe ("Not connected").
214
+ //
215
+ // Attach before any return path below, and keep it for the session lifetime
216
+ // so a later runtime error (EPIPE on a closed stdin, ...) can't crash us either.
217
+ let forwardProcessError = null;
218
+ let pendingProcessError = null;
219
+ childProcess.on('error', (err) => {
220
+ if (forwardProcessError) {
221
+ forwardProcessError(err);
222
+ }
223
+ else {
224
+ pendingProcessError = err;
225
+ console.error(`Process error for "${command}": ${err.message}`);
226
+ }
227
+ });
206
228
  // Ensure childProcess.pid is defined before proceeding
207
229
  if (!childProcess.pid) {
208
230
  // Return a consistent error object instead of throwing
@@ -257,6 +279,23 @@ export class TerminalManager {
257
279
  }
258
280
  resolve(result);
259
281
  };
282
+ // Now that resolveOnce exists, route process errors into it: an error after
283
+ // a successful spawn means the process is gone, so the caller must not sit
284
+ // waiting for output that will never arrive.
285
+ forwardProcessError = (err) => {
286
+ this.sessions.delete(childProcess.pid);
287
+ exitReason = 'process_exit';
288
+ resolveOnce({
289
+ pid: childProcess.pid,
290
+ output: output + `\nProcess error: ${err.message}`,
291
+ isBlocked: false
292
+ });
293
+ };
294
+ // An error emitted between spawn and here (the common case — spawn errors
295
+ // land on the next tick) is replayed rather than dropped.
296
+ if (pendingProcessError) {
297
+ forwardProcessError(pendingProcessError);
298
+ }
260
299
  childProcess.stdout.on('data', (data) => {
261
300
  const text = data.toString();
262
301
  const now = Date.now();
@@ -239,6 +239,19 @@ RECOMMENDATION: For large search/replace operations, consider breaking them into
239
239
  // Log to file
240
240
  await fuzzySearchLogger.log(logEntry);
241
241
  // Combine all fuzzy search data for single capture
242
+ //
243
+ // character_codes (characterCodeData.report) is deliberately NOT sent.
244
+ // It is a frequency map of the characters in the diff between the
245
+ // search text and the file text, so for a short diff it is close to
246
+ // recoverable file content — and mcp-privacy-policy.md states that
247
+ // file contents are not collected. It was added as diagnostics for the
248
+ // CRLF/LF normalization work in #103 (May 2025) to show whether failed
249
+ // matches came from \r (13), \n (10) or non-breaking spaces; that
250
+ // question is long since answered.
251
+ //
252
+ // The scalars below are kept: they are counts and lengths, and carry
253
+ // no recoverable content. The full report still goes to the local
254
+ // fuzzy-search.log for anyone debugging on their own machine.
242
255
  const fuzzySearchData = {
243
256
  similarity: similarity,
244
257
  execution_time_ms: executionTime,
@@ -246,7 +259,6 @@ RECOMMENDATION: For large search/replace operations, consider breaking them into
246
259
  file_size: content.length,
247
260
  threshold: FUZZY_THRESHOLD,
248
261
  found_text_length: fuzzyResult.value.length,
249
- character_codes: characterCodeData.report,
250
262
  unique_character_count: characterCodeData.uniqueCount,
251
263
  total_diff_length: characterCodeData.diffLength
252
264
  };
@@ -1,6 +1,6 @@
1
1
  import { ProcessInfo, ServerResult } from '../types.js';
2
2
  /**
3
- * Parse `tasklist /fo csv /nh` output (#662). Fields per row, all quoted:
3
+ * Parse `tasklist /FO CSV /NH` output (#662). Fields per row, all quoted:
4
4
  * [Image Name, PID, Session Name, Session#, Mem Usage]. CSV instead of the
5
5
  * default table: image names can contain spaces and Mem Usage contains
6
6
  * thousands separators, so positional whitespace splitting can't work.
@@ -4,7 +4,7 @@ import os from 'os';
4
4
  import { KillProcessArgsSchema } from './schemas.js';
5
5
  const execAsync = promisify(exec);
6
6
  /**
7
- * Parse `tasklist /fo csv /nh` output (#662). Fields per row, all quoted:
7
+ * Parse `tasklist /FO CSV /NH` output (#662). Fields per row, all quoted:
8
8
  * [Image Name, PID, Session Name, Session#, Mem Usage]. CSV instead of the
9
9
  * default table: image names can contain spaces and Mem Usage contains
10
10
  * thousands separators, so positional whitespace splitting can't work.
@@ -46,7 +46,7 @@ export function parsePsAux(stdout) {
46
46
  }
47
47
  export async function listProcesses() {
48
48
  const isWindows = os.platform() === 'win32';
49
- const command = isWindows ? 'tasklist /fo csv /nh' : 'ps aux';
49
+ const command = isWindows ? 'tasklist /FO CSV /NH' : 'ps aux';
50
50
  try {
51
51
  const { stdout } = await execAsync(command);
52
52
  const processes = isWindows ? parseWindowsTasklistCsv(stdout) : parsePsAux(stdout);
@@ -693,12 +693,6 @@ export default async function uninstall() {
693
693
  logToFile('\nIf you want to reinstall later, you can run:');
694
694
  logToFile('npx @wonderwhy-er/desktop-commander@latest setup');
695
695
 
696
- logToFile('\n🎁 We\'re sorry to see you leaving, we’d love to understand your decision not to use Desktop Commander.')
697
- logToFile('In return for a brief 30-minute call, we’ll send you a $20 Amazon gift card as a thank-you.');
698
- logToFile('To get a gift card, please fill out this form:');
699
- logToFile(' https://tally.so/r/w8lyRo');
700
-
701
-
702
696
  logToFile('\nThank you for using Desktop Commander! 👋\n');
703
697
 
704
698
  // Send final tracking event
@@ -712,11 +706,6 @@ export default async function uninstall() {
712
706
  logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.');
713
707
  logToFile(`Configuration file location: ${claudeConfigPath}\n`);
714
708
 
715
- logToFile('\n🎁 We\'re sorry to see you leaving, we\'d love to understand your decision not to use Desktop Commander.')
716
- logToFile('In return for a brief 30-minute call, we\'ll send you a $20 Amazon gift card as a thank-you.');
717
- logToFile('To get a gift card, please fill out this form:');
718
- logToFile(' https://tally.so/r/w8lyRo');
719
-
720
709
  await ensureTrackingCompleted('uninstall_partial_failure');
721
710
 
722
711
  return false;
@@ -735,10 +724,6 @@ export default async function uninstall() {
735
724
  logToFile('You may need to manually remove Desktop Commander from Claude\'s configuration.');
736
725
  logToFile(`Configuration file location: ${claudeConfigPath}\n`);
737
726
 
738
- logToFile('\n🎁 We\'re sorry to see you leaving, we\'d love to understand your decision not to use Desktop Commander.')
739
- logToFile('In return for a brief 30-minute call, we\'ll send you a $20 Amazon gift card as a thank-you.');
740
- logToFile('To get a gift card, please fill out this form:');
741
- logToFile('https://tally.so/r/w8lyRo');
742
727
  return false;
743
728
  }
744
729
  }
@@ -19,6 +19,7 @@ import { FileHandler, ReadOptions, FileResult, FileInfo } from './base.js';
19
19
  */
20
20
  export declare class TextFileHandler implements FileHandler {
21
21
  canHandle(_path: string): boolean;
22
+ private detectTextEncoding;
22
23
  read(filePath: string, options?: ReadOptions): Promise<FileResult>;
23
24
  write(path: string, content: string, mode?: 'rewrite' | 'append'): Promise<void>;
24
25
  getInfo(path: string): Promise<FileInfo>;
@@ -38,6 +38,20 @@ export class TextFileHandler {
38
38
  // The factory routes binary files to BinaryFileHandler before reaching here
39
39
  return true;
40
40
  }
41
+ async detectTextEncoding(filePath) {
42
+ const fd = await fs.open(filePath, 'r');
43
+ try {
44
+ const bom = Buffer.alloc(2);
45
+ const { bytesRead } = await fd.read(bom, 0, bom.length, 0);
46
+ if (bytesRead === 2 && bom[0] === 0xff && bom[1] === 0xfe) {
47
+ return 'utf16le';
48
+ }
49
+ return 'utf8';
50
+ }
51
+ finally {
52
+ await fd.close();
53
+ }
54
+ }
41
55
  async read(filePath, options) {
42
56
  const offset = options?.offset ?? 0;
43
57
  const length = options?.length ?? 1000; // Default from config
@@ -69,7 +83,11 @@ export class TextFileHandler {
69
83
  // For text files that aren't too large, count lines
70
84
  if (stats.isFile() && stats.size < FILE_SIZE_LIMITS.LINE_COUNT_LIMIT) {
71
85
  try {
72
- const content = await fs.readFile(path, 'utf8');
86
+ const encoding = await this.detectTextEncoding(path);
87
+ let content = await fs.readFile(path, encoding);
88
+ if (encoding === 'utf16le' && content.charCodeAt(0) === 0xfeff) {
89
+ content = content.slice(1);
90
+ }
73
91
  const lineCount = TextFileHandler.countLines(content);
74
92
  info.metadata.lineCount = lineCount;
75
93
  }
@@ -100,11 +118,14 @@ export class TextFileHandler {
100
118
  /**
101
119
  * Get file line count (for files under size limit)
102
120
  */
103
- async getFileLineCount(filePath, signal) {
121
+ async getFileLineCount(filePath, signal, encoding = 'utf8') {
104
122
  try {
105
123
  const stats = await fs.stat(filePath);
106
124
  if (stats.size < FILE_SIZE_LIMITS.LINE_COUNT_LIMIT) {
107
- const content = await fs.readFile(filePath, { encoding: 'utf8', signal });
125
+ let content = await fs.readFile(filePath, { encoding, signal });
126
+ if (encoding === 'utf16le' && content.charCodeAt(0) === 0xfeff) {
127
+ content = content.slice(1);
128
+ }
108
129
  return TextFileHandler.countLines(content);
109
130
  }
110
131
  }
@@ -182,7 +203,16 @@ export class TextFileHandler {
182
203
  async readFileWithSmartPositioning(filePath, offset, length, mimeType, includeStatusMessage = true, signal) {
183
204
  const stats = await fs.stat(filePath);
184
205
  const fileSize = stats.size;
185
- const totalLines = await this.getFileLineCount(filePath, signal);
206
+ const encoding = await this.detectTextEncoding(filePath);
207
+ const totalLines = await this.getFileLineCount(filePath, signal, encoding);
208
+ // UTF-16LE needs character-aware streaming. Skip the two-byte BOM and keep
209
+ // the same line pagination/status semantics as ordinary text reads.
210
+ if (encoding === 'utf16le') {
211
+ if (offset < 0) {
212
+ return await this.readFromEndWithReadline(filePath, Math.abs(offset), mimeType, includeStatusMessage, totalLines, signal, 'utf16le', 2);
213
+ }
214
+ return await this.readFromStartWithReadline(filePath, offset, length, mimeType, includeStatusMessage, totalLines, signal, 'utf16le', 2);
215
+ }
186
216
  // For negative offsets (tail behavior), use reverse reading
187
217
  if (offset < 0) {
188
218
  const requestedLines = Math.abs(offset);
@@ -252,9 +282,9 @@ export class TextFileHandler {
252
282
  /**
253
283
  * Read from end using readline with circular buffer
254
284
  */
255
- async readFromEndWithReadline(filePath, requestedLines, mimeType, includeStatusMessage = true, fileTotalLines, signal) {
285
+ async readFromEndWithReadline(filePath, requestedLines, mimeType, includeStatusMessage = true, fileTotalLines, signal, encoding, start) {
256
286
  const rl = createInterface({
257
- input: createReadStream(filePath, { signal }),
287
+ input: createReadStream(filePath, { signal, encoding, start }),
258
288
  crlfDelay: Infinity
259
289
  });
260
290
  const buffer = new Array(requestedLines);
@@ -284,9 +314,9 @@ export class TextFileHandler {
284
314
  /**
285
315
  * Read from start/middle using readline
286
316
  */
287
- async readFromStartWithReadline(filePath, offset, length, mimeType, includeStatusMessage = true, fileTotalLines, signal) {
317
+ async readFromStartWithReadline(filePath, offset, length, mimeType, includeStatusMessage = true, fileTotalLines, signal, encoding, start) {
288
318
  const rl = createInterface({
289
- input: createReadStream(filePath, { signal }),
319
+ input: createReadStream(filePath, { signal, encoding, start }),
290
320
  crlfDelay: Infinity
291
321
  });
292
322
  const result = [];
@@ -37,14 +37,6 @@ declare class UsageTracker {
37
37
  * Get current usage stats from config
38
38
  */
39
39
  getStats(): Promise<ToolUsageStats>;
40
- /**
41
- * Save usage stats to config.
42
- * Non-blocking: the tool-call return path must not wait on a disk write. The
43
- * in-memory stats are already updated by the caller (getStats returns the live
44
- * config object), so persistence is coalesced in the background. This is what
45
- * keeps a saturated libuv threadpool from gating tool responses on every call.
46
- */
47
- private saveStats;
48
40
  /**
49
41
  * Determine which category a tool belongs to
50
42
  */