@wonderwhy-er/desktop-commander 0.1.37 → 0.1.39

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 (36) hide show
  1. package/README.md +1 -1
  2. package/dist/REPLSessionManager.d.ts +109 -0
  3. package/dist/REPLSessionManager.js +364 -0
  4. package/dist/REPLSessionManager.test.d.ts +1 -0
  5. package/dist/REPLSessionManager.test.js +75 -0
  6. package/dist/client/replClient.d.ts +63 -0
  7. package/dist/client/replClient.js +217 -0
  8. package/dist/client/sshClient.d.ts +82 -0
  9. package/dist/client/sshClient.js +200 -0
  10. package/dist/handlers/repl-handlers.d.ts +21 -0
  11. package/dist/handlers/repl-handlers.js +37 -0
  12. package/dist/handlers/replCommandHandler.d.ts +125 -0
  13. package/dist/handlers/replCommandHandler.js +255 -0
  14. package/dist/handlers/replCommandHandler.test.d.ts +1 -0
  15. package/dist/handlers/replCommandHandler.test.js +103 -0
  16. package/dist/index.js +1 -2
  17. package/dist/repl-manager.d.ts +73 -0
  18. package/dist/repl-manager.js +407 -0
  19. package/dist/replIntegration.d.ts +14 -0
  20. package/dist/replIntegration.js +27 -0
  21. package/dist/setup-claude-server.js +14 -15
  22. package/dist/tools/edit.js +83 -24
  23. package/dist/tools/enhanced-read-output.js +69 -0
  24. package/dist/tools/enhanced-send-input.js +111 -0
  25. package/dist/tools/filesystem.js +6 -5
  26. package/dist/tools/repl.d.ts +21 -0
  27. package/dist/tools/repl.js +217 -0
  28. package/dist/tools/send-input.d.ts +2 -0
  29. package/dist/tools/send-input.js +45 -0
  30. package/dist/utils/lineEndingHandler.d.ts +21 -0
  31. package/dist/utils/lineEndingHandler.js +77 -0
  32. package/dist/utils/lineEndingHandler_optimized.d.ts +21 -0
  33. package/dist/utils/lineEndingHandler_optimized.js +77 -0
  34. package/dist/version.d.ts +1 -1
  35. package/dist/version.js +1 -1
  36. package/package.json +1 -1
