@masstensor/diagnose 0.3.2 → 0.5.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 (61) hide show
  1. package/README.md +46 -7
  2. package/USER_GUIDE.md +305 -12
  3. package/dist/agent-command.d.ts +4 -0
  4. package/dist/agent-command.js +33 -0
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +38 -8
  7. package/dist/cli.js +173 -22
  8. package/dist/discover.js +1 -1
  9. package/dist/engine.d.ts +2 -0
  10. package/dist/engine.js +37 -4
  11. package/dist/history.d.ts +13 -0
  12. package/dist/history.js +57 -0
  13. package/dist/journal.d.ts +23 -1
  14. package/dist/journal.js +82 -5
  15. package/dist/maintenance.d.ts +2 -0
  16. package/dist/maintenance.js +46 -0
  17. package/dist/mcp.d.ts +1 -1
  18. package/dist/mcp.js +21 -18
  19. package/dist/operator.d.ts +2 -0
  20. package/dist/operator.js +17 -5
  21. package/dist/pairing.d.ts +40 -0
  22. package/dist/pairing.js +92 -0
  23. package/dist/peer.d.ts +4 -0
  24. package/dist/peer.js +10 -3
  25. package/dist/resources.js +47 -26
  26. package/dist/schema.d.ts +2 -0
  27. package/dist/schema.js +2 -2
  28. package/dist/skill.d.ts +8 -0
  29. package/dist/skill.js +58 -0
  30. package/dist/transfers.js +28 -11
  31. package/dist/util.d.ts +2 -0
  32. package/dist/util.js +16 -3
  33. package/examples/skills/device-troubleshooting/SKILL.md +35 -0
  34. package/examples/skills/device-troubleshooting/references/device-profile.md +16 -0
  35. package/examples/skills/owon.md +27 -0
  36. package/npm-shrinkwrap.json +199 -3
  37. package/package.json +11 -5
  38. package/scripts/setup-node.ps1 +54 -0
  39. package/scripts/setup-node.sh +52 -0
  40. package/src/agent-command.ts +25 -0
  41. package/src/agent.ts +30 -7
  42. package/src/cli.ts +51 -20
  43. package/src/discover.ts +1 -1
  44. package/src/engine.ts +19 -4
  45. package/src/history.ts +43 -0
  46. package/src/journal.ts +41 -5
  47. package/src/maintenance.ts +30 -0
  48. package/src/mcp.ts +18 -16
  49. package/src/operator.ts +15 -6
  50. package/src/pairing.ts +64 -0
  51. package/src/peer.ts +6 -4
  52. package/src/resources.ts +35 -13
  53. package/src/schema.ts +4 -4
  54. package/src/skill.ts +44 -0
  55. package/src/transfers.ts +14 -3
  56. package/src/util.ts +14 -3
  57. package/test/agent.test.ts +53 -6
  58. package/test/pairing.test.ts +124 -0
  59. package/test/review.test.ts +128 -0
  60. package/test/setup.test.ts +16 -0
  61. package/test/skill.test.ts +25 -0
package/src/peer.ts CHANGED
@@ -4,7 +4,7 @@ import { Handshake, parseCode, type SecureCipher } from './crypto.js';
4
4
  import { CHUNK_SIZE, MAX_FRAME, parseMessage, type WireMessage } from './schema.js';
5
5
  import { safeText } from './util.js';
