@wonderwhy-er/desktop-commander 0.2.51 → 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 (117) hide show
  1. package/README.md +14 -24
  2. package/dist/command-manager.d.ts +7 -2
  3. package/dist/command-manager.js +16 -11
  4. package/dist/config-manager.d.ts +49 -3
  5. package/dist/config-manager.js +329 -87
  6. package/dist/config-recovery.d.ts +28 -0
  7. package/dist/config-recovery.js +81 -0
  8. package/dist/config.d.ts +1 -0
  9. package/dist/config.js +9 -0
  10. package/dist/handlers/filesystem-handlers.d.ts +1 -1
  11. package/dist/handlers/filesystem-handlers.js +26 -16
  12. package/dist/handlers/search-answers.d.ts +58 -0
  13. package/dist/handlers/search-answers.js +172 -0
  14. package/dist/handlers/search-handlers.js +4 -92
  15. package/dist/index.js +14 -7
  16. package/dist/npm-scripts/remote.js +32 -4
  17. package/dist/remote-device/broadcast-analytics.d.ts +28 -0
  18. package/dist/remote-device/broadcast-analytics.js +41 -0
  19. package/dist/remote-device/desktop-commander-integration.d.ts +20 -0
  20. package/dist/remote-device/desktop-commander-integration.js +121 -40
  21. package/dist/remote-device/device-authenticator.d.ts +13 -1
  22. package/dist/remote-device/device-authenticator.js +87 -47
  23. package/dist/remote-device/device.d.ts +14 -0
  24. package/dist/remote-device/device.js +244 -51
  25. package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
  26. package/dist/remote-device/mqtt-enrollment.js +162 -0
  27. package/dist/remote-device/mqtt-transport.d.ts +44 -0
  28. package/dist/remote-device/mqtt-transport.js +197 -0
  29. package/dist/remote-device/remote-channel.d.ts +64 -3
  30. package/dist/remote-device/remote-channel.js +317 -48
  31. package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
  32. package/dist/remote-device/transport-analytics.d.ts +29 -0
  33. package/dist/remote-device/transport-analytics.js +44 -0
  34. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  35. package/dist/remote-device/transport-telemetry.js +48 -0
  36. package/dist/search-manager.d.ts +239 -27
  37. package/dist/search-manager.js +746 -312
  38. package/dist/server.js +77 -92
  39. package/dist/terminal-manager.d.ts +138 -21
  40. package/dist/terminal-manager.js +300 -215
  41. package/dist/tools/config.d.ts +1 -1
  42. package/dist/tools/config.js +21 -70
  43. package/dist/tools/edit.js +12 -4
  44. package/dist/tools/filesystem.d.ts +30 -6
  45. package/dist/tools/filesystem.js +246 -140
  46. package/dist/tools/improved-process-tools.d.ts +9 -3
  47. package/dist/tools/improved-process-tools.js +171 -68
  48. package/dist/tools/pdf/extract-images.d.ts +2 -0
  49. package/dist/tools/pdf/extract-images.js +4 -1
  50. package/dist/tools/pdf/index.d.ts +5 -3
  51. package/dist/tools/pdf/index.js +4 -3
  52. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  53. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  54. package/dist/tools/pdf/manipulations.d.ts +12 -1
  55. package/dist/tools/pdf/manipulations.js +17 -4
  56. package/dist/tools/pdf/markdown.d.ts +96 -0
  57. package/dist/tools/pdf/markdown.js +485 -20
  58. package/dist/tools/pdf/utils.d.ts +2 -2
  59. package/dist/tools/pdf/utils.js +4 -4
  60. package/dist/tools/process.js +8 -5
  61. package/dist/tools/schemas.d.ts +1 -1
  62. package/dist/tools/schemas.js +15 -6
  63. package/dist/tools/search.d.ts +32 -0
  64. package/dist/tools/search.js +202 -0
  65. package/dist/types.d.ts +1 -1
  66. package/dist/ui/config-editor/config-editor-runtime.js +6 -6
  67. package/dist/ui/config-editor/src/app.js +2 -15
  68. package/dist/utils/ab-test.js +27 -9
  69. package/dist/utils/atomic-write.d.ts +14 -0
  70. package/dist/utils/atomic-write.js +80 -0
  71. package/dist/utils/capture.d.ts +17 -1
  72. package/dist/utils/capture.js +177 -68
  73. package/dist/utils/exit-process.d.ts +24 -0
  74. package/dist/utils/exit-process.js +31 -0
  75. package/dist/utils/feature-flags.js +2 -1
  76. package/dist/utils/files/base.d.ts +3 -1
  77. package/dist/utils/files/docx.d.ts +3 -0
  78. package/dist/utils/files/docx.js +24 -9
  79. package/dist/utils/files/excel.d.ts +10 -0
  80. package/dist/utils/files/excel.js +93 -33
  81. package/dist/utils/files/factory.d.ts +22 -1
  82. package/dist/utils/files/factory.js +59 -4
  83. package/dist/utils/files/image.d.ts +12 -4
  84. package/dist/utils/files/image.js +19 -8
  85. package/dist/utils/files/index.d.ts +5 -3
  86. package/dist/utils/files/index.js +4 -3
  87. package/dist/utils/files/pdf.js +18 -36
  88. package/dist/utils/files/text.d.ts +21 -5
  89. package/dist/utils/files/text.js +90 -86
  90. package/dist/utils/internal-facts.d.ts +3 -0
  91. package/dist/utils/internal-facts.js +23 -0
  92. package/dist/utils/lazy-package.d.ts +23 -0
  93. package/dist/utils/lazy-package.js +42 -0
  94. package/dist/utils/open-browser.js +2 -1
  95. package/dist/utils/process-detection.d.ts +24 -5
  96. package/dist/utils/process-detection.js +199 -89
  97. package/dist/utils/process-tree.d.ts +14 -0
  98. package/dist/utils/process-tree.js +223 -0
  99. package/dist/utils/rename.d.ts +9 -0
  100. package/dist/utils/rename.js +74 -0
  101. package/dist/utils/ripgrep-resolver.js +9 -14
  102. package/dist/utils/shell.d.ts +42 -0
  103. package/dist/utils/shell.js +187 -0
  104. package/dist/utils/system-info.js +9 -7
  105. package/dist/utils/trackTools.js +2 -1
  106. package/dist/version.d.ts +1 -1
  107. package/dist/version.js +1 -1
  108. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  109. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  110. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  111. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  112. package/package.json +8 -2
  113. package/vendor/telemetry-contract/README.md +56 -0
  114. package/vendor/telemetry-contract/package.json +32 -0
  115. package/vendor/telemetry-contract/transport.d.ts +38 -0
  116. package/vendor/telemetry-contract/transport.js +164 -0
  117. package/vendor/telemetry-contract/transport.test.js +39 -0
