@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,7 +1,7 @@
1
- import { execSync } from 'child_process';
2
1
  import { existsSync, chmodSync } from 'fs';
3
2
  import path from 'path';
4
3
  import os from 'os';
4
+ import { resolveShellPath } from './shell.js';
5
5
  let cachedRgPath = null;
6
6
  /**
7
7
  * Resolve ripgrep binary path with multiple fallback strategies
@@ -31,23 +31,18 @@ export async function getRipgrepPath() {
31
31
  catch (e) {
32
32
  // @vscode/ripgrep import or binary resolution failed, continue to fallbacks
33
33
  }
34
- // Strategy 2: Try system ripgrep using 'which' (Unix) or 'where' (Windows)
35
- try {
36
- const systemRg = process.platform === 'win32' ? 'rg.exe' : 'rg';
37
- const whichCmd = process.platform === 'win32' ? 'where' : 'which';
38
- const result = execSync(`${whichCmd} ${systemRg}`, { encoding: 'utf-8' }).trim().split(/\r?\n/)[0];
39
- if (result && existsSync(result)) {
40
- cachedRgPath = result;
41
- return result;
42
- }
43
- }
44
- catch (e) {
45
- // System rg not found via which
34
+ // Strategy 2: system ripgrep on PATH (never the working folder, which
35
+ // 'where' searched first on Windows)
36
+ const systemRg = resolveShellPath(process.platform === 'win32' ? 'rg.exe' : 'rg');
37
+ if (systemRg) {
38
+ cachedRgPath = systemRg;
39
+ return systemRg;
46
40
  }
47
41
  // Strategy 3: Try common installation paths
48
42
  const commonPaths = [];
49
43
  if (process.platform === 'win32') {
50
- commonPaths.push('C:\\Program Files\\Ripgrep\\rg.exe', 'C:\\Program Files (x86)\\Ripgrep\\rg.exe', path.join(os.homedir(), 'scoop', 'apps', 'ripgrep', 'current', 'rg.exe'), path.join(os.homedir(), '.cargo', 'bin', 'rg.exe'));
44
+ // Windows' own Program Files folders, which aren't always on C:
45
+ commonPaths.push(path.join(process.env.ProgramFiles ?? 'C:\\Program Files', 'Ripgrep', 'rg.exe'), path.join(process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)', 'Ripgrep', 'rg.exe'), path.join(os.homedir(), 'scoop', 'apps', 'ripgrep', 'current', 'rg.exe'), path.join(os.homedir(), '.cargo', 'bin', 'rg.exe'));
51
46
  }
52
47
  else {
53
48
  commonPaths.push('/usr/local/bin/rg', '/usr/bin/rg', path.join(os.homedir(), '.cargo', 'bin', 'rg'), '/opt/homebrew/bin/rg' // Apple Silicon Homebrew
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Resolves a shell or other program name ("pwsh", "bash.exe", "where") or path
3
+ * ("/bin/zsh") to an executable file. Bare names are searched in PATH's
4
+ * folders only, never the working folder. Returns null when it can't be found.
5
+ */
6
+ export declare function resolveShellPath(shell: string): string | null;
7
+ export declare function isShellAvailable(shell: string): boolean;
8
+ /**
9
+ * The full path to start a program by: the one found on PATH. Windows looks
10
+ * for a bare name ("powershell.exe", "cmd", "tasklist") in the working folder
11
+ * before PATH, so a file of that name there would run instead; every program
12
+ * Desktop Commander starts by name goes through here. On Windows a bare name
13
+ * not found on PATH is an error rather than a name Windows would look up in
14
+ * the working folder. A path (absolute, or with a folder in it) is kept as
15
+ * given, and so is a bare name elsewhere, where the working folder isn't searched.
16
+ */
17
+ export declare function resolveProgramPath(program: string): string;
18
+ /**
19
+ * The shell used when the user hasn't configured one.
20
+ * Windows: Windows PowerShell, falling back to %ComSpec%.
21
+ * macOS/Linux: $SHELL, falling back to the OS default shell.
22
+ */
23
+ export declare function getDefaultShell(): string;
24
+ /**
25
+ * Shells installed on this machine, default shell first. Only shells that
26
+ * resolve to an executable are returned.
27
+ */
28
+ export declare function detectAvailableShells(): string[];
29
+ /**
30
+ * Configuration for spawning a shell with appropriate flags
31
+ */
32
+ export interface ShellSpawnConfig {
33
+ executable: string;
34
+ args: string[];
35
+ useShellOption: string | boolean;
36
+ windowsVerbatim?: boolean;
37
+ }
38
+ /**
39
+ * Get the appropriate spawn configuration for a given shell
40
+ * This handles login shell flags for different shell types
41
+ */
42
+ export declare function getShellSpawnArgs(shellPath: string, command: string): ShellSpawnConfig;
@@ -0,0 +1,187 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ /**
5
+ * Single source of truth for shells: which shell is the default on this
6
+ * machine, which shells are installed, and how to invoke each of them.
7
+ * Config defaults, system info, process tools, the terminal manager and the
8
+ * config editor all derive their shell choices from here.
9
+ */
10
+ // Shell executables Windows can host. Which of them exist is resolved on PATH.
11
+ const WINDOWS_SHELLS = ['powershell.exe', 'pwsh.exe', 'cmd.exe', 'bash.exe'];
12
+ function isWindows() {
13
+ return os.platform() === 'win32';
14
+ }
15
+ function isExecutableFile(filePath) {
16
+ try {
17
+ fs.accessSync(filePath, isWindows() ? fs.constants.F_OK : fs.constants.X_OK);
18
+ return fs.statSync(filePath).isFile();
19
+ }
20
+ catch {
21
+ // Missing or not executable: this candidate isn't a usable shell, the next one is tried
22
+ return false;
23
+ }
24
+ }
25
+ function windowsExecutableExtensions() {
26
+ const fromEnv = (process.env.PATHEXT ?? '').split(';').map((ext) => ext.trim()).filter(Boolean);
27
+ return [...new Set(['.EXE', ...fromEnv])];
28
+ }
29
+ /**
30
+ * Resolves a shell or other program name ("pwsh", "bash.exe", "where") or path
31
+ * ("/bin/zsh") to an executable file. Bare names are searched in PATH's
32
+ * folders only, never the working folder. Returns null when it can't be found.
33
+ */
34
+ export function resolveShellPath(shell) {
35
+ const name = shell.trim();
36
+ if (!name)
37
+ return null;
38
+ if (path.isAbsolute(name) || name.includes('/') || name.includes('\\')) {
39
+ return isExecutableFile(name) ? name : null;
40
+ }
41
+ const extensions = isWindows() && !path.extname(name) ? windowsExecutableExtensions() : [''];
42
+ const pathDirs = (process.env.PATH ?? '').split(path.delimiter)
43
+ .map((dir) => dir.trim().replace(/^"(.*)"$/, '$1'))
44
+ .filter(Boolean);
45
+ for (const dir of pathDirs) {
46
+ for (const ext of extensions) {
47
+ const candidate = path.join(dir, name + ext);
48
+ if (isExecutableFile(candidate))
49
+ return candidate;
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ export function isShellAvailable(shell) {
55
+ return resolveShellPath(shell) !== null;
56
+ }
57
+ /**
58
+ * The full path to start a program by: the one found on PATH. Windows looks
59
+ * for a bare name ("powershell.exe", "cmd", "tasklist") in the working folder
60
+ * before PATH, so a file of that name there would run instead; every program
61
+ * Desktop Commander starts by name goes through here. On Windows a bare name
62
+ * not found on PATH is an error rather than a name Windows would look up in
63
+ * the working folder. A path (absolute, or with a folder in it) is kept as
64
+ * given, and so is a bare name elsewhere, where the working folder isn't searched.
65
+ */
66
+ export function resolveProgramPath(program) {
67
+ const resolved = resolveShellPath(program);
68
+ if (resolved)
69
+ return resolved;
70
+ const name = program.trim();
71
+ if (isWindows() && !name.includes('/') && !name.includes('\\')) {
72
+ throw new Error(`${name} was not found on PATH`);
73
+ }
74
+ return program;
75
+ }
76
+ /**
77
+ * The shell used when the user hasn't configured one.
78
+ * Windows: Windows PowerShell, falling back to %ComSpec%.
79
+ * macOS/Linux: $SHELL, falling back to the OS default shell.
80
+ */
81
+ export function getDefaultShell() {
82
+ if (isWindows()) {
83
+ if (isShellAvailable('powershell.exe'))
84
+ return 'powershell.exe';
85
+ return process.env.ComSpec || 'cmd.exe';
86
+ }
87
+ const userShell = process.env.SHELL;
88
+ if (userShell && isShellAvailable(userShell))
89
+ return userShell;
90
+ // $SHELL may be unset when launched from a GUI app such as Claude Desktop.
91
+ // zsh is the macOS default since Catalina; /bin/sh is guaranteed by POSIX.
92
+ return os.platform() === 'darwin' ? '/bin/zsh' : '/bin/sh';
93
+ }
94
+ // Login programs /etc/shells can list that don't run a command given with -c,
95
+ // the way every command here starts: terminal multiplexers (screen, tmux),
96
+ // git-shell (git commands only), and programs that refuse a login
97
+ const NOT_COMMAND_SHELLS = new Set(['nologin', 'false', 'true', 'sync', 'git-shell', 'screen', 'tmux']);
98
+ function readEtcShells() {
99
+ try {
100
+ return fs.readFileSync('/etc/shells', 'utf8')
101
+ .split(/\r?\n/)
102
+ .map((line) => line.trim())
103
+ .filter((line) => line.length > 0 && !line.startsWith('#'))
104
+ .filter((line) => !NOT_COMMAND_SHELLS.has(path.basename(line)));
105
+ }
106
+ catch {
107
+ // Best-effort discovery only: no readable /etc/shells means no extra shells to list
108
+ return [];
109
+ }
110
+ }
111
+ /**
112
+ * Shells installed on this machine, default shell first. Only shells that
113
+ * resolve to an executable are returned.
114
+ */
115
+ export function detectAvailableShells() {
116
+ const shells = new Set();
117
+ const add = (shell) => {
118
+ const value = shell?.trim();
119
+ if (value && isShellAvailable(value))
120
+ shells.add(value);
121
+ };
122
+ add(getDefaultShell());
123
+ if (isWindows()) {
124
+ WINDOWS_SHELLS.forEach(add);
125
+ }
126
+ else {
127
+ add(process.env.SHELL);
128
+ readEtcShells().forEach(add);
129
+ }
130
+ return [...shells];
131
+ }
132
+ /**
133
+ * Get the appropriate spawn configuration for a given shell
134
+ * This handles login shell flags for different shell types
135
+ */
136
+ export function getShellSpawnArgs(shellPath, command) {
137
+ const shellName = path.basename(shellPath).toLowerCase();
138
+ const executable = resolveProgramPath(shellPath);
139
+ // Unix shells with login flag support
140
+ if (shellName.includes('bash') || shellName.includes('zsh')) {
141
+ return {
142
+ executable,
143
+ args: ['-l', '-c', command],
144
+ useShellOption: false
145
+ };
146
+ }
147
+ // PowerShell Core (cross-platform, supports -Login)
148
+ if (shellName === 'pwsh' || shellName === 'pwsh.exe') {
149
+ return {
150
+ executable,
151
+ args: ['-Login', '-Command', command],
152
+ useShellOption: false
153
+ };
154
+ }
155
+ // Windows PowerShell 5.1 (no login flag support)
156
+ if (shellName === 'powershell' || shellName === 'powershell.exe') {
157
+ return {
158
+ executable,
159
+ args: ['-Command', command],
160
+ useShellOption: false
161
+ };
162
+ }
163
+ // CMD
164
+ if (shellName === 'cmd' || shellName === 'cmd.exe') {
165
+ return {
166
+ executable,
167
+ args: ['/c', command],
168
+ windowsVerbatim: true,
169
+ useShellOption: false
170
+ };
171
+ }
172
+ // Fish shell (uses -l for login, -c for command)
173
+ if (shellName.includes('fish')) {
174
+ return {
175
+ executable,
176
+ args: ['-l', '-c', command],
177
+ useShellOption: false
178
+ };
179
+ }
180
+ // Unknown/other shells - use shell option for safety
181
+ // This provides a fallback for shells we don't explicitly handle
182
+ return {
183
+ executable: command,
184
+ args: [],
185
+ useShellOption: executable
186
+ };
187
+ }
@@ -1,7 +1,8 @@
1
1
  import os from 'os';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
- import { execSync } from 'child_process';
4
+ import { execFileSync } from 'child_process';
5
+ import { getDefaultShell, resolveShellPath } from './shell.js';
5
6
  /**
6
7
  * Detect container environment and type
7
8
  */
@@ -370,8 +371,13 @@ function detectPythonInfo() {
370
371
  ? ['python', 'python3', 'py'] // Windows: 'python' is common, 'py' launcher
371
372
  : ['python3', 'python']; // Unix: prefer python3
372
373
  for (const cmd of pythonCommands) {
374
+ // The python on PATH, never one in the working folder (which Windows
375
+ // searches first for a bare name); not on PATH means not available
376
+ const program = resolveShellPath(cmd);
377
+ if (!program)
378
+ continue;
373
379
  try {
374
- const version = execSync(`${cmd} --version`, {
380
+ const version = execFileSync(program, ['--version'], {
375
381
  encoding: 'utf8',
376
382
  timeout: 5000,
377
383
  stdio: ['pipe', 'pipe', 'pipe']
@@ -403,12 +409,11 @@ export function getSystemInfo() {
403
409
  const containerDetection = detectContainerEnvironment();
404
410
  const mountPoints = containerDetection.isContainer ? discoverContainerMounts(containerDetection.isContainer) : [];
405
411
  let platformName;
406
- let defaultShell;
412
+ const defaultShell = getDefaultShell();
407
413
  let pathSeparator;
408
414
  let examplePaths;
409
415
  if (isWindows) {
410
416
  platformName = 'Windows';
411
- defaultShell = 'powershell.exe';
412
417
  pathSeparator = '\\';
413
418
  examplePaths = {
414
419
  home: 'C:\\Users\\username',
@@ -418,7 +423,6 @@ export function getSystemInfo() {
418
423
  }
419
424
  else if (isMacOS) {
420
425
  platformName = 'macOS';
421
- defaultShell = 'zsh';
422
426
  pathSeparator = '/';
423
427
  examplePaths = {
424
428
  home: '/Users/username',
@@ -428,7 +432,6 @@ export function getSystemInfo() {
428
432
  }
429
433
  else if (isLinux) {
430
434
  platformName = 'Linux';
431
- defaultShell = 'bash';
432
435
  pathSeparator = '/';
433
436
  examplePaths = {
434
437
  home: '/home/username',
@@ -439,7 +442,6 @@ export function getSystemInfo() {
439
442
  else {
440
443
  // Fallback for other Unix-like systems
441
444
  platformName = 'Unix';
442
- defaultShell = 'bash';
443
445
  pathSeparator = '/';
444
446
  examplePaths = {
445
447
  home: '/home/username',
@@ -1,6 +1,7 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { TOOL_CALL_FILE, TOOL_CALL_FILE_MAX_SIZE } from '../config.js';
4
+ import { renameWithRetry } from './rename.js';
4
5
  // Ensure the directory for the log file exists
5
6
  const logDir = path.dirname(TOOL_CALL_FILE);
6
7
  await fs.promises.mkdir(logDir, { recursive: true });
@@ -34,7 +35,7 @@ export async function trackToolCall(toolName, args) {
34
35
  const rotateTimestamp = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}_${String(date.getHours()).padStart(2, '0')}-${String(date.getMinutes()).padStart(2, '0')}-${String(date.getSeconds()).padStart(2, '0')}`;
35
36
  const newFileName = path.join(dirName, `${fileBase}_${rotateTimestamp}${fileExt}`);
36
37
  // Rename the current file
37
- await fs.promises.rename(TOOL_CALL_FILE, newFileName);
38
+ await renameWithRetry(TOOL_CALL_FILE, newFileName);
38
39
  }
39
40
  // Append to log file (if file was renamed, this will create a new file)
40
41
  await fs.promises.appendFile(TOOL_CALL_FILE, logEntry, 'utf8');
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.2.51";
1
+ export declare const VERSION = "0.3.1-alpha.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.2.51';
1
+ export const VERSION = '0.3.1-alpha.0';
@@ -0,0 +1,56 @@
1
+ # @desktop-commander/telemetry-contract
2
+
3
+ Transport observation request contract shared by telemetry-proxy and Remote MCP.
4
+ Import it as `@desktop-commander/telemetry-contract/transport`.
5
+
6
+ `parseRemoteTransportPayload(body)` validates 1–10 transport events for authenticated
7
+ `/remote/collect` requests with a top-level `user_id`.
8
+ `parseDeviceTransportPayload(body)` validates the same event shape for `/mp/collect`
9
+ with a top-level `client_id` and an event `device_id`. It assigns `source=device`.
10
+
11
+ Both functions return normalized events or throw before admitting any event. Event
12
+ names may match `params.stage` or `params.transport`, preserving older transport-named
13
+ events. Unknown and invalid optional parameters are removed. TypeScript declarations
14
+ describe the transport payloads; ordinary device and command telemetry are outside
15
+ this package.
16
+
17
+ ## Make a contract change
18
+
19
+ Edit `transport.js` and its matching `transport.d.ts` types, then update
20
+ `transport.test.js`. Keep changes to ordinary device and command telemetry out
21
+ of this package. From the telemetry-proxy root, run `npm test`, then commit and
22
+ push the change for review.
23
+
24
+ ## Publish a version
25
+
26
+ 1. On a clean branch containing the reviewed changes, run this from the
27
+ telemetry-proxy root for a compatible fix:
28
+
29
+ ```sh
30
+ cd packages/telemetry-contract
31
+ npm version patch
32
+ ```
33
+
34
+ `preversion` checks for tracked changes and runs the contract test.
35
+ `npm version` bumps `package.json`; the `version` script commits it and
36
+ creates the tag using the prefix in this package's `.npmrc`. `postversion`
37
+ pushes the commit and tag to `origin` together. If that push fails, fix the
38
+ cause and push the existing commit and tag; do not run `npm version` again.
39
+ Use `minor` for compatible additions or coordinate breaking changes with
40
+ consumers before a `major` release.
41
+
42
+ 2. Check the **Publish telemetry contract** GitHub Actions run. It verifies that
43
+ the tag matches `package.json`, runs the package test, and publishes to
44
+ GitHub Packages as `@desktop-commander/telemetry-contract@0.1.1`. Published
45
+ versions cannot be overwritten; bump the version for another release.
46
+ 3. In Remote MCP, with `GITHUB_PACKAGES_TOKEN` available to npm, update the
47
+ pinned dependency and lockfile, then run its tests:
48
+
49
+ ```sh
50
+ npm install --save-exact @desktop-commander/telemetry-contract@0.1.1
51
+ npm test
52
+ ```
53
+
54
+ Commit `package.json` and `package-lock.json` together. Remote MCP's Cloud
55
+ Build uses `MCP_REMOTE_GITHUB_PACKAGES_TOKEN` from Secret Manager to install
56
+ the private package. No tarball needs to be copied between repositories.
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@desktop-commander/telemetry-contract",
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/desktop-commander/telemetry-proxy.git",
8
+ "directory": "packages/telemetry-contract"
9
+ },
10
+ "publishConfig": {
11
+ "registry": "https://npm.pkg.github.com"
12
+ },
13
+ "exports": {
14
+ "./transport": {
15
+ "types": "./transport.d.ts",
16
+ "default": "./transport.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "transport.js",
21
+ "transport.d.ts"
22
+ ],
23
+ "scripts": {
24
+ "preversion": "git diff --quiet && git diff --cached --quiet && npm test",
25
+ "version": "git add package.json && git commit -m \"chore: release telemetry contract v${npm_new_version}\" && git tag \"$(npm config get tag-version-prefix)${npm_new_version}\"",
26
+ "postversion": "git push --atomic origin HEAD \"refs/tags/$(npm config get tag-version-prefix)${npm_new_version}\"",
27
+ "test": "node transport.test.js"
28
+ },
29
+ "engines": {
30
+ "node": ">=20"
31
+ }
32
+ }
@@ -0,0 +1,38 @@
1
+ export interface TransportParams {
2
+ call_id: string;
3
+ stage: string;
4
+ timestamp_utc: string;
5
+ monotonic_ms?: number;
6
+ transport?: 'mqtt' | 'broadcast';
7
+ device_id?: string;
8
+ [key: string]: unknown;
9
+ }
10
+
11
+ export interface TransportEvent {
12
+ name: string;
13
+ params: TransportParams;
14
+ }
15
+
16
+ export interface RemoteTransportPayload {
17
+ user_id: string;
18
+ timestamp_micros?: number;
19
+ events: TransportEvent[];
20
+ }
21
+
22
+ export interface DeviceTransportPayload {
23
+ client_id: string;
24
+ timestamp_micros?: number;
25
+ events: Array<{ name: string; params: TransportParams & { device_id: string } }>;
26
+ }
27
+
28
+ /** Identifies a transport batch before choosing the ordinary event path. */
29
+ export function hasTransportEvents(payload: unknown): boolean;
30
+
31
+ /** Validates one event and removes unknown or invalid optional fields. */
32
+ export function sanitizeTransportEvent(eventName: string, params: unknown): TransportParams;
33
+
34
+ /** Validates a 1–10 event authenticated backend batch. */
35
+ export function parseRemoteTransportPayload(payload: unknown): RemoteTransportPayload;
36
+
37
+ /** Validates a 1–10 event device batch and assigns source=device. */
38
+ export function parseDeviceTransportPayload(payload: unknown): DeviceTransportPayload;
@@ -0,0 +1,164 @@
1
+ const REQUIRED = ["call_id", "stage", "timestamp_utc"];
2
+ const OPTIONAL = [
3
+ "monotonic_ms",
4
+ "transport",
5
+ "notification_id",
6
+ "attempt_number",
7
+ "observation_id",
8
+ "source_process_id",
9
+ "schema_version",
10
+ "outcome",
11
+ "reason",
12
+ "duration_ms",
13
+ "retry_wait_ms",
14
+ "arrival_gap_ms",
15
+ "deadline_utc",
16
+ "tool_call_received_utc",
17
+ "tool_call_received_monotonic_ms",
18
+ "duplicate_count",
19
+ "dropped_count",
20
+ "source",
21
+ "device_id",
22
+ "environment",
23
+ "operation",
24
+ "operation_id",
25
+ "operation_attempt",
26
+ "result_source",
27
+ "tool_name",
28
+ ];
29
+
30
+ function isTimestamp(value) {
31
+ const iso = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
32
+ return typeof value === "string" && iso.test(value) && !Number.isNaN(Date.parse(value));
33
+ }
34
+
35
+ function validProperty(key, value) {
36
+ switch (key) {
37
+ case "source_process_id":
38
+ case "device_id":
39
+ case "call_id":
40
+ case "notification_id":
41
+ case "observation_id":
42
+ case "operation_id":
43
+ return typeof value === "string" && value.length > 0;
44
+ case "transport":
45
+ return value === "mqtt" || value === "broadcast";
46
+ case "stage":
47
+ case "outcome":
48
+ case "reason":
49
+ case "operation":
50
+ case "environment":
51
+ return typeof value === "string" && value.length > 0;
52
+ case "tool_name":
53
+ return typeof value === "string";
54
+ case "result_source":
55
+ return value === "doorbell" || value === "recovery";
56
+ case "operation_attempt":
57
+ case "schema_version":
58
+ return Number.isSafeInteger(value) && value >= 1;
59
+ case "source":
60
+ return value === "server" || value === "device";
61
+ case "attempt_number":
62
+ case "duplicate_count":
63
+ case "dropped_count":
64
+ return Number.isSafeInteger(value) && value >= 0;
65
+ case "timestamp_utc":
66
+ case "deadline_utc":
67
+ case "tool_call_received_utc":
68
+ return isTimestamp(value);
69
+ default:
70
+ return (
71
+ typeof value === "number" &&
72
+ Number.isFinite(value) &&
73
+ Math.abs(value) <= Number.MAX_SAFE_INTEGER &&
74
+ (key === "arrival_gap_ms" || value >= 0)
75
+ );
76
+ }
77
+ }
78
+
79
+ export function hasTransportEvents(payload) {
80
+ return (
81
+ Array.isArray(payload?.events) &&
82
+ payload.events.some((event) => {
83
+ const params = event?.params;
84
+ const transport = params?.transport;
85
+ return (
86
+ event?.name === "mqtt" ||
87
+ event?.name === "broadcast" ||
88
+ (["mqtt", "broadcast"].includes(transport) && (params?.call_id !== undefined || params?.stage !== undefined)) ||
89
+ (params?.call_id !== undefined && event?.name === params?.stage)
90
+ );
91
+ })
92
+ );
93
+ }
94
+
95
+ export function sanitizeTransportEvent(eventName, rawParams) {
96
+ if (
97
+ !rawParams ||
98
+ typeof rawParams !== "object" ||
99
+ Array.isArray(rawParams) ||
100
+ (eventName !== rawParams.stage && eventName !== rawParams.transport)
101
+ ) {
102
+ throw new Error("Invalid transport event");
103
+ }
104
+ const params = {};
105
+ for (const key of REQUIRED) {
106
+ if (!Object.hasOwn(rawParams, key) || !validProperty(key, rawParams[key])) {
107
+ throw new Error("Invalid transport event property");
108
+ }
109
+ params[key] = key.endsWith("_utc") ? new Date(rawParams[key]).toISOString() : rawParams[key];
110
+ }
111
+ for (const key of OPTIONAL) {
112
+ if (!Object.hasOwn(rawParams, key) || !validProperty(key, rawParams[key])) {
113
+ continue;
114
+ }
115
+ params[key] = key.endsWith("_utc") ? new Date(rawParams[key]).toISOString() : rawParams[key];
116
+ }
117
+ return params;
118
+ }
119
+
120
+ function parseTransportPayload(payload, isServer) {
121
+ if (
122
+ !payload ||
123
+ typeof payload !== "object" ||
124
+ Array.isArray(payload) ||
125
+ !Array.isArray(payload.events) ||
126
+ payload.events.length < 1 ||
127
+ payload.events.length > 10
128
+ ) {
129
+ throw new Error("Invalid events");
130
+ }
131
+ const userId = typeof payload.user_id === "string" ? payload.user_id.trim() : "";
132
+ if (isServer && (!userId || userId.length > 128)) {
133
+ throw new Error("Invalid user_id");
134
+ }
135
+ if (!isServer && (typeof payload.client_id !== "string" || !payload.client_id)) {
136
+ throw new Error("Invalid client_id");
137
+ }
138
+ const events = payload.events.map((event) => {
139
+ if (!event || typeof event !== "object" || Array.isArray(event)) {
140
+ throw new Error("Invalid event");
141
+ }
142
+ const raw = event.params;
143
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
144
+ throw new Error("Invalid params");
145
+ }
146
+ const params = sanitizeTransportEvent(event.name, isServer ? raw : { ...raw, source: "device" });
147
+ if (!isServer && !params.device_id) {
148
+ throw new Error("Missing device_id");
149
+ }
150
+ return { name: params.stage, params };
151
+ });
152
+ if (isServer) {
153
+ return { user_id: userId, events };
154
+ }
155
+ return { client_id: payload.client_id, events };
156
+ }
157
+
158
+ export function parseRemoteTransportPayload(payload) {
159
+ return parseTransportPayload(payload, true);
160
+ }
161
+
162
+ export function parseDeviceTransportPayload(payload) {
163
+ return parseTransportPayload(payload, false);
164
+ }