@masstensor/diagnose 0.3.0 → 0.5.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 (62) hide show
  1. package/README.md +77 -111
  2. package/USER_GUIDE.md +567 -0
  3. package/deploy/Caddyfile +15 -1
  4. package/dist/agent-command.d.ts +4 -0
  5. package/dist/agent-command.js +33 -0
  6. package/dist/agent.d.ts +2 -0
  7. package/dist/agent.js +115 -0
  8. package/dist/cli.js +178 -22
  9. package/dist/discover.js +1 -1
  10. package/dist/engine.d.ts +2 -0
  11. package/dist/engine.js +37 -4
  12. package/dist/history.d.ts +13 -0
  13. package/dist/history.js +57 -0
  14. package/dist/journal.d.ts +23 -1
  15. package/dist/journal.js +82 -5
  16. package/dist/maintenance.d.ts +2 -0
  17. package/dist/maintenance.js +46 -0
  18. package/dist/mcp.d.ts +1 -1
  19. package/dist/mcp.js +21 -18
  20. package/dist/operator.d.ts +2 -0
  21. package/dist/operator.js +17 -5
  22. package/dist/pairing.d.ts +40 -0
  23. package/dist/pairing.js +92 -0
  24. package/dist/peer.d.ts +4 -0
  25. package/dist/peer.js +10 -3
  26. package/dist/resources.js +47 -26
  27. package/dist/schema.d.ts +2 -0
  28. package/dist/schema.js +2 -2
  29. package/dist/skill.d.ts +8 -0
  30. package/dist/skill.js +58 -0
  31. package/dist/transfers.js +28 -11
  32. package/dist/util.d.ts +2 -0
  33. package/dist/util.js +16 -3
  34. package/examples/skills/device-troubleshooting/SKILL.md +35 -0
  35. package/examples/skills/device-troubleshooting/references/device-profile.md +16 -0
  36. package/examples/skills/owon.md +27 -0
  37. package/npm-shrinkwrap.json +215 -5
  38. package/package.json +23 -5
  39. package/scripts/setup-node.ps1 +54 -0
  40. package/scripts/setup-node.sh +52 -0
  41. package/src/agent-command.ts +25 -0
  42. package/src/agent.ts +79 -0
  43. package/src/cli.ts +53 -20
  44. package/src/discover.ts +1 -1
  45. package/src/engine.ts +19 -4
  46. package/src/history.ts +43 -0
  47. package/src/journal.ts +41 -5
  48. package/src/maintenance.ts +30 -0
  49. package/src/mcp.ts +18 -16
  50. package/src/operator.ts +15 -6
  51. package/src/pairing.ts +64 -0
  52. package/src/peer.ts +6 -4
  53. package/src/resources.ts +35 -13
  54. package/src/schema.ts +4 -4
  55. package/src/skill.ts +44 -0
  56. package/src/transfers.ts +14 -3
  57. package/src/util.ts +14 -3
  58. package/test/agent.test.ts +104 -0
  59. package/test/pairing.test.ts +124 -0
  60. package/test/review.test.ts +128 -0
  61. package/test/setup.test.ts +16 -0
  62. package/test/skill.test.ts +25 -0
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@masstensor/diagnose",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@masstensor/diagnose",
9
- "version": "0.3.0",
9
+ "version": "0.5.0",
10
+ "hasInstallScript": true,
10
11
  "license": "MIT",
11
12
  "dependencies": {
12
13
  "@modelcontextprotocol/sdk": "1.32.2",
@@ -21,14 +22,15 @@
21
22
  "diagnose-relay": "dist/relay-main.js"
22
23
  },
23
24
  "devDependencies": {
25
+ "@napi-rs/canvas": "0.1.80",
24
26
  "@types/node": "22.20.5",
25
27
  "@types/ws": "8.18.1",
28
+ "marked": "18.2.1",
26
29
  "typescript": "7.0.2"
27
30
  },
28
31
  "engines": {
29
- "node": ">=22.18.0"
30
- },
31
- "hasInstallScript": true
32
+ "node": ">=20.10.0"
33
+ }
32
34
  },
33
35
  "node_modules/@hono/node-server": {
34
36
  "version": "2.1.8",
@@ -82,6 +84,201 @@
82
84
  }
83
85
  }
84
86
  },
