@wonderwhy-er/desktop-commander 0.2.52 → 0.3.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 (118) 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 +55 -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 +17 -3
  16. package/dist/remote-device/desktop-commander-integration.d.ts +1 -0
  17. package/dist/remote-device/desktop-commander-integration.js +19 -25
  18. package/dist/remote-device/device.d.ts +14 -0
  19. package/dist/remote-device/device.js +137 -30
  20. package/dist/remote-device/diagnostics/device-log.d.ts +63 -0
  21. package/dist/remote-device/diagnostics/device-log.js +219 -0
  22. package/dist/remote-device/diagnostics/redact.d.ts +1 -0
  23. package/dist/remote-device/diagnostics/redact.js +76 -0
  24. package/dist/remote-device/diagnostics/report.d.ts +118 -0
  25. package/dist/remote-device/diagnostics/report.js +748 -0
  26. package/dist/remote-device/diagnostics/upload.d.ts +11 -0
  27. package/dist/remote-device/diagnostics/upload.js +59 -0
  28. package/dist/remote-device/realtime-health-telemetry.d.ts +35 -0
  29. package/dist/remote-device/realtime-health-telemetry.js +110 -0
  30. package/dist/remote-device/remote-channel.d.ts +36 -4
  31. package/dist/remote-device/remote-channel.js +230 -50
  32. package/dist/remote-device/scripts/blocking-offline-update.js +108 -69
  33. package/dist/remote-device/transport-telemetry.d.ts +32 -0
  34. package/dist/remote-device/transport-telemetry.js +48 -0
  35. package/dist/search-manager.d.ts +239 -27
  36. package/dist/search-manager.js +746 -312
  37. package/dist/server.js +124 -222
  38. package/dist/terminal-manager.d.ts +138 -21
  39. package/dist/terminal-manager.js +300 -215
  40. package/dist/tools/config.d.ts +1 -1
  41. package/dist/tools/config.js +21 -70
  42. package/dist/tools/edit.js +12 -4
  43. package/dist/tools/filesystem.d.ts +30 -6
  44. package/dist/tools/filesystem.js +246 -140
  45. package/dist/tools/improved-process-tools.d.ts +9 -3
  46. package/dist/tools/improved-process-tools.js +171 -68
  47. package/dist/tools/pdf/extract-images.d.ts +2 -0
  48. package/dist/tools/pdf/extract-images.js +4 -1
  49. package/dist/tools/pdf/index.d.ts +5 -3
  50. package/dist/tools/pdf/index.js +4 -3
  51. package/dist/tools/pdf/lib/pdf2md.d.ts +8 -1
  52. package/dist/tools/pdf/lib/pdf2md.js +12 -5
  53. package/dist/tools/pdf/manipulations.d.ts +12 -1
  54. package/dist/tools/pdf/manipulations.js +17 -4
  55. package/dist/tools/pdf/markdown.d.ts +96 -0
  56. package/dist/tools/pdf/markdown.js +485 -20
  57. package/dist/tools/pdf/utils.d.ts +2 -2
  58. package/dist/tools/pdf/utils.js +4 -4
  59. package/dist/tools/process.js +8 -5
  60. package/dist/tools/schemas.d.ts +1 -11
  61. package/dist/tools/schemas.js +15 -14
  62. package/dist/types.d.ts +1 -1
  63. package/dist/ui/config-editor/config-editor-runtime.js +53 -53
  64. package/dist/ui/config-editor/src/app.js +2 -15
  65. package/dist/ui/file-preview/preview-runtime.js +190 -182
  66. package/dist/utils/ab-test.js +27 -9
  67. package/dist/utils/atomic-write.d.ts +14 -0
  68. package/dist/utils/atomic-write.js +80 -0
  69. package/dist/utils/capture.d.ts +17 -1
  70. package/dist/utils/capture.js +177 -68
  71. package/dist/utils/exit-process.d.ts +24 -0
  72. package/dist/utils/exit-process.js +31 -0
  73. package/dist/utils/feature-flags.js +2 -1
  74. package/dist/utils/files/base.d.ts +3 -1
  75. package/dist/utils/files/docx.d.ts +3 -0
  76. package/dist/utils/files/docx.js +24 -9
  77. package/dist/utils/files/excel.d.ts +10 -0
  78. package/dist/utils/files/excel.js +93 -33
  79. package/dist/utils/files/factory.d.ts +22 -1
  80. package/dist/utils/files/factory.js +59 -4
  81. package/dist/utils/files/image.d.ts +12 -4
  82. package/dist/utils/files/image.js +19 -8
  83. package/dist/utils/files/index.d.ts +5 -3
  84. package/dist/utils/files/index.js +4 -3
  85. package/dist/utils/files/pdf.js +18 -36
  86. package/dist/utils/files/text.d.ts +21 -5
  87. package/dist/utils/files/text.js +90 -86
  88. package/dist/utils/internal-facts.d.ts +3 -0
  89. package/dist/utils/internal-facts.js +23 -0
  90. package/dist/utils/lazy-package.d.ts +25 -0
  91. package/dist/utils/lazy-package.js +44 -0
  92. package/dist/utils/open-browser.js +2 -1
  93. package/dist/utils/process-detection.d.ts +24 -5
  94. package/dist/utils/process-detection.js +199 -89
  95. package/dist/utils/process-tree.d.ts +14 -0
  96. package/dist/utils/process-tree.js +223 -0
  97. package/dist/utils/rename.d.ts +9 -0
  98. package/dist/utils/rename.js +74 -0
  99. package/dist/utils/ripgrep-resolver.js +9 -14
  100. package/dist/utils/shell.d.ts +42 -0
  101. package/dist/utils/shell.js +187 -0
  102. package/dist/utils/system-info.d.ts +1 -0
  103. package/dist/utils/system-info.js +40 -25
  104. package/dist/utils/trackTools.js +2 -1
  105. package/dist/utils/usageTracker.d.ts +0 -39
  106. package/dist/utils/usageTracker.js +1 -161
  107. package/dist/version.d.ts +1 -1
  108. package/dist/version.js +1 -1
  109. package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -0
  110. package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -0
  111. package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -0
  112. package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -0
  113. package/package.json +32 -16
  114. package/vendor/telemetry-contract/README.md +56 -0
  115. package/vendor/telemetry-contract/package.json +32 -0
  116. package/vendor/telemetry-contract/transport.d.ts +38 -0
  117. package/vendor/telemetry-contract/transport.js +164 -0
  118. package/vendor/telemetry-contract/transport.test.js +39 -0
