@masstensor/diagnose 0.0.0-stage → 0.2.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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -2
  3. package/deploy/Caddyfile +3 -0
  4. package/deploy/ecosystem.config.cjs +1 -0
  5. package/deploy/start-relay.sh +4 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +145 -0
  8. package/dist/crypto.d.ts +25 -0
  9. package/dist/crypto.js +60 -0
  10. package/dist/engine.d.ts +27 -0
  11. package/dist/engine.js +245 -0
  12. package/dist/executor.d.ts +18 -0
  13. package/dist/executor.js +208 -0
  14. package/dist/mcp.d.ts +1 -0
  15. package/dist/mcp.js +38 -0
  16. package/dist/operator.d.ts +21 -0
  17. package/dist/operator.js +69 -0
  18. package/dist/peer.d.ts +51 -0
  19. package/dist/peer.js +253 -0
  20. package/dist/relay-main.d.ts +2 -0
  21. package/dist/relay-main.js +6 -0
  22. package/dist/relay.d.ts +15 -0
  23. package/dist/relay.js +176 -0
  24. package/dist/schema.d.ts +298 -0
  25. package/dist/schema.js +32 -0
  26. package/dist/util.d.ts +11 -0
  27. package/dist/util.js +46 -0
  28. package/npm-shrinkwrap.json +2229 -0
  29. package/package.json +46 -4
  30. package/src/cli.ts +86 -0
  31. package/src/crypto.ts +54 -0
  32. package/src/engine.ts +156 -0
  33. package/src/executor.ts +131 -0
  34. package/src/mcp.ts +27 -0
  35. package/src/operator.ts +46 -0
  36. package/src/peer.ts +174 -0
  37. package/src/relay-main.ts +5 -0
  38. package/src/relay.ts +97 -0
  39. package/src/schema.ts +50 -0
  40. package/src/util.ts +39 -0
  41. package/src/vendor.d.ts +22 -0
  42. package/test/CACOPHONY-LICENSE +24 -0
  43. package/test/batch.test.ts +132 -0
  44. package/test/cli.test.ts +60 -0
  45. package/test/mcp.test.ts +32 -0
  46. package/test/noise-vector.json +40 -0
  47. package/test/probe.test.ts +131 -0
  48. package/test/serial.test.ts +24 -0
  49. package/test/vector.test.ts +32 -0
  50. package/tsconfig.json +8 -0
