@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.
Files changed (46) hide show
  1. package/PAIRING_PROTOCOL.md +1 -1
  2. package/README.md +22 -8
  3. package/USER_GUIDE.md +33 -649
  4. package/dist/cli.js +44 -7
  5. package/dist/discover.js +1 -1
  6. package/dist/engine.js +15 -8
  7. package/dist/install-skill.d.ts +2 -0
  8. package/dist/install-skill.js +57 -0
  9. package/dist/mcp.js +27 -4
  10. package/dist/operator.js +2 -0
  11. package/dist/peer.d.ts +1 -0
  12. package/dist/peer.js +24 -3
  13. package/dist/relay.js +21 -8
  14. package/dist/schema.d.ts +4 -1
  15. package/dist/schema.js +2 -2
  16. package/dist/session-limits.d.ts +3 -0
  17. package/dist/session-limits.js +3 -0
  18. package/dist/skill-session.d.ts +1 -0
  19. package/dist/skill-session.js +272 -0
  20. package/docs/guide/automation.md +184 -0
  21. package/docs/guide/diagnose.md +93 -0
  22. package/docs/guide/on-site.md +139 -0
  23. package/docs/guide/procedures.md +183 -0
  24. package/docs/guide/reconnect.md +58 -0
  25. package/docs/guide/troubleshooting.md +77 -0
  26. package/npm-shrinkwrap.json +2 -2
  27. package/package.json +3 -1
  28. package/skills/connect/SKILL.md +66 -0
  29. package/skills/connect/scripts/run.mjs +37 -0
  30. package/src/cli.ts +42 -8
  31. package/src/discover.ts +1 -1
  32. package/src/engine.ts +12 -5
  33. package/src/install-skill.ts +57 -0
  34. package/src/mcp.ts +25 -5
  35. package/src/operator.ts +2 -0
  36. package/src/peer.ts +24 -4
  37. package/src/relay.ts +20 -4
  38. package/src/schema.ts +4 -2
  39. package/src/session-limits.ts +3 -0
  40. package/src/skill-session.ts +245 -0
  41. package/test/cli.test.ts +55 -7
  42. package/test/install-skill.test.ts +37 -0
  43. package/test/pairing.test.ts +6 -1
  44. package/test/review.test.ts +16 -0
  45. package/test/short-pairing.test.ts +42 -0
  46. package/test/skill-session.test.ts +93 -0
