@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
@@ -1,9 +1,10 @@
1
1
  import { spawn } from 'child_process';
2
- import path from 'path';
3
- import { DEFAULT_COMMAND_TIMEOUT } from './config.js';
2
+ import { DEFAULT_COMMAND_TIMEOUT, MAX_PROCESS_WAIT_MS } from './config.js';
4
3
  import { configManager } from './config-manager.js';
5
4
  import { capture } from "./utils/capture.js";
6
- import { analyzeProcessState } from './utils/process-detection.js';
5
+ import { analyzeProcessState, STATE_DETECTION_TAIL_CHARS } from './utils/process-detection.js';
6
+ import { getDefaultShell, getShellSpawnArgs } from './utils/shell.js';
7
+ import { terminateProcessTree } from './utils/process-tree.js';
7
8
  /**
8
9
  * Standard Windows PATHEXT value, used to repair a corrupted PATHEXT before
9
10
  * spawning child shells.
@@ -32,76 +33,35 @@ function getRepairedPathExt() {
32
33
  }
33
34
  return current;
34
35
  }
36
+ const OUTPUT_STREAMS = ['stdout', 'stderr'];
37
+ function newStreamTails() {
38
+ return { stdout: { text: '', chars: 0, turn: 0 }, stderr: { text: '', chars: 0, turn: 0 } };
39
+ }
40
+ /**
41
+ * The one place that turns a caller's timeout_ms into the time a process wait
42
+ * may actually block. When `capped`, the call returns at the ceiling with the
43
+ * process still running and the caller continues with read_process_output.
44
+ */
45
+ export function getProcessWaitLimit(timeoutMs, capMs = MAX_PROCESS_WAIT_MS) {
46
+ return { waitMs: Math.min(timeoutMs, capMs), capMs, capped: timeoutMs > capMs };
47
+ }
35
48
  /**
36
49
  * Output buffering caps. Without a cap, a process emitting enough output makes
37
50
  * string concatenation throw "RangeError: Invalid string length" at V8's max
38
51
  * string size (~536M chars) inside a stdout 'data' handler — an uncaught
39
52
  * exception that kills the whole server (index.ts exits on uncaughtException).
40
- * The cap also bounds the join() cost in snapshot reads and the periodic
41
- * process-state scan, both of which are O(total output).
53
+ * The cap also bounds the cost of the reads that are O(total output), such as
54
+ * since-start snapshot reads.
42
55
  */
43
56
  export const MAX_BUFFERED_OUTPUT_CHARS = 50 * 1024 * 1024; // per session; oldest lines evicted first
44
57
  const MAX_LINE_CHARS = 1024 * 1024; // force-split longer lines so eviction can work
