@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/dist/relay.js
CHANGED
|
@@ -2,15 +2,23 @@ import http from 'node:http';
|
|
|
2
2
|
import { createReadStream, statSync } from 'node:fs';
|
|
3
3
|
import { WebSocket, WebSocketServer } from 'ws';
|
|
4
4
|
import { MAX_FRAME } from './schema.js';
|
|
5
|
+
import { INVITATION_MS } from './crypto.js';
|
|
6
|
+
import { VaultServer } from './vault-server.js';
|
|
5
7
|
const control = (ws, type, extra = {}) => { if (ws.readyState === WebSocket.OPEN)
|
|
6
8
|
ws.send(JSON.stringify({ type, ...extra })); };
|
|
7
9
|
export function createRelay(options = {}) {
|
|
10
|
+
const vault = options.vaultPath ? new VaultServer(options.vaultPath) : undefined;
|
|
8
11
|
const rooms = new Map();
|
|
9
12
|
const clients = new Map();
|
|
10
13
|
const connectionsByIp = new Map();
|
|
14
|
+
const connectionRates = new Map();
|
|
11
15
|
const server = http.createServer((req, res) => {
|
|
12
16
|
res.setHeader('Cache-Control', 'no-store');
|
|
13
17
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
18
|
+
if (req.url?.startsWith('/v1/library') && vault) {
|
|
19
|
+
void vault.handle(req, res);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
14
22
|
if (req.method === 'GET' && req.url === '/healthz') {
|
|
15
23
|
res.setHeader('Content-Type', 'application/json');
|
|
16
24
|
res.end('{"ok":true,"protocol":1}');
|
|
@@ -44,6 +52,16 @@ export function createRelay(options = {}) {
|
|
|
44
52
|
wss.on('connection', (ws, req) => {
|
|
45
53
|
const direct = req.socket.remoteAddress ?? 'unknown';
|
|
46
54
|
const ip = ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(direct) ? String(req.headers['x-forwarded-for'] ?? direct).split(',')[0].trim() : direct;
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
for (const [key, rate] of connectionRates)
|
|
57
|
+
if (now - rate.since > 60000)
|
|
58
|
+
connectionRates.delete(key);
|
|
59
|
+
const rate = connectionRates.get(ip) ?? { since: now, count: 0 };
|
|
60
|
+
if ((!connectionRates.has(ip) && connectionRates.size >= 10000) || ++rate.count > 60) {
|
|
61
|
+
ws.close(1008, 'Connection rate limit');
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
connectionRates.set(ip, rate);
|
|
47
65
|
if ((connectionsByIp.get(ip) ?? 0) >= 30) {
|
|
48
66
|
ws.close(1008, 'Connection limit');
|
|
49
67
|
return;
|
|
@@ -62,19 +80,24 @@ export function createRelay(options = {}) {
|
|
|
62
80
|
if (binary || bytes.length > 256)
|
|
63
81
|
throw new Error();
|
|
64
82
|
const msg = JSON.parse(bytes.toString());
|
|
65
|
-
|
|
83
|
+
const short = msg.version === 2 && /^S2\.[a-z]{2}$/.test(msg.room);
|
|
84
|
+
if (!(short || (msg.version === 1 && /^[A-Za-z0-9_-]{16}$/.test(msg.room))) || !['host', 'join'].includes(msg.role))
|
|
66
85
|
throw new Error();
|
|
67
86
|
if (msg.role === 'host') {
|
|
87
|
+
if (short && rooms.has(msg.room)) {
|
|
88
|
+
ws.close(1008, 'Invitation locator occupied');
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
68
91
|
if (rooms.has(msg.room) || rooms.size >= (options.maxRooms ?? 100))
|
|
69
92
|
throw new Error();
|
|
70
|
-
rooms.set(msg.room, { host: ws, locked: false, attempts: 0, expires: Date.now() + (options.invitationMs ?? 600000), frames: 0, window: Date.now() });
|
|
93
|
+
rooms.set(msg.room, { short, host: ws, locked: false, attempts: 0, expires: Date.now() + (short ? Math.min(options.invitationMs ?? INVITATION_MS, INVITATION_MS) : options.invitationMs ?? 600000), frames: 0, window: Date.now() });
|
|
71
94
|
state.role = 'host';
|
|
72
95
|
state.room = msg.room;
|
|
73
96
|
control(ws, 'registered');
|
|
74
97
|
}
|
|
75
98
|
else {
|
|
76
99
|
const room = rooms.get(msg.room);
|
|
77
|
-
if (!room || room.locked || room.peer || room.attempts >= 10 || room.expires < Date.now())
|
|
100
|
+
if (!room || room.locked || room.peer || room.attempts >= (room.short ? 5 : 10) || room.expires < Date.now())
|
|
78
101
|
throw new Error();
|
|
79
102
|
state.role = 'join';
|
|
80
103
|
state.room = msg.room;
|
|
@@ -87,7 +110,7 @@ export function createRelay(options = {}) {
|
|
|
87
110
|
return;
|
|
88
111
|
}
|
|
89
112
|
const room = rooms.get(state.room);
|
|
90
|
-
if (!room)
|
|
113
|
+
if (!room || room.expires < Date.now())
|
|
91
114
|
throw new Error();
|
|
92
115
|
if (binary) {
|
|
93
116
|
if (Date.now() - room.window > 1000) {
|
package/dist/resources.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { spawn as spawnProcess } from 'node:child_process';
|
|
2
2
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
3
3
|
import { constants } from 'node:fs';
|
|
4
|
-
import { open, lstat, realpath, rename, unlink } from 'node:fs/promises';
|
|
4
|
+
import { open, lstat, realpath, rename, unlink, link } from 'node:fs/promises';
|
|
5
5
|
import { dirname, resolve, join, basename } from 'node:path';
|
|
6
6
|
import net from 'node:net';
|
|
7
|
-
import { Journal } from './journal.js';
|
|
7
|
+
import { Journal, retention } from './journal.js';
|
|
8
8
|
import { killTree } from './executor.js';
|
|
9
9
|
import { sha256 } from './util.js';
|
|
10
10
|
import { preparePty } from './prepare-pty.js';
|
|
@@ -38,10 +38,14 @@ export class SessionResources {
|
|
|
38
38
|
writes = new Map();
|
|
39
39
|
constructor(root, audit) {
|
|
40
40
|
this.audit = audit;
|
|
41
|
-
this.journal = new Journal(root);
|
|
41
|
+
this.journal = new Journal(root, retention);
|
|
42
42
|
}
|
|
43
43
|
setAudit(audit) { this.audit = audit; }
|
|
44
44
|
create(id, kind, owner, retainOnDisconnect, details = {}) {
|
|
45
|
+
for (const [key, value] of this.resources) {
|
|
46
|
+
if (!['running', 'open', 'listening'].includes(value.meta.state) && (!this.journal.exists(key) || this.resources.size >= 256))
|
|
47
|
+
this.resources.delete(key);
|
|
48
|
+
}
|
|
45
49
|
if (this.resources.has(id) || this.journal.exists(id))
|
|
46
50
|
throw new Error('Resource ID already exists. Resume it; do not replay its creation.');
|
|
47
51
|
if ([...this.resources.values()].filter(r => ['running', 'open', 'listening'].includes(r.meta.state)).length >= 128)
|
|
@@ -128,6 +132,8 @@ export class SessionResources {
|
|
|
128
132
|
if (bytes.length > 65536 || bytes.toString('base64') !== (request.data ?? ''))
|
|
129
133
|
throw new Error('Invalid input encoding');
|
|
130
134
|
this.audit.record('resource.input', { id: meta.id, bytes: bytes.length, eof: request.eof });
|
|
135
|
+
if (meta.kind === 'process')
|
|
136
|
+
this.audit.history.event(meta.id, 'process-input', { encoding: 'base64', data: bytes.toString('base64'), eof: request.eof });
|
|
131
137
|
await resource.input(bytes, request.eof);
|
|
132
138
|
return { acceptedBytes: bytes.length };
|
|
133
139
|
}
|
|
@@ -163,8 +169,10 @@ export class SessionResources {
|
|
|
163
169
|
for (const key of Object.keys(env))
|
|
164
170
|
if (/^(?:DIAGNOSE_|OWON_|NPM_TOKEN|NODE_AUTH_TOKEN)/i.test(key))
|
|
165
171
|
delete env[key];
|
|
166
|
-
let timer,
|
|
167
|
-
|
|
172
|
+
let timer, closing;
|
|
173
|
+
// A leader exiting does not mean its process group has exited. Clean up
|
|
174
|
+
// immediately, while the group ID still belongs to this job.
|
|
175
|
+
const ended = (code, signal) => { resource.signal?.('SIGKILL'); clearTimeout(timer); meta.state = 'exited'; meta.exitCode = code; if (signal !== undefined)
|
|
168
176
|
meta.signal = signal; this.journal.save(meta); this.audit.record('resource.process-exited', { id: meta.id, exitCode: code }); };
|
|
169
177
|
const collect = (stream, bytes) => {
|
|
170
178
|
try {
|
|
@@ -197,7 +205,10 @@ export class SessionResources {
|
|
|
197
205
|
child.write('\x04'); };
|
|
198
206
|
resource.resize = (cols, rows) => { child.resize(cols, rows); meta.cols = cols; meta.rows = rows; this.journal.save(meta); };
|
|
199
207
|
resource.signal = signal => { try {
|
|
200
|
-
|
|
208
|
+
if (process.platform === 'win32')
|
|
209
|
+
child.kill(signal);
|
|
210
|
+
else
|
|
211
|
+
process.kill(-child.pid, signal);
|
|
201
212
|
}
|
|
202
213
|
catch { } };
|
|
203
214
|
}
|
|
@@ -207,8 +218,8 @@ export class SessionResources {
|
|
|
207
218
|
child.stdout.on('data', bytes => collect('stdout', bytes));
|
|
208
219
|
child.stderr.on('data', bytes => collect('stderr', bytes));
|
|
209
220
|
child.stdin.on('error', () => { });
|
|
210
|
-
child.on('error', error => { meta.error = error.message; });
|
|
211
|
-
child.on('
|
|
221
|
+
child.on('error', error => { meta.error = error.message; meta.state = 'failed'; this.journal.save(meta); });
|
|
222
|
+
child.on('exit', (code, signal) => ended(code, signal ?? undefined));
|
|
212
223
|
resource.input = (bytes, eof) => new Promise((resolveInput, reject) => { if (child.stdin.destroyed || child.stdin.writableEnded) {
|
|
213
224
|
reject(new Error('Process stdin is closed'));
|
|
214
225
|
return;
|
|
@@ -225,12 +236,19 @@ export class SessionResources {
|
|
|
225
236
|
catch { }
|
|
226
237
|
} };
|
|
227
238
|
}
|
|
228
|
-
resource.close = () => {
|
|
229
|
-
closing
|
|
239
|
+
resource.close = () => {
|
|
240
|
+
if (closing)
|
|
241
|
+
return closing;
|
|
242
|
+
if (meta.state !== 'running')
|
|
243
|
+
return;
|
|
230
244
|
resource.signal?.('SIGTERM');
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
245
|
+
closing = new Promise(resolveClose => setTimeout(() => {
|
|
246
|
+
if (meta.state === 'running')
|
|
247
|
+
resource.signal?.('SIGKILL');
|
|
248
|
+
resolveClose();
|
|
249
|
+
}, 1000));
|
|
250
|
+
return closing;
|
|
251
|
+
};
|
|
234
252
|
if (args.timeoutMs) {
|
|
235
253
|
timer = setTimeout(() => { meta.timedOut = true; void resource.close(); }, args.timeoutMs);
|
|
236
254
|
timer.unref();
|
|
@@ -261,7 +279,7 @@ export class SessionResources {
|
|
|
261
279
|
const before = await currentHash(path);
|
|
262
280
|
if (before !== null && !args.overwrite)
|
|
263
281
|
throw new Error('Target exists; explicit overwrite authorization required');
|
|
264
|
-
details = { path, parent: await realpath(dirname(path)), temp: join(dirname(path), `.${basename(path)}.diagnose-${task.id}`), beforeSha256: before, size: args.size, sha256: args.sha256, offset: 0 };
|
|
282
|
+
details = { path, parent: await realpath(dirname(path)), temp: join(dirname(path), `.${basename(path)}.diagnose-${task.id}`), beforeSha256: before, mode: before === null ? 0o600 : (await lstat(path)).mode & 0o777, size: args.size, sha256: args.sha256, offset: 0 };
|
|
265
283
|
}
|
|
266
284
|
signal?.throwIfAborted();
|
|
267
285
|
const { resource, token } = this.create(task.id, args.direction, owner, args.retainOnDisconnect, details);
|
|
@@ -312,9 +330,19 @@ export class SessionResources {
|
|
|
312
330
|
throw new Error('Upload SHA-256 mismatch; destination untouched');
|
|
313
331
|
if (await realpath(dirname(String(meta.path))) !== meta.parent || await currentHash(String(meta.path)) !== meta.beforeSha256)
|
|
314
332
|
throw new Error('Destination changed since upload authorization');
|
|
333
|
+
if (closed || resource.owner !== owner)
|
|
334
|
+
throw new Error('Transfer authorization was revoked');
|
|
335
|
+
await file.chmod(Number(meta.mode ?? 0o600));
|
|
315
336
|
await file.close();
|
|
337
|
+
if (closed || resource.owner !== owner)
|
|
338
|
+
throw new Error('Transfer authorization was revoked');
|
|
316
339
|
closed = true;
|
|
317
|
-
|
|
340
|
+
if (meta.beforeSha256 === null) {
|
|
341
|
+
await link(String(meta.temp), String(meta.path));
|
|
342
|
+
await unlink(String(meta.temp));
|
|
343
|
+
}
|
|
344
|
+
else
|
|
345
|
+
await rename(String(meta.temp), String(meta.path));
|
|
318
346
|
meta.state = 'committed';
|
|
319
347
|
this.journal.save(meta);
|
|
320
348
|
this.audit.record('resource.file-changed', { id: meta.id, path: meta.path, beforeSha256: meta.beforeSha256, afterSha256: meta.sha256, bytes: meta.size });
|
|
@@ -403,22 +431,15 @@ export class SessionResources {
|
|
|
403
431
|
this.journal.save(resource.meta);
|
|
404
432
|
return { ...publicMeta(resource.meta), resumeToken: token };
|
|
405
433
|
}
|
|
406
|
-
async disconnect(owner) {
|
|
407
|
-
|
|
408
|
-
resource.owner = '';
|
|
409
|
-
if (!resource.meta.retainOnDisconnect)
|
|
410
|
-
await resource.close();
|
|
411
|
-
} }
|
|
434
|
+
async disconnect(owner) { const affected = [...this.resources.values()].filter(resource => resource.owner === owner); for (const resource of affected)
|
|
435
|
+
resource.owner = ''; await Promise.all(affected.filter(resource => !resource.meta.retainOnDisconnect).map(resource => resource.close())); }
|
|
412
436
|
async abandon(task, owner) { const id = task.operation === 'resource.resume' ? task.arguments.id : task.id, resource = this.resources.get(id); if (resource?.owner === owner) {
|
|
413
437
|
resource.owner = '';
|
|
414
438
|
if (task.operation !== 'resource.resume' || !resource.meta.retainOnDisconnect)
|
|
415
439
|
await resource.close();
|
|
416
440
|
} }
|
|
417
|
-
async revoke(owner) {
|
|
418
|
-
|
|
419
|
-
resource.owner = '';
|
|
420
|
-
await resource.close();
|
|
421
|
-
} }
|
|
441
|
+
async revoke(owner) { const affected = [...this.resources.values()].filter(resource => owner === undefined || resource.owner === owner); for (const resource of affected)
|
|
442
|
+
resource.owner = ''; await Promise.all(affected.map(resource => resource.close())); }
|
|
422
443
|
listLocal() { return [...this.resources.values()].map(resource => publicMeta(resource.meta)); }
|
|
423
444
|
async localInput(id, value) { const resource = this.resources.get(id); if (!resource?.input || resource.meta.state !== 'running')
|
|
424
445
|
throw new Error('No live process with this ID'); this.audit.record('resource.local-input', { id, bytes: value.length }); await resource.input(value, false); }
|
package/dist/schema.d.ts
CHANGED
|
@@ -729,12 +729,14 @@ export type WireMessage = {
|
|
|
729
729
|
type: 'session.accepted';
|
|
730
730
|
label: string;
|
|
731
731
|
fingerprint: string;
|
|
732
|
+
credential?: string;
|
|
732
733
|
} | {
|
|
733
734
|
type: 'session.closed';
|
|
734
735
|
reason: string;
|
|
735
736
|
} | {
|
|
736
737
|
type: 'task.request';
|
|
737
738
|
task: Task;
|
|
739
|
+
sequence?: number;
|
|
738
740
|
} | {
|
|
739
741
|
type: 'task.started';
|
|
740
742
|
id: string;
|
package/dist/schema.js
CHANGED
|
@@ -31,13 +31,13 @@ export const resourceRequestSchema = z.object({ id: z.string().uuid().optional()
|
|
|
31
31
|
export function parseMessage(value) {
|
|
32
32
|
const basic = z.object({ type: z.string() }).passthrough().parse(value);
|
|
33
33
|
switch (basic.type) {
|
|
34
|
-
case 'task.request': return { type: basic.type, task: taskSchema.parse(basic.task) };
|
|
34
|
+
case 'task.request': return { type: basic.type, task: taskSchema.parse(basic.task), ...(basic.sequence === undefined ? {} : { sequence: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).parse(basic.sequence) }) };
|
|
35
35
|
case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
|
|
36
36
|
case 'resource.request': return { type: basic.type, requestId: z.string().uuid().parse(basic.requestId), request: resourceRequestSchema.parse(basic.request) };
|
|
37
37
|
case 'resource.result': return z.object({ type: z.literal('resource.result'), requestId: z.string().uuid(), value: z.unknown().optional(), error: z.string().max(2000).optional() }).strict().parse(value);
|
|
38
38
|
case 'ping':
|
|
39
39
|
case 'pong': return { type: basic.type };
|
|
40
|
-
case 'session.accepted': return z.object({ type: z.literal('session.accepted'), label: z.string().max(120), fingerprint: z.string().max(100) }).strict().parse(value);
|
|
40
|
+
case 'session.accepted': return z.object({ type: z.literal('session.accepted'), label: z.string().max(120), fingerprint: z.string().max(100), credential: z.string().regex(/^D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}$/).optional() }).strict().parse(value);
|
|
41
41
|
case 'session.closed': return z.object({ type: z.literal('session.closed'), reason: z.string().max(200) }).strict().parse(value);
|
|
42
42
|
case 'task.started': return z.object({ type: z.literal('task.started'), id: z.string().uuid(), digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict().parse(value);
|
|
43
43
|
case 'task.output': return z.object({ type: z.literal('task.output'), id: z.string().uuid(), stream: z.string().max(20), chunk: z.string().max(CHUNK_SIZE * 2), index: z.number().int().min(0) }).strict().parse(value);
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare function pakeMessage(stage: string, value: string): Buffer;
|
|
2
|
+
export declare function pakeValue(bytes: Buffer, expected: string): string;
|
|
3
|
+
export declare class InvitationHost {
|
|
4
|
+
private room;
|
|
5
|
+
private setup;
|
|
6
|
+
private record;
|
|
7
|
+
private state?;
|
|
8
|
+
constructor(room: string, password: Buffer);
|
|
9
|
+
start(bytes: Buffer): Buffer;
|
|
10
|
+
finish(bytes: Buffer): Buffer;
|
|
11
|
+
reset(): void;
|
|
12
|
+
destroy(): void;
|
|
13
|
+
}
|
|
14
|
+
export declare class InvitationJoin {
|
|
15
|
+
private room;
|
|
16
|
+
private password;
|
|
17
|
+
private state?;
|
|
18
|
+
constructor(room: string, password: Buffer);
|
|
19
|
+
start(): Buffer;
|
|
20
|
+
finish(bytes: Buffer): {
|
|
21
|
+
reply: Buffer;
|
|
22
|
+
secret: Buffer;
|
|
23
|
+
};
|
|
24
|
+
destroy(): void;
|
|
25
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import * as opaque from '@serenity-kit/opaque';
|
|
2
|
+
import { hkdfSync } from 'node:crypto';
|
|
3
|
+
// Registration runs entirely on the probe. The relay sees neither the password,
|
|
4
|
+
// registration record nor OPAQUE server setup. Both login roles are endpoints.
|
|
5
|
+
await opaque.ready;
|
|
6
|
+
const identifiers = (room) => ({ client: `diagnose/v2/operator/${room}`, server: `diagnose/v2/probe/${room}` });
|
|
7
|
+
const key = (sessionKey, room) => Buffer.from(hkdfSync('sha256', Buffer.from(sessionKey, 'base64url'), 'diagnose/opaque/v2', `noise-psk/${room}`, 32));
|
|
8
|
+
export function pakeMessage(stage, value) { return Buffer.from(JSON.stringify({ pake: stage, value })); }
|
|
9
|
+
export function pakeValue(bytes, expected) {
|
|
10
|
+
if (bytes.length > 4096)
|
|
11
|
+
throw new Error('Oversized PAKE message');
|
|
12
|
+
const value = JSON.parse(bytes.toString());
|
|
13
|
+
if (value?.pake !== expected || typeof value.value !== 'string' || !/^[A-Za-z0-9_+/=-]{1,2048}$/.test(value.value) || Object.keys(value).length !== 2)
|
|
14
|
+
throw new Error('Invalid PAKE message');
|
|
15
|
+
return value.value;
|
|
16
|
+
}
|
|
17
|
+
export class InvitationHost {
|
|
18
|
+
room;
|
|
19
|
+
setup;
|
|
20
|
+
record;
|
|
21
|
+
state;
|
|
22
|
+
constructor(room, password) {
|
|
23
|
+
this.room = room;
|
|
24
|
+
this.setup = opaque.server.createSetup();
|
|
25
|
+
const registration = opaque.client.startRegistration({ password: password.toString() });
|
|
26
|
+
const response = opaque.server.createRegistrationResponse({ serverSetup: this.setup, userIdentifier: room, registrationRequest: registration.registrationRequest });
|
|
27
|
+
this.record = opaque.client.finishRegistration({ clientRegistrationState: registration.clientRegistrationState, registrationResponse: response.registrationResponse, password: password.toString(), identifiers: identifiers(room), keyStretching: 'memory-constrained' }).registrationRecord;
|
|
28
|
+
}
|
|
29
|
+
start(bytes) {
|
|
30
|
+
if (this.state)
|
|
31
|
+
throw new Error('PAKE already started');
|
|
32
|
+
const response = opaque.server.startLogin({ serverSetup: this.setup, registrationRecord: this.record, userIdentifier: this.room, startLoginRequest: pakeValue(bytes, 'start'), identifiers: identifiers(this.room) });
|
|
33
|
+
this.state = response.serverLoginState;
|
|
34
|
+
return pakeMessage('response', response.loginResponse);
|
|
35
|
+
}
|
|
36
|
+
finish(bytes) {
|
|
37
|
+
if (!this.state)
|
|
38
|
+
throw new Error('PAKE not started');
|
|
39
|
+
const state = this.state;
|
|
40
|
+
this.state = undefined;
|
|
41
|
+
const response = opaque.server.finishLogin({ serverLoginState: state, finishLoginRequest: pakeValue(bytes, 'finish'), identifiers: identifiers(this.room) });
|
|
42
|
+
return key(response.sessionKey, this.room);
|
|
43
|
+
}
|
|
44
|
+
reset() { this.state = undefined; }
|
|
45
|
+
destroy() { this.reset(); this.setup = ''; this.record = ''; }
|
|
46
|
+
}
|
|
47
|
+
export class InvitationJoin {
|
|
48
|
+
room;
|
|
49
|
+
password;
|
|
50
|
+
state;
|
|
51
|
+
constructor(room, password) {
|
|
52
|
+
this.room = room;
|
|
53
|
+
this.password = password;
|
|
54
|
+
}
|
|
55
|
+
start() {
|
|
56
|
+
if (this.state)
|
|
57
|
+
throw new Error('PAKE already started');
|
|
58
|
+
const response = opaque.client.startLogin({ password: this.password.toString() });
|
|
59
|
+
this.state = response.clientLoginState;
|
|
60
|
+
return pakeMessage('start', response.startLoginRequest);
|
|
61
|
+
}
|
|
62
|
+
finish(bytes) {
|
|
63
|
+
if (!this.state)
|
|
64
|
+
throw new Error('PAKE not started');
|
|
65
|
+
const state = this.state;
|
|
66
|
+
this.state = undefined;
|
|
67
|
+
const response = opaque.client.finishLogin({ clientLoginState: state, password: this.password.toString(), loginResponse: pakeValue(bytes, 'response'), identifiers: identifiers(this.room), keyStretching: 'memory-constrained' });
|
|
68
|
+
if (!response)
|
|
69
|
+
throw new Error('Incorrect invitation');
|
|
70
|
+
return { reply: pakeMessage('finish', response.finishLoginRequest), secret: key(response.sessionKey, this.room) };
|
|
71
|
+
}
|
|
72
|
+
destroy() { this.state = undefined; }
|
|
73
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type SessionSkill } from './skill.js';
|
|
2
|
+
export declare const skillsUsage = "diagnose skills import NAME FILE.md|DIRECTORY\ndiagnose skills list\nLaunch: diagnose agent codex|claude|gemini --skill library:NAME@REVISION";
|
|
3
|
+
export declare class SkillLibrary {
|
|
4
|
+
readonly root: string;
|
|
5
|
+
constructor(root?: string);
|
|
6
|
+
bundle(reference: string): Promise<{
|
|
7
|
+
reference: string;
|
|
8
|
+
files: {
|
|
9
|
+
path: string;
|
|
10
|
+
data: string;
|
|
11
|
+
}[];
|
|
12
|
+
}>;
|
|
13
|
+
exportTo(reference: string, directory: string): Promise<void>;
|
|
14
|
+
private writeBundle;
|
|
15
|
+
restore(bundle: {
|
|
16
|
+
reference: string;
|
|
17
|
+
files: {
|
|
18
|
+
path: string;
|
|
19
|
+
data: string;
|
|
20
|
+
}[];
|
|
21
|
+
}): Promise<string>;
|
|
22
|
+
import(name: string, input: string): Promise<string>;
|
|
23
|
+
load(reference: string): Promise<SessionSkill>;
|
|
24
|
+
list(): Promise<string[]>;
|
|
25
|
+
}
|
|
26
|
+
export declare function resolveSkill(input: string): Promise<SessionSkill>;
|
|
27
|
+
export declare function skillsCommand(args: string[]): Promise<void>;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, mkdtemp, open, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { loadSkill } from './skill.js';
|
|
7
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
8
|
+
const MAX_FILES = 128;
|
|
9
|
+
const namePattern = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
10
|
+
const revisionPattern = /^[a-f0-9]{64}$/;
|
|
11
|
+
export const skillsUsage = 'diagnose skills import NAME FILE.md|DIRECTORY\ndiagnose skills list\nLaunch: diagnose agent codex|claude|gemini --skill library:NAME@REVISION';
|
|
12
|
+
// Portable names only: reject separators, traversal, Windows aliases and device names.
|
|
13
|
+
function validPart(part) {
|
|
14
|
+
return /^[a-zA-Z0-9_.-]+$/.test(part) && !['.', '..'].includes(part) && !/[. ]$/.test(part) && !/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part);
|
|
15
|
+
}
|
|
16
|
+
async function readBundle(input) {
|
|
17
|
+
const source = resolve(input), info = await lstat(source);
|
|
18
|
+
if (info.isSymbolicLink())
|
|
19
|
+
throw new Error('Skill bundles cannot contain symbolic links');
|
|
20
|
+
const entries = [];
|
|
21
|
+
let total = 0, visited = 0;
|
|
22
|
+
const add = async (file, path) => {
|
|
23
|
+
if (entries.length >= MAX_FILES)
|
|
24
|
+
throw new Error('Skill bundle exceeds 128 files');
|
|
25
|
+
const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
26
|
+
try {
|
|
27
|
+
const metadata = await handle.stat();
|
|
28
|
+
if (!metadata.isFile())
|
|
29
|
+
throw new Error('Skill bundles require regular files');
|
|
30
|
+
if (metadata.size > MAX_BYTES - total)
|
|
31
|
+
throw new Error('Skill bundle exceeds 8 MiB');
|
|
32
|
+
const buffer = Buffer.alloc(MAX_BYTES - total + 1);
|
|
33
|
+
let size = 0;
|
|
34
|
+
while (size < buffer.length) {
|
|
35
|
+
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, size);
|
|
36
|
+
if (!bytesRead)
|
|
37
|
+
break;
|
|
38
|
+
size += bytesRead;
|
|
39
|
+
}
|
|
40
|
+
total += size;
|
|
41
|
+
if (total > MAX_BYTES)
|
|
42
|
+
throw new Error('Skill bundle exceeds 8 MiB');
|
|
43
|
+
entries.push({ path, bytes: Buffer.from(buffer.subarray(0, size)), executable: !!(metadata.mode & 0o111) });
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
await handle.close();
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const walk = async (directory, prefix, depth) => {
|
|
50
|
+
if (depth > 16)
|
|
51
|
+
throw new Error('Skill directory nesting exceeds 16 levels');
|
|
52
|
+
const names = await readdir(directory);
|
|
53
|
+
const portable = new Set();
|
|
54
|
+
for (const name of names.sort()) {
|
|
55
|
+
if (++visited > 256)
|
|
56
|
+
throw new Error('Skill bundle exceeds 256 directory entries');
|
|
57
|
+
if (!validPart(name) || portable.has(name.toLowerCase()))
|
|
58
|
+
throw new Error('Skill bundle contains a non-portable or duplicate path');
|
|
59
|
+
portable.add(name.toLowerCase());
|
|
60
|
+
const file = join(directory, name), path = prefix + name, item = await lstat(file);
|
|
61
|
+
if (item.isSymbolicLink())
|
|
62
|
+
throw new Error('Skill bundles cannot contain symbolic links');
|
|
63
|
+
if (item.isDirectory())
|
|
64
|
+
await walk(file, path + '/', depth + 1);
|
|
65
|
+
else if (item.isFile())
|
|
66
|
+
await add(file, path);
|
|
67
|
+
else
|
|
68
|
+
throw new Error('Skill bundles require regular files');
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
if (info.isDirectory())
|
|
72
|
+
await walk(source, '', 0);
|
|
73
|
+
else {
|
|
74
|
+
await loadSkill(source);
|
|
75
|
+
await add(source, 'SKILL.md');
|
|
76
|
+
}
|
|
77
|
+
if (!entries.some(entry => entry.path === 'SKILL.md'))
|
|
78
|
+
throw new Error('Skill directory requires SKILL.md');
|
|
79
|
+
await loadSkill(info.isDirectory() ? join(source, 'SKILL.md') : source);
|
|
80
|
+
return entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
81
|
+
}
|
|
82
|
+
function digest(entries) {
|
|
83
|
+
// Length-delimited canonical JSON avoids ambiguous path/content concatenation.
|
|
84
|
+
return createHash('sha256').update(JSON.stringify(entries.map(entry => [entry.path, entry.bytes.toString('base64')]))).digest('hex');
|
|
85
|
+
}
|
|
86
|
+
export class SkillLibrary {
|
|
87
|
+
root;
|
|
88
|
+
constructor(root = join(homedir(), '.diagnose', 'skills')) {
|
|
89
|
+
this.root = root;
|
|
90
|
+
}
|
|
91
|
+
async bundle(reference) {
|
|
92
|
+
const skill = await this.load(reference);
|
|
93
|
+
return { reference, files: (await readBundle(skill.baseDirectory)).map(entry => ({ path: entry.path, data: entry.bytes.toString('base64') })) };
|
|
94
|
+
}
|
|
95
|
+
async exportTo(reference, directory) {
|
|
96
|
+
const bundle = await this.bundle(reference);
|
|
97
|
+
await this.writeBundle(bundle.files, directory);
|
|
98
|
+
}
|
|
99
|
+
async writeBundle(files, directory) {
|
|
100
|
+
if (!Array.isArray(files) || files.length > MAX_FILES)
|
|
101
|
+
throw new Error('Invalid skill bundle');
|
|
102
|
+
let total = 0;
|
|
103
|
+
for (const entry of files) {
|
|
104
|
+
if (typeof entry.path !== 'string' || entry.path.length > 2048 || !entry.path.split('/').every(validPart) || typeof entry.data !== 'string')
|
|
105
|
+
throw new Error('Invalid bundle path or content');
|
|
106
|
+
const bytes = Buffer.from(entry.data, 'base64');
|
|
107
|
+
total += bytes.length;
|
|
108
|
+
if (total > MAX_BYTES || bytes.toString('base64') !== entry.data)
|
|
109
|
+
throw new Error('Invalid or oversized bundle content');
|
|
110
|
+
const parts = entry.path.split('/'), name = parts.pop();
|
|
111
|
+
const parent = join(directory, ...parts);
|
|
112
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
113
|
+
await writeFile(join(parent, name), bytes, { flag: 'wx', mode: 0o600 });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async restore(bundle) {
|
|
117
|
+
const match = /^library:([a-z0-9][a-z0-9-]{0,63})@([a-f0-9]{64})$/.exec(bundle.reference);
|
|
118
|
+
if (!match)
|
|
119
|
+
throw new Error('Invalid bundle reference');
|
|
120
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
121
|
+
const directory = await mkdtemp(join(this.root, '.restore-'));
|
|
122
|
+
try {
|
|
123
|
+
await this.writeBundle(bundle.files, directory);
|
|
124
|
+
if (digest(await readBundle(directory)) !== match[2])
|
|
125
|
+
throw new Error('Downloaded bundle failed integrity verification');
|
|
126
|
+
return await this.import(match[1], directory);
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
await rm(directory, { recursive: true, force: true });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async import(name, input) {
|
|
133
|
+
if (!namePattern.test(name) || !validPart(name))
|
|
134
|
+
throw new Error('Skill name must be a portable name of 1..64 lowercase letters, digits or hyphens, starting with a letter or digit');
|
|
135
|
+
const entries = await readBundle(input), revision = digest(entries), parent = join(this.root, name);
|
|
136
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
137
|
+
const reference = `library:${name}@${revision}`, destination = join(parent, revision);
|
|
138
|
+
try {
|
|
139
|
+
await lstat(destination);
|
|
140
|
+
await this.load(reference);
|
|
141
|
+
return reference;
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (error.code !== 'ENOENT')
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
const temporary = await mkdtemp(join(parent, '.import-'));
|
|
148
|
+
try {
|
|
149
|
+
for (const entry of entries) {
|
|
150
|
+
const parts = entry.path.split('/');
|
|
151
|
+
const filename = parts.pop();
|
|
152
|
+
const directory = join(temporary, ...parts);
|
|
153
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
154
|
+
await writeFile(join(directory, filename), entry.bytes, { flag: 'wx', mode: entry.executable ? 0o700 : 0o600 });
|
|
155
|
+
}
|
|
156
|
+
if (digest(await readBundle(temporary)) !== revision)
|
|
157
|
+
throw new Error('Skill changed during import');
|
|
158
|
+
try {
|
|
159
|
+
await rename(temporary, destination);
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
// Windows reports EPERM when another import already published this
|
|
163
|
+
// nonempty directory. Accept only a fully verified existing revision,
|
|
164
|
+
// never an error code alone (which could also mean real permission loss).
|
|
165
|
+
try {
|
|
166
|
+
await this.load(reference);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
await this.load(reference);
|
|
173
|
+
return reference;
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
await rm(temporary, { recursive: true, force: true });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async load(reference) {
|
|
180
|
+
const match = /^library:([^@]+)@([^@]+)$/.exec(reference);
|
|
181
|
+
if (!match || !namePattern.test(match[1]) || !validPart(match[1]) || !revisionPattern.test(match[2]))
|
|
182
|
+
throw new Error('Use library:NAME@FULL_SHA256_REVISION from diagnose skills list');
|
|
183
|
+
const directory = join(this.root, match[1], match[2]);
|
|
184
|
+
if (digest(await readBundle(directory)) !== match[2])
|
|
185
|
+
throw new Error('Stored skill failed integrity verification; import a clean copy');
|
|
186
|
+
return { ...await loadSkill(directory), libraryReference: reference };
|
|
187
|
+
}
|
|
188
|
+
async list() {
|
|
189
|
+
let names;
|
|
190
|
+
try {
|
|
191
|
+
names = await readdir(this.root);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
if (error.code === 'ENOENT')
|
|
195
|
+
return [];
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
const references = [];
|
|
199
|
+
for (const name of names.sort()) {
|
|
200
|
+
if (!namePattern.test(name) || !(await lstat(join(this.root, name))).isDirectory())
|
|
201
|
+
continue;
|
|
202
|
+
for (const revision of (await readdir(join(this.root, name))).sort()) {
|
|
203
|
+
if (revisionPattern.test(revision))
|
|
204
|
+
references.push(`library:${name}@${revision}`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return references;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
export async function resolveSkill(input) {
|
|
211
|
+
return input.startsWith('library:') ? new SkillLibrary().load(input) : loadSkill(input);
|
|
212
|
+
}
|
|
213
|
+
export async function skillsCommand(args) {
|
|
214
|
+
const library = new SkillLibrary();
|
|
215
|
+
if (args[0] === 'import' && args.length === 3) {
|
|
216
|
+
console.log(await library.import(args[1], args[2]));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (args[0] === 'list' && args.length === 1) {
|
|
220
|
+
console.log(JSON.stringify(await library.list(), null, 2));
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (args.length && !['--help', 'help'].includes(args[0]))
|
|
224
|
+
throw new Error(skillsUsage);
|
|
225
|
+
console.log(skillsUsage);
|
|
226
|
+
}
|
package/dist/skill.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type SessionSkill = {
|
|
2
|
+
sourceFile: string;
|
|
3
|
+
baseDirectory: string;
|
|
4
|
+
sha256: string;
|
|
5
|
+
instructions: string;
|
|
6
|
+
libraryReference?: string;
|
|
7
|
+
};
|
|
8
|
+
export declare function loadSkill(input: string): Promise<SessionSkill>;
|
|
9
|
+
export declare function skillPrompt(snapshot: string): string;
|