@masstensor/diagnose 0.3.2 → 0.7.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.
- package/DEVELOPMENT_PLAN.md +69 -0
- package/KNOWLEDGE_SECURITY.md +47 -0
- package/PAIRING_PROTOCOL.md +37 -0
- package/README.md +56 -9
- package/USER_GUIDE.md +460 -20
- package/deploy/Caddyfile +1 -1
- package/deploy/ecosystem.config.cjs +1 -1
- package/dist/agent-command.d.ts +4 -0
- package/dist/agent-command.js +33 -0
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +48 -8
- package/dist/cases.d.ts +118 -0
- package/dist/cases.js +115 -0
- package/dist/cli.js +187 -25
- package/dist/crypto.d.ts +7 -0
- package/dist/crypto.js +16 -1
- package/dist/discover.js +1 -1
- package/dist/engine.d.ts +3 -0
- package/dist/engine.js +49 -9
- package/dist/history.d.ts +13 -0
- package/dist/history.js +57 -0
- package/dist/journal.d.ts +23 -1
- package/dist/journal.js +82 -5
- package/dist/knowledge-cli.d.ts +2 -0
- package/dist/knowledge-cli.js +164 -0
- package/dist/knowledge-drafts.d.ts +47 -0
- package/dist/knowledge-drafts.js +76 -0
- package/dist/knowledge-mcp.d.ts +5 -0
- package/dist/knowledge-mcp.js +65 -0
- package/dist/maintenance.d.ts +2 -0
- package/dist/maintenance.js +46 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +42 -20
- package/dist/operator.d.ts +4 -0
- package/dist/operator.js +33 -8
- package/dist/pairing.d.ts +40 -0
- package/dist/pairing.js +92 -0
- package/dist/peer.d.ts +13 -0
- package/dist/peer.js +87 -11
- package/dist/relay-main.js +1 -1
- package/dist/relay.d.ts +1 -0
- package/dist/relay.js +27 -4
- package/dist/resources.js +47 -26
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +2 -2
- package/dist/short-pairing.d.ts +25 -0
- package/dist/short-pairing.js +73 -0
- package/dist/skill-library.d.ts +27 -0
- package/dist/skill-library.js +226 -0
- package/dist/skill.d.ts +9 -0
- package/dist/skill.js +59 -0
- package/dist/transfers.js +28 -11
- package/dist/util.d.ts +2 -0
- package/dist/util.js +17 -3
- package/dist/vault-crypto.d.ts +11 -0
- package/dist/vault-crypto.js +30 -0
- package/dist/vault-server.d.ts +10 -0
- package/dist/vault-server.js +156 -0
- package/dist/vault.d.ts +19 -0
- package/dist/vault.js +72 -0
- package/examples/skills/device-troubleshooting/SKILL.md +35 -0
- package/examples/skills/device-troubleshooting/references/device-profile.md +16 -0
- package/examples/skills/owon.md +27 -0
- package/npm-shrinkwrap.json +209 -3
- package/package.json +15 -5
- package/scripts/setup-node.ps1 +54 -0
- package/scripts/setup-node.sh +52 -0
- package/src/agent-command.ts +25 -0
- package/src/agent.ts +37 -7
- package/src/cases.ts +74 -0
- package/src/cli.ts +57 -22
- package/src/crypto.ts +14 -1
- package/src/discover.ts +1 -1
- package/src/engine.ts +28 -7
- package/src/history.ts +43 -0
- package/src/journal.ts +41 -5
- package/src/knowledge-cli.ts +67 -0
- package/src/knowledge-drafts.ts +55 -0
- package/src/knowledge-mcp.ts +35 -0
- package/src/maintenance.ts +30 -0
- package/src/mcp.ts +26 -18
- package/src/operator.ts +25 -9
- package/src/pairing.ts +64 -0
- package/src/peer.ts +42 -14
- package/src/relay-main.ts +1 -1
- package/src/relay.ts +18 -6
- package/src/resources.ts +35 -13
- package/src/schema.ts +4 -4
- package/src/short-pairing.ts +57 -0
- package/src/skill-library.ts +162 -0
- package/src/skill.ts +45 -0
- package/src/transfers.ts +14 -3
- package/src/util.ts +15 -3
- package/src/vault-crypto.ts +25 -0
- package/src/vault-server.ts +72 -0
- package/src/vault.ts +51 -0
- package/test/agent.test.ts +79 -7
- package/test/cli.test.ts +3 -3
- package/test/knowledge-mcp.test.ts +37 -0
- package/test/knowledge.test.ts +112 -0
- package/test/mcp.test.ts +1 -1
- package/test/pairing.test.ts +124 -0
- package/test/review.test.ts +129 -0
- package/test/setup.test.ts +16 -0
- package/test/short-pairing.test.ts +100 -0
- package/test/skill-library.test.ts +62 -0
- package/test/skill.test.ts +25 -0
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@masstensor/diagnose",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@masstensor/diagnose",
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.7.0",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "MIT",
|
|
12
12
|
"dependencies": {
|
|
13
13
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
14
|
+
"@serenity-kit/opaque": "1.1.0",
|
|
14
15
|
"node-pty": "1.1.0",
|
|
15
16
|
"noise-handshake": "4.2.1",
|
|
16
17
|
"serialport": "13.0.0",
|
|
@@ -22,13 +23,14 @@
|
|
|
22
23
|
"diagnose-relay": "dist/relay-main.js"
|
|
23
24
|
},
|
|
24
25
|
"devDependencies": {
|
|
26
|
+
"@napi-rs/canvas": "0.1.80",
|
|
25
27
|
"@types/node": "22.20.5",
|
|
26
28
|
"@types/ws": "8.18.1",
|
|
27
29
|
"marked": "18.2.1",
|
|
28
30
|
"typescript": "7.0.2"
|
|
29
31
|
},
|
|
30
32
|
"engines": {
|
|
31
|
-
"node": ">=
|
|
33
|
+
"node": ">=20.10.0"
|
|
32
34
|
}
|
|
33
35
|
},
|
|
34
36
|
"node_modules/@hono/node-server": {
|
|
@@ -83,6 +85,210 @@
|
|
|
83
85
|
}
|
|
84
86
|
}
|
|
85
87
|
},
|
|
88
|
+
"node_modules/@napi-rs/canvas": {
|
|
89
|
+
"version": "0.1.80",
|
|
90
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.80.tgz",
|
|
91
|
+
"integrity": "sha512-DxuT1ClnIPts1kQx8FBmkk4BQDTfI5kIzywAaMjQSXfNnra5UFU9PwurXrl+Je3bJ6BGsp/zmshVVFbCmyI+ww==",
|
|
92
|
+
"dev": true,
|
|
93
|
+
"license": "MIT",
|
|
94
|
+
"workspaces": [
|
|
95
|
+
"e2e/*"
|
|
96
|
+
],
|
|
97
|
+
"engines": {
|
|
98
|
+
"node": ">= 10"
|
|
99
|
+
},
|
|
100
|
+
"optionalDependencies": {
|
|
101
|
+
"@napi-rs/canvas-android-arm64": "0.1.80",
|
|
102
|
+
"@napi-rs/canvas-darwin-arm64": "0.1.80",
|
|
103
|
+
"@napi-rs/canvas-darwin-x64": "0.1.80",
|
|
104
|
+
"@napi-rs/canvas-linux-arm-gnueabihf": "0.1.80",
|
|
105
|
+
"@napi-rs/canvas-linux-arm64-gnu": "0.1.80",
|
|
106
|
+
"@napi-rs/canvas-linux-arm64-musl": "0.1.80",
|
|
107
|
+
"@napi-rs/canvas-linux-riscv64-gnu": "0.1.80",
|
|
108
|
+
"@napi-rs/canvas-linux-x64-gnu": "0.1.80",
|
|
109
|
+
"@napi-rs/canvas-linux-x64-musl": "0.1.80",
|
|
110
|
+
"@napi-rs/canvas-win32-x64-msvc": "0.1.80"
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
"node_modules/@napi-rs/canvas-android-arm64": {
|
|
114
|
+
"version": "0.1.80",
|
|
115
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.80.tgz",
|
|
116
|
+
"integrity": "sha512-sk7xhN/MoXeuExlggf91pNziBxLPVUqF2CAVnB57KLG/pz7+U5TKG8eXdc3pm0d7Od0WreB6ZKLj37sX9muGOQ==",
|
|
117
|
+
"cpu": [
|
|
118
|
+
"arm64"
|
|
119
|
+
],
|
|
120
|
+
"dev": true,
|
|
121
|
+
"license": "MIT",
|
|
122
|
+
"optional": true,
|
|
123
|
+
"os": [
|
|
124
|
+
"android"
|
|
125
|
+
],
|
|
126
|
+
"engines": {
|
|
127
|
+
"node": ">= 10"
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
"node_modules/@napi-rs/canvas-darwin-arm64": {
|
|
131
|
+
"version": "0.1.80",
|
|
132
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.80.tgz",
|
|
133
|
+
"integrity": "sha512-O64APRTXRUiAz0P8gErkfEr3lipLJgM6pjATwavZ22ebhjYl/SUbpgM0xcWPQBNMP1n29afAC/Us5PX1vg+JNQ==",
|
|
134
|
+
"cpu": [
|
|
135
|
+
"arm64"
|
|
136
|
+
],
|
|
137
|
+
"dev": true,
|
|
138
|
+
"license": "MIT",
|
|
139
|
+
"optional": true,
|
|
140
|
+
"os": [
|
|
141
|
+
"darwin"
|
|
142
|
+
],
|
|
143
|
+
"engines": {
|
|
144
|
+
"node": ">= 10"
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
"node_modules/@napi-rs/canvas-darwin-x64": {
|
|
148
|
+
"version": "0.1.80",
|
|
149
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.80.tgz",
|
|
150
|
+
"integrity": "sha512-FqqSU7qFce0Cp3pwnTjVkKjjOtxMqRe6lmINxpIZYaZNnVI0H5FtsaraZJ36SiTHNjZlUB69/HhxNDT1Aaa9vA==",
|
|
151
|
+
"cpu": [
|
|
152
|
+
"x64"
|
|
153
|
+
],
|
|
154
|
+
"dev": true,
|
|
155
|
+
"license": "MIT",
|
|
156
|
+
"optional": true,
|
|
157
|
+
"os": [
|
|
158
|
+
"darwin"
|
|
159
|
+
],
|
|
160
|
+
"engines": {
|
|
161
|
+
"node": ">= 10"
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
|
|
165
|
+
"version": "0.1.80",
|
|
166
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.80.tgz",
|
|
167
|
+
"integrity": "sha512-eyWz0ddBDQc7/JbAtY4OtZ5SpK8tR4JsCYEZjCE3dI8pqoWUC8oMwYSBGCYfsx2w47cQgQCgMVRVTFiiO38hHQ==",
|
|
168
|
+
"cpu": [
|
|
169
|
+
"arm"
|
|
170
|
+
],
|
|
171
|
+
"dev": true,
|
|
172
|
+
"license": "MIT",
|
|
173
|
+
"optional": true,
|
|
174
|
+
"os": [
|
|
175
|
+
"linux"
|
|
176
|
+
],
|
|
177
|
+
"engines": {
|
|
178
|
+
"node": ">= 10"
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
"node_modules/@napi-rs/canvas-linux-arm64-gnu": {
|
|
182
|
+
"version": "0.1.80",
|
|
183
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.80.tgz",
|
|
184
|
+
"integrity": "sha512-qwA63t8A86bnxhuA/GwOkK3jvb+XTQaTiVML0vAWoHyoZYTjNs7BzoOONDgTnNtr8/yHrq64XXzUoLqDzU+Uuw==",
|
|
185
|
+
"cpu": [
|
|
186
|
+
"arm64"
|
|
187
|
+
],
|
|
188
|
+
"dev": true,
|
|
189
|
+
"license": "MIT",
|
|
190
|
+
"optional": true,
|
|
191
|
+
"os": [
|
|
192
|
+
"linux"
|
|
193
|
+
],
|
|
194
|
+
"engines": {
|
|
195
|
+
"node": ">= 10"
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
"node_modules/@napi-rs/canvas-linux-arm64-musl": {
|
|
199
|
+
"version": "0.1.80",
|
|
200
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.80.tgz",
|
|
201
|
+
"integrity": "sha512-1XbCOz/ymhj24lFaIXtWnwv/6eFHXDrjP0jYkc6iHQ9q8oXKzUX1Lc6bu+wuGiLhGh2GS/2JlfORC5ZcXimRcg==",
|
|
202
|
+
"cpu": [
|
|
203
|
+
"arm64"
|
|
204
|
+
],
|
|
205
|
+
"dev": true,
|
|
206
|
+
"license": "MIT",
|
|
207
|
+
"optional": true,
|
|
208
|
+
"os": [
|
|
209
|
+
"linux"
|
|
210
|
+
],
|
|
211
|
+
"engines": {
|
|
212
|
+
"node": ">= 10"
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
|
|
216
|
+
"version": "0.1.80",
|
|
217
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.80.tgz",
|
|
218
|
+
"integrity": "sha512-XTzR125w5ZMs0lJcxRlS1K3P5RaZ9RmUsPtd1uGt+EfDyYMu4c6SEROYsxyatbbu/2+lPe7MPHOO/0a0x7L/gw==",
|
|
219
|
+
"cpu": [
|
|
220
|
+
"riscv64"
|
|
221
|
+
],
|
|
222
|
+
"dev": true,
|
|
223
|
+
"license": "MIT",
|
|
224
|
+
"optional": true,
|
|
225
|
+
"os": [
|
|
226
|
+
"linux"
|
|
227
|
+
],
|
|
228
|
+
"engines": {
|
|
229
|
+
"node": ">= 10"
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
"node_modules/@napi-rs/canvas-linux-x64-gnu": {
|
|
233
|
+
"version": "0.1.80",
|
|
234
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.80.tgz",
|
|
235
|
+
"integrity": "sha512-BeXAmhKg1kX3UCrJsYbdQd3hIMDH/K6HnP/pG2LuITaXhXBiNdh//TVVVVCBbJzVQaV5gK/4ZOCMrQW9mvuTqA==",
|
|
236
|
+
"cpu": [
|
|
237
|
+
"x64"
|
|
238
|
+
],
|
|
239
|
+
"dev": true,
|
|
240
|
+
"license": "MIT",
|
|
241
|
+
"optional": true,
|
|
242
|
+
"os": [
|
|
243
|
+
"linux"
|
|
244
|
+
],
|
|
245
|
+
"engines": {
|
|
246
|
+
"node": ">= 10"
|
|
247
|
+
}
|
|
248
|
+
},
|
|
249
|
+
"node_modules/@napi-rs/canvas-linux-x64-musl": {
|
|
250
|
+
"version": "0.1.80",
|
|
251
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.80.tgz",
|
|
252
|
+
"integrity": "sha512-x0XvZWdHbkgdgucJsRxprX/4o4sEed7qo9rCQA9ugiS9qE2QvP0RIiEugtZhfLH3cyI+jIRFJHV4Fuz+1BHHMg==",
|
|
253
|
+
"cpu": [
|
|
254
|
+
"x64"
|
|
255
|
+
],
|
|
256
|
+
"dev": true,
|
|
257
|
+
"license": "MIT",
|
|
258
|
+
"optional": true,
|
|
259
|
+
"os": [
|
|
260
|
+
"linux"
|
|
261
|
+
],
|
|
262
|
+
"engines": {
|
|
263
|
+
"node": ">= 10"
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
"node_modules/@napi-rs/canvas-win32-x64-msvc": {
|
|
267
|
+
"version": "0.1.80",
|
|
268
|
+
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.80.tgz",
|
|
269
|
+
"integrity": "sha512-Z8jPsM6df5V8B1HrCHB05+bDiCxjE9QA//3YrkKIdVDEwn5RKaqOxCJDRJkl48cJbylcrJbW4HxZbTte8juuPg==",
|
|
270
|
+
"cpu": [
|
|
271
|
+
"x64"
|
|
272
|
+
],
|
|
273
|
+
"dev": true,
|
|
274
|
+
"license": "MIT",
|
|
275
|
+
"optional": true,
|
|
276
|
+
"os": [
|
|
277
|
+
"win32"
|
|
278
|
+
],
|
|
279
|
+
"engines": {
|
|
280
|
+
"node": ">= 10"
|
|
281
|
+
}
|
|
282
|
+
},
|
|
283
|
+
"node_modules/@serenity-kit/opaque": {
|
|
284
|
+
"version": "1.1.0",
|
|
285
|
+
"resolved": "https://registry.npmjs.org/@serenity-kit/opaque/-/opaque-1.1.0.tgz",
|
|
286
|
+
"integrity": "sha512-Y6v/+hRMn0MdMEk5+/ArM0vPIiFfFEbdTZc7oAx+cWyvGODGezAQ/sMjXBVogf7NsS9z9EV0Ve5paZCVULuedw==",
|
|
287
|
+
"license": "MIT",
|
|
288
|
+
"bin": {
|
|
289
|
+
"opaque": "bin/index.js"
|
|
290
|
+
}
|
|
291
|
+
},
|
|
86
292
|
"node_modules/@serialport/binding-mock": {
|
|
87
293
|
"version": "10.2.2",
|
|
88
294
|
"resolved": "https://registry.npmjs.org/@serialport/binding-mock/-/binding-mock-10.2.2.tgz",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@masstensor/diagnose",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.7.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": ">=
|
|
12
|
+
"node": ">=20.10.0"
|
|
13
13
|
},
|
|
14
14
|
"bin": {
|
|
15
15
|
"diagnose": "dist/cli.js",
|
|
@@ -26,7 +26,13 @@
|
|
|
26
26
|
"test/*.test.ts",
|
|
27
27
|
"test/noise-vector.json",
|
|
28
28
|
"deploy",
|
|
29
|
-
"test/CACOPHONY-LICENSE"
|
|
29
|
+
"test/CACOPHONY-LICENSE",
|
|
30
|
+
"examples/skills",
|
|
31
|
+
"scripts/setup-node.sh",
|
|
32
|
+
"scripts/setup-node.ps1",
|
|
33
|
+
"KNOWLEDGE_SECURITY.md",
|
|
34
|
+
"DEVELOPMENT_PLAN.md",
|
|
35
|
+
"PAIRING_PROTOCOL.md"
|
|
30
36
|
],
|
|
31
37
|
"scripts": {
|
|
32
38
|
"build": "tsc",
|
|
@@ -35,10 +41,13 @@
|
|
|
35
41
|
"prepack": "npm run build",
|
|
36
42
|
"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();\"",
|
|
37
43
|
"build:site": "tsc -p site/tsconfig.json && node --experimental-strip-types site/build.ts",
|
|
38
|
-
"check:site": "node --experimental-strip-types site/check.ts"
|
|
44
|
+
"check:site": "node --experimental-strip-types site/check.ts",
|
|
45
|
+
"video:render": "node --experimental-strip-types video/render-en.ts",
|
|
46
|
+
"video:preview": "node --experimental-strip-types video/render-en.ts --preview"
|
|
39
47
|
},
|
|
40
48
|
"dependencies": {
|
|
41
49
|
"@modelcontextprotocol/sdk": "1.32.2",
|
|
50
|
+
"@serenity-kit/opaque": "1.1.0",
|
|
42
51
|
"node-pty": "1.1.0",
|
|
43
52
|
"noise-handshake": "4.2.1",
|
|
44
53
|
"serialport": "13.0.0",
|
|
@@ -46,6 +55,7 @@
|
|
|
46
55
|
"zod": "4.6.7"
|
|
47
56
|
},
|
|
48
57
|
"devDependencies": {
|
|
58
|
+
"@napi-rs/canvas": "0.1.80",
|
|
49
59
|
"@types/node": "22.20.5",
|
|
50
60
|
"@types/ws": "8.18.1",
|
|
51
61
|
"marked": "18.2.1",
|
|
@@ -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
CHANGED
|
@@ -1,29 +1,51 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { constants } from 'node:os';
|
|
3
|
-
import { mkdtemp, readFile, writeFile, rm, mkdir, readdir, symlink } from 'node:fs/promises';
|
|
3
|
+
import { mkdtemp, readFile, writeFile, rm, mkdir, readdir, symlink, stat, copyFile } from 'node:fs/promises';
|
|
4
4
|
import { tmpdir, homedir } from 'node:os';
|
|
5
5
|
import { join, resolve } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { parseArgs } from 'node:util';
|
|
8
|
+
import { PairingStore } from './pairing.js';
|
|
9
|
+
import { skillPrompt } from './skill.js';
|
|
10
|
+
import { resolveSkill } from './skill-library.js';
|
|
11
|
+
import { Cases } from './cases.js';
|
|
12
|
+
import { agentCommand } from './agent-command.js';
|
|
8
13
|
|
|
9
|
-
export const agentUsage = 'diagnose agent codex|claude|gemini [--relay URL] [-- agent arguments...]';
|
|
14
|
+
export const agentUsage = 'diagnose agent codex|claude|gemini [--device NAME] [--case ID] [--skill FILE.md|DIRECTORY|library:NAME@REVISION] [--relay URL] [-- agent arguments...]';
|
|
10
15
|
|
|
11
16
|
export async function launchAgent(argv: string[]): Promise<number> {
|
|
12
17
|
const separator = argv.indexOf('--');
|
|
13
18
|
const extra = separator < 0 ? [] : argv.slice(separator + 1);
|
|
14
|
-
const { positionals, values } = parseArgs({ args: separator < 0 ? argv : argv.slice(0, separator), allowPositionals: true, options: { relay: { type: 'string' }, help: { type: 'boolean', short: 'h' } } });
|
|
19
|
+
const { positionals, values } = parseArgs({ args: separator < 0 ? argv : argv.slice(0, separator), allowPositionals: true, options: { relay: { type: 'string' }, skill: { type: 'string' }, device: { type: 'string' }, case: { type: 'string' }, help: { type: 'boolean', short: 'h' } } });
|
|
15
20
|
if (values.help || !positionals.length) { console.log(agentUsage); return 0; }
|
|
16
21
|
const [agent] = positionals;
|
|
17
22
|
if (positionals.length !== 1 || !['codex', 'claude', 'gemini'].includes(agent)) throw new Error(agentUsage);
|
|
23
|
+
if (values.device) new PairingStore().get(values.device, 'operator');
|
|
24
|
+
const selectedCase = values.case ? new Cases().get(values.case) : undefined;
|
|
25
|
+
if (selectedCase?.host && values.device && selectedCase.host !== values.device) throw new Error('Selected case belongs to a different paired computer');
|
|
26
|
+
if (selectedCase?.skill && values.skill && selectedCase.skill !== values.skill) throw new Error('Case skill revision differs from selected skill');
|
|
27
|
+
const skillInput = values.skill ?? selectedCase?.skill;
|
|
28
|
+
let skill = skillInput ? await resolveSkill(skillInput) : undefined;
|
|
29
|
+
if (selectedCase && !skill) skill = { sourceFile: '', baseDirectory: process.cwd(), sha256: '', instructions: 'Use diagnose_case show to read the selected case. Confirm the external target identity, inspect interfaces conservatively, diagnose the stated goal, apply only authorized repairs, and record evidence-backed verification. Propose a reusable skill draft if useful.' };
|
|
30
|
+
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');
|
|
18
31
|
if (values.relay) {
|
|
19
32
|
const url = new URL(values.relay);
|
|
20
33
|
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');
|
|
21
34
|
if (url.username || url.password) throw new Error('Relay URL must not contain credentials');
|
|
22
35
|
}
|
|
23
36
|
// Reuse this exact installed version. No global install or extra npx download.
|
|
24
|
-
const server = { command: process.execPath, args: [fileURLToPath(new URL('./cli.js', import.meta.url)), 'mcp', ...(values.relay ? [values.relay] : [])] };
|
|
37
|
+
const server = { command: process.execPath, args: [fileURLToPath(new URL('./cli.js', import.meta.url)), 'mcp', ...(values.relay ? [values.relay] : []), ...(values.device ? ['--device', values.device] : []), ...(values.case ? ['--case', values.case] : [])] };
|
|
25
38
|
const env = { ...process.env }; let directory: string | undefined;
|
|
26
39
|
try {
|
|
40
|
+
let prompt: string | undefined, taskDirectory: string | undefined;
|
|
41
|
+
if (skill) {
|
|
42
|
+
directory = await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
|
|
43
|
+
taskDirectory = join(directory, 'task'); await mkdir(taskDirectory, { mode: 0o700 });
|
|
44
|
+
const snapshot = join(taskDirectory, 'task.json');
|
|
45
|
+
await writeFile(snapshot, JSON.stringify(skill), { mode: 0o600 });
|
|
46
|
+
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.' : '');
|
|
47
|
+
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.');
|
|
48
|
+
}
|
|
27
49
|
let args: string[];
|
|
28
50
|
if (agent === 'codex') args = ['-c', `mcp_servers.diagnose.command=${JSON.stringify(server.command)}`, '-c', `mcp_servers.diagnose.args=${JSON.stringify(server.args)}`, ...extra];
|
|
29
51
|
else if (agent === 'claude') args = ['--mcp-config', JSON.stringify({ mcpServers: { diagnose: server } }), ...extra];
|
|
@@ -35,17 +57,25 @@ export async function launchAgent(argv: string[]): Promise<number> {
|
|
|
35
57
|
let settings: Record<string, unknown> = {};
|
|
36
58
|
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}`); }
|
|
37
59
|
if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw new Error('Gemini user settings must be a JSON object');
|
|
38
|
-
directory
|
|
60
|
+
directory ??= await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
|
|
39
61
|
const configRoot = join(directory, '.gemini'); await mkdir(configRoot, { mode: 0o700 });
|
|
40
62
|
let entries: string[] = [];
|
|
41
63
|
try { entries = await readdir(originalRoot); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
|
|
42
|
-
for (const name of entries) if (name !== 'settings.json')
|
|
64
|
+
for (const name of entries) if (name !== 'settings.json') {
|
|
65
|
+
const source = join(originalRoot, name), target = join(configRoot, name);
|
|
66
|
+
if (process.platform === 'win32') {
|
|
67
|
+
if ((await stat(source)).isDirectory()) await symlink(source, target, 'junction');
|
|
68
|
+
else await copyFile(source, target);
|
|
69
|
+
} else await symlink(source, target);
|
|
70
|
+
}
|
|
43
71
|
const path = join(configRoot, 'settings.json');
|
|
44
72
|
await writeFile(path, JSON.stringify({ ...settings, mcpServers: { ...(settings.mcpServers as object ?? {}), diagnose: server } }), { mode: 0o600 });
|
|
45
73
|
env.GEMINI_CLI_HOME = directory; args = extra;
|
|
46
74
|
}
|
|
75
|
+
if (prompt) args = agent === 'gemini' ? [...args, '--include-directories', taskDirectory!, '--prompt-interactive', prompt] : [...args, '--add-dir', taskDirectory!, '--', prompt];
|
|
76
|
+
const command = await agentCommand(agent, args, env);
|
|
47
77
|
return await new Promise<number>((resolveExit, reject) => {
|
|
48
|
-
const child = spawn(
|
|
78
|
+
const child = spawn(command.command, command.args, { env, stdio: 'inherit', shell: false });
|
|
49
79
|
const interrupt = () => { child.kill('SIGINT'); }, terminate = () => { child.kill('SIGTERM'); };
|
|
50
80
|
process.on('SIGINT', interrupt); process.on('SIGTERM', terminate);
|
|
51
81
|
const cleanup = () => { process.off('SIGINT', interrupt); process.off('SIGTERM', terminate); };
|
package/src/cases.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { unlinkSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { Journal } from './journal.js';
|
|
7
|
+
import { redact } from './util.js';
|
|
8
|
+
|
|
9
|
+
const text = z.string().min(1).max(4000);
|
|
10
|
+
export const targetSchema = z.object({ name: text, model: text.optional(), identity: text.optional(), interface: z.enum(['usb', 'serial', 'lan', 'host', 'other']), address: text.optional() }).strict();
|
|
11
|
+
export const caseInputSchema = z.object({ goal: text, target: targetSchema, host: z.string().max(120).optional(), skill: z.string().max(4096).optional() }).strict();
|
|
12
|
+
export const conclusionSchema = z.object({ outcome: z.enum(['resolved', 'unresolved', 'needs-physical-work', 'insufficient-evidence']), summary: text, changes: z.array(text).max(100).default([]), remaining: z.array(text).max(100).default([]), baseline: z.string().uuid().optional(), verification: z.string().uuid().optional() }).strict();
|
|
13
|
+
export type Evidence = { id: string; at: string; kind: string; taskId?: string; digest: string; data: unknown; truncated: boolean };
|
|
14
|
+
export type Case = z.infer<typeof caseInputSchema> & { id: string; createdAt: string; conclusion?: z.infer<typeof conclusionSchema>; evidence: Evidence[]; recordingLimited?: boolean };
|
|
15
|
+
|
|
16
|
+
// Structured credentials are excluded before local persistence; arbitrary output is
|
|
17
|
+
// still sensitive. Encryption is at rest with a same-user key, not an OS sandbox.
|
|
18
|
+
export function sanitize(value: unknown): unknown {
|
|
19
|
+
if (typeof value === 'string') return redact(value).replace(/\bK1\.[A-Za-z0-9_-]{43}\b/g, '[LIBRARY KEY]');
|
|
20
|
+
if (Array.isArray(value)) return value.map(sanitize);
|
|
21
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, /password|secret|token|authorization|credential|^code$/i.test(key) ? '[REDACTED]' : sanitize(item)]));
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
export class Cases {
|
|
25
|
+
private journal: Journal;
|
|
26
|
+
constructor(readonly root = join(homedir(), '.diagnose', 'cases')) { this.journal = new Journal(root); }
|
|
27
|
+
create(input: z.infer<typeof caseInputSchema>): Case {
|
|
28
|
+
if (this.journal.list().length >= 100) throw new Error('Case limit reached (100); export and remove old cases');
|
|
29
|
+
const value = { ...caseInputSchema.parse(input), id: randomUUID(), createdAt: new Date().toISOString(), evidence: [] };
|
|
30
|
+
this.save(value); return value;
|
|
31
|
+
}
|
|
32
|
+
get(id: string): Case { z.string().uuid().parse(id); return this.journal.load(id).case as Case; }
|
|
33
|
+
save(value: Case): void {
|
|
34
|
+
this.journal.save({ id: value.id, kind: 'process', state: 'case', createdAt: value.createdAt, updatedAt: '', ownerPid: 0, tokenHash: '', retainOnDisconnect: false, case: value });
|
|
35
|
+
}
|
|
36
|
+
list() { return this.journal.list().map(meta => { const value = meta.case as Case; return { id: value.id, goal: value.goal, target: value.target, createdAt: value.createdAt, outcome: value.conclusion?.outcome ?? 'open', evidenceCount: value.evidence.length }; }); }
|
|
37
|
+
remove(id: string): void { this.get(id); if (existsSync(join(this.root, id + '.lock'))) throw new Error('Case is in use; stop its agent before removing it'); unlinkSync(join(this.root, id + '.meta')); }
|
|
38
|
+
claim(id: string): () => void {
|
|
39
|
+
this.get(id); const path = join(this.root, id + '.lock'), token = randomUUID();
|
|
40
|
+
try { writeFileSync(path, JSON.stringify({ pid: process.pid, token }), { flag: 'wx', mode: 0o600 }); }
|
|
41
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new Error('Case already has a writer. Stop its agent, or use diagnose cases unlock ID after an unclean exit.'); throw error; }
|
|
42
|
+
return () => { try { if (JSON.parse(readFileSync(path, 'utf8')).token === token) unlinkSync(path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; } };
|
|
43
|
+
}
|
|
44
|
+
unlock(id: string): void {
|
|
45
|
+
this.get(id); const path = join(this.root, id + '.lock'), lock = JSON.parse(readFileSync(path, 'utf8'));
|
|
46
|
+
if (!Number.isSafeInteger(lock.pid) || lock.pid <= 0) throw new Error('Invalid case lock; inspect locally');
|
|
47
|
+
let alive = true; try { process.kill(lock.pid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ESRCH') alive = false; }
|
|
48
|
+
if (alive) throw new Error('Case writer is still alive; stop the agent first');
|
|
49
|
+
unlinkSync(path);
|
|
50
|
+
}
|
|
51
|
+
record(id: string, kind: string, data: unknown, taskId?: string): Evidence | undefined {
|
|
52
|
+
const value = this.get(id);
|
|
53
|
+
if (value.evidence.length >= 200) { value.recordingLimited = true; this.save(value); return undefined; }
|
|
54
|
+
const serialized = JSON.stringify(sanitize(data));
|
|
55
|
+
const truncated = Buffer.byteLength(serialized) > 32768;
|
|
56
|
+
const evidence: Evidence = { id: randomUUID(), at: new Date().toISOString(), kind, taskId, digest: createHash('sha256').update(serialized).digest('hex'), data: truncated ? { preview: serialized.slice(0, 8000), note: 'Evidence exceeded 32 KiB; only preview retained' } : JSON.parse(serialized), truncated };
|
|
57
|
+
value.evidence.push(evidence); this.save(value); return evidence;
|
|
58
|
+
}
|
|
59
|
+
finish(id: string, input: z.infer<typeof conclusionSchema>): Case {
|
|
60
|
+
const conclusion = conclusionSchema.parse(input), value = this.get(id);
|
|
61
|
+
if (conclusion.outcome === 'resolved') {
|
|
62
|
+
const baseline = value.evidence.find(item => item.id === conclusion.baseline), verification = value.evidence.find(item => item.id === conclusion.verification);
|
|
63
|
+
const result = (verification?.data as { result?: { status?: string } })?.result;
|
|
64
|
+
if (!baseline || baseline.kind !== 'task.result' || !verification || verification.kind !== 'task.result' || baseline.id === verification.id || value.evidence.indexOf(verification) <= value.evidence.indexOf(baseline) || verification.truncated || result?.status !== 'ok') throw new Error('Resolved requires distinct baseline and later successful verification evidence IDs from this case');
|
|
65
|
+
}
|
|
66
|
+
for (const reference of [conclusion.baseline, conclusion.verification]) if (reference && !value.evidence.some(item => item.id === reference)) throw new Error('Unknown case evidence ID');
|
|
67
|
+
value.conclusion = sanitize(conclusion) as typeof conclusion; this.save(value); return value;
|
|
68
|
+
}
|
|
69
|
+
report(id: string) {
|
|
70
|
+
const value = this.get(id);
|
|
71
|
+
// Deliberately exclude target addresses, command arguments and result bodies.
|
|
72
|
+
return { id: value.id, createdAt: value.createdAt, goal: sanitize(value.goal), target: { name: sanitize(value.target.name), model: sanitize(value.target.model), interface: value.target.interface }, skill: value.skill, conclusion: value.conclusion, recordingLimited: value.recordingLimited ?? false, evidence: value.evidence.map(({ id, at, kind, taskId, digest, truncated }) => ({ id, at, kind, taskId, digest, truncated })), note: 'Conclusion is an agent/diagnostician assessment, not an independent proof. Review free text for customer details before sharing.' };
|
|
73
|
+
}
|
|
74
|
+
}
|