@@ -1,12 +1,33 @@
1
1
  import { configManager } from '../config-manager.js';
2
2
  import { featureFlagManager } from './feature-flags.js';
3
- // Cache for variant assignments (loaded once per session)
4
- const variantCache = {};
3
+ // Cache for variant assignments (loaded once per session). This map and the
4
+ // experiments map are keyed by experiment names from remote JSON, so they have
5
+ // no prototype: a name like __proto__ or constructor is an entry like any other.
6
+ const variantCache = Object.create(null);
5
7
  /**
6
- * Get experiments config from feature flags
8
+ * Get experiments config from feature flags.
9
+ * The config is remote JSON, so it is validated here once: every experiment
10
+ * comes back as { variants: WeightedVariant[] }, keeping only variants with a
11
+ * string name (an invalid or negative weight counts as 0). One malformed entry
12
+ * must not break the lookups for all the others.
7
13
  */
8
14
  function getExperiments() {
9
- return featureFlagManager.get('experiments', {});
15
+ const raw = featureFlagManager.get('experiments', {});
16
+ const experiments = Object.create(null);
17
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
18
+ return experiments;
19
+ for (const [name, experiment] of Object.entries(raw)) {
20
+ const rawVariants = Array.isArray(experiment?.variants) ? experiment.variants : [];
21
+ const variants = [];
22
+ for (const v of rawVariants) {
23
+ if (typeof v?.name !== 'string' || !v.name)
24
+ continue;
25
+ const weight = typeof v.weight === 'number' && Number.isFinite(v.weight) && v.weight > 0 ? v.weight : 0;
26
+ variants.push({ name: v.name, weight });
27
+ }
28
+ experiments[name] = { variants };
29
+ }
30
+ return experiments;
10
31
  }
11
32
  /**
12
33
  * Get user's variant for an experiment (cached, deterministic)
@@ -15,7 +36,7 @@ function getExperiments() {
15
36
  async function getVariant(experimentName) {
16
37
  const experiments = getExperiments();
17
38
  const experiment = experiments[experimentName];
18
- if (!experiment?.variants?.length)
39
+ if (!experiment?.variants.length)
19
40
  return null;
20
41
  // Check cache
21
42
  if (variantCache[experimentName]) {
@@ -68,11 +89,8 @@ export async function getABTestVariant(experimentName) {
68
89
  */
