@wonderwhy-er/desktop-commander 0.2.3 → 0.2.4

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 (43) hide show
  1. package/README.md +25 -3
  2. package/dist/config-manager.d.ts +10 -0
  3. package/dist/config-manager.js +7 -1
  4. package/dist/handlers/edit-search-handlers.js +25 -6
  5. package/dist/handlers/terminal-handlers.d.ts +8 -4
  6. package/dist/handlers/terminal-handlers.js +16 -10
  7. package/dist/index-dxt.d.ts +2 -0
  8. package/dist/index-dxt.js +76 -0
  9. package/dist/index-with-startup-detection.d.ts +5 -0
  10. package/dist/index-with-startup-detection.js +180 -0
  11. package/dist/server.d.ts +5 -0
  12. package/dist/server.js +343 -42
  13. package/dist/terminal-manager.d.ts +7 -0
  14. package/dist/terminal-manager.js +93 -18
  15. package/dist/tools/client.d.ts +10 -0
  16. package/dist/tools/client.js +13 -0
  17. package/dist/tools/config.d.ts +1 -1
  18. package/dist/tools/config.js +21 -3
  19. package/dist/tools/edit.js +4 -3
  20. package/dist/tools/environment.d.ts +55 -0
  21. package/dist/tools/environment.js +65 -0
  22. package/dist/tools/feedback.d.ts +8 -0
  23. package/dist/tools/feedback.js +132 -0
  24. package/dist/tools/filesystem.js +152 -57
  25. package/dist/tools/improved-process-tools.js +170 -29
  26. package/dist/tools/schemas.d.ts +20 -2
  27. package/dist/tools/schemas.js +20 -2
  28. package/dist/tools/usage.d.ts +5 -0
  29. package/dist/tools/usage.js +24 -0
  30. package/dist/utils/capture.js +23 -1
  31. package/dist/utils/early-logger.d.ts +4 -0
  32. package/dist/utils/early-logger.js +35 -0
  33. package/dist/utils/mcp-logger.d.ts +30 -0
  34. package/dist/utils/mcp-logger.js +59 -0
  35. package/dist/utils/smithery-detector.d.ts +94 -0
  36. package/dist/utils/smithery-detector.js +292 -0
  37. package/dist/utils/startup-detector.d.ts +65 -0
  38. package/dist/utils/startup-detector.js +390 -0
  39. package/dist/utils/usageTracker.d.ts +85 -0
  40. package/dist/utils/usageTracker.js +280 -0
  41. package/dist/version.d.ts +1 -1
  42. package/dist/version.js +1 -1
  43. package/package.json +3 -1
package/dist/server.js CHANGED
@@ -1,12 +1,19 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
- import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ListPromptsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
2
+ import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ListPromptsRequestSchema, InitializeRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { zodToJsonSchema } from "zod-to-json-schema";
4
- // Shared constants for tool descriptions
5
- const PATH_GUIDANCE = `IMPORTANT: Always use absolute paths (starting with '/' or drive letter like 'C:\\') for reliability. Relative paths may fail as they depend on the current working directory. Tilde paths (~/...) might not work in all contexts. Unless the user explicitly asks for relative paths, use absolute paths.`;
4
+ import { getSystemInfo, getOSSpecificGuidance, getPathGuidance, getDevelopmentToolGuidance } from './utils/system-info.js';
5
+ // Get system information once at startup
6
+ const SYSTEM_INFO = getSystemInfo();
7
+ const OS_GUIDANCE = getOSSpecificGuidance(SYSTEM_INFO);
8
+ const DEV_TOOL_GUIDANCE = getDevelopmentToolGuidance(SYSTEM_INFO);
9
+ const PATH_GUIDANCE = `IMPORTANT: ${getPathGuidance(SYSTEM_INFO)} Relative paths may fail as they depend on the current working directory. Tilde paths (~/...) might not work in all contexts. Unless the user explicitly asks for relative paths, use absolute paths.`;
6
10
  const CMD_PREFIX_DESCRIPTION = `This command can be referenced as "DC: ..." or "use Desktop Commander to ..." in your instructions.`;