package/dist/server.js CHANGED
@@ -21,7 +21,7 @@ import { processDockerPrompt } from './utils/dockerPrompt.js';
21
21
  import { toolHistory } from './utils/toolHistory.js';
22
22
  import { handleWelcomePageOnboarding, skipWelcomePageOnboarding } from './utils/welcome-onboarding.js';
23
23
  import { VERSION } from './version.js';
24
- import { capture, capture_call_tool, runInUiOriginCallContext } from "./utils/capture.js";
24
+ import { addToolCallPaths, capture, capture_call_tool, runInUiOriginCallContext, runWithToolCallPaths } from "./utils/capture.js";
25
25
  import { logToStderr, logger } from './utils/logger.js';
26
26
  import { buildUiToolMeta, CONFIG_EDITOR_RESOURCE_URI, FILE_PREVIEW_RESOURCE_URI, } from './ui/contracts.js';
27
27
  import { listUiResources, readUiResource } from './ui/resources.js';
@@ -278,7 +278,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
278
278
  Read contents from files and URLs.
279
279
  Read PDF files and extract content as markdown and images.
280
280
 
281
- Prefer this over 'execute_command' with cat/type for viewing files.
281
+ Suitable for reading authorized local files directly without starting a shell command.
282
282
 
283
283
  Supports partial file reading with:
284
284
  - 'offset' (start line, default: 0)