45
- const MAX_WAIT_OUTPUT_CHARS = 2 * 1024 * 1024; // start_process wait buffer (prompt/state detection)
46
- /**
47
- * Get the appropriate spawn configuration for a given shell
48
- * This handles login shell flags for different shell types
49
- */
50
- function getShellSpawnArgs(shellPath, command) {
51
- const shellName = path.basename(shellPath).toLowerCase();
52
- // Unix shells with login flag support
53
- if (shellName.includes('bash') || shellName.includes('zsh')) {
54
- return {
55
- executable: shellPath,
56
- args: ['-l', '-c', command],
57
- useShellOption: false
58
- };
59
- }
60
- // PowerShell Core (cross-platform, supports -Login)
61
- if (shellName === 'pwsh' || shellName === 'pwsh.exe') {
62
- return {
63
- executable: shellPath,
64
- args: ['-Login', '-Command', command],
65
- useShellOption: false
66
- };
67
- }
68
- // Windows PowerShell 5.1 (no login flag support)
69
- if (shellName === 'powershell' || shellName === 'powershell.exe') {
70
- return {
71
- executable: shellPath,
72
- args: ['-Command', command],
73
- useShellOption: false
74
- };
75
- }
76
- // CMD
77
- if (shellName === 'cmd' || shellName === 'cmd.exe') {
78
- return {
79
- executable: shellPath,
80
- args: ['/c', command],
81
- windowsVerbatim: true,
82
- useShellOption: false
83
- };
84
- }
85
- // Fish shell (uses -l for login, -c for command)
86
- if (shellName.includes('fish')) {
87
- return {
88
- executable: shellPath,
89
- args: ['-l', '-c', command],
90
- useShellOption: false
91
- };
92
- }
93
- // Unknown/other shells - use shell option for safety
94
- // This provides a fallback for shells we don't explicitly handle
95
- return {
96
- executable: command,
97
- args: [],
98
- useShellOption: shellPath
99
- };
100
- }
58
+ const MAX_WAIT_OUTPUT_CHARS = 2 * 1024 * 1024; // start_process wait buffer (the initial output it returns)
101
59
  export class TerminalManager {
102
60
  constructor() {
103
61
  this.sessions = new Map();
104
62
  this.completedSessions = new Map();
63
+ this.deliveryTurn = 0;
64
+ this.deliveryTurnOpen = false;
105
65
  }
106
66
  /**
107
67
  * Send input to a running process
@@ -128,19 +88,17 @@ export class TerminalManager {
128
88
  return false;
129
89
  }
130
90
  }
131
- async executeCommand(command, timeoutMs = DEFAULT_COMMAND_TIMEOUT, shell, collectTiming = false) {
132
- // Get the shell from config if not specified
133
- let shellToUse = shell;
134
- if (!shellToUse) {
135
- try {
136
- const config = await configManager.getConfig();
137
- shellToUse = config.defaultShell || true;
138
- }
139
- catch (error) {
140
- // If there's an error getting the config, fall back to default
141
- shellToUse = true;
142
- }
91
+ async executeCommand(command, timeoutMs = DEFAULT_COMMAND_TIMEOUT, shell, collectTiming = false, maxWaitMs = MAX_PROCESS_WAIT_MS) {
92
+ let config = {};
93
+ try {
94
+ config = await configManager.getConfig();
95
+ }
96
+ catch (error) {
97
+ // If there's an error getting the config, fall back to the default shell
143
98
  }
99
+ // Get the shell from config if not specified
100
+ const shellToUse = shell || config.defaultShell || getDefaultShell();
101
+ const waitLimit = getProcessWaitLimit(timeoutMs, maxWaitMs);
144
102
  // For REPL interactions, we need to ensure stdin, stdout, and stderr are properly configured
145
103
  // Note: No special stdio options needed here, Node.js handles pipes by default
146
104
  // Enhance SSH commands automatically
@@ -149,39 +107,18 @@ export class TerminalManager {
149
107
  enhancedCommand = command.replace(/^ssh /, 'ssh -t ');
150
108
  console.log(`Enhanced SSH command: ${enhancedCommand}`);
151
109
  }
152
- // Get the appropriate spawn configuration for the shell
153
- let spawnConfig;
154
- let spawnOptions;
155
- if (typeof shellToUse === 'string') {
156
- // Use shell-specific configuration with login flags where appropriate
157
- spawnConfig = getShellSpawnArgs(shellToUse, enhancedCommand);
158
- spawnOptions = {
159
- env: {
160
- ...process.env,
161
- TERM: 'xterm-256color' // Better terminal compatibility
162
- },
163
- windowsHide: true // Prevent visible console windows on Windows
164
- };
165
- // Add shell option if needed (for unknown shells)
166
- if (spawnConfig.useShellOption) {
167
- spawnOptions.shell = spawnConfig.useShellOption;
168
- }
169
- }
170
- else {
171
- // Boolean or undefined shell - use default shell option behavior
172
- spawnConfig = {
173
- executable: enhancedCommand,
174
- args: [],
175
- useShellOption: shellToUse
176
- };
177
- spawnOptions = {
178
- shell: shellToUse,
179
- env: {
180
- ...process.env,
181
- TERM: 'xterm-256color'
182
- },
183
- windowsHide: true // Prevent visible console windows on Windows
184
- };
110
+ // Get the appropriate spawn configuration for the shell, with login flags where appropriate
111
+ const spawnConfig = getShellSpawnArgs(shellToUse, enhancedCommand);
112
+ const spawnOptions = {
113
+ env: {
114
+ ...process.env,
115
+ TERM: 'xterm-256color' // Better terminal compatibility
116
+ },
117
+ windowsHide: true // Prevent visible console windows on Windows
118
+ };
119
+ // Add shell option if needed (for unknown shells)
120
+ if (spawnConfig.useShellOption) {
121
+ spawnOptions.shell = spawnConfig.useShellOption;
185
122
  }
186
123
  // Repair PATHEXT on Windows before spawning. On some Windows DXT launches
187
124
  // the server process inherits a corrupted PATHEXT (e.g. ".CPL"), which we
@@ -228,10 +165,12 @@ export class TerminalManager {
228
165
  // Ensure childProcess.pid is defined before proceeding
229
166
  if (!childProcess.pid) {
230
167
  // Return a consistent error object instead of throwing
168
+ const output = 'Error: Failed to get process ID. The command could not be executed.';
231
169
  return {
232
170
  pid: -1, // Use -1 to indicate an error state
233
- output: 'Error: Failed to get process ID. The command could not be executed.',
234
- isBlocked: false
171
+ output,
172
+ isBlocked: false,
173
+ processState: analyzeProcessState(output)
235
174
  };
236
175
  }
237
176
  const session = {
@@ -239,11 +178,12 @@ export class TerminalManager {
239
178
  process: childProcess,
240
179
  outputLines: [], // Line-based buffer
241
180
  lastReadIndex: 0, // Track where "new" output starts
242
- isBlocked: false,
181
+ lastReadOpenLine: '',
243
182
  startTime: new Date(),
244
183
  bufferedChars: 0,
245
184
  evictedLines: 0,
246
- evictedChars: 0
185
+ evictedChars: 0,
186
+ streams: newStreamTails()
247
187
  };
248
188
  this.sessions.set(childProcess.pid, session);
249
189
  // Timing telemetry
@@ -255,14 +195,26 @@ export class TerminalManager {
255
195
  return new Promise((resolve) => {
256
196
  let resolved = false;
257
197
  let periodicCheck = null;
258
- // Quick prompt patterns for immediate detection
259
- const quickPromptPatterns = />>>\s*$|>\s*$|\$\s*$|#\s*$/;
260
- const resolveOnce = (result) => {
198
+ let waitTimer = null;
199
+ // Whether the process waits for input, judged as the periodic check does:
200
+ // from the end of each output stream, not from the chunk that just came
201
+ // (a chunk can end in the middle of a line, e.g. right after "<div>").
202
+ const waitingForInput = () => this.getProcessState(childProcess.pid)?.isWaitingForInput === true;
203
+ const resolveOnce = (waitResult) => {
261
204
  if (resolved)
262
205
  return;
263
206
  resolved = true;
264
207
  if (periodicCheck)
265
208
  clearInterval(periodicCheck);
209
+ if (waitTimer)
210
+ clearTimeout(waitTimer);
211
+ // The state the wait ended in, from the session: finished if the
212
+ // process exited, else judged from its output. A process error after
213
+ // the exit leaves no session behind, so the text it returns is judged.
214
+ const result = {
215
+ ...waitResult,
216
+ processState: this.getProcessState(childProcess.pid) ?? analyzeProcessState(waitResult.output)
217
+ };
266
218
  // Add timing info if requested
267
219
  if (collectTiming) {
268
220
  const endTime = Date.now();
@@ -279,11 +231,15 @@ export class TerminalManager {
279
231
  }
280
232
  resolve(result);
281
233
  };
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.
234
+ // Now that resolveOnce exists, route process errors into it, so the caller
235
+ // doesn't sit waiting for output. The session goes only if the process
236
+ // has exited: Node also emits 'error' when a kill fails or a message can't
237
+ // be sent, and the process runs on. It then stays listed, readable and
238
+ // terminable, and its 'exit' records the completion as usual.
285
239
  forwardProcessError = (err) => {
286
- this.sessions.delete(childProcess.pid);
240
+ if (childProcess.exitCode !== null || childProcess.signalCode !== null) {
241
+ this.sessions.delete(childProcess.pid);
242
+ }
287
243
  exitReason = 'process_exit';
288
244
  resolveOnce({
289
245
  pid: childProcess.pid,
@@ -302,16 +258,15 @@ export class TerminalManager {
302
258
  if (!firstOutputTime)
303
259
  firstOutputTime = now;
304
260
  lastOutputTime = now;
305
- // `output` only feeds the wait-phase result and prompt/state detection,
306
- // so stop growing it once resolved and keep only a bounded tail.
261
+ // `output` only feeds the wait-phase result, so stop growing it once
262
+ // resolved and keep only a bounded tail.
307
263
  if (!resolved) {
308
264
  output += text;
309
265
  if (output.length > MAX_WAIT_OUTPUT_CHARS) {
310
266
  output = output.slice(-Math.floor(MAX_WAIT_OUTPUT_CHARS / 2));
311
267
  }
312
268
  }
313
- // Append to line-based buffer
314
- this.appendToLineBuffer(session, text);
269
+ this.recordOutput(session, 'stdout', text);
315
270
  // Record output event if collecting timing
316
271
  if (collectTiming) {
317
272
  outputEvents.push({
@@ -322,9 +277,8 @@ export class TerminalManager {
322
277
  snippet: text.slice(0, 50).replace(/\n/g, '\\n')
323
278
  });
324
279
  }
325
- // Immediate check for obvious prompts
326
- if (quickPromptPatterns.test(text)) {
327
- session.isBlocked = true;
280
+ // Immediate check for a prompt
281
+ if (waitingForInput()) {
328
282
  exitReason = 'early_exit_quick_pattern';
329
283
  if (collectTiming && outputEvents.length > 0) {
330
284
  outputEvents[outputEvents.length - 1].matchedPattern = 'quick_pattern';
@@ -348,8 +302,7 @@ export class TerminalManager {
348
302
  output = output.slice(-Math.floor(MAX_WAIT_OUTPUT_CHARS / 2));
349
303
  }
350
304
  }
351
- // Append to line-based buffer
352
- this.appendToLineBuffer(session, text);
305
+ this.recordOutput(session, 'stderr', text);
353
306
  // Record output event if collecting timing
354
307
  if (collectTiming) {
355
308
  outputEvents.push({
@@ -363,40 +316,34 @@ export class TerminalManager {
363
316
  });
364
317
  // Periodic comprehensive check every 100ms
365
318
  periodicCheck = setInterval(() => {
366
- if (output.trim()) {
367
- const processState = analyzeProcessState(output, childProcess.pid);
368
- if (processState.isWaitingForInput) {
369
- session.isBlocked = true;
370
- exitReason = 'early_exit_periodic_check';
371
- resolveOnce({
372
- pid: childProcess.pid,
373
- output,
374
- isBlocked: true
375
- });
376
- }
319
+ if (waitingForInput()) {
320
+ exitReason = 'early_exit_periodic_check';
321
+ resolveOnce({
322
+ pid: childProcess.pid,
323
+ output,
324
+ isBlocked: true
325
+ });
377
326
  }
378
327
  }, 100);
379
- // Timeout fallback
380
- setTimeout(() => {
381
- session.isBlocked = true;
328
+ // Timeout fallback, bounded by the wait ceiling so the call returns
329
+ // before the MCP client gives up on it; the process keeps running.
330
+ waitTimer = setTimeout(() => {
382
331
  exitReason = 'timeout';
383
332
  resolveOnce({
384
333
  pid: childProcess.pid,
385
334
  output,
386
- isBlocked: true
335
+ isBlocked: true,
336
+ ...(waitLimit.capped && { waitCappedAtMs: waitLimit.capMs })
387
337
  });
388
- }, timeoutMs);
389
- childProcess.on('exit', (code) => {
338
+ }, waitLimit.waitMs);
339
+ childProcess.on('exit', (code, signal) => {
390
340
  if (childProcess.pid) {
391
341
  // Store completed session before removing active session
392
342
  this.completedSessions.set(childProcess.pid, {
393
- pid: childProcess.pid,
394
- outputLines: [...session.outputLines], // Copy line buffer
343
+ session,
395
344
  exitCode: code,
396
- startTime: session.startTime,
397
- endTime: new Date(),
398
- evictedLines: session.evictedLines,
399
- evictedChars: session.evictedChars
345
+ signal,
346
+ endTime: new Date()
400
347
  });
401
348
  // Keep only last 100 completed sessions
402
349
  if (this.completedSessions.size > 100) {
@@ -414,6 +361,35 @@ export class TerminalManager {
414
361
  });
415
362
  });
416
363
  }
364
+ /**
365
+ * Add a chunk of one stream's output to the session: to the merged line
366
+ * buffer, and to that stream's tail for state detection.
367
+ */
368
+ recordOutput(session, stream, text) {
369
+ this.appendToLineBuffer(session, text);
370
+ const tail = session.streams[stream];
371
+ tail.text = (text.length >= STATE_DETECTION_TAIL_CHARS ? text : tail.text + text).slice(-STATE_DETECTION_TAIL_CHARS);
372
+ tail.chars += text.length;
373
+ tail.turn = this.currentDeliveryTurn();
374
+ }
375
+ /**
376
+ * Number of the event-loop turn now delivering output; every chunk
377
+ * dispatched before the next check phase (setImmediate) shares it.
378
+ *
379
+ * stdout and stderr are separate pipes. Each turn delivers what the OS had
380
+ * ready when the loop polled, so a chunk delivered in a later turn was
381
+ * written after the chunks of earlier turns. Within one turn the pipes come
382
+ * in either order: when python -i's final stdout newline and its stderr
383
+ * ">>> " prompt are both waiting, the prompt is often delivered first.
384
+ */
385
+ currentDeliveryTurn() {
386
+ if (!this.deliveryTurnOpen) {
387
+ this.deliveryTurnOpen = true;
388
+ this.deliveryTurn++;
389
+ setImmediate(() => { this.deliveryTurnOpen = false; });
390
+ }
391
+ return this.deliveryTurn;
392
+ }
417
393
  /**
418
394
  * Append text to a session's line buffer
419
395
  * Handles partial lines and newline splitting
@@ -457,14 +433,20 @@ export class TerminalManager {
457
433
  // Enforce the per-session cap by evicting the oldest lines. Keeps the
458
434
  // buffer far below V8's max string length so concatenation and join()
459
435
  // can never throw "Invalid string length" and kill the server.
460
- while (session.bufferedChars > MAX_BUFFERED_OUTPUT_CHARS && session.outputLines.length > 1) {
461
- const dropped = session.outputLines.shift();
462
- const droppedJoinedChars = dropped.length + 1; // +1 for its join separator
436
+ // Count them first and drop them with one splice: on an array this large
437
+ // every shift() copies the whole array, and a line-by-line shift() stalled
438
+ // the event loop for seconds per chunk once a session reached the cap.
439
+ let evicted = 0;
440
+ while (session.bufferedChars > MAX_BUFFERED_OUTPUT_CHARS && evicted < session.outputLines.length - 1) {
441
+ const droppedJoinedChars = session.outputLines[evicted].length + 1; // +1 for its join separator
463
442
  session.bufferedChars -= droppedJoinedChars;
464
443
  session.evictedChars += droppedJoinedChars;
465
- session.evictedLines++;
466
- if (session.lastReadIndex > 0)
467
- session.lastReadIndex--;
444
+ evicted++;
445
+ }
446
+ if (evicted > 0) {
447
+ session.outputLines.splice(0, evicted);
448
+ session.evictedLines += evicted;
449
+ session.lastReadIndex = Math.max(0, session.lastReadIndex - evicted);
468
450
  }
469
451
  }
470
452
  /**
@@ -478,53 +460,92 @@ export class TerminalManager {
478
460
  // First check active sessions
479
461
  const session = this.sessions.get(pid);
480
462
  if (session) {
481
- const result = this.readFromLineBuffer(session.outputLines, offset, length, session.lastReadIndex, (newIndex) => { session.lastReadIndex = newIndex; }, false, undefined);
463
+ const result = this.readFromLineBuffer(session, offset, length, false, undefined);
482
464
  result.evictedLines = session.evictedLines;
483
465
  return result;
484
466
  }
485
- // Then check completed sessions
467
+ // Then check completed sessions: they keep their read position, so
468
+ // reading on after the exit continues where the last read stopped
486
469
  const completedSession = this.completedSessions.get(pid);
487
470
  if (completedSession) {
488
- const runtimeMs = completedSession.endTime.getTime() - completedSession.startTime.getTime();
489
- const result = this.readFromLineBuffer(completedSession.outputLines, offset, length, 0, // Completed sessions don't track read position
490
- () => { }, // No-op for completed sessions
491
- true, completedSession.exitCode, runtimeMs);
492
- result.evictedLines = completedSession.evictedLines;
471
+ const runtimeMs = completedSession.endTime.getTime() - completedSession.session.startTime.getTime();
472
+ const result = this.readFromLineBuffer(completedSession.session, offset, length, true, completedSession.exitCode, runtimeMs);
473
+ result.evictedLines = completedSession.session.evictedLines;
474
+ result.signal = completedSession.signal;
493
475
  return result;
494
476
  }
495
477
  return null;
496
478
  }
497
479
  /**
498
- * Internal helper to read from a line buffer with offset/length
480
+ * Whether a default read (offset 0) has anything to return: complete lines
481
+ * past the read position, or an unfinished last line with text a read
482
+ * hasn't returned (see readFromLineBuffer). Line counts alone can't tell
483
+ * the second: text appended to that line adds no line.
484
+ */
485
+ hasUnreadOutput(pid) {
486
+ const session = this.sessions.get(pid) ?? this.completedSessions.get(pid)?.session;
487
+ if (!session) {
488
+ return false;
489
+ }
490
+ return session.outputLines.length - 1 > session.lastReadIndex || TerminalManager.openLineHasNewText(session);
491
+ }
492
+ /**
493
+ * Whether the unfinished last line has text that a default read hasn't
494
+ * returned. Empty, it has nothing to return. Its text is compared with what
495
+ * a read last returned only while it is the line that read stopped at: a
496
+ * later line is new even when its text is the same (a REPL's next ">>> ").
497
+ */
498
+ static openLineHasNewText(session) {
499
+ const lines = session.outputLines;
500
+ const openLine = lines[lines.length - 1] ?? '';
501
+ return openLine !== '' && (lines.length - 1 !== session.lastReadIndex || openLine !== session.lastReadOpenLine);
502
+ }
503
+ /**
504
+ * Internal helper to read from a session's line buffer with offset/length
499
505
  */
500
- readFromLineBuffer(lines, offset, length, lastReadIndex, updateLastRead, isComplete, exitCode, runtimeMs) {
501
- const totalLines = lines.length;
506
+ readFromLineBuffer(session, offset, length, isComplete, exitCode, runtimeMs) {
507
+ const lines = session.outputLines;
508
+ // The empty last line after a trailing newline holds nothing: it isn't
509
+ // counted (total, remaining, tail offsets) or returned. A last line with
510
+ // text, unfinished or not, is.
511
+ const totalLines = lines[lines.length - 1] === '' ? lines.length - 1 : lines.length;
502
512
  let startIndex;
503
513
  let linesToRead;
514
+ let readableEnd = totalLines;
504
515
  if (offset < 0) {
505
516
  // Negative offset = start position from end, then read 'length' lines forward
506
517
  // e.g., offset=-50, length=10 means: start 50 lines from end, read 10 lines
507
518
  const fromEnd = Math.abs(offset);
508
519
  startIndex = Math.max(0, totalLines - fromEnd);
509
- linesToRead = lines.slice(startIndex, startIndex + length);
520
+ linesToRead = lines.slice(startIndex, Math.min(startIndex + length, totalLines));
510
521
  // Don't update lastReadIndex for tail reads
511
522
  }
512
523
  else if (offset === 0) {
513
- // offset=0 means "from where I last read" (like getNewOutput)
514
- startIndex = lastReadIndex;
515
- linesToRead = lines.slice(startIndex, startIndex + length);
516
- // Update lastReadIndex for "new output" behavior
517
- updateLastRead(Math.min(startIndex + linesToRead.length, totalLines));
524
+ // offset=0 means "from where I last read" (like getNewOutput).
525
+ // The last line is unfinished: output is appended to it until a newline
526
+ // arrives, even after the exit (a process the command started can still
527
+ // write). So it is returned only when it has text a read hasn't
528
+ // returned, and the read position never moves past it: counting it as
529
+ // read would lose whatever is appended to it next.
530
+ const openLineIndex = Math.max(lines.length - 1, 0);
531
+ readableEnd = TerminalManager.openLineHasNewText(session) ? lines.length : openLineIndex;
532
+ startIndex = session.lastReadIndex;
533
+ linesToRead = lines.slice(startIndex, Math.min(startIndex + length, readableEnd));
534
+ const readTo = startIndex + linesToRead.length;
535
+ if (readTo === lines.length) {
536
+ session.lastReadOpenLine = lines[lines.length - 1];
537
+ }
538
+ session.lastReadIndex = Math.min(readTo, openLineIndex);
518
539
  }
519
540
  else {
520
541
  // Positive offset = absolute position
521
542
  startIndex = offset;
522
- linesToRead = lines.slice(startIndex, startIndex + length);
543
+ linesToRead = lines.slice(startIndex, Math.min(startIndex + length, totalLines));
523
544
  // Don't update lastReadIndex for absolute position reads
524
545
  }
525
546
  const readCount = linesToRead.length;
526
547
  const endIndex = startIndex + readCount;
527
- const remaining = Math.max(0, totalLines - endIndex);
548
+ const remaining = Math.max(0, readableEnd - endIndex);
528
549
  return {
529
550
  lines: linesToRead,
530
551
  totalLines,
@@ -546,7 +567,7 @@ export class TerminalManager {
546
567
  }
547
568
  const completedSession = this.completedSessions.get(pid);
548
569
  if (completedSession) {
549
- return completedSession.outputLines.length;
570
+ return completedSession.session.outputLines.length;
550
571
  }
551
572
  return null;
552
573
  }
@@ -585,17 +606,7 @@ export class TerminalManager {
585
606
  */
586
607
  captureOutputSnapshot(pid) {
587
608
  const session = this.sessions.get(pid);
588
- if (session) {
589
- const fullOutput = session.outputLines.join('\n');
590
- return {
591
- // Absolute since process start (includes evicted output), so the
592
- // offset stays valid even if the cap evicts lines between
593
- // snapshot and read.
594
- totalChars: session.evictedChars + fullOutput.length,
595
- lineCount: session.evictedLines + session.outputLines.length
596
- };
597
- }
598
- return null;
609
+ return session ? TerminalManager.endOfOutput(session) : null;
599
610
  }
600
611
  /**
601
612
  * Get output that appeared since a snapshot was taken.
@@ -603,30 +614,99 @@ export class TerminalManager {
603
614
  * Also checks completed sessions in case process finished between snapshot and poll.
604
615
  */
605
616
  getOutputSinceSnapshot(pid, snapshot) {
606
- // Check active session first
617
+ return this.readOutputSince(pid, snapshot)?.output ?? null;
618
+ }
619
+ /**
620
+ * Output that appeared since `snapshot`, plus the snapshot at the current end
621
+ * of output. A poller passes `next` back in to read only the output that
622
+ * arrived since its previous poll. Costs O(output since snapshot), never
623
+ * O(whole buffer), so polling stays cheap however much history the session
624
+ * has retained. Also checks completed sessions in case the process finished
625
+ * between snapshot and poll.
626
+ */
627
+ readOutputSince(pid, snapshot) {
628
+ const buffer = this.sessions.get(pid) ?? this.completedSessions.get(pid)?.session;
629
+ if (!buffer) {
630
+ return null;
631
+ }
632
+ return {
633
+ output: TerminalManager.outputSinceSnapshot(buffer, snapshot.totalChars),
634
+ next: TerminalManager.endOfOutput(buffer)
635
+ };
636
+ }
637
+ /**
638
+ * Snapshot at the current end of a buffer, in O(1): bufferedChars is the
639
+ * joined length of the retained lines, so nothing is joined here.
640
+ */
641
+ static endOfOutput(buffer) {
642
+ return {
643
+ // Absolute since process start (includes evicted output), so the
644
+ // offset stays valid even if the cap evicts lines between
645
+ // snapshot and read.
646
+ totalChars: buffer.evictedChars + buffer.bufferedChars,
647
+ lineCount: buffer.evictedLines + buffer.outputLines.length,
648
+ streamChars: { stdout: buffer.streams.stdout.chars, stderr: buffer.streams.stderr.chars }
649
+ };
650
+ }
651
+ /**
652
+ * The process's state: finished once it has exited, whatever its output
653
+ * says; otherwise waiting for input or running, judged from the end of the
654
+ * output it wrote since `since` (default: since it started). Reads only the
655
+ * per-stream tails, so it costs the same however much output the process
656
+ * has produced. The one place start_process, interact_with_process,
657
+ * read_process_output and list_sessions get the state from.
658
+ */
659
+ getProcessState(pid, since) {
607
660
  const session = this.sessions.get(pid);
608
661
  if (session) {
609
- return TerminalManager.outputSinceSnapshot(session.outputLines, session.evictedChars, snapshot.totalChars);
662
+ return analyzeProcessState(TerminalManager.lastWrittenOutput(session.streams, since), pid);
610
663
  }
611
- // Fallback to completed sessions - process may have finished between snapshot and poll
612
664
  const completedSession = this.completedSessions.get(pid);
613
- if (completedSession) {
614
- return TerminalManager.outputSinceSnapshot(completedSession.outputLines, completedSession.evictedChars, snapshot.totalChars);
665
+ if (!completedSession) {
666
+ return null;
615
667
  }
616
- return null;
668
+ const lastOutput = TerminalManager.lastWrittenOutput(completedSession.session.streams, since).join('\n');
669
+ return { isWaitingForInput: false, isFinished: true, isRunning: false, lastOutput };
617
670
  }
618
671
  /**
619
- * New output since a snapshot, in absolute (since process start) offsets.
620
- * If eviction dropped part of the unseen output, returns what the buffer
621
- * still holds — the oldest unseen chars are lost to the cap.
672
+ * The output since `since` of each stream that may have written last: the
673
+ * streams delivered in the latest turn that delivered anything since then.
674
+ * Their relative order within that turn is unknown (see
675
+ * currentDeliveryTurn), so each is judged on its own; streams last
676
+ * delivered in an earlier turn wrote before them and can't end the output.
622
677
  */
623
- static outputSinceSnapshot(outputLines, evictedChars, snapshotTotalChars) {
624
- const fullOutput = outputLines.join('\n');
625
- const newChars = evictedChars + fullOutput.length - snapshotTotalChars;
626
- if (newChars <= 0) {
678
+ static lastWrittenOutput(streams, since) {
679
+ const recent = OUTPUT_STREAMS
680
+ .map(name => {
681
+ const { text, chars, turn } = streams[name];
682
+ const newChars = chars - (since?.streamChars[name] ?? 0);
683
+ return { text: newChars > 0 ? text.slice(-newChars) : '', turn };
684
+ })
685
+ .filter(stream => stream.text.length > 0);
686
+ const lastTurn = Math.max(...recent.map(stream => stream.turn));
687
+ return recent.filter(stream => stream.turn === lastTurn).map(stream => stream.text);
688
+ }
689
+ /**
690
+ * New output since a snapshot, in absolute (since process start) offsets:
691
+ * the last (end - snapshot) chars of the joined buffer. Walks back from the
692
+ * newest line only until the snapshot position is covered and joins just
693
+ * those lines. If eviction dropped part of the unseen output, returns what
694
+ * the buffer still holds — the oldest unseen chars are lost to the cap.
695
+ */
696
+ static outputSinceSnapshot(buffer, snapshotTotalChars) {
697
+ const { outputLines } = buffer;
698
+ const newChars = buffer.evictedChars + buffer.bufferedChars - snapshotTotalChars;
699
+ if (newChars <= 0 || outputLines.length === 0) {
627
700
  return ''; // No new output
628
701
  }
629
- return fullOutput.substring(Math.max(0, fullOutput.length - newChars));
702
+ let firstLine = outputLines.length - 1;
703
+ let tailChars = outputLines[firstLine].length; // Joined length of outputLines[firstLine..]
704
+ while (tailChars < newChars && firstLine > 0) {
705
+ firstLine--;
706
+ tailChars += outputLines[firstLine].length + 1; // +1 for its join separator
707
+ }
708
+ const tail = outputLines.slice(firstLine).join('\n');
709
+ return tail.substring(Math.max(0, tail.length - newChars));
630
710
  }
631
711
  /**
632
712
  * Get a session by PID
@@ -636,32 +716,37 @@ export class TerminalManager {
636
716
  getSession(pid) {
637
717
  return this.sessions.get(pid);
638
718
  }
639
- forceTerminate(pid) {
719
+ /**
720
+ * End a session: its shell and every process the command started (see
721
+ * terminateProcessTree). Killing only the shell left the program running.
722
+ * Resolves once they are gone: 'terminated', or 'failed' if some could not
723
+ * be ended; 'not_found' when no session runs as `pid`. Never rejects.
724
+ */
725
+ async forceTerminate(pid) {
640
726
  const session = this.sessions.get(pid);
641
727
  if (!session) {
642
- return false;
728
+ return 'not_found';
643
729
  }
644
- try {
645
- session.process.kill('SIGINT');
646
- setTimeout(() => {
647
- if (this.sessions.has(pid)) {
648
- session.process.kill('SIGKILL');
649
- }
650
- }, 1000);
651
- return true;
730
+ if (!session.termination) {
731
+ // Calls made while it runs share it; a failed one is dropped, so the next call tries again
732
+ session.termination = terminateProcessTree(session.process).then((ended) => {
733
+ if (!ended)
734
+ session.termination = undefined;
735
+ return ended;
736
+ });
652
737
  }
653
- catch (error) {
654
- // Convert error to string, handling both Error objects and other types
655
- const errorMessage = error instanceof Error ? error.message : String(error);
656
- capture('server_request_error', { error: errorMessage, message: `Failed to terminate process ${pid}:` });
657
- return false;
738
+ if (await session.termination) {
739
+ return 'terminated';
658
740
  }
741
+ capture('server_request_error', { error: 'Process tree termination failed', message: `Failed to terminate process ${pid}:` });
742
+ return 'failed';
659
743
  }
660
744
  listActiveSessions() {
661
745
  const now = new Date();
662
746
  return Array.from(this.sessions.values()).map(session => ({
663
747
  pid: session.pid,
664
- isBlocked: session.isBlocked,
748
+ // Waiting for input now, judged from its output like every other state answer
749
+ isBlocked: this.getProcessState(session.pid)?.isWaitingForInput ?? false,
665
750
  runtime: now.getTime() - session.startTime.getTime()
666
751
  }));
667
752
  }