package/src/peer.ts ADDED
@@ -0,0 +1,174 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { WebSocket } from 'ws';
3
+ import { Handshake, parseCode, type SecureCipher } from './crypto.js';
4
+ import { CHUNK_SIZE, MAX_FRAME, parseMessage, type WireMessage } from './schema.js';
5
+ import { safeText } from './util.js';
6
+
7
+ export type PeerOptions = { role: 'host' | 'join'; code: string; relay: string; label?: string; accept?: (peer: { label: string; fingerprint: string; signal: AbortSignal }) => Promise<boolean>; approvalTimeoutMs?: number };
8
+ 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 }; }
9
+ export function relayUrl(value: string): string {
10
+ const url = new URL(value);
11
+ if (url.protocol === 'https:') url.protocol = 'wss:';
12
+ if (url.protocol === 'http:') url.protocol = 'ws:';
13
+ if (url.username || url.password || url.search || url.hash || !['wss:', 'ws:'].includes(url.protocol)) throw new Error('Invalid relay URL');
14
+ if (url.protocol === 'ws:' && !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)) throw new Error('Remote relays require TLS');
15
+ url.pathname = '/v1/connect'; return url.href;
16
+ }
17
+
18
+ export class Peer extends EventEmitter {
19
+ private ws: WebSocket;
20
+ private secret: Buffer;
21
+ private room: string;
22
+ private handshake?: Handshake;
23
+ private cipher?: SecureCipher;
24
+ private registered = deferred<void>();
25
+ private accepted = deferred<void>();
26
+ private endedState = deferred<string>();
27
+ readonly active = this.accepted.promise;
28
+ readonly ended = this.endedState.promise;
29
+ private approved = false;
30
+ private destroyed = false;
31
+ private generation = 0;
32
+ private approval?: AbortController;
33
+ private queue: Promise<void> = Promise.resolve();
34
+ private queuedBytes = 0;
35
+ private parts: Buffer[] = [];
36
+ private partialSize = 0;
37
+ private lastSeen = Date.now();
38
+ private heartbeat?: NodeJS.Timeout;
39
+ private connectionTimer: NodeJS.Timeout;
40
+ private handshakeTimer?: NodeJS.Timeout;
41
+ fingerprint = '';
42
+
43
+ constructor(private options: PeerOptions) {
44
+ super();
45
+ const { room, secret } = parseCode(options.code); this.room = room; this.secret = secret;
46
+ this.ws = new WebSocket(relayUrl(options.relay), { maxPayload: MAX_FRAME, perMessageDeflate: false, handshakeTimeout: 10000 });
47
+ this.connectionTimer = setTimeout(() => this.close('Relay registration timeout'), 12000);
48
+ this.ws.on('open', () => this.ws.send(JSON.stringify({ version: 1, role: options.role, room })));
49
+ this.ws.on('error', () => this.close('Relay connection failed'));
50
+ this.ws.on('close', () => this.close('Relay disconnected'));
51
+ this.ws.on('message', (bytes, binary) => {
52
+ try {
53
+ if (binary) this.receive(Buffer.from(bytes as Buffer));
54
+ else this.control(JSON.parse(bytes.toString()));
55
+ } catch {
56
+ if (options.role === 'host' && !this.approved) this.rejectAttempt();
57
+ else this.close('Authentication or protocol check failed');
58
+ }
59
+ });
60
+ }
61
+ async open(): Promise<this> { await this.registered.promise; if (this.options.role === 'join') await this.active; return this; }
62
+ private control(message: { type: string }): void {
63
+ switch (message.type) {
64
+ case 'registered': clearTimeout(this.connectionTimer); this.registered.resolve(); break;
65
+ case 'joined':
66
+ clearTimeout(this.connectionTimer); this.registered.resolve();
67
+ this.handshake = new Handshake(true, this.room, this.secret);
68
+ this.ws.send(this.handshake.send(Buffer.from(JSON.stringify({ role: 'operator', label: (this.options.label ?? 'Diagnostic operator').slice(0, 120) }))));
69
+ this.handshakeTimer = setTimeout(() => this.close('Pairing or user approval timeout'), this.options.approvalTimeoutMs ?? 120000);
70
+ break;
71
+ case 'peer':
72
+ if (this.options.role !== 'host' || this.approved) throw new Error('Unexpected peer');
73
+ this.handshake?.destroy(); this.handshake = new Handshake(false, this.room, this.secret);
74
+ clearTimeout(this.handshakeTimer);
75
+ this.handshakeTimer = setTimeout(() => this.rejectAttempt(), 15000);
76
+ break;
77
+ case 'peer-left':
78
+ if (this.approved) this.close('Operator disconnected'); else this.resetAttempt();
79
+ break;
80
+ default: throw new Error('Unexpected relay control');
81
+ }
82
+ }
83
+ private receive(bytes: Buffer): void {
84
+ if (!this.cipher) {
85
+ if (!this.handshake || bytes.length > 4096) throw new Error('Invalid handshake');
86
+ const hello = JSON.parse(this.handshake.receive(bytes).toString());
87
+ if (typeof hello.label !== 'string' || hello.label.length > 120 || hello.role !== (this.options.role === 'host' ? 'operator' : 'probe')) throw new Error('Invalid peer hello');
88
+ if (this.options.role === 'host') {
89
+ const reply = this.handshake.send(Buffer.from(JSON.stringify({ role: 'probe', label: (this.options.label ?? 'User probe').slice(0, 120) })));
90
+ this.cipher = this.handshake.split(); this.handshake = undefined; this.fingerprint = this.cipher.fingerprint;
91
+ this.ws.send(reply);
92
+ clearTimeout(this.handshakeTimer);
93
+ const generation = ++this.generation;
94
+ this.approval = new AbortController();
95
+ const timer = setTimeout(() => { this.approval?.abort(); this.close('Pairing approval timeout'); }, this.options.approvalTimeoutMs ?? 120000);
96
+ this.handshakeTimer = timer;
97
+ void (async () => {
98
+ const allowed = await this.options.accept?.({ label: safeText(hello.label), fingerprint: this.fingerprint, signal: this.approval!.signal });
99
+ clearTimeout(timer);
100
+ if (this.destroyed || generation !== this.generation) return;
101
+ if (!allowed || this.approval?.signal.aborted) { await this.send({ type: 'session.closed', reason: 'User declined pairing' }); this.close('User declined pairing'); return; }
102
+ this.ws.send(JSON.stringify({ type: 'lock' }));
103
+ this.approved = true;
104
+ await this.send({ type: 'session.accepted', label: safeText(this.options.label ?? 'User probe'), fingerprint: this.fingerprint });
105
+ this.activate();
106
+ })().catch(() => this.close('Pairing approval failed'));
107
+ } else {
108
+ this.cipher = this.handshake.split(); this.handshake = undefined; this.fingerprint = this.cipher.fingerprint;
109
+ }
110
+ return;
111
+ }
112
+ const frame = this.cipher.decrypt(bytes);
113
+ if (frame.length < 1 || frame[0] > 1) throw new Error('Bad encrypted frame');
114
+ this.parts.push(frame.subarray(1)); this.partialSize += frame.length - 1;
115
+ if (this.partialSize > 2 * 1024 * 1024) throw new Error('Message too large');
116
+ if (frame[0] === 0) return;
117
+ const message = parseMessage(JSON.parse(Buffer.concat(this.parts).toString())); this.parts = []; this.partialSize = 0;
118
+ this.lastSeen = Date.now();
119
+ if (message.type === 'session.closed') { this.close(message.reason); return; }
120
+ if (message.type === 'session.accepted' && this.options.role === 'join' && !this.approved) {
121
+ if (message.fingerprint !== this.fingerprint) throw new Error('Channel binding mismatch');
122
+ clearTimeout(this.handshakeTimer); this.approved = true; this.activate(); return;
123
+ }
124
+ if (!this.approved) throw new Error('Not authorized');
125
+ if (message.type === 'ping') { void this.send({ type: 'pong' }).catch(() => this.close('Heartbeat failed')); return; }
126
+ if (message.type === 'pong') return;
127
+ this.emit('message', message);
128
+ }
129
+ private activate(): void {
130
+ this.secret.fill(0); this.lastSeen = Date.now(); this.accepted.resolve(); this.emit('active');
131
+ this.heartbeat = setInterval(() => {
132
+ if (Date.now() - this.lastSeen > 25000) { this.close('Peer heartbeat timeout'); return; }
133
+ void this.send({ type: 'ping' }).catch(() => this.close('Heartbeat failed'));
134
+ }, 5000);
135
+ this.heartbeat.unref();
136
+ }
137
+ send(message: WireMessage): Promise<void> {
138
+ if (!this.cipher || this.destroyed) return Promise.reject(new Error('Encrypted connection unavailable'));
139
+ const payload = Buffer.from(JSON.stringify(message));
140
+ if (payload.length > 2 * 1024 * 1024 || this.queuedBytes + payload.length > 4 * 1024 * 1024) return Promise.reject(new Error('Send queue exceeded'));
141
+ this.queuedBytes += payload.length;
142
+ const operation = this.queue.then(async () => {
143
+ for (let offset = 0; offset < payload.length; offset += CHUNK_SIZE) {
144
+ if (this.destroyed || !this.cipher) throw new Error('Connection closed');
145
+ const part = payload.subarray(offset, offset + CHUNK_SIZE);
146
+ const frame = Buffer.concat([Buffer.from([offset + part.length === payload.length ? 1 : 0]), part]);
147
+ await this.writeRaw(this.cipher.encrypt(frame));
148
+ // Bound sustained traffic below the relay's shared per-room frame budget.
149
+ await new Promise(resolve => setTimeout(resolve, 10));
150
+ }
151
+ }).finally(() => { this.queuedBytes -= payload.length; });
152
+ this.queue = operation.catch(() => this.close('Encrypted transport failed'));
153
+ return operation;
154
+ }
155
+ private writeRaw(bytes: Buffer): Promise<void> {
156
+ return new Promise((resolve, reject) => { if (this.ws.readyState !== WebSocket.OPEN) { reject(new Error('Socket closed')); return; } this.ws.send(bytes, { binary: true }, error => error ? reject(error) : resolve()); });
157
+ }
158
+ private resetAttempt(): void {
159
+ this.generation++; this.approval?.abort(); clearTimeout(this.handshakeTimer);
160
+ this.handshake?.destroy(); this.handshake = undefined; this.cipher?.destroy(); this.cipher = undefined;
161
+ this.parts = []; this.partialSize = 0;
162
+ }
163
+ private rejectAttempt(): void {
164
+ this.resetAttempt();
165
+ if (this.ws.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type: 'reject' }));
166
+ }
167
+ close(reason = 'Session ended'): void {
168
+ if (this.destroyed) return;
169
+ this.destroyed = true; clearTimeout(this.connectionTimer); clearInterval(this.heartbeat); this.resetAttempt(); this.secret.fill(0);
170
+ const error = new Error(reason); this.registered.reject(error); this.accepted.reject(error); this.endedState.resolve(reason);
171
+ this.ws.close(1000, 'Session ended'); const kill = setTimeout(() => this.ws.terminate(), 1000); kill.unref();
172
+ this.emit('closed', reason);
173
+ }
174
+ }
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { createRelay } from './relay.js';
3
+ const relay = createRelay({ host: process.env.HOST ?? '127.0.0.1', port: Number(process.env.PORT ?? 8792), downloadPath: process.env.DOWNLOAD_PATH });
4
+ relay.listen().then(() => console.log('diagnose-relay ready')).catch(() => { console.error('RELAY_START_FAILED'); process.exitCode = 1; });
5
+ for (const signal of ['SIGTERM', 'SIGINT']) process.once(signal, () => { void relay.close(); });
package/src/relay.ts ADDED
@@ -0,0 +1,97 @@
1
+ import http from 'node:http';
2
+ import { createReadStream, statSync } from 'node:fs';
3
+ import { WebSocket, WebSocketServer } from 'ws';
4
+ import { MAX_FRAME } from './schema.js';
5
+
6
+ export type RelayOptions = { host?: string; port?: number; invitationMs?: number; sessionMs?: number; maxRooms?: number; downloadPath?: string; observeCiphertext?: (bytes: Buffer) => void };
7
+ type Room = { host: WebSocket; peer?: WebSocket; locked: boolean; attempts: number; expires: number; frames: number; window: number };
8
+ const control = (ws: WebSocket, type: string, extra = {}): void => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type, ...extra })); };
9
+
10
+ export function createRelay(options: RelayOptions = {}) {
11
+ const rooms = new Map<string, Room>();
12
+ const clients = new Map<WebSocket, { role?: 'host' | 'join'; room?: string; ip: string; alive: boolean }>();
13
+ const connectionsByIp = new Map<string, number>();
14
+ const server = http.createServer((req, res) => {
15
+ res.setHeader('Cache-Control', 'no-store');
16
+ res.setHeader('X-Content-Type-Options', 'nosniff');
17
+ if (req.method === 'GET' && req.url === '/healthz') { res.setHeader('Content-Type', 'application/json'); res.end('{"ok":true,"protocol":1}'); return; }
18
+ if (req.method === 'GET' && req.url === '/downloads/diagnose-0.1.0.tgz' && options.downloadPath) {
19
+ try { const size = statSync(options.downloadPath).size; res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Length', size); createReadStream(options.downloadPath).on('error', () => res.destroy()).pipe(res); } catch { res.writeHead(404); res.end(); } return;
20
+ }
21
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
22
+ res.writeHead(req.url === '/' ? 200 : 404);
23
+ res.end(req.url === '/' ? 'Diagnose blind relay v1. User-approved, end-to-end encrypted diagnostics.\n' : 'Not found\n');
24
+ });
25
+ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME, perMessageDeflate: false });
26
+ server.on('upgrade', (req, socket, head) => {
27
+ if (req.url !== '/v1/connect' || clients.size >= 400) { socket.destroy(); return; }
28
+ wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req));
29
+ });
30
+ wss.on('connection', (ws, req) => {
31
+ const direct = req.socket.remoteAddress ?? 'unknown';
32
+ const ip = ['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(direct) ? String(req.headers['x-forwarded-for'] ?? direct).split(',')[0].trim() : direct;
33
+ if ((connectionsByIp.get(ip) ?? 0) >= 30) { ws.close(1008, 'Connection limit'); return; }
34
+ connectionsByIp.set(ip, (connectionsByIp.get(ip) ?? 0) + 1);
35
+ const state = { ip, alive: true } as { role?: 'host' | 'join'; room?: string; ip: string; alive: boolean };
36
+ clients.set(ws, state);
37
+ const registration = setTimeout(() => { if (!state.role) ws.close(1008, 'Registration timeout'); }, 5000);
38
+ ws.on('pong', () => { state.alive = true; });
39
+ ws.on('error', () => ws.terminate());
40
+ ws.on('message', (raw, binary) => {
41
+ try {
42
+ const bytes = Buffer.from(raw as Buffer);
43
+ if (!state.role) {
44
+ if (binary || bytes.length > 256) throw new Error();
45
+ const msg = JSON.parse(bytes.toString());
46
+ if (msg.version !== 1 || !/^[A-Za-z0-9_-]{16}$/.test(msg.room) || !['host', 'join'].includes(msg.role)) throw new Error();
47
+ if (msg.role === 'host') {
48
+ if (rooms.has(msg.room) || rooms.size >= (options.maxRooms ?? 100)) throw new Error();
49
+ rooms.set(msg.room, { host: ws, locked: false, attempts: 0, expires: Date.now() + (options.invitationMs ?? 600000), frames: 0, window: Date.now() });
50
+ state.role = 'host'; state.room = msg.room; control(ws, 'registered');
51
+ } else {
52
+ const room = rooms.get(msg.room);
53
+ if (!room || room.locked || room.peer || room.attempts >= 10 || room.expires < Date.now()) throw new Error();
54
+ state.role = 'join'; state.room = msg.room; room.peer = ws; room.attempts++;
55
+ control(room.host, 'peer'); control(ws, 'joined');
56
+ }
57
+ clearTimeout(registration); return;
58
+ }
59
+ const room = rooms.get(state.room!);
60
+ if (!room) throw new Error();
61
+ if (binary) {
62
+ if (Date.now() - room.window > 1000) { room.window = Date.now(); room.frames = 0; }
63
+ if (++room.frames > 250 || bytes.length > MAX_FRAME) throw new Error();
64
+ const target = state.role === 'host' ? room.peer : room.host;
65
+ if (!target || target.readyState !== WebSocket.OPEN || target.bufferedAmount > 1024 * 1024) throw new Error();
66
+ let buffered = 0; for (const client of clients.keys()) buffered += client.bufferedAmount;
67
+ if (buffered > 64 * 1024 * 1024) throw new Error();
68
+ options.observeCiphertext?.(bytes);
69
+ target.send(bytes, { binary: true }); return;
70
+ }
71
+ if (bytes.length > 128 || state.role !== 'host') throw new Error();
72
+ const msg = JSON.parse(bytes.toString());
73
+ if (msg.type === 'lock') { room.locked = true; room.expires = Date.now() + (options.sessionMs ?? 3600000); }
74
+ else if (msg.type === 'reject' && !room.locked) { const peer = room.peer; room.peer = undefined; peer?.close(1008, 'Pairing rejected'); }
75
+ else throw new Error();
76
+ } catch { ws.close(1008, 'Protocol rejected'); }
77
+ });
78
+ ws.on('close', () => {
79
+ clearTimeout(registration); clients.delete(ws);
80
+ const count = (connectionsByIp.get(ip) ?? 1) - 1;
81
+ if (count > 0) connectionsByIp.set(ip, count); else connectionsByIp.delete(ip);
82
+ const room = rooms.get(state.room!); if (!room) return;
83
+ if (state.role === 'host') { rooms.delete(state.room!); room.peer?.close(1000, 'Session ended'); }
84
+ else if (room.peer === ws) { room.peer = undefined; control(room.host, 'peer-left'); if (room.locked) room.host.close(1000, 'Peer disconnected'); }
85
+ });
86
+ });
87
+ const sweep = setInterval(() => {
88
+ 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'); }
89
+ for (const [ws, state] of clients) { if (!state.alive) ws.terminate(); else { state.alive = false; ws.ping(); } }
90
+ }, 10000);
91
+ sweep.unref();
92
+ return {
93
+ server,
94
+ async listen(): Promise<number> { await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(options.port ?? 8792, options.host ?? '127.0.0.1', () => { server.off('error', reject); resolve(); }); }); return (server.address() as import('node:net').AddressInfo).port; },
95
+ async close(): Promise<void> { clearInterval(sweep); for (const ws of wss.clients) ws.terminate(); await new Promise<void>(resolve => wss.close(() => resolve())); await new Promise<void>(resolve => server.close(() => resolve())); },
96
+ };
97
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { z } from 'zod';
2
+
3
+ export const MAX_FRAME = 64 * 1024;
4
+ export const CHUNK_SIZE = 12 * 1024;
5
+ export const MAX_OUTPUT = 10 * 1024 * 1024;
6
+ const path = z.string().min(1).max(4096);
7
+ const common = { id: z.string().uuid(), reason: z.string().min(1).max(1000) };
8
+ export const atomicOperationNames = ['system.inspect', 'file.read', 'file.write', 'process.run', 'process.script', 'serial.capture', 'serial.exchange'] as const;
9
+ export const atomicTaskSchema = z.discriminatedUnion('operation', [
10
+ z.object({ ...common, operation: z.literal('system.inspect'), arguments: z.object({}).strict() }).strict(),
11
+ z.object({ ...common, operation: z.literal('file.read'), arguments: z.object({ path, offset: z.number().int().min(0).default(0), length: z.number().int().min(1).max(1024 * 1024).default(65536) }).strict() }).strict(),
12
+ z.object({ ...common, operation: z.literal('file.write'), arguments: z.object({ path, content: z.string().max(1024 * 1024), expectedSha256: z.string().regex(/^[a-f0-9]{64}$/).optional() }).strict() }).strict(),
13
+ z.object({ ...common, operation: z.literal('process.run'), arguments: z.object({ executable: path, args: z.array(z.string().max(65536)).max(128).default([]), cwd: path.optional(), timeoutMs: z.number().int().min(100).max(300000).default(60000) }).strict() }).strict(),
14
+ z.object({ ...common, operation: z.literal('process.script'), arguments: z.object({ interpreter: path, script: z.string().min(1).max(256 * 1024), args: z.array(z.string().max(65536)).max(128).default([]), cwd: path.optional(), timeoutMs: z.number().int().min(100).max(300000).default(60000) }).strict() }).strict(),
15
+ ...(['serial.capture', 'serial.exchange'] as const).map(operation => z.object({ ...common, operation: z.literal(operation), arguments: z.object({ path, baudRate: z.number().int().min(300).max(3000000).default(115200), durationMs: z.number().int().min(100).max(300000).default(20000), dataHex: z.string().regex(/^(?:[a-fA-F0-9]{2})*$/).max(65536).optional() }).strict() }).strict()),
16
+ ]);
17
+ export const batchTaskSchema = z.object({ ...common, operation: z.literal('batch.run'), arguments: z.object({ steps: z.array(atomicTaskSchema).min(1).max(32), stopOnError: z.boolean().default(true), timeoutMs: z.number().int().min(100).max(300000).default(300000) }).strict() }).strict().refine(task => new Set([task.id, ...task.arguments.steps.map(step => step.id)]).size === task.arguments.steps.length + 1, 'Batch task IDs must be unique');
18
+ export const taskSchema = z.union([atomicTaskSchema, batchTaskSchema]);
19
+ export type AtomicTask = z.infer<typeof atomicTaskSchema>;
20
+ export type BatchTask = z.infer<typeof batchTaskSchema>;
21
+ export type Task = z.infer<typeof taskSchema>;
22
+ export type TaskInput = { operation: Task['operation']; arguments: Record<string, unknown>; reason: string };
23
+ export type ApprovalStage = 'execute' | 'send';
24
+ export type Approval = { stage: ApprovalStage; task: Task; digest: string; preview: string; bytes?: number; signal?: AbortSignal };
25
+ export type ApprovalHandler = (request: Approval) => Promise<boolean>;
26
+ export type Result = { status: 'ok' | 'error' | 'denied' | 'cancelled' | 'duplicate'; data?: unknown; error?: string; exitCode?: number | null; truncated?: boolean };
27
+ export type WireMessage =
28
+ | { type: 'session.accepted'; label: string; fingerprint: string }
29
+ | { type: 'session.closed'; reason: string }
30
+ | { type: 'task.request'; task: Task }
31
+ | { type: 'task.started'; id: string; digest: string }
32
+ | { type: 'task.output'; id: string; stream: string; chunk: string; index: number }
33
+ | { type: 'task.result'; id: string; result: Result }
34
+ | { type: 'task.cancel'; id: string }
35
+ | { type: 'ping' | 'pong' };
36
+
37
+ export function parseMessage(value: unknown): WireMessage {
38
+ const basic = z.object({ type: z.string() }).passthrough().parse(value);
39
+ switch (basic.type) {
40
+ case 'task.request': return { type: basic.type, task: taskSchema.parse(basic.task) };
41
+ case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
42
+ case 'ping': case 'pong': return { type: basic.type };
43
+ case 'session.accepted': return z.object({ type: z.literal('session.accepted'), label: z.string().max(120), fingerprint: z.string().max(100) }).strict().parse(value);
44
+ case 'session.closed': return z.object({ type: z.literal('session.closed'), reason: z.string().max(200) }).strict().parse(value);
45
+ 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);
46
+ case 'task.output': return z.object({ type: z.literal('task.output'), id: z.string().uuid(), stream: z.string().max(20), chunk: z.string().max(CHUNK_SIZE * 2), index: z.number().int().min(0) }).strict().parse(value);
47
+ case 'task.result': return z.object({ type: z.literal('task.result'), id: z.string().uuid(), result: z.object({ status: z.enum(['ok', 'error', 'denied', 'cancelled', 'duplicate']), data: z.unknown().optional(), error: z.string().max(2000).optional(), exitCode: z.number().int().nullable().optional(), truncated: z.boolean().optional() }).strict() }).strict().parse(value);
48
+ default: throw new Error('Unsupported message type');
49
+ }
50
+ }
package/src/util.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { appendFileSync, mkdirSync, openSync, closeSync, realpathSync } from 'node:fs';
3
+ import { dirname, resolve, relative, isAbsolute } from 'node:path';
4
+ import os from 'node:os';
5
+
6
+ export function safeText(text: string): string {
7
+ return text.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
8
+ }
9
+ export function redact(text: string): string {
10
+ return safeText(text)
11
+ .replace(/("?(?:password|passwd|pswd|secret|token|session|authorization|api[_-]?key)"?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,}\r\n]+)/gi, '$1[REDACTED]')
12
+ .replace(/\bD1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}\b/g, '[PAIRING CODE]')
13
+ .replace(/\b[a-f0-9]{32,}\b/gi, '[REDACTED]')
14
+ .replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, '[PRIVATE KEY]');
15
+ }
16
+ export function canonical(value: unknown): string {
17
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
18
+ if (value !== null && typeof value === 'object') return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
19
+ return JSON.stringify(value);
20
+ }
21
+ export const digest = (value: unknown): string => createHash('sha256').update(canonical(value)).digest('hex');
22
+ export const sha256 = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex');
23
+ export function inside(root: string, path: string): boolean {
24
+ try { const diff = relative(realpathSync(root), realpathSync(path)); return diff === '' || (!diff.startsWith('..') && !isAbsolute(diff)); } catch { return false; }
25
+ }
26
+
27
+ export class Audit {
28
+ readonly path: string;
29
+ constructor(path = resolve(os.homedir(), '.diagnose', `audit-${Date.now()}.jsonl`)) {
30
+ this.path = path;
31
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
32
+ const fd = openSync(path, 'ax', 0o600); closeSync(fd);
33
+ this.record('session.created', {});
34
+ }
35
+ record(event: string, details: Record<string, unknown>): void {
36
+ // No command text, payload, credentials, or file contents are persisted by default.
37
+ appendFileSync(this.path, JSON.stringify({ at: new Date().toISOString(), event, ...details }) + '\n', { mode: 0o600, flush: true });
38
+ }
39
+ }
@@ -0,0 +1,22 @@
1
+ declare module 'noise-handshake' {
2
+ export default class Noise {
3
+ constructor(pattern: string, initiator: boolean, staticKeypair?: unknown, options?: Record<string, unknown>);
4
+ initialise(prologue: Buffer): void;
5
+ send(payload?: Buffer): Buffer;
6
+ recv(message: Buffer): Buffer;
7
+ complete: boolean;
8
+ tx: Buffer;
9
+ rx: Buffer;
10
+ hash: Buffer;
11
+ e: { publicKey: Buffer; secretKey: Buffer } | null;
12
+ psk: Buffer | null;
13
+ }
14
+ }
15
+ declare module 'noise-handshake/cipher.js' {
16
+ export default class Cipher {
17
+ constructor(key: Buffer);
18
+ encrypt(plaintext: Buffer, ad?: Buffer): Buffer;
19
+ decrypt(ciphertext: Buffer, ad?: Buffer): Buffer;
20
+ _clear(): void;
21
+ }
22
+ }
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <http://unlicense.org>
@@ -0,0 +1,132 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { createRelay } from '../dist/relay.js';
8
+ import { createCode } from '../dist/crypto.js';
9
+ import { Peer } from '../dist/peer.js';
10
+ import { ProbeEngine } from '../dist/engine.js';
11
+ import { Operator } from '../dist/operator.js';
12
+ import { Audit } from '../dist/util.js';
13
+ import { taskSchema, type ApprovalHandler, type TaskInput } from '../dist/schema.js';
14
+
15
+ const dir = mkdtempSync(join(tmpdir(), 'diagnose-batch-'));
16
+ const script = (source: string) => ({ operation: 'process.script', arguments: { interpreter: process.execPath, script: source } });
17
+ async function session(approve: ApprovalHandler = async () => true, notice: (text: string) => void = () => {}) {
18
+ const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`; const code = createCode();
19
+ const host = new Peer({ role: 'host', code, relay: url, accept: async () => true });
20
+ const audit = new Audit(join(dir, randomUUID() + '.jsonl')); const engine = new ProbeEngine(host, approve, audit, notice); await host.open();
21
+ const peer = new Peer({ role: 'join', code, relay: url }); const operator = new Operator(peer); await peer.open();
22
+ return { engine, audit, operator, peer, async close() { peer.close(); host.close(); await relay.close(); } };
23
+ }
24
+ function batch(steps: unknown[], extra = {}): TaskInput { return { operation: 'batch.run', arguments: { steps, ...extra }, reason: 'Batch acceptance' }; }
25
+ async function waitFile(path: string): Promise<void> { for (let i = 0; i < 100 && !existsSync(path); i++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(existsSync(path), 'diagnostic process started'); }
26
+
27
+ test('one plan approval and one transfer approval cover ordered writes, reads and a full script', async () => {
28
+ const stages: string[] = [], previews: string[] = []; const target = join(dir, randomUUID());
29
+ const source = 'const n = 2 + 3;\nconsole.log("script result", n);';
30
+ const s = await session(async request => { stages.push(request.stage); previews.push(request.preview); return true; });
31
+ try {
32
+ const result = await s.operator.run(batch([{ operation: 'file.write', arguments: { path: target, content: 'plan-data' } }, { operation: 'file.read', arguments: { path: target } }, script(source)]));
33
+ assert.equal(result.result.status, 'ok'); assert.deepEqual(stages, ['execute', 'send']); assert.ok(previews[0].includes(source), 'complete multiline script shown');
34
+ assert.equal(result.outputs['1.file'], 'plan-data'); assert.equal(result.outputs['2.stdout'], 'script result 5\n');
35
+ const data = result.result.data as any; assert.equal(data.completedSteps, 3); assert.equal(data.steps[0].result.status, 'ok');
36
+ const entries = readFileSync(s.audit.path, 'utf8').trim().split('\n').map(line => JSON.parse(line));
37
+ assert.equal(entries.filter(e => e.event === 'task.executing').length, 3); assert.ok(entries.some(e => e.event === 'task.file-changed' && e.parentId === result.id));
38
+ } finally { await s.close(); }
39
+ });
40
+
41
+ test('batch refusal does not execute; transfer refusal returns no collected output', async () => {
42
+ let executeAllowed = false; const target = join(dir, randomUUID()); const s = await session(async request => executeAllowed && request.stage === 'execute');
43
+ try {
44
+ const refused = await s.operator.run(batch([{ operation: 'file.write', arguments: { path: target, content: 'no' } }]));
45
+ assert.equal(refused.result.status, 'denied'); assert.equal(existsSync(target), false);
46
+ executeAllowed = true;
47
+ const local = await s.operator.run(batch([script('console.log("LOCAL_BATCH_ONLY")'), script('console.log("LOCAL_SECOND")')]));
48
+ assert.equal(local.result.status, 'denied'); assert.deepEqual(local.outputs, {});
49
+ } finally { await s.close(); }
50
+ });
51
+
52
+ test('batch failure stops later steps by default; explicit continue runs independent steps', async () => {
53
+ const s = await session(); const target = join(dir, randomUUID());
54
+ try {
55
+ const steps = [script('throw new Error("expected failure")'), { operation: 'file.write', arguments: { path: target, content: 'continued' } }];
56
+ const stopped = await s.operator.run(batch(steps)); assert.equal(stopped.result.status, 'error'); assert.equal(existsSync(target), false); assert.equal((stopped.result.data as any).completedSteps, 1);
57
+ const continued = await s.operator.run(batch(steps, { stopOnError: false })); assert.equal(continued.result.status, 'error'); assert.equal(readFileSync(target, 'utf8'), 'continued'); assert.equal((continued.result.data as any).completedSteps, 2);
58
+ } finally { await s.close(); }
59
+ });
60
+
61
+ test('batch deadline terminates the child and leaves later steps unexecuted', async () => {
62
+ const pidPath = join(dir, randomUUID() + '.pid'), target = join(dir, randomUUID()); const s = await session();
63
+ try {
64
+ const result = await s.operator.run(batch([script(`require('fs').writeFileSync(${JSON.stringify(pidPath)},String(process.pid));setInterval(()=>{},1000)`), { operation: 'file.write', arguments: { path: target, content: 'no' } }], { timeoutMs: 350 }));
65
+ assert.equal(result.result.error, 'Batch timeout'); assert.equal(existsSync(target), false); assert.ok(existsSync(pidPath));
66
+ assert.throws(() => process.kill(Number(readFileSync(pidPath, 'utf8')), 0), { code: 'ESRCH' });
67
+ } finally { await s.close(); }
68
+ });
69
+
70
+ test('auto mode approves execution AND transfer; local revocation cancels work and restores prompts', async () => {
71
+ let prompts = 0; const pidPath = join(dir, randomUUID() + '.pid'), target = join(dir, randomUUID());
72
+ const s = await session(async () => { prompts++; return false; });
73
+ try {
74
+ assert.equal(s.engine.permissionMode, 'ask'); s.engine.setPermissionMode('auto');
75
+ const result = await s.operator.run(batch([script('console.log("automatic first")'), script('console.log("automatic second")')]));
76
+ assert.equal(result.result.status, 'ok'); assert.equal(result.outputs['1.stdout'], 'automatic second\n'); assert.equal(prompts, 0);
77
+ const id = await s.operator.start(batch([script(`require('fs').writeFileSync(${JSON.stringify(pidPath)},String(process.pid));setInterval(()=>{},1000)`), { operation: 'file.write', arguments: { path: target, content: 'no' } }]));
78
+ await waitFile(pidPath); s.engine.setPermissionMode('ask');
79
+ const cancelled = await s.operator.wait(id, 5000); assert.equal('result' in cancelled && cancelled.result.status, 'cancelled'); assert.equal(existsSync(target), false);
80
+ assert.throws(() => process.kill(Number(readFileSync(pidPath, 'utf8')), 0), { code: 'ESRCH' });
81
+ const denied = await s.operator.run({ operation: 'system.inspect', arguments: {}, reason: 'After revoke' }); assert.equal(denied.result.status, 'denied'); assert.equal(prompts, 1);
82
+ const events = readFileSync(s.audit.path, 'utf8').trim().split('\n').map(line => JSON.parse(line));
83
+ assert.ok(events.some(e => e.event === 'permissions.changed' && e.automaticTransfer));
84
+ assert.ok(events.some(e => e.event === 'task.auto-approved' && e.stage === 'send'));
85
+ } finally { await s.close(); }
86
+ });
87
+
88
+ test('revoking during automatic send approval prevents output transmission', async () => {
89
+ let revoke = () => {}; const s = await session(async () => false, value => { if (value.startsWith('[AUTO send]')) revoke(); });
90
+ try {
91
+ s.engine.setPermissionMode('auto'); revoke = () => s.engine.setPermissionMode('ask');
92
+ const result = await s.operator.run(batch([script('console.log("REVOKED_BEFORE_TRANSFER")')]));
93
+ assert.equal(result.result.status, 'cancelled'); assert.deepEqual(result.outputs, {});
94
+ } finally { await s.close(); }
95
+ });
96
+
97
+ test('explicit batch cancel stops the process and remaining steps', async () => {
98
+ const pidPath = join(dir, randomUUID() + '.pid'), target = join(dir, randomUUID()); const s = await session();
99
+ try {
100
+ const id = await s.operator.start(batch([script(`require('fs').writeFileSync(${JSON.stringify(pidPath)},String(process.pid));setInterval(()=>{},1000)`), { operation: 'file.write', arguments: { path: target, content: 'no' } }]));
101
+ await waitFile(pidPath); await s.operator.cancel(id); const result = await s.operator.wait(id, 5000);
102
+ assert.equal('result' in result && result.result.status, 'cancelled'); assert.equal(existsSync(target), false);
103
+ } finally { await s.close(); }
104
+ });
105
+
106
+ test('all batch output shares a bounded budget and no later modifications occur after exhaustion', async () => {
107
+ const target = join(dir, randomUUID()); let bytes = 0; const s = await session(async request => { if (request.stage === 'send') { bytes = request.bytes!; return false; } return true; });
108
+ try {
109
+ const result = await s.operator.run(batch([script('process.stdout.write("z".repeat(6*1024*1024))'), script('process.stdout.write("z".repeat(6*1024*1024))'), { operation: 'file.write', arguments: { path: target, content: 'no' } }]));
110
+ assert.equal(result.result.status, 'denied'); assert.equal(bytes, 10 * 1024 * 1024); assert.equal(existsSync(target), false);
111
+ } finally { await s.close(); }
112
+ });
113
+
114
+ test('parameter tampering, remote permission fields, nested plans and duplicate step IDs are rejected', async () => {
115
+ const target = join(dir, randomUUID()); const s = await session(async request => { if (request.stage === 'execute' && request.task.operation === 'batch.run') request.task.arguments.steps[0].reason = 'changed'; return true; });
116
+ try {
117
+ const result = await s.operator.run(batch([{ operation: 'file.write', arguments: { path: target, content: 'no' } }])); assert.equal(result.result.status, 'error'); assert.equal(existsSync(target), false);
118
+ await assert.rejects(s.operator.start(batch([script('console.log(1)')], { permissions: 'auto' })));
119
+ await assert.rejects(s.operator.start(batch([{ operation: 'batch.run', arguments: { steps: [script('console.log(1)')] } }])));
120
+ const id = randomUUID(); const step = { ...script('console.log(1)'), id, reason: 'duplicate' };
121
+ assert.equal(taskSchema.safeParse({ ...batch([step, step]), id: randomUUID() }).success, false);
122
+ assert.equal(s.engine.permissionMode, 'ask');
123
+ } finally { await s.close(); }
124
+ });
125
+
126
+ test('a requested partial file range does not stop unrelated batch steps', async () => {
127
+ const target = join(dir, randomUUID()); writeFileSync(target, '0123456789'); const s = await session();
128
+ try {
129
+ const result = await s.operator.run(batch([{ operation: 'file.read', arguments: { path: target, length: 3 } }, script('console.log("after partial read")')]));
130
+ assert.equal(result.result.status, 'ok'); assert.equal(result.outputs['0.file'], '012'); assert.equal(result.outputs['1.stdout'], 'after partial read\n');
131
+ } finally { await s.close(); }
132
+ });
@@ -0,0 +1,60 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { spawn } from 'node:child_process';
4
+ import { resolve } from 'node:path';
5
+ import { mkdtempSync } from 'node:fs';
6
+ import { tmpdir } from 'node:os';
7
+ import { createRelay } from '../dist/relay.js';
8
+ import { Peer } from '../dist/peer.js';
9
+ import { Operator } from '../dist/operator.js';
10
+
11
+ test('actual host CLI displays and enforces pairing, execution and transfer prompts', { skip: process.platform !== 'darwin', timeout: 15000 }, async () => {
12
+ const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`;
13
+ // macOS script accepts a POSIX pipe, but not Node's socketpair-backed stdin.
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;
16
+ let stderr = ''; child.stderr.on('data', bytes => { stderr += bytes.toString(); });
17
+ let codeResolve!: (value: string) => void;
18
+ const code = new Promise<string>(resolve => { codeResolve = resolve; });
19
+ child.stdout.on('data', bytes => {
20
+ text += bytes.toString(); const match = /D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/.exec(text); if (match) codeResolve(match[0]);
21
+ if (!pairing && text.includes('Allow this temporary diagnostic session?')) { pairing = true; child.stdin.write('y\n'); }
22
+ if (!executing && text.includes('Allow exactly this operation?')) { executing = true; child.stdin.write('y\n'); }
23
+ if (!sending && text.includes('Send these results (')) { sending = true; child.stdin.write('y\n'); }
24
+ });
25
+ const timer = setTimeout(() => child.kill('SIGKILL'), 12000);
26
+ let peer: Peer | undefined;
27
+ try {
28
+ const pairCode = await Promise.race([code, new Promise<never>((_, reject) => child.once('exit', () => reject(new Error('CLI exited before registration: ' + stderr))))]);
29
+ peer = new Peer({ role: 'join', code: pairCode, relay: url }); const operator = new Operator(peer); await peer.open();
30
+ 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
+ } finally { clearTimeout(timer); peer?.close(); child.stdin.end('\x03'); if (child.pid) { try { process.kill(-child.pid, 'SIGTERM'); } catch {} } await relay.close(); }
33
+ });
34
+
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
+ const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`;
37
+ 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
+ const code = new Promise<string>(resolve => { resolveCode = resolve; });
40
+ child.stderr.resume();
41
+ child.stdout.on('data', bytes => {
42
+ output += bytes.toString(); const match = /D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/.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
+ const executionCount = output.split('Allow exactly this operation?').length - 1;
45
+ if (executionCount > executionPrompts) { executionPrompts = executionCount; child.stdin.write('n\n'); }
46
+ transferPrompts = output.split('Send these results (').length - 1;
47
+ });
48
+ const waitFor = async (predicate: () => boolean) => { for (let i = 0; i < 100 && !predicate(); i++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(predicate()); };
49
+ let peer: Peer | undefined;
50
+ try {
51
+ peer = new Peer({ role: 'join', code: await code, relay: url }); const operator = new Operator(peer); await peer.open();
52
+ 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
+ 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
+ child.stdin.write('permissions ask\n'); await waitFor(() => output.includes('Automatic permissions revoked'));
55
+ const denied = await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'After revoke' }); assert.equal(denied.result.status, 'denied'); assert.equal(executionPrompts, 1);
56
+ child.stdin.write('permissions auto\n'); await waitFor(() => output.includes('within 60 seconds to grant'));
57
+ child.stdin.write('permissions allow-auto\n'); await waitFor(() => output.split('Permission mode: auto').length >= 3);
58
+ const again = await operator.run(plan); assert.equal(again.result.status, 'ok'); assert.equal(executionPrompts, 1); assert.equal(transferPrompts, 0);
59
+ } finally { peer?.close(); child.stdin.end('\x03'); if (child.pid) { try { process.kill(-child.pid, 'SIGTERM'); } catch {} } await relay.close(); }
60
+ });