87
+ "node_modules/@napi-rs/canvas": {
88
+ "version": "0.1.80",
89
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.80.tgz",
90
+ "integrity": "sha512-DxuT1ClnIPts1kQx8FBmkk4BQDTfI5kIzywAaMjQSXfNnra5UFU9PwurXrl+Je3bJ6BGsp/zmshVVFbCmyI+ww==",
91
+ "dev": true,
92
+ "license": "MIT",
93
+ "workspaces": [
94
+ "e2e/*"
95
+ ],
96
+ "engines": {
97
+ "node": ">= 10"
98
+ },
99
+ "optionalDependencies": {
100
+ "@napi-rs/canvas-android-arm64": "0.1.80",
101
+ "@napi-rs/canvas-darwin-arm64": "0.1.80",
102
+ "@napi-rs/canvas-darwin-x64": "0.1.80",
103
+ "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.80",
104
+ "@napi-rs/canvas-linux-arm64-gnu": "0.1.80",
105
+ "@napi-rs/canvas-linux-arm64-musl": "0.1.80",
106
+ "@napi-rs/canvas-linux-riscv64-gnu": "0.1.80",
107
+ "@napi-rs/canvas-linux-x64-gnu": "0.1.80",
108
+ "@napi-rs/canvas-linux-x64-musl": "0.1.80",
109
+ "@napi-rs/canvas-win32-x64-msvc": "0.1.80"
110
+ }
111
+ },
112
+ "node_modules/@napi-rs/canvas-android-arm64": {
113
+ "version": "0.1.80",
114
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.80.tgz",
115
+ "integrity": "sha512-sk7xhN/MoXeuExlggf91pNziBxLPVUqF2CAVnB57KLG/pz7+U5TKG8eXdc3pm0d7Od0WreB6ZKLj37sX9muGOQ==",
116
+ "cpu": [
117
+ "arm64"
118
+ ],
119
+ "dev": true,
120
+ "license": "MIT",
121
+ "optional": true,
122
+ "os": [
123
+ "android"
124
+ ],
125
+ "engines": {
126
+ "node": ">= 10"
127
+ }
128
+ },
129
+ "node_modules/@napi-rs/canvas-darwin-arm64": {
130
+ "version": "0.1.80",
131
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.80.tgz",
132
+ "integrity": "sha512-O64APRTXRUiAz0P8gErkfEr3lipLJgM6pjATwavZ22ebhjYl/SUbpgM0xcWPQBNMP1n29afAC/Us5PX1vg+JNQ==",
133
+ "cpu": [
134
+ "arm64"
135
+ ],
136
+ "dev": true,
137
+ "license": "MIT",
138
+ "optional": true,
139
+ "os": [
140
+ "darwin"
141
+ ],
142
+ "engines": {
143
+ "node": ">= 10"
144
+ }
145
+ },
146
+ "node_modules/@napi-rs/canvas-darwin-x64": {
147
+ "version": "0.1.80",
148
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.80.tgz",
149
+ "integrity": "sha512-FqqSU7qFce0Cp3pwnTjVkKjjOtxMqRe6lmINxpIZYaZNnVI0H5FtsaraZJ36SiTHNjZlUB69/HhxNDT1Aaa9vA==",
150
+ "cpu": [
151
+ "x64"
152
+ ],
153
+ "dev": true,
154
+ "license": "MIT",
155
+ "optional": true,
156
+ "os": [
157
+ "darwin"
158
+ ],
159
+ "engines": {
160
+ "node": ">= 10"
161
+ }
162
+ },
163
+ "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
164
+ "version": "0.1.80",
165
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.80.tgz",
166
+ "integrity": "sha512-eyWz0ddBDQc7/JbAtY4OtZ5SpK8tR4JsCYEZjCE3dI8pqoWUC8oMwYSBGCYfsx2w47cQgQCgMVRVTFiiO38hHQ==",
167
+ "cpu": [
168
+ "arm"
169
+ ],
170
+ "dev": true,
171
+ "license": "MIT",
172
+ "optional": true,
173
+ "os": [
174
+ "linux"
175
+ ],
176
+ "engines": {
177
+ "node": ">= 10"
178
+ }
179
+ },
180
+ "node_modules/@napi-rs/canvas-linux-arm64-gnu": {
181
+ "version": "0.1.80",
182
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.80.tgz",
183
+ "integrity": "sha512-qwA63t8A86bnxhuA/GwOkK3jvb+XTQaTiVML0vAWoHyoZYTjNs7BzoOONDgTnNtr8/yHrq64XXzUoLqDzU+Uuw==",
184
+ "cpu": [
185
+ "arm64"
186
+ ],
187
+ "dev": true,
188
+ "license": "MIT",
189
+ "optional": true,
190
+ "os": [
191
+ "linux"
192
+ ],
193
+ "engines": {
194
+ "node": ">= 10"
195
+ }
196
+ },
197
+ "node_modules/@napi-rs/canvas-linux-arm64-musl": {
198
+ "version": "0.1.80",
199
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.80.tgz",
200
+ "integrity": "sha512-1XbCOz/ymhj24lFaIXtWnwv/6eFHXDrjP0jYkc6iHQ9q8oXKzUX1Lc6bu+wuGiLhGh2GS/2JlfORC5ZcXimRcg==",
201
+ "cpu": [
202
+ "arm64"
203
+ ],
204
+ "dev": true,
205
+ "license": "MIT",
206
+ "optional": true,
207
+ "os": [
208
+ "linux"
209
+ ],
210
+ "engines": {
211
+ "node": ">= 10"
212
+ }
213
+ },
214
+ "node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
215
+ "version": "0.1.80",
216
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.80.tgz",
217
+ "integrity": "sha512-XTzR125w5ZMs0lJcxRlS1K3P5RaZ9RmUsPtd1uGt+EfDyYMu4c6SEROYsxyatbbu/2+lPe7MPHOO/0a0x7L/gw==",
218
+ "cpu": [
219
+ "riscv64"
220
+ ],
221
+ "dev": true,
222
+ "license": "MIT",
223
+ "optional": true,
224
+ "os": [
225
+ "linux"
226
+ ],
227
+ "engines": {
228
+ "node": ">= 10"
229
+ }
230
+ },
231
+ "node_modules/@napi-rs/canvas-linux-x64-gnu": {
232
+ "version": "0.1.80",
233
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.80.tgz",
234
+ "integrity": "sha512-BeXAmhKg1kX3UCrJsYbdQd3hIMDH/K6HnP/pG2LuITaXhXBiNdh//TVVVVCBbJzVQaV5gK/4ZOCMrQW9mvuTqA==",
235
+ "cpu": [
236
+ "x64"
237
+ ],
238
+ "dev": true,
239
+ "license": "MIT",
240
+ "optional": true,
241
+ "os": [
242
+ "linux"
243
+ ],
244
+ "engines": {
245
+ "node": ">= 10"
246
+ }
247
+ },
248
+ "node_modules/@napi-rs/canvas-linux-x64-musl": {
249
+ "version": "0.1.80",
250
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.80.tgz",
251
+ "integrity": "sha512-x0XvZWdHbkgdgucJsRxprX/4o4sEed7qo9rCQA9ugiS9qE2QvP0RIiEugtZhfLH3cyI+jIRFJHV4Fuz+1BHHMg==",
252
+ "cpu": [
253
+ "x64"
254
+ ],
255
+ "dev": true,
256
+ "license": "MIT",
257
+ "optional": true,
258
+ "os": [
259
+ "linux"
260
+ ],
261
+ "engines": {
262
+ "node": ">= 10"
263
+ }
264
+ },
265
+ "node_modules/@napi-rs/canvas-win32-x64-msvc": {
266
+ "version": "0.1.80",
267
+ "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.80.tgz",
268
+ "integrity": "sha512-Z8jPsM6df5V8B1HrCHB05+bDiCxjE9QA//3YrkKIdVDEwn5RKaqOxCJDRJkl48cJbylcrJbW4HxZbTte8juuPg==",
269
+ "cpu": [
270
+ "x64"
271
+ ],
272
+ "dev": true,
273
+ "license": "MIT",
274
+ "optional": true,
275
+ "os": [
276
+ "win32"
277
+ ],
278
+ "engines": {
279
+ "node": ">= 10"
280
+ }
281
+ },
85
282
  "node_modules/@serialport/binding-mock": {
86
283
  "version": "10.2.2",
87
284
  "resolved": "https://registry.npmjs.org/@serialport/binding-mock/-/binding-mock-10.2.2.tgz",
@@ -1485,6 +1682,19 @@
1485
1682
  "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
1486
1683
  "license": "BSD-2-Clause"
1487
1684
  },
