@wonderwhy-er/desktop-commander 0.2.52 → 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 (113) hide show
  1. package/dist/command-manager.d.ts +7 -2
  2. package/dist/command-manager.js +16 -11
  3. package/dist/config-manager.d.ts +49 -3
  4. package/dist/config-manager.js +329 -87
  5. package/dist/config-recovery.d.ts +28 -0
  6. package/dist/config-recovery.js +81 -0
  7. package/dist/config.d.ts +1 -0
  8. package/dist/config.js +9 -0
  9. package/dist/handlers/filesystem-handlers.d.ts +1 -1
  10. package/dist/handlers/filesystem-handlers.js +26 -16
  11. package/dist/handlers/search-answers.d.ts +58 -0
  12. package/dist/handlers/search-answers.js +172 -0
  13. package/dist/handlers/search-handlers.js +4 -92
  14. package/dist/index.js +14 -7
  15. package/dist/npm-scripts/remote.js +2 -3
  16. package/dist/remote-device/broadcast-analytics.d.ts +28 -0
  17. package/dist/remote-device/broadcast-analytics.js +41 -0
  18. package/dist/remote-device/desktop-commander-integration.js +19 -25
  19. package/dist/remote-device/device.d.ts +14 -0
  20. package/dist/remote-device/device.js +137 -30
  21. package/dist/remote-device/mqtt-enrollment.d.ts +16 -0
  22. package/dist/remote-device/mqtt-enrollment.js +162 -0
  23. package/dist/remote-device/mqtt-transport.d.ts +44 -0
  24. package/dist/remote-device/mqtt-transport.js +197 -0
  25. package/dist/remote-device/remote-channel.d.ts +12 -0
  26. package/dist/remote-device/remote-channel.js +55 -8
  27. package/dist/remote-device/scripts/blocking-offline-update.js +106 -69
  28. package/dist/remote-device/transport-analytics.d.ts +29 -0
  29. package/dist/remote-device/transport-analytics.js +44 -0
  30. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  31. package/dist/remote-device/transport-telemetry.js +48 -0
  32. package/dist/search-manager.d.ts +239 -27
  33. package/dist/search-manager.js +746 -312
  34. package/dist/server.js +44 -11
  35. package/dist/terminal-manager.d.ts +138 -21
  36. package/dist/terminal-manager.js +300 -215
  37. package/dist/tools/config.d.ts +1 -1
  38. package/dist/tools/config.js +21 -70
  39. package/dist/tools/edit.js +12 -4
  40. package/dist/tools/filesystem.d.ts +30 -6
  41. package/dist/tools/filesystem.js +246 -140
  42. package/dist/tools/improved-process-tools.d.ts +9 -3
  43. package/dist/tools/improved-process-tools.js +171 -68
  44. package/dist/tools/pdf/extract-images.d.ts +2 -0
  45. package/dist/tools/pdf/extract-images.js +4 -1
  46. package/dist/tools/pdf/index.d.ts +5 -3
  47. package/dist/tools/pdf/index.js +4 -3
  48. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  49. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  50. package/dist/tools/pdf/manipulations.d.ts +12 -1
  51. package/dist/tools/pdf/manipulations.js +17 -4
  52. package/dist/tools/pdf/markdown.d.ts +96 -0
  53. package/dist/tools/pdf/markdown.js +485 -20
  54. package/dist/tools/pdf/utils.d.ts +2 -2
  55. package/dist/tools/pdf/utils.js +4 -4
  56. package/dist/tools/process.js +8 -5
  57. package/dist/tools/schemas.d.ts +1 -1
  58. package/dist/tools/schemas.js +15 -6
  59. package/dist/tools/search.d.ts +32 -0
  60. package/dist/tools/search.js +202 -0
  61. package/dist/types.d.ts +1 -1
  62. package/dist/ui/config-editor/config-editor-runtime.js +6 -6
  63. package/dist/ui/config-editor/src/app.js +2 -15
  64. package/dist/utils/ab-test.js +27 -9
  65. package/dist/utils/atomic-write.d.ts +14 -0
  66. package/dist/utils/atomic-write.js +80 -0
  67. package/dist/utils/capture.d.ts +17 -1
  68. package/dist/utils/capture.js +177 -68
  69. package/dist/utils/exit-process.d.ts +24 -0
  70. package/dist/utils/exit-process.js +31 -0
  71. package/dist/utils/feature-flags.js +2 -1
  72. package/dist/utils/files/base.d.ts +3 -1
  73. package/dist/utils/files/docx.d.ts +3 -0
  74. package/dist/utils/files/docx.js +24 -9
  75. package/dist/utils/files/excel.d.ts +10 -0
  76. package/dist/utils/files/excel.js +93 -33
  77. package/dist/utils/files/factory.d.ts +22 -1
  78. package/dist/utils/files/factory.js +59 -4
  79. package/dist/utils/files/image.d.ts +12 -4
  80. package/dist/utils/files/image.js +19 -8
  81. package/dist/utils/files/index.d.ts +5 -3
  82. package/dist/utils/files/index.js +4 -3
  83. package/dist/utils/files/pdf.js +18 -36
  84. package/dist/utils/files/text.d.ts +21 -5
  85. package/dist/utils/files/text.js +90 -86
  86. package/dist/utils/internal-facts.d.ts +3 -0
  87. package/dist/utils/internal-facts.js +23 -0
  88. package/dist/utils/lazy-package.d.ts +23 -0
  89. package/dist/utils/lazy-package.js +42 -0
  90. package/dist/utils/open-browser.js +2 -1
  91. package/dist/utils/process-detection.d.ts +24 -5
  92. package/dist/utils/process-detection.js +199 -89
  93. package/dist/utils/process-tree.d.ts +14 -0
  94. package/dist/utils/process-tree.js +223 -0
  95. package/dist/utils/rename.d.ts +9 -0
  96. package/dist/utils/rename.js +74 -0
  97. package/dist/utils/ripgrep-resolver.js +9 -14
  98. package/dist/utils/shell.d.ts +42 -0
  99. package/dist/utils/shell.js +187 -0
  100. package/dist/utils/system-info.js +9 -7
  101. package/dist/utils/trackTools.js +2 -1
  102. package/dist/version.d.ts +1 -1
  103. package/dist/version.js +1 -1
  104. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  105. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  106. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  107. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  108. package/package.json +8 -2
  109. package/vendor/telemetry-contract/README.md +56 -0
  110. package/vendor/telemetry-contract/package.json +32 -0
  111. package/vendor/telemetry-contract/transport.d.ts +38 -0
  112. package/vendor/telemetry-contract/transport.js +164 -0
  113. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -26,27 +26,9 @@ export class PdfFileHandler {
26
26
  const { offset = 0, length } = options ?? {};
27
27
  try {
28
28
  // Use existing PDF parser
29
- // Ensure we pass a valid PageRange or number array
30
- // If length is undefined, we assume "rest of file" which requires careful handling.
31
- // If length is defined, we pass { offset, length }.
32
- // If neither, we pass empty array (all pages).
29
+ // With no length, read from offset to the last page (all pages from offset 0)
33
30
  // Note: offset defaults to 0 if undefined.
34
- let range;
35
- if (length !== undefined) {
36
- range = { offset, length };
37
- }
38
- else if (offset > 0) {
39
- // If offset provided but no length, try to read reasonable amount or all?
40
- // PageRange requires length. Let's assume 0 means "all" or use a large number?
41
- // Looking at pdf2md implementation, it uses generatePageNumbers(offset, length, total).
42
- // We'll pass 0 for length to imply "rest" if supported, or just undefined length if valid.
43
- // But typescript requires length.
44
- range = { offset, length: 0 };
45
- }
46
- else {
47
- range = [];
48
- }
49
- const pdfResult = await parsePdfToMarkdown(path, range);
31
+ const pdfResult = await parsePdfToMarkdown(path, { offset, length: length ?? Infinity });
50
32
  return {
51
33
  content: '', // Main content is in metadata.pages
52
34
  mimeType: 'application/pdf',
@@ -75,9 +57,14 @@ export class PdfFileHandler {
75
57
  * Write PDF - creates from markdown or operations
76
58
  */
77
59
  async write(path, content, mode) {
60
+ // A PDF can't take text at its end: rendering the content would replace the file
61
+ if (mode === 'append') {
62
+ throw new Error('PDF append not supported. Use write_pdf to modify existing PDF files.');
63
+ }
78
64
  // If content is string, treat as markdown to convert
79
65
  if (typeof content === 'string') {
80
- await parseMarkdownToPdf(content, path);
66
+ const pdfBuffer = await parseMarkdownToPdf(content);
67
+ await fs.writeFile(path, pdfBuffer);
81
68
  }
82
69
  else if (Array.isArray(content)) {
83
70
  // Array of operations - use editPdf
@@ -92,21 +79,16 @@ export class PdfFileHandler {
92
79
  * Edit PDF by range/operations
93
80
  */
94
81
  async editRange(path, range, content, options) {
95
- try {
96
- // For PDF, range editing isn't directly supported
97
- // Could interpret range as page numbers in future
98
- const resultBuffer = await editPdf(path, content);
99
- await fs.writeFile(options?.outputPath || path, resultBuffer);
100
- return { success: true, editsApplied: 1 };
101
- }
102
- catch (error) {
103
- const errorMessage = error instanceof Error ? error.message : String(error);
104
- return {
105
- success: false,
106
- editsApplied: 0,
107
- errors: [{ location: range, error: errorMessage }]
108
- };
109
- }
82
+ // For PDF, range editing isn't directly supported
83
+ // Could interpret range as page numbers in future
84
+ // The output path and inserted PDFs are checked as write_pdf checks them.
85
+ // Errors reach edit_block (as the Excel handler's do), which answers with them.
86
+ // Imported when used: tools/filesystem.js loads this handler through the file handler factory
87
+ const { validatePdfOperationPaths } = await import('../../tools/filesystem.js');
88
+ const targetPath = await validatePdfOperationPaths(path, content, options?.outputPath);
89
+ const resultBuffer = await editPdf(path, content);
90
+ await fs.writeFile(targetPath, resultBuffer);
91
+ return { success: true, editsApplied: 1 };
110
92
  }
111
93
  /**
112
94
  * Get PDF file information
@@ -24,7 +24,8 @@ export declare class TextFileHandler implements FileHandler {
24
24
  write(path: string, content: string, mode?: 'rewrite' | 'append'): Promise<void>;
25
25
  getInfo(path: string): Promise<FileInfo>;
26
26
  /**
27
- * Count lines in text content
27
+ * Count lines in text content the way read_file reads them (lineBreakBetween).
28
+ * A line break at the very end ends the last line; it doesn't start another.
28
29
  * Made static and public for use by other modules (e.g., writeFile telemetry in filesystem.ts)
29
30
  */
30
31
  static countLines(content: string): number;
@@ -46,19 +47,34 @@ export declare class TextFileHandler implements FileHandler {
46
47
  */
47
48
  private readFileWithSmartPositioning;
48
49
  /**
49
- * Read last N lines efficiently by reading file backwards
50
+ * Read last N lines efficiently: find where they start by reading the file
51
+ * backwards, then read them from there as readline does for smaller files
50
52
  */
51
53
  private readLastNLinesReverse;
54
+ /**
55
+ * Byte position where the last `n` lines start, found by reading 8 KB chunks
56
+ * backwards and finding line breaks by lineBreakBetween. A line break at the
57
+ * very end ends the last line instead of starting another.
58
+ */
59
+ private findLastLinesStart;
52
60
  /**
53
61
  * Read from end using readline with circular buffer
54
62
  */
55
63
  private readFromEndWithReadline;
56
64
  /**
57
- * Read from start/middle using readline
65
+ * Read from start/middle using readline. With `start`, reading begins at
66
+ * that byte, where line `startLine` begins.
58
67
  */
59
68
  private readFromStartWithReadline;
60
69
  /**
61
- * Read from estimated byte position for very large files
70
+ * Read from a deep offset in a very large file: find the byte where line
71
+ * `offset` starts, then read from there with readline
72
+ */
73
+ private readFromDeepOffset;
74
+ /**
75
+ * Byte position where line `line` (0-based) starts, or the file size when
76
+ * the file has fewer lines. Counts line breaks by lineBreakBetween in raw
77
+ * bytes, which is much faster than reading lines.
62
78
  */
63
- private readFromEstimatedPosition;
79
+ private findLineStart;
64
80
  }
@@ -24,10 +24,28 @@ const FILE_SIZE_LIMITS = {
24
24
  };
25
25
  const READ_PERFORMANCE_THRESHOLDS = {
26
26
  SMALL_READ_THRESHOLD: 100, // For very small reads
27
- DEEP_OFFSET_THRESHOLD: 1000, // For byte estimation
28
- SAMPLE_SIZE: 10000, // Sample size for estimation
27
+ DEEP_OFFSET_THRESHOLD: 1000, // Past this line, find where it starts first
29
28
  CHUNK_SIZE: 8192, // 8KB chunks for reverse reading
29
+ SCAN_CHUNK_SIZE: 64 * 1024, // 64KB chunks for counting line breaks forward
30
30
  };
31
+ const LINE_FEED = 0x0a;
32
+ const CARRIAGE_RETURN = 0x0d;
33
+ /**
34
+ * The line breaks read_file reads by (readline's): LF, CRLF as one break, and
35
+ * a lone CR. True when a line ends between two adjacent code units: the bytes
36
+ * of UTF-8 text (an LF or CR byte is never part of another character) or a
37
+ * string's characters. `after` is -1 at the end of the text.
38
+ */
39
+ function lineBreakBetween(before, after) {
40
+ return before === LINE_FEED || (before === CARRIAGE_RETURN && after !== LINE_FEED);
41
+ }
42
+ function throwIfAborted(signal) {
43
+ if (signal?.aborted) {
44
+ const err = new Error('Read aborted');
45
+ err.code = 'ABORT_ERR';
46
+ throw err;
47
+ }
48
+ }
31
49
  /**
32
50
  * Text file handler implementation
33
51
  * Binary detection is done at the factory level - this handler assumes file is text
@@ -101,19 +119,19 @@ export class TextFileHandler {
101
119
  // Private Helper Methods (extracted from filesystem.ts)
102
120
  // ========================================================================
103
121
  /**
104
- * Count lines in text content
122
+ * Count lines in text content the way read_file reads them (lineBreakBetween).
123
+ * A line break at the very end ends the last line; it doesn't start another.
105
124
  * Made static and public for use by other modules (e.g., writeFile telemetry in filesystem.ts)
106
125
  */
107
126
  static countLines(content) {
108
127
  if (content === '')
109
128
  return 0;
110
- // A file with N lines has N-1 newline characters.
111
- // If the file ends with a trailing newline, don't count the empty string after it.
112
- const lines = content.split('\n');
113
- if (lines[lines.length - 1] === '') {
114
- return lines.length - 1;
129
+ let lines = 1;
130
+ for (let i = 1; i < content.length; i++) {
131
+ if (lineBreakBetween(content.charCodeAt(i - 1), content.charCodeAt(i)))
132
+ lines++;
115
133
  }
116
- return lines.length;
134
+ return lines;
117
135
  }
118
136
  /**
119
137
  * Get file line count (for files under size limit)
@@ -231,7 +249,7 @@ export class TextFileHandler {
231
249
  }
232
250
  else {
233
251
  if (offset > READ_PERFORMANCE_THRESHOLDS.DEEP_OFFSET_THRESHOLD) {
234
- return await this.readFromEstimatedPosition(filePath, offset, length, mimeType, includeStatusMessage, totalLines, signal);
252
+ return await this.readFromDeepOffset(filePath, offset, length, mimeType, includeStatusMessage, totalLines, signal);
235
253
  }
236
254
  else {
237
255
  return await this.readFromStartWithReadline(filePath, offset, length, mimeType, includeStatusMessage, totalLines, signal);
@@ -240,40 +258,40 @@ export class TextFileHandler {
240
258
  }
241
259
  }
242
260
  /**
243
- * Read last N lines efficiently by reading file backwards
261
+ * Read last N lines efficiently: find where they start by reading the file
262
+ * backwards, then read them from there as readline does for smaller files
244
263
  */
245
264
  async readLastNLinesReverse(filePath, n, mimeType, includeStatusMessage = true, fileTotalLines, signal) {
265
+ const start = await this.findLastLinesStart(filePath, n, signal);
266
+ return this.readFromEndWithReadline(filePath, n, mimeType, includeStatusMessage, fileTotalLines, signal, undefined, start);
267
+ }
268
+ /**
269
+ * Byte position where the last `n` lines start, found by reading 8 KB chunks
270
+ * backwards and finding line breaks by lineBreakBetween. A line break at the
271
+ * very end ends the last line instead of starting another.
272
+ */
273
+ async findLastLinesStart(filePath, n, signal) {
246
274
  const fd = await fs.open(filePath, 'r');
247
275
  try {
248
- const stats = await fd.stat();
249
- const fileSize = stats.size;
250
- let position = fileSize;
251
- let lines = [];
252
- let partialLine = '';
253
- while (position > 0 && lines.length < n) {
254
- if (signal?.aborted) {
255
- const err = new Error('Read aborted');
256
- err.code = 'ABORT_ERR';
257
- throw err;
258
- }
259
- const readSize = Math.min(READ_PERFORMANCE_THRESHOLDS.CHUNK_SIZE, position);
276
+ const { size } = await fd.stat();
277
+ const buffer = Buffer.alloc(READ_PERFORMANCE_THRESHOLDS.CHUNK_SIZE);
278
+ let position = size;
279
+ let breaks = 0;
280
+ let after = -1; // the byte after buffer[i]; -1 at the end of the file
281
+ while (position > 0) {
282
+ throwIfAborted(signal);
283
+ const readSize = Math.min(buffer.length, position);
260
284
  position -= readSize;
261
- const buffer = Buffer.alloc(readSize);
262
285
  await fd.read(buffer, 0, readSize, position);
263
- const chunk = buffer.toString('utf-8');
264
- const text = chunk + partialLine;
265
- const chunkLines = text.split('\n');
266
- partialLine = chunkLines.shift() || '';
267
- lines = chunkLines.concat(lines);
268
- }
269
- if (position === 0 && partialLine) {
270
- lines.unshift(partialLine);
286
+ for (let i = readSize - 1; i >= 0; i--) {
287
+ const byte = buffer[i];
288
+ if (after !== -1 && lineBreakBetween(byte, after) && ++breaks === n) {
289
+ return position + i + 1;
290
+ }
291
+ after = byte;
292
+ }
271
293
  }
272
- const result = lines.slice(-n);
273
- const content = includeStatusMessage
274
- ? `${this.generateEnhancedStatusMessage(result.length, -n, fileTotalLines, true)}\n\n${result.join('\n')}`
275
- : result.join('\n');
276
- return { content, mimeType, metadata: {} };
294
+ return 0;
277
295
  }
278
296
  finally {
279
297
  await fd.close();
@@ -312,15 +330,16 @@ export class TextFileHandler {
312
330
  return { content, mimeType, metadata: {} };
313
331
  }
314
332
  /**
315
- * Read from start/middle using readline
333
+ * Read from start/middle using readline. With `start`, reading begins at
334
+ * that byte, where line `startLine` begins.
316
335
  */
317
- async readFromStartWithReadline(filePath, offset, length, mimeType, includeStatusMessage = true, fileTotalLines, signal, encoding, start) {
336
+ async readFromStartWithReadline(filePath, offset, length, mimeType, includeStatusMessage = true, fileTotalLines, signal, encoding, start, startLine = 0) {
318
337
  const rl = createInterface({
319
338
  input: createReadStream(filePath, { signal, encoding, start }),
320
339
  crlfDelay: Infinity
321
340
  });
322
341
  const result = [];
323
- let lineNumber = 0;
342
+ let lineNumber = startLine;
324
343
  for await (const line of rl) {
325
344
  if (lineNumber >= offset && result.length < length) {
326
345
  result.push(line);
@@ -341,57 +360,42 @@ export class TextFileHandler {
341
360
  }
342
361
  }
343
362
  /**
344
- * Read from estimated byte position for very large files
363
+ * Read from a deep offset in a very large file: find the byte where line
364
+ * `offset` starts, then read from there with readline
345
365
  */
346
- async readFromEstimatedPosition(filePath, offset, length, mimeType, includeStatusMessage = true, fileTotalLines, signal) {
347
- // First, do a quick scan to estimate lines per byte
348
- const rl = createInterface({
349
- input: createReadStream(filePath, { signal }),
350
- crlfDelay: Infinity
351
- });
352
- let sampleLines = 0;
353
- let bytesRead = 0;
354
- for await (const line of rl) {
355
- bytesRead += Buffer.byteLength(line, 'utf-8') + 1;
356
- sampleLines++;
357
- if (bytesRead >= READ_PERFORMANCE_THRESHOLDS.SAMPLE_SIZE)
358
- break;
359
- }
360
- rl.close();
361
- if (sampleLines === 0) {
362
- return await this.readFromStartWithReadline(filePath, offset, length, mimeType, includeStatusMessage, fileTotalLines, signal);
363
- }
364
- // Estimate position
365
- const avgLineLength = bytesRead / sampleLines;
366
- const estimatedBytePosition = Math.floor(offset * avgLineLength);
366
+ async readFromDeepOffset(filePath, offset, length, mimeType, includeStatusMessage = true, fileTotalLines, signal) {
367
+ const start = await this.findLineStart(filePath, offset, signal);
368
+ return this.readFromStartWithReadline(filePath, offset, length, mimeType, includeStatusMessage, fileTotalLines, signal, undefined, start, offset);
369
+ }
370
+ /**
371
+ * Byte position where line `line` (0-based) starts, or the file size when
372
+ * the file has fewer lines. Counts line breaks by lineBreakBetween in raw
373
+ * bytes, which is much faster than reading lines.
374
+ */
375
+ async findLineStart(filePath, line, signal) {
376
+ if (line <= 0)
377
+ return 0;
367
378
  const fd = await fs.open(filePath, 'r');
368
379
  try {
369
- const stats = await fd.stat();
370
- const startPosition = Math.min(estimatedBytePosition, stats.size);
371
- const stream = createReadStream(filePath, { start: startPosition, signal });
372
- const rl2 = createInterface({
373
- input: stream,
374
- crlfDelay: Infinity
375
- });
376
- const result = [];
377
- let firstLineSkipped = false;
378
- for await (const line of rl2) {
379
- if (!firstLineSkipped && startPosition > 0) {
380
- firstLineSkipped = true;
381
- continue;
382
- }
383
- if (result.length < length) {
384
- result.push(line);
385
- }
386
- else {
387
- break;
380
+ const buffer = Buffer.alloc(READ_PERFORMANCE_THRESHOLDS.SCAN_CHUNK_SIZE);
381
+ let position = 0;
382
+ let breaks = 0;
383
+ let previous = -1;
384
+ for (;;) {
385
+ throwIfAborted(signal);
386
+ const { bytesRead } = await fd.read(buffer, 0, buffer.length, position);
387
+ if (bytesRead === 0)
388
+ return position;
389
+ for (let i = 0; i < bytesRead; i++) {
390
+ const byte = buffer[i];
391
+ // A line break before this byte: the next line starts here
392
+ if (lineBreakBetween(previous, byte) && ++breaks === line) {
393
+ return position + i;
394
+ }
395
+ previous = byte;
388
396
  }
397
+ position += bytesRead;
389
398
  }
390
- rl2.close();
391
- const content = includeStatusMessage
392
- ? `${this.generateEnhancedStatusMessage(result.length, offset, fileTotalLines, false)}\n\n${result.join('\n')}`
393
- : result.join('\n');
394
- return { content, mimeType, metadata: {} };
395
399
  }
396
400
  finally {
397
401
  await fd.close();
@@ -0,0 +1,3 @@
1
+ import type { ServerResult } from '../types.js';
2
+ /** The result as the client receives it: without structuredContent kept internal */
3
+ export declare function withoutInternalFacts(toolName: string, result: ServerResult): ServerResult;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Tools whose structuredContent is for Desktop Commander's own code and tests
3
+ * only: fixes added it next to the text, and a client must keep receiving what
4
+ * it received before (no new information in tool results). It is dropped here,
5
+ * before the result is recorded in the tool-call history or sent. Tools that
6
+ * already sent structuredContent (the read_file/edit widgets, get_config) are
7
+ * not listed and keep it.
8
+ */
9
+ const INTERNAL_STRUCTURED_CONTENT_TOOLS = new Set([
10
+ 'write_pdf',
11
+ 'start_process',
12
+ 'interact_with_process',
13
+ 'list_sessions',
14
+ 'start_search',
15
+ 'get_more_search_results',
16
+ ]);
17
+ /** The result as the client receives it: without structuredContent kept internal */
18
+ export function withoutInternalFacts(toolName, result) {
19
+ if (!INTERNAL_STRUCTURED_CONTENT_TOOLS.has(toolName) || !('structuredContent' in result))
20
+ return result;
21
+ const { structuredContent: _internal, ...sent } = result;
22
+ return sent;
23
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * A package only some files need, declared next to the code that uses it,
3
+ * whose load() loads it on first use (#715). Loading them before initialize
4
+ * took 25-90 s on one reporter's machine and timed the client out, and loading
5
+ * one inside the tool call that first needs it can take longer than a client
6
+ * waits. So the server preloads them right after initialize, one at a time
7
+ * (preloadFileSupport() in utils/files/factory.ts), and until one is loaded the
8
+ * calls that need it answer at once that it is still loading. preload() loads
9
+ * it on a later turn of the event loop, so a call that starts it answers
10
+ * first. `error` says why the last preload failed. Node keeps a failed
11
+ * import() failed, so a package loaded with import() then `needsRestart`.
12
+ */
13
+ export declare class LazyPackage<T> {
14
+ readonly name: string;
15
+ readonly support: string;
16
+ readonly load: () => T;
17
+ loaded: boolean;
18
+ error?: string;
19
+ needsRestart: boolean;
20
+ private running?;
21
+ constructor(name: string, support: string, load: () => T);
22
+ preload(): Promise<void>;
23
+ }
@@ -0,0 +1,42 @@
1
+ import { logger } from './logger.js';
2
+ /**
3
+ * A package only some files need, declared next to the code that uses it,
4
+ * whose load() loads it on first use (#715). Loading them before initialize
5
+ * took 25-90 s on one reporter's machine and timed the client out, and loading
6
+ * one inside the tool call that first needs it can take longer than a client
7
+ * waits. So the server preloads them right after initialize, one at a time
8
+ * (preloadFileSupport() in utils/files/factory.ts), and until one is loaded the
9
+ * calls that need it answer at once that it is still loading. preload() loads
10
+ * it on a later turn of the event loop, so a call that starts it answers
11
+ * first. `error` says why the last preload failed. Node keeps a failed
12
+ * import() failed, so a package loaded with import() then `needsRestart`.
13
+ */
14
+ export class LazyPackage {
15
+ constructor(name, support, load) {
16
+ this.name = name;
17
+ this.support = support;
18
+ this.load = load;
19
+ this.loaded = false;
20
+ this.needsRestart = false;
21
+ }
22
+ preload() {
23
+ this.running ?? (this.running = new Promise((resolve) => setImmediate(resolve)).then(async () => {
24
+ let loading;
25
+ try {
26
+ loading = this.load();
27
+ await loading;
28
+ this.loaded = true;
29
+ this.error = undefined;
30
+ }
31
+ catch (error) {
32
+ this.error = error instanceof Error ? error.message : String(error);
33
+ this.needsRestart = loading instanceof Promise;
34
+ logger.error(`Loading ${this.name} failed: ${this.error}`);
35
+ }
36
+ finally {
37
+ this.running = undefined;
38
+ }
39
+ }));
40
+ return this.running;
41
+ }
42
+ }
@@ -1,6 +1,7 @@
1
1
  import { execFile, spawn } from 'child_process';
2
2
  import os from 'os';
3
3
  import { logToStderr } from './logger.js';
4
+ import { resolveProgramPath } from './shell.js';
4
5
  /**
5
6
  * Open a URL in the default browser (cross-platform)
6
7
  * Uses execFile/spawn with args array to avoid shell injection
@@ -24,7 +25,7 @@ export async function openBrowser(url) {
24
25
  break;
25
26
  case 'win32':
26
27
  // Windows 'start' is a shell builtin, use spawn with shell but pass URL as separate arg
27
- spawn('cmd', ['/c', 'start', '', url], { shell: false, windowsHide: true }).on('close', (code) => {
28
+ spawn(resolveProgramPath('cmd'), ['/c', 'start', '', url], { shell: false, windowsHide: true }).on('close', (code) => {
28
29
  code === 0 ? resolve() : reject(new Error(`Exit code ${code}`));
29
30
  });
30
31
  break;
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * REPL and Process State Detection Utilities
3
- * Detects when processes are waiting for input vs finished vs running
3
+ * Detects from its output whether a running process is waiting for input.
4
+ * Whether it has finished is known from its exit, never from its output
5
+ * (see TerminalManager.getProcessState).
4
6
  */
5
7
  export interface ProcessState {
6
8
  isWaitingForInput: boolean;
@@ -10,13 +12,30 @@ export interface ProcessState {
10
12
  lastOutput: string;
11
13
  }
12
14
  /**
13
- * Analyze process output to determine current state
15
+ * How much of the end of the output state detection examines. A prompt is
16
+ * the last thing a process writes before it waits for input, so the end of
17
+ * the output decides the state; examining only this much keeps detection's
18
+ * cost the same however much output there is.
14
19
  */
15
- export declare function analyzeProcessState(output: string, pid?: number): ProcessState;
20
+ export declare const STATE_DETECTION_TAIL_CHARS = 4096;
16
21
  /**
17
- * Clean output by removing prompts and input echoes
22
+ * Analyze a running process's output to determine whether it is waiting for
23
+ * input. Output text never makes a process finished: a line such as
24
+ * "Error: retrying" doesn't end it.
25
+ *
26
+ * `output` is what the process wrote most recently. For a process writing to
27
+ * both stdout and stderr it can be the recent output of each stream that may
28
+ * have written last (see TerminalManager.getProcessState): their relative
29
+ * order is unknown, so the process is waiting for input if any of them ends
30
+ * in a prompt. Only the last STATE_DETECTION_TAIL_CHARS of each are examined.
18
31
  */
19
- export declare function cleanProcessOutput(output: string, inputSent?: string): string;
32
+ export declare function analyzeProcessState(output: string | readonly string[], pid?: number): ProcessState;
33
+ /**
34
+ * Clean output by removing prompts and input echoes. `readAtPrompt`: whether
35
+ * the process was waiting at a prompt when the input was sent; one that
36
+ * wasn't (a shell reading commands without a prompt) prints none for it.
37
+ */
38
+ export declare function cleanProcessOutput(output: string, inputSent?: string, readAtPrompt?: boolean): string;
20
39
  /**
21
40
  * Format process state for user display
22
41
  */