@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,226 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, mkdtemp, open, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { loadSkill } from './skill.js';
|
|
7
|
+
const MAX_BYTES = 8 * 1024 * 1024;
|
|
8
|
+
const MAX_FILES = 128;
|
|
9
|
+
const namePattern = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
10
|
+
const revisionPattern = /^[a-f0-9]{64}$/;
|
|
11
|
+
export const skillsUsage = 'diagnose skills import NAME FILE.md|DIRECTORY\ndiagnose skills list\nLaunch: diagnose agent codex|claude|gemini --skill library:NAME@REVISION';
|
|
12
|
+
// Portable names only: reject separators, traversal, Windows aliases and device names.
|
|
13
|
+
function validPart(part) {
|
|
14
|
+
return /^[a-zA-Z0-9_.-]+$/.test(part) && !['.', '..'].includes(part) && !/[. ]$/.test(part) && !/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part);
|
|
15
|
+
}
|
|
16
|
+
async function readBundle(input) {
|
|
17
|
+
const source = resolve(input), info = await lstat(source);
|
|
18
|
+
if (info.isSymbolicLink())
|
|
19
|
+
throw new Error('Skill bundles cannot contain symbolic links');
|
|
20
|
+
const entries = [];
|
|
21
|
+
let total = 0, visited = 0;
|
|
22
|
+
const add = async (file, path) => {
|
|
23
|
+
if (entries.length >= MAX_FILES)
|
|
24
|
+
throw new Error('Skill bundle exceeds 128 files');
|
|
25
|
+
const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
26
|
+
try {
|
|
27
|
+
const metadata = await handle.stat();
|
|
28
|
+
if (!metadata.isFile())
|
|
29
|
+
throw new Error('Skill bundles require regular files');
|
|
30
|
+
if (metadata.size > MAX_BYTES - total)
|
|
31
|
+
throw new Error('Skill bundle exceeds 8 MiB');
|
|
32
|
+
const buffer = Buffer.alloc(MAX_BYTES - total + 1);
|
|
33
|
+
let size = 0;
|
|
34
|
+
while (size < buffer.length) {
|
|
35
|
+
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, size);
|
|
36
|
+
if (!bytesRead)
|
|
37
|
+
break;
|
|
38
|
+
size += bytesRead;
|
|
39
|
+
}
|
|
40
|
+
total += size;
|
|
41
|
+
if (total > MAX_BYTES)
|
|
42
|
+
throw new Error('Skill bundle exceeds 8 MiB');
|
|
43
|
+
entries.push({ path, bytes: Buffer.from(buffer.subarray(0, size)), executable: !!(metadata.mode & 0o111) });
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
await handle.close();
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const walk = async (directory, prefix, depth) => {
|
|
50
|
+
if (depth > 16)
|
|
51
|
+
throw new Error('Skill directory nesting exceeds 16 levels');
|
|
52
|
+
const names = await readdir(directory);
|
|
53
|
+
const portable = new Set();
|
|
54
|
+
for (const name of names.sort()) {
|
|
55
|
+
if (++visited > 256)
|
|
56
|
+
throw new Error('Skill bundle exceeds 256 directory entries');
|
|
57
|
+
if (!validPart(name) || portable.has(name.toLowerCase()))
|
|
58
|
+
throw new Error('Skill bundle contains a non-portable or duplicate path');
|
|
59
|
+
portable.add(name.toLowerCase());
|
|
60
|
+
const file = join(directory, name), path = prefix + name, item = await lstat(file);
|
|
61
|
+
if (item.isSymbolicLink())
|
|
62
|
+
throw new Error('Skill bundles cannot contain symbolic links');
|
|
63
|
+
if (item.isDirectory())
|
|
64
|
+
await walk(file, path + '/', depth + 1);
|
|
65
|
+
else if (item.isFile())
|
|
66
|
+
await add(file, path);
|
|
67
|
+
else
|
|
68
|
+
throw new Error('Skill bundles require regular files');
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
if (info.isDirectory())
|
|
72
|
+
await walk(source, '', 0);
|
|
73
|
+
else {
|
|
74
|
+
await loadSkill(source);
|
|
75
|
+
await add(source, 'SKILL.md');
|
|
76
|
+
}
|
|
77
|
+
if (!entries.some(entry => entry.path === 'SKILL.md'))
|
|
78
|
+
throw new Error('Skill directory requires SKILL.md');
|
|
79
|
+
await loadSkill(info.isDirectory() ? join(source, 'SKILL.md') : source);
|
|
80
|
+
return entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
81
|
+
}
|
|
82
|
+
function digest(entries) {
|
|
83
|
+
// Length-delimited canonical JSON avoids ambiguous path/content concatenation.
|
|
84
|
+
return createHash('sha256').update(JSON.stringify(entries.map(entry => [entry.path, entry.bytes.toString('base64')]))).digest('hex');
|
|
85
|
+
}
|
|
86
|
+
export class SkillLibrary {
|
|
87
|
+
root;
|
|
88
|
+
constructor(root = join(homedir(), '.diagnose', 'skills')) {
|
|
89
|
+
this.root = root;
|
|
90
|
+
}
|
|
91
|
+
async bundle(reference) {
|
|
92
|
+
const skill = await this.load(reference);
|
|
93
|
+
return { reference, files: (await readBundle(skill.baseDirectory)).map(entry => ({ path: entry.path, data: entry.bytes.toString('base64') })) };
|
|
94
|
+
}
|
|
95
|
+
async exportTo(reference, directory) {
|
|
96
|
+
const bundle = await this.bundle(reference);
|
|
97
|
+
await this.writeBundle(bundle.files, directory);
|
|
98
|
+
}
|
|
99
|
+
async writeBundle(files, directory) {
|
|
100
|
+
if (!Array.isArray(files) || files.length > MAX_FILES)
|
|
101
|
+
throw new Error('Invalid skill bundle');
|
|
102
|
+
let total = 0;
|
|
103
|
+
for (const entry of files) {
|
|
104
|
+
if (typeof entry.path !== 'string' || entry.path.length > 2048 || !entry.path.split('/').every(validPart) || typeof entry.data !== 'string')
|
|
105
|
+
throw new Error('Invalid bundle path or content');
|
|
106
|
+
const bytes = Buffer.from(entry.data, 'base64');
|
|
107
|
+
total += bytes.length;
|
|
108
|
+
if (total > MAX_BYTES || bytes.toString('base64') !== entry.data)
|
|
109
|
+
throw new Error('Invalid or oversized bundle content');
|
|
110
|
+
const parts = entry.path.split('/'), name = parts.pop();
|
|
111
|
+
const parent = join(directory, ...parts);
|
|
112
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
113
|
+
await writeFile(join(parent, name), bytes, { flag: 'wx', mode: 0o600 });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async restore(bundle) {
|
|
117
|
+
const match = /^library:([a-z0-9][a-z0-9-]{0,63})@([a-f0-9]{64})$/.exec(bundle.reference);
|
|
118
|
+
if (!match)
|
|
119
|
+
throw new Error('Invalid bundle reference');
|
|
120
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
121
|
+
const directory = await mkdtemp(join(this.root, '.restore-'));
|
|
122
|
+
try {
|
|
123
|
+
await this.writeBundle(bundle.files, directory);
|
|
124
|
+
if (digest(await readBundle(directory)) !== match[2])
|
|
125
|
+
throw new Error('Downloaded bundle failed integrity verification');
|
|
126
|
+
return await this.import(match[1], directory);
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
await rm(directory, { recursive: true, force: true });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async import(name, input) {
|
|
133
|
+
if (!namePattern.test(name) || !validPart(name))
|
|
134
|
+
throw new Error('Skill name must be a portable name of 1..64 lowercase letters, digits or hyphens, starting with a letter or digit');
|
|
135
|
+
const entries = await readBundle(input), revision = digest(entries), parent = join(this.root, name);
|
|
136
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
137
|
+
const reference = `library:${name}@${revision}`, destination = join(parent, revision);
|
|
138
|
+
try {
|
|
139
|
+
await lstat(destination);
|
|
140
|
+
await this.load(reference);
|
|
141
|
+
return reference;
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (error.code !== 'ENOENT')
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
const temporary = await mkdtemp(join(parent, '.import-'));
|
|
148
|
+
try {
|
|
149
|
+
for (const entry of entries) {
|
|
150
|
+
const parts = entry.path.split('/');
|
|
151
|
+
const filename = parts.pop();
|
|
152
|
+
const directory = join(temporary, ...parts);
|
|
153
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
154
|
+
await writeFile(join(directory, filename), entry.bytes, { flag: 'wx', mode: entry.executable ? 0o700 : 0o600 });
|
|
155
|
+
}
|
|
156
|
+
if (digest(await readBundle(temporary)) !== revision)
|
|
157
|
+
throw new Error('Skill changed during import');
|
|
158
|
+
try {
|
|
159
|
+
await rename(temporary, destination);
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
// Windows reports EPERM when another import already published this
|
|
163
|
+
// nonempty directory. Accept only a fully verified existing revision,
|
|
164
|
+
// never an error code alone (which could also mean real permission loss).
|
|
165
|
+
try {
|
|
166
|
+
await this.load(reference);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
throw error;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
await this.load(reference);
|
|
173
|
+
return reference;
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
await rm(temporary, { recursive: true, force: true });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async load(reference) {
|
|
180
|
+
const match = /^library:([^@]+)@([^@]+)$/.exec(reference);
|
|
181
|
+
if (!match || !namePattern.test(match[1]) || !validPart(match[1]) || !revisionPattern.test(match[2]))
|
|
182
|
+
throw new Error('Use library:NAME@FULL_SHA256_REVISION from diagnose skills list');
|
|
183
|
+
const directory = join(this.root, match[1], match[2]);
|
|
184
|
+
if (digest(await readBundle(directory)) !== match[2])
|
|
185
|
+
throw new Error('Stored skill failed integrity verification; import a clean copy');
|
|
186
|
+
return { ...await loadSkill(directory), libraryReference: reference };
|
|
187
|
+
}
|
|
188
|
+
async list() {
|
|
189
|
+
let names;
|
|
190
|
+
try {
|
|
191
|
+
names = await readdir(this.root);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
if (error.code === 'ENOENT')
|
|
195
|
+
return [];
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
const references = [];
|
|
199
|
+
for (const name of names.sort()) {
|
|
200
|
+
if (!namePattern.test(name) || !(await lstat(join(this.root, name))).isDirectory())
|
|
201
|
+
continue;
|
|
202
|
+
for (const revision of (await readdir(join(this.root, name))).sort()) {
|
|
203
|
+
if (revisionPattern.test(revision))
|
|
204
|
+
references.push(`library:${name}@${revision}`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return references;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
export async function resolveSkill(input) {
|
|
211
|
+
return input.startsWith('library:') ? new SkillLibrary().load(input) : loadSkill(input);
|
|
212
|
+
}
|
|
213
|
+
export async function skillsCommand(args) {
|
|
214
|
+
const library = new SkillLibrary();
|
|
215
|
+
if (args[0] === 'import' && args.length === 3) {
|
|
216
|
+
console.log(await library.import(args[1], args[2]));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (args[0] === 'list' && args.length === 1) {
|
|
220
|
+
console.log(JSON.stringify(await library.list(), null, 2));
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (args.length && !['--help', 'help'].includes(args[0]))
|
|
224
|
+
throw new Error(skillsUsage);
|
|
225
|
+
console.log(skillsUsage);
|
|
226
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function skillSessionCommand(args: string[]): Promise<void>;
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { fork } from 'node:child_process';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { createServer } 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
|
+
const cli = fileURLToPath(new URL('./cli.js', import.meta.url));
|
|
10
|
+
const loopback = '127.0.0.1';
|
|
11
|
+
const defaultRelay = 'https://diagnose.fenginwind.com';
|
|
12
|
+
const requestMs = 135_000;
|
|
13
|
+
const diagnosticOperations = new Set([
|
|
14
|
+
'system.inspect', 'file.read', 'file.stat', 'file.list', 'file.write',
|
|
15
|
+
'process.run', 'serial.capture', 'serial.exchange',
|
|
16
|
+
]);
|
|
17
|
+
const tools = new Set(['diagnose_start', 'diagnose_batch', 'diagnose_wait', 'diagnose_cancel']);
|
|
18
|
+
function record(value) {
|
|
19
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
20
|
+
throw new Error('Expected a JSON object');
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
async function readJson(stream) {
|
|
24
|
+
const chunks = [];
|
|
25
|
+
let length = 0;
|
|
26
|
+
for await (const part of stream) {
|
|
27
|
+
const bytes = Buffer.from(part);
|
|
28
|
+
length += bytes.length;
|
|
29
|
+
if (length > 2 * 1024 * 1024)
|
|
30
|
+
throw new Error('JSON request is too large');
|
|
31
|
+
chunks.push(bytes);
|
|
32
|
+
}
|
|
33
|
+
let parsed;
|
|
34
|
+
try {
|
|
35
|
+
parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
throw new Error('Invalid JSON on stdin or in session request');
|
|
39
|
+
}
|
|
40
|
+
return record(parsed);
|
|
41
|
+
}
|
|
42
|
+
function respond(response, status, body) {
|
|
43
|
+
response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
44
|
+
response.end(JSON.stringify(body));
|
|
45
|
+
}
|
|
46
|
+
function validateCall(name, args) {
|
|
47
|
+
if (typeof name !== 'string' || !tools.has(name))
|
|
48
|
+
throw new Error('Unsupported tool for a skill session');
|
|
49
|
+
if (name === 'diagnose_start' && !diagnosticOperations.has(String(args.operation)))
|
|
50
|
+
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
|
+
async function serve(relay) {
|
|
56
|
+
if (!process.send || !process.connected)
|
|
57
|
+
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;
|
|
62
|
+
let stopped = false;
|
|
63
|
+
let closing = false;
|
|
64
|
+
let connected = false;
|
|
65
|
+
let busy = false;
|
|
66
|
+
const stop = () => {
|
|
67
|
+
if (stopped)
|
|
68
|
+
return;
|
|
69
|
+
stopped = true;
|
|
70
|
+
clearTimeout(idle);
|
|
71
|
+
server.close();
|
|
72
|
+
server.closeAllConnections();
|
|
73
|
+
void client.close().catch(() => { });
|
|
74
|
+
if (process.connected)
|
|
75
|
+
process.disconnect?.();
|
|
76
|
+
};
|
|
77
|
+
const refreshIdle = (ms = DEFAULT_IDLE_MS) => {
|
|
78
|
+
clearTimeout(idle);
|
|
79
|
+
idle = setTimeout(stop, ms);
|
|
80
|
+
};
|
|
81
|
+
const handle = async (request, response) => {
|
|
82
|
+
if (request.headers.authorization !== 'Bearer ' + secret) {
|
|
83
|
+
respond(response, 403, { error: 'Invalid skill session' });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (request.method !== 'POST' || !['/pair', '/call', '/close'].includes(request.url ?? '')) {
|
|
87
|
+
respond(response, 404, { error: 'Unknown skill session action' });
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (closing) {
|
|
91
|
+
respond(response, 409, { error: 'Skill session is closing' });
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (request.url === '/close') {
|
|
95
|
+
closing = true;
|
|
96
|
+
if (connected)
|
|
97
|
+
await client.callTool({ name: 'diagnose_disconnect', arguments: {} }, undefined, { timeout: 3000 }).catch(() => { });
|
|
98
|
+
response.once('finish', stop);
|
|
99
|
+
respond(response, 200, { disconnected: true });
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (busy) {
|
|
103
|
+
respond(response, 409, { error: 'Another call is in progress for this session' });
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
busy = true;
|
|
107
|
+
let activity = false;
|
|
108
|
+
try {
|
|
109
|
+
const input = await readJson(request);
|
|
110
|
+
let name;
|
|
111
|
+
let args;
|
|
112
|
+
if (request.url === '/pair') {
|
|
113
|
+
if (connected)
|
|
114
|
+
throw new Error('Skill session is already paired');
|
|
115
|
+
args = { code: input.code, label: input.label };
|
|
116
|
+
name = 'diagnose_pair';
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
if (!connected)
|
|
120
|
+
throw new Error('Skill session is not paired');
|
|
121
|
+
args = record(input.arguments);
|
|
122
|
+
validateCall(input.tool, args);
|
|
123
|
+
name = input.tool;
|
|
124
|
+
activity = true;
|
|
125
|
+
refreshIdle();
|
|
126
|
+
}
|
|
127
|
+
const result = await client.callTool({ name, arguments: args }, undefined, { timeout: requestMs });
|
|
128
|
+
if (result.isError) {
|
|
129
|
+
const content = result.content;
|
|
130
|
+
const error = Array.isArray(content) ? content.find(item => item.type === 'text')?.text : undefined;
|
|
131
|
+
respond(response, 400, { error: typeof error === 'string' ? error : 'Diagnose rejected the request' });
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
if (name === 'diagnose_pair') {
|
|
135
|
+
connected = true;
|
|
136
|
+
refreshIdle();
|
|
137
|
+
}
|
|
138
|
+
respond(response, 200, result.structuredContent ?? result.content);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
respond(response, 400, { error: error.message });
|
|
143
|
+
}
|
|
144
|
+
finally {
|
|
145
|
+
busy = false;
|
|
146
|
+
if (activity && !stopped)
|
|
147
|
+
refreshIdle();
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const server = createServer((request, response) => { void handle(request, response); });
|
|
151
|
+
server.maxConnections = 8;
|
|
152
|
+
server.requestTimeout = requestMs;
|
|
153
|
+
process.once('SIGINT', stop);
|
|
154
|
+
process.once('SIGTERM', stop);
|
|
155
|
+
client.onclose = stop;
|
|
156
|
+
try {
|
|
157
|
+
await client.connect(transport, { timeout: 15_000 });
|
|
158
|
+
await new Promise((resolve, reject) => {
|
|
159
|
+
server.once('error', reject);
|
|
160
|
+
server.listen(0, loopback, resolve);
|
|
161
|
+
});
|
|
162
|
+
const port = server.address().port;
|
|
163
|
+
refreshIdle(requestMs + 25_000);
|
|
164
|
+
process.send({ port, secret });
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
stop();
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function endpoint(value) {
|
|
172
|
+
if (typeof value !== 'string' || !/^\d{1,5}\.[a-f0-9]{64}$/.test(value))
|
|
173
|
+
throw new Error('Invalid skill session handle');
|
|
174
|
+
const [port, secret] = value.split('.');
|
|
175
|
+
if (Number(port) < 1 || Number(port) > 65535)
|
|
176
|
+
throw new Error('Invalid skill session handle');
|
|
177
|
+
return { port: Number(port), secret: secret };
|
|
178
|
+
}
|
|
179
|
+
async function requestSession(session, action, body = {}) {
|
|
180
|
+
let response;
|
|
181
|
+
try {
|
|
182
|
+
response = await fetch(`http://${loopback}:${session.port}/${action}`, {
|
|
183
|
+
method: 'POST',
|
|
184
|
+
headers: { authorization: 'Bearer ' + session.secret, 'content-type': 'application/json' },
|
|
185
|
+
body: JSON.stringify(body),
|
|
186
|
+
signal: AbortSignal.timeout(requestMs + 5000),
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
throw new Error('Skill session unavailable or timed out. Inspect the result before retrying a change.');
|
|
191
|
+
}
|
|
192
|
+
const result = record(await response.json());
|
|
193
|
+
if (!response.ok)
|
|
194
|
+
throw new Error(String(result.error ?? 'Skill session request failed'));
|
|
195
|
+
return result;
|
|
196
|
+
}
|
|
197
|
+
async function open(input) {
|
|
198
|
+
if (typeof input.code !== 'string' || input.code.length > 120 || !input.code.trim())
|
|
199
|
+
throw new Error('Supply the one-time pairing code on stdin');
|
|
200
|
+
if (typeof input.label !== 'string' || !input.label.trim() || input.label.length > 120)
|
|
201
|
+
throw new Error('Supply a diagnostic label on stdin');
|
|
202
|
+
if (input.relay !== undefined && typeof input.relay !== 'string')
|
|
203
|
+
throw new Error('Invalid relay URL');
|
|
204
|
+
const relay = input.relay ?? defaultRelay;
|
|
205
|
+
relayUrl(relay);
|
|
206
|
+
const worker = fork(cli, ['skill-session', '_serve', relay], { detached: true, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
|
|
207
|
+
try {
|
|
208
|
+
const session = await new Promise((resolve, reject) => {
|
|
209
|
+
const done = (error, result) => {
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
worker.off('error', failed);
|
|
212
|
+
worker.off('exit', exited);
|
|
213
|
+
worker.off('message', ready);
|
|
214
|
+
if (error)
|
|
215
|
+
reject(error);
|
|
216
|
+
else
|
|
217
|
+
resolve(result);
|
|
218
|
+
};
|
|
219
|
+
const failed = (error) => done(error);
|
|
220
|
+
const exited = () => done(new Error('Skill session worker exited during startup'));
|
|
221
|
+
const ready = (message) => {
|
|
222
|
+
try {
|
|
223
|
+
done(undefined, endpoint(`${message.port}.${message.secret}`));
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
done(error);
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
const timer = setTimeout(() => done(new Error('Skill session worker did not start')), 20_000);
|
|
230
|
+
worker.once('error', failed);
|
|
231
|
+
worker.once('exit', exited);
|
|
232
|
+
worker.once('message', ready);
|
|
233
|
+
});
|
|
234
|
+
worker.disconnect();
|
|
235
|
+
worker.unref();
|
|
236
|
+
const result = await requestSession(session, 'pair', { code: input.code, label: input.label });
|
|
237
|
+
return { ...result, session: session.port + '.' + session.secret, idleSeconds: DEFAULT_IDLE_MS / 1000 };
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
worker.kill();
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
export async function skillSessionCommand(args) {
|
|
245
|
+
if (args[0] === '_serve' && args.length === 2) {
|
|
246
|
+
await serve(args[1]);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
const [action] = args;
|
|
250
|
+
if (args.length !== 1 || !['open', 'call', 'close'].includes(action ?? '')) {
|
|
251
|
+
throw new Error('Usage: diagnose skill-session open|call|close (JSON on stdin)');
|
|
252
|
+
}
|
|
253
|
+
const input = await readJson(process.stdin);
|
|
254
|
+
const result = action === 'open' ? await open(input)
|
|
255
|
+
: await requestSession(endpoint(input.session), action, action === 'call' ? { tool: input.tool, arguments: input.arguments } : {});
|
|
256
|
+
console.log(JSON.stringify(result));
|
|
257
|
+
}
|
package/dist/skill.d.ts
CHANGED
package/dist/skill.js
CHANGED
|
@@ -51,6 +51,7 @@ export function skillPrompt(snapshot) {
|
|
|
51
51
|
'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.',
|
|
52
52
|
'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.',
|
|
53
53
|
'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.',
|
|
54
|
+
'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.',
|
|
54
55
|
'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.',
|
|
55
56
|
'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.',
|
|
56
57
|
'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/dist/util.js
CHANGED
|
@@ -10,6 +10,7 @@ export function safeText(text) {
|
|
|
10
10
|
export function redact(text) {
|
|
11
11
|
return safeText(text)
|
|
12
12
|
.replace(/("?(?:password|passwd|pswd|secret|token|session|authorization|api[_-]?key)"?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,}\r\n]+)/gi, '$1[REDACTED]')
|
|
13
|
+
.replace(/\b[a-z]{3}-[a-z]{3}-[a-z]{3}\b/gi, '[INVITATION CODE]')
|
|
13
14
|
.replace(/\bD1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}\b/g, '[PAIRING CODE]')
|
|
14
15
|
.replace(/\b[a-f0-9]{32,}\b/gi, '[REDACTED]')
|
|
15
16
|
.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, '[PRIVATE KEY]');
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const MAX_VAULT_OBJECT: number;
|
|
2
|
+
export declare function newRecovery(): string;
|
|
3
|
+
export declare function vaultKeys(recovery: string): {
|
|
4
|
+
auth: string;
|
|
5
|
+
namespace: string;
|
|
6
|
+
encryption: Buffer<ArrayBuffer>;
|
|
7
|
+
index: Buffer<ArrayBuffer>;
|
|
8
|
+
};
|
|
9
|
+
export declare function objectId(recovery: string, reference: string): string;
|
|
10
|
+
export declare function sealBundle(recovery: string, id: string, bytes: Buffer): Buffer;
|
|
11
|
+
export declare function openBundle(recovery: string, id: string, sealed: Buffer): Buffer;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createHash, createHmac, hkdfSync, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
|
|
2
|
+
export const MAX_VAULT_OBJECT = 12 * 1024 * 1024;
|
|
3
|
+
export function newRecovery() { return 'K1.' + randomBytes(32).toString('base64url'); }
|
|
4
|
+
export function vaultKeys(recovery) {
|
|
5
|
+
if (!/^K1\.[A-Za-z0-9_-]{43}$/.test(recovery))
|
|
6
|
+
throw new Error('Invalid library recovery key');
|
|
7
|
+
const root = Buffer.from(recovery.slice(3), 'base64url');
|
|
8
|
+
if (root.toString('base64url') !== recovery.slice(3))
|
|
9
|
+
throw new Error('Noncanonical recovery key');
|
|
10
|
+
const derive = (purpose) => Buffer.from(hkdfSync('sha256', root, 'diagnose-library-v1', purpose, 32));
|
|
11
|
+
const auth = derive('authentication').toString('base64url');
|
|
12
|
+
return { auth, namespace: createHash('sha256').update(auth).digest('hex'), encryption: derive('encryption'), index: derive('object-names') };
|
|
13
|
+
}
|
|
14
|
+
export function objectId(recovery, reference) { return createHmac('sha256', vaultKeys(recovery).index).update(reference).digest('hex'); }
|
|
15
|
+
export function sealBundle(recovery, id, bytes) {
|
|
16
|
+
const keys = vaultKeys(recovery), nonce = randomBytes(12), cipher = createCipheriv('aes-256-gcm', keys.encryption, nonce);
|
|
17
|
+
cipher.setAAD(Buffer.from(`diagnose-library-v1:${keys.namespace}:${id}`));
|
|
18
|
+
const sealed = Buffer.concat([Buffer.from([1]), nonce, cipher.update(bytes), cipher.final(), cipher.getAuthTag()]);
|
|
19
|
+
if (sealed.length > MAX_VAULT_OBJECT)
|
|
20
|
+
throw new Error('Encrypted bundle exceeds 12 MiB');
|
|
21
|
+
return sealed;
|
|
22
|
+
}
|
|
23
|
+
export function openBundle(recovery, id, sealed) {
|
|
24
|
+
if (sealed.length < 29 || sealed.length > MAX_VAULT_OBJECT || sealed[0] !== 1)
|
|
25
|
+
throw new Error('Invalid encrypted library object');
|
|
26
|
+
const keys = vaultKeys(recovery), decipher = createDecipheriv('aes-256-gcm', keys.encryption, sealed.subarray(1, 13));
|
|
27
|
+
decipher.setAAD(Buffer.from(`diagnose-library-v1:${keys.namespace}:${id}`));
|
|
28
|
+
decipher.setAuthTag(sealed.subarray(-16));
|
|
29
|
+
return Buffer.concat([decipher.update(sealed.subarray(13, -16)), decipher.final()]);
|
|
30
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
export declare class VaultServer {
|
|
3
|
+
readonly root: string;
|
|
4
|
+
readonly maxTotalBytes: number;
|
|
5
|
+
private activeUploads;
|
|
6
|
+
private requests;
|
|
7
|
+
constructor(root: string, maxTotalBytes?: number);
|
|
8
|
+
private inventory;
|
|
9
|
+
handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
|
|
10
|
+
}
|