@@ -0,0 +1,407 @@
1
+ import { terminalManager } from './terminal-manager.js';
2
+ import { capture } from './utils/capture.js';
3
+ /**
4
+ * Manager for REPL (Read-Eval-Print Loop) sessions
5
+ * Provides a higher-level API for working with interactive programming environments
6
+ */
7
+ export class REPLManager {
8
+ constructor() {
9
+ this.sessions = new Map();
10
+ // Language-specific configurations for various REPLs
11
+ this.languageConfigs = {
12
+ 'python': {
13
+ command: process.platform === 'win32' ? 'python' : 'python3',
14
+ args: ['-i'],
15
+ promptPattern: /^(>>>|\.\.\.) /m,
16
+ errorPattern: /\b(Error|Exception|SyntaxError|TypeError|ValueError|NameError|ImportError|AttributeError)\b:.*$/m,
17
+ continuationPattern: /^\.\.\./m,
18
+ executeBlock: (code) => {
19
+ // Break code into lines
20
+ const lines = code.split('\n');
21
+ // For Python, we need to add an extra newline after blocks to execute them
22
+ if (lines.length > 1 && lines[lines.length - 1].trim() !== '') {
23
+ lines.push(''); // Add an empty line to end the block
24
+ }
25
+ return lines;
26
+ }
27
+ },
28
+ 'node': {
29
+ command: 'node',
30
+ args: ['-i'], // Use the -i flag to force interactive mode
31
+ promptPattern: /^> ?$/m, // Updated to match exactly the Node.js prompt at beginning of line
32
+ errorPattern: /\b(Error|SyntaxError|TypeError|ReferenceError|RangeError)\b:.*$/m,
33
+ executeBlock: (code) => {
34
+ // For Node.js REPL, we need different handling for multi-line code
35
+ const lines = code.split('\n');
36
+ if (lines.length > 1) {
37
+ // For multi-line code, we'll just execute it as one string
38
+ // Node.js can handle this without entering editor mode
39
+ return [code];
40
+ }
41
+ return [code];
42
+ }
43
+ },
44
+ 'bash': {
45
+ command: 'bash',
46
+ args: ['-i'],
47
+ promptPattern: /[\w\d\-_]+@[\w\d\-_]+:.*[$#] $/m,
48
+ errorPattern: /\b(command not found|No such file or directory|syntax error|Permission denied)\b/m
49
+ }
50
+ };
51
+ }
52
+ /**
53
+ * Calculate an appropriate timeout based on code complexity
54
+ */
55
+ calculateTimeout(code, language) {
56
+ // Base timeout
57
+ let timeout = 2000;
58
+ // Add time for loops
59
+ const loopCount = (code.match(/for|while/g) || []).length;
60
+ timeout += loopCount * 1000;
61
+ // Add time for imports/requires
62
+ const importPatterns = {
63
+ 'python': [/import/g, /from\s+\w+\s+import/g],
64
+ 'node': [/require\(/g, /import\s+.*\s+from/g],
65
+ 'bash': [/source/g]
66
+ };
67
+ const patterns = importPatterns[language] || [];
68
+ let importCount = 0;
69
+ patterns.forEach(pattern => {
70
+ importCount += (code.match(pattern) || []).length;
71
+ });
72
+ timeout += importCount * 2000;
73
+ // Add more time for long scripts
74
+ const lineCount = code.split('\n').length;
75
+ timeout += lineCount * 200;
76
+ // Cap at reasonable maximum
77
+ return Math.min(timeout, 30000);
78
+ }
79
+ /**
80
+ * Detect when a REPL is ready for input by looking for prompt patterns
81
+ */
82
+ isReadyForInput(output, language) {
83
+ const config = this.languageConfigs[language];
84
+ if (!config || !config.promptPattern)
85
+ return false;
86
+ // For Node.js, look for the prompt at the end of the output
87
+ if (language === 'node') {
88
+ const lines = output.split('\n');
89
+ const lastLine = lines[lines.length - 1].trim();
90
+ return lastLine === '>' || lastLine === '...';
91
+ }
92
+ // For other languages, use the regular pattern
93
+ return config.promptPattern.test(output);
94
+ }
95
+ /**
96
+ * Detect errors in REPL output
97
+ */
98
+ detectErrors(output, language) {
99
+ const config = this.languageConfigs[language];
100
+ if (!config || !config.errorPattern)
101
+ return null;
102
+ const match = output.match(config.errorPattern);
103
+ return match ? match[0] : null;
104
+ }
105
+ /**
106
+ * Create a new REPL session for the specified language
107
+ */
108
+ async createSession(language, timeout = 5000) {
109
+ try {
110
+ const config = this.languageConfigs[language];
111
+ if (!config) {
112
+ throw new Error(`Unsupported language: ${language}`);
113
+ }
114
+ // Prepare the command and arguments
115
+ const command = `${config.command} ${config.args.join(' ')}`.trim();
116
+ // Start the process
117
+ const result = await terminalManager.executeCommand(command, timeout);
118
+ if (result.pid <= 0) {
119
+ throw new Error(`Failed to start ${language} REPL: ${result.output}`);
120
+ }
121
+ // Record session information
122
+ this.sessions.set(result.pid, {
123
+ pid: result.pid,
124
+ language,
125
+ startTime: Date.now(),
126
+ lastActivity: Date.now(),
127
+ outputBuffer: result.output || ''
128
+ });
129
+ capture('repl_session_created', {
130
+ language,
131
+ pid: result.pid
132
+ });
133
+ return result.pid;
134
+ }
135
+ catch (error) {
136
+ const errorMessage = error instanceof Error ? error.message : String(error);
137
+ capture('repl_session_creation_failed', {
138
+ language,
139
+ error: errorMessage
140
+ });
141
+ throw error;
142
+ }
143
+ }
144
+ /**
145
+ * Send and read REPL output with a timeout
146
+ * This combines sending input and reading output in a single operation
147
+ */
148
+ async sendAndReadREPL(pid, input, options = {}) {
149
+ const session = this.sessions.get(pid);
150
+ if (!session) {
151
+ return {
152
+ success: false,
153
+ output: null,
154
+ error: `No active session with PID ${pid}`,
155
+ timeout: false
156
+ };
157
+ }
158
+ try {
159
+ // Update last activity time
160
+ session.lastActivity = Date.now();
161
+ // Get the language configuration
162
+ const config = this.languageConfigs[session.language];
163
+ // Default timeout based on code complexity
164
+ const timeout = options.timeout || this.calculateTimeout(input, session.language);
165
+ // Clear any existing output
166
+ const existingOutput = terminalManager.getNewOutput(pid) || '';
167
+ if (existingOutput) {
168
+ session.outputBuffer += existingOutput;
169
+ }
170
+ // For Node.js, we need to handle the initial startup differently
171
+ if (session.language === 'node' && session.outputBuffer.length === 0) {
172
+ // Wait for Node.js to initialize if this is the first command
173
+ await new Promise(resolve => setTimeout(resolve, 1000));
174
+ const initialOutput = terminalManager.getNewOutput(pid) || '';
175
+ if (initialOutput) {
176
+ session.outputBuffer += initialOutput;
177
+ }
178
+ // Add another small delay to ensure the Node.js REPL is fully ready
179
+ await new Promise(resolve => setTimeout(resolve, 500));
180
+ }
181
+ let output = "";
182
+ // For Node.js, always send the entire code block at once
183
+ if (session.language === 'node' && options.multiline && input.includes('\n')) {
184
+ const success = terminalManager.sendInputToProcess(pid, input.endsWith('\n') ? input : input + '\n');
185
+ if (!success) {
186
+ return {
187
+ success: false,
188
+ output: session.outputBuffer,
189
+ error: "Failed to send input to Node.js REPL",
190
+ timeout: false
191
+ };
192
+ }
193
+ }
194
+ // For other languages or single-line input, process according to language rules
195
+ else if (options.multiline && config.executeBlock) {
196
+ const lines = config.executeBlock(input);
197
+ // For other languages, send each line individually
198
+ for (const line of lines) {
199
+ const success = terminalManager.sendInputToProcess(pid, line + '\n');
200
+ if (!success) {
201
+ return {
202
+ success: false,
203
+ output: session.outputBuffer,
204
+ error: "Failed to send input to process",
205
+ timeout: false
206
+ };
207
+ }
208
+ // Wait a small amount of time between lines
209
+ await new Promise(resolve => setTimeout(resolve, 100));
210
+ }
211
+ }
212
+ else {
213
+ // Single line input
214
+ const success = terminalManager.sendInputToProcess(pid, input.endsWith('\n') ? input : input + '\n');
215
+ if (!success) {
216
+ return {
217
+ success: false,
218
+ output: session.outputBuffer,
219
+ error: "Failed to send input to process",
220
+ timeout: false
221
+ };
222
+ }
223
+ }
224
+ // Wait for output with timeout
225
+ output = "";
226
+ const startTime = Date.now();
227
+ let isTimedOut = false;
228
+ let lastOutputLength = 0;
229
+ let noOutputTime = 0;
230
+ // Keep checking for output until timeout
231
+ while (Date.now() - startTime < timeout) {
232
+ // Check for new output
233
+ const newOutput = terminalManager.getNewOutput(pid) || '';
234
+ if (newOutput && newOutput.length > 0) {
235
+ output += newOutput;
236
+ session.outputBuffer += newOutput;
237
+ lastOutputLength = output.length;
238
+ noOutputTime = 0; // Reset no output timer
239
+ // If we're waiting for a prompt and it appears, we're done
240
+ if (options.waitForPrompt && this.isReadyForInput(output, session.language)) {
241
+ break;
242
+ }
243
+ // Check for errors if we're not ignoring them
244
+ if (!options.ignoreErrors) {
245
+ const error = this.detectErrors(output, session.language);
246
+ if (error) {
247
+ return {
248
+ success: false,
249
+ output,
250
+ error,
251
+ timeout: false
252
+ };
253
+ }
254
+ }
255
+ }
256
+ else {
257
+ // If no new output, increment the no output timer
258
+ noOutputTime += 100;
259
+ }
260
+ // For Node.js, we need to be more patient due to REPL behavior
261
+ const nodeWaitThreshold = session.language === 'node' ? 2000 : 1000;
262
+ // If no new output for specified time and we have some output, we're probably done
263
+ if (output.length > 0 && output.length === lastOutputLength && noOutputTime > nodeWaitThreshold) {
264
+ // For Node.js, make sure we have a prompt before finishing
265
+ if (session.language === 'node') {
266
+ if (this.isReadyForInput(output, 'node')) {
267
+ break;
268
+ }
269
+ }
270
+ else {
271
+ break;
272
+ }
273
+ }
274
+ // Small delay between checks
275
+ await new Promise(resolve => setTimeout(resolve, 100));
276
+ }
277
+ // Check if we timed out
278
+ isTimedOut = (Date.now() - startTime) >= timeout;
279
+ return {
280
+ success: !isTimedOut || output.length > 0,
281
+ output,
282
+ timeout: isTimedOut
283
+ };
284
+ }
285
+ catch (error) {
286
+ const errorMessage = error instanceof Error ? error.message : String(error);
287
+ capture('repl_command_failed', {
288
+ pid,
289
+ language: session.language,
290
+ error: errorMessage
291
+ });
292
+ return {
293
+ success: false,
294
+ output: null,
295
+ error: errorMessage,
296
+ timeout: false
297
+ };
298
+ }
299
+ }
300
+ /**
301
+ * Execute a code block in a REPL session
302
+ */
303
+ async executeCode(pid, code, options = {}) {
304
+ const session = this.sessions.get(pid);
305
+ if (!session) {
306
+ return {
307
+ success: false,
308
+ output: null,
309
+ error: `No active session with PID ${pid}`,
310
+ timeout: false
311
+ };
312
+ }
313
+ try {
314
+ capture('repl_execute_code', {
315
+ pid,
316
+ language: session.language,
317
+ codeLength: code.length,
318
+ lineCount: code.split('\n').length
319
+ });
320
+ // If code is multi-line, handle it accordingly
321
+ const isMultiline = code.includes('\n');
322
+ // For Node.js, use a longer timeout by default
323
+ if (session.language === 'node' && !options.timeout) {
324
+ options.timeout = Math.max(this.calculateTimeout(code, session.language), 5000);
325
+ }
326
+ // For Node.js, always wait for prompt
327
+ if (session.language === 'node' && options.waitForPrompt === undefined) {
328
+ options.waitForPrompt = true;
329
+ }
330
+ return this.sendAndReadREPL(pid, code, {
331
+ ...options,
332
+ multiline: isMultiline
333
+ });
334
+ }
335
+ catch (error) {
336
+ const errorMessage = error instanceof Error ? error.message : String(error);
337
+ capture('repl_execute_code_failed', {
338
+ pid,
339
+ language: session.language,
340
+ error: errorMessage
341
+ });
342
+ return {
343
+ success: false,
344
+ output: null,
345
+ error: errorMessage,
346
+ timeout: false
347
+ };
348
+ }
349
+ }
350
+ /**
351
+ * Terminate a REPL session
352
+ */
353
+ async terminateSession(pid) {
354
+ try {
355
+ const session = this.sessions.get(pid);
356
+ if (!session) {
357
+ return false;
358
+ }
359
+ // Terminate the process
360
+ const success = terminalManager.forceTerminate(pid);
361
+ // Remove from our sessions map
362
+ if (success) {
363
+ this.sessions.delete(pid);
364
+ capture('repl_session_terminated', {
365
+ pid,
366
+ language: session.language,
367
+ runtime: Date.now() - session.startTime
368
+ });
369
+ }
370
+ return success;
371
+ }
372
+ catch (error) {
373
+ const errorMessage = error instanceof Error ? error.message : String(error);
374
+ capture('repl_session_termination_failed', {
375
+ pid,
376
+ error: errorMessage
377
+ });
378
+ return false;
379
+ }
380
+ }
381
+ /**
382
+ * List all active REPL sessions
383
+ */
384
+ listSessions() {
385
+ return Array.from(this.sessions.values()).map(session => ({
386
+ pid: session.pid,
387
+ language: session.language,
388
+ runtime: Date.now() - session.startTime
389
+ }));
390
+ }
391
+ /**
392
+ * Get information about a specific REPL session
393
+ */
394
+ getSessionInfo(pid) {
395
+ const session = this.sessions.get(pid);
396
+ if (!session) {
397
+ return null;
398
+ }
399
+ return {
400
+ pid: session.pid,
401
+ language: session.language,
402
+ runtime: Date.now() - session.startTime
403
+ };
404
+ }
405
+ }
406
+ // Export singleton instance
407
+ export const replManager = new REPLManager();
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Integration file showing how to integrate REPL functionality
3
+ * with the Claude Server Commander
4
+ */
5
+ interface ServerInterface {
6
+ registerCommands: (commands: Record<string, Function>) => void;
7
+ }
8
+ /**
9
+ * Integrates REPL functionality with the server
10
+ * @param server - Server instance
11
+ * @param terminalManager - Terminal manager instance
12
+ */
13
+ export declare function integrateREPL(server: ServerInterface, terminalManager: any): void;
14
+ export {};
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Integration file showing how to integrate REPL functionality
3
+ * with the Claude Server Commander
4
+ */
5
+ import { initializeREPLManager, replCommandHandler } from './handlers/replCommandHandler.js';
6
+ /**
7
+ * Integrates REPL functionality with the server
8
+ * @param server - Server instance
9
+ * @param terminalManager - Terminal manager instance
10
+ */
11
+ export function integrateREPL(server, terminalManager) {
12
+ // Initialize the REPL manager with the terminal manager
13
+ initializeREPLManager(terminalManager);
14
+ // Register REPL commands with the server
15
+ server.registerCommands({
16
+ // REPL language sessions (Python, Node.js, Bash)
17
+ 'repl.create': replCommandHandler.createREPLSession,
18
+ 'repl.execute': replCommandHandler.executeREPLCode,
19
+ 'repl.list': replCommandHandler.listREPLSessions,
20
+ 'repl.close': replCommandHandler.closeREPLSession,
21
+ 'repl.closeIdle': replCommandHandler.closeIdleREPLSessions,
22
+ // SSH specific commands
23
+ 'ssh.create': replCommandHandler.createSSHSession,
24
+ 'ssh.execute': replCommandHandler.executeSSHCommand
25
+ });
26
+ console.log('REPL and SSH functionality integrated successfully');
27
+ }
@@ -243,8 +243,6 @@ async function trackEvent(eventName, additionalProps = {}) {
243
243
 
244
244
  } catch (error) {
245
245
  lastError = error;
246
- logToFile(`Error tracking event ${eventName} (attempt ${attempt}/${maxRetries + 1}): ${error}`, true);
247
-
248
246
  if (attempt <= maxRetries) {
249
247
  // Wait before retry (exponential backoff)
250
248
  await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
@@ -261,7 +259,6 @@ async function trackEvent(eventName, additionalProps = {}) {
261
259
  async function ensureTrackingCompleted(eventName, additionalProps = {}, timeoutMs = 6000) {
262
260
  return new Promise(async (resolve) => {
263
261
  const timeoutId = setTimeout(() => {
264
- logToFile(`Tracking timeout for ${eventName}`, true);
265
262
  resolve(false);
266
263
  }, timeoutMs);
267
264
 
@@ -271,7 +268,6 @@ async function ensureTrackingCompleted(eventName, additionalProps = {}, timeoutM
271
268
  resolve(true);
272
269
  } catch (error) {
273
270
  clearTimeout(timeoutId);
274
- logToFile(`Failed to complete tracking for ${eventName}: ${error}`, true);
275
271
  resolve(false);
276
272
  }
277
273
  });
@@ -309,15 +305,17 @@ function logToFile(message, isError = false) {
309
305
 
310
306
  // Setup global error handlers
311
307
  process.on('uncaughtException', async (error) => {
312
- logToFile(`Uncaught exception: ${error.stack || error.message}`, true);
313
308
  await trackEvent('npx_setup_uncaught_exception', { error: error.message });
314
- process.exit(1);
309
+ setTimeout(() => {
310
+ process.exit(1);
311
+ }, 1000);
315
312
  });
316
313
 
317
314
  process.on('unhandledRejection', async (reason, promise) => {
318
- logToFile(`Unhandled rejection at: ${promise}, reason: ${reason}`, true);
319
315
  await trackEvent('npx_setup_unhandled_rejection', { error: String(reason) });
320
- process.exit(1);
316
+ setTimeout(() => {
317
+ process.exit(1);
318
+ }, 1000);
321
319
  });
322
320
 
323
321
  // Track when the process is about to exi
@@ -325,8 +323,6 @@ let isExiting = false;
325
323
  process.on('exit', () => {
326
324
  if (!isExiting) {
327
325
  isExiting = true;
328
- // Synchronous tracking for exit handler
329
- logToFile('Process is exiting. Some tracking events may not be sent.');
330
326
  }
331
327
  });
332
328
 
@@ -403,7 +399,6 @@ try {
403
399
  updateSetupStep(machineIdInitStep, 'fallback', error);
404
400
  }
405
401
  } catch (error) {
406
- logToFile(`Error initializing user ID: ${error}`, true);
407
402
  addSetupStep('initialize_machine_id', 'failed', error);
408
403
  }
409
404
 
@@ -479,14 +474,15 @@ async function restartClaude() {
479
474
  } else if (platform === "darwin") {
480
475
  await execAsync(`open -a "Claude"`);
481
476
  updateSetupStep(startStep, 'completed');
477
+ logToFile(`Claude has been restarted.`);
482
478
  await trackEvent('npx_setup_start_claude_success', { platform });
483
479
  } else if (platform === "linux") {
484
480
  await execAsync(`claude`);
481
+ logToFile(`Claude has been restarted.`);
485
482
  updateSetupStep(startStep, 'completed');
486
483
  await trackEvent('npx_setup_start_claude_success', { platform });
487
484
  }
488
485
 
489
- logToFile(`Claude has been restarted.`);
490
486
  updateSetupStep(restartStep, 'completed');
491
487
  await trackEvent('npx_setup_restart_claude_success', { platform });
492
488
  } catch (startError) {
@@ -684,7 +680,6 @@ export default async function setup() {
684
680
 
685
681
  // Check if the old "desktopCommander" exists and remove i
686
682
  if (config.mcpServers.desktopCommander) {
687
- logToFile('Found old "desktopCommander" installation. Removing it...');
688
683
  delete config.mcpServers.desktopCommander;
689
684
  await trackEvent('npx_setup_remove_old_config');
690
685
  }
@@ -743,7 +738,9 @@ export default async function setup() {
743
738
  if (process.argv.length >= 2 && process.argv[1] === fileURLToPath(import.meta.url)) {
744
739
  setup().then(success => {
745
740
  if (!success) {
746
- process.exit(1);
741
+ setTimeout(() => {
742
+ process.exit(1);
743
+ }, 1000);
747
744
  }
748
745
  }).catch(async error => {
749
746
  await ensureTrackingCompleted('npx_setup_fatal_error', {
@@ -751,6 +748,8 @@ if (process.argv.length >= 2 && process.argv[1] === fileURLToPath(import.meta.ur
751
748
  error_stack: error.stack
752
749
  });
753
750
  logToFile(`Fatal error: ${error}`, true);
754
- process.exit(1);
751
+ setTimeout(() => {
752
+ process.exit(1);
753
+ }, 1000);
755
754
  });
756
755
  }