6
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; sessionMs?: number };
7
+ 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 };
8
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
9
  export function relayUrl(value: string): string {
10
10
  const url = new URL(value);
@@ -39,6 +39,7 @@ export class Peer extends EventEmitter {
39
39
  private connectionTimer: NodeJS.Timeout;
40
40
  private handshakeTimer?: NodeJS.Timeout;
41
41
  fingerprint = '';
42
+ rememberedCode?: string;
42
43
 
43
44
  constructor(private options: PeerOptions) {
44
45
  super();
@@ -65,7 +66,7 @@ export class Peer extends EventEmitter {
65
66
  case 'joined':
66
67
  clearTimeout(this.connectionTimer); this.registered.resolve();
67
68
  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.ws.send(this.handshake.send(Buffer.from(JSON.stringify({ role: 'operator', label: (this.options.label ?? 'Diagnostic operator').slice(0, 120), ...(this.options.remember ? { remember: true } : {}) }))));
69
70
  this.handshakeTimer = setTimeout(() => this.close('Pairing or user approval timeout'), this.options.approvalTimeoutMs ?? 120000);
70
71
  break;
71
72
  case 'peer':
@@ -95,13 +96,13 @@ export class Peer extends EventEmitter {
95
96
  const timer = setTimeout(() => { this.approval?.abort(); this.close('Pairing approval timeout'); }, this.options.approvalTimeoutMs ?? 120000);
96
97
  this.handshakeTimer = timer;
97
98
  void (async () => {
98
- const allowed = await this.options.accept?.({ label: safeText(hello.label), fingerprint: this.fingerprint, signal: this.approval!.signal });
99
+ const allowed = await this.options.accept?.({ label: safeText(hello.label), fingerprint: this.fingerprint, signal: this.approval!.signal, remember: hello.remember === true });
99
100
  clearTimeout(timer);
100
101
  if (this.destroyed || generation !== this.generation) return;
101
102
  if (!allowed || this.approval?.signal.aborted) { await this.send({ type: 'session.closed', reason: 'User declined pairing' }); this.close('User declined pairing'); return; }
102
103
  this.ws.send(JSON.stringify({ type: 'lock', ...(this.options.sessionMs === undefined ? {} : { ttlMs: this.options.sessionMs || 7 * 86400000 }) }));
103
104
  this.approved = true;
104
- await this.send({ type: 'session.accepted', label: safeText(this.options.label ?? 'User probe'), fingerprint: this.fingerprint });
105
+ 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!() } : {}) });
105
106
  this.activate();
106
107
  })().catch(() => this.close('Pairing approval failed'));
107
108
  } else {
@@ -119,6 +120,7 @@ export class Peer extends EventEmitter {
119
120
  if (message.type === 'session.closed') { this.close(message.reason); return; }
120
121
  if (message.type === 'session.accepted' && this.options.role === 'join' && !this.approved) {
121
122
  if (message.fingerprint !== this.fingerprint) throw new Error('Channel binding mismatch');
123
+ if (message.credential) { if (!this.options.remember) throw new Error('Unexpected pairing credential'); parseCode(message.credential); this.rememberedCode = message.credential; }
122
124
  clearTimeout(this.handshakeTimer); this.approved = true; this.activate(); return;
123
125
  }
124
126
  if (!this.approved) throw new Error('Not authorized');
package/src/resources.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { spawn as spawnProcess } from 'node:child_process';
2
2
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
3
3
  import { constants } from 'node:fs';
4
- import { open, lstat, realpath, rename, unlink } from 'node:fs/promises';
4
+ import { open, lstat, realpath, rename, unlink, link } from 'node:fs/promises';
5
5
  import { dirname, resolve, join, basename } from 'node:path';
6
6
  import net from 'node:net';
7
- import { Journal, type ResourceMeta } from './journal.js';
7
+ import { Journal, retention, type ResourceMeta } from './journal.js';
8
8
  import { killTree } from './executor.js';
9
9
  import { Audit, sha256 } from './util.js';
10
10
  import type { AtomicTask, ResourceRequest } from './schema.js';
@@ -21,9 +21,12 @@ export class SessionResources {
21
21
  readonly journal: Journal;
22
22
  private resources = new Map<string, Resource>();
23
23
  private writes = new Map<string, Promise<unknown>>();
24
- constructor(root: string, private audit: Audit) { this.journal = new Journal(root); }
24
+ constructor(root: string, private audit: Audit) { this.journal = new Journal(root, retention); }
25
25
  setAudit(audit: Audit): void { this.audit = audit; }
26
26
  private create(id: string, kind: ResourceMeta['kind'], owner: string, retainOnDisconnect: boolean, details: Record<string, unknown> = {}): { resource: Resource; token: string } {
27
+ for (const [key, value] of this.resources) {
28
+ if (!['running', 'open', 'listening'].includes(value.meta.state) && (!this.journal.exists(key) || this.resources.size >= 256)) this.resources.delete(key);
29
+ }
27
30
  if (this.resources.has(id) || this.journal.exists(id)) throw new Error('Resource ID already exists. Resume it; do not replay its creation.');
28
31
  if ([...this.resources.values()].filter(r => ['running', 'open', 'listening'].includes(r.meta.state)).length >= 128) throw new Error('Active resource limit reached; close unused resources');
29
32
  const token = randomBytes(32).toString('base64url'), now = new Date().toISOString();
@@ -72,7 +75,9 @@ export class SessionResources {
72
75
  if (request.action === 'input') {
73
76
  if (!resource.input) throw new Error('This resource does not accept input'); const bytes = Buffer.from(request.data ?? '', 'base64');
74
77
  if (bytes.length > 65536 || bytes.toString('base64') !== (request.data ?? '')) throw new Error('Invalid input encoding');
75
- this.audit.record('resource.input', { id: meta.id, bytes: bytes.length, eof: request.eof }); await resource.input(bytes, request.eof); return { acceptedBytes: bytes.length };
78
+ this.audit.record('resource.input', { id: meta.id, bytes: bytes.length, eof: request.eof });
79
+ if (meta.kind === 'process') this.audit.history.event(meta.id, 'process-input', { encoding: 'base64', data: bytes.toString('base64'), eof: request.eof });
80
+ await resource.input(bytes, request.eof); return { acceptedBytes: bytes.length };
76
81
  }
77
82
  if (request.action === 'resize') { if (!resource.resize || !request.cols || !request.rows) throw new Error('Resize requires a PTY and dimensions'); this.audit.record('resource.resize', { id: meta.id, cols: request.cols, rows: request.rows }); resource.resize(request.cols, request.rows); return publicMeta(meta); }
78
83
  if (request.action === 'signal') { if (!resource.signal) throw new Error('Not a running process'); const signal = request.signal ?? 'SIGINT'; this.audit.record('resource.signal', { id: meta.id, signal }); resource.signal(signal); return { signalled: true }; }
@@ -84,8 +89,10 @@ export class SessionResources {
84
89
  const args = task.arguments, executable = args.executable ?? (process.platform === 'win32' ? process.env.ComSpec ?? 'cmd.exe' : process.env.SHELL ?? '/bin/sh');
85
90
  const { resource, token } = this.create(task.id, 'process', owner, args.retainOnDisconnect, { state: 'running', executable, cwd: resolve(args.cwd ?? process.cwd()), pty: args.pty, cols: args.cols, rows: args.rows, bytes: 0 });
86
91
  const { meta } = resource; const env = { ...process.env, ...args.env }; for (const key of Object.keys(env)) if (/^(?:DIAGNOSE_|OWON_|NPM_TOKEN|NODE_AUTH_TOKEN)/i.test(key)) delete env[key];
87
- let timer: NodeJS.Timeout | undefined, force: NodeJS.Timeout | undefined, closing = false;
88
- const ended = (code: number | null, signal?: number | string): void => { clearTimeout(timer); clearTimeout(force); meta.state = 'exited'; meta.exitCode = code; if (signal !== undefined) meta.signal = signal; this.journal.save(meta); this.audit.record('resource.process-exited', { id: meta.id, exitCode: code }); };
92
+ let timer: NodeJS.Timeout | undefined, closing: Promise<void> | undefined;
93
+ // A leader exiting does not mean its process group has exited. Clean up
94
+ // immediately, while the group ID still belongs to this job.
95
+ const ended = (code: number | null, signal?: number | string): void => { resource.signal?.('SIGKILL'); clearTimeout(timer); meta.state = 'exited'; meta.exitCode = code; if (signal !== undefined) meta.signal = signal; this.journal.save(meta); this.audit.record('resource.process-exited', { id: meta.id, exitCode: code }); };
89
96
  const collect = (stream: string, bytes: Buffer): void => {
90
97
  try {
91
98
  const keep = Math.max(0, Math.min(bytes.length, args.maxOutputBytes - Number(meta.bytes))); if (keep) this.journal.append(meta.id, stream, bytes.subarray(0, keep)); meta.bytes = Number(meta.bytes) + keep;
@@ -99,15 +106,24 @@ export class SessionResources {
99
106
  child.onData(value => collect('terminal', Buffer.isBuffer(value) ? value : Buffer.from(value))); child.onExit(value => ended(value.exitCode, value.signal));
100
107
  resource.input = async (bytes, eof) => { child.write(bytes.toString('utf8')); if (eof) child.write('\x04'); };
101
108
  resource.resize = (cols, rows) => { child.resize(cols, rows); meta.cols = cols; meta.rows = rows; this.journal.save(meta); };
102
- resource.signal = signal => { try { child.kill(signal); } catch {} };
109
+ resource.signal = signal => { try { if (process.platform === 'win32') child.kill(signal); else process.kill(-child.pid, signal as NodeJS.Signals); } catch {} };
103
110
  } else {
104
111
  const child = spawnProcess(executable, args.args, { cwd: String(meta.cwd), env, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }); meta.pid = child.pid;
105
112
  child.stdout.on('data', bytes => collect('stdout', bytes)); child.stderr.on('data', bytes => collect('stderr', bytes)); child.stdin.on('error', () => {});
106
- child.on('error', error => { meta.error = error.message; }); child.on('close', (code, signal) => ended(code, signal ?? undefined));
113
+ child.on('error', error => { meta.error = error.message; meta.state = 'failed'; this.journal.save(meta); }); child.on('exit', (code, signal) => ended(code, signal ?? undefined));
107
114
  resource.input = (bytes, eof) => new Promise((resolveInput, reject) => { if (child.stdin.destroyed || child.stdin.writableEnded) { reject(new Error('Process stdin is closed')); return; } if (eof) child.stdin.end(bytes, resolveInput); else child.stdin.write(bytes, error => error ? reject(error) : resolveInput()); });
108
115
  resource.signal = signal => { if (process.platform === 'win32') killTree(child, signal === 'SIGKILL'); else { try { process.kill(-child.pid!, signal as NodeJS.Signals); } catch {} } };
109
116
  }
110
- resource.close = () => { if (meta.state === 'running' && !closing) { closing = true; resource.signal?.('SIGTERM'); force = setTimeout(() => resource.signal?.('SIGKILL'), 1000); force.unref(); } };
117
+ resource.close = () => {
118
+ if (closing) return closing;
119
+ if (meta.state !== 'running') return;
120
+ resource.signal?.('SIGTERM');
121
+ closing = new Promise<void>(resolveClose => setTimeout(() => {
122
+ if (meta.state === 'running') resource.signal?.('SIGKILL');
123
+ resolveClose();
124
+ }, 1000));
125
+ return closing;
126
+ };
111
127
  if (args.timeoutMs) { timer = setTimeout(() => { meta.timedOut = true; void resource.close(); }, args.timeoutMs); timer.unref(); }
112
128
  this.journal.save(meta); this.audit.record('resource.process-started', { id: meta.id, pid: meta.pid, pty: args.pty, retainOnDisconnect: args.retainOnDisconnect });
113
129
  return { ...publicMeta(meta), resumeToken: token, output: 'Raw, unredacted bytes. Poll read from cursor 0 for live output; input/resize/signals are authorized for this handle.' };
@@ -116,7 +132,7 @@ export class SessionResources {
116
132
  private async startTransfer(task: Extract<AtomicTask, { operation: 'file.transfer' }>, owner: string, signal?: AbortSignal): Promise<unknown> {
117
133
  const args = task.arguments, path = resolve(args.path); let details: Record<string, unknown>;
118
134
  if (args.direction === 'download') { const stat = await lstat(path); if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('Download requires a regular non-symlink file'); details = { path, size: stat.size, sha256: await fileHash(path), offset: 0 }; }
119
- else { if (args.size === undefined || !args.sha256) throw new Error('Upload requires exact size and SHA-256'); const before = await currentHash(path); if (before !== null && !args.overwrite) throw new Error('Target exists; explicit overwrite authorization required'); details = { path, parent: await realpath(dirname(path)), temp: join(dirname(path), `.${basename(path)}.diagnose-${task.id}`), beforeSha256: before, size: args.size, sha256: args.sha256, offset: 0 }; }
135
+ else { if (args.size === undefined || !args.sha256) throw new Error('Upload requires exact size and SHA-256'); const before = await currentHash(path); if (before !== null && !args.overwrite) throw new Error('Target exists; explicit overwrite authorization required'); details = { path, parent: await realpath(dirname(path)), temp: join(dirname(path), `.${basename(path)}.diagnose-${task.id}`), beforeSha256: before, mode: before === null ? 0o600 : (await lstat(path)).mode & 0o777, size: args.size, sha256: args.sha256, offset: 0 }; }
120
136
  signal?.throwIfAborted(); const { resource, token } = this.create(task.id, args.direction, owner, args.retainOnDisconnect, details);
121
137
  const live = await this.restoreTransfer(resource.meta, owner, true); if (signal?.aborted || resource.owner !== owner) { await live.close(); throw new Error('Transfer authorization was cancelled'); } this.resources.set(task.id, live);
122
138
  this.audit.record('resource.transfer-opened', { id: task.id, direction: args.direction, path, size: details.size }); return { ...publicMeta(live.meta), resumeToken: token, encoding: 'base64', redaction: 'none; exact file bytes' };
@@ -137,7 +153,13 @@ export class SessionResources {
137
153
  if (meta.offset !== meta.size) throw new Error('Upload is incomplete'); await file.sync();
138
154
  if (await fileHash(String(meta.temp)) !== meta.sha256) throw new Error('Upload SHA-256 mismatch; destination untouched');
139
155
  if (await realpath(dirname(String(meta.path))) !== meta.parent || await currentHash(String(meta.path)) !== meta.beforeSha256) throw new Error('Destination changed since upload authorization');
140
- await file.close(); closed = true; await rename(String(meta.temp), String(meta.path)); meta.state = 'committed'; this.journal.save(meta); this.audit.record('resource.file-changed', { id: meta.id, path: meta.path, beforeSha256: meta.beforeSha256, afterSha256: meta.sha256, bytes: meta.size }); return publicMeta(meta);
156
+ if (closed || resource.owner !== owner) throw new Error('Transfer authorization was revoked');
157
+ await file.chmod(Number(meta.mode ?? 0o600)); await file.close();
158
+ if (closed || resource.owner !== owner) throw new Error('Transfer authorization was revoked');
159
+ closed = true;
160
+ if (meta.beforeSha256 === null) { await link(String(meta.temp), String(meta.path)); await unlink(String(meta.temp)); }
161
+ else await rename(String(meta.temp), String(meta.path));
162
+ meta.state = 'committed'; this.journal.save(meta); this.audit.record('resource.file-changed', { id: meta.id, path: meta.path, beforeSha256: meta.beforeSha256, afterSha256: meta.sha256, bytes: meta.size }); return publicMeta(meta);
141
163
  };
142
164
  }
143
165
  return resource;
@@ -170,9 +192,9 @@ export class SessionResources {
170
192
  resource.close = async () => { server?.close(); for (const child of this.resources.values()) if (child.meta.parentId === task.id) await child.close(); resource.meta.state = 'closed'; this.journal.save(resource.meta); };
171
193
  this.journal.save(resource.meta); return { ...publicMeta(resource.meta), resumeToken: token };
172
194
  }
173
- async disconnect(owner: string): Promise<void> { for (const resource of this.resources.values()) if (resource.owner === owner) { resource.owner = ''; if (!resource.meta.retainOnDisconnect) await resource.close(); } }
195
+ async disconnect(owner: string): Promise<void> { const affected = [...this.resources.values()].filter(resource => resource.owner === owner); for (const resource of affected) resource.owner = ''; await Promise.all(affected.filter(resource => !resource.meta.retainOnDisconnect).map(resource => resource.close())); }
174
196
  async abandon(task: AtomicTask, owner: string): Promise<void> { const id = task.operation === 'resource.resume' ? task.arguments.id : task.id, resource = this.resources.get(id); if (resource?.owner === owner) { resource.owner = ''; if (task.operation !== 'resource.resume' || !resource.meta.retainOnDisconnect) await resource.close(); } }
175
- async revoke(owner?: string): Promise<void> { for (const resource of this.resources.values()) if (owner === undefined || resource.owner === owner) { resource.owner = ''; await resource.close(); } }
197
+ async revoke(owner?: string): Promise<void> { const affected = [...this.resources.values()].filter(resource => owner === undefined || resource.owner === owner); for (const resource of affected) resource.owner = ''; await Promise.all(affected.map(resource => resource.close())); }
176
198
  listLocal(): Record<string, unknown>[] { return [...this.resources.values()].map(resource => publicMeta(resource.meta)); }
177
199
  async localInput(id: string, value: Buffer): Promise<void> { const resource = this.resources.get(id); if (!resource?.input || resource.meta.state !== 'running') throw new Error('No live process with this ID'); this.audit.record('resource.local-input', { id, bytes: value.length }); await resource.input(value, false); }
178
200
  renewCredential(id: string): string { const meta = this.resources.get(id)?.meta ?? this.journal.load(id); const token = randomBytes(32).toString('base64url'); meta.tokenHash = sha256(Buffer.from(token)); this.journal.save(meta); this.audit.record('resource.local-credential-renewed', { id }); return token; }
package/src/schema.ts CHANGED
@@ -39,9 +39,9 @@ export type Result = { status: 'ok' | 'error' | 'denied' | 'cancelled' | 'duplic
39
39
  export const resourceRequestSchema = z.object({ id: z.string().uuid().optional(), action: z.enum(['list', 'read', 'input', 'resize', 'signal', 'status', 'close', 'commit', 'connect', 'accept']), cursor: z.number().int().min(0).default(0), limit: z.number().int().min(1).max(65536).default(65536), data: z.string().max(90000).optional(), eof: z.boolean().default(false), cols: z.number().int().min(20).max(500).optional(), rows: z.number().int().min(5).max(200).optional(), signal: z.enum(['SIGINT', 'SIGTERM', 'SIGKILL', 'SIGHUP', 'SIGQUIT']).optional(), host: z.string().min(1).max(253).optional(), port: z.number().int().min(1).max(65535).optional() }).strict();
40
40
  export type ResourceRequest = z.infer<typeof resourceRequestSchema>;
41
41
  export type WireMessage =
42
- | { type: 'session.accepted'; label: string; fingerprint: string }
42
+ | { type: 'session.accepted'; label: string; fingerprint: string; credential?: string }
43
43
  | { type: 'session.closed'; reason: string }
44
- | { type: 'task.request'; task: Task }
44
+ | { type: 'task.request'; task: Task; sequence?: number }
45
45
  | { type: 'task.started'; id: string; digest: string }
46
46
  | { type: 'task.output'; id: string; stream: string; chunk: string; index: number }
47
47
  | { type: 'task.result'; id: string; result: Result }
@@ -55,12 +55,12 @@ export type WireMessage =
55
55
  export function parseMessage(value: unknown): WireMessage {
56
56
  const basic = z.object({ type: z.string() }).passthrough().parse(value);
57
57
  switch (basic.type) {
58
- case 'task.request': return { type: basic.type, task: taskSchema.parse(basic.task) };
58
+ case 'task.request': return { type: basic.type, task: taskSchema.parse(basic.task), ...(basic.sequence === undefined ? {} : { sequence: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).parse(basic.sequence) }) };
59
59
  case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
60
60
  case 'resource.request': return { type: basic.type, requestId: z.string().uuid().parse(basic.requestId), request: resourceRequestSchema.parse(basic.request) };
61
61
  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
62
  case 'ping': case 'pong': return { type: basic.type };
63
- case 'session.accepted': return z.object({ type: z.literal('session.accepted'), label: z.string().max(120), fingerprint: z.string().max(100) }).strict().parse(value);
63
+ 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
64
  case 'session.closed': return z.object({ type: z.literal('session.closed'), reason: z.string().max(200) }).strict().parse(value);
65
65
  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);
66
66
  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);
package/src/skill.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { open, realpath, stat } from 'node:fs/promises';
2
+ import { dirname, extname, join, resolve } from 'node:path';
3
+ import { isUtf8 } from 'node:buffer';
4
+ import { createHash } from 'node:crypto';
5
+
6
+ export type SessionSkill = { sourceFile: string; baseDirectory: string; sha256: string; instructions: string };
7
+ const MAX_SKILL = 256 * 1024;
8
+
9
+ export async function loadSkill(input: string): Promise<SessionSkill> {
10
+ if (!input.trim()) throw new Error('--skill requires a non-empty path');
11
+ let path = resolve(input);
12
+ if ((await stat(path)).isDirectory()) path = join(path, 'SKILL.md');
13
+ if (!['.md', '.markdown'].includes(extname(path).toLowerCase())) throw new Error('--skill requires a Markdown file or a directory containing SKILL.md');
14
+ const sourceFile = await realpath(path);
15
+ if (!(await stat(sourceFile)).isFile()) throw new Error('Skill must be a regular file');
16
+ const file = await open(sourceFile, 'r');
17
+ try {
18
+ const info = await file.stat();
19
+ if (!info.isFile()) throw new Error('Skill must be a regular file');
20
+ if (info.size > MAX_SKILL) throw new Error('Skill exceeds 256 KiB');
21
+ const buffer = Buffer.alloc(MAX_SKILL + 1); let length = 0;
22
+ while (length < buffer.length) { const { bytesRead } = await file.read(buffer, length, buffer.length - length, length); if (!bytesRead) break; length += bytesRead; }
23
+ if (length > MAX_SKILL) throw new Error('Skill exceeds 256 KiB');
24
+ const bytes = buffer.subarray(0, length);
25
+ if (!isUtf8(bytes)) throw new Error('Skill must contain UTF-8 Markdown');
26
+ const instructions = bytes.toString('utf8').replace(/^\uFEFF/, '');
27
+ if (!instructions.trim()) throw new Error('Skill is empty');
28
+ return { sourceFile, baseDirectory: dirname(sourceFile), sha256: createHash('sha256').update(bytes).digest('hex'), instructions };
29
+ } finally { await file.close(); }
30
+ }
31
+
32
+ export function skillPrompt(snapshot: string): string {
33
+ return [
34
+ 'Start the remote troubleshooting task selected by the diagnostician now.',
35
+ `Task snapshot path (JSON): ${JSON.stringify(snapshot)}`,
36
+ 'First read this local UTF-8 JSON file using your local file-reading tools. Follow its instructions field as the task for this session; do not merely summarize it or wait for the task to be repeated.',
37
+ 'Resolve relative references and scripts against baseDirectory in the snapshot. It is a Markdown task or skill entry, not a globally installed agent skill. Read referenced material only as needed. Bundled scripts are task resources, not startup hooks; run them only as required by the task and existing permissions.',
38
+ 'Referenced files and scripts are initially on the diagnostician computer. For a remote script, explicitly submit its contents or transfer it with authorization; do not assume the same path exists remotely.',
39
+ 'Use diagnose_* MCP tools for actions on the remote user computer. Your ordinary shell and file tools operate on the diagnostician computer; do not confuse the two.',
40
+ 'If a pairing code, target identity, or necessary detail is missing, ask the diagnostician for it, then continue. Keep pairing codes and credentials out of command arguments and reports.',
41
+ 'Pair and obtain the remote user approval before remote actions. Respect the existing user and agent permission modes; this task does not grant permissions or authorize bypassing them.',
42
+ 'Investigate, explain the proposed repair and its impact, apply only authorized changes, repeat the original failing check, and report evidence, changes, and remaining issues. Do not claim success without verification.'
43
+ ].join('\n');
44
+ }
package/src/transfers.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { open, stat, rename, writeFile, readFile, unlink } from 'node:fs/promises';
1
+ import { open, stat, lstat, rename, writeFile, readFile, unlink, link, chmod } from 'node:fs/promises';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { resolve } from 'node:path';
4
4
  import type { Operator } from './operator.js';
@@ -6,6 +6,10 @@ export type TransferProgress = { state: string; bytes: number; size: number; res
6
6
  export type TransferOptions = { resumeId?: string; resumeToken?: string; overwrite?: boolean; signal?: AbortSignal; progress?: (progress: TransferProgress) => void };
7
7
  type Descriptor = { id: string; resumeToken?: string; size: number; sha256: string; offset: number };
8
8
  async function hash(path: string): Promise<string> { const file = await open(path, 'r'); try { const value = createHash('sha256'); for await (const bytes of file.createReadStream({ autoClose: false })) value.update(bytes); return value.digest('hex'); } finally { await file.close(); } }
9
+ async function snapshot(path: string): Promise<{ sha256: string; mode: number } | null> {
10
+ try { const info = await lstat(path); if (!info.isFile() || info.isSymbolicLink()) throw new Error('Local target must be a regular non-symlink file'); return { sha256: await hash(path), mode: info.mode & 0o777 }; }
11
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
12
+ }
9
13
  async function grant(operator: Operator, input: Parameters<Operator['run']>[0], options: TransferOptions): Promise<Descriptor> {
10
14
  options.signal?.throwIfAborted(); const id = await operator.start(options.resumeId ? { operation: 'resource.resume', arguments: { id: options.resumeId, resumeToken: options.resumeToken }, reason: input.reason } : input);
11
15
  const abort = () => { void operator.cancel(id).catch(() => {}); }; options.signal?.addEventListener('abort', abort, { once: true });
@@ -26,7 +30,8 @@ export async function upload(operator: Operator, localPath: string, remotePath:
26
30
  }
27
31
  export async function download(operator: Operator, remotePath: string, localPath: string, reason: string, options: TransferOptions = {}): Promise<TransferProgress> {
28
32
  const destination = resolve(localPath), partial = destination + '.diagnose.part', sidecar = destination + '.diagnose.json';
29
- try { await stat(destination); if (!options.overwrite) throw new Error('Local target exists; explicit overwrite is required'); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
33
+ const before = await snapshot(destination);
34
+ if (before && !options.overwrite) throw new Error('Local target exists; explicit overwrite is required');
30
35
  let saved: { resourceId: string; resumeToken: string; sha256: string } | undefined;
31
36
  try { saved = JSON.parse(await readFile(sidecar, 'utf8')); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
32
37
  const effective = options.resumeId ? options : saved ? { ...options, resumeId: saved.resourceId, resumeToken: saved.resumeToken } : options;
@@ -44,5 +49,11 @@ export async function download(operator: Operator, remotePath: string, localPath
44
49
  await file.sync();
45
50
  } finally { await file.close(); }
46
51
  if (progress.bytes !== resource.size || await hash(partial) !== resource.sha256) throw new Error('Download integrity mismatch; destination untouched');
47
- options.signal?.throwIfAborted(); await rename(partial, destination); await unlink(sidecar); await operator.resource({ id: resource.id, action: 'close' }); progress.state = 'completed'; options.progress?.({ ...progress }); return progress;
52
+ options.signal?.throwIfAborted();
53
+ if (before === null) { await link(partial, destination); await unlink(partial); }
54
+ else {
55
+ if (JSON.stringify(await snapshot(destination)) !== JSON.stringify(before)) throw new Error('Local destination changed during download; destination untouched');
56
+ await chmod(partial, before.mode); options.signal?.throwIfAborted(); await rename(partial, destination);
57
+ }
58
+ await unlink(sidecar); await operator.resource({ id: resource.id, action: 'close' }); progress.state = 'completed'; options.progress?.({ ...progress }); return progress;
48
59
  }
package/src/util.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { createHash } from 'node:crypto';
2
- import { appendFileSync, mkdirSync, openSync, closeSync, realpathSync } from 'node:fs';
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { appendFileSync, mkdirSync, openSync, closeSync, realpathSync, statSync, renameSync } from 'node:fs';
3
3
  import { dirname, resolve, relative, isAbsolute } from 'node:path';
4
4
  import os from 'node:os';
5
+ import { History } from './history.js';
6
+ import { cleanupAudit } from './maintenance.js';
5
7
 
6
8
  export function safeText(text: string): string {
7
9
  return text.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
@@ -26,14 +28,23 @@ export function inside(root: string, path: string): boolean {
26
28
 
27
29
  export class Audit {
28
30
  readonly path: string;
29
- constructor(path = resolve(os.homedir(), '.diagnose', `audit-${Date.now()}.jsonl`)) {
31
+ readonly history: History;
32
+ constructor(path = resolve(os.homedir(), '.diagnose', `audit-${Date.now()}-pid${process.pid}-${randomUUID()}.jsonl`)) {
30
33
  this.path = path;
31
34
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
32
35
  const fd = openSync(path, 'ax', 0o600); closeSync(fd);
36
+ this.history = new History(resolve(dirname(path), 'history'));
37
+ cleanupAudit(dirname(path), undefined, path);
33
38
  this.record('session.created', {});
34
39
  }
35
40
  record(event: string, details: Record<string, unknown>): void {
36
41
  // No command text, payload, credentials, or file contents are persisted by default.
42
+ if (statSync(this.path).size > 8 * 1024 * 1024) {
43
+ renameSync(this.path, this.path.replace(/\.jsonl$/, '') + `-closed-${randomUUID()}.jsonl`);
44
+ const fd = openSync(this.path, 'ax', 0o600); closeSync(fd);
45
+ cleanupAudit(dirname(this.path), undefined, this.path);
46
+ }
37
47
  appendFileSync(this.path, JSON.stringify({ at: new Date().toISOString(), event, ...details }) + '\n', { mode: 0o600, flush: true });
48
+ if (typeof details.id === 'string') this.history.event(details.id, event, details);
38
49
  }
39
50
  }
@@ -1,16 +1,18 @@
1
1
  import { test } from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
3
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync } from 'node:fs';
4
4
  import { tmpdir } from 'node:os';
5
- import { join, resolve } from 'node:path';
5
+ import { dirname, join, resolve } from 'node:path';
6
6
  import { spawn } from 'node:child_process';
7
7
  import { createRequire } from 'node:module';
8
8
  import { pathToFileURL } from 'node:url';
9
+ import { PairingStore } from '../dist/pairing.js';
10
+ import { createCode } from '../dist/crypto.js';
9
11
  const require = createRequire(import.meta.url);
10
- const cli = resolve('dist/cli.js');
12
+ const cli = realpathSync(process.env.DIAGNOSE_TEST_CLI ?? resolve('dist/cli.js'));
11
13
 
12
14
  function fixture() {
13
- const root = mkdtempSync(join(tmpdir(), 'diagnose agent test ')), capture = join(root, 'capture.json'), settings = join(root, '.gemini', 'settings.json');
15
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'diagnose agent test '))), capture = join(root, 'capture.json'), settings = join(root, '.gemini', 'settings.json');
14
16
  mkdirSync(join(root, '.gemini'));
15
17
  writeFileSync(settings, JSON.stringify({ security: { marker: 'preserve-admin-policy' }, mcpServers: { existing: { command: 'unchanged' } } }));
16
18
  for (const name of ['.codex', '.claude', '.gemini']) { mkdirSync(join(root, name), { recursive: true }); writeFileSync(join(root, name, 'sentinel'), 'unchanged'); }
@@ -21,9 +23,12 @@ const fs=require('node:fs'), args=process.argv.slice(2), agent=require('node:pat
21
23
  if(agent==='codex'){const overrides=args.filter((_,i)=>args[i-1]==='-c');server={command:JSON.parse(overrides[0].split('=').slice(1).join('=')),args:JSON.parse(overrides[1].split('=').slice(1).join('='))};}
22
24
  else if(agent==='claude')server=JSON.parse(args[args.indexOf('--mcp-config')+1]).mcpServers.diagnose;
23
25
  else{settingsPath=require('node:path').join(process.env.GEMINI_CLI_HOME,'.gemini','settings.json');const settings=JSON.parse(fs.readFileSync(settingsPath,'utf8'));server=settings.mcpServers.diagnose;admin=settings.security; if(settings.mcpServers.existing.command!=='unchanged')throw Error('Existing MCP lost');}
26
+ let task,taskPath,taskMode;const initial=agent==='gemini'?args[args.indexOf('--prompt-interactive')+1]:args.at(-1);if(initial?.includes('Task snapshot path (JSON):')){const marker=initial.split('\\n').find(x=>x.startsWith('Task snapshot path (JSON): '));taskPath=JSON.parse(marker.slice('Task snapshot path (JSON): '.length));task=JSON.parse(fs.readFileSync(taskPath,'utf8'));taskMode=fs.statSync(taskPath).mode&511;}
24
27
  const {Client}=await import(${JSON.stringify(client)}),{StdioClientTransport}=await import(${JSON.stringify(transport)});
25
- const client=new Client({name:'launcher-acceptance',version:'1'});await client.connect(new StdioClientTransport(server));const tools=(await client.listTools()).tools.map(t=>t.name);await client.close();
26
- fs.writeFileSync(process.env.TEST_CAPTURE,JSON.stringify({args,server,tools,settingsPath,admin}));if(process.env.TEST_WAIT){process.on('SIGTERM',()=>process.exit(23));setInterval(()=>{},1000)}else process.exit(Number(process.env.TEST_EXIT||0));
28
+ const client=new Client({name:'launcher-acceptance',version:'1'});await client.connect(new StdioClientTransport(server));const tools=(await client.listTools()).tools.map(t=>t.name);let workflow;
29
+ if(process.env.TEST_PAIR_CODE){if(!task?.instructions.includes('STARTUP_WORKFLOW_ACCEPTANCE'))throw Error('Selected task was not read');const call=async(name,args)=>{const r=await client.callTool({name,arguments:args});if(r.isError)throw Error(r.content[0].text);return JSON.parse(r.content[0].text);};await call('diagnose_pair',{code:process.env.TEST_PAIR_CODE,label:'Explicitly authorized fixture agent'});const {id}=await call('diagnose_batch',{reason:'Selected startup task: fix and verify scratch configuration',steps:[{operation:'file.write',arguments:{path:process.env.TEST_REMOTE_TARGET,content:'fixed'}},{operation:'file.read',arguments:{path:process.env.TEST_REMOTE_TARGET}}]});workflow=await call('diagnose_wait',{id,timeoutMs:5000,release:true});await call('diagnose_disconnect',{});}
30
+ await client.close();
31
+ fs.writeFileSync(process.env.TEST_CAPTURE,JSON.stringify({args,server,tools,settingsPath,admin,task,taskPath,taskMode,workflow}));if(process.env.TEST_WAIT){process.on('SIGTERM',()=>process.exit(23));setInterval(()=>{},1000)}else process.exit(Number(process.env.TEST_EXIT||0));
27
32
  })().catch(e=>{console.error(e);process.exit(99)});
28
33
  `;
29
34
  for (const agent of ['codex', 'claude', 'gemini']) writeFileSync(join(root, agent), stub, { mode: 0o700 });
@@ -55,3 +60,45 @@ test('agent forwards termination and cleans the Gemini overlay', { skip: process
55
60
  try { for (let i = 0; i < 100 && !existsSync(f.capture); i++) await new Promise(resolveWait => setTimeout(resolveWait, 20)); assert.ok(existsSync(f.capture)); const captured = JSON.parse(readFileSync(f.capture, 'utf8')); child.kill('SIGTERM'); assert.equal(await exit, 23); assert.equal(existsSync(captured.settingsPath), false); assert.ok(existsSync(f.settings)); }
56
61
  finally { child.kill('SIGKILL'); }
57
62
  });
63
+
64
+ for (const agent of ['codex', 'claude', 'gemini']) test(`agent ${agent} loads the same selected Markdown task at startup without exposing its body in argv`, { skip: process.platform === 'win32', timeout: 15000 }, async () => {
65
+ const f = fixture(), source = join(f.root, 'device "profile".md'), body = '# Device task\nPRIVATE_TASK_MARKER\nRead references/profile.md and diagnose the selected device.\nLiteral $(do-not-execute).'; writeFileSync(source, body);
66
+ new PairingStore(join(f.root, '.diagnose', 'pairings')).add({ role: 'operator', name: 'alice-pc', label: 'test', relay: 'https://relay.example.test', code: createCode() });
67
+ const result = await run(['agent', agent, '--device', 'alice-pc', '--skill', source, '--', '--model', 'selected-model'], { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture });
68
+ assert.equal(result.code, 0, result.output); const captured = JSON.parse(readFileSync(f.capture, 'utf8'));
69
+ assert.deepEqual(captured.server.args.slice(-2), ['--device', 'alice-pc']); assert.match(captured.args.at(-1), /do not ask for a pairing code/);
70
+ assert.equal(captured.task.instructions, body); assert.equal(captured.task.sourceFile, source); assert.equal(captured.task.baseDirectory, f.root); assert.equal(captured.taskMode, 0o600); assert.equal(existsSync(captured.taskPath), false); assert.ok(captured.tools.includes('diagnose_pair'));
71
+ const scopeFlag = agent === 'gemini' ? '--include-directories' : '--add-dir';
72
+ assert.equal(captured.args[captured.args.indexOf(scopeFlag) + 1], dirname(captured.taskPath));
73
+ assert.notEqual(dirname(captured.taskPath), f.root);
74
+ if (captured.settingsPath) assert.ok(!captured.settingsPath.startsWith(dirname(captured.taskPath) + '/'));
75
+ assert.ok(!captured.args.join(' ').includes('PRIVATE_TASK_MARKER')); assert.ok(!result.output.includes('PRIVATE_TASK_MARKER')); assert.ok(captured.args.includes('selected-model'));
76
+ const prompt = captured.args.at(-1); assert.match(prompt, /Start the remote troubleshooting task/); assert.match(prompt, /do not merely summarize/); assert.match(prompt, /approval/);
77
+ if (agent === 'gemini') assert.equal(captured.args.at(-2), '--prompt-interactive'); else assert.equal(captured.args.at(-2), '--');
78
+ });
79
+
80
+ test('skill directory is accepted, and invalid skills fail before launching an agent', { skip: process.platform === 'win32', timeout: 15000 }, async () => {
81
+ const f = fixture(), skill = join(f.root, 'device-skill'); mkdirSync(skill); writeFileSync(join(skill, 'SKILL.md'), '# Device skill\nInspect first.');
82
+ const env = { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture };
83
+ const result = await run(['agent', 'codex', '--skill', skill], env); assert.equal(result.code, 0, result.output); assert.equal(JSON.parse(readFileSync(f.capture, 'utf8')).task.sourceFile, join(skill, 'SKILL.md'));
84
+ const missing = await run(['agent', 'codex', '--skill', join(f.root, 'missing.md')], { ...env, TEST_CAPTURE: join(f.root, 'must-not-run') }); assert.equal(missing.code, 1); assert.equal(existsSync(join(f.root, 'must-not-run')), false);
85
+ const conflict = await run(['agent', 'gemini', '--skill', skill, '--', '--prompt', 'another task'], env); assert.equal(conflict.code, 1); assert.match(conflict.output, /initial task/);
86
+ });
87
+
88
+ test('termination also removes the skill snapshot', { skip: process.platform === 'win32', timeout: 10000 }, async () => {
89
+ const f = fixture(), source = join(f.root, 'task.md'); writeFileSync(source, '# Test task');
90
+ const child = spawn(process.execPath, [cli, 'agent', 'codex', '--skill', source], { env: { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, TEST_CAPTURE: f.capture, TEST_WAIT: '1' }, stdio: 'ignore' }); const exit = new Promise<number | null>(resolveExit => child.once('close', resolveExit));
91
+ try { for (let i = 0; i < 100 && !existsSync(f.capture); i++) await new Promise(resolveWait => setTimeout(resolveWait, 20)); assert.ok(existsSync(f.capture)); const captured = JSON.parse(readFileSync(f.capture, 'utf8')); child.kill('SIGTERM'); assert.equal(await exit, 23); assert.equal(existsSync(captured.taskPath), false); }
92
+ finally { child.kill('SIGKILL'); }
93
+ });
94
+
95
+ for (const agent of ['codex', 'claude', 'gemini']) test(`selected startup task reaches a remote repair and verification over real MCP for ${agent}`, { skip: process.platform === 'win32', timeout: 15000 }, async () => {
96
+ const { createRelay } = await import('../dist/relay.js'), { createCode } = await import('../dist/crypto.js'), { Peer } = await import('../dist/peer.js'), { ProbeEngine } = await import('../dist/engine.js'), { Audit } = await import('../dist/util.js');
97
+ const f = fixture(), task = join(f.root, 'repair.md'), target = join(f.root, 'remote-config.txt'); writeFileSync(task, '# STARTUP_WORKFLOW_ACCEPTANCE\nRepair the scratch configuration and read it back to verify.'); writeFileSync(target, 'broken');
98
+ const relay = createRelay({ port: 0 }), url = `ws://127.0.0.1:${await relay.listen()}`, code = createCode(), stages: string[] = [];
99
+ const host = new Peer({ role: 'host', code, relay: url, accept: async () => true }); const engine = new ProbeEngine(host, async request => { stages.push(request.stage); return request.task.operation === 'batch.run' && request.task.arguments.steps.every(step => 'path' in step.arguments && step.arguments.path === target); }, new Audit(join(f.root, 'audit.jsonl')), () => {}); await host.open();
100
+ try {
101
+ const result = await run(['agent', agent, '--skill', task, '--relay', url], { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture, TEST_PAIR_CODE: code, TEST_REMOTE_TARGET: target });
102
+ assert.equal(result.code, 0, result.output); const captured = JSON.parse(readFileSync(f.capture, 'utf8')); assert.equal(captured.workflow.result.status, 'ok'); assert.equal(captured.workflow.outputs['1.file'], 'fixed'); assert.equal(readFileSync(target, 'utf8'), 'fixed'); assert.deepEqual(stages, ['execute', 'send']); assert.ok(!captured.args.join(' ').includes(code));
103
+ } finally { engine.cancelAll(); host.close(); await relay.close(); }
104
+ });
@@ -0,0 +1,124 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, readFileSync, readdirSync, statSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { PairingStore, automatic, RememberedConnection } from '../dist/pairing.js';
7
+ import { createCode } from '../dist/crypto.js';
8
+ import { createRelay } from '../dist/relay.js';
9
+ import { Peer } from '../dist/peer.js';
10
+ import { ProbeEngine } from '../dist/engine.js';
11
+ import { Audit } from '../dist/util.js';
12
+ const scratch = () => mkdtempSync(join(tmpdir(), 'diagnose-pairing-'));
13
+
14
+ test('pairing credentials survive restart encrypted; grants expire by wall clock; deletion revokes local record', () => {
15
+ const root = scratch(), store = new PairingStore(root), code = createCode();
16
+ const value = store.add({ role: 'operator', name: 'alice-pc', code, relay: 'https://diagnose.fenginwind.com', label: 'support / AI' });
17
+ value.autoUntil = 2000; store.save(value);
18
+ assert.equal(automatic(value, 1999), true); assert.equal(automatic(value, 2000), false);
19
+ value.autoUntil = null; assert.equal(automatic(value), true); value.paused = true; assert.equal(automatic(value), false);
20
+ const restarted = new PairingStore(root); assert.equal(restarted.get('alice-pc', 'operator').code, code);
21
+ for (const name of readdirSync(root).filter(name => name.endsWith('.meta'))) { assert.equal(readFileSync(join(root, name)).includes(Buffer.from(code)), false); if (process.platform !== 'win32') assert.equal(statSync(join(root, name)).mode & 0o777, 0o600); }
22
+ assert.throws(() => store.add({ ...value, name: 'alice-pc' }));
23
+ restarted.remove(value.id); assert.deepEqual(store.list(), []);
24
+ });
25
+
26
+ test('remembered connection reconnects with fresh encryption and never replays a command', { timeout: 15000 }, async () => {
27
+ const root = scratch(), frames: Buffer[] = [], relay = createRelay({ port: 0, observeCiphertext: bytes => frames.push(Buffer.from(bytes)) });
28
+ const url = `ws://127.0.0.1:${await relay.listen()}`, code = createCode();
29
+ const record = new PairingStore(root).add({ role: 'operator', name: 'alice', label: 'test', relay: url, code });
30
+ const connection = new RememberedConnection(record, 3000);
31
+ let approvals = 0;
32
+ const host = () => { const peer = new Peer({ role: 'host', code, relay: url, accept: async () => true }); new ProbeEngine(peer, async () => { approvals++; return true; }, new Audit(join(root, `audit-${Math.random()}`))); return peer; };
33
+ let probe = host(); await probe.open();
34
+ try {
35
+ const first = await connection.connect(), fingerprint = first.peer.fingerprint;
36
+ const result = await first.run({ operation: 'system.inspect', arguments: {}, reason: 'First task' }); assert.equal(result.result.status, 'ok');
37
+ first.peer.close(); await probe.ended; probe.close(); await new Promise(resolve => setTimeout(resolve, 80));
38
+ probe = host(); await probe.open();
39
+ const second = await connection.connect(); assert.notEqual(second, first); assert.notEqual(second.peer.fingerprint, fingerprint);
40
+ assert.equal(approvals, 2, 'reconnection must not replay completed task');
41
+ assert.equal((await second.run({ operation: 'system.inspect', arguments: {}, reason: 'Second task' })).result.status, 'ok'); assert.equal(approvals, 4);
42
+ assert.equal(Buffer.concat(frames).includes(Buffer.from(code)), false);
43
+ connection.close(); await assert.rejects(connection.connect(), /ended/);
44
+ } finally { connection.close(); probe.close(); await relay.close(); }
45
+ });
46
+
47
+ test('actual host survives probe and relay restarts, pauses access, and revokes pairing', { skip: process.platform !== 'darwin', timeout: 25000 }, async () => {
48
+ const { spawn } = await import('node:child_process'); const { resolve } = await import('node:path');
49
+ const root = scratch(); let relay = createRelay({ port: 0 }); const port = await relay.listen(), url = `ws://127.0.0.1:${port}`;
50
+ let output = '', pairPrompts = 0;
51
+ const start = () => {
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;
54
+ };
55
+ let child = start(), peer: Peer | undefined;
56
+ const until = async (predicate: () => boolean) => { for (let i = 0; i < 300 && !predicate(); i++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(predicate(), output); };
57
+ const stop = async () => { const ended = new Promise(resolve => child.once('exit', resolve)); if (child.pid) try { process.kill(-child.pid, 'SIGTERM'); } catch {} await ended; };
58
+ try {
59
+ await until(() => /D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/.test(output));
60
+ const invitation = output.match(/D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}/)![0];
61
+ peer = new Peer({ role: 'join', code: invitation, relay: url, label: 'Remembered support / test AI', remember: true }); await peer.open();
62
+ const credential = peer.rememberedCode!; assert.ok(credential); assert.notEqual(credential, invitation);
63
+ peer.close(); await until(() => output.includes('Waiting for connections'));
64
+ const store = new PairingStore(join(root, '.diagnose', 'pairings')); const record = store.list('host')[0]; assert.equal(record.code, credential);
65
+ await stop(); output = ''; child = start(); await until(() => output.includes('Waiting for connections'));
66
+ const connection = new RememberedConnection({ ...record, role: 'operator' }, 2000);
67
+ let operator = await connection.connect(); assert.equal((await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'Restart without pairing or approval' })).result.status, 'ok'); assert.equal(pairPrompts, 1);
68
+ child.stdin.write('pause\n'); await until(() => output.includes('Remote access is paused'));
69
+ await operator.peer.ended; await assert.rejects(connection.connect());
70
+ child.stdin.write('resume\n'); await until(() => output.split('Waiting for connections').length >= 3);
71
+ operator = await connection.connect(); assert.equal((await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'Resume without a new code' })).result.status, 'ok');
72
+ await relay.close(); await operator.peer.ended; relay = createRelay({ port }); await relay.listen();
73
+ operator = await connection.connect(); assert.equal((await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'Relay restarted; same pairing and unexpired permission' })).result.status, 'ok');
74
+ child.stdin.write('unpair\n'); await operator.peer.ended; await until(() => output.includes('Pairing revoked'));
75
+ assert.deepEqual(store.list('host'), []); await assert.rejects(connection.connect()); connection.close();
76
+ assert.equal(output.includes(credential), false, 'durable credential must never be printed');
77
+ } finally { peer?.close(); await stop(); await relay.close(); }
78
+ });
79
+
80
+ test('real MCP sessions reuse a saved device; a broken request is not replayed after reconnect', { timeout: 15000 }, async () => {
81
+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js'); const { StdioClientTransport } = await import('@modelcontextprotocol/sdk/client/stdio.js'); const { resolve } = await import('node:path');
82
+ const root = scratch(), relay = createRelay({ port: 0 }), url = `ws://127.0.0.1:${await relay.listen()}`, code = createCode();
83
+ new PairingStore(join(root, '.diagnose', 'pairings')).add({ role: 'operator', name: 'alice', label: 'test', relay: url, code });
84
+ let count = 0;
85
+ const host = () => { const peer = new Peer({ role: 'host', code, relay: url, accept: async () => true }); new ProbeEngine(peer, async () => true, new Audit(join(root, `audit-${Math.random()}`))); peer.on('message', message => { if (message.type === 'task.request') count++; }); return peer; };
86
+ let probe = host(); await probe.open();
87
+ const session = async () => { const client = new Client({ name: 'remembered-test', version: '1' }); await client.connect(new StdioClientTransport({ command: process.execPath, args: [resolve('dist/cli.js'), 'mcp', '--device', 'alice'], env: { ...process.env, HOME: root } as Record<string, string>, stderr: 'pipe' })); return client; };
88
+ const value = (result: any) => { assert.ok(!result.isError, JSON.stringify(result)); return JSON.parse(result.content[0].text); };
89
+ let client = await session();
90
+ try {
91
+ const task = value(await client.callTool({ name: 'diagnose_start', arguments: { operation: 'system.inspect', arguments: {}, reason: 'Saved device, no code' } })); assert.equal(value(await client.callTool({ name: 'diagnose_wait', arguments: { id: task.id, timeoutMs: 3000 } })).result.status, 'ok');
92
+ await client.close(); await probe.ended; await new Promise(resolve => setTimeout(resolve, 80)); probe = host(); await probe.open(); client = await session();
93
+ const slow = value(await client.callTool({ name: 'diagnose_start', arguments: { operation: 'process.script', arguments: { interpreter: process.execPath, script: 'setTimeout(()=>{},10000)' }, reason: 'Interrupt without replay' } }));
94
+ probe.close(); await probe.ended; await new Promise(resolve => setTimeout(resolve, 80)); probe = host(); await probe.open();
95
+ const next = value(await client.callTool({ name: 'diagnose_start', arguments: { operation: 'system.inspect', arguments: {}, reason: 'Reconnect for new work only' } })); assert.equal(value(await client.callTool({ name: 'diagnose_wait', arguments: { id: next.id, timeoutMs: 3000 } })).result.status, 'ok');
96
+ assert.equal(count, 3); const lost = await client.callTool({ name: 'diagnose_wait', arguments: { id: slow.id } }); assert.equal(lost.isError, true);
97
+ } finally { await client.close(); probe.close(); await relay.close(); }
98
+ });
99
+
100
+ test('pair CLI saves a separately provisioned credential and lists only safe metadata', { skip: process.platform !== 'darwin', timeout: 12000 }, async () => {
101
+ const { spawn } = await import('node:child_process'); const { resolve } = await import('node:path');
102
+ const root = scratch(), relay = createRelay({ port: 0 }), url = `ws://127.0.0.1:${await relay.listen()}`, code = createCode(), credential = createCode();
103
+ let requestedRemember = false;
104
+ const host = new Peer({ role: 'host', code, relay: url, provision: () => credential, accept: async ({ remember }) => { requestedRemember = remember; return true; } }); await host.open();
105
+ const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'pair-cli-test', process.execPath, resolve('dist/cli.js'), 'pair', url, '--name', 'alice-pc'], { detached: true, env: { ...process.env, HOME: root }, stdio: ['pipe', 'pipe', 'pipe'] });
106
+ let output = '', stage = 0; child.stderr.resume(); child.stdout.on('data', bytes => { output += bytes.toString(); if (!stage && output.includes('Pairing code:')) { stage = 1; child.stdin.write(code + '\n'); } if (stage === 1 && output.includes('Your label')) { stage = 2; child.stdin.write('Support / AI provider\n'); } if (stage === 2 && output.includes('Paired. Start diagnosis')) { stage = 3; child.stdin.end(); } });
107
+ const timer = setTimeout(() => { if (child.pid) try { process.kill(-child.pid, 'SIGTERM'); } catch {} }, 8000);
108
+ try {
109
+ const exit = await new Promise(resolve => child.once('exit', resolve)); assert.equal(exit, 0, output); assert.equal(requestedRemember, true);
110
+ const saved = new PairingStore(join(root, '.diagnose', 'pairings')).get('alice-pc', 'operator'); assert.equal(saved.code, credential); assert.equal(output.includes(credential), false);
111
+ const listing = spawn(process.execPath, [resolve('dist/cli.js'), 'devices'], { env: { ...process.env, HOME: root } }); let metadata = ''; listing.stdout.on('data', bytes => metadata += bytes); await new Promise(resolve => listing.once('exit', resolve)); assert.equal(JSON.parse(metadata)[0].name, 'alice-pc'); assert.equal(metadata.includes(credential), false);
112
+ } finally { clearTimeout(timer); host.close(); if (child.pid) try { process.kill(-child.pid, 'SIGTERM'); } catch {} await relay.close(); }
113
+ });
114
+
115
+ for (const lifetime of [-1, 1500]) test(`remembered auto grant (${lifetime > 0 ? 'timer expiry' : 'already expired'}) requires approval after probe restart`, { skip: process.platform !== 'darwin', timeout: 12000 }, async () => {
116
+ const { spawn } = await import('node:child_process'); const { resolve } = await import('node:path');
117
+ const root = scratch(), relay = createRelay({ port: 0 }), url = `ws://127.0.0.1:${await relay.listen()}`, code = createCode();
118
+ const store = new PairingStore(join(root, '.diagnose', 'pairings')), record = store.add({ role: 'host', name: 'diagnostician', label: 'test', relay: url, code }); record.autoUntil = Date.now() + lifetime; store.save(record);
119
+ const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'expiry-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: root }, stdio: ['pipe', 'pipe', 'pipe'] });
120
+ let output = '', prompts = 0; child.stderr.resume(); child.stdout.on('data', bytes => { output += bytes.toString(); if (output.includes('Allow exactly this operation?') && !prompts) { prompts++; child.stdin.write('n\n'); } });
121
+ const connection = new RememberedConnection({ ...record, role: 'operator' }, 4000);
122
+ try { const operator = await connection.connect(); if (lifetime > 0) { for (let i = 0; i < 150 && !output.includes('Permission mode: ask'); i++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(output.includes('Permission mode: ask')); } const result = await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'Expired auto must not renew' }); assert.equal(result.result.status, 'denied'); assert.equal(prompts, 1); assert.equal(output.includes('Pairing code ('), false); }
123
+ finally { connection.close(); if (child.pid) try { process.kill(-child.pid, 'SIGTERM'); } catch {} await relay.close(); }
124
+ });