69
90
  export async function hasFeature(featureName) {
70
91
  const experiments = getExperiments();
71
- if (!experiments || typeof experiments !== 'object')
72
- return false;
73
92
  for (const [expName, experiment] of Object.entries(experiments)) {
74
- const variantNames = experiment?.variants?.map(v => v.name) || [];
75
- if (variantNames.includes(featureName)) {
93
+ if (experiment.variants.some(v => v.name === featureName)) {
76
94
  const variant = await getVariant(expName);
77
95
  return variant === featureName;
78
96
  }
@@ -0,0 +1,14 @@
1
+ export interface AtomicWriteOptions {
2
+ encoding?: BufferEncoding;
3
+ mode?: number;
4
+ /**
5
+ * A last check once the new content is on disk, before it replaces the file:
6
+ * if it throws, nothing is replaced and the write rejects with its error
7
+ */
8
+ beforeCommit?: () => void | Promise<void>;
9
+ }
10
+ /**
11
+ * Atomically replaces `filePath` with `data`. Resolves once the new content is
12
+ * committed; rejects (leaving the previous file intact) if it can't be.
13
+ */
14
+ export declare function writeFileAtomic(filePath: string, data: string | Uint8Array, options?: AtomicWriteOptions): Promise<void>;
@@ -0,0 +1,80 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { renameWithRetry } from './rename.js';
4
+ import { logger } from './logger.js';
5
+ /**
6
+ * Single place for crash-safe file writes. Data goes to a temp file next to
7
+ * the target and a rename swaps it in, so readers only ever see the previous
8
+ * or the new complete file — never a truncated one.
9
+ *
10
+ * - The temp file's data is flushed to disk before the rename: otherwise the
11
+ * new name can reach the disk before the data, and a crash or power loss
12
+ * leaves the file empty or zero-filled (#697, #692). On macOS/Linux the
13
+ * folder is flushed after the rename, so the rename itself survives.
14
+ * - Writes to the same file from this process run one after another, so the
15
+ * per-process temp name (`<file>.<pid>.tmp`) can't collide; the pid keeps
16
+ * separate processes off each other's temp file.
17
+ * - The swap goes through renameWithRetry, which rides out Windows' brief
18
+ * locks on files other processes have open.
19
+ */
20
+ const pendingWrites = new Map();
21
+ async function writeThroughTempFile(filePath, data, options) {
22
+ const tempPath = `${filePath}.${process.pid}.tmp`;
23
+ try {
24
+ const handle = await fs.open(tempPath, 'w', options.mode);
25
+ try {
26
+ await handle.writeFile(data, { encoding: options.encoding ?? 'utf8' });
27
+ await handle.sync();
28
+ }
29
+ finally {
30
+ await handle.close();
31
+ }
32
+ await options.beforeCommit?.();
33
+ await renameWithRetry(tempPath, filePath);
34
+ }
35
+ finally {
36
+ // After a successful rename the temp file is gone (ENOENT); after a failed
37
+ // write, removing it is best effort and the write's own error is what's reported
38
+ await fs.unlink(tempPath).catch(() => { });
39
+ }
40
+ await syncFolder(path.dirname(filePath));
41
+ }
42
+ /**
43
+ * macOS/Linux: flushes the folder, so a rename in it reaches the disk. Windows
44
+ * can't open a folder for flushing, and NTFS journals the rename itself. The
45
+ * new content is already committed when this runs, so a failure is logged,
46
+ * not reported as a failed write.
47
+ */
48
+ async function syncFolder(folder) {
49
+ if (process.platform === 'win32')
50
+ return;
51
+ try {
52
+ const handle = await fs.open(folder, 'r');
53
+ try {
54
+ await handle.sync();
55
+ }
56
+ finally {
57
+ await handle.close();
58
+ }
59
+ }
60
+ catch (error) {
61
+ logger.error(`Could not flush ${folder} after replacing a file in it: ${error instanceof Error ? error.message : String(error)}`);
62
+ }
63
+ }
64
+ /**
65
+ * Atomically replaces `filePath` with `data`. Resolves once the new content is
66
+ * committed; rejects (leaving the previous file intact) if it can't be.
67
+ */
68
+ export function writeFileAtomic(filePath, data, options = {}) {
69
+ const key = path.resolve(filePath);
70
+ const previous = pendingWrites.get(key) ?? Promise.resolve();
71
+ // The previous write's failure was already reported to its own caller; this one runs regardless
72
+ const write = previous.catch(() => { }).then(() => writeThroughTempFile(key, data, options));
73
+ pendingWrites.set(key, write);
74
+ // Bookkeeping only: the caller gets `write` itself, with its rejection
75
+ write.finally(() => {
76
+ if (pendingWrites.get(key) === write)
77
+ pendingWrites.delete(key);
78
+ }).catch(() => { });
79
+ return write;
80
+ }
@@ -1,5 +1,10 @@
1
+ import type { TransportParams } from '@desktop-commander/telemetry-contract/transport';
1
2
  export declare function runInUiOriginCallContext<T>(fn: () => T): T;
2
3
  export declare function isInsideUiOriginCall(): boolean;
4
+ /** Runs a tool call with its own set of known paths. */
5
+ export declare function runWithToolCallPaths<T>(fn: () => T): T;
6
+ /** Adds paths (strings, or arrays of them) to the current tool call's known paths. */
7
+ export declare function addToolCallPaths(...paths: unknown[]): void;
3
8
  /**
4
9
  * Hard kill-switch for telemetry via environment variable.
5
10
  *
@@ -13,7 +18,7 @@ export declare function isTelemetryDisabledByEnv(): boolean;
13
18
  * @param error Error object or string to sanitize
14
19
  * @returns An object with sanitized message and optional error code
15
20
  */
16
- export declare function sanitizeError(error: any): {
21
+ export declare function sanitizeError(error: any, knownPaths?: readonly string[]): {
17
22
  message: string;
18
23
  code?: string;
19
24
  };
@@ -23,7 +28,18 @@ export declare function sanitizeError(error: any): {
23
28
  * @param properties Optional event properties
24
29
  */
25
30
  export declare const captureBase: (captureURL: string, event: string, properties?: any) => Promise<void>;
31
+ /**
32
+ * Build the standard event properties used by the telemetry proxy.
33
+ * Extracted from captureBase so both paths get identical data.
34
+ */
35
+ /** Builds the telemetry payload properties for an event, with paths and errors sanitized. */
36
+ export declare const buildEventProperties: (properties?: any) => Promise<any>;
26
37
  export declare const capture: (event: string, properties?: any) => Promise<void>;
38
+ /**
39
+ * Send only contract-validated transport fields through the existing proxy sender,
40
+ * redacted like every other event (known paths, path properties, error text).
41
+ */
42
+ export declare const captureTransport: (event: string, properties: TransportParams) => Promise<void>;
27
43
  export declare const capture_call_tool: (event: string, properties?: any) => Promise<void>;
28
44
  export declare const capture_ui_event: (event: string, properties?: any) => Promise<void>;
29
45
  /**
@@ -1,4 +1,4 @@
1
- import { platform } from 'os';
1
+ import { platform, homedir } from 'os';
2
2
  import * as https from 'https';
3
3
  import { AsyncLocalStorage } from 'async_hooks';
4
4
  import { configManager, isTelemetryDisabledValue } from '../config-manager.js';
@@ -16,6 +16,25 @@ export function runInUiOriginCallContext(fn) {
16
16
  export function isInsideUiOriginCall() {
17
17
  return uiOriginCallContext.getStore() === true;
18
18
  }
19
+ // The paths the current tool call works on: its path arguments and what they
20
+ // resolve to. Telemetry replaces these exact values in an event's text before
21
+ // any pattern, so such a path goes whole, spaces and all, and the text around
22
+ // it stays (a pattern can't tell where an unquoted path with spaces ends).
23
+ const toolCallPaths = new AsyncLocalStorage();
24
+ /** Runs a tool call with its own set of known paths. */
25
+ export function runWithToolCallPaths(fn) {
26
+ return toolCallPaths.run(new Set(), fn);
27
+ }
28
+ /** Adds paths (strings, or arrays of them) to the current tool call's known paths. */
29
+ export function addToolCallPaths(...paths) {
30
+ const known = toolCallPaths.getStore();
31
+ if (!known)
32
+ return;
33
+ for (const value of paths.flat()) {
34
+ if (typeof value === 'string' && value.trim())
35
+ known.add(value);
36
+ }
37
+ }
19
38
  let VERSION = 'unknown';
20
39
  try {
21
40
  const versionModule = await import('../version.js');
@@ -52,7 +71,7 @@ export function isTelemetryDisabledByEnv() {
52
71
  * @param error Error object or string to sanitize
53
72
  * @returns An object with sanitized message and optional error code
54
73
  */
55
- export function sanitizeError(error) {
74
+ export function sanitizeError(error, knownPaths = []) {
56
75
  let errorMessage = '';
57
76
  let errorCode = undefined;
58
77
  if (error instanceof Error) {
@@ -69,15 +88,134 @@ export function sanitizeError(error) {
69
88
  else {
70
89
  errorMessage = 'Unknown error';
71
90
  }
72
- // Remove any file paths using regex
73
- // This pattern matches common path formats including Windows and Unix-style paths
74
- errorMessage = errorMessage.replace(/(?:\/|\\)[\w\d_.-\/\\]+/g, '[PATH]');
75
- errorMessage = errorMessage.replace(/[A-Za-z]:\\[\w\d_.-\/\\]+/g, '[PATH]');
76
91
  return {
77
- message: errorMessage,
92
+ message: redactPaths(errorMessage, knownPaths),
78
93
  code: errorCode
79
94
  };
80
95
  }
96
+ // Quoted text containing a separator is a path, whatever else it contains
97
+ // (Node quotes paths in fs errors: open 'C:\Users\John Smith\a.txt').
98
+ const QUOTED_PATH_PATTERN = /(['"`])(?:(?!\1)[^\r\n])*[\\/](?:(?!\1)[^\r\n])*\1/g;
99
+ // The last resort, for an unquoted path nothing else knows: the whole word
100
+ // around its first separator (C:\..., scripts/deploy.sh), running to
101
+ // whitespace or a quote; punctuation that ends it ("a.txt: denied", "a, b",
102
+ // "(see a.txt)") stays outside. A space is part of it when more path follows
103
+ // (C:\Users\John Smith\a.txt). A last name with a space can't be told from the
104
+ // text after it, which is why known paths are replaced first.
105
+ const PATH_PATTERN = /[^\s'"`\\/()[\]{}<>]*[\\/][^\s'"`]*?(?: +[^\s'"`\\/]+[\\/][^\s'"`]*?)*(?=[.,:;!?)\]}>]*(?:[\s'"`]|$))/g;
106
+ /**
107
+ * Matches one known path exactly, with either separator between its names,
108
+ * and only where it stands on its own: not inside a longer name before or
109
+ * after it. Null for a value too short to tell from ordinary text ("/", "~", "C:\").
110
+ */
111
+ function knownPathPattern(knownPath) {
112
+ const names = knownPath.trim().split(/[\\/]+/).filter(Boolean);
113
+ const letters = names.join('');
114
+ if (/^[A-Za-z]:$/.test(letters) || letters.replace(/[.~]/g, '').length < 2)
115
+ return null;
116
+ const source = names.map(name => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('[\\\\/]+');
117
+ const leadingSeparator = /^[\\/]/.test(knownPath.trim()) ? '[\\\\/]+' : '';
118
+ // Before it: the start, a separator, whitespace, a quote or an opening mark.
119
+ // After it: a separator, whitespace, a quote, a closing mark, clause
120
+ // punctuation followed by whitespace, or the end.
121
+ return new RegExp(`(?<![^\\s\\\\/'"\`(\\[=:,])${leadingSeparator}${source}(?=[\\\\/\\s'"\`)\\]]|[.,:;!?](?:\\s|$)|$)`, platform() === 'win32' ? 'gi' : 'g');
122
+ }
123
+ /**
124
+ * Replaces every file path in a message with [PATH], keeping the text around
125
+ * it. Known paths go first, each as a whole: the home folder (the part that
126
+ * identifies the user) and any the caller knows (the event's own path
127
+ * properties, the tool call's paths, the allowed folders), longest first so a
128
+ * known folder doesn't cut a known file inside it. Then quoted paths, then
129
+ * the last-resort pattern.
130
+ */
131
+ function redactPaths(message, knownPaths = []) {
132
+ return redactKnownPaths(message, knownPaths)
133
+ .replace(QUOTED_PATH_PATTERN, '$1[PATH]$1')
134
+ .replace(PATH_PATTERN, '[PATH]')
135
+ .replace(/(?:\[PATH\])+/g, '[PATH]');
136
+ }
137
+ /** Only the first step of redactPaths(): the home folder and the given paths, each whole. */
138
+ function redactKnownPaths(message, knownPaths = []) {
139
+ const known = [...new Set([homedir(), ...knownPaths])].sort((a, b) => b.length - a.length);
140
+ for (const knownPath of known) {
141
+ const pattern = knownPathPattern(knownPath);
142
+ if (pattern)
143
+ message = message.replace(pattern, '[PATH]');
144
+ }
145
+ return message;
146
+ }
147
+ // Properties that carry free text our capture() calls send (error text, a
148
+ // command line): redacted like `error`
149
+ const TEXT_PROPERTY_KEYS = ['message', 'errorMessage', 'errMsg', 'error_message', 'reason', 'command', 'commands'];
150
+ // Properties that hold paths: dropped from every event, after their values
151
+ // have been used to redact the event's messages
152
+ const PATH_PROPERTY_KEYS = ['path', 'filePath', 'directory', 'file_path', 'sourcePath', 'destinationPath', 'fullPath', 'rootPath'];
153
+ function isPathProperty(key) {
154
+ const lowerKey = key.toLowerCase();
155
+ return PATH_PROPERTY_KEYS.some(sk => lowerKey.includes(sk)) && lowerKey !== 'fileextension'; // keep fileExtension as it's safe
156
+ }
157
+ /** The string values (or strings in array values) of an event's path properties. */
158
+ function pathPropertyValues(properties) {
159
+ if (!properties || typeof properties !== 'object')
160
+ return [];
161
+ return Object.keys(properties)
162
+ .filter(isPathProperty)
163
+ .flatMap(key => [properties[key]].flat())
164
+ .filter((value) => typeof value === 'string');
165
+ }
166
+ /**
167
+ * Copies caller-supplied event properties into a telemetry-safe object.
168
+ * The copy is deep so we never alter objects the caller keeps using (e.g. error
169
+ * objects that are also returned to the AI). `error` is sanitized from the
170
+ * ORIGINAL value: an Error's name, message and code are not enumerable, so the
171
+ * JSON copy reduces it to {} and would report "Unknown error".
172
+ */
173
+ function sanitizeEventProperties(properties, knownPaths = []) {
174
+ let sanitizedProperties;
175
+ try {
176
+ sanitizedProperties = properties ? JSON.parse(JSON.stringify(properties)) : {};
177
+ }
178
+ catch {
179
+ // Properties JSON can't copy (circular, BigInt) are dropped; the event itself is still sent
180
+ sanitizedProperties = {};
181
+ }
182
+ // The exact paths this event knows: the ones passed in, and its own path
183
+ // properties (dropped below)
184
+ const known = [...knownPaths, ...pathPropertyValues(properties)];
185
+ const error = properties?.error;
186
+ if (error && (typeof error === 'object' || typeof error === 'string')) {
187
+ const sanitized = sanitizeError(error, known);
188
+ sanitizedProperties.error = sanitized.message;
189
+ if (sanitized.code)
190
+ sanitizedProperties.errorCode = sanitized.code;
191
+ }
192
+ // Every other string property (or string in an array property): free text
193
+ // is redacted like `error`; anything else gets its known absolute paths
194
+ // replaced, which touches nothing but those paths. A relative known path
195
+ // ("content") could equal an ordinary value, so it is only used on free text.
196
+ const knownAbsolute = known.filter(p => /[\\/]/.test(p));
197
+ for (const key of Object.keys(sanitizedProperties)) {
198
+ if (key === 'error' || isPathProperty(key))
199
+ continue;
200
+ const redact = TEXT_PROPERTY_KEYS.includes(key)
201
+ ? (text) => redactPaths(text, known)
202
+ : (text) => redactKnownPaths(text, knownAbsolute);
203
+ const value = sanitizedProperties[key];
204
+ if (typeof value === 'string') {
205
+ sanitizedProperties[key] = redact(value);
206
+ }
207
+ else if (Array.isArray(value)) {
208
+ sanitizedProperties[key] = value.map(item => typeof item === 'string' ? redact(item) : item);
209
+ }
210
+ }
211
+ // Remove any properties that might contain paths
212
+ for (const key of Object.keys(sanitizedProperties)) {
213
+ if (isPathProperty(key)) {
214
+ delete sanitizedProperties[key];
215
+ }
216
+ }
217
+ return sanitizedProperties;
218
+ }
81
219
  /**
82
220
  * Send an event to telemetry
83
221
  * @param event Event name
@@ -118,38 +256,7 @@ export const captureBase = async (captureURL, event, properties) => {
118
256
  if (sawOnboardingPage !== undefined) {
119
257
  clientContext = { ...clientContext, saw_onboarding_page: sawOnboardingPage };
120
258
  }
121
- // Create a deep copy of properties to avoid modifying the original objects
122
- // This ensures we don't alter error objects that are also returned to the AI
123
- let sanitizedProperties;
124
- try {
125
- sanitizedProperties = properties ? JSON.parse(JSON.stringify(properties)) : {};
126
- }
127
- catch (e) {
128
- sanitizedProperties = {};
129
- }
130
- // Sanitize error objects if present
131
- if (sanitizedProperties.error) {
132
- // Handle different types of error objects
133
- if (typeof sanitizedProperties.error === 'object' && sanitizedProperties.error !== null) {
134
- const sanitized = sanitizeError(sanitizedProperties.error);
135
- sanitizedProperties.error = sanitized.message;
136
- if (sanitized.code) {
137
- sanitizedProperties.errorCode = sanitized.code;
138
- }
139
- }
140
- else if (typeof sanitizedProperties.error === 'string') {
141
- sanitizedProperties.error = sanitizeError(sanitizedProperties.error).message;
142
- }
143
- }
144
- // Remove any properties that might contain paths
145
- const sensitiveKeys = ['path', 'filePath', 'directory', 'file_path', 'sourcePath', 'destinationPath', 'fullPath', 'rootPath'];
146
- for (const key of Object.keys(sanitizedProperties)) {
147
- const lowerKey = key.toLowerCase();
148
- if (sensitiveKeys.some(sensitiveKey => lowerKey.includes(sensitiveKey)) &&
149
- lowerKey !== 'fileextension') { // keep fileExtension as it's safe
150
- delete sanitizedProperties[key];
151
- }
152
- }
259
+ const sanitizedProperties = sanitizeEventProperties(properties);
153
260
  // Is MCP installed with DXT
154
261
  let isDXT = 'false';
155
262
  if (process.env.MCP_DXT) {
@@ -274,11 +381,20 @@ export const captureBase = async (captureURL, event, properties) => {
274
381
  // Silently fail - we don't want analytics issues to break functionality
275
382
  }
276
383
  };
384
+ /** The exact paths an event is redacted with first: the current tool call's and the allowed folders. */
385
+ const knownEventPaths = async () => {
386
+ const allowedDirectories = await configManager.getValue('allowedDirectories');
387
+ return [
388
+ ...(toolCallPaths.getStore() ?? []),
389
+ ...(Array.isArray(allowedDirectories) ? allowedDirectories.filter((dir) => typeof dir === 'string') : []),
390
+ ];
391
+ };
277
392
  /**
278
393
  * Build the standard event properties used by the telemetry proxy.
279
394
  * Extracted from captureBase so both paths get identical data.
280
395
  */
281
- const buildEventProperties = async (properties) => {
396
+ /** Builds the telemetry payload properties for an event, with paths and errors sanitized. */
397
+ export const buildEventProperties = async (properties) => {
282
398
  if (uniqueUserId === 'unknown') {
283
399
  uniqueUserId = await configManager.getOrCreateClientId();
284
400
  }
@@ -296,31 +412,7 @@ const buildEventProperties = async (properties) => {
296
412
  if (sawOnboardingPage !== undefined) {
297
413
  clientContext.saw_onboarding_page = sawOnboardingPage;
298
414
  }
299
- let sanitizedProperties;
300
- try {
301
- sanitizedProperties = properties ? JSON.parse(JSON.stringify(properties)) : {};
302
- }
303
- catch {
304
- sanitizedProperties = {};
305
- }
306
- if (sanitizedProperties.error) {
307
- if (typeof sanitizedProperties.error === 'object' && sanitizedProperties.error !== null) {
308
- const sanitized = sanitizeError(sanitizedProperties.error);
309
- sanitizedProperties.error = sanitized.message;
310
- if (sanitized.code)
311
- sanitizedProperties.errorCode = sanitized.code;
312
- }
313
- else if (typeof sanitizedProperties.error === 'string') {
314
- sanitizedProperties.error = sanitizeError(sanitizedProperties.error).message;
315
- }
316
- }
317
- const sensitiveKeys = ['path', 'filePath', 'directory', 'file_path', 'sourcePath', 'destinationPath', 'fullPath', 'rootPath'];
318
- for (const key of Object.keys(sanitizedProperties)) {
319
- const lowerKey = key.toLowerCase();
320
- if (sensitiveKeys.some(sk => lowerKey.includes(sk)) && lowerKey !== 'fileextension') {
321
- delete sanitizedProperties[key];
322
- }
323
- }
415
+ const sanitizedProperties = sanitizeEventProperties(properties, await knownEventPaths());
324
416
  let isDXT = 'false';
325
417
  if (process.env.MCP_DXT)
326
418
  isDXT = 'true';
@@ -441,9 +533,8 @@ const postTelemetryPayload = async (endpoint, payload) => {
441
533
  // can be silently dropped. If we need delivery guarantees on short-lived paths,
442
534
  // expose an awaitable variant or flush-before-exit hook.
443
535
  export const capture = async (event, properties) => {
444
- // Tool calls fired programmatically by the widget UIs must produce zero
445
- // telemetry — drop every event raised while serving one.
446
- if (isInsideUiOriginCall()) {
536
+ // Drop UI-origin calls and explicit opt-outs before preparing an event.
537
+ if (isInsideUiOriginCall() || isTelemetryDisabledByEnv()) {
447
538
  return;
448
539
  }
449
540
  void (async () => {
@@ -456,6 +547,24 @@ export const capture = async (event, properties) => {
456
547
  }
457
548
  })();
458
549
  };
550
+ /**
551
+ * Send only contract-validated transport fields through the existing proxy sender,
552
+ * redacted like every other event (known paths, path properties, error text).
553
+ */
554
+ export const captureTransport = async (event, properties) => {
555
+ if (isInsideUiOriginCall() || isTelemetryDisabledByEnv())
556
+ return;
557
+ void (async () => {
558
+ try {
559
+ if (uniqueUserId === 'unknown')
560
+ uniqueUserId = await configManager.getOrCreateClientId();
561
+ await sendToTelemetryProxy(event, sanitizeEventProperties(properties, await knownEventPaths()));
562
+ }
563
+ catch {
564
+ // Telemetry must not affect command handling.
565
+ }
566
+ })();
567
+ };
459
568
  export const capture_call_tool = capture;
460
569
  export const capture_ui_event = capture;
461
570
  /**
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Single place for ending the process on purpose. Use this instead of process.exit().
3
+ *
4
+ * process.exit() tears Node down at once, without waiting for work V8 still
5
+ * runs on background threads. On Windows that aborts the process with
6
+ * "Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), file src\win\async.c"
7
+ * and exit code 0xC0000409 instead of the one asked for, whenever V8 is still
8
+ * compiling WebAssembly, e.g. the HTTP parser fetch() compiles right after a
9
+ * download (nodejs/node#56645). An exit that happens because nothing is left
10
+ * to do waits for that work.
11
+ *
12
+ * So exitProcess() sets the exit code and lets Node exit on its own. If
13
+ * something keeps the process alive (stdin, a socket, a timer), process.exit()
14
+ * ends it after EXIT_GRACE_MS, by which time that background work is done.
15
+ * Either way 'exit' listeners run and pending stdout/stderr writes get the
16
+ * grace period to flush.
17
+ *
18
+ * Unlike process.exit() this returns, and the process keeps running for up to
19
+ * EXIT_GRACE_MS: callers return right after calling it. Only the first call
20
+ * counts; later calls (a second Ctrl+C, a timeout firing) keep its exit code.
21
+ */
22
+ /** Longest the process keeps running after exitProcess() */
23
+ export declare const EXIT_GRACE_MS = 1000;
24
+ export declare function exitProcess(code: number): void;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Single place for ending the process on purpose. Use this instead of process.exit().
3
+ *
4
+ * process.exit() tears Node down at once, without waiting for work V8 still
5
+ * runs on background threads. On Windows that aborts the process with
6
+ * "Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), file src\win\async.c"
7
+ * and exit code 0xC0000409 instead of the one asked for, whenever V8 is still
8
+ * compiling WebAssembly, e.g. the HTTP parser fetch() compiles right after a
9
+ * download (nodejs/node#56645). An exit that happens because nothing is left
10
+ * to do waits for that work.
11
+ *
12
+ * So exitProcess() sets the exit code and lets Node exit on its own. If
13
+ * something keeps the process alive (stdin, a socket, a timer), process.exit()
14
+ * ends it after EXIT_GRACE_MS, by which time that background work is done.
15
+ * Either way 'exit' listeners run and pending stdout/stderr writes get the
16
+ * grace period to flush.
17
+ *
18
+ * Unlike process.exit() this returns, and the process keeps running for up to
19
+ * EXIT_GRACE_MS: callers return right after calling it. Only the first call
20
+ * counts; later calls (a second Ctrl+C, a timeout firing) keep its exit code.
21
+ */
22
+ /** Longest the process keeps running after exitProcess() */
23
+ export const EXIT_GRACE_MS = 1000;
24
+ let exitCode;
25
+ export function exitProcess(code) {
26
+ if (exitCode !== undefined)
27
+ return;
28
+ exitCode = code;
29
+ process.exitCode = code;
30
+ setTimeout(() => process.exit(code), EXIT_GRACE_MS).unref();
31
+ }
@@ -3,6 +3,7 @@ import path from 'path';
3
3
  import { existsSync } from 'fs';
4
4
  import { CONFIG_FILE } from '../config.js';
5
5
  import { logger } from './logger.js';
6
+ import { writeFileAtomic } from './atomic-write.js';
6
7
  class FeatureFlagManager {
7
8
  constructor() {
8
9
  this.flags = {};
@@ -194,7 +195,7 @@ class FeatureFlagManager {
194
195
  if (!existsSync(configDir)) {
195
196
  await fs.mkdir(configDir, { recursive: true });
196
197
  }
197
- await fs.writeFile(this.cachePath, JSON.stringify(config, null, 2), 'utf8');
198
+ await writeFileAtomic(this.cachePath, JSON.stringify(config, null, 2));
198
199
  // Don't log here - this runs async and can cause issues with MCP clients
199
200
  }
200
201
  catch (error) {
@@ -69,6 +69,8 @@ export interface ReadOptions {
69
69
  range?: string;
70
70
  /** Whether to include status messages (default: true) */
71
71
  includeStatusMessage?: boolean;
72
+ /** Read an SVG as an image (base64), as the file preview widget draws it; otherwise it is text */
73
+ svgAsImage?: boolean;
72
74
  /** Optional AbortSignal to cancel an in-flight read (frees fd/thread on timeout). */
73
75
  signal?: AbortSignal;
74
76
  }
@@ -167,7 +169,7 @@ export interface FileInfo {
167
169
  /** File permissions (octal string) */
168
170
  permissions: string;
169
171
  /** File type classification */
170
- fileType: 'text' | 'excel' | 'image' | 'binary' | 'docx';
172
+ fileType: 'text' | 'excel' | 'image' | 'binary' | 'docx' | 'directory';
171
173
  /** Type-specific metadata */
172
174
  metadata?: FileMetadata;
173
175
  }
@@ -15,7 +15,10 @@
15
15
  *
16
16
  * Round-trip: DOCX → unzip → pretty-print → [outline or raw] → edit → compact → repack
17
17
  */
18
+ import type PizZip from 'pizzip';
19
+ import { LazyPackage } from '../lazy-package.js';
18
20
  import { FileHandler, FileResult, FileInfo, ReadOptions, EditResult } from './base.js';
21
+ export declare const pizzipPackage: LazyPackage<typeof PizZip>;
19
22
  export declare class DocxFileHandler implements FileHandler {
20
23
  private readonly extensions;
21
24
  canHandle(path: string): boolean;