@masstensor/diagnose 0.7.0 → 0.8.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/src/mcp.ts CHANGED
@@ -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.7.0' });
16
+ const server = new McpServer({ name: 'diagnose', version: '0.8.0' });
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>();
@@ -53,7 +53,15 @@ export async function serveMcp(relay: string, device?: string, caseId?: string):
53
53
  if (action === 'open') { if (forwards.has(resourceId)) throw new Error('Forward already open'); forwards.set(resourceId, await forward(await connected(), resourceId, localPort)); }
54
54
  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
55
  });
56
- server.registerTool('diagnose_disconnect', { description: 'End this diagnostic connection. Remembered pairing remains until revoked on the user computer.', inputSchema: {} }, async () => { remembered?.close(); remembered = undefined; operator?.peer.close(); operator = undefined; return answer({ disconnected: true }); });
56
+ server.registerTool('diagnose_disconnect', { description: 'Explicitly end this diagnostic connection. Remembered pairing remains until revoked on the user computer.', inputSchema: {} }, async () => {
57
+ remembered?.close(); remembered = undefined;
58
+ const peer = operator?.peer; operator = undefined;
59
+ if (peer) {
60
+ await peer.send({ type: 'session.closed', reason: 'Diagnostician ended session' }).catch(() => {});
61
+ peer.close();
62
+ }
63
+ return answer({ disconnected: true });
64
+ });
57
65
  let stopped = false;
58
66
  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
67
  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,6 +4,7 @@ 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 };
9
10
  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 }; }