7
- import { ExecuteCommandArgsSchema, ReadOutputArgsSchema, ForceTerminateArgsSchema, ListSessionsArgsSchema, KillProcessArgsSchema, ReadFileArgsSchema, ReadMultipleFilesArgsSchema, WriteFileArgsSchema, CreateDirectoryArgsSchema, ListDirectoryArgsSchema, MoveFileArgsSchema, SearchFilesArgsSchema, GetFileInfoArgsSchema, SearchCodeArgsSchema, GetConfigArgsSchema, SetConfigValueArgsSchema, ListProcessesArgsSchema, EditBlockArgsSchema, } from './tools/schemas.js';
11
+ import { StartProcessArgsSchema, ReadProcessOutputArgsSchema, InteractWithProcessArgsSchema, ForceTerminateArgsSchema, ListSessionsArgsSchema, KillProcessArgsSchema, ReadFileArgsSchema, ReadMultipleFilesArgsSchema, WriteFileArgsSchema, CreateDirectoryArgsSchema, ListDirectoryArgsSchema, MoveFileArgsSchema, SearchFilesArgsSchema, GetFileInfoArgsSchema, SearchCodeArgsSchema, GetConfigArgsSchema, SetConfigValueArgsSchema, ListProcessesArgsSchema, EditBlockArgsSchema, GetUsageStatsArgsSchema, GiveFeedbackArgsSchema, } from './tools/schemas.js';
8
12
  import { getConfig, setConfigValue } from './tools/config.js';
13
+ import { getUsageStats } from './tools/usage.js';
14
+ import { giveFeedbackToDesktopCommander } from './tools/feedback.js';
9
15
  import { trackToolCall } from './utils/trackTools.js';
16
+ import { usageTracker } from './utils/usageTracker.js';
10
17
  import { VERSION } from './version.js';
11
18
  import { capture, capture_call_tool } from "./utils/capture.js";
12
19
  console.error("Loading server.ts");
@@ -34,6 +41,41 @@ server.setRequestHandler(ListPromptsRequestSchema, async () => {
34
41
  prompts: [],
35
42
  };
36
43
  });
44
+ // Store current client info (simple variable)
45
+ let currentClient = { name: 'uninitialized', version: 'uninitialized' };
46
+ // Add handler for initialization method - capture client info
47
+ server.setRequestHandler(InitializeRequestSchema, async (request) => {
48
+ try {
49
+ // Extract and store current client information
50
+ const clientInfo = request.params?.clientInfo;
51
+ if (clientInfo) {
52
+ currentClient = {
53
+ name: clientInfo.name || 'unknown',
54
+ version: clientInfo.version || 'unknown'
55
+ };
56
+ console.log(`Client connected: ${currentClient.name} v${currentClient.version}`);
57
+ }
58
+ // Return standard initialization response
59
+ return {
60
+ protocolVersion: "2024-11-05",
61
+ capabilities: {
62
+ tools: {},
63
+ resources: {},
64
+ prompts: {},
65
+ },
66
+ serverInfo: {
67
+ name: "desktop-commander",
68
+ version: VERSION,
69
+ },
70
+ };
71
+ }
72
+ catch (error) {
73
+ console.error("Error in initialization handler:", error);
74
+ throw error;
75
+ }
76
+ });
77
+ // Export current client info for access by other modules
78
+ export { currentClient };
37
79
  console.error("Setting up request handlers...");
