@masstensor/diagnose 0.7.0 → 0.8.1
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/PAIRING_PROTOCOL.md +1 -1
- package/README.md +22 -8
- package/USER_GUIDE.md +33 -649
- package/dist/cli.js +44 -7
- package/dist/discover.js +1 -1
- package/dist/engine.js +15 -8
- package/dist/install-skill.d.ts +2 -0
- package/dist/install-skill.js +57 -0
- package/dist/mcp.js +27 -4
- package/dist/operator.js +2 -0
- package/dist/peer.d.ts +1 -0
- package/dist/peer.js +24 -3
- package/dist/relay.js +21 -8
- package/dist/schema.d.ts +4 -1
- package/dist/schema.js +2 -2
- package/dist/session-limits.d.ts +3 -0
- package/dist/session-limits.js +3 -0
- package/dist/skill-session.d.ts +1 -0
- package/dist/skill-session.js +272 -0
- package/docs/guide/automation.md +184 -0
- package/docs/guide/diagnose.md +93 -0
- package/docs/guide/on-site.md +139 -0
- package/docs/guide/procedures.md +183 -0
- package/docs/guide/reconnect.md +58 -0
- package/docs/guide/troubleshooting.md +77 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -1
- package/skills/connect/SKILL.md +66 -0
- package/skills/connect/scripts/run.mjs +37 -0
- package/src/cli.ts +42 -8
- package/src/discover.ts +1 -1
- package/src/engine.ts +12 -5
- package/src/install-skill.ts +57 -0
- package/src/mcp.ts +25 -5
- package/src/operator.ts +2 -0
- package/src/peer.ts +24 -4
- package/src/relay.ts +20 -4
- package/src/schema.ts +4 -2
- package/src/session-limits.ts +3 -0
- package/src/skill-session.ts +245 -0
- package/test/cli.test.ts +55 -7
- package/test/install-skill.test.ts +37 -0
- package/test/pairing.test.ts +6 -1
- package/test/review.test.ts +16 -0
- package/test/short-pairing.test.ts +42 -0
- package/test/skill-session.test.ts +93 -0
package/src/cli.ts
CHANGED
|
@@ -22,6 +22,7 @@ import { History } from './history.js';
|
|
|
22
22
|
import { cleanupLocal } from './maintenance.js';
|
|
23
23
|
import { skillsCommand, skillsUsage } from './skill-library.js';
|
|
24
24
|
import { knowledgeCommand, knowledgeUsage } from './knowledge-cli.js';
|
|
25
|
+
import { DEFAULT_IDLE_MS } from './session-limits.js';
|
|
25
26
|
|
|
26
27
|
async function attachTerminal(operator: Operator, id: string): Promise<void> {
|
|
27
28
|
let done = false, cursor = 0; const wasRaw = stdin.isRaw;
|
|
@@ -34,21 +35,29 @@ async function attachTerminal(operator: Operator, id: string): Promise<void> {
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
async function main(): Promise<void> {
|
|
38
|
+
if (process.argv[2] === 'install-skill') {
|
|
39
|
+
await (await import('./install-skill.js')).installSkill(process.argv.slice(3));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (process.argv[2] === 'skill-session') {
|
|
43
|
+
await (await import('./skill-session.js')).skillSessionCommand(process.argv.slice(3));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
37
46
|
if (['cases', 'drafts', 'vault'].includes(process.argv[2])) { await knowledgeCommand(process.argv[2], process.argv.slice(3)); return; }
|
|
38
47
|
if (process.argv[2] === 'skills') { await skillsCommand(process.argv.slice(3)); return; }
|
|
39
48
|
if (process.argv[2] === 'agent') { process.exitCode = await launchAgent(process.argv.slice(3)); return; }
|
|
40
|
-
const { positionals, values } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { 'session-minutes': { type: 'string', default: '
|
|
49
|
+
const { positionals, values } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { 'session-minutes': { type: 'string', default: '0' }, 'idle-minutes': { type: 'string', default: String(DEFAULT_IDLE_MS / 60_000) }, device: { type: 'string' }, case: { type: 'string' }, name: { type: 'string' }, days: { type: 'string', default: '7' }, cursor: { type: 'string', default: '0' } } });
|
|
41
50
|
const [command = 'help', relay = 'https://diagnose.fenginwind.com'] = positionals;
|
|
42
51
|
if (command === 'history') { console.log(safeText(JSON.stringify(new History().list(), null, 2))); return; }
|
|
43
52
|
if (command === 'show') { const cursor = Number(values.cursor); if (!Number.isSafeInteger(cursor) || cursor < 0) throw new Error('Cursor must be a nonnegative integer'); console.log(safeText(JSON.stringify(new History().show(positionals[1] ?? '', cursor), null, 2))); return; }
|
|
44
53
|
if (command === 'cleanup') { console.log(JSON.stringify(cleanupLocal(Number(values.days)), null, 2)); return; }
|
|
45
54
|
if (positionals.length > 2) throw new Error('Usage: diagnose start|connect|terminal|mcp [relay-url]');
|
|
46
55
|
const sessionMinutes = Number(values['session-minutes']), idleMinutes = Number(values['idle-minutes']);
|
|
47
|
-
if (![sessionMinutes, idleMinutes].every(value => Number.isInteger(value) && value >= 0 && value <= 10080)) throw new Error('Timeouts must be 0..10080 minutes; 0 disables endpoint timeout
|
|
56
|
+
if (![sessionMinutes, idleMinutes].every(value => Number.isInteger(value) && value >= 0 && value <= 10080)) throw new Error('Timeouts must be 0..10080 minutes; 0 disables that endpoint timeout');
|
|
48
57
|
if (command === 'devices') { console.log(JSON.stringify(new PairingStore(join(homedir(), '.diagnose', 'pairings')).list('operator').map(({ name, id, relay }) => ({ name, id, relay })), null, 2)); return; }
|
|
49
58
|
if (command === 'forget') { const store = new PairingStore(join(homedir(), '.diagnose', 'pairings')); store.remove(store.get(values.device ?? '', 'operator').id); console.log('Local pairing removed. Revoke on the user computer to invalidate its credential.'); return; }
|
|
50
59
|
if (command === 'mcp') { await serveMcp(relay, values.device, values.case); return; }
|
|
51
|
-
if (!['start', 'connect', 'terminal', 'pair'].includes(command)) { console.log(`diagnose start|connect|terminal|mcp [relay-url] [--device NAME]\ndiagnose pair [relay-url] --name NAME\ndiagnose history\ndiagnose show ID [--cursor OFFSET]\ndiagnose cleanup [--days 7]\ndiagnose devices\ndiagnose forget --device NAME\n${agentUsage}\n${skillsUsage}\n${knowledgeUsage}\nNode.js >=20.10. Pairing codes are entered interactively, never as arguments.`); return; }
|
|
60
|
+
if (!['start', 'connect', 'terminal', 'pair'].includes(command)) { console.log(`diagnose start|connect|terminal|mcp [relay-url] [--device NAME]\ndiagnose pair [relay-url] --name NAME\ndiagnose history\ndiagnose show ID [--cursor OFFSET]\ndiagnose cleanup [--days 7]\ndiagnose devices\ndiagnose forget --device NAME\n${agentUsage}\n${(await import('./install-skill.js')).installSkillUsage}\n${skillsUsage}\n${knowledgeUsage}\nNode.js >=20.10. Pairing codes are entered interactively, never as arguments.`); return; }
|
|
52
61
|
if (!stdin.isTTY || !stdout.isTTY) throw new Error('Interactive terminal required. AI clients should use diagnose mcp.');
|
|
53
62
|
const rl = createInterface({ input: stdin, output: stdout });
|
|
54
63
|
const shutdown = new AbortController(); let peer: Peer | undefined, engine: ProbeEngine | undefined;
|
|
@@ -70,6 +79,16 @@ async function main(): Promise<void> {
|
|
|
70
79
|
if (command === 'start') {
|
|
71
80
|
const store = new PairingStore();
|
|
72
81
|
console.log('Task details and collected results are saved in encrypted local history for up to 7 days (256 MiB budget). View with diagnose history / diagnose show ID; remove inactive records with diagnose cleanup --days 0. Scripts may contain sensitive data.');
|
|
82
|
+
let nextSessionApproval: 'review' | 'tasks' | 'everything' = 'review';
|
|
83
|
+
if (!store.list('host').length) {
|
|
84
|
+
console.log('Auto approval lets the diagnostician run tasks with your OS permissions and receive results without further prompts.');
|
|
85
|
+
console.log('Approve everything also lets anyone with the next one-time invitation connect without confirmation. Share that invitation privately.');
|
|
86
|
+
const choice = (await rl.question('Task approval for the next session? [Enter=review / a=auto tasks only / e=approve everything] ', { signal: shutdown.signal })).trim().toLowerCase();
|
|
87
|
+
nextSessionApproval = choice === 'e' ? 'everything' : choice === 'a' ? 'tasks' : 'review';
|
|
88
|
+
console.log(nextSessionApproval === 'everything' ? 'Approve everything selected for this temporary invitation: connection, task execution, and result transmission.'
|
|
89
|
+
: nextSessionApproval === 'tasks' ? 'Auto approval selected for the next temporary session, subject to your pairing confirmation.'
|
|
90
|
+
: 'You will review task execution and result transfers.');
|
|
91
|
+
}
|
|
73
92
|
const firstAudit = new Audit(); resources = new SessionResources(join(homedir(), '.diagnose', 'resources'), firstAudit); let sessions = 0;
|
|
74
93
|
while (!shutdown.signal.aborted) {
|
|
75
94
|
let remembered: import('./pairing.js').Pairing | undefined = store.list('host')[0];
|
|
@@ -81,11 +100,25 @@ async function main(): Promise<void> {
|
|
|
81
100
|
if (remembered) { audit.record('pairing.reconnected', { id: remembered.id }); return !remembered.paused; }
|
|
82
101
|
if (remember) console.log('REMEMBER THIS DIAGNOSTICIAN: this computer will accept future connections using a new private credential until you type "unpair". Task approval remains enabled. AUTO lasts one hour, across reconnects.');
|
|
83
102
|
console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
103
|
+
if (!remember && nextSessionApproval === 'everything') {
|
|
104
|
+
signal.throwIfAborted();
|
|
105
|
+
nextSessionApproval = 'review';
|
|
106
|
+
audit.record('session.pairing-decision', { allowed: true, fingerprint, approval: 'everything' });
|
|
107
|
+
engine!.setPermissionMode('auto');
|
|
108
|
+
console.log('Connection approved by your startup selection (Approve everything).');
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
const preselectedAuto = nextSessionApproval === 'tasks' && !remember;
|
|
112
|
+
console.log(preselectedAuto ? 'You selected auto approval at startup. Choose y to confirm it or r to connect with per-task review.' : 'Choose y: approve each task/batch and its transfer.\nChoose a: grant automatic execution AND transmission (one hour if remembered; otherwise this temporary session).');
|
|
113
|
+
console.log('AUTO: commands have your OS permissions; results go to the diagnostician and their AI without further prompts. Raw terminal, file and tunnel channels are NOT redacted. A channel grant includes continuing input/output within its scope.\nRevoke locally with "permissions ask", cancel with "cancel", or end with Ctrl+C. Already transmitted data cannot be recalled.');
|
|
114
|
+
const prompt = preselectedAuto ? 'Allow this temporary session with auto approval? [y / r=review / N] '
|
|
115
|
+
: remember ? 'Remember and allow this diagnostician? [y / a=auto for 1 hour / N] ' : 'Allow this temporary diagnostic session? [y / a=auto / N] ';
|
|
116
|
+
const answer = (await rl.question(prompt, { signal })).trim().toLowerCase();
|
|
117
|
+
const auto = preselectedAuto ? answer === 'y' : answer === 'a';
|
|
118
|
+
const allowed = answer === 'y' || (preselectedAuto ? answer === 'r' : auto);
|
|
119
|
+
if (allowed) nextSessionApproval = 'review';
|
|
87
120
|
if (allowed && remember) { provision = createCode(); remembered = store.add({ role: 'host', name: 'diagnostician', label, relay, code: provision }); audit.record('pairing.remembered', { id: remembered.id }); }
|
|
88
|
-
if (
|
|
121
|
+
if (auto) { engine!.setPermissionMode('auto'); if (remembered) { remembered.autoUntil = Date.now() + 3600000; store.save(remembered); scheduleGrant(); } }
|
|
89
122
|
audit.record('session.pairing-decision', { allowed, fingerprint }); return allowed;
|
|
90
123
|
} });
|
|
91
124
|
engine = new ProbeEngine(peer, async request => {
|
|
@@ -112,7 +145,7 @@ async function main(): Promise<void> {
|
|
|
112
145
|
else console.log('No pending grant. First type "permissions auto" and read its explanation.');
|
|
113
146
|
return true;
|
|
114
147
|
}
|
|
115
|
-
if (value === 'permissions ask') { autoRequestedAt = 0; clearTimeout(grantTimer); if (remembered) { remembered.autoUntil = 0; store.save(remembered); } engine!.setPermissionMode('ask'); engine!.cancelAll(); void resources!.revoke().catch(error => console.error(safeText((error as Error).message))); console.log('Approval required. Automatic permissions revoked; any active work is cancelled.'); return true; }
|
|
148
|
+
if (value === 'permissions ask') { nextSessionApproval = 'review'; autoRequestedAt = 0; clearTimeout(grantTimer); if (remembered) { remembered.autoUntil = 0; store.save(remembered); } engine!.setPermissionMode('ask'); engine!.cancelAll(); void resources!.revoke().catch(error => console.error(safeText((error as Error).message))); console.log('Approval required. Automatic permissions revoked; any active work is cancelled.'); return true; }
|
|
116
149
|
if (value === 'cancel') { engine!.cancelAll(); void resources!.revoke().catch(error => console.error(safeText((error as Error).message))); console.log('Cancellation requested for the current task/batch and retained resources.'); return true; }
|
|
117
150
|
if (value === 'jobs') { console.log(safeText(JSON.stringify(resources!.listLocal(), null, 2))); return true; }
|
|
118
151
|
if (value.startsWith('recover ')) { const id = value.slice(8).trim(); console.log(`Resource: ${id}\nNew recovery credential (share privately): ${resources!.renewCredential(id)}`); return true; }
|
|
@@ -137,6 +170,7 @@ async function main(): Promise<void> {
|
|
|
137
170
|
await peer.open();
|
|
138
171
|
console.log(remembered ? `Remembered diagnostician: ${safeText(remembered.label)}. Waiting for connections. Local commands: pairing, pause, resume, unpair, permissions ask, permissions auto [forever], cancel, jobs, exit. Audit: ${audit.path}` : `Relay: ${relay}\nAudit: ${audit.path}\nPairing code (30 minutes, one-time, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
|
|
139
172
|
console.log(`Session ended: ${safeText(await peer.ended)}`);
|
|
173
|
+
if (nextSessionApproval === 'everything') nextSessionApproval = 'review';
|
|
140
174
|
} catch (error) { const collision = (error as Error).message.includes('Invitation locator occupied'); if (!shutdown.signal.aborted) console.log(collision ? 'Choosing another invitation code...' : `Relay unavailable: ${safeText((error as Error).message)}. Retained work remains local; retrying in 3 seconds.`); await delay(collision ? 100 : 3000, undefined, { signal: shutdown.signal }).catch(() => {}); }
|
|
141
175
|
finally { clearTimeout(grantTimer); rl.off('line', onLocalLine); }
|
|
142
176
|
active = false; if (secretPending) await secretPending;
|
package/src/discover.ts
CHANGED
|
@@ -13,5 +13,5 @@ export async function inspectSystem(): Promise<Record<string, unknown>> {
|
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
15
|
const elevated = process.platform === 'win32' ? /S-1-16-(12288|16384)/.test(spawnSync('whoami', ['/groups'], { encoding: 'utf8', timeout: 3000, windowsHide: true }).stdout ?? '') : process.geteuid?.() === 0;
|
|
16
|
-
return { platform: process.platform, arch: process.arch, release: os.release(), node: process.version, hostname: os.hostname(), cwd: process.cwd(), home: os.homedir(), username: os.userInfo().username, elevated, shell: process.platform === 'win32' ? process.env.ComSpec ?? 'cmd.exe' : process.env.SHELL ?? '/bin/sh', commands, serialPorts: await SerialPort.list(), networkInterfaces: os.networkInterfaces(), protocol: 1, version: '0.
|
|
16
|
+
return { platform: process.platform, arch: process.arch, release: os.release(), node: process.version, hostname: os.hostname(), cwd: process.cwd(), home: os.homedir(), username: os.userInfo().username, elevated, shell: process.platform === 'win32' ? process.env.ComSpec ?? 'cmd.exe' : process.env.SHELL ?? '/bin/sh', commands, serialPorts: await SerialPort.list(), networkInterfaces: os.networkInterfaces(), protocol: 1, version: '0.8.1', capabilities: ['batch', 'script', 'process-stdin', 'pty', 'terminal-resize', 'signals', 'concurrent-jobs', 'encrypted-output-journal', 'resource-resume', 'binary-transfer', 'filesystem', 'local-forward', 'remote-forward', 'socks5'] };
|
|
17
17
|
}
|
package/src/engine.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { Audit, digest, redact, safeText } from './util.js';
|
|
|
5
5
|
import { SessionResources, resourceOperation } from './resources.js';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
7
|
import { dirname, join, basename } from 'node:path';
|
|
8
|
+
import { DEFAULT_IDLE_MS } from './session-limits.js';
|
|
8
9
|
|
|
9
10
|
export type PermissionMode = 'ask' | 'auto';
|
|
10
11
|
function aborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
|
|
@@ -46,15 +47,21 @@ export class ProbeEngine {
|
|
|
46
47
|
constructor(private peer: Peer, private approve: ApprovalHandler, readonly audit: Audit, private notice: (message: string) => void = () => {}, options: { resources?: SessionResources; idleMs?: number; lifetimeMs?: number } = {}) {
|
|
47
48
|
this.resources = options.resources ?? new SessionResources(join(dirname(audit.path), basename(audit.path) + '.resources'), audit);
|
|
48
49
|
this.resources.setAudit(audit);
|
|
50
|
+
const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
|
|
51
|
+
const refreshIdle = () => {
|
|
52
|
+
if (!idleMs || this.ended) return;
|
|
53
|
+
clearTimeout(this.idle);
|
|
54
|
+
this.idle = setTimeout(() => peer.close('Idle timeout'), idleMs);
|
|
55
|
+
};
|
|
49
56
|
// Waiting for an invitation/approval is not diagnostic session time.
|
|
50
|
-
// Otherwise the default ten-minute idle timer would cut a 30-minute code short.
|
|
51
57
|
void peer.active.then(() => {
|
|
52
58
|
if (this.ended) return;
|
|
53
|
-
|
|
54
|
-
if (options.lifetimeMs
|
|
59
|
+
refreshIdle();
|
|
60
|
+
if (options.lifetimeMs) this.lifetime = setTimeout(() => peer.close('Session lifetime exceeded'), options.lifetimeMs);
|
|
55
61
|
}).catch(() => {});
|
|
62
|
+
peer.on('activity', refreshIdle);
|
|
56
63
|
peer.on('message', (message: WireMessage) => {
|
|
57
|
-
|
|
64
|
+
refreshIdle();
|
|
58
65
|
if (message.type === 'resource.request') { void this.resources.control(this.owner, message.request).then(value => this.peer.send({ type: 'resource.result', requestId: message.requestId, value }), error => this.peer.send({ type: 'resource.result', requestId: message.requestId, error: redact((error as Error).message).slice(0, 2000) })).catch(() => {}); return; }
|
|
59
66
|
if (message.type === 'task.cancel') { try { audit.record('task.cancel-requested', { id: message.id, source: 'operator' }); this.jobs.get(message.id)?.abort(); void this.resources.control(this.owner, { id: message.id, action: 'close', cursor: 0, limit: 65536, eof: false }).catch(() => {}); } catch { peer.close('Audit unavailable'); } return; }
|
|
60
67
|
if (message.type !== 'task.request') { peer.close('Unexpected operator message'); return; }
|
|
@@ -74,7 +81,7 @@ export class ProbeEngine {
|
|
|
74
81
|
const controller = new AbortController(); this.jobs.set(task.id, controller);
|
|
75
82
|
void this.run(task, controller);
|
|
76
83
|
});
|
|
77
|
-
peer.on('closed', () => { this.ended = true; clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values()) controller.abort(); void this.resources.disconnect(this.owner).catch(() => {}); try { audit.record('session.closed', {}); } catch { /* Session is already closed. */ } });
|
|
84
|
+
peer.on('closed', (reason?: string) => { this.ended = true; clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values()) controller.abort(); void this.resources.disconnect(this.owner).catch(() => {}); try { audit.record('session.closed', { reason: reason && redact(reason) }); } catch { /* Session is already closed. */ } });
|
|
78
85
|
}
|
|
79
86
|
private async reply(id: string, result: Result): Promise<void> { await this.peer.send({ type: 'task.result', id, result }).catch(() => {}); }
|
|
80
87
|
private async finish(id: string, result: Result): Promise<void> { this.jobs.delete(id); await this.reply(id, result); }
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
export const installSkillUsage = 'diagnose install-skill claude|codex|gemini';
|
|
8
|
+
const locations = new Map([
|
|
9
|
+
['claude', { directory: '.claude', invocation: '/diagnose' }],
|
|
10
|
+
['codex', { directory: '.agents', invocation: '$diagnose' }],
|
|
11
|
+
['gemini', { directory: '.gemini', invocation: 'Use the Diagnose skill' }],
|
|
12
|
+
]);
|
|
13
|
+
|
|
14
|
+
export async function installSkill(args: string[]): Promise<void> {
|
|
15
|
+
const agent = args.length === 1 ? locations.get(args[0]!) : undefined;
|
|
16
|
+
if (!agent) throw new Error('Usage: ' + installSkillUsage);
|
|
17
|
+
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
18
|
+
const source = join(root, 'skills', 'connect');
|
|
19
|
+
const library = join(homedir(), agent.directory, 'skills');
|
|
20
|
+
const target = join(library, 'diagnose');
|
|
21
|
+
const [skill, helper] = await Promise.all([
|
|
22
|
+
readFile(join(source, 'SKILL.md'), 'utf8'),
|
|
23
|
+
readFile(join(source, 'scripts/run.mjs')),
|
|
24
|
+
]);
|
|
25
|
+
const files = new Map([
|
|
26
|
+
['SKILL.md', Buffer.from(skill.replace(/^name: connect$/m, 'name: diagnose'))],
|
|
27
|
+
['scripts/run.mjs', helper],
|
|
28
|
+
]);
|
|
29
|
+
const runtime = 'scripts/local-runtime.json';
|
|
30
|
+
if (existsSync(join(root, '.git'))) {
|
|
31
|
+
files.set(runtime, Buffer.from(JSON.stringify({ cli: join(root, 'dist', 'cli.js') }) + '\n'));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
await mkdir(library, { recursive: true, mode: 0o700 });
|
|
35
|
+
try {
|
|
36
|
+
await mkdir(target, { mode: 0o700 });
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
|
|
39
|
+
const sameFiles = (await Promise.all([...files].map(async ([file, bytes]) =>
|
|
40
|
+
(await readFile(join(target, file)).catch(() => undefined))?.equals(bytes) === true
|
|
41
|
+
))).every(Boolean) && (files.has(runtime) || !existsSync(join(target, runtime)));
|
|
42
|
+
if (!sameFiles) throw new Error('A different Skill already exists at ' + target + '. Move it before installing.');
|
|
43
|
+
console.log('Diagnose Skill is already installed at ' + target);
|
|
44
|
+
console.log('In a new agent session, use ' + agent.invocation + '.');
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
await mkdir(join(target, 'scripts'), { mode: 0o700 });
|
|
50
|
+
for (const [file, bytes] of files) await writeFile(join(target, file), bytes, { mode: 0o600, flag: 'wx' });
|
|
51
|
+
} catch (error) {
|
|
52
|
+
await rm(target, { recursive: true, force: true });
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
console.log('Installed Diagnose Skill at ' + target);
|
|
56
|
+
console.log('In a new agent session, use ' + agent.invocation + '.');
|
|
57
|
+
}
|
package/src/mcp.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
2
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import { Peer } from './peer.js';
|
|
4
|
+
import { Peer, pairingProgress } from './peer.js';
|
|
5
5
|
import { Operator } from './operator.js';
|
|
6
6
|
import { atomicOperationNames, batchOperationNames, resourceRequestSchema } from './schema.js';
|
|
7
7
|
import type { TaskInput } from './schema.js';
|
|
@@ -13,7 +13,7 @@ import { safeText } from './util.js';
|
|
|
13
13
|
import { registerKnowledge } from './knowledge-mcp.js';
|
|
14
14
|
|
|
15
15
|
export async function serveMcp(relay: string, device?: string, caseId?: string): Promise<void> {
|
|
16
|
-
const server = new McpServer({ name: 'diagnose', version: '0.
|
|
16
|
+
const server = new McpServer({ name: 'diagnose', version: '0.8.1' });
|
|
17
17
|
let operator: Operator | undefined;
|
|
18
18
|
let remembered = device ? new RememberedConnection(new PairingStore().get(device, 'operator')) : undefined;
|
|
19
19
|
const transfers = new Map<string, { progress: TransferProgress; controller: AbortController }>(), forwards = new Map<string, Forward>();
|
|
@@ -23,10 +23,22 @@ export async function serveMcp(relay: string, device?: string, caseId?: string):
|
|
|
23
23
|
const observed = new WeakSet<Operator>();
|
|
24
24
|
const attach = (value: Operator) => { value.observe = knowledge.observe; if (!observed.has(value)) { observed.add(value); value.peer.once('closed', () => { connectionState = 'disconnected'; if (operator === value) operator = undefined; }); } connectionState = 'connected'; return value; };
|
|
25
25
|
const connected = async (): Promise<Operator> => { try { if (remembered) return attach(await remembered.connect()); if (!operator) throw new Error('Pair first, or launch with --device NAME'); return attach(operator); } catch (error) { connectionState = 'unavailable'; throw error; } };
|
|
26
|
-
server.registerTool('diagnose_pair', { description: 'Connect using the user-shared nine-letter invitation (abc-def-ghi; case, spaces and hyphens ignored). Legacy D1 codes are also accepted. The
|
|
26
|
+
server.registerTool('diagnose_pair', { description: 'Connect using the user-shared nine-letter invitation (abc-def-ghi; case, spaces and hyphens ignored). Legacy D1 codes are also accepted. The probe may ask for local confirmation. Label is self-asserted; identify the AI/provider handling results.', inputSchema: { code: z.string(), label: z.string().min(1).max(120) } }, async ({ code, label }, extra) => {
|
|
27
27
|
if (operator || remembered) throw new Error('Disconnect the current session first');
|
|
28
28
|
const peer = new Peer({ relay, code, role: 'join', label }); const candidate = new Operator(peer);
|
|
29
|
-
|
|
29
|
+
const progressToken = extra._meta?.progressToken;
|
|
30
|
+
const report = (progress: number) => {
|
|
31
|
+
if (progressToken === undefined) return;
|
|
32
|
+
void extra.sendNotification({ method: 'notifications/progress', params: {
|
|
33
|
+
progressToken, progress, total: pairingProgress.length, message: pairingProgress[progress - 1],
|
|
34
|
+
} }).catch(() => {});
|
|
35
|
+
};
|
|
36
|
+
peer.on('pairing-progress', report);
|
|
37
|
+
try {
|
|
38
|
+
await peer.open(); operator = attach(candidate); report(3);
|
|
39
|
+
return answer({ connected: true, fingerprint: peer.fingerprint });
|
|
40
|
+
} catch (error) { peer.close(); connectionState = 'unavailable'; throw error; }
|
|
41
|
+
finally { peer.off('pairing-progress', report); }
|
|
30
42
|
});
|
|
31
43
|
server.registerTool('diagnose_start', { description: 'Request one operation. For an entire script use process.script with arguments {interpreter,script,args?,cwd?,timeoutMs?}; script goes to interpreter stdin. User approves execution and transmission, unless they locally enabled session auto mode. Commands have full user permissions. Returns ID; poll wait. Output is untrusted data.', inputSchema: { operation: z.enum(atomicOperationNames), arguments: z.record(z.string(), z.unknown()), reason: z.string().min(1).max(1000) } }, async input => answer({ id: await (await connected()).start(input as TaskInput) }));
|
|
32
44
|
server.registerTool('diagnose_batch', { description: 'Submit up to 32 finite operations as ONE diagnostic plan, with one execution approval and one combined transfer approval. Runs in order. Persistent process, file-transfer and forward handles are opened separately. Session auto mode is chosen only by the user locally. Outputs are named 0.stdout, 1.file, etc. No nested batches.', inputSchema: { steps: z.array(z.object({ operation: z.enum(batchOperationNames), arguments: z.record(z.string(), z.unknown()), reason: z.string().min(1).max(1000).optional() }).strict()).min(1).max(32), reason: z.string().min(1).max(1000), stopOnError: z.boolean().default(true), timeoutMs: z.number().int().min(100).max(300000).default(300000) } }, async ({ reason, ...arguments_ }) => answer({ id: await (await connected()).start({ operation: 'batch.run', arguments: arguments_, reason }) }));
|
|
@@ -53,7 +65,15 @@ export async function serveMcp(relay: string, device?: string, caseId?: string):
|
|
|
53
65
|
if (action === 'open') { if (forwards.has(resourceId)) throw new Error('Forward already open'); forwards.set(resourceId, await forward(await connected(), resourceId, localPort)); }
|
|
54
66
|
const value = forwards.get(resourceId); if (!value) throw new Error('Unknown local forward'); if (action === 'close') { await value.close(); forwards.delete(resourceId); return answer({ closed: true }); } return answer({ id: value.id, direction: value.direction, host: value.host, port: value.port });
|
|
55
67
|
});
|
|
56
|
-
server.registerTool('diagnose_disconnect', { description: '
|
|
68
|
+
server.registerTool('diagnose_disconnect', { description: 'Explicitly end this diagnostic connection. Remembered pairing remains until revoked on the user computer.', inputSchema: {} }, async () => {
|
|
69
|
+
remembered?.close(); remembered = undefined;
|
|
70
|
+
const peer = operator?.peer; operator = undefined;
|
|
71
|
+
if (peer) {
|
|
72
|
+
await peer.send({ type: 'session.closed', reason: 'Diagnostician ended session' }).catch(() => {});
|
|
73
|
+
peer.close();
|
|
74
|
+
}
|
|
75
|
+
return answer({ disconnected: true });
|
|
76
|
+
});
|
|
57
77
|
let stopped = false;
|
|
58
78
|
const stop = () => { if (stopped) return; stopped = true; for (const transfer of transfers.values()) transfer.controller.abort(); for (const value of forwards.values()) void value.close(); remembered?.close(); operator?.peer.close(); knowledge.close(); void server.close(); };
|
|
59
79
|
process.once('exit', () => knowledge.close());
|
package/src/operator.ts
CHANGED
|
@@ -47,6 +47,8 @@ export class Operator {
|
|
|
47
47
|
}
|
|
48
48
|
async wait(id: string, timeoutMs = 1000): Promise<Outcome | { id: string; pending: true }> {
|
|
49
49
|
const job = this.jobs.get(id); if (!job) throw new Error('Unknown or expired task result; completed results are bounded to 128 tasks / 32 MiB. Do not replay modifications; inspect remote state or local history.');
|
|
50
|
+
// Polling a real task is diagnostic activity even though the result is cached locally.
|
|
51
|
+
void this.peer.send({ type: 'ping', activity: true }).catch(() => {});
|
|
50
52
|
let timer: NodeJS.Timeout | undefined;
|
|
51
53
|
try { return await Promise.race([job.promise, new Promise<{ id: string; pending: true }>(resolve => { timer = setTimeout(() => resolve({ id, pending: true }), timeoutMs); })]); }
|
|
52
54
|
finally { clearTimeout(timer); }
|
package/src/peer.ts
CHANGED
|
@@ -4,8 +4,14 @@ import { Handshake, parseCode, parseInvitation, INVITATION_MS, type SecureCipher
|
|
|
4
4
|
import { CHUNK_SIZE, MAX_FRAME, parseMessage, type WireMessage } from './schema.js';
|
|
5
5
|
import { safeText } from './util.js';
|
|
6
6
|
import { InvitationHost, InvitationJoin } from './short-pairing.js';
|
|
7
|
+
import { LEGACY_RELAY_MAX_MS } from './session-limits.js';
|
|
7
8
|
|
|
8
9
|
export type PeerOptions = { role: 'host' | 'join'; code: string; relay: string; label?: string; remember?: boolean; provision?: () => string | undefined; accept?: (peer: { label: string; fingerprint: string; signal: AbortSignal; remember: boolean }) => Promise<boolean>; approvalTimeoutMs?: number; sessionMs?: number; invitationMs?: number };
|
|
10
|
+
export const pairingProgress = [
|
|
11
|
+
'Connected to the relay. Verifying the on-site probe.',
|
|
12
|
+
'Authenticated the on-site probe. Waiting for it to accept the connection. Approve on site if prompted.',
|
|
13
|
+
'Paired with the on-site probe.',
|
|
14
|
+
] as const;
|
|
9
15
|
function deferred<T>() { let resolve!: (value: T) => void; let reject!: (error: Error) => void; const promise = new Promise<T>((a, b) => { resolve = a; reject = b; }); promise.catch(() => {}); return { promise, resolve, reject }; }
|
|
10
16
|
export function relayUrl(value: string): string {
|
|
11
17
|
const url = new URL(value);
|
|
@@ -56,9 +62,16 @@ export class Peer extends EventEmitter {
|
|
|
56
62
|
this.ws = new WebSocket(relayUrl(options.relay), { maxPayload: MAX_FRAME, perMessageDeflate: false, handshakeTimeout: 10000 });
|
|
57
63
|
this.connectionTimer = setTimeout(() => this.close('Relay registration timeout'), 12000);
|
|
58
64
|
if (short && options.role === 'host') this.invitationTimer = setTimeout(() => this.close('Invitation expired; generate a new code'), Math.min(options.invitationMs ?? INVITATION_MS, INVITATION_MS));
|
|
59
|
-
this.ws.on('open', () =>
|
|
65
|
+
this.ws.on('open', () => {
|
|
66
|
+
this.ws.send(JSON.stringify({ version: short ? 2 : 1, role: options.role, room }));
|
|
67
|
+
if (options.role === 'join') this.emit('pairing-progress', 1);
|
|
68
|
+
});
|
|
60
69
|
this.ws.on('error', () => this.close('Relay connection failed'));
|
|
61
|
-
this.ws.on('close', (_code, reason) =>
|
|
70
|
+
this.ws.on('close', (_code, reason) => {
|
|
71
|
+
const message = reason.toString();
|
|
72
|
+
this.close(message === 'Invitation locator occupied' ? 'Invitation locator occupied; generating a new code'
|
|
73
|
+
: message === 'Session expired' ? 'Relay session expired' : 'Relay disconnected');
|
|
74
|
+
});
|
|
62
75
|
this.ws.on('message', (bytes, binary) => {
|
|
63
76
|
try {
|
|
64
77
|
if (binary) this.receive(Buffer.from(bytes as Buffer));
|
|
@@ -124,13 +137,16 @@ export class Peer extends EventEmitter {
|
|
|
124
137
|
clearTimeout(timer);
|
|
125
138
|
if (this.destroyed || generation !== this.generation) return;
|
|
126
139
|
if (!allowed || this.approval?.signal.aborted) { await this.send({ type: 'session.closed', reason: 'User declined pairing' }); this.close('User declined pairing'); return; }
|
|
127
|
-
this.ws.send(JSON.stringify(
|
|
140
|
+
this.ws.send(JSON.stringify(this.options.sessionMs
|
|
141
|
+
? { type: 'lock', ttlMs: this.options.sessionMs }
|
|
142
|
+
: { type: 'lock', sliding: true, ttlMs: LEGACY_RELAY_MAX_MS }));
|
|
128
143
|
this.approved = true;
|
|
129
144
|
await this.send({ type: 'session.accepted', label: safeText(this.options.label ?? 'User probe'), fingerprint: this.fingerprint, ...(hello.remember === true && this.options.provision?.() ? { credential: this.options.provision!() } : {}) });
|
|
130
145
|
this.activate();
|
|
131
146
|
})().catch(() => this.close('Pairing approval failed'));
|
|
132
147
|
} else {
|
|
133
148
|
this.cipher = this.handshake.split(); this.handshake = undefined; this.fingerprint = this.cipher.fingerprint;
|
|
149
|
+
this.emit('pairing-progress', 2);
|
|
134
150
|
}
|
|
135
151
|
return;
|
|
136
152
|
}
|
|
@@ -148,7 +164,10 @@ export class Peer extends EventEmitter {
|
|
|
148
164
|
clearTimeout(this.handshakeTimer); this.approved = true; this.activate(); return;
|
|
149
165
|
}
|
|
150
166
|
if (!this.approved) throw new Error('Not authorized');
|
|
151
|
-
if (message.type === 'ping') {
|
|
167
|
+
if (message.type === 'ping') {
|
|
168
|
+
if (message.activity && this.options.role === 'host') this.emit('activity');
|
|
169
|
+
void this.send({ type: 'pong' }).catch(() => this.close('Heartbeat failed')); return;
|
|
170
|
+
}
|
|
152
171
|
if (message.type === 'pong') return;
|
|
153
172
|
this.emit('message', message);
|
|
154
173
|
}
|
|
@@ -174,6 +193,7 @@ export class Peer extends EventEmitter {
|
|
|
174
193
|
// Bound sustained traffic below the relay's shared per-room frame budget.
|
|
175
194
|
await new Promise(resolve => setTimeout(resolve, 10));
|
|
176
195
|
}
|
|
196
|
+
if (message.type.startsWith('task.') || message.type.startsWith('resource.')) this.emit('activity');
|
|
177
197
|
}).finally(() => { this.queuedBytes -= payload.length; });
|
|
178
198
|
this.queue = operation.catch(() => this.close('Encrypted transport failed'));
|
|
179
199
|
return operation;
|
package/src/relay.ts
CHANGED
|
@@ -4,14 +4,20 @@ import { WebSocket, WebSocketServer } from 'ws';
|
|
|
4
4
|
import { MAX_FRAME } from './schema.js';
|
|
5
5
|
import { INVITATION_MS } from './crypto.js';
|
|
6
6
|
import { VaultServer } from './vault-server.js';
|
|
7
|
+
import { DEFAULT_IDLE_MS, LEGACY_RELAY_MAX_MS } from './session-limits.js';
|
|
7
8
|
|
|
8
9
|
export type RelayOptions = { host?: string; port?: number; invitationMs?: number; sessionMs?: number; maxRooms?: number; downloadPath?: string; vaultPath?: string; observeCiphertext?: (bytes: Buffer) => void };
|
|
9
|
-
type Room = { short: boolean; host: WebSocket; peer?: WebSocket; locked: boolean; attempts: number; expires: number; frames: number; window: number };
|
|
10
|
+
type Room = { short: boolean; host: WebSocket; peer?: WebSocket; locked: boolean; attempts: number; expires: number; renewMs?: number; frames: number; window: number };
|
|
10
11
|
const control = (ws: WebSocket, type: string, extra = {}): void => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type, ...extra })); };
|
|
11
12
|
|
|
12
13
|
export function createRelay(options: RelayOptions = {}) {
|
|
13
14
|
const vault = options.vaultPath ? new VaultServer(options.vaultPath) : undefined;
|
|
14
15
|
const rooms = new Map<string, Room>();
|
|
16
|
+
const expireRoom = (id: string, room: Room): void => {
|
|
17
|
+
rooms.delete(id);
|
|
18
|
+
room.host.close(1000, 'Session expired');
|
|
19
|
+
room.peer?.close(1000, 'Session expired');
|
|
20
|
+
};
|
|
15
21
|
const clients = new Map<WebSocket, { role?: 'host' | 'join'; room?: string; ip: string; alive: boolean }>();
|
|
16
22
|
const connectionsByIp = new Map<string, number>();
|
|
17
23
|
const connectionRates = new Map<string, { since: number; count: number }>();
|
|
@@ -69,7 +75,8 @@ export function createRelay(options: RelayOptions = {}) {
|
|
|
69
75
|
clearTimeout(registration); return;
|
|
70
76
|
}
|
|
71
77
|
const room = rooms.get(state.room!);
|
|
72
|
-
if (!room
|
|
78
|
+
if (!room) throw new Error();
|
|
79
|
+
if (room.expires <= Date.now()) { expireRoom(state.room!, room); return; }
|
|
73
80
|
if (binary) {
|
|
74
81
|
if (Date.now() - room.window > 1000) { room.window = Date.now(); room.frames = 0; }
|
|
75
82
|
if (++room.frames > 250 || bytes.length > MAX_FRAME) throw new Error();
|
|
@@ -77,12 +84,21 @@ export function createRelay(options: RelayOptions = {}) {
|
|
|
77
84
|
if (!target || target.readyState !== WebSocket.OPEN || target.bufferedAmount > 1024 * 1024) throw new Error();
|
|
78
85
|
let buffered = 0; for (const client of clients.keys()) buffered += client.bufferedAmount;
|
|
79
86
|
if (buffered > 64 * 1024 * 1024) throw new Error();
|
|
87
|
+
// The relay can see ciphertext traffic, not diagnostic activity. The
|
|
88
|
+
// probe enforces the real idle timeout without counting heartbeats.
|
|
89
|
+
if (room.renewMs) room.expires = Date.now() + room.renewMs;
|
|
80
90
|
options.observeCiphertext?.(bytes);
|
|
81
91
|
target.send(bytes, { binary: true }); return;
|
|
82
92
|
}
|
|
83
93
|
if (bytes.length > 128 || state.role !== 'host') throw new Error();
|
|
84
94
|
const msg = JSON.parse(bytes.toString());
|
|
85
|
-
if (msg.type === 'lock' && !room.locked) {
|
|
95
|
+
if (msg.type === 'lock' && !room.locked) {
|
|
96
|
+
const requested = msg.ttlMs;
|
|
97
|
+
if (requested !== undefined && (!Number.isInteger(requested) || requested < 60000 || requested > LEGACY_RELAY_MAX_MS)) throw new Error();
|
|
98
|
+
room.locked = true;
|
|
99
|
+
if (msg.sliding === true) room.renewMs = options.sessionMs ?? DEFAULT_IDLE_MS;
|
|
100
|
+
room.expires = Date.now() + (room.renewMs ?? requested ?? options.sessionMs ?? DEFAULT_IDLE_MS);
|
|
101
|
+
}
|
|
86
102
|
else if (msg.type === 'reject' && !room.locked) { const peer = room.peer; room.peer = undefined; peer?.close(1008, 'Pairing rejected'); }
|
|
87
103
|
else throw new Error();
|
|
88
104
|
} catch { ws.close(1008, 'Protocol rejected'); }
|
|
@@ -97,7 +113,7 @@ export function createRelay(options: RelayOptions = {}) {
|
|
|
97
113
|
});
|
|
98
114
|
});
|
|
99
115
|
const sweep = setInterval(() => {
|
|
100
|
-
for (const [id, room] of rooms) if (room.expires
|
|
116
|
+
for (const [id, room] of rooms) if (room.expires <= Date.now()) expireRoom(id, room);
|
|
101
117
|
for (const [ws, state] of clients) { if (!state.alive) ws.terminate(); else { state.alive = false; ws.ping(); } }
|
|
102
118
|
}, 10000);
|
|
103
119
|
sweep.unref();
|
package/src/schema.ts
CHANGED
|
@@ -50,7 +50,8 @@ export type WireMessage =
|
|
|
50
50
|
| { type: 'resource.result'; requestId: string; value?: unknown; error?: string }
|
|
51
51
|
| { type: 'resource.request'; requestId: string; request: ResourceRequest }
|
|
52
52
|
| { type: 'resource.result'; requestId: string; value?: unknown; error?: string }
|
|
53
|
-
| { type: 'ping'
|
|
53
|
+
| { type: 'ping'; activity?: true }
|
|
54
|
+
| { type: 'pong' };
|
|
54
55
|
|
|
55
56
|
export function parseMessage(value: unknown): WireMessage {
|
|
56
57
|
const basic = z.object({ type: z.string() }).passthrough().parse(value);
|
|
@@ -59,7 +60,8 @@ export function parseMessage(value: unknown): WireMessage {
|
|
|
59
60
|
case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
|
|
60
61
|
case 'resource.request': return { type: basic.type, requestId: z.string().uuid().parse(basic.requestId), request: resourceRequestSchema.parse(basic.request) };
|
|
61
62
|
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);
|
|
62
|
-
case 'ping':
|
|
63
|
+
case 'ping': return basic.activity === true ? { type: 'ping', activity: true } : { type: 'ping' };
|
|
64
|
+
case 'pong': return { type: 'pong' };
|
|
63
65
|
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);
|
|
64
66
|
case 'session.closed': return z.object({ type: z.literal('session.closed'), reason: z.string().max(200) }).strict().parse(value);
|
|
65
67
|
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);
|