1685
+ "node_modules/marked": {
1686
+ "version": "18.2.1",
1687
+ "resolved": "https://registry.npmjs.org/marked/-/marked-18.2.1.tgz",
1688
+ "integrity": "sha512-ii4bxCTCqqwpT86XZWgJNs+ZnAIZksmLGYMViWA7PDIXYIeNo1x6cDdX3JOip9NM/cI6p8z57FxliACboTruMA==",
1689
+ "dev": true,
1690
+ "license": "MIT",
1691
+ "bin": {
1692
+ "marked": "bin/marked.js"
1693
+ },
1694
+ "engines": {
1695
+ "node": ">= 20"
1696
+ }
1697
+ },
1488
1698
  "node_modules/math-intrinsics": {
1489
1699
  "version": "1.1.0",
1490
1700
  "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@masstensor/diagnose",
3
- "version": "0.3.0",
4
- "description": "End-to-end encrypted, user-approved remote diagnostics over a blind relay",
3
+ "version": "0.5.0",
4
+ "description": "Agent-led remote troubleshooting and problem resolution, with end-to-end encryption and user-controlled permissions",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "publishConfig": {
@@ -9,7 +9,7 @@
9
9
  "registry": "https://registry.npmjs.org/"
10
10
  },
11
11
  "engines": {
12
- "node": ">=22.18.0"
12
+ "node": ">=20.10.0"
13
13
  },
14
14
  "bin": {
15
15
  "diagnose": "dist/cli.js",
@@ -18,6 +18,7 @@
18
18
  "files": [
19
19
  "dist",
20
20
  "README.md",
21
+ "USER_GUIDE.md",
21
22
  "LICENSE",
22
23
  "npm-shrinkwrap.json",
23
24
  "src",
@@ -25,14 +26,21 @@
25
26
  "test/*.test.ts",
26
27
  "test/noise-vector.json",
27
28
  "deploy",
28
- "test/CACOPHONY-LICENSE"
29
+ "test/CACOPHONY-LICENSE",
30
+ "examples/skills",
31
+ "scripts/setup-node.sh",
32
+ "scripts/setup-node.ps1"
29
33
  ],
30
34
  "scripts": {
31
35
  "build": "tsc",
32
36
  "check": "tsc --noEmit",
33
37
  "test": "npm run build && node --experimental-strip-types --test --test-concurrency=1 test/*.test.ts",
34
38
  "prepack": "npm run build",
35
- "postinstall": "node --input-type=module -e \"import { existsSync } from 'node:fs'; if (existsSync('dist/prepare-pty.js')) await (await import('./dist/prepare-pty.js')).preparePty();\""
39
+ "postinstall": "node --input-type=module -e \"import { existsSync } from 'node:fs'; if (existsSync('dist/prepare-pty.js')) await (await import('./dist/prepare-pty.js')).preparePty();\"",
40
+ "build:site": "tsc -p site/tsconfig.json && node --experimental-strip-types site/build.ts",
41
+ "check:site": "node --experimental-strip-types site/check.ts",
42
+ "video:render": "node --experimental-strip-types video/render-en.ts",
43
+ "video:preview": "node --experimental-strip-types video/render-en.ts --preview"
36
44
  },
37
45
  "dependencies": {
38
46
  "@modelcontextprotocol/sdk": "1.32.2",
@@ -43,8 +51,18 @@
43
51
  "zod": "4.6.7"
44
52
  },
45
53
  "devDependencies": {
54
+ "@napi-rs/canvas": "0.1.80",
46
55
  "@types/node": "22.20.5",
47
56
  "@types/ws": "8.18.1",
57
+ "marked": "18.2.1",
48
58
  "typescript": "7.0.2"
59
+ },
60
+ "repository": {
61
+ "type": "git",
62
+ "url": "git+https://github.com/zkwasm/diagnose.git"
63
+ },
64
+ "homepage": "https://diagnose.fenginwind.com",
65
+ "bugs": {
66
+ "url": "https://github.com/zkwasm/diagnose/issues"
49
67
  }
50
68
  }
@@ -0,0 +1,54 @@
1
+ # Run in Windows PowerShell. Installs a private runtime without administrator access.
2
+ $ErrorActionPreference = 'Stop'
3
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
4
+ if (Get-Command node -ErrorAction SilentlyContinue) {
5
+ Write-Host 'Existing Node.js detected. It will NOT be updated, replaced or reconfigured.'
6
+ $versionText = & node --version
7
+ Write-Host $versionText
8
+ $versionMatch = [regex]::Match([string]$versionText, '^v([0-9]+)\.([0-9]+)\.([0-9]+)$')
9
+ if ($LASTEXITCODE -ne 0 -or -not $versionMatch.Success -or ([int]$versionMatch.Groups[1].Value -lt 20) -or ([int]$versionMatch.Groups[1].Value -eq 20 -and [int]$versionMatch.Groups[2].Value -lt 10)) { throw 'Diagnose requires Node.js 20.10+. Nothing was changed. Ask your diagnostician about a separate compatible runtime.' }
10
+ foreach ($tool in @('npm.cmd', 'npx.cmd')) {
11
+ if (-not (Get-Command $tool -ErrorAction SilentlyContinue)) { throw "Existing Node.js is missing $tool. Nothing was changed; ask your diagnostician for help." }
12
+ & $tool --version
13
+ if ($LASTEXITCODE -ne 0) { throw "$tool verification failed. Nothing was changed." }
14
+ }
15
+ Write-Host 'Setup complete. Existing Node.js, npm and npx were reused without changes.'
16
+ return
17
+ }
18
+ $cpu = [Environment]::GetEnvironmentVariable('PROCESSOR_ARCHITEW6432')
19
+ if (-not $cpu) { $cpu = $env:PROCESSOR_ARCHITECTURE }
20
+ if (-not $cpu) { throw 'Could not identify CPU architecture.' }
21
+ switch ($cpu.ToUpperInvariant()) { 'AMD64' { $arch = 'x64' } 'ARM64' { $arch = 'arm64' } default { throw 'Unsupported CPU. Ask your diagnostician for help.' } }
22
+ $prefix = Join-Path $env:USERPROFILE '.diagnose\node'
23
+ New-Item -ItemType Directory -Force -Path $prefix | Out-Null
24
+ $stage = Join-Path $prefix ('.setup-' + [Guid]::NewGuid().ToString())
25
+ New-Item -ItemType Directory -Path $stage | Out-Null
26
+ try {
27
+ Write-Host 'Finding the current Node.js 22 release on nodejs.org...'
28
+ $manifest = (Invoke-WebRequest -UseBasicParsing -Uri 'https://nodejs.org/dist/latest-v22.x/SHASUMS256.txt').Content
29
+ $match = [regex]::Match($manifest, "(?m)^([a-f0-9]{64})\s+(node-v22\.([0-9]+)\.[0-9]+-win-$arch\.zip)\s*$")
30
+ if (-not $match.Success -or [int]$match.Groups[3].Value -lt 18) { throw 'Could not identify a supported official release.' }
31
+ $filename = $match.Groups[2].Value
32
+ $archive = Join-Path $stage 'node.zip'
33
+ $release = [regex]::Match($filename, '^node-(v22\.[0-9]+\.[0-9]+)-').Groups[1].Value
34
+ Write-Host "Downloading $filename from nodejs.org..."
35
+ Invoke-WebRequest -UseBasicParsing -Uri ('https://nodejs.org/dist/' + $release + '/' + $filename) -OutFile $archive
36
+ if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -ne $match.Groups[1].Value) { throw 'Checksum mismatch. Nothing was installed. Run setup again.' }
37
+ Write-Host 'Checksum verified. Installing into your private .diagnose\node directory...'
38
+ Expand-Archive -LiteralPath $archive -DestinationPath $stage
39
+ $directory = $filename.Substring(0, $filename.Length - 4)
40
+ $destination = Join-Path $prefix $directory
41
+ if (-not (Test-Path -LiteralPath $destination)) { Move-Item -LiteralPath (Join-Path $stage $directory) -Destination $destination }
42
+ $userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
43
+ if (($userPath -split ';') -notcontains $destination) { [Environment]::SetEnvironmentVariable('Path', ($destination + ';' + $userPath), 'User') }
44
+ $env:Path = $destination + ';' + $env:Path
45
+ } finally { Remove-Item -LiteralPath $stage -Recurse -Force }
46
+
47
+ Write-Host 'Checking Node.js, npm and npx:'
48
+ & node --version
49
+ if ($LASTEXITCODE -ne 0) { throw 'Node.js verification failed.' }
50
+ & npm.cmd --version
51
+ if ($LASTEXITCODE -ne 0) { throw 'npm verification failed.' }
52
+ & npx.cmd --version
53
+ if ($LASTEXITCODE -ne 0) { throw 'npx verification failed.' }
54
+ Write-Host 'Setup complete. You can now run: npx.cmd @masstensor/diagnose@latest start'
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env bash
2
+ # Install a private Node.js 22 runtime without requiring Node, npm or sudo.
3
+ set -euo pipefail
4
+ umask 077
5
+ if command -v node >/dev/null 2>&1; then
6
+ echo 'Existing Node.js detected. It will NOT be updated, replaced or reconfigured.'
7
+ node --version
8
+ if ! node -e 'const v=process.versions.node.split(".").map(Number);process.exit(v[0]>20||(v[0]===20&&v[1]>=10)?0:1)' 2>/dev/null; then
9
+ echo 'Diagnose requires Node.js 20.10+. Your installation was left unchanged. Ask your diagnostician about a separate compatible runtime.' >&2
10
+ exit 1
11
+ fi
12
+ for tool in npm npx; do
13
+ if ! command -v "$tool" >/dev/null 2>&1 || ! "$tool" --version; then echo "Existing Node.js is missing working $tool. Nothing was changed; ask your diagnostician for help." >&2; exit 1; fi
14
+ done
15
+ echo 'Setup complete. Existing Node.js, npm and npx were reused without changes.'
16
+ exit 0
17
+ fi
18
+ prefix="$HOME/.diagnose/node"
19
+ mkdir -p "$prefix"
20
+ case "$(uname -s)" in Darwin) platform=darwin ;; Linux) platform=linux ;; *) echo 'Use setup-node.ps1 on Windows.' >&2; exit 1 ;; esac
21
+ case "$(uname -m)" in arm64|aarch64) arch=arm64 ;; x86_64|amd64) arch=x64 ;; *) echo 'Unsupported CPU. Ask your diagnostician for help.' >&2; exit 1 ;; esac
22
+ for tool in curl tar awk; do command -v "$tool" >/dev/null || { echo "Missing $tool. Ask your diagnostician to install it." >&2; exit 1; }; done
23
+ stage=$(mktemp -d "$prefix/.setup.XXXXXX")
24
+ trap 'rm -rf "$stage"' EXIT
25
+ fetch() { curl --proto '=https' --proto-redir '=https' --tlsv1.2 --fail --show-error --location --connect-timeout 20 --max-time 600 "$1" -o "$2"; }
26
+ echo 'Finding the current Node.js 22 release on nodejs.org...'
27
+ fetch https://nodejs.org/dist/latest-v22.x/SHASUMS256.txt "$stage/checksums"
28
+ filename=$(awk -v suffix="-$platform-$arch.tar.gz" '$2 ~ /^node-v22\.[0-9]+\.[0-9]+-/ && substr($2,length($2)-length(suffix)+1)==suffix {print $2;exit}' "$stage/checksums")
29
+ [[ "$filename" =~ ^node-v22\.([0-9]+)\.[0-9]+-(darwin|linux)-(arm64|x64)\.tar\.gz$ ]] && [ "${BASH_REMATCH[1]}" -ge 18 ] || { echo 'Could not identify a supported official release.' >&2; exit 1; }
30
+ expected=$(awk -v file="$filename" '$2==file {print $1;exit}' "$stage/checksums")
31
+ echo "Downloading $filename from nodejs.org..."
32
+ release=${filename#node-}; release=${release%%-*}
33
+ fetch "https://nodejs.org/dist/$release/$filename" "$stage/node.tar.gz"
34
+ if command -v shasum >/dev/null; then actual=$(shasum -a 256 "$stage/node.tar.gz" | awk '{print $1}'); else actual=$(sha256sum "$stage/node.tar.gz" | awk '{print $1}'); fi
35
+ [ "$actual" = "$expected" ] || { echo 'Checksum mismatch. Nothing was installed. Run the setup command again.' >&2; exit 1; }
36
+ echo 'Checksum verified. Installing into your private .diagnose/node directory...'
37
+ tar -xzf "$stage/node.tar.gz" -C "$stage"
38
+ directory=${filename%.tar.gz}
39
+ "$stage/$directory/bin/node" --version
40
+ if [ ! -e "$prefix/$directory" ]; then mv "$stage/$directory" "$prefix/$directory"; fi
41
+ printf 'export PATH="$HOME/.diagnose/node/%s/bin:$PATH"\n' "$directory" > "$prefix/env"
42
+ line='[ ! -f "$HOME/.diagnose/node/env" ] || . "$HOME/.diagnose/node/env"'
43
+ if [ "$platform" = darwin ]; then profiles=("$HOME/.zshrc" "$HOME/.bash_profile"); else profiles=("$HOME/.bashrc" "$HOME/.profile"); fi
44
+ for profile in "${profiles[@]}"; do
45
+ if ! grep -Fqx "$line" "$profile" 2>/dev/null; then printf '\n# Diagnose private Node.js runtime\n%s\n' "$line" >> "$profile"; fi
46
+ done
47
+ . "$prefix/env"
48
+ echo 'Checking Node.js, npm and npx:'
49
+ node --version
50
+ npm --version
51
+ npx --version
52
+ echo 'Setup complete. You can now run: npx @masstensor/diagnose@latest start'
@@ -0,0 +1,25 @@
1
+ import { access, readFile } from 'node:fs/promises';
2
+ import { join, resolve, relative, isAbsolute, dirname } from 'node:path';
3
+
4
+ // npm's Windows .cmd wrappers are not executables. Resolve their Node entry
5
+ // point instead of interpolating user prompts or JSON through cmd.exe.
6
+ export async function agentCommand(name: string, args: string[], env: NodeJS.ProcessEnv, platform: string = process.platform): Promise<{ command: string; args: string[] }> {
7
+ if (platform !== 'win32') return { command: name, args };
8
+ const path = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] ?? '';
9
+ for (const directory of path.split(';').filter(Boolean)) {
10
+ for (const extension of ['.exe', '.cmd']) {
11
+ const candidate = join(directory.replace(/^"|"$/g, ''), name + extension);
12
+ try { await access(candidate); } catch { continue; }
13
+ if (extension === '.exe') return { command: candidate, args };
14
+ const wrapper = await readFile(candidate, 'utf8');
15
+ const match = /"%dp0%[\\/]([^"\r\n]+\.(?:cjs|mjs|js))"/i.exec(wrapper);
16
+ if (!match) throw new Error(`Unsupported ${name}.cmd launcher. Install the official npm package or native executable; Diagnose will not pass prompts through a shell.`);
17
+ const entry = resolve(dirname(candidate), match[1].replace(/\\/g, '/'));
18
+ const diff = relative(dirname(candidate), entry);
19
+ if (diff.startsWith('..') || isAbsolute(diff)) throw new Error('Agent npm entry point is outside its installation directory');
20
+ await access(entry);
21
+ return { command: process.execPath, args: [entry, ...args] };
22
+ }
23
+ }
24
+ throw new Error(`${name} was not found on PATH. Install and sign in to its CLI first.`);
25
+ }
package/src/agent.ts ADDED
@@ -0,0 +1,79 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { constants } from 'node:os';
3
+ import { mkdtemp, readFile, writeFile, rm, mkdir, readdir, symlink, stat, copyFile } from 'node:fs/promises';
4
+ import { tmpdir, homedir } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { parseArgs } from 'node:util';
8
+ import { PairingStore } from './pairing.js';
9
+ import { loadSkill, skillPrompt } from './skill.js';
10
+ import { agentCommand } from './agent-command.js';
11
+
12
+ export const agentUsage = 'diagnose agent codex|claude|gemini [--device NAME] [--skill FILE.md|DIRECTORY] [--relay URL] [-- agent arguments...]';
13
+
14
+ export async function launchAgent(argv: string[]): Promise<number> {
15
+ const separator = argv.indexOf('--');
16
+ const extra = separator < 0 ? [] : argv.slice(separator + 1);
17
+ const { positionals, values } = parseArgs({ args: separator < 0 ? argv : argv.slice(0, separator), allowPositionals: true, options: { relay: { type: 'string' }, skill: { type: 'string' }, device: { type: 'string' }, help: { type: 'boolean', short: 'h' } } });
18
+ if (values.help || !positionals.length) { console.log(agentUsage); return 0; }
19
+ const [agent] = positionals;
20
+ if (positionals.length !== 1 || !['codex', 'claude', 'gemini'].includes(agent)) throw new Error(agentUsage);
21
+ if (values.device) new PairingStore().get(values.device, 'operator');
22
+ const skill = values.skill === undefined ? undefined : await loadSkill(values.skill);
23
+ if (skill && agent === 'gemini' && extra.some(arg => ['-p', '--prompt', '-i', '--prompt-interactive'].includes(arg) || arg.startsWith('--prompt=') || arg.startsWith('--prompt-interactive='))) throw new Error('--skill supplies the initial task; do not also pass a Gemini prompt option');
24
+ if (values.relay) {
25
+ const url = new URL(values.relay);
26
+ if (!['https:', 'wss:'].includes(url.protocol) && !(['http:', 'ws:'].includes(url.protocol) && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) throw new Error('Relay requires HTTPS/WSS, except loopback tests');
27
+ if (url.username || url.password) throw new Error('Relay URL must not contain credentials');
28
+ }
29
+ // Reuse this exact installed version. No global install or extra npx download.
30
+ const server = { command: process.execPath, args: [fileURLToPath(new URL('./cli.js', import.meta.url)), 'mcp', ...(values.relay ? [values.relay] : []), ...(values.device ? ['--device', values.device] : [])] };
31
+ const env = { ...process.env }; let directory: string | undefined;
32
+ try {
33
+ let prompt: string | undefined, taskDirectory: string | undefined;
34
+ if (skill) {
35
+ directory = await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
36
+ taskDirectory = join(directory, 'task'); await mkdir(taskDirectory, { mode: 0o700 });
37
+ const snapshot = join(taskDirectory, 'task.json');
38
+ await writeFile(snapshot, JSON.stringify(skill), { mode: 0o600 });
39
+ prompt = skillPrompt(snapshot) + (values.device ? '\nDiagnose MCP is already configured for the saved device ' + JSON.stringify(values.device) + '. Use its tools directly; do not ask for a pairing code. If unavailable, ask the user to start or resume their probe.' : '');
40
+ console.error('Starting the selected skill. Its instructions and referenced data may be sent to your chosen AI provider. Remote pairing and existing permissions still apply.');
41
+ }
42
+ let args: string[];
43
+ if (agent === 'codex') args = ['-c', `mcp_servers.diagnose.command=${JSON.stringify(server.command)}`, '-c', `mcp_servers.diagnose.args=${JSON.stringify(server.args)}`, ...extra];
44
+ else if (agent === 'claude') args = ['--mcp-config', JSON.stringify({ mcpServers: { diagnose: server } }), ...extra];
45
+ else {
46
+ // Gemini has no --mcp-config. Isolate its user settings, retain its real
47
+ // administrator policy and reuse existing login/history through links.
48
+ const originalRoot = resolve(env.GEMINI_CLI_HOME ?? homedir(), '.gemini');
49
+ const original = join(originalRoot, 'settings.json');
50
+ let settings: Record<string, unknown> = {};
51
+ try { settings = JSON.parse((await readFile(original, 'utf8')).replace(/^\uFEFF/, '')); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw new Error(`Cannot read Gemini user settings: ${(error as Error).message}`); }
52
+ if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw new Error('Gemini user settings must be a JSON object');
53
+ directory ??= await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
54
+ const configRoot = join(directory, '.gemini'); await mkdir(configRoot, { mode: 0o700 });
55
+ let entries: string[] = [];
56
+ try { entries = await readdir(originalRoot); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
57
+ for (const name of entries) if (name !== 'settings.json') {
58
+ const source = join(originalRoot, name), target = join(configRoot, name);
59
+ if (process.platform === 'win32') {
60
+ if ((await stat(source)).isDirectory()) await symlink(source, target, 'junction');
61
+ else await copyFile(source, target);
62
+ } else await symlink(source, target);
63
+ }
64
+ const path = join(configRoot, 'settings.json');
65
+ await writeFile(path, JSON.stringify({ ...settings, mcpServers: { ...(settings.mcpServers as object ?? {}), diagnose: server } }), { mode: 0o600 });
66
+ env.GEMINI_CLI_HOME = directory; args = extra;
67
+ }
68
+ if (prompt) args = agent === 'gemini' ? [...args, '--include-directories', taskDirectory!, '--prompt-interactive', prompt] : [...args, '--add-dir', taskDirectory!, '--', prompt];
69
+ const command = await agentCommand(agent, args, env);
70
+ return await new Promise<number>((resolveExit, reject) => {
71
+ const child = spawn(command.command, command.args, { env, stdio: 'inherit', shell: false });
72
+ const interrupt = () => { child.kill('SIGINT'); }, terminate = () => { child.kill('SIGTERM'); };
73
+ process.on('SIGINT', interrupt); process.on('SIGTERM', terminate);
74
+ const cleanup = () => { process.off('SIGINT', interrupt); process.off('SIGTERM', terminate); };
75
+ child.once('error', error => { cleanup(); reject((error as NodeJS.ErrnoException).code === 'ENOENT' ? new Error(`${agent} was not found on PATH. Install and sign in to its CLI first.`) : error); });
76
+ child.once('close', (code, signal) => { cleanup(); resolveExit(code ?? (signal ? 128 + (constants.signals[signal] ?? 1) : 1)); });
77
+ });
78
+ } finally { if (directory) await rm(directory, { recursive: true, force: true }); }
79
+ }