@@ -58,7 +59,11 @@ export class Peer extends EventEmitter {
58
59
  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
60
  this.ws.on('open', () => this.ws.send(JSON.stringify({ version: short ? 2 : 1, role: options.role, room })));
60
61
  this.ws.on('error', () => this.close('Relay connection failed'));
61
- this.ws.on('close', (_code, reason) => this.close(reason.toString() === 'Invitation locator occupied' ? 'Invitation locator occupied; generating a new code' : 'Relay disconnected'));
62
+ this.ws.on('close', (_code, reason) => {
63
+ const message = reason.toString();
64
+ this.close(message === 'Invitation locator occupied' ? 'Invitation locator occupied; generating a new code'
65
+ : message === 'Session expired' ? 'Relay session expired' : 'Relay disconnected');
66
+ });
62
67
  this.ws.on('message', (bytes, binary) => {
63
68
  try {
64
69
  if (binary) this.receive(Buffer.from(bytes as Buffer));
@@ -124,7 +129,9 @@ export class Peer extends EventEmitter {
124
129
  clearTimeout(timer);
125
130
  if (this.destroyed || generation !== this.generation) return;
126
131
  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({ type: 'lock', ...(this.options.sessionMs === undefined ? {} : { ttlMs: this.options.sessionMs || 7 * 86400000 }) }));
132
+ this.ws.send(JSON.stringify(this.options.sessionMs
133
+ ? { type: 'lock', ttlMs: this.options.sessionMs }
134
+ : { type: 'lock', sliding: true, ttlMs: LEGACY_RELAY_MAX_MS }));
128
135
  this.approved = true;
129
136
  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
137
  this.activate();
@@ -148,7 +155,10 @@ export class Peer extends EventEmitter {
148
155
  clearTimeout(this.handshakeTimer); this.approved = true; this.activate(); return;
149
156
  }
150
157
  if (!this.approved) throw new Error('Not authorized');
151
- if (message.type === 'ping') { void this.send({ type: 'pong' }).catch(() => this.close('Heartbeat failed')); return; }
158
+ if (message.type === 'ping') {
159
+ if (message.activity && this.options.role === 'host') this.emit('activity');
160
+ void this.send({ type: 'pong' }).catch(() => this.close('Heartbeat failed')); return;
161
+ }
152
162
  if (message.type === 'pong') return;
153
163
  this.emit('message', message);
154
164
  }
@@ -174,6 +184,7 @@ export class Peer extends EventEmitter {
174
184
  // Bound sustained traffic below the relay's shared per-room frame budget.
175
185
  await new Promise(resolve => setTimeout(resolve, 10));
176
186
  }
187
+ if (message.type.startsWith('task.') || message.type.startsWith('resource.')) this.emit('activity');
177
188
  }).finally(() => { this.queuedBytes -= payload.length; });
178
189
  this.queue = operation.catch(() => this.close('Encrypted transport failed'));
179
190
  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 || room.expires < Date.now()) throw new Error();
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) { const requested = msg.ttlMs; if (requested !== undefined && (!Number.isInteger(requested) || requested < 60000 || requested > 7 * 86400000)) throw new Error(); room.locked = true; room.expires = Date.now() + (requested ?? options.sessionMs ?? 3600000); }
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 < Date.now()) { rooms.delete(id); room.host.close(1000, 'Session expired'); room.peer?.close(1000, 'Session expired'); }
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' | 'pong' };
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': case 'pong': return { type: basic.type };
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);
@@ -0,0 +1,3 @@
1
+ /** Default inactivity window after a temporary diagnostic connection is approved. */
2
+ export const DEFAULT_IDLE_MS = 6 * 60 * 60_000;
3
+ export const LEGACY_RELAY_MAX_MS = 7 * 24 * 60 * 60_000;
@@ -0,0 +1,233 @@
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 { 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, { timeout: requestMs });
119
+ if (result.isError) {
120
+ const content = result.content;
121
+ const error = Array.isArray(content) ? content.find(item => item.type === 'text')?.text : undefined;
122
+ respond(response, 400, { error: typeof error === 'string' ? error : 'Diagnose rejected the request' });
123
+ } else {
124
+ if (name === 'diagnose_pair') {
125
+ connected = true;
126
+ refreshIdle();
127
+ }
128
+ respond(response, 200, result.structuredContent ?? result.content);
129
+ }
130
+ } catch (error) {
131
+ respond(response, 400, { error: (error as Error).message });
132
+ } finally {
133
+ busy = false;
134
+ if (activity && !stopped) refreshIdle();
135
+ }
136
+ };
137
+ const server = createServer((request, response) => { void handle(request, response); });
138
+ server.maxConnections = 8;
139
+ server.requestTimeout = requestMs;
140
+ process.once('SIGINT', stop);
141
+ process.once('SIGTERM', stop);
142
+ client.onclose = stop;
143
+ try {
144
+ await client.connect(transport, { timeout: 15_000 });
145
+ await new Promise<void>((resolve, reject) => {
146
+ server.once('error', reject);
147
+ server.listen(0, loopback, resolve);
148
+ });
149
+ const port = (server.address() as { port: number }).port;
150
+ refreshIdle(requestMs + 25_000);
151
+ process.send({ port, secret });
152
+ } catch (error) {
153
+ stop();
154
+ throw error;
155
+ }
156
+ }
157
+
158
+ function endpoint(value: unknown): Endpoint {
159
+ if (typeof value !== 'string' || !/^\d{1,5}\.[a-f0-9]{64}$/.test(value)) throw new Error('Invalid skill session handle');
160
+ const [port, secret] = value.split('.');
161
+ if (Number(port) < 1 || Number(port) > 65535) throw new Error('Invalid skill session handle');
162
+ return { port: Number(port), secret: secret! };
163
+ }
164
+
165
+ async function requestSession(session: Endpoint, action: string, body: Json = {}): Promise<Json> {
166
+ let response: Response;
167
+ try {
168
+ response = await fetch(`http://${loopback}:${session.port}/${action}`, {
169
+ method: 'POST',
170
+ headers: { authorization: 'Bearer ' + session.secret, 'content-type': 'application/json' },
171
+ body: JSON.stringify(body),
172
+ signal: AbortSignal.timeout(requestMs + 5000),
173
+ });
174
+ } catch {
175
+ throw new Error('Skill session unavailable or timed out. Inspect the result before retrying a change.');
176
+ }
177
+ const result = record(await response.json());
178
+ if (!response.ok) throw new Error(String(result.error ?? 'Skill session request failed'));
179
+ return result;
180
+ }
181
+
182
+ async function open(input: Json): Promise<Json> {
183
+ if (typeof input.code !== 'string' || input.code.length > 120 || !input.code.trim()) throw new Error('Supply the one-time pairing code on stdin');
184
+ if (typeof input.label !== 'string' || !input.label.trim() || input.label.length > 120) throw new Error('Supply a diagnostic label on stdin');
185
+ if (input.relay !== undefined && typeof input.relay !== 'string') throw new Error('Invalid relay URL');
186
+ const relay = input.relay ?? defaultRelay;
187
+ relayUrl(relay);
188
+ const worker = fork(cli, ['skill-session', '_serve', relay], { detached: true, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
189
+ try {
190
+ const session = await new Promise<Endpoint>((resolve, reject) => {
191
+ const done = (error?: Error, result?: Endpoint) => {
192
+ clearTimeout(timer);
193
+ worker.off('error', failed);
194
+ worker.off('exit', exited);
195
+ worker.off('message', ready);
196
+ if (error) reject(error);
197
+ else resolve(result!);
198
+ };
199
+ const failed = (error: Error) => done(error);
200
+ const exited = () => done(new Error('Skill session worker exited during startup'));
201
+ const ready = (message: Endpoint) => {
202
+ try { done(undefined, endpoint(`${message.port}.${message.secret}`)); }
203
+ catch (error) { done(error as Error); }
204
+ };
205
+ const timer = setTimeout(() => done(new Error('Skill session worker did not start')), 20_000);
206
+ worker.once('error', failed);
207
+ worker.once('exit', exited);
208
+ worker.once('message', ready);
209
+ });
210
+ worker.disconnect();
211
+ worker.unref();
212
+ const result = await requestSession(session, 'pair', { code: input.code, label: input.label });
213
+ return { ...result, session: session.port + '.' + session.secret, idleSeconds: DEFAULT_IDLE_MS / 1000 };
214
+ } catch (error) {
215
+ worker.kill();
216
+ throw error;
217
+ }
218
+ }
219
+
220
+ export async function skillSessionCommand(args: string[]): Promise<void> {
221
+ if (args[0] === '_serve' && args.length === 2) {
222
+ await serve(args[1]!);
223
+ return;
224
+ }
225
+ const [action] = args;
226
+ if (args.length !== 1 || !['open', 'call', 'close'].includes(action ?? '')) {
227
+ throw new Error('Usage: diagnose skill-session open|call|close (JSON on stdin)');
228
+ }
229
+ const input = await readJson(process.stdin);
230
+ const result = action === 'open' ? await open(input)
231
+ : await requestSession(endpoint(input.session), action!, action === 'call' ? { tool: input.tool, arguments: input.arguments } : {});
232
+ console.log(JSON.stringify(result));
233
+ }
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 });