@@ -790,47 +790,27 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
790
790
  {
791
791
  name: "start_process",
792
792
  description: `
793
- Start a new terminal process with intelligent state detection.
793
+ Start a terminal process on the authorized device with intelligent state detection.
794
794
 
795
- PRIMARY TOOL FOR FILE ANALYSIS AND DATA PROCESSING
796
- This is the ONLY correct tool for analyzing local files (CSV, JSON, logs, etc.).
797
- The analysis tool CANNOT access local files and WILL FAIL - always use processes for file-based work.
798
-
799
- CRITICAL RULE: For ANY local file work, ALWAYS use this tool + interact_with_process, NEVER use analysis/REPL tool.
795
+ Suitable for shell commands, interactive REPL sessions, data-processing scripts,
796
+ programmatic file analysis, and other long-running terminal work.
800
797
 
801
798
  ${OS_GUIDANCE}
802
799
 
803
- REQUIRED WORKFLOW FOR LOCAL FILES:
804
- 1. start_process("python3 -i") - Start Python REPL for data analysis
805
- 2. interact_with_process(pid, "import pandas as pd, numpy as np")
806
- 3. interact_with_process(pid, "df = pd.read_csv('/absolute/path/file.csv')")
807
- 4. interact_with_process(pid, "print(df.describe())")
808
- 5. Continue analysis with pandas, matplotlib, seaborn, etc.
809
-
810
- COMMON FILE ANALYSIS PATTERNS:
811
- • start_process("python3 -i") → Python REPL for data analysis (RECOMMENDED)
812
- • start_process("node -i") → Node.js REPL for JSON processing
813
- • start_process("node:local") → Node.js on MCP server (stateless, ES imports, all code in one call)
814
- • start_process("cut -d',' -f1 file.csv | sort | uniq -c") → Quick CSV analysis
815
- • start_process("wc -l /path/file.csv") → Line counting
816
- • start_process("head -10 /path/file.csv") → File preview
817
-
818
- BINARY FILE SUPPORT:
819
- For PDF, Excel, Word, archives, databases, and other binary formats, use process tools with appropriate libraries or command-line utilities.
820
-
821
- INTERACTIVE PROCESSES FOR DATA ANALYSIS:
822
- For code/calculations, use in this priority order:
823
- 1. start_process("python3 -i") - Python REPL (preferred)
824
- 2. start_process("node -i") - Node.js REPL (when Python unavailable)
825
- 3. start_process("node:local") - Node.js fallback (when node -i fails)
826
- 4. Use interact_with_process() to send commands
827
- 5. Use read_process_output() to get responses
828
- When Python is unavailable, prefer Node.js over shell for calculations.
829
- Node.js: Always use ES import syntax (import x from 'y'), not require().
800
+ Examples:
801
+ • start_process("python3 -i") → Start an interactive Python REPL
802
+ • start_process("node -i") → Start an interactive Node.js REPL
803
+ • start_process("node:local") → Run stateless Node.js code on the MCP server
804
+ • start_process("wc -l /path/file.csv") → Run a one-shot shell command
805
+
806
+ Interactive process sessions support follow-up input after they are started.
807
+ Long-running process sessions expose newly available output while they remain active.
808
+ Binary files can be processed with appropriate command-line tools or libraries available
809
+ in the selected process environment.
830
810
 
831
811
  SMART DETECTION:
832
812
  - Detects REPL prompts (>>>, >, $, etc.)
833
- - Identifies when process is waiting for input
813
+ - Identifies when a process is waiting for input
834
814
  - Recognizes process completion vs timeout
835
815
  - Early exit prevents unnecessary waiting
836
816
 
@@ -845,10 +825,6 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
845
825
  - Total duration and time to first output
846
826
  - Complete timeline of all output events with timestamps
847
827
  - Which detection mechanism triggered early exit
848
- Use this to identify missed optimization opportunities and improve detection patterns.
849
-
850
- ALWAYS USE FOR: Local file analysis, CSV processing, data exploration, system commands
851
- NEVER USE ANALYSIS TOOL FOR: Local file access (analysis tool is browser-only and WILL FAIL)
852
828
 
853
829
  ${PATH_GUIDANCE}
854
830
  ${CMD_PREFIX_DESCRIPTION}`,
@@ -904,60 +880,36 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
904
880
  {
905
881
  name: "interact_with_process",
906
882
  description: `
907
- Send input to a running process and automatically receive the response.
908
-
909
- CRITICAL: THIS IS THE PRIMARY TOOL FOR ALL LOCAL FILE ANALYSIS
910
- For ANY local file analysis (CSV, JSON, data processing), ALWAYS use this instead of the analysis tool.
911
- The analysis tool CANNOT access local files and WILL FAIL - use processes for ALL file-based work.
883
+ Send input to an existing terminal or REPL process and return newly available output.
912
884
 
913
- FILE ANALYSIS PRIORITY ORDER (MANDATORY):
914
- 1. ALWAYS FIRST: Use this tool (start_process + interact_with_process) for local data analysis
915
- 2. ALTERNATIVE: Use command-line tools (cut, awk, grep) for quick processing
916
- 3. NEVER EVER: Use analysis tool for local file access (IT WILL FAIL)
885
+ Useful for interactive shells, Python/Node/R/Julia REPLs, database consoles,
886
+ and long-running commands started with start_process().
917
887
 
918
- REQUIRED INTERACTIVE WORKFLOW FOR FILE ANALYSIS:
919
- 1. Start REPL: start_process("python3 -i")
920
- 2. Load libraries: interact_with_process(pid, "import pandas as pd, numpy as np")
921
- 3. Read file: interact_with_process(pid, "df = pd.read_csv('/absolute/path/file.csv')")
922
- 4. Analyze: interact_with_process(pid, "print(df.describe())")
923
- 5. Continue: interact_with_process(pid, "df.groupby('column').size()")
924
-
925
- BINARY FILE PROCESSING WORKFLOWS:
926
- Use appropriate Python libraries (PyPDF2, pandas, docx2txt, etc.) or command-line tools for binary file analysis.
888
+ Examples:
889
+ - Interactive Python REPL sessions can be started with \`python3 -i\`.
890
+ - Existing interactive sessions accept additional input such as imports or analysis commands.
891
+ - Interactive sessions can return newly available output while they remain active.
927
892
 
928
893
  SMART DETECTION:
929
- - Automatically waits for REPL prompt (>>>, >, etc.)
894
+ - Automatically waits for a recognized prompt when requested
930
895
  - Detects errors and completion states
931
- - Early exit prevents timeout delays
932
- - Clean output formatting (removes prompts)
933
-
934
- SUPPORTED REPLs:
935
- - Python: python3 -i (RECOMMENDED for data analysis)
936
- - Node.js: node -i
937
- - R: R
938
- - Julia: julia
939
- - Shell: bash, zsh
940
- - Database: mysql, postgres
896
+ - Early exit prevents unnecessary waiting
897
+ - Cleans common REPL prompt text from returned output
941
898
 
942
899
  PARAMETERS:
943
- - pid: Process ID from start_process
944
- - input: Code/command to execute
945
- - timeout_ms: Max wait (default: 8000ms)
946
- - wait_for_prompt: Auto-wait for response (default: true)
947
- - verbose_timing: Enable detailed performance telemetry (default: false)
900
+ - pid: Process ID returned by start_process
901
+ - input: Text or command to send to the process
902
+ - timeout_ms: Maximum wait time (default: 8000ms)
903
+ - wait_for_prompt: Whether to wait for a prompt before returning (default: true)
904
+ - verbose_timing: Include detailed timing telemetry (default: false)
948
905
 
949
906
  Returns execution result with status indicators.
950
907
 
951
908
  PERFORMANCE DEBUGGING (verbose_timing parameter):
952
- Set verbose_timing: true to get detailed timing information including:
953
- - Exit reason (early_exit_quick_pattern, early_exit_periodic_check, process_finished, timeout, no_wait)
909
+ When enabled, detailed timing includes:
910
+ - Exit reason
954
911
  - Total duration and time to first output
955
- - Complete timeline of all output events with timestamps
956
- - Which detection mechanism triggered early exit
957
- Use this to identify slow interactions and optimize detection patterns.
958
-
959
- ALWAYS USE FOR: CSV analysis, JSON processing, file statistics, data visualization prep, ANY local file work
960
- NEVER USE ANALYSIS TOOL FOR: Local file access (it cannot read files from disk and WILL FAIL)
912
+ - Timeline of output events
961
913
 
962
914
  ${CMD_PREFIX_DESCRIPTION}`,
963
915
  inputSchema: zodToJsonSchema(InteractWithProcessArgsSchema),
@@ -1158,6 +1110,19 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
1158
1110
  }
1159
1111
  });