@@ -0,0 +1,245 @@
1
+ import { fork } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
6
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
7
+ import { pairingProgress, relayUrl } from './peer.js';
8
+ import { DEFAULT_IDLE_MS } from './session-limits.js';
9
+
10
+ const cli = fileURLToPath(new URL('./cli.js', import.meta.url));
11
+ const loopback = '127.0.0.1';
12
+ const defaultRelay = 'https://diagnose.fenginwind.com';
13
+ const requestMs = 135_000;
14
+ const diagnosticOperations = new Set([
15
+ 'system.inspect', 'file.read', 'file.stat', 'file.list', 'file.write',
16
+ 'process.run', 'serial.capture', 'serial.exchange',
17
+ ]);
18
+ const tools = new Set(['diagnose_start', 'diagnose_batch', 'diagnose_wait', 'diagnose_cancel']);
19
+
20
+ type Json = Record<string, unknown>;
21
+ type Endpoint = { port: number; secret: string };
22
+
23
+ function record(value: unknown): Json {
24
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Expected a JSON object');
25
+ return value as Json;
26
+ }
27
+
28
+ async function readJson(stream: NodeJS.ReadableStream): Promise<Json> {
29
+ const chunks: Buffer[] = [];
30
+ let length = 0;
31
+ for await (const part of stream) {
32
+ const bytes = Buffer.from(part);
33
+ length += bytes.length;
34
+ if (length > 2 * 1024 * 1024) throw new Error('JSON request is too large');
35
+ chunks.push(bytes);
36
+ }
37
+ let parsed: unknown;
38
+ try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
39
+ catch { throw new Error('Invalid JSON on stdin or in session request'); }
40
+ return record(parsed);
41
+ }
42
+
43
+ function respond(response: ServerResponse, status: number, body: unknown): void {
44
+ response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
45
+ response.end(JSON.stringify(body));
46
+ }
47
+
48
+ function validateCall(name: unknown, args: Json): asserts name is string {
49
+ if (typeof name !== 'string' || !tools.has(name)) throw new Error('Unsupported tool for a skill session');
50
+ if (name === 'diagnose_start' && !diagnosticOperations.has(String(args.operation))) throw new Error('Unsupported operation for a skill session');
51
+ if (name === 'diagnose_batch' && (!Array.isArray(args.steps) || args.steps.some(step => !diagnosticOperations.has(String(record(step).operation))))) {
52
+ throw new Error('Unsupported batch operation for a skill session');
53
+ }
54
+ }
55
+
56
+ async function serve(relay: string): Promise<void> {
57
+ if (!process.send || !process.connected) throw new Error('Skill session worker must be started by the CLI');
58
+ const secret = randomBytes(32).toString('hex');
59
+ const client = new Client({ name: 'diagnose-skill-session', version: '1' });
60
+ const transport = new StdioClientTransport({ command: process.execPath, args: [cli, 'mcp', relay], stderr: 'ignore' });
61
+ let idle: NodeJS.Timeout | undefined;
62
+ let stopped = false;
63
+ let closing = false;
64
+ let connected = false;
65
+ let busy = false;
66
+ const stop = () => {
67
+ if (stopped) return;
68
+ stopped = true;
69
+ clearTimeout(idle);
70
+ server.close();
71
+ server.closeAllConnections();
72
+ void client.close().catch(() => {});
73
+ if (process.connected) process.disconnect?.();
74
+ };
75
+ const refreshIdle = (ms = DEFAULT_IDLE_MS) => {
76
+ clearTimeout(idle);
77
+ idle = setTimeout(stop, ms);
78
+ };
79
+ const handle = async (request: IncomingMessage, response: ServerResponse) => {
80
+ if (request.headers.authorization !== 'Bearer ' + secret) {
81
+ respond(response, 403, { error: 'Invalid skill session' });
82
+ return;
83
+ }
84
+ if (request.method !== 'POST' || !['/pair', '/call', '/close'].includes(request.url ?? '')) {
85
+ respond(response, 404, { error: 'Unknown skill session action' });
86
+ return;
87
+ }
88
+ if (closing) { respond(response, 409, { error: 'Skill session is closing' }); return; }
89
+ if (request.url === '/close') {
90
+ closing = true;
91
+ if (connected) await client.callTool({ name: 'diagnose_disconnect', arguments: {} }, undefined, { timeout: 3000 }).catch(() => {});
92
+ response.once('finish', stop);
93
+ respond(response, 200, { disconnected: true });
94
+ return;
95
+ }
96
+ if (busy) {
97
+ respond(response, 409, { error: 'Another call is in progress for this session' });
98
+ return;
99
+ }
100
+ busy = true;
101
+ let activity = false;
102
+ try {
103
+ const input = await readJson(request);
104
+ let name: string;
105
+ let args: Json;
106
+ if (request.url === '/pair') {
107
+ if (connected) throw new Error('Skill session is already paired');
108
+ args = { code: input.code, label: input.label };
109
+ name = 'diagnose_pair';
110
+ } else {
111
+ if (!connected) throw new Error('Skill session is not paired');
112
+ args = record(input.arguments);
113
+ validateCall(input.tool, args);
114
+ name = input.tool;
115
+ activity = true;
116
+ refreshIdle();
117
+ }
118
+ const result = await client.callTool({ name, arguments: args }, undefined, {
119
+ timeout: requestMs,
120
+ ...(name === 'diagnose_pair' && { onprogress: ({ progress }) => {
121
+ if (progress < pairingProgress.length && process.connected) process.send?.({ progress }, () => {});
122
+ } }),
123
+ });
124
+ if (result.isError) {
125
+ const content = result.content;
126
+ const error = Array.isArray(content) ? content.find(item => item.type === 'text')?.text : undefined;
127
+ respond(response, 400, { error: typeof error === 'string' ? error : 'Diagnose rejected the request' });
128
+ } else {
129
+ if (name === 'diagnose_pair') {
130
+ connected = true;
131
+ refreshIdle();
132
+ }
133
+ respond(response, 200, result.structuredContent ?? result.content);
134
+ }
135
+ } catch (error) {
136
+ respond(response, 400, { error: (error as Error).message });
137
+ } finally {
138
+ busy = false;
139
+ if (activity && !stopped) refreshIdle();
140
+ }
141
+ };
142
+ const server = createServer((request, response) => { void handle(request, response); });
143
+ server.maxConnections = 8;
144
+ server.requestTimeout = requestMs;
145
+ process.once('SIGINT', stop);
146
+ process.once('SIGTERM', stop);
147
+ client.onclose = stop;
148
+ try {
149
+ await client.connect(transport, { timeout: 15_000 });
150
+ await new Promise<void>((resolve, reject) => {
151
+ server.once('error', reject);
152
+ server.listen(0, loopback, resolve);
153
+ });
154
+ const port = (server.address() as { port: number }).port;
155
+ refreshIdle(requestMs + 25_000);
156
+ process.send({ port, secret });
157
+ } catch (error) {
158
+ stop();
159
+ throw error;
160
+ }
161
+ }
162
+
163
+ function endpoint(value: unknown): Endpoint {
164
+ if (typeof value !== 'string' || !/^\d{1,5}\.[a-f0-9]{64}$/.test(value)) throw new Error('Invalid skill session handle');
165
+ const [port, secret] = value.split('.');
166
+ if (Number(port) < 1 || Number(port) > 65535) throw new Error('Invalid skill session handle');
167
+ return { port: Number(port), secret: secret! };
168
+ }
169
+
170
+ async function requestSession(session: Endpoint, action: string, body: Json = {}): Promise<Json> {
171
+ let response: Response;
172
+ try {
173
+ response = await fetch(`http://${loopback}:${session.port}/${action}`, {
174
+ method: 'POST',
175
+ headers: { authorization: 'Bearer ' + session.secret, 'content-type': 'application/json' },
176
+ body: JSON.stringify(body),
177
+ signal: AbortSignal.timeout(requestMs + 5000),
178
+ });
179
+ } catch {
180
+ throw new Error('Skill session unavailable or timed out. Inspect the result before retrying a change.');
181
+ }
182
+ const result = record(await response.json());
183
+ if (!response.ok) throw new Error(String(result.error ?? 'Skill session request failed'));
184
+ return result;
185
+ }
186
+
187
+ async function open(input: Json): Promise<Json> {
188
+ if (typeof input.code !== 'string' || input.code.length > 120 || !input.code.trim()) throw new Error('Supply the one-time pairing code on stdin');
189
+ if (typeof input.label !== 'string' || !input.label.trim() || input.label.length > 120) throw new Error('Supply a diagnostic label on stdin');
190
+ if (input.relay !== undefined && typeof input.relay !== 'string') throw new Error('Invalid relay URL');
191
+ const relay = input.relay ?? defaultRelay;
192
+ relayUrl(relay);
193
+ console.error('Connecting to the Diagnose relay.');
194
+ const worker = fork(cli, ['skill-session', '_serve', relay], { detached: true, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
195
+ try {
196
+ const session = await new Promise<Endpoint>((resolve, reject) => {
197
+ const done = (error?: Error, result?: Endpoint) => {
198
+ clearTimeout(timer);
199
+ worker.off('error', failed);
200
+ worker.off('exit', exited);
201
+ worker.off('message', ready);
202
+ if (error) reject(error);
203
+ else resolve(result!);
204
+ };
205
+ const failed = (error: Error) => done(error);
206
+ const exited = () => done(new Error('Skill session worker exited during startup'));
207
+ const ready = (message: Endpoint) => {
208
+ try { done(undefined, endpoint(`${message.port}.${message.secret}`)); }
209
+ catch (error) { done(error as Error); }
210
+ };
211
+ const timer = setTimeout(() => done(new Error('Skill session worker did not start')), 20_000);
212
+ worker.once('error', failed);
213
+ worker.once('exit', exited);
214
+ worker.once('message', ready);
215
+ });
216
+ worker.on('message', (message: { progress?: number }) => {
217
+ if (typeof message.progress !== 'number') return;
218
+ const text = pairingProgress[message.progress - 1];
219
+ if (text) console.error(text);
220
+ });
221
+ const result = await requestSession(session, 'pair', { code: input.code, label: input.label });
222
+ console.error(pairingProgress[2]);
223
+ worker.disconnect();
224
+ worker.unref();
225
+ return { ...result, session: session.port + '.' + session.secret, idleSeconds: DEFAULT_IDLE_MS / 1000 };
226
+ } catch (error) {
227
+ worker.kill();
228
+ throw error;
229
+ }
230
+ }
231
+
232
+ export async function skillSessionCommand(args: string[]): Promise<void> {
233
+ if (args[0] === '_serve' && args.length === 2) {
234
+ await serve(args[1]!);
235
+ return;
236
+ }
237
+ const [action] = args;
238
+ if (args.length !== 1 || !['open', 'call', 'close'].includes(action ?? '')) {
239
+ throw new Error('Usage: diagnose skill-session open|call|close (JSON on stdin)');
240
+ }
241
+ const input = await readJson(process.stdin);
242
+ const result = action === 'open' ? await open(input)
243
+ : await requestSession(endpoint(input.session), action!, action === 'call' ? { tool: input.tool, arguments: input.arguments } : {});
244
+ console.log(JSON.stringify(result));
245
+ }
package/test/cli.test.ts CHANGED
@@ -12,12 +12,13 @@ test('actual host CLI displays and enforces pairing, execution and transfer prom
12
12
  const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`;
13
13
  // macOS script accepts a POSIX pipe, but not Node's socketpair-backed stdin.
14
14
  const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'diagnose-cli-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: mkdtempSync(tmpdir() + '/diagnose-cli-') }, stdio: ['pipe', 'pipe', 'pipe'] });
15
- let text = '', pairing = false, executing = false, sending = false;
15
+ let text = '', startup = false, pairing = false, executing = false, sending = false;
16
16
  let stderr = ''; child.stderr.on('data', bytes => { stderr += bytes.toString(); });
17
17
  let codeResolve!: (value: string) => void;
18
18
  const code = new Promise<string>(resolve => { codeResolve = resolve; });
19
19
  child.stdout.on('data', bytes => {
20
20
  text += bytes.toString(); const match = /\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/.exec(text); if (match) codeResolve(match[0]);
21
+ if (!startup && text.includes('Task approval for the next session?')) { startup = true; child.stdin.write('\n'); }
21
22
  if (!pairing && text.includes('Allow this temporary diagnostic session?')) { pairing = true; child.stdin.write('y\n'); }
22
23
  if (!executing && text.includes('Allow exactly this operation?')) { executing = true; child.stdin.write('y\n'); }
23
24
  if (!sending && text.includes('Send these results (')) { sending = true; child.stdin.write('y\n'); }
@@ -28,19 +29,21 @@ test('actual host CLI displays and enforces pairing, execution and transfer prom
28
29
  const pairCode = await Promise.race([code, new Promise<never>((_, reject) => child.once('exit', () => reject(new Error('CLI exited before registration: ' + stderr))))]);
29
30
  peer = new Peer({ role: 'join', code: pairCode, relay: url }); const operator = new Operator(peer); await peer.open();
30
31
  const result = await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'Verify terminal approvals' });
31
- assert.equal(result.result.status, 'ok'); assert.ok(pairing && executing && sending); assert.ok(text.includes('TRANSFER APPROVAL'));
32
+ assert.equal(result.result.status, 'ok'); assert.ok(startup && pairing && executing && sending); assert.ok(text.includes('TRANSFER APPROVAL'));
32
33
  } finally { clearTimeout(timer); peer?.close(); child.stdin.end('\x03'); if (child.pid) { try { process.kill(-child.pid, 'SIGTERM'); } catch {} } await relay.close(); }
33
34
  });
34
35
 
35
- test('host CLI auto selection skips task prompts, can revoke, and requires local confirmation to enable again', { skip: process.platform !== 'darwin', timeout: 15000 }, async () => {
36
+ test('host CLI offers auto before the invitation, confirms at pairing and limits it to that session', { skip: process.platform !== 'darwin', timeout: 15000 }, async () => {
36
37
  const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`;
37
38
  const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'diagnose-cli-auto-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: mkdtempSync(tmpdir() + '/diagnose-cli-auto-') }, stdio: ['pipe', 'pipe', 'pipe'] });
38
- let output = '', paired = false, executionPrompts = 0, transferPrompts = 0; let resolveCode!: (value: string) => void;
39
+ let output = '', startup = false, paired = false, secondPair = false, executionPrompts = 0, transferPrompts = 0; let resolveCode!: (value: string) => void;
39
40
  const code = new Promise<string>(resolve => { resolveCode = resolve; });
40
41
  child.stderr.resume();
41
42
  child.stdout.on('data', bytes => {
42
43
  output += bytes.toString(); const match = /\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/.exec(output); if (match) resolveCode(match[0]);
43
- if (!paired && output.includes('Allow this temporary diagnostic session?')) { paired = true; child.stdin.write('a\n'); }
44
+ if (!startup && output.includes('Task approval for the next session?')) { startup = true; child.stdin.write('a\n'); }
45
+ if (!paired && output.includes('Allow this temporary session with auto approval?')) { paired = true; child.stdin.write('y\n'); }
46
+ if (!secondPair && output.includes('Allow this temporary diagnostic session?')) { secondPair = true; child.stdin.write('y\n'); }
44
47
  const executionCount = output.split('Allow exactly this operation?').length - 1;
45
48
  if (executionCount > executionPrompts) { executionPrompts = executionCount; child.stdin.write('n\n'); }
46
49
  transferPrompts = output.split('Send these results (').length - 1;
@@ -48,7 +51,10 @@ test('host CLI auto selection skips task prompts, can revoke, and requires local
48
51
  const waitFor = async (predicate: () => boolean) => { for (let i = 0; i < 100 && !predicate(); i++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(predicate()); };
49
52
  let peer: Peer | undefined;
50
53
  try {
51
- peer = new Peer({ role: 'join', code: await code, relay: url }); const operator = new Operator(peer); await peer.open();
54
+ const firstCode = await code;
55
+ assert.ok(startup && output.includes('Auto approval selected'));
56
+ assert.ok(output.indexOf('Task approval for the next session?') < output.indexOf(firstCode));
57
+ peer = new Peer({ role: 'join', code: firstCode, relay: url }); const operator = new Operator(peer); await peer.open();
52
58
  const plan = { operation: 'batch.run' as const, arguments: { steps: [{ operation: 'process.script', arguments: { interpreter: process.execPath, script: 'console.log("CLI auto")' } }, { operation: 'system.inspect', arguments: {} }] }, reason: 'Verify CLI auto plan' };
53
59
  const result = await operator.run(plan); assert.equal(result.result.status, 'ok'); assert.equal(result.outputs['0.stdout'], 'CLI auto\n'); assert.equal(executionPrompts, 0); assert.equal(transferPrompts, 0); assert.ok(output.includes('without further prompts'));
54
60
  child.stdin.write('permissions ask\n'); await waitFor(() => output.includes('Automatic permissions revoked'));
@@ -56,6 +62,48 @@ test('host CLI auto selection skips task prompts, can revoke, and requires local
56
62
  child.stdin.write('permissions auto\n'); await waitFor(() => output.includes('within 60 seconds to grant'));
57
63
  child.stdin.write('permissions allow-auto\n'); await waitFor(() => output.split('Permission mode: auto').length >= 3);
58
64
  const again = await operator.run(plan); assert.equal(again.result.status, 'ok'); assert.equal(executionPrompts, 1); assert.equal(transferPrompts, 0);
65
+ peer.close();
66
+ const codes = () => [...new Set(output.match(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/g) ?? [])];
67
+ await waitFor(() => codes().length >= 2);
68
+ peer = new Peer({ role: 'join', code: codes()[1], relay: url });
69
+ const nextOperator = new Operator(peer); await peer.open();
70
+ const next = await nextOperator.run({ operation: 'system.inspect', arguments: {}, reason: 'New sessions require fresh approval' });
71
+ assert.equal(next.result.status, 'denied'); assert.ok(secondPair); assert.equal(executionPrompts, 2);
72
+ } finally { peer?.close(); child.stdin.end('\x03'); if (child.pid) { try { process.kill(-child.pid, 'SIGTERM'); } catch {} } await relay.close(); }
73
+ });
74
+
75
+ test('Approve everything accepts a short invitation once and automatically executes and sends the result', { skip: process.platform !== 'darwin', timeout: 15000 }, async () => {
76
+ const relay = createRelay({ port: 0 }), url = `ws://127.0.0.1:${await relay.listen()}`;
77
+ const root = mkdtempSync(join(tmpdir(), 'diagnose-cli-all-'));
78
+ const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'diagnose-cli-all-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: root }, stdio: ['pipe', 'pipe', 'pipe'] });
79
+ let output = '', startup = false, secondPrompt = false;
80
+ child.stderr.resume();
81
+ child.stdout.on('data', bytes => {
82
+ output += bytes.toString();
83
+ if (!startup && output.includes('e=approve everything')) { startup = true; child.stdin.write('e\n'); }
84
+ if (!secondPrompt && output.includes('Allow this temporary diagnostic session?')) { secondPrompt = true; child.stdin.write('n\n'); }
85
+ });
86
+ const codes = () => [...new Set(output.match(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/g) ?? [])];
87
+ const untilCode = async (index: number) => {
88
+ for (let i = 0; i < 200 && !codes()[index]; i++) await new Promise(resolve => setTimeout(resolve, 20));
89
+ assert.ok(codes()[index], output);
90
+ return codes()[index]!;
91
+ };
92
+ let peer: Peer | undefined;
93
+ try {
94
+ peer = new Peer({ role: 'join', code: await untilCode(0), relay: url });
95
+ const operator = new Operator(peer);
96
+ await peer.open();
97
+ assert.match(output, /Connection approved by your startup selection/);
98
+ const result = await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'Verify session-wide approval' });
99
+ assert.equal(result.result.status, 'ok');
100
+ assert.match(output, /\[AUTO send\] system\.inspect/);
101
+ assert.doesNotMatch(output, /EXECUTION APPROVAL|TRANSFER APPROVAL/);
102
+ assert.equal(secondPrompt, false);
103
+ peer.close();
104
+ peer = new Peer({ role: 'join', code: await untilCode(1), relay: url });
105
+ await assert.rejects(peer.open());
106
+ assert.equal(secondPrompt, true, 'A new invitation must require local pairing approval');
59
107
  } finally { peer?.close(); child.stdin.end('\x03'); if (child.pid) { try { process.kill(-child.pid, 'SIGTERM'); } catch {} } await relay.close(); }
60
108
  });
61
109
 
@@ -74,7 +122,7 @@ test('terminal CLI attaches a native PTY and executes interactive input', { skip
74
122
  test('host CLI re-pairs after disconnect and resumes retained process without rerunning it', { skip: process.platform !== 'darwin', timeout: 15000 }, async () => {
75
123
  const childHome = mkdtempSync(join(tmpdir(), 'diagnose-repair-')), relay = createRelay({ port: 0 }), url = `ws://127.0.0.1:${await relay.listen()}`;
76
124
  const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'repair-test', process.execPath, 'dist/cli.js', 'start', url], { detached: true, env: { ...process.env, HOME: childHome }, stdio: ['pipe', 'pipe', 'pipe'] });
77
- let output = '', approvals = 0; child.stderr.resume(); child.stdout.on('data', bytes => { output += bytes.toString(); const count = output.split('Allow this temporary diagnostic session?').length - 1; if (count > approvals) { approvals = count; child.stdin.write('a\n'); } });
125
+ let output = '', startup = false, approvals = 0; child.stderr.resume(); child.stdout.on('data', bytes => { output += bytes.toString(); if (!startup && output.includes('Task approval for the next session?')) { startup = true; child.stdin.write('\n'); } const count = output.split('Allow this temporary diagnostic session?').length - 1; if (count > approvals) { approvals = count; child.stdin.write('a\n'); } });
78
126
  const codes = () => [...new Set(output.match(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/g) ?? [])];
79
127
  const until = async (predicate: () => boolean) => { for (let n = 0; n < 200 && !predicate(); n++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(predicate(), output); };
80
128
  let peer: Peer | undefined;
@@ -0,0 +1,37 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join, resolve } from 'node:path';
7
+
8
+ test('installs each native Skill, uses the source build outside the project, and preserves existing files', () => {
9
+ const home = mkdtempSync(join(tmpdir(), 'diagnose-install-skill-'));
10
+ const cli = resolve('dist/cli.js');
11
+ const env = { ...process.env, HOME: home, USERPROFILE: home };
12
+ delete (env as NodeJS.ProcessEnv).DIAGNOSE_SKILL_CLI;
13
+ const install = (agent: string) => spawnSync(process.execPath, [cli, 'install-skill', agent], { cwd: home, env, encoding: 'utf8' });
14
+ try {
15
+ for (const [agent, directory] of [['claude', '.claude'], ['codex', '.agents'], ['gemini', '.gemini']]) {
16
+ const result = install(agent);
17
+ assert.equal(result.status, 0, result.stderr);
18
+ const skill = join(home, directory!, 'skills', 'diagnose');
19
+ const nativeSkill = readFileSync('skills/connect/SKILL.md', 'utf8');
20
+ assert.match(nativeSkill, /^name: connect$/m);
21
+ assert.equal(readFileSync(join(skill, 'SKILL.md'), 'utf8'), nativeSkill.replace(/^name: connect$/m, 'name: diagnose'));
22
+ const helper = spawnSync(process.execPath, [join(skill, 'scripts/run.mjs'), 'open'], { cwd: home, env, input: '{}', encoding: 'utf8' });
23
+ assert.equal(helper.status, 1);
24
+ assert.match(helper.stderr, /Supply the one-time pairing code on stdin/);
25
+ const repeated = install(agent);
26
+ assert.equal(repeated.status, 0, repeated.stderr);
27
+ assert.match(repeated.stdout, /already installed/);
28
+ }
29
+ const custom = join(home, '.claude', 'skills', 'diagnose', 'SKILL.md');
30
+ writeFileSync(custom, 'my custom skill');
31
+ const conflict = install('claude');
32
+ assert.equal(conflict.status, 1);
33
+ assert.match(conflict.stderr, /A different Skill already exists/);
34
+ assert.equal(readFileSync(custom, 'utf8'), 'my custom skill');
35
+ assert.equal(install('unknown-agent').status, 1);
36
+ } finally { rmSync(home, { recursive: true, force: true }); }
37
+ });
@@ -50,7 +50,12 @@ test('actual host survives probe and relay restarts, pauses access, and revokes
50
50
  let output = '', pairPrompts = 0;
51
51
  const start = () => {
52
52
  const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'remember-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: root }, stdio: ['pipe', 'pipe', 'pipe'] });
53
- child.stderr.resume(); child.stdout.on('data', bytes => { output += bytes.toString(); if (output.includes('Remember and allow this diagnostician?') && !pairPrompts) { pairPrompts++; child.stdin.write('a\n'); } }); return child;
53
+ let startup = false;
54
+ child.stderr.resume(); child.stdout.on('data', bytes => {
55
+ output += bytes.toString();
56
+ if (!startup && output.includes('Task approval for the next session?')) { startup = true; child.stdin.write('e\n'); }
57
+ if (output.includes('Remember and allow this diagnostician?') && !pairPrompts) { pairPrompts++; child.stdin.write('a\n'); }
58
+ }); return child;
54
59
  };
55
60
  let child = start(), peer: Peer | undefined;
56
61
  const until = async (predicate: () => boolean) => { for (let i = 0; i < 300 && !predicate(); i++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(predicate(), output); };
@@ -73,6 +73,22 @@ class FixturePeer extends EventEmitter {
73
73
  close(reason: string) { this.emit('closed', reason); }
74
74
  request(task: Task, sequence: number): Promise<WireMessage> { return new Promise(resolve => { this.response = value => { if (value.type === 'task.result') resolve(value); }; this.emit('message', { type: 'task.request', task, sequence }); }); }
75
75
  }
76
+ test('probe resets its six-hour idle timeout on activity without a fixed total limit', async t => {
77
+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
78
+ const peer = new FixturePeer(), reasons: string[] = [];
79
+ peer.on('closed', reason => reasons.push(reason));
80
+ new ProbeEngine(peer as unknown as Peer, async () => false, new Audit(join(directory(), 'audit.jsonl')));
81
+ await peer.active;
82
+ for (let round = 0; round < 3; round++) {
83
+ t.mock.timers.tick(5 * 60 * 60_000);
84
+ assert.deepEqual(reasons, []);
85
+ peer.emit('activity');
86
+ }
87
+ t.mock.timers.tick(6 * 60 * 60_000 - 1);
88
+ assert.deepEqual(reasons, []);
89
+ t.mock.timers.tick(1);
90
+ assert.deepEqual(reasons, ['Idle timeout']);
91
+ });
76
92
  test('more than 1000 sequenced tasks work and replayed sequences are rejected', { timeout: 60000 }, async () => {
77
93
  const root = directory(), peer = new FixturePeer(); let approvals = 0;
78
94
  new ProbeEngine(peer as unknown as Peer, async () => { approvals++; return false; }, new Audit(join(root, 'audit.jsonl')), () => {}, { idleMs: 0, lifetimeMs: 0 });
@@ -98,3 +98,45 @@ test('session idle and lifetime clocks start after pairing, not while the code i
98
98
  try { await joiner.open(); assert.equal(await host.ended, 'Idle timeout'); }
99
99
  finally { joiner.close(); host.close(); await relay.close(); await rm(root, { recursive: true, force: true }); }
100
100
  });
101
+
102
+ test('relay renews the locked room on encrypted traffic past six hours and expires a silent room', { timeout: 10000 }, async t => {
103
+ let now = Date.now();
104
+ t.mock.method(Date, 'now', () => now);
105
+ const relay = createRelay({ port: 0 }), url = 'ws://127.0.0.1:' + await relay.listen(), code = createInvitation();
106
+ const host = new Peer({ role: 'host', code, relay: url, accept: async () => true });
107
+ let joiner: Peer | undefined;
108
+ try {
109
+ await host.open();
110
+ joiner = new Peer({ role: 'join', code, relay: url });
111
+ await joiner.open();
112
+ await host.active;
113
+ for (let round = 0; round < 3; round++) {
114
+ now += 5 * 60 * 60_000;
115
+ const received = once(host, 'message');
116
+ await joiner.send({ type: 'task.cancel', id: '26155a8b-c35a-436e-948a-9797732e6259' });
117
+ assert.equal((await received)[0].type, 'task.cancel');
118
+ }
119
+ now += 6 * 60 * 60_000;
120
+ await joiner.send({ type: 'ping' });
121
+ assert.equal(await host.ended, 'Relay session expired');
122
+ assert.equal(await joiner.ended, 'Relay session expired');
123
+ } finally { joiner?.close(); host.close(); await relay.close(); }
124
+ });
125
+
126
+ test('normal heartbeat is not diagnostic activity but an explicit result poll is', { timeout: 5000 }, async () => {
127
+ const relay = createRelay({ port: 0 }), url = 'ws://127.0.0.1:' + await relay.listen(), code = createInvitation();
128
+ const host = new Peer({ role: 'host', code, relay: url, accept: async () => true });
129
+ await host.open();
130
+ const joiner = new Peer({ role: 'join', code, relay: url });
131
+ let activity = 0;
132
+ host.on('activity', () => { activity++; });
133
+ try {
134
+ await joiner.open();
135
+ await joiner.send({ type: 'ping' });
136
+ assert.equal(activity, 0);
137
+ const touched = once(host, 'activity');
138
+ await joiner.send({ type: 'ping', activity: true });
139
+ await touched;
140
+ assert.equal(activity, 1);
141
+ } finally { joiner.close(); host.close(); await relay.close(); }
142
+ });
@@ -0,0 +1,93 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { spawn } from 'node:child_process';
4
+ import { createHash } from 'node:crypto';
5
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
6
+ import { join, resolve } from 'node:path';
7
+ import { tmpdir } from 'node:os';
8
+ import { createRelay } from '../dist/relay.js';
9
+ import { createInvitation } from '../dist/crypto.js';
10
+ import { Peer } from '../dist/peer.js';
11
+ import { ProbeEngine } from '../dist/engine.js';
12
+ import { Audit } from '../dist/util.js';
13
+
14
+ function helper(action: string, input: Record<string, unknown>, onProgress?: (stderr: string) => void): Promise<Record<string, any>> {
15
+ const script = process.env.DIAGNOSE_TEST_SKILL ?? resolve('skills/connect/scripts/run.mjs');
16
+ const child = spawn(process.execPath, [script, action], { stdio: 'pipe' });
17
+ let out = '', err = '';
18
+ child.stdout.setEncoding('utf8').on('data', text => { out += text; });
19
+ child.stderr.setEncoding('utf8').on('data', text => { err += text; onProgress?.(err); });
20
+ child.stdin.end(JSON.stringify(input));
21
+ return new Promise((resolve, reject) => {
22
+ child.on('error', reject);
23
+ child.on('close', status => {
24
+ if (status !== 0) { reject(new Error(err)); return; }
25
+ try { resolve(JSON.parse(out)); }
26
+ catch (error) { reject(error); }
27
+ });
28
+ });
29
+ }
30
+
31
+ test('native Skill helper pairs once, runs a shell command, reuses the connection for a repair and closes it', { timeout: 30000 }, async () => {
32
+ const scratch = await mkdtemp(join(tmpdir(), 'diagnose-skill-'));
33
+ const config = join(scratch, 'config.txt');
34
+ await writeFile(config, 'offline\n');
35
+ const relay = createRelay({ port: 0 });
36
+ const url = 'ws://127.0.0.1:' + await relay.listen();
37
+ const code = createInvitation();
38
+ let pairs = 0;
39
+ let approve!: (value: boolean) => void;
40
+ const approval = new Promise<boolean>(resolve => { approve = resolve; });
41
+ const approvals: Array<string> = [];
42
+ const host = new Peer({ role: 'host', code, relay: url, approvalTimeoutMs: 5000, accept: async () => { pairs++; return approval; } });
43
+ new ProbeEngine(host, async request => { approvals.push(request.stage); return true; }, new Audit(join(scratch, 'audit')));
44
+ let session: string | undefined;
45
+ try {
46
+ await host.open();
47
+ let progress = '';
48
+ const opened = await helper('open', { code, label: 'Skill test', relay: url }, stderr => {
49
+ progress = stderr;
50
+ if (stderr.includes('Waiting for it to accept the connection')) approve(true);
51
+ });
52
+ assert.match(progress, /Connecting to the Diagnose relay\.[\s\S]+Connected to the relay\.[\s\S]+Authenticated the on-site probe\.[\s\S]+Paired with the on-site probe\./);
53
+ assert.ok(!progress.includes(code));
54
+ assert.equal(opened.connected, true);
55
+ assert.equal(opened.idleSeconds, 6 * 60 * 60);
56
+ session = opened.session;
57
+ assert.ok(session);
58
+ const call = (tool: string, args: object) => helper('call', { session, tool, arguments: args });
59
+ const run = async (operation: string, args: object) => {
60
+ const { id } = await call('diagnose_start', { operation, arguments: args, reason: 'Test an isolated demo configuration' });
61
+ return call('diagnose_wait', { id, timeoutMs: 5000 });
62
+ };
63
+ const forged = session.replace(/.$/, session.endsWith('0') ? '1' : '0');
64
+ await assert.rejects(helper('close', { session: forged }), /Invalid skill session/);
65
+ await assert.rejects(call('diagnose_start', { operation: 'net.forward', arguments: {} }), /Unsupported operation/);
66
+ const inspection = await run('system.inspect', {});
67
+ assert.equal(inspection.result.data.platform, process.platform);
68
+ assert.ok(Array.isArray(inspection.result.data.serialPorts));
69
+ const command = process.platform === 'win32'
70
+ ? { executable: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-Command', '40 + 2'] }
71
+ : { executable: '/bin/sh', args: ['-c', 'printf "%s" "$((40 + 2))"'] };
72
+ const executed = await run('process.run', { ...command, cwd: scratch, timeoutMs: 5000 });
73
+ assert.equal(executed.result.status, 'ok');
74
+ assert.equal(executed.outputs.stdout.trim(), '42');
75
+ assert.equal((await run('file.read', { path: config })).outputs.file, 'offline\n');
76
+ const expectedSha256 = createHash('sha256').update('offline\n').digest('hex');
77
+ assert.equal((await run('file.write', { path: config, content: 'online\n', expectedSha256 })).result.status, 'ok');
78
+ assert.equal((await run('file.read', { path: config })).outputs.file, 'online\n');
79
+ assert.equal(await readFile(config, 'utf8'), 'online\n');
80
+ assert.equal(pairs, 1);
81
+ assert.deepEqual(approvals, ['execute', 'send', 'execute', 'send', 'execute', 'send', 'execute', 'send', 'execute', 'send']);
82
+ const handle = session;
83
+ assert.equal((await helper('close', { session })).disconnected, true);
84
+ session = undefined;
85
+ assert.equal(await host.ended, 'Diagnostician ended session');
86
+ await assert.rejects(helper('call', { session: handle, tool: 'diagnose_wait', arguments: {} }), /session unavailable/i);
87
+ } finally {
88
+ if (session) await helper('close', { session }).catch(() => {});
89
+ host.close();
90
+ await relay.close();
91
+ await rm(scratch, { recursive: true, force: true });
92
+ }
93
+ });