@masstensor/diagnose 0.5.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DEVELOPMENT_PLAN.md +69 -0
- package/KNOWLEDGE_SECURITY.md +47 -0
- package/PAIRING_PROTOCOL.md +37 -0
- package/README.md +28 -6
- package/USER_GUIDE.md +250 -34
- package/deploy/Caddyfile +1 -1
- package/deploy/ecosystem.config.cjs +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +15 -5
- package/dist/cases.d.ts +118 -0
- package/dist/cases.js +115 -0
- package/dist/cli.js +61 -13
- package/dist/crypto.d.ts +7 -0
- package/dist/crypto.js +16 -1
- package/dist/discover.js +1 -1
- package/dist/engine.d.ts +1 -0
- package/dist/engine.js +21 -7
- package/dist/install-skill.d.ts +2 -0
- package/dist/install-skill.js +57 -0
- package/dist/knowledge-cli.d.ts +2 -0
- package/dist/knowledge-cli.js +164 -0
- package/dist/knowledge-drafts.d.ts +47 -0
- package/dist/knowledge-drafts.js +76 -0
- package/dist/knowledge-mcp.d.ts +5 -0
- package/dist/knowledge-mcp.js +65 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +38 -9
- package/dist/operator.d.ts +2 -0
- package/dist/operator.js +18 -3
- package/dist/peer.d.ts +9 -0
- package/dist/peer.js +90 -10
- package/dist/relay-main.js +1 -1
- package/dist/relay.d.ts +1 -0
- package/dist/relay.js +46 -10
- package/dist/schema.d.ts +4 -1
- package/dist/schema.js +2 -2
- package/dist/session-limits.d.ts +3 -0
- package/dist/session-limits.js +3 -0
- package/dist/short-pairing.d.ts +25 -0
- package/dist/short-pairing.js +73 -0
- package/dist/skill-library.d.ts +27 -0
- package/dist/skill-library.js +226 -0
- package/dist/skill-session.d.ts +1 -0
- package/dist/skill-session.js +257 -0
- package/dist/skill.d.ts +1 -0
- package/dist/skill.js +1 -0
- package/dist/util.js +1 -0
- package/dist/vault-crypto.d.ts +11 -0
- package/dist/vault-crypto.js +30 -0
- package/dist/vault-server.d.ts +10 -0
- package/dist/vault-server.js +156 -0
- package/dist/vault.d.ts +19 -0
- package/dist/vault.js +72 -0
- package/npm-shrinkwrap.json +12 -2
- package/package.json +7 -2
- package/skills/connect/SKILL.md +60 -0
- package/skills/connect/scripts/run.mjs +37 -0
- package/src/agent.ts +12 -5
- package/src/cases.ts +74 -0
- package/src/cli.ts +51 -13
- package/src/crypto.ts +14 -1
- package/src/discover.ts +1 -1
- package/src/engine.ts +17 -4
- package/src/install-skill.ts +57 -0
- package/src/knowledge-cli.ts +67 -0
- package/src/knowledge-drafts.ts +55 -0
- package/src/knowledge-mcp.ts +35 -0
- package/src/mcp.ts +21 -7
- package/src/operator.ts +12 -3
- package/src/peer.ts +51 -14
- package/src/relay-main.ts +1 -1
- package/src/relay.ts +35 -7
- package/src/schema.ts +4 -2
- package/src/session-limits.ts +3 -0
- package/src/short-pairing.ts +57 -0
- package/src/skill-library.ts +162 -0
- package/src/skill-session.ts +233 -0
- package/src/skill.ts +2 -1
- package/src/util.ts +1 -0
- package/src/vault-crypto.ts +25 -0
- package/src/vault-server.ts +72 -0
- package/src/vault.ts +51 -0
- package/test/agent.test.ts +26 -1
- package/test/cli.test.ts +58 -10
- package/test/install-skill.test.ts +37 -0
- package/test/knowledge-mcp.test.ts +37 -0
- package/test/knowledge.test.ts +112 -0
- package/test/mcp.test.ts +1 -1
- package/test/pairing.test.ts +8 -3
- package/test/review.test.ts +17 -0
- package/test/short-pairing.test.ts +142 -0
- package/test/skill-library.test.ts +62 -0
- package/test/skill-session.test.ts +79 -0
- package/test/skill.test.ts +1 -1
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { fork } from 'node:child_process';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
6
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
7
|
+
import { relayUrl } from './peer.js';
|
|
8
|
+
import { DEFAULT_IDLE_MS } from './session-limits.js';
|
|
9
|
+
|
|
10
|
+
const cli = fileURLToPath(new URL('./cli.js', import.meta.url));
|
|
11
|
+
const loopback = '127.0.0.1';
|
|
12
|
+
const defaultRelay = 'https://diagnose.fenginwind.com';
|
|
13
|
+
const requestMs = 135_000;
|
|
14
|
+
const diagnosticOperations = new Set([
|
|
15
|
+
'system.inspect', 'file.read', 'file.stat', 'file.list', 'file.write',
|
|
16
|
+
'process.run', 'serial.capture', 'serial.exchange',
|
|
17
|
+
]);
|
|
18
|
+
const tools = new Set(['diagnose_start', 'diagnose_batch', 'diagnose_wait', 'diagnose_cancel']);
|
|
19
|
+
|
|
20
|
+
type Json = Record<string, unknown>;
|
|
21
|
+
type Endpoint = { port: number; secret: string };
|
|
22
|
+
|
|
23
|
+
function record(value: unknown): Json {
|
|
24
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Expected a JSON object');
|
|
25
|
+
return value as Json;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function readJson(stream: NodeJS.ReadableStream): Promise<Json> {
|
|
29
|
+
const chunks: Buffer[] = [];
|
|
30
|
+
let length = 0;
|
|
31
|
+
for await (const part of stream) {
|
|
32
|
+
const bytes = Buffer.from(part);
|
|
33
|
+
length += bytes.length;
|
|
34
|
+
if (length > 2 * 1024 * 1024) throw new Error('JSON request is too large');
|
|
35
|
+
chunks.push(bytes);
|
|
36
|
+
}
|
|
37
|
+
let parsed: unknown;
|
|
38
|
+
try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
|
39
|
+
catch { throw new Error('Invalid JSON on stdin or in session request'); }
|
|
40
|
+
return record(parsed);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function respond(response: ServerResponse, status: number, body: unknown): void {
|
|
44
|
+
response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
45
|
+
response.end(JSON.stringify(body));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function validateCall(name: unknown, args: Json): asserts name is string {
|
|
49
|
+
if (typeof name !== 'string' || !tools.has(name)) throw new Error('Unsupported tool for a skill session');
|
|
50
|
+
if (name === 'diagnose_start' && !diagnosticOperations.has(String(args.operation))) throw new Error('Unsupported operation for a skill session');
|
|
51
|
+
if (name === 'diagnose_batch' && (!Array.isArray(args.steps) || args.steps.some(step => !diagnosticOperations.has(String(record(step).operation))))) {
|
|
52
|
+
throw new Error('Unsupported batch operation for a skill session');
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function serve(relay: string): Promise<void> {
|
|
57
|
+
if (!process.send || !process.connected) throw new Error('Skill session worker must be started by the CLI');
|
|
58
|
+
const secret = randomBytes(32).toString('hex');
|
|
59
|
+
const client = new Client({ name: 'diagnose-skill-session', version: '1' });
|
|
60
|
+
const transport = new StdioClientTransport({ command: process.execPath, args: [cli, 'mcp', relay], stderr: 'ignore' });
|
|
61
|
+
let idle: NodeJS.Timeout | undefined;
|
|
62
|
+
let stopped = false;
|
|
63
|
+
let closing = false;
|
|
64
|
+
let connected = false;
|
|
65
|
+
let busy = false;
|
|
66
|
+
const stop = () => {
|
|
67
|
+
if (stopped) return;
|
|
68
|
+
stopped = true;
|
|
69
|
+
clearTimeout(idle);
|
|
70
|
+
server.close();
|
|
71
|
+
server.closeAllConnections();
|
|
72
|
+
void client.close().catch(() => {});
|
|
73
|
+
if (process.connected) process.disconnect?.();
|
|
74
|
+
};
|
|
75
|
+
const refreshIdle = (ms = DEFAULT_IDLE_MS) => {
|
|
76
|
+
clearTimeout(idle);
|
|
77
|
+
idle = setTimeout(stop, ms);
|
|
78
|
+
};
|
|
79
|
+
const handle = async (request: IncomingMessage, response: ServerResponse) => {
|
|
80
|
+
if (request.headers.authorization !== 'Bearer ' + secret) {
|
|
81
|
+
respond(response, 403, { error: 'Invalid skill session' });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (request.method !== 'POST' || !['/pair', '/call', '/close'].includes(request.url ?? '')) {
|
|
85
|
+
respond(response, 404, { error: 'Unknown skill session action' });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (closing) { respond(response, 409, { error: 'Skill session is closing' }); return; }
|
|
89
|
+
if (request.url === '/close') {
|
|
90
|
+
closing = true;
|
|
91
|
+
if (connected) await client.callTool({ name: 'diagnose_disconnect', arguments: {} }, undefined, { timeout: 3000 }).catch(() => {});
|
|
92
|
+
response.once('finish', stop);
|
|
93
|
+
respond(response, 200, { disconnected: true });
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (busy) {
|
|
97
|
+
respond(response, 409, { error: 'Another call is in progress for this session' });
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
busy = true;
|
|
101
|
+
let activity = false;
|
|
102
|
+
try {
|
|
103
|
+
const input = await readJson(request);
|
|
104
|
+
let name: string;
|
|
105
|
+
let args: Json;
|
|
106
|
+
if (request.url === '/pair') {
|
|
107
|
+
if (connected) throw new Error('Skill session is already paired');
|
|
108
|
+
args = { code: input.code, label: input.label };
|
|
109
|
+
name = 'diagnose_pair';
|
|
110
|
+
} else {
|
|
111
|
+
if (!connected) throw new Error('Skill session is not paired');
|
|
112
|
+
args = record(input.arguments);
|
|
113
|
+
validateCall(input.tool, args);
|
|
114
|
+
name = input.tool;
|
|
115
|
+
activity = true;
|
|
116
|
+
refreshIdle();
|
|
117
|
+
}
|
|
118
|
+
const result = await client.callTool({ name, arguments: args }, undefined, { timeout: requestMs });
|
|
119
|
+
if (result.isError) {
|
|
120
|
+
const content = result.content;
|
|
121
|
+
const error = Array.isArray(content) ? content.find(item => item.type === 'text')?.text : undefined;
|
|
122
|
+
respond(response, 400, { error: typeof error === 'string' ? error : 'Diagnose rejected the request' });
|
|
123
|
+
} else {
|
|
124
|
+
if (name === 'diagnose_pair') {
|
|
125
|
+
connected = true;
|
|
126
|
+
refreshIdle();
|
|
127
|
+
}
|
|
128
|
+
respond(response, 200, result.structuredContent ?? result.content);
|
|
129
|
+
}
|
|
130
|
+
} catch (error) {
|
|
131
|
+
respond(response, 400, { error: (error as Error).message });
|
|
132
|
+
} finally {
|
|
133
|
+
busy = false;
|
|
134
|
+
if (activity && !stopped) refreshIdle();
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
const server = createServer((request, response) => { void handle(request, response); });
|
|
138
|
+
server.maxConnections = 8;
|
|
139
|
+
server.requestTimeout = requestMs;
|
|
140
|
+
process.once('SIGINT', stop);
|
|
141
|
+
process.once('SIGTERM', stop);
|
|
142
|
+
client.onclose = stop;
|
|
143
|
+
try {
|
|
144
|
+
await client.connect(transport, { timeout: 15_000 });
|
|
145
|
+
await new Promise<void>((resolve, reject) => {
|
|
146
|
+
server.once('error', reject);
|
|
147
|
+
server.listen(0, loopback, resolve);
|
|
148
|
+
});
|
|
149
|
+
const port = (server.address() as { port: number }).port;
|
|
150
|
+
refreshIdle(requestMs + 25_000);
|
|
151
|
+
process.send({ port, secret });
|
|
152
|
+
} catch (error) {
|
|
153
|
+
stop();
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function endpoint(value: unknown): Endpoint {
|
|
159
|
+
if (typeof value !== 'string' || !/^\d{1,5}\.[a-f0-9]{64}$/.test(value)) throw new Error('Invalid skill session handle');
|
|
160
|
+
const [port, secret] = value.split('.');
|
|
161
|
+
if (Number(port) < 1 || Number(port) > 65535) throw new Error('Invalid skill session handle');
|
|
162
|
+
return { port: Number(port), secret: secret! };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function requestSession(session: Endpoint, action: string, body: Json = {}): Promise<Json> {
|
|
166
|
+
let response: Response;
|
|
167
|
+
try {
|
|
168
|
+
response = await fetch(`http://${loopback}:${session.port}/${action}`, {
|
|
169
|
+
method: 'POST',
|
|
170
|
+
headers: { authorization: 'Bearer ' + session.secret, 'content-type': 'application/json' },
|
|
171
|
+
body: JSON.stringify(body),
|
|
172
|
+
signal: AbortSignal.timeout(requestMs + 5000),
|
|
173
|
+
});
|
|
174
|
+
} catch {
|
|
175
|
+
throw new Error('Skill session unavailable or timed out. Inspect the result before retrying a change.');
|
|
176
|
+
}
|
|
177
|
+
const result = record(await response.json());
|
|
178
|
+
if (!response.ok) throw new Error(String(result.error ?? 'Skill session request failed'));
|
|
179
|
+
return result;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function open(input: Json): Promise<Json> {
|
|
183
|
+
if (typeof input.code !== 'string' || input.code.length > 120 || !input.code.trim()) throw new Error('Supply the one-time pairing code on stdin');
|
|
184
|
+
if (typeof input.label !== 'string' || !input.label.trim() || input.label.length > 120) throw new Error('Supply a diagnostic label on stdin');
|
|
185
|
+
if (input.relay !== undefined && typeof input.relay !== 'string') throw new Error('Invalid relay URL');
|
|
186
|
+
const relay = input.relay ?? defaultRelay;
|
|
187
|
+
relayUrl(relay);
|
|
188
|
+
const worker = fork(cli, ['skill-session', '_serve', relay], { detached: true, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
|
|
189
|
+
try {
|
|
190
|
+
const session = await new Promise<Endpoint>((resolve, reject) => {
|
|
191
|
+
const done = (error?: Error, result?: Endpoint) => {
|
|
192
|
+
clearTimeout(timer);
|
|
193
|
+
worker.off('error', failed);
|
|
194
|
+
worker.off('exit', exited);
|
|
195
|
+
worker.off('message', ready);
|
|
196
|
+
if (error) reject(error);
|
|
197
|
+
else resolve(result!);
|
|
198
|
+
};
|
|
199
|
+
const failed = (error: Error) => done(error);
|
|
200
|
+
const exited = () => done(new Error('Skill session worker exited during startup'));
|
|
201
|
+
const ready = (message: Endpoint) => {
|
|
202
|
+
try { done(undefined, endpoint(`${message.port}.${message.secret}`)); }
|
|
203
|
+
catch (error) { done(error as Error); }
|
|
204
|
+
};
|
|
205
|
+
const timer = setTimeout(() => done(new Error('Skill session worker did not start')), 20_000);
|
|
206
|
+
worker.once('error', failed);
|
|
207
|
+
worker.once('exit', exited);
|
|
208
|
+
worker.once('message', ready);
|
|
209
|
+
});
|
|
210
|
+
worker.disconnect();
|
|
211
|
+
worker.unref();
|
|
212
|
+
const result = await requestSession(session, 'pair', { code: input.code, label: input.label });
|
|
213
|
+
return { ...result, session: session.port + '.' + session.secret, idleSeconds: DEFAULT_IDLE_MS / 1000 };
|
|
214
|
+
} catch (error) {
|
|
215
|
+
worker.kill();
|
|
216
|
+
throw error;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export async function skillSessionCommand(args: string[]): Promise<void> {
|
|
221
|
+
if (args[0] === '_serve' && args.length === 2) {
|
|
222
|
+
await serve(args[1]!);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const [action] = args;
|
|
226
|
+
if (args.length !== 1 || !['open', 'call', 'close'].includes(action ?? '')) {
|
|
227
|
+
throw new Error('Usage: diagnose skill-session open|call|close (JSON on stdin)');
|
|
228
|
+
}
|
|
229
|
+
const input = await readJson(process.stdin);
|
|
230
|
+
const result = action === 'open' ? await open(input)
|
|
231
|
+
: await requestSession(endpoint(input.session), action!, action === 'call' ? { tool: input.tool, arguments: input.arguments } : {});
|
|
232
|
+
console.log(JSON.stringify(result));
|
|
233
|
+
}
|
package/src/skill.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { dirname, extname, join, resolve } from 'node:path';
|
|
|
3
3
|
import { isUtf8 } from 'node:buffer';
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
5
|
|
|
6
|
-
export type SessionSkill = { sourceFile: string; baseDirectory: string; sha256: string; instructions: string };
|
|
6
|
+
export type SessionSkill = { sourceFile: string; baseDirectory: string; sha256: string; instructions: string; libraryReference?: string };
|
|
7
7
|
const MAX_SKILL = 256 * 1024;
|
|
8
8
|
|
|
9
9
|
export async function loadSkill(input: string): Promise<SessionSkill> {
|
|
@@ -37,6 +37,7 @@ export function skillPrompt(snapshot: string): string {
|
|
|
37
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
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
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
|
+
'Use diagnose_capabilities to inspect argument schemas. Use diagnose_case status/show to find an existing case. If none exists, create one for the actual external target and goal before remote tasks; if the snapshot has libraryReference, record it as the case skill. Confirm target identity and interface before repairs. Keep before/after evidence IDs and finish the case with a supported outcome. If reusable knowledge emerged, propose diagnose_skill_draft for human review; never run draft acceptance or vault upload on the diagnostician behalf.',
|
|
40
41
|
'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
42
|
'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
43
|
'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.'
|
package/src/util.ts
CHANGED
|
@@ -11,6 +11,7 @@ export function safeText(text: string): string {
|
|
|
11
11
|
export function redact(text: string): string {
|
|
12
12
|
return safeText(text)
|
|
13
13
|
.replace(/("?(?:password|passwd|pswd|secret|token|session|authorization|api[_-]?key)"?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,}\r\n]+)/gi, '$1[REDACTED]')
|
|
14
|
+
.replace(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/gi, '[INVITATION CODE]')
|
|
14
15
|
.replace(/\bD1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}\b/g, '[PAIRING CODE]')
|
|
15
16
|
.replace(/\b[a-f0-9]{32,}\b/gi, '[REDACTED]')
|
|
16
17
|
.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, '[PRIVATE KEY]');
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createHash, createHmac, hkdfSync, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
|
|
2
|
+
export const MAX_VAULT_OBJECT = 12 * 1024 * 1024;
|
|
3
|
+
export function newRecovery(): string { return 'K1.' + randomBytes(32).toString('base64url'); }
|
|
4
|
+
export function vaultKeys(recovery: string) {
|
|
5
|
+
if (!/^K1\.[A-Za-z0-9_-]{43}$/.test(recovery)) throw new Error('Invalid library recovery key');
|
|
6
|
+
const root = Buffer.from(recovery.slice(3), 'base64url');
|
|
7
|
+
if (root.toString('base64url') !== recovery.slice(3)) throw new Error('Noncanonical recovery key');
|
|
8
|
+
const derive = (purpose: string) => Buffer.from(hkdfSync('sha256', root, 'diagnose-library-v1', purpose, 32));
|
|
9
|
+
const auth = derive('authentication').toString('base64url');
|
|
10
|
+
return { auth, namespace: createHash('sha256').update(auth).digest('hex'), encryption: derive('encryption'), index: derive('object-names') };
|
|
11
|
+
}
|
|
12
|
+
export function objectId(recovery: string, reference: string): string { return createHmac('sha256', vaultKeys(recovery).index).update(reference).digest('hex'); }
|
|
13
|
+
export function sealBundle(recovery: string, id: string, bytes: Buffer): Buffer {
|
|
14
|
+
const keys = vaultKeys(recovery), nonce = randomBytes(12), cipher = createCipheriv('aes-256-gcm', keys.encryption, nonce);
|
|
15
|
+
cipher.setAAD(Buffer.from(`diagnose-library-v1:${keys.namespace}:${id}`));
|
|
16
|
+
const sealed = Buffer.concat([Buffer.from([1]), nonce, cipher.update(bytes), cipher.final(), cipher.getAuthTag()]);
|
|
17
|
+
if (sealed.length > MAX_VAULT_OBJECT) throw new Error('Encrypted bundle exceeds 12 MiB');
|
|
18
|
+
return sealed;
|
|
19
|
+
}
|
|
20
|
+
export function openBundle(recovery: string, id: string, sealed: Buffer): Buffer {
|
|
21
|
+
if (sealed.length < 29 || sealed.length > MAX_VAULT_OBJECT || sealed[0] !== 1) throw new Error('Invalid encrypted library object');
|
|
22
|
+
const keys = vaultKeys(recovery), decipher = createDecipheriv('aes-256-gcm', keys.encryption, sealed.subarray(1, 13));
|
|
23
|
+
decipher.setAAD(Buffer.from(`diagnose-library-v1:${keys.namespace}:${id}`)); decipher.setAuthTag(sealed.subarray(-16));
|
|
24
|
+
return Buffer.concat([decipher.update(sealed.subarray(13, -16)), decipher.final()]);
|
|
25
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdirSync, readdirSync, statSync, existsSync, readFileSync, writeFileSync, renameSync, rmSync, unlinkSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { MAX_VAULT_OBJECT } from './vault-crypto.js';
|
|
6
|
+
|
|
7
|
+
// Opaque capability-authenticated immutable objects. No encryption key reaches
|
|
8
|
+
// this module. One relay process owns the store; do not use PM2 cluster mode.
|
|
9
|
+
export class VaultServer {
|
|
10
|
+
private activeUploads = 0;
|
|
11
|
+
private requests = new Map<string, { since: number; count: number }>();
|
|
12
|
+
constructor(readonly root: string, readonly maxTotalBytes = 1024 ** 3) {
|
|
13
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
14
|
+
// No interrupted request is published: abandoned staging files are disposable.
|
|
15
|
+
for (const name of readdirSync(root)) if (/^[a-f0-9]{64}$/.test(name)) for (const file of readdirSync(join(root, name))) if (file.startsWith('.upload-')) rmSync(join(root, name, file), { force: true });
|
|
16
|
+
}
|
|
17
|
+
private inventory(directory: string): { id: string; bytes: number }[] {
|
|
18
|
+
if (!existsSync(directory)) return [];
|
|
19
|
+
return readdirSync(directory).filter(name => /^[a-f0-9]{64}$/.test(name)).map(id => ({ id, bytes: statSync(join(directory, id)).size }));
|
|
20
|
+
}
|
|
21
|
+
async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
22
|
+
const send = (status: number, value: unknown) => { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); };
|
|
23
|
+
try {
|
|
24
|
+
const direct = req.socket.remoteAddress ?? 'unknown';
|
|
25
|
+
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;
|
|
26
|
+
for (const [key, rate] of this.requests) if (Date.now() - rate.since > 60000) this.requests.delete(key);
|
|
27
|
+
if (!this.requests.has(ip) && this.requests.size >= 10000) { send(429, { error: 'Rate limit' }); return; }
|
|
28
|
+
const rate = this.requests.get(ip) ?? { since: Date.now(), count: 0 }; this.requests.set(ip, rate);
|
|
29
|
+
if (++rate.count > 600) { send(429, { error: 'Rate limit' }); return; }
|
|
30
|
+
const auth = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(req.headers.authorization ?? '');
|
|
31
|
+
if (!auth) { send(401, { error: 'Library capability required' }); return; }
|
|
32
|
+
const namespace = createHash('sha256').update(auth[1]).digest('hex'), directory = join(this.root, namespace);
|
|
33
|
+
if (existsSync(join(this.root, namespace + '.revoked'))) { send(403, { error: 'Library revoked' }); return; }
|
|
34
|
+
const match = /^\/v1\/library(?:\/([a-f0-9]{64}))?$/.exec(req.url ?? '');
|
|
35
|
+
if (!match) { send(404, { error: 'Not found' }); return; }
|
|
36
|
+
const id = match[1];
|
|
37
|
+
if (req.method === 'GET') {
|
|
38
|
+
if (!id) { send(200, { objects: this.inventory(directory) }); return; }
|
|
39
|
+
const path = join(directory, id);
|
|
40
|
+
if (!existsSync(path)) { send(404, { error: 'Not found' }); return; }
|
|
41
|
+
const bytes = readFileSync(path); res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Length': bytes.length }); res.end(bytes); return;
|
|
42
|
+
}
|
|
43
|
+
if (req.method === 'DELETE' && !id) {
|
|
44
|
+
if (!existsSync(directory)) { send(404, { error: 'Library not found' }); return; }
|
|
45
|
+
writeFileSync(join(this.root, namespace + '.revoked'), '', { mode: 0o600, flush: true }); rmSync(directory, { recursive: true, force: true }); send(200, { revoked: true }); return;
|
|
46
|
+
}
|
|
47
|
+
if (req.method !== 'PUT' || !id) { send(405, { error: 'Use GET, PUT object or DELETE library' }); return; }
|
|
48
|
+
const length = Number(req.headers['content-length']);
|
|
49
|
+
if (!Number.isInteger(length) || length < 29 || length > MAX_VAULT_OBJECT) { send(413, { error: 'Content-Length required, 29 bytes..12 MiB' }); return; }
|
|
50
|
+
if (this.activeUploads >= 2) { send(429, { error: 'Upload capacity reached' }); return; }
|
|
51
|
+
if (existsSync(join(directory, id))) { send(409, { error: 'Immutable object already exists' }); return; }
|
|
52
|
+
this.activeUploads++;
|
|
53
|
+
const deadline = setTimeout(() => req.destroy(), 30000);
|
|
54
|
+
try {
|
|
55
|
+
const chunks: Buffer[] = []; let size = 0;
|
|
56
|
+
for await (const chunk of req) { size += chunk.length; if (size > length) throw new Error('Size mismatch'); chunks.push(Buffer.from(chunk)); }
|
|
57
|
+
if (size !== length) throw new Error('Incomplete upload');
|
|
58
|
+
// Commit checks are synchronous so concurrent requests cannot overrun quota.
|
|
59
|
+
if (existsSync(join(this.root, namespace + '.revoked'))) { send(403, { error: 'Library revoked' }); return; }
|
|
60
|
+
const own = this.inventory(directory), names = readdirSync(this.root).filter(name => /^[a-f0-9]{64}(?:\.revoked)?$/.test(name));
|
|
61
|
+
const total = names.filter(name => !name.endsWith('.revoked')).reduce((sum, name) => sum + this.inventory(join(this.root, name)).reduce((n, item) => n + item.bytes, 0), 0);
|
|
62
|
+
if (own.length >= 128 || own.reduce((n, item) => n + item.bytes, 0) + size > 128 * 1024 ** 2 || total + size > this.maxTotalBytes || (!existsSync(directory) && names.length >= 1000)) { send(507, { error: 'Library storage quota reached' }); return; }
|
|
63
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
64
|
+
if (existsSync(join(directory, id))) { send(409, { error: 'Immutable object already exists' }); return; }
|
|
65
|
+
const path = join(directory, '.upload-' + randomUUID());
|
|
66
|
+
try { writeFileSync(path, Buffer.concat(chunks), { flag: 'wx', mode: 0o600, flush: true }); renameSync(path, join(directory, id)); }
|
|
67
|
+
finally { if (existsSync(path)) unlinkSync(path); }
|
|
68
|
+
send(201, { stored: true });
|
|
69
|
+
} finally { clearTimeout(deadline); this.activeUploads--; }
|
|
70
|
+
} catch { if (!res.headersSent && !res.destroyed) send(400, { error: 'Library request failed' }); else res.destroy(); }
|
|
71
|
+
}
|
|
72
|
+
}
|
package/src/vault.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { readFile, writeFile, mkdir, rm } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { SkillLibrary } from './skill-library.js';
|
|
5
|
+
import { MAX_VAULT_OBJECT, newRecovery, vaultKeys, objectId, sealBundle, openBundle } from './vault-crypto.js';
|
|
6
|
+
|
|
7
|
+
export class Vault {
|
|
8
|
+
constructor(readonly library = new SkillLibrary(), readonly root = join(homedir(), '.diagnose', 'vault'), readonly relay = 'https://diagnose.fenginwind.com') {
|
|
9
|
+
const url = new URL(relay);
|
|
10
|
+
if (url.username || url.password || url.search || url.hash || !['', '/'].includes(url.pathname) || !(url.protocol === 'https:' || (url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)))) throw new Error('Library relay must be an HTTPS origin (HTTP allowed only for loopback tests)');
|
|
11
|
+
}
|
|
12
|
+
private async key(): Promise<string> { const value = (await readFile(join(this.root, 'recovery'), 'utf8')).trim(); vaultKeys(value); return value; }
|
|
13
|
+
async initialize(recovery = newRecovery()): Promise<void> {
|
|
14
|
+
vaultKeys(recovery); await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
15
|
+
await writeFile(join(this.root, 'recovery'), recovery + '\n', { flag: 'wx', mode: 0o600, flush: true });
|
|
16
|
+
}
|
|
17
|
+
async backup(path: string): Promise<void> { await writeFile(path, await this.key() + '\n', { flag: 'wx', mode: 0o600, flush: true }); }
|
|
18
|
+
private async request(method: string, suffix = '', body?: Buffer): Promise<Buffer> {
|
|
19
|
+
const auth = vaultKeys(await this.key()).auth;
|
|
20
|
+
const response = await fetch(new URL('/v1/library' + suffix, this.relay), { method, headers: { Authorization: 'Bearer ' + auth, ...(body ? { 'Content-Type': 'application/octet-stream', 'Content-Length': String(body.length) } : {}) }, body: body ? new Uint8Array(body) : undefined, redirect: 'error', signal: AbortSignal.timeout(45000) });
|
|
21
|
+
if (!response.ok) { await response.body?.cancel(); throw new Error(`Library ${method} failed (${response.status}); no action was retried`); }
|
|
22
|
+
const chunks: Buffer[] = []; let total = 0;
|
|
23
|
+
if (response.body) for await (const chunk of response.body) { total += chunk.length; if (total > MAX_VAULT_OBJECT) throw new Error('Library response too large'); chunks.push(Buffer.from(chunk)); }
|
|
24
|
+
return Buffer.concat(chunks);
|
|
25
|
+
}
|
|
26
|
+
async list(): Promise<{ id: string; bytes: number }[]> {
|
|
27
|
+
const response = JSON.parse((await this.request('GET')).toString());
|
|
28
|
+
if (!Array.isArray(response.objects) || response.objects.length > 128 || response.objects.some((item: { id?: unknown; bytes?: number }) => typeof item.id !== 'string' || !/^[a-f0-9]{64}$/.test(item.id) || !Number.isInteger(item.bytes) || item.bytes! > MAX_VAULT_OBJECT || item.bytes! < 29)) throw new Error('Invalid library inventory');
|
|
29
|
+
return response.objects;
|
|
30
|
+
}
|
|
31
|
+
async push(reference: string): Promise<void> {
|
|
32
|
+
const recovery = await this.key(), bundle = await this.library.bundle(reference), id = objectId(recovery, reference);
|
|
33
|
+
const existing = (await this.list()).some(item => item.id === id);
|
|
34
|
+
if (existing) {
|
|
35
|
+
const bytes = openBundle(recovery, id, await this.request('GET', '/' + id));
|
|
36
|
+
if (bytes.toString() !== JSON.stringify(bundle)) throw new Error('Remote immutable version conflicts with local bundle'); return;
|
|
37
|
+
}
|
|
38
|
+
await this.request('PUT', '/' + id, sealBundle(recovery, id, Buffer.from(JSON.stringify(bundle))));
|
|
39
|
+
}
|
|
40
|
+
async pull(): Promise<string[]> {
|
|
41
|
+
const recovery = await this.key(), references: string[] = [];
|
|
42
|
+
for (const { id } of await this.list()) {
|
|
43
|
+
const bundle = JSON.parse(openBundle(recovery, id, await this.request('GET', '/' + id)).toString());
|
|
44
|
+
if (typeof bundle.reference !== 'string' || objectId(recovery, bundle.reference) !== id) throw new Error('Library object identity mismatch');
|
|
45
|
+
references.push(await this.library.restore(bundle));
|
|
46
|
+
}
|
|
47
|
+
return references;
|
|
48
|
+
}
|
|
49
|
+
async revoke(): Promise<void> { await this.request('DELETE'); }
|
|
50
|
+
async forget(): Promise<void> { await rm(join(this.root, 'recovery')); }
|
|
51
|
+
}
|
package/test/agent.test.ts
CHANGED
|
@@ -41,7 +41,7 @@ for (const agent of ['codex', 'claude', 'gemini']) test(`agent ${agent} loads re
|
|
|
41
41
|
const f = fixture(), before = readFileSync(f.settings, 'utf8');
|
|
42
42
|
const result = await run(['agent', agent, '--relay', 'https://relay.example.test', '--', '--model', 'a model with spaces', 'literal $(do-not-execute)'], { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture, TEST_EXIT: '7' });
|
|
43
43
|
assert.equal(result.code, 7, result.output); const captured = JSON.parse(readFileSync(f.capture, 'utf8'));
|
|
44
|
-
assert.equal(captured.server.command, process.execPath); assert.deepEqual(captured.server.args, [cli, 'mcp', 'https://relay.example.test']); assert.equal(captured.tools.length,
|
|
44
|
+
assert.equal(captured.server.command, process.execPath); assert.deepEqual(captured.server.args, [cli, 'mcp', 'https://relay.example.test']); assert.equal(captured.tools.length, 15); assert.ok(captured.tools.includes('diagnose_pair')); assert.ok(captured.tools.includes('diagnose_process'));
|
|
45
45
|
assert.deepEqual(captured.args.slice(-3), ['--model', 'a model with spaces', 'literal $(do-not-execute)']);
|
|
46
46
|
assert.equal(readFileSync(f.settings, 'utf8'), before); for (const name of ['.codex', '.claude', '.gemini']) assert.equal(readFileSync(join(f.root, name, 'sentinel'), 'utf8'), 'unchanged');
|
|
47
47
|
if (agent === 'gemini') { assert.equal(captured.admin.marker, 'preserve-admin-policy'); assert.equal(existsSync(captured.settingsPath), false); }
|
|
@@ -85,6 +85,20 @@ test('skill directory is accepted, and invalid skills fail before launching an a
|
|
|
85
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
86
|
});
|
|
87
87
|
|
|
88
|
+
for (const agent of ['codex', 'claude', 'gemini']) test(`agent ${agent} launches a pinned library bundle through the CLI`, { skip: process.platform === 'win32', timeout: 15000 }, async () => {
|
|
89
|
+
const f = fixture(), source = join(f.root, 'source'); mkdirSync(source); mkdirSync(join(source, 'references'));
|
|
90
|
+
writeFileSync(join(source, 'SKILL.md'), '# Library task\nRead references/profile.md.'); writeFileSync(join(source, 'references/profile.md'), 'Model A');
|
|
91
|
+
const env = { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture };
|
|
92
|
+
const imported = await run(['skills', 'import', 'gateway', source], env); assert.equal(imported.code, 0, imported.output);
|
|
93
|
+
const reference = imported.output.trim(); assert.match(reference, /^library:gateway@[a-f0-9]{64}$/);
|
|
94
|
+
const listed = await run(['skills', 'list'], env); assert.deepEqual(JSON.parse(listed.output), [reference]);
|
|
95
|
+
const launched = await run(['agent', agent, '--skill', reference], env); assert.equal(launched.code, 0, launched.output);
|
|
96
|
+
const captured = JSON.parse(readFileSync(f.capture, 'utf8'));
|
|
97
|
+
assert.equal(captured.task.instructions, '# Library task\nRead references/profile.md.');
|
|
98
|
+
assert.equal(readFileSync(join(captured.task.baseDirectory, 'references/profile.md'), 'utf8'), 'Model A');
|
|
99
|
+
assert.ok(captured.task.baseDirectory.includes(reference.split('@')[1]));
|
|
100
|
+
});
|
|
101
|
+
|
|
88
102
|
test('termination also removes the skill snapshot', { skip: process.platform === 'win32', timeout: 10000 }, async () => {
|
|
89
103
|
const f = fixture(), source = join(f.root, 'task.md'); writeFileSync(source, '# Test task');
|
|
90
104
|
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));
|
|
@@ -102,3 +116,14 @@ for (const agent of ['codex', 'claude', 'gemini']) test(`selected startup task r
|
|
|
102
116
|
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
117
|
} finally { engine.cancelAll(); host.close(); await relay.close(); }
|
|
104
118
|
});
|
|
119
|
+
|
|
120
|
+
for (const agent of ['codex', 'claude', 'gemini']) test(`agent ${agent} starts the selected case with its pinned skill`, { skip: process.platform === 'win32', timeout: 15000 }, async () => {
|
|
121
|
+
const { Cases } = await import('../dist/cases.js'), { SkillLibrary } = await import('../dist/skill-library.js');
|
|
122
|
+
const f = fixture(), source = join(f.root, 'task.md'); writeFileSync(source, '# Case procedure');
|
|
123
|
+
const reference = await new SkillLibrary(join(f.root, '.diagnose', 'skills')).import('gateway', source);
|
|
124
|
+
const selected = new Cases(join(f.root, '.diagnose', 'cases')).create({ goal: 'Check device logs', target: { name: 'Gateway', interface: 'serial' }, skill: reference });
|
|
125
|
+
const env = { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture };
|
|
126
|
+
const result = await run(['agent', agent, '--case', selected.id], env); assert.equal(result.code, 0, result.output);
|
|
127
|
+
const captured = JSON.parse(readFileSync(f.capture, 'utf8')); assert.equal(captured.task.libraryReference, reference); assert.deepEqual(captured.server.args.slice(-2), ['--case', selected.id]);
|
|
128
|
+
const conflict = await run(['agent', agent, '--case', selected.id, '--skill', source], env); assert.equal(conflict.code, 1); assert.match(conflict.output, /revision differs/);
|
|
129
|
+
});
|
package/test/cli.test.ts
CHANGED
|
@@ -12,12 +12,13 @@ test('actual host CLI displays and enforces pairing, execution and transfer prom
|
|
|
12
12
|
const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`;
|
|
13
13
|
// macOS script accepts a POSIX pipe, but not Node's socketpair-backed stdin.
|
|
14
14
|
const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'diagnose-cli-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: mkdtempSync(tmpdir() + '/diagnose-cli-') }, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
15
|
-
let text = '', pairing = false, executing = false, sending = false;
|
|
15
|
+
let text = '', startup = false, pairing = false, executing = false, sending = false;
|
|
16
16
|
let stderr = ''; child.stderr.on('data', bytes => { stderr += bytes.toString(); });
|
|
17
17
|
let codeResolve!: (value: string) => void;
|
|
18
18
|
const code = new Promise<string>(resolve => { codeResolve = resolve; });
|
|
19
19
|
child.stdout.on('data', bytes => {
|
|
20
|
-
text += bytes.toString(); const match =
|
|
20
|
+
text += bytes.toString(); const match = /\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/.exec(text); if (match) codeResolve(match[0]);
|
|
21
|
+
if (!startup && text.includes('Task approval for the next session?')) { startup = true; child.stdin.write('\n'); }
|
|
21
22
|
if (!pairing && text.includes('Allow this temporary diagnostic session?')) { pairing = true; child.stdin.write('y\n'); }
|
|
22
23
|
if (!executing && text.includes('Allow exactly this operation?')) { executing = true; child.stdin.write('y\n'); }
|
|
23
24
|
if (!sending && text.includes('Send these results (')) { sending = true; child.stdin.write('y\n'); }
|
|
@@ -28,19 +29,21 @@ test('actual host CLI displays and enforces pairing, execution and transfer prom
|
|
|
28
29
|
const pairCode = await Promise.race([code, new Promise<never>((_, reject) => child.once('exit', () => reject(new Error('CLI exited before registration: ' + stderr))))]);
|
|
29
30
|
peer = new Peer({ role: 'join', code: pairCode, relay: url }); const operator = new Operator(peer); await peer.open();
|
|
30
31
|
const result = await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'Verify terminal approvals' });
|
|
31
|
-
assert.equal(result.result.status, 'ok'); assert.ok(pairing && executing && sending); assert.ok(text.includes('TRANSFER APPROVAL'));
|
|
32
|
+
assert.equal(result.result.status, 'ok'); assert.ok(startup && pairing && executing && sending); assert.ok(text.includes('TRANSFER APPROVAL'));
|
|
32
33
|
} finally { clearTimeout(timer); peer?.close(); child.stdin.end('\x03'); if (child.pid) { try { process.kill(-child.pid, 'SIGTERM'); } catch {} } await relay.close(); }
|
|
33
34
|
});
|
|
34
35
|
|
|
35
|
-
test('host CLI auto
|
|
36
|
+
test('host CLI offers auto before the invitation, confirms at pairing and limits it to that session', { skip: process.platform !== 'darwin', timeout: 15000 }, async () => {
|
|
36
37
|
const relay = createRelay({ port: 0 }); const url = `ws://127.0.0.1:${await relay.listen()}`;
|
|
37
38
|
const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'diagnose-cli-auto-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: mkdtempSync(tmpdir() + '/diagnose-cli-auto-') }, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
38
|
-
let output = '', paired = false, executionPrompts = 0, transferPrompts = 0; let resolveCode!: (value: string) => void;
|
|
39
|
+
let output = '', startup = false, paired = false, secondPair = false, executionPrompts = 0, transferPrompts = 0; let resolveCode!: (value: string) => void;
|
|
39
40
|
const code = new Promise<string>(resolve => { resolveCode = resolve; });
|
|
40
41
|
child.stderr.resume();
|
|
41
42
|
child.stdout.on('data', bytes => {
|
|
42
|
-
output += bytes.toString(); const match =
|
|
43
|
-
if (!
|
|
43
|
+
output += bytes.toString(); const match = /\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/.exec(output); if (match) resolveCode(match[0]);
|
|
44
|
+
if (!startup && output.includes('Task approval for the next session?')) { startup = true; child.stdin.write('a\n'); }
|
|
45
|
+
if (!paired && output.includes('Allow this temporary session with auto approval?')) { paired = true; child.stdin.write('y\n'); }
|
|
46
|
+
if (!secondPair && output.includes('Allow this temporary diagnostic session?')) { secondPair = true; child.stdin.write('y\n'); }
|
|
44
47
|
const executionCount = output.split('Allow exactly this operation?').length - 1;
|
|
45
48
|
if (executionCount > executionPrompts) { executionPrompts = executionCount; child.stdin.write('n\n'); }
|
|
46
49
|
transferPrompts = output.split('Send these results (').length - 1;
|
|
@@ -48,7 +51,10 @@ test('host CLI auto selection skips task prompts, can revoke, and requires local
|
|
|
48
51
|
const waitFor = async (predicate: () => boolean) => { for (let i = 0; i < 100 && !predicate(); i++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(predicate()); };
|
|
49
52
|
let peer: Peer | undefined;
|
|
50
53
|
try {
|
|
51
|
-
|
|
54
|
+
const firstCode = await code;
|
|
55
|
+
assert.ok(startup && output.includes('Auto approval selected'));
|
|
56
|
+
assert.ok(output.indexOf('Task approval for the next session?') < output.indexOf(firstCode));
|
|
57
|
+
peer = new Peer({ role: 'join', code: firstCode, relay: url }); const operator = new Operator(peer); await peer.open();
|
|
52
58
|
const plan = { operation: 'batch.run' as const, arguments: { steps: [{ operation: 'process.script', arguments: { interpreter: process.execPath, script: 'console.log("CLI auto")' } }, { operation: 'system.inspect', arguments: {} }] }, reason: 'Verify CLI auto plan' };
|
|
53
59
|
const result = await operator.run(plan); assert.equal(result.result.status, 'ok'); assert.equal(result.outputs['0.stdout'], 'CLI auto\n'); assert.equal(executionPrompts, 0); assert.equal(transferPrompts, 0); assert.ok(output.includes('without further prompts'));
|
|
54
60
|
child.stdin.write('permissions ask\n'); await waitFor(() => output.includes('Automatic permissions revoked'));
|
|
@@ -56,6 +62,48 @@ test('host CLI auto selection skips task prompts, can revoke, and requires local
|
|
|
56
62
|
child.stdin.write('permissions auto\n'); await waitFor(() => output.includes('within 60 seconds to grant'));
|
|
57
63
|
child.stdin.write('permissions allow-auto\n'); await waitFor(() => output.split('Permission mode: auto').length >= 3);
|
|
58
64
|
const again = await operator.run(plan); assert.equal(again.result.status, 'ok'); assert.equal(executionPrompts, 1); assert.equal(transferPrompts, 0);
|
|
65
|
+
peer.close();
|
|
66
|
+
const codes = () => [...new Set(output.match(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/g) ?? [])];
|
|
67
|
+
await waitFor(() => codes().length >= 2);
|
|
68
|
+
peer = new Peer({ role: 'join', code: codes()[1], relay: url });
|
|
69
|
+
const nextOperator = new Operator(peer); await peer.open();
|
|
70
|
+
const next = await nextOperator.run({ operation: 'system.inspect', arguments: {}, reason: 'New sessions require fresh approval' });
|
|
71
|
+
assert.equal(next.result.status, 'denied'); assert.ok(secondPair); assert.equal(executionPrompts, 2);
|
|
72
|
+
} finally { peer?.close(); child.stdin.end('\x03'); if (child.pid) { try { process.kill(-child.pid, 'SIGTERM'); } catch {} } await relay.close(); }
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test('Approve everything accepts a short invitation once and automatically executes and sends the result', { skip: process.platform !== 'darwin', timeout: 15000 }, async () => {
|
|
76
|
+
const relay = createRelay({ port: 0 }), url = `ws://127.0.0.1:${await relay.listen()}`;
|
|
77
|
+
const root = mkdtempSync(join(tmpdir(), 'diagnose-cli-all-'));
|
|
78
|
+
const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'diagnose-cli-all-test', process.execPath, resolve('dist/cli.js'), 'start', url], { detached: true, env: { ...process.env, HOME: root }, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
79
|
+
let output = '', startup = false, secondPrompt = false;
|
|
80
|
+
child.stderr.resume();
|
|
81
|
+
child.stdout.on('data', bytes => {
|
|
82
|
+
output += bytes.toString();
|
|
83
|
+
if (!startup && output.includes('e=approve everything')) { startup = true; child.stdin.write('e\n'); }
|
|
84
|
+
if (!secondPrompt && output.includes('Allow this temporary diagnostic session?')) { secondPrompt = true; child.stdin.write('n\n'); }
|
|
85
|
+
});
|
|
86
|
+
const codes = () => [...new Set(output.match(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/g) ?? [])];
|
|
87
|
+
const untilCode = async (index: number) => {
|
|
88
|
+
for (let i = 0; i < 200 && !codes()[index]; i++) await new Promise(resolve => setTimeout(resolve, 20));
|
|
89
|
+
assert.ok(codes()[index], output);
|
|
90
|
+
return codes()[index]!;
|
|
91
|
+
};
|
|
92
|
+
let peer: Peer | undefined;
|
|
93
|
+
try {
|
|
94
|
+
peer = new Peer({ role: 'join', code: await untilCode(0), relay: url });
|
|
95
|
+
const operator = new Operator(peer);
|
|
96
|
+
await peer.open();
|
|
97
|
+
assert.match(output, /Connection approved by your startup selection/);
|
|
98
|
+
const result = await operator.run({ operation: 'system.inspect', arguments: {}, reason: 'Verify session-wide approval' });
|
|
99
|
+
assert.equal(result.result.status, 'ok');
|
|
100
|
+
assert.match(output, /\[AUTO send\] system\.inspect/);
|
|
101
|
+
assert.doesNotMatch(output, /EXECUTION APPROVAL|TRANSFER APPROVAL/);
|
|
102
|
+
assert.equal(secondPrompt, false);
|
|
103
|
+
peer.close();
|
|
104
|
+
peer = new Peer({ role: 'join', code: await untilCode(1), relay: url });
|
|
105
|
+
await assert.rejects(peer.open());
|
|
106
|
+
assert.equal(secondPrompt, true, 'A new invitation must require local pairing approval');
|
|
59
107
|
} finally { peer?.close(); child.stdin.end('\x03'); if (child.pid) { try { process.kill(-child.pid, 'SIGTERM'); } catch {} } await relay.close(); }
|
|
60
108
|
});
|
|
61
109
|
|
|
@@ -74,8 +122,8 @@ test('terminal CLI attaches a native PTY and executes interactive input', { skip
|
|
|
74
122
|
test('host CLI re-pairs after disconnect and resumes retained process without rerunning it', { skip: process.platform !== 'darwin', timeout: 15000 }, async () => {
|
|
75
123
|
const childHome = mkdtempSync(join(tmpdir(), 'diagnose-repair-')), relay = createRelay({ port: 0 }), url = `ws://127.0.0.1:${await relay.listen()}`;
|
|
76
124
|
const child = spawn('/bin/sh', ['-c', 'cat | /usr/bin/script -q /dev/null "$@"', 'repair-test', process.execPath, 'dist/cli.js', 'start', url], { detached: true, env: { ...process.env, HOME: childHome }, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
77
|
-
let output = '', approvals = 0; child.stderr.resume(); child.stdout.on('data', bytes => { output += bytes.toString(); const count = output.split('Allow this temporary diagnostic session?').length - 1; if (count > approvals) { approvals = count; child.stdin.write('a\n'); } });
|
|
78
|
-
const codes = () => [...new Set(output.match(
|
|
125
|
+
let output = '', startup = false, approvals = 0; child.stderr.resume(); child.stdout.on('data', bytes => { output += bytes.toString(); if (!startup && output.includes('Task approval for the next session?')) { startup = true; child.stdin.write('\n'); } const count = output.split('Allow this temporary diagnostic session?').length - 1; if (count > approvals) { approvals = count; child.stdin.write('a\n'); } });
|
|
126
|
+
const codes = () => [...new Set(output.match(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/g) ?? [])];
|
|
79
127
|
const until = async (predicate: () => boolean) => { for (let n = 0; n < 200 && !predicate(); n++) await new Promise(resolve => setTimeout(resolve, 20)); assert.ok(predicate(), output); };
|
|
80
128
|
let peer: Peer | undefined;
|
|
81
129
|
try {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import { mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join, resolve } from 'node:path';
|
|
7
|
+
|
|
8
|
+
test('installs each native Skill, uses the source build outside the project, and preserves existing files', () => {
|
|
9
|
+
const home = mkdtempSync(join(tmpdir(), 'diagnose-install-skill-'));
|
|
10
|
+
const cli = resolve('dist/cli.js');
|
|
11
|
+
const env = { ...process.env, HOME: home, USERPROFILE: home };
|
|
12
|
+
delete (env as NodeJS.ProcessEnv).DIAGNOSE_SKILL_CLI;
|
|
13
|
+
const install = (agent: string) => spawnSync(process.execPath, [cli, 'install-skill', agent], { cwd: home, env, encoding: 'utf8' });
|
|
14
|
+
try {
|
|
15
|
+
for (const [agent, directory] of [['claude', '.claude'], ['codex', '.agents'], ['gemini', '.gemini']]) {
|
|
16
|
+
const result = install(agent);
|
|
17
|
+
assert.equal(result.status, 0, result.stderr);
|
|
18
|
+
const skill = join(home, directory!, 'skills', 'diagnose');
|
|
19
|
+
const nativeSkill = readFileSync('skills/connect/SKILL.md', 'utf8');
|
|
20
|
+
assert.match(nativeSkill, /^name: connect$/m);
|
|
21
|
+
assert.equal(readFileSync(join(skill, 'SKILL.md'), 'utf8'), nativeSkill.replace(/^name: connect$/m, 'name: diagnose'));
|
|
22
|
+
const helper = spawnSync(process.execPath, [join(skill, 'scripts/run.mjs'), 'open'], { cwd: home, env, input: '{}', encoding: 'utf8' });
|
|
23
|
+
assert.equal(helper.status, 1);
|
|
24
|
+
assert.match(helper.stderr, /Supply the one-time pairing code on stdin/);
|
|
25
|
+
const repeated = install(agent);
|
|
26
|
+
assert.equal(repeated.status, 0, repeated.stderr);
|
|
27
|
+
assert.match(repeated.stdout, /already installed/);
|
|
28
|
+
}
|
|
29
|
+
const custom = join(home, '.claude', 'skills', 'diagnose', 'SKILL.md');
|
|
30
|
+
writeFileSync(custom, 'my custom skill');
|
|
31
|
+
const conflict = install('claude');
|
|
32
|
+
assert.equal(conflict.status, 1);
|
|
33
|
+
assert.match(conflict.stderr, /A different Skill already exists/);
|
|
34
|
+
assert.equal(readFileSync(custom, 'utf8'), 'my custom skill');
|
|
35
|
+
assert.equal(install('unknown-agent').status, 1);
|
|
36
|
+
} finally { rmSync(home, { recursive: true, force: true }); }
|
|
37
|
+
});
|