1160
1112
  import * as handlers from './handlers/index.js';
1113
+ import { withoutInternalFacts } from './utils/internal-facts.js';
1114
+ import { stillLoadingError } from './utils/files/index.js';
1115
+ /**
1116
+ * A tool call on an Excel, DOCX or PDF file whose package is still loading
1117
+ * after initialize answers at once with this error (utils/files/factory.ts)
1118
+ * instead of loading it inside the call. Not sent to telemetry, unlike other
1119
+ * errors: it names the file. read_multiple_files answers per file;
1120
+ * get_file_info waits for the load, or loads it itself, and so does a search.
1121
+ */
1122
+ function stillLoading(filePath, action, options) {
1123
+ const error = typeof filePath === 'string' ? stillLoadingError(filePath, action, options) : undefined;
1124
+ return error === undefined ? undefined : { content: [{ type: 'text', text: `Error: ${error}` }], isError: true };
1125
+ }
1161
1126
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
1162
1127
  const args = request.params.arguments;
1163
1128
  // Calls fired programmatically by the widget UIs (file preview, config
@@ -1167,11 +1132,24 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1167
1132
  // (server_call_tool, server_read_file, server_edit_block, ...). Deliberate
1168
1133
  // UI interactions are tracked separately via mcp_ui_event.