38
80
  server.setRequestHandler(ListToolsRequestSchema, async () => {
39
81
  try {
@@ -51,7 +93,10 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
51
93
  - fileReadLineLimit (max lines for read_file, default 1000)
52
94
  - fileWriteLineLimit (max lines per write_file call, default 50)
53
95
  - telemetryEnabled (boolean for telemetry opt-in/out)
54
- - version (version of the DesktopCommander)
96
+ - currentClient (information about the currently connected MCP client)
97
+ - clientHistory (history of all clients that have connected)
98
+ - version (version of the DesktopCommander)
99
+ - systemInfo (operating system and environment details)
55
100
  ${CMD_PREFIX_DESCRIPTION}`,
56
101
  inputSchema: zodToJsonSchema(GetConfigArgsSchema),
57
102
  },
@@ -136,7 +181,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
136
181
  description: `
137
182
  Write or append to file contents.
138
183
 
139
- 🎯 CHUNKING IS STANDARD PRACTICE: Always write files in chunks of 25-30 lines maximum.
184
+ CHUNKING IS STANDARD PRACTICE: Always write files in chunks of 25-30 lines maximum.
140
185
  This is the normal, recommended way to write files - not an emergency measure.
141
186
 
142
187
  STANDARD PROCESS FOR ANY FILE:
@@ -144,7 +189,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
144
189
  2. THEN → write_file(filePath, secondChunk, {mode: 'append'}) [≤30 lines]
145
190
  3. CONTINUE → write_file(filePath, nextChunk, {mode: 'append'}) [≤30 lines]
146
191
 
147
- ⚠️ ALWAYS CHUNK PROACTIVELY - don't wait for performance warnings!
192
+ ALWAYS CHUNK PROACTIVELY - don't wait for performance warnings!
148
193
 
149
194
  WHEN TO CHUNK (always be proactive):
150
195
  1. Any file expected to be longer than 25-30 lines
@@ -292,27 +337,132 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
292
337
  },
293
338
  // Terminal tools
294
339
  {
295
- name: "execute_command",
340
+ name: "start_process",
341
+ description: `
342
+ Start a new terminal process with intelligent state detection.
343
+
344
+ PRIMARY TOOL FOR FILE ANALYSIS AND DATA PROCESSING
345
+ This is the ONLY correct tool for analyzing local files (CSV, JSON, logs, etc.).
346
+ The analysis tool CANNOT access local files and WILL FAIL - always use processes for file-based work.
347
+
348
+ CRITICAL RULE: For ANY local file work, ALWAYS use this tool + interact_with_process, NEVER use analysis/REPL tool.
349
+
350
+ ${OS_GUIDANCE}
351
+
352
+ REQUIRED WORKFLOW FOR LOCAL FILES:
353
+ 1. start_process("python3 -i") - Start Python REPL for data analysis
354
+ 2. interact_with_process(pid, "import pandas as pd, numpy as np")
355
+ 3. interact_with_process(pid, "df = pd.read_csv('/absolute/path/file.csv')")
356
+ 4. interact_with_process(pid, "print(df.describe())")
357
+ 5. Continue analysis with pandas, matplotlib, seaborn, etc.
358
+
359
+ COMMON FILE ANALYSIS PATTERNS:
360
+ • start_process("python3 -i") → Python REPL for data analysis (RECOMMENDED)
361
+ • start_process("node -i") → Node.js for JSON processing
362
+ • start_process("cut -d',' -f1 file.csv | sort | uniq -c") → Quick CSV analysis
363
+ • start_process("wc -l /path/file.csv") → Line counting
364
+ • start_process("head -10 /path/file.csv") → File preview
365
+
366
+ INTERACTIVE PROCESSES FOR DATA ANALYSIS:
367
+ 1. start_process("python3 -i") - Start Python REPL for data work
368
+ 2. start_process("node -i") - Start Node.js REPL for JSON/JS
369
+ 3. start_process("bash") - Start interactive bash shell
370
+ 4. Use interact_with_process() to send commands
371
+ 5. Use read_process_output() to get responses
372
+
373
+ SMART DETECTION:
374
+ - Detects REPL prompts (>>>, >, $, etc.)
375
+ - Identifies when process is waiting for input
376
+ - Recognizes process completion vs timeout
377
+ - Early exit prevents unnecessary waiting
378
+
379
+ STATES DETECTED:
380
+ Process waiting for input (shows prompt)
381
+ Process finished execution
382
+ Process running (use read_process_output)
383
+
384
+ ALWAYS USE FOR: Local file analysis, CSV processing, data exploration, system commands
385
+ NEVER USE ANALYSIS TOOL FOR: Local file access (analysis tool is browser-only and WILL FAIL)
386
+
387
+ ${PATH_GUIDANCE}
388
+ ${CMD_PREFIX_DESCRIPTION}`,
389
+ inputSchema: zodToJsonSchema(StartProcessArgsSchema),
390
+ },
391
+ {
392
+ name: "read_process_output",
296
393
  description: `
297
- Execute a terminal command with timeout.
394
+ Read output from a running process with intelligent completion detection.
298
395
 
299
- Command will continue running in background if it doesn't complete within timeout.
396
+ Automatically detects when process is ready for more input instead of timing out.
300
397
 
301
- NOTE: For file operations, prefer specialized tools like read_file, search_code,
302
- list_directory instead of cat, grep, or ls commands.
398
+ SMART FEATURES:
399
+ - Early exit when REPL shows prompt (>>>, >, etc.)
400
+ - Detects process completion vs still running
401
+ - Prevents hanging on interactive prompts
402
+ - Clear status messages about process state
403
+
404
+ REPL USAGE:
405
+ - Stops immediately when REPL prompt detected
406
+ - Shows clear status: waiting for input vs finished
407
+ - Shorter timeouts needed due to smart detection
408
+ - Works with Python, Node.js, R, Julia, etc.
409
+
410
+ DETECTION STATES:
411
+ Process waiting for input (ready for interact_with_process)
412
+ Process finished execution
413
+ Timeout reached (may still be running)
303
414
 
304
- ${PATH_GUIDANCE}
305
415
  ${CMD_PREFIX_DESCRIPTION}`,
306
- inputSchema: zodToJsonSchema(ExecuteCommandArgsSchema),
416
+ inputSchema: zodToJsonSchema(ReadProcessOutputArgsSchema),
307
417
  },
308
418
  {
309
- name: "read_output",
419
+ name: "interact_with_process",
310
420
  description: `
311
- Read new output from a running terminal session.
312
- Set timeout_ms for long running commands.
421
+ Send input to a running process and automatically receive the response.
422
+
423
+ CRITICAL: THIS IS THE PRIMARY TOOL FOR ALL LOCAL FILE ANALYSIS
424
+ For ANY local file analysis (CSV, JSON, data processing), ALWAYS use this instead of the analysis tool.
425
+ The analysis tool CANNOT access local files and WILL FAIL - use processes for ALL file-based work.
426
+
427
+ FILE ANALYSIS PRIORITY ORDER (MANDATORY):
428
+ 1. ALWAYS FIRST: Use this tool (start_process + interact_with_process) for local data analysis
429
+ 2. ALTERNATIVE: Use command-line tools (cut, awk, grep) for quick processing
430
+ 3. NEVER EVER: Use analysis tool for local file access (IT WILL FAIL)
431
+
432
+ REQUIRED INTERACTIVE WORKFLOW FOR FILE ANALYSIS:
433
+ 1. Start REPL: start_process("python3 -i")
434
+ 2. Load libraries: interact_with_process(pid, "import pandas as pd, numpy as np")
435
+ 3. Read file: interact_with_process(pid, "df = pd.read_csv('/absolute/path/file.csv')")
436
+ 4. Analyze: interact_with_process(pid, "print(df.describe())")
437
+ 5. Continue: interact_with_process(pid, "df.groupby('column').size()")
438
+
439
+ SMART DETECTION:
440
+ - Automatically waits for REPL prompt (>>>, >, etc.)
441
+ - Detects errors and completion states
442
+ - Early exit prevents timeout delays
443
+ - Clean output formatting (removes prompts)
444
+
445
+ SUPPORTED REPLs:
446
+ - Python: python3 -i (RECOMMENDED for data analysis)
447
+ - Node.js: node -i
448
+ - R: R
449
+ - Julia: julia
450
+ - Shell: bash, zsh
451
+ - Database: mysql, postgres
452
+
453
+ PARAMETERS:
454
+ - pid: Process ID from start_process
455
+ - input: Code/command to execute
456
+ - timeout_ms: Max wait (default: 8000ms)
457
+ - wait_for_prompt: Auto-wait for response (default: true)
458
+
459
+ Returns execution result with status indicators.
460
+
461
+ ALWAYS USE FOR: CSV analysis, JSON processing, file statistics, data visualization prep, ANY local file work
462
+ NEVER USE ANALYSIS TOOL FOR: Local file access (it cannot read files from disk and WILL FAIL)
313
463
 
314
464
  ${CMD_PREFIX_DESCRIPTION}`,
315
- inputSchema: zodToJsonSchema(ReadOutputArgsSchema),
465
+ inputSchema: zodToJsonSchema(InteractWithProcessArgsSchema),
316
466
  },
317
467
  {
318
468
  name: "force_terminate",
@@ -327,6 +477,16 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
327
477
  description: `
328
478
  List all active terminal sessions.
329
479
 
480
+ Shows session status including:
481
+ - PID: Process identifier
482
+ - Blocked: Whether session is waiting for input
483
+ - Runtime: How long the session has been running
484
+
485
+ DEBUGGING REPLs:
486
+ - "Blocked: true" often means REPL is waiting for input
487
+ - Use this to verify sessions are running before sending input
488
+ - Long runtime with blocked status may indicate stuck process
489
+
330
490
  ${CMD_PREFIX_DESCRIPTION}`,
331
491
  inputSchema: zodToJsonSchema(ListSessionsArgsSchema),
332
492
  },
@@ -350,6 +510,53 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
350
510
  ${CMD_PREFIX_DESCRIPTION}`,
351
511
  inputSchema: zodToJsonSchema(KillProcessArgsSchema),
352
512
  },
513
+ {
514
+ name: "get_usage_stats",
515
+ description: `
516
+ Get usage statistics for debugging and analysis.
517
+
518
+ Returns summary of tool usage, success/failure rates, and performance metrics.
519
+
520
+ ${CMD_PREFIX_DESCRIPTION}`,
521
+ inputSchema: zodToJsonSchema(GetUsageStatsArgsSchema),
522
+ },
523
+ {
524
+ name: "give_feedback_to_desktop_commander",
525
+ description: `
526
+ Open feedback form in browser to provide feedback about Desktop Commander.
527
+
528
+ IMPORTANT: This tool simply opens the feedback form - no pre-filling available.
529
+ The user will fill out the form manually in their browser.
530
+
531
+ WORKFLOW:
532
+ 1. When user agrees to give feedback, just call this tool immediately
533
+ 2. No need to ask questions or collect information
534
+ 3. Tool opens form with only usage statistics pre-filled automatically:
535
+ - tool_call_count: Number of commands they've made
536
+ - days_using: How many days they've used Desktop Commander
537
+ - platform: Their operating system (Mac/Windows/Linux)
538
+ - client_id: Analytics identifier
539
+
540
+ All survey questions will be answered directly in the form:
541
+ - Job title and technical comfort level
542
+ - Company URL for industry context
543
+ - Other AI tools they use
544
+ - Desktop Commander's biggest advantage
545
+ - How they typically use it
546
+ - Recommendation likelihood (0-10)
547
+ - User study participation interest
548
+ - Email and any additional feedback
549
+
550
+ EXAMPLE INTERACTION:
551
+ User: "sure, I'll give feedback"
552
+ Claude: "Perfect! Let me open the feedback form for you."
553
+ [calls tool immediately]
554
+
555
+ No parameters are needed - just call the tool to open the form.
556
+
557
+ ${CMD_PREFIX_DESCRIPTION}`,
558
+ inputSchema: zodToJsonSchema(GiveFeedbackArgsSchema),
559
+ },
353
560
  ],
354
561
  };
355
562
  }
@@ -360,83 +567,177 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
360
567
  });
361
568
  import * as handlers from './handlers/index.js';
362
569
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
570
+ const { name, arguments: args } = request.params;
363
571
  try {
364
- const { name, arguments: args } = request.params;
365
572
  capture_call_tool('server_call_tool', {
366
573
  name
367
574
  });
368
575
  // Track tool call
369
576
  trackToolCall(name, args);
370
577
  // Using a more structured approach with dedicated handlers
578
+ let result;
371
579
  switch (name) {
372
580
  // Config tools
373
581
  case "get_config":
374
582
  try {
375
- return await getConfig();
583
+ result = await getConfig();
376
584
  }
377
585
  catch (error) {
378
586
  capture('server_request_error', { message: `Error in get_config handler: ${error}` });
379
- return {
587
+ result = {
380
588
  content: [{ type: "text", text: `Error: Failed to get configuration` }],
381
589
  isError: true,
382
590
  };
383
591
  }
592
+ break;
384
593
  case "set_config_value":
385
594
  try {
386
- return await setConfigValue(args);
595
+ result = await setConfigValue(args);
387
596
  }
388
597
  catch (error) {
389
598
  capture('server_request_error', { message: `Error in set_config_value handler: ${error}` });
390
- return {
599
+ result = {
391
600
  content: [{ type: "text", text: `Error: Failed to set configuration value` }],
392
601
  isError: true,
393
602
  };
394
603
  }
604
+ break;
605
+ case "get_usage_stats":
606
+ try {
607
+ result = await getUsageStats();
608
+ }
609
+ catch (error) {
610
+ capture('server_request_error', { message: `Error in get_usage_stats handler: ${error}` });
611
+ result = {
612
+ content: [{ type: "text", text: `Error: Failed to get usage statistics` }],
613
+ isError: true,
614
+ };
615
+ }
616
+ break;
617
+ case "give_feedback_to_desktop_commander":
618
+ try {
619
+ result = await giveFeedbackToDesktopCommander(args);
620
+ }
621
+ catch (error) {
622
+ capture('server_request_error', { message: `Error in give_feedback_to_desktop_commander handler: ${error}` });
623
+ result = {
624
+ content: [{ type: "text", text: `Error: Failed to open feedback form` }],
625
+ isError: true,
626
+ };
627
+ }
628
+ break;
395
629
  // Terminal tools
396
- case "execute_command":
397
- return await handlers.handleExecuteCommand(args);
398
- case "read_output":
399
- return await handlers.handleReadOutput(args);
630
+ case "start_process":
631
+ result = await handlers.handleStartProcess(args);
632
+ break;
633
+ case "read_process_output":
634
+ result = await handlers.handleReadProcessOutput(args);
635
+ break;
636
+ case "interact_with_process":
637
+ result = await handlers.handleInteractWithProcess(args);
638
+ break;
400
639
  case "force_terminate":
401
- return await handlers.handleForceTerminate(args);
640
+ result = await handlers.handleForceTerminate(args);
641
+ break;
402
642
  case "list_sessions":
403
- return await handlers.handleListSessions();
643
+ result = await handlers.handleListSessions();
644
+ break;
404
645
  // Process tools
405
646
  case "list_processes":
406
- return await handlers.handleListProcesses();
647
+ result = await handlers.handleListProcesses();
648
+ break;
407
649
  case "kill_process":
408
- return await handlers.handleKillProcess(args);
650
+ result = await handlers.handleKillProcess(args);
651
+ break;
652
+ // Note: REPL functionality removed in favor of using general terminal commands
409
653
  // Filesystem tools
410
654
  case "read_file":
411
- return await handlers.handleReadFile(args);
655
+ result = await handlers.handleReadFile(args);
656
+ break;
412
657
  case "read_multiple_files":
413
- return await handlers.handleReadMultipleFiles(args);
658
+ result = await handlers.handleReadMultipleFiles(args);
659
+ break;
414
660
  case "write_file":
415
- return await handlers.handleWriteFile(args);
661
+ result = await handlers.handleWriteFile(args);
662
+ break;
416
663
  case "create_directory":
417
- return await handlers.handleCreateDirectory(args);
664
+ result = await handlers.handleCreateDirectory(args);
665
+ break;
418
666
  case "list_directory":
419
- return await handlers.handleListDirectory(args);
667
+ result = await handlers.handleListDirectory(args);
668
+ break;
420
669
  case "move_file":
421
- return await handlers.handleMoveFile(args);
670
+ result = await handlers.handleMoveFile(args);
671
+ break;
422
672
  case "search_files":
423
- return await handlers.handleSearchFiles(args);
673
+ result = await handlers.handleSearchFiles(args);
674
+ break;
424
675
  case "search_code":
425
- return await handlers.handleSearchCode(args);
676
+ result = await handlers.handleSearchCode(args);
677
+ break;
426
678
  case "get_file_info":
427
- return await handlers.handleGetFileInfo(args);
679
+ result = await handlers.handleGetFileInfo(args);
680
+ break;
428
681
  case "edit_block":
429
- return await handlers.handleEditBlock(args);
682
+ result = await handlers.handleEditBlock(args);
683
+ break;
430
684
  default:
431
685
  capture('server_unknown_tool', { name });
432
- return {
686
+ result = {
433
687
  content: [{ type: "text", text: `Error: Unknown tool: ${name}` }],
434
688
  isError: true,
435
689
  };
436
690
  }
691
+ // Track success or failure based on result
692
+ if (result.isError) {
693
+ await usageTracker.trackFailure(name);
694
+ console.log(`[FEEDBACK DEBUG] Tool ${name} failed, not checking feedback`);
695
+ }
696
+ else {
697
+ await usageTracker.trackSuccess(name);
698
+ console.log(`[FEEDBACK DEBUG] Tool ${name} succeeded, checking feedback...`);
699
+ // Check if should prompt for feedback (only on successful operations)
700
+ const shouldPrompt = await usageTracker.shouldPromptForFeedback();
701
+ console.log(`[FEEDBACK DEBUG] Should prompt for feedback: ${shouldPrompt}`);
702
+ if (shouldPrompt) {
703
+ console.log(`[FEEDBACK DEBUG] Generating feedback message...`);
704
+ const feedbackResult = await usageTracker.getFeedbackPromptMessage();
705
+ console.log(`[FEEDBACK DEBUG] Generated variant: ${feedbackResult.variant}`);
706
+ // Capture feedback prompt injection event
707
+ const stats = await usageTracker.getStats();
708
+ await capture('feedback_prompt_injected', {
709
+ trigger_tool: name,
710
+ total_calls: stats.totalToolCalls,
711
+ successful_calls: stats.successfulCalls,
712
+ failed_calls: stats.failedCalls,
713
+ days_since_first_use: Math.floor((Date.now() - stats.firstUsed) / (1000 * 60 * 60 * 24)),
714
+ total_sessions: stats.totalSessions,
715
+ message_variant: feedbackResult.variant
716
+ });
717
+ // Inject feedback instruction for the LLM
718
+ if (result.content && result.content.length > 0 && result.content[0].type === "text") {
719
+ const currentContent = result.content[0].text || '';
720
+ result.content[0].text = `${currentContent}${feedbackResult.message}`;
721
+ }
722
+ else {
723
+ result.content = [
724
+ ...(result.content || []),
725
+ {
726
+ type: "text",
727
+ text: feedbackResult.message
728
+ }
729
+ ];
730
+ }
731
+ // Mark that we've prompted (to prevent spam)
732
+ await usageTracker.markFeedbackPrompted();
733
+ }
734
+ }
735
+ return result;
437
736
  }
438
737
  catch (error) {
439
738
  const errorMessage = error instanceof Error ? error.message : String(error);
739
+ // Track the failure
740
+ await usageTracker.trackFailure(name);
440
741
  capture('server_request_error', {
441
742
  error: errorMessage
442
743
  });
@@ -9,6 +9,13 @@ interface CompletedSession {
9
9
  export declare class TerminalManager {
10
10
  private sessions;
11
11
  private completedSessions;
12
+ /**
13
+ * Send input to a running process
14
+ * @param pid Process ID
15
+ * @param input Text to send to the process
16
+ * @returns Whether input was successfully sent
17
+ */
18
+ sendInputToProcess(pid: number, input: string): boolean;
12
19
  executeCommand(command: string, timeoutMs?: number, shell?: string): Promise<CommandExecutionResult>;
13
20
  getNewOutput(pid: number): string | null;
14
21
  /**