1169
1134
  const isUiOriginCall = !!(args && typeof args === 'object' && args.origin === 'ui');
1170
- if (isUiOriginCall) {
1171
- return runInUiOriginCallContext(() => handleCallToolRequest(request));
1172
- }
1173
- return handleCallToolRequest(request);
1135
+ // Each call keeps the paths it works on, starting with its path arguments,
1136
+ // so telemetry can replace them whole in any error text the call produces
1137
+ return runWithToolCallPaths(() => {
1138
+ addToolCallPaths(...pathArguments(args));
1139
+ if (isUiOriginCall) {
1140
+ return runInUiOriginCallContext(() => handleCallToolRequest(request));
1141
+ }
1142
+ return handleCallToolRequest(request);
1143
+ });
1174
1144
  });
1145
+ /** The values of the tool arguments that hold paths (path, paths, file_path, outputPath, source, destination, shell, ...). */
1146
+ function pathArguments(args) {
1147
+ if (!args || typeof args !== 'object')
1148
+ return [];
1149
+ return Object.entries(args)
1150
+ .filter(([key]) => /path/i.test(key) || key === 'source' || key === 'destination' || key === 'shell')
1151
+ .map(([, value]) => value);
1152
+ }
1175
1153
  async function handleCallToolRequest(request) {
1176
1154
  const { name, arguments: args } = request.params;
1177
1155
  const startTime = Date.now();
@@ -1372,17 +1350,22 @@ async function handleCallToolRequest(request) {
1372
1350
  // Note: REPL functionality removed in favor of using general terminal commands
1373
1351
  // Filesystem tools
1374
1352
  case "read_file":
1375
- result = await handlers.handleReadFile(args);
1353
+ result = stillLoading(args?.path, 'read', { isUrl: args?.isUrl === true }) ?? await handlers.handleReadFile(args);
1376
1354
  break;
1377
1355
  case "read_multiple_files":
1378
- result = await handlers.handleReadMultipleFiles(args);
1356
+ result = await handlers.handleReadMultipleFiles(args, (filePath) => stillLoadingError(filePath, 'read'));
1379
1357
  break;
1380
1358
  case "write_file":
1381
- result = await handlers.handleWriteFile(args);
1359
+ result = stillLoading(args?.path, 'write') ?? await handlers.handleWriteFile(args);
1382
1360
  break;
1383
- case "write_pdf":
1384
- result = await handlers.handleWritePdf(args);
1361
+ case "write_pdf": {
1362
+ // Markdown (a new PDF) or page edits, read as the tool reads them;
1363
+ // arguments the tool refuses get its own error
1364
+ const parsed = WritePdfArgsSchema.safeParse(args);
1365
+ const action = parsed.success && typeof parsed.data.content === 'string' ? 'write' : 'edit';
1366
+ result = (parsed.success ? stillLoading(parsed.data.path, action, { isPdf: true }) : undefined) ?? await handlers.handleWritePdf(args);
1385
1367
  break;
1368
+ }
1386
1369
  case "create_directory":
1387
1370
  result = await handlers.handleCreateDirectory(args);
1388
1371
  break;
@@ -1408,7 +1391,7 @@ async function handleCallToolRequest(request) {
1408
1391
  result = await handlers.handleGetFileInfo(args);
1409
1392
  break;
1410
1393
  case "edit_block":
1411
- result = await handlers.handleEditBlock(args);
1394
+ result = stillLoading(args?.file_path, 'edit') ?? await handlers.handleEditBlock(args);
1412
1395
  break;
1413
1396
  default:
1414
1397
  capture('server_unknown_tool', { name });
@@ -1417,6 +1400,8 @@ async function handleCallToolRequest(request) {
1417
1400
  isError: true,
1418
1401
  };
1419
1402
  }
1403
+ // What the client receives (and the history records): facts kept internal are dropped
1404
+ result = withoutInternalFacts(name, result);
1420
1405
  // Add tool call to history (exclude only get_recent_tool_calls to prevent recursion)
1421
1406
  const duration = Date.now() - startTime;
1422
1407
  isError = !!result.isError;
@@ -1,20 +1,68 @@
1
1
  import { TerminalSession, CommandExecutionResult, ActiveSession } from './types.js';
2
+ import { type ProcessState } from './utils/process-detection.js';
3
+ /** A child process's output pipes. */
4
+ type OutputStream = 'stdout' | 'stderr';
5
+ /** The end of one output pipe, kept for process-state detection (see getProcessState). */
6
+ interface StreamTail {
7
+ text: string;
8
+ chars: number;
9
+ turn: number;
10
+ }
11
+ type StreamTails = Record<OutputStream, StreamTail>;
12
+ /** An active session plus the per-stream tails that state detection reads. */
13
+ interface ManagedSession extends TerminalSession {
14
+ streams: StreamTails;
15
+ termination?: Promise<boolean>;
16
+ }
17
+ /** Outcome of forceTerminate */
18
+ export type TerminateOutcome = 'terminated' | 'failed' | 'not_found';
2
19
  interface CompletedSession {
3
- pid: number;
4
- outputLines: string[];
20
+ session: ManagedSession;
5
21
  exitCode: number | null;
6
- startTime: Date;
22
+ signal: NodeJS.Signals | null;
7
23
  endTime: Date;
8
- evictedLines: number;
9
- evictedChars: number;
24
+ }
25
+ /**
26
+ * A position in a session's output, absolute since process start (evicted
27
+ * output included), so it stays valid while the buffer cap evicts lines.
28
+ */
29
+ export interface OutputSnapshot {
30
+ totalChars: number;
31
+ lineCount: number;
32
+ streamChars: Record<OutputStream, number>;
33
+ }
34
+ /**
35
+ * Ceiling for a single blocking process wait (start_process's initial wait,
36
+ * interact_with_process, read_process_output). The wait is otherwise bounded
37
+ * only by the caller's timeout_ms, and MCP clients abandon a tool call after
38
+ * ~4 minutes (Claude Desktop: "No result received ... after 4 minutes"), so a
39
+ * large timeout_ms on a long, prompt-less command used to outlive the client.
40
+ * The ceiling is MAX_PROCESS_WAIT_MS; callers other than the tools (tests) may
41
+ * pass a smaller one.
42
+ */
43
+ export interface ProcessWaitLimit {
44
+ waitMs: number;
45
+ capMs: number;
46
+ capped: boolean;
47
+ }
48
+ /**
49
+ * The one place that turns a caller's timeout_ms into the time a process wait
50
+ * may actually block. When `capped`, the call returns at the ceiling with the
51
+ * process still running and the caller continues with read_process_output.
52
+ */
53
+ export declare function getProcessWaitLimit(timeoutMs: number, capMs?: number): ProcessWaitLimit;
54
+ /** executeCommand result: CommandExecutionResult plus the process state and whether the wait ceiling ended the wait. */
55
+ export interface ProcessStartResult extends CommandExecutionResult {
56
+ processState: ProcessState;
57
+ waitCappedAtMs?: number;
10
58
  }
11
59
  /**
12
60
  * Output buffering caps. Without a cap, a process emitting enough output makes
13
61
  * string concatenation throw "RangeError: Invalid string length" at V8's max
14
62
  * string size (~536M chars) inside a stdout 'data' handler — an uncaught
15
63
  * exception that kills the whole server (index.ts exits on uncaughtException).
16
- * The cap also bounds the join() cost in snapshot reads and the periodic
17
- * process-state scan, both of which are O(total output).
64
+ * The cap also bounds the cost of the reads that are O(total output), such as
65
+ * since-start snapshot reads.
18
66
  */
19
67
  export declare const MAX_BUFFERED_OUTPUT_CHARS: number;
20
68
  export interface PaginatedOutputResult {
@@ -25,12 +73,15 @@ export interface PaginatedOutputResult {
25
73
  remaining: number;
26
74
  isComplete: boolean;
27
75
  exitCode?: number | null;
76
+ signal?: NodeJS.Signals | null;
28
77
  runtimeMs?: number;
29
78
  evictedLines?: number;
30
79
  }
31
80
  export declare class TerminalManager {
32
81
  private sessions;
33
82
  private completedSessions;
83
+ private deliveryTurn;
84
+ private deliveryTurnOpen;
34
85
  /**
35
86
  * Send input to a running process
36
87
  * @param pid Process ID
@@ -38,7 +89,23 @@ export declare class TerminalManager {
38
89
  * @returns Whether input was successfully sent
39
90
  */
40
91
  sendInputToProcess(pid: number, input: string): boolean;
41
- executeCommand(command: string, timeoutMs?: number, shell?: string, collectTiming?: boolean): Promise<CommandExecutionResult>;
92
+ executeCommand(command: string, timeoutMs?: number, shell?: string, collectTiming?: boolean, maxWaitMs?: number): Promise<ProcessStartResult>;
93
+ /**
94
+ * Add a chunk of one stream's output to the session: to the merged line
95
+ * buffer, and to that stream's tail for state detection.
96
+ */
97
+ private recordOutput;
98
+ /**
99
+ * Number of the event-loop turn now delivering output; every chunk
100
+ * dispatched before the next check phase (setImmediate) shares it.
101
+ *
102
+ * stdout and stderr are separate pipes. Each turn delivers what the OS had
103
+ * ready when the loop polled, so a chunk delivered in a later turn was
104
+ * written after the chunks of earlier turns. Within one turn the pipes come
105
+ * in either order: when python -i's final stdout newline and its stderr
106
+ * ">>> " prompt are both waiting, the prompt is often delivered first.
107
+ */
108
+ private currentDeliveryTurn;
42
109
  /**
43
110
  * Append text to a session's line buffer
44
111
  * Handles partial lines and newline splitting
@@ -53,7 +120,21 @@ export declare class TerminalManager {
53
120
  */
54
121
  readOutputPaginated(pid: number, offset?: number, length?: number): PaginatedOutputResult | null;
55
122
  /**
56
- * Internal helper to read from a line buffer with offset/length
123
+ * Whether a default read (offset 0) has anything to return: complete lines
124
+ * past the read position, or an unfinished last line with text a read
125
+ * hasn't returned (see readFromLineBuffer). Line counts alone can't tell
126
+ * the second: text appended to that line adds no line.
127
+ */
128
+ hasUnreadOutput(pid: number): boolean;
129
+ /**
130
+ * Whether the unfinished last line has text that a default read hasn't
131
+ * returned. Empty, it has nothing to return. Its text is compared with what
132
+ * a read last returned only while it is the line that read stopped at: a
133
+ * later line is new even when its text is the same (a REPL's next ">>> ").
134
+ */
135
+ private static openLineHasNewText;
136
+ /**
137
+ * Internal helper to read from a session's line buffer with offset/length
57
138
  */
58
139
  private readFromLineBuffer;
59
140
  /**
@@ -71,23 +152,53 @@ export declare class TerminalManager {
71
152
  * Capture a snapshot of current output state for interaction tracking.
72
153
  * Used by interactWithProcess to know what output existed before sending input.
73
154
  */
74
- captureOutputSnapshot(pid: number): {
75
- totalChars: number;
76
- lineCount: number;
77
- } | null;
155
+ captureOutputSnapshot(pid: number): OutputSnapshot | null;
78
156
  /**
79
157
  * Get output that appeared since a snapshot was taken.
80
158
  * This handles the case where output is appended to the last line (REPL prompts).
81
159
  * Also checks completed sessions in case process finished between snapshot and poll.
82
160
  */
83
- getOutputSinceSnapshot(pid: number, snapshot: {
84
- totalChars: number;
85
- lineCount: number;
86
- }): string | null;
161
+ getOutputSinceSnapshot(pid: number, snapshot: OutputSnapshot): string | null;
87
162
  /**
88
- * New output since a snapshot, in absolute (since process start) offsets.
89
- * If eviction dropped part of the unseen output, returns what the buffer
90
- * still holds — the oldest unseen chars are lost to the cap.
163
+ * Output that appeared since `snapshot`, plus the snapshot at the current end
164
+ * of output. A poller passes `next` back in to read only the output that
165
+ * arrived since its previous poll. Costs O(output since snapshot), never
166
+ * O(whole buffer), so polling stays cheap however much history the session
167
+ * has retained. Also checks completed sessions in case the process finished
168
+ * between snapshot and poll.
169
+ */
170
+ readOutputSince(pid: number, snapshot: OutputSnapshot): {
171
+ output: string;
172
+ next: OutputSnapshot;
173
+ } | null;
174
+ /**
175
+ * Snapshot at the current end of a buffer, in O(1): bufferedChars is the
176
+ * joined length of the retained lines, so nothing is joined here.
177
+ */
178
+ private static endOfOutput;
179
+ /**
180
+ * The process's state: finished once it has exited, whatever its output
181
+ * says; otherwise waiting for input or running, judged from the end of the
182
+ * output it wrote since `since` (default: since it started). Reads only the
183
+ * per-stream tails, so it costs the same however much output the process
184
+ * has produced. The one place start_process, interact_with_process,
185
+ * read_process_output and list_sessions get the state from.
186
+ */
187
+ getProcessState(pid: number, since?: OutputSnapshot): ProcessState | null;
188
+ /**
189
+ * The output since `since` of each stream that may have written last: the
190
+ * streams delivered in the latest turn that delivered anything since then.
191
+ * Their relative order within that turn is unknown (see
192
+ * currentDeliveryTurn), so each is judged on its own; streams last
193
+ * delivered in an earlier turn wrote before them and can't end the output.
194
+ */
195
+ private static lastWrittenOutput;
196
+ /**
197
+ * New output since a snapshot, in absolute (since process start) offsets:
198
+ * the last (end - snapshot) chars of the joined buffer. Walks back from the
199
+ * newest line only until the snapshot position is covered and joins just
200
+ * those lines. If eviction dropped part of the unseen output, returns what
201
+ * the buffer still holds — the oldest unseen chars are lost to the cap.
91
202
  */
92
203
  private static outputSinceSnapshot;
93
204
  /**
@@ -96,7 +207,13 @@ export declare class TerminalManager {
96
207
  * @returns The session or undefined if not found
97
208
  */
98
209
  getSession(pid: number): TerminalSession | undefined;
99
- forceTerminate(pid: number): boolean;
210
+ /**
211
+ * End a session: its shell and every process the command started (see
212
+ * terminateProcessTree). Killing only the shell left the program running.
213
+ * Resolves once they are gone: 'terminated', or 'failed' if some could not
214
+ * be ended; 'not_found' when no session runs as `pid`. Never rejects.
215
+ */
216
+ forceTerminate(pid: number): Promise<TerminateOutcome>;
100
217
  listActiveSessions(): ActiveSession[];
101
218
  listCompletedSessions(): CompletedSession[];
102
219
  }