@masstensor/diagnose 0.8.0 → 0.8.2
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/README.md +23 -22
- package/USER_GUIDE.md +40 -714
- package/dist/agent.js +8 -8
- package/dist/discover.js +1 -1
- package/dist/mcp.js +16 -3
- package/dist/peer.d.ts +1 -0
- package/dist/peer.js +11 -1
- package/dist/skill-session.js +18 -3
- package/dist/skill.d.ts +8 -1
- package/dist/skill.js +48 -2
- package/docs/guide/automation.md +184 -0
- package/docs/guide/diagnose.md +88 -0
- package/docs/guide/examples.md +69 -0
- package/docs/guide/on-site.md +139 -0
- package/docs/guide/procedures.md +185 -0
- package/docs/guide/reconnect.md +58 -0
- package/docs/guide/troubleshooting.md +77 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/skills/connect/SKILL.md +8 -2
- package/skills/connect/scripts/run.mjs +1 -1
- package/src/agent.ts +8 -7
- package/src/discover.ts +1 -1
- package/src/mcp.ts +16 -4
- package/src/peer.ts +10 -1
- package/src/skill-session.ts +15 -3
- package/src/skill.ts +47 -2
- package/test/agent.test.ts +22 -2
- package/test/skill-session.test.ts +26 -7
- package/test/skill.test.ts +12 -1
|
@@ -26,7 +26,7 @@ function configuredCli() {
|
|
|
26
26
|
const cli = process.env.DIAGNOSE_SKILL_CLI || configuredCli();
|
|
27
27
|
const args = cli
|
|
28
28
|
? [cli, 'skill-session', action]
|
|
29
|
-
: ['--yes', '@masstensor/diagnose@0.8.
|
|
29
|
+
: ['--yes', '@masstensor/diagnose@0.8.2', 'skill-session', action];
|
|
30
30
|
const command = cli ? process.execPath : process.platform === 'win32' ? 'npx.cmd' : 'npx';
|
|
31
31
|
const result = spawnSync(command, args, {
|
|
32
32
|
stdio: 'inherit',
|
package/src/agent.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { join, resolve } from 'node:path';
|
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { parseArgs } from 'node:util';
|
|
8
8
|
import { PairingStore } from './pairing.js';
|
|
9
|
-
import { skillPrompt } from './skill.js';
|
|
9
|
+
import { caseInstructions, promptLanguage, skillPrompt } from './skill.js';
|
|
10
10
|
import { resolveSkill } from './skill-library.js';
|
|
11
11
|
import { Cases } from './cases.js';
|
|
12
12
|
import { agentCommand } from './agent-command.js';
|
|
@@ -25,9 +25,8 @@ export async function launchAgent(argv: string[]): Promise<number> {
|
|
|
25
25
|
if (selectedCase?.host && values.device && selectedCase.host !== values.device) throw new Error('Selected case belongs to a different paired computer');
|
|
26
26
|
if (selectedCase?.skill && values.skill && selectedCase.skill !== values.skill) throw new Error('Case skill revision differs from selected skill');
|
|
27
27
|
const skillInput = values.skill ?? selectedCase?.skill;
|
|
28
|
-
|
|
29
|
-
if (
|
|
30
|
-
if (skill && agent === 'gemini' && extra.some(arg => ['-p', '--prompt', '-i', '--prompt-interactive'].includes(arg) || arg.startsWith('--prompt=') || arg.startsWith('--prompt-interactive='))) throw new Error('--skill supplies the initial task; do not also pass a Gemini prompt option');
|
|
28
|
+
const skill = skillInput ? await resolveSkill(skillInput) : undefined;
|
|
29
|
+
if ((skill || selectedCase) && agent === 'gemini' && extra.some(arg => ['-p', '--prompt', '-i', '--prompt-interactive'].includes(arg) || arg.startsWith('--prompt=') || arg.startsWith('--prompt-interactive='))) throw new Error('--skill supplies the initial task; do not also pass a Gemini prompt option');
|
|
31
30
|
if (values.relay) {
|
|
32
31
|
const url = new URL(values.relay);
|
|
33
32
|
if (!['https:', 'wss:'].includes(url.protocol) && !(['http:', 'ws:'].includes(url.protocol) && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) throw new Error('Relay requires HTTPS/WSS, except loopback tests');
|
|
@@ -38,12 +37,14 @@ export async function launchAgent(argv: string[]): Promise<number> {
|
|
|
38
37
|
const env = { ...process.env }; let directory: string | undefined;
|
|
39
38
|
try {
|
|
40
39
|
let prompt: string | undefined, taskDirectory: string | undefined;
|
|
41
|
-
if (skill) {
|
|
40
|
+
if (skill || selectedCase) {
|
|
41
|
+
const language = await promptLanguage();
|
|
42
42
|
directory = await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
|
|
43
43
|
taskDirectory = join(directory, 'task'); await mkdir(taskDirectory, { mode: 0o700 });
|
|
44
44
|
const snapshot = join(taskDirectory, 'task.json');
|
|
45
|
-
|
|
46
|
-
|
|
45
|
+
const task = skill ?? { sourceFile: '', baseDirectory: process.cwd(), sha256: '', instructions: caseInstructions[language] };
|
|
46
|
+
await writeFile(snapshot, JSON.stringify(task), { mode: 0o600 });
|
|
47
|
+
prompt = skillPrompt(snapshot, language, values.device);
|
|
47
48
|
console.error('Starting the selected skill. Its instructions and referenced data may be sent to your chosen AI provider. Remote pairing and existing permissions still apply.');
|
|
48
49
|
}
|
|
49
50
|
let args: string[];
|
package/src/discover.ts
CHANGED
|
@@ -13,5 +13,5 @@ export async function inspectSystem(): Promise<Record<string, unknown>> {
|
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
15
|
const elevated = process.platform === 'win32' ? /S-1-16-(12288|16384)/.test(spawnSync('whoami', ['/groups'], { encoding: 'utf8', timeout: 3000, windowsHide: true }).stdout ?? '') : process.geteuid?.() === 0;
|
|
16
|
-
return { platform: process.platform, arch: process.arch, release: os.release(), node: process.version, hostname: os.hostname(), cwd: process.cwd(), home: os.homedir(), username: os.userInfo().username, elevated, shell: process.platform === 'win32' ? process.env.ComSpec ?? 'cmd.exe' : process.env.SHELL ?? '/bin/sh', commands, serialPorts: await SerialPort.list(), networkInterfaces: os.networkInterfaces(), protocol: 1, version: '0.8.
|
|
16
|
+
return { platform: process.platform, arch: process.arch, release: os.release(), node: process.version, hostname: os.hostname(), cwd: process.cwd(), home: os.homedir(), username: os.userInfo().username, elevated, shell: process.platform === 'win32' ? process.env.ComSpec ?? 'cmd.exe' : process.env.SHELL ?? '/bin/sh', commands, serialPorts: await SerialPort.list(), networkInterfaces: os.networkInterfaces(), protocol: 1, version: '0.8.2', capabilities: ['batch', 'script', 'process-stdin', 'pty', 'terminal-resize', 'signals', 'concurrent-jobs', 'encrypted-output-journal', 'resource-resume', 'binary-transfer', 'filesystem', 'local-forward', 'remote-forward', 'socks5'] };
|
|
17
17
|
}
|
package/src/mcp.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
2
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import { Peer } from './peer.js';
|
|
4
|
+
import { Peer, pairingProgress } from './peer.js';
|
|
5
5
|
import { Operator } from './operator.js';
|
|
6
6
|
import { atomicOperationNames, batchOperationNames, resourceRequestSchema } from './schema.js';
|
|
7
7
|
import type { TaskInput } from './schema.js';
|
|
@@ -13,7 +13,7 @@ import { safeText } from './util.js';
|
|
|
13
13
|
import { registerKnowledge } from './knowledge-mcp.js';
|
|
14
14
|
|
|
15
15
|
export async function serveMcp(relay: string, device?: string, caseId?: string): Promise<void> {
|
|
16
|
-
const server = new McpServer({ name: 'diagnose', version: '0.8.
|
|
16
|
+
const server = new McpServer({ name: 'diagnose', version: '0.8.2' });
|
|
17
17
|
let operator: Operator | undefined;
|
|
18
18
|
let remembered = device ? new RememberedConnection(new PairingStore().get(device, 'operator')) : undefined;
|
|
19
19
|
const transfers = new Map<string, { progress: TransferProgress; controller: AbortController }>(), forwards = new Map<string, Forward>();
|
|
@@ -23,10 +23,22 @@ export async function serveMcp(relay: string, device?: string, caseId?: string):
|
|
|
23
23
|
const observed = new WeakSet<Operator>();
|
|
24
24
|
const attach = (value: Operator) => { value.observe = knowledge.observe; if (!observed.has(value)) { observed.add(value); value.peer.once('closed', () => { connectionState = 'disconnected'; if (operator === value) operator = undefined; }); } connectionState = 'connected'; return value; };
|
|
25
25
|
const connected = async (): Promise<Operator> => { try { if (remembered) return attach(await remembered.connect()); if (!operator) throw new Error('Pair first, or launch with --device NAME'); return attach(operator); } catch (error) { connectionState = 'unavailable'; throw error; } };
|
|
26
|
-
server.registerTool('diagnose_pair', { description: 'Connect using the user-shared nine-letter invitation (abc-def-ghi; case, spaces and hyphens ignored). Legacy D1 codes are also accepted. The
|
|
26
|
+
server.registerTool('diagnose_pair', { description: 'Connect using the user-shared nine-letter invitation (abc-def-ghi; case, spaces and hyphens ignored). Legacy D1 codes are also accepted. The probe may ask for local confirmation. Label is self-asserted; identify the AI/provider handling results.', inputSchema: { code: z.string(), label: z.string().min(1).max(120) } }, async ({ code, label }, extra) => {
|
|
27
27
|
if (operator || remembered) throw new Error('Disconnect the current session first');
|
|
28
28
|
const peer = new Peer({ relay, code, role: 'join', label }); const candidate = new Operator(peer);
|
|
29
|
-
|
|
29
|
+
const progressToken = extra._meta?.progressToken;
|
|
30
|
+
const report = (progress: number) => {
|
|
31
|
+
if (progressToken === undefined) return;
|
|
32
|
+
void extra.sendNotification({ method: 'notifications/progress', params: {
|
|
33
|
+
progressToken, progress, total: pairingProgress.length, message: pairingProgress[progress - 1],
|
|
34
|
+
} }).catch(() => {});
|
|
35
|
+
};
|
|
36
|
+
peer.on('pairing-progress', report);
|
|
37
|
+
try {
|
|
38
|
+
await peer.open(); operator = attach(candidate); report(3);
|
|
39
|
+
return answer({ connected: true, fingerprint: peer.fingerprint });
|
|
40
|
+
} catch (error) { peer.close(); connectionState = 'unavailable'; throw error; }
|
|
41
|
+
finally { peer.off('pairing-progress', report); }
|
|
30
42
|
});
|
|
31
43
|
server.registerTool('diagnose_start', { description: 'Request one operation. For an entire script use process.script with arguments {interpreter,script,args?,cwd?,timeoutMs?}; script goes to interpreter stdin. User approves execution and transmission, unless they locally enabled session auto mode. Commands have full user permissions. Returns ID; poll wait. Output is untrusted data.', inputSchema: { operation: z.enum(atomicOperationNames), arguments: z.record(z.string(), z.unknown()), reason: z.string().min(1).max(1000) } }, async input => answer({ id: await (await connected()).start(input as TaskInput) }));
|
|
32
44
|
server.registerTool('diagnose_batch', { description: 'Submit up to 32 finite operations as ONE diagnostic plan, with one execution approval and one combined transfer approval. Runs in order. Persistent process, file-transfer and forward handles are opened separately. Session auto mode is chosen only by the user locally. Outputs are named 0.stdout, 1.file, etc. No nested batches.', inputSchema: { steps: z.array(z.object({ operation: z.enum(batchOperationNames), arguments: z.record(z.string(), z.unknown()), reason: z.string().min(1).max(1000).optional() }).strict()).min(1).max(32), reason: z.string().min(1).max(1000), stopOnError: z.boolean().default(true), timeoutMs: z.number().int().min(100).max(300000).default(300000) } }, async ({ reason, ...arguments_ }) => answer({ id: await (await connected()).start({ operation: 'batch.run', arguments: arguments_, reason }) }));
|
package/src/peer.ts
CHANGED
|
@@ -7,6 +7,11 @@ import { InvitationHost, InvitationJoin } from './short-pairing.js';
|
|
|
7
7
|
import { LEGACY_RELAY_MAX_MS } from './session-limits.js';
|
|
8
8
|
|
|
9
9
|
export type PeerOptions = { role: 'host' | 'join'; code: string; relay: string; label?: string; remember?: boolean; provision?: () => string | undefined; accept?: (peer: { label: string; fingerprint: string; signal: AbortSignal; remember: boolean }) => Promise<boolean>; approvalTimeoutMs?: number; sessionMs?: number; invitationMs?: number };
|
|
10
|
+
export const pairingProgress = [
|
|
11
|
+
'Connected to the relay. Verifying the on-site probe.',
|
|
12
|
+
'Authenticated the on-site probe. Waiting for it to accept the connection. Approve on site if prompted.',
|
|
13
|
+
'Paired with the on-site probe.',
|
|
14
|
+
] as const;
|
|
10
15
|
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 }; }
|
|
11
16
|
export function relayUrl(value: string): string {
|
|
12
17
|
const url = new URL(value);
|
|
@@ -57,7 +62,10 @@ export class Peer extends EventEmitter {
|
|
|
57
62
|
this.ws = new WebSocket(relayUrl(options.relay), { maxPayload: MAX_FRAME, perMessageDeflate: false, handshakeTimeout: 10000 });
|
|
58
63
|
this.connectionTimer = setTimeout(() => this.close('Relay registration timeout'), 12000);
|
|
59
64
|
if (short && options.role === 'host') this.invitationTimer = setTimeout(() => this.close('Invitation expired; generate a new code'), Math.min(options.invitationMs ?? INVITATION_MS, INVITATION_MS));
|
|
60
|
-
this.ws.on('open', () =>
|
|
65
|
+
this.ws.on('open', () => {
|
|
66
|
+
this.ws.send(JSON.stringify({ version: short ? 2 : 1, role: options.role, room }));
|
|
67
|
+
if (options.role === 'join') this.emit('pairing-progress', 1);
|
|
68
|
+
});
|
|
61
69
|
this.ws.on('error', () => this.close('Relay connection failed'));
|
|
62
70
|
this.ws.on('close', (_code, reason) => {
|
|
63
71
|
const message = reason.toString();
|
|
@@ -138,6 +146,7 @@ export class Peer extends EventEmitter {
|
|
|
138
146
|
})().catch(() => this.close('Pairing approval failed'));
|
|
139
147
|
} else {
|
|
140
148
|
this.cipher = this.handshake.split(); this.handshake = undefined; this.fingerprint = this.cipher.fingerprint;
|
|
149
|
+
this.emit('pairing-progress', 2);
|
|
141
150
|
}
|
|
142
151
|
return;
|
|
143
152
|
}
|
package/src/skill-session.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'node:ht
|
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
5
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
6
6
|
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
7
|
-
import { relayUrl } from './peer.js';
|
|
7
|
+
import { pairingProgress, relayUrl } from './peer.js';
|
|
8
8
|
import { DEFAULT_IDLE_MS } from './session-limits.js';
|
|
9
9
|
|
|
10
10
|
const cli = fileURLToPath(new URL('./cli.js', import.meta.url));
|
|
@@ -115,7 +115,12 @@ async function serve(relay: string): Promise<void> {
|
|
|
115
115
|
activity = true;
|
|
116
116
|
refreshIdle();
|
|
117
117
|
}
|
|
118
|
-
const result = await client.callTool({ name, arguments: args }, undefined, {
|
|
118
|
+
const result = await client.callTool({ name, arguments: args }, undefined, {
|
|
119
|
+
timeout: requestMs,
|
|
120
|
+
...(name === 'diagnose_pair' && { onprogress: ({ progress }) => {
|
|
121
|
+
if (progress < pairingProgress.length && process.connected) process.send?.({ progress }, () => {});
|
|
122
|
+
} }),
|
|
123
|
+
});
|
|
119
124
|
if (result.isError) {
|
|
120
125
|
const content = result.content;
|
|
121
126
|
const error = Array.isArray(content) ? content.find(item => item.type === 'text')?.text : undefined;
|
|
@@ -185,6 +190,7 @@ async function open(input: Json): Promise<Json> {
|
|
|
185
190
|
if (input.relay !== undefined && typeof input.relay !== 'string') throw new Error('Invalid relay URL');
|
|
186
191
|
const relay = input.relay ?? defaultRelay;
|
|
187
192
|
relayUrl(relay);
|
|
193
|
+
console.error('Connecting to the Diagnose relay.');
|
|
188
194
|
const worker = fork(cli, ['skill-session', '_serve', relay], { detached: true, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
|
|
189
195
|
try {
|
|
190
196
|
const session = await new Promise<Endpoint>((resolve, reject) => {
|
|
@@ -207,9 +213,15 @@ async function open(input: Json): Promise<Json> {
|
|
|
207
213
|
worker.once('exit', exited);
|
|
208
214
|
worker.once('message', ready);
|
|
209
215
|
});
|
|
216
|
+
worker.on('message', (message: { progress?: number }) => {
|
|
217
|
+
if (typeof message.progress !== 'number') return;
|
|
218
|
+
const text = pairingProgress[message.progress - 1];
|
|
219
|
+
if (text) console.error(text);
|
|
220
|
+
});
|
|
221
|
+
const result = await requestSession(session, 'pair', { code: input.code, label: input.label });
|
|
222
|
+
console.error(pairingProgress[2]);
|
|
210
223
|
worker.disconnect();
|
|
211
224
|
worker.unref();
|
|
212
|
-
const result = await requestSession(session, 'pair', { code: input.code, label: input.label });
|
|
213
225
|
return { ...result, session: session.port + '.' + session.secret, idleSeconds: DEFAULT_IDLE_MS / 1000 };
|
|
214
226
|
} catch (error) {
|
|
215
227
|
worker.kill();
|
package/src/skill.ts
CHANGED
|
@@ -2,9 +2,39 @@ import { open, realpath, stat } from 'node:fs/promises';
|
|
|
2
2
|
import { dirname, extname, join, resolve } from 'node:path';
|
|
3
3
|
import { isUtf8 } from 'node:buffer';
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
5
7
|
|
|
6
8
|
export type SessionSkill = { sourceFile: string; baseDirectory: string; sha256: string; instructions: string; libraryReference?: string };
|
|
7
9
|
const MAX_SKILL = 256 * 1024;
|
|
10
|
+
const readLocale = promisify(execFile);
|
|
11
|
+
type PromptLanguage = 'en' | 'zh';
|
|
12
|
+
|
|
13
|
+
export async function promptLanguage(env = process.env): Promise<PromptLanguage> {
|
|
14
|
+
let locale = [env.LC_ALL, env.LC_MESSAGES].map(value => value?.trim())
|
|
15
|
+
.find(value => value && !/^(?:C|POSIX)(?:[.@]|$)/i.test(value));
|
|
16
|
+
if (!locale) {
|
|
17
|
+
const options = { timeout: 3000, windowsHide: true };
|
|
18
|
+
try {
|
|
19
|
+
if (process.platform === 'darwin') {
|
|
20
|
+
const { stdout } = await readLocale('/usr/bin/defaults', ['read', '-g', 'AppleLanguages'], options);
|
|
21
|
+
locale = /^\s*\(\s*"?([\w-]+)/.exec(stdout)?.[1];
|
|
22
|
+
} else if (process.platform === 'win32') {
|
|
23
|
+
const executable = join(env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
24
|
+
const { stdout } = await readLocale(executable, ['-NoProfile', '-NonInteractive', '-Command', '(Get-UICulture).Name'], options);
|
|
25
|
+
locale = stdout.trim();
|
|
26
|
+
} else {
|
|
27
|
+
locale = env.LANGUAGE?.split(':')[0]?.trim() || env.LANG?.trim();
|
|
28
|
+
}
|
|
29
|
+
} catch { /* A missing or restricted OS locale reader falls back to the runtime locale. */ }
|
|
30
|
+
}
|
|
31
|
+
return /^zh(?:[-_.@]|$)/i.test(locale || Intl.DateTimeFormat().resolvedOptions().locale) ? 'zh' : 'en';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const caseInstructions = {
|
|
35
|
+
en: 'Use diagnose_case show to read the selected case. Confirm the external target identity, inspect interfaces conservatively, diagnose the stated goal, apply only authorized repairs, and record evidence-backed verification. Propose a reusable skill draft if useful.',
|
|
36
|
+
zh: '调用 diagnose_case show 读取所选案例。确认外接设备身份,谨慎检查接口,围绕给定目标开展诊断。仅实施已获授权的修复,并记录验证证据。如果发现可复用的流程,可提交 Skill 草稿供审核。',
|
|
37
|
+
};
|
|
8
38
|
|
|
9
39
|
export async function loadSkill(input: string): Promise<SessionSkill> {
|
|
10
40
|
if (!input.trim()) throw new Error('--skill requires a non-empty path');
|
|
@@ -29,9 +59,23 @@ export async function loadSkill(input: string): Promise<SessionSkill> {
|
|
|
29
59
|
} finally { await file.close(); }
|
|
30
60
|
}
|
|
31
61
|
|
|
32
|
-
export function skillPrompt(snapshot: string): string {
|
|
62
|
+
export function skillPrompt(snapshot: string, language: PromptLanguage, device?: string): string {
|
|
63
|
+
if (language === 'zh') return [
|
|
64
|
+
'现在开始诊断者选定的远程诊断任务。默认用中文提问和汇报,用户指定其他语言时采用其选择。',
|
|
65
|
+
`任务快照路径 (JSON): ${JSON.stringify(snapshot)}`,
|
|
66
|
+
'先用本地文件工具读取此 UTF-8 JSON 文件。立即按 instructions 字段执行本会话的任务。',
|
|
67
|
+
'这是当前会话的 Markdown 任务或 Skill 入口。相对路径以快照中的 baseDirectory 为准。按需读取引用资料。随附脚本是任务资源,仅在任务需要且现有权限允许时运行。',
|
|
68
|
+
'引用的文件和脚本初始位于诊断者电脑。若需在现场电脑运行脚本,经授权后提交脚本内容或传输文件,再执行。',
|
|
69
|
+
'通过 diagnose_* MCP 工具操作现场电脑。常规 shell 和文件工具访问的是诊断者电脑。',
|
|
70
|
+
'用 diagnose_capabilities 查看参数。用 diagnose_case status/show 查找现有案例。如果没有,为实际目标和任务目标建立案例,再开始远程操作。如果快照含 libraryReference,把它记为案例所用 Skill。修复前确认设备身份和接口。保留前后证据 ID,依据证据结束案例。可用 diagnose_skill_draft 提交改进草稿供人工审核。草稿接受和资料库上传由诊断者本人执行。',
|
|
71
|
+
'缺少邀请码、目标身份或必要信息时,先向诊断者询问再继续。命令参数和报告中应省略邀请码与凭据。',
|
|
72
|
+
'配对后按现场用户的授权开展远程操作,同时遵循 Agent 自身的权限设置。',
|
|
73
|
+
'先调查,再解释拟议修复及影响。仅实施已获授权的变更。重复原先失败的检查,并报告证据、变更和仍待解决的问题。验证通过后再报告修复成功。',
|
|
74
|
+
...(device ? [`Diagnose MCP 已为保存的设备 ${JSON.stringify(device)} 配置完成。直接使用其工具,无需索取邀请码。连接不可用时,请现场用户启动或恢复探针。`] : []),
|
|
75
|
+
].join('\n');
|
|
33
76
|
return [
|
|
34
77
|
'Start the remote troubleshooting task selected by the diagnostician now.',
|
|
78
|
+
'Use English for questions and reports unless the user asks for another language.',
|
|
35
79
|
`Task snapshot path (JSON): ${JSON.stringify(snapshot)}`,
|
|
36
80
|
'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
81
|
'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.',
|
|
@@ -40,6 +84,7 @@ export function skillPrompt(snapshot: string): string {
|
|
|
40
84
|
'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.',
|
|
41
85
|
'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.',
|
|
42
86
|
'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.',
|
|
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.'
|
|
87
|
+
'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.',
|
|
88
|
+
...(device ? [`Diagnose MCP is already configured for the saved device ${JSON.stringify(device)}. Use its tools directly; do not ask for a pairing code. If unavailable, ask the user to start or resume their probe.`] : []),
|
|
44
89
|
].join('\n');
|
|
45
90
|
}
|
package/test/agent.test.ts
CHANGED
|
@@ -23,7 +23,7 @@ const fs=require('node:fs'), args=process.argv.slice(2), agent=require('node:pat
|
|
|
23
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('='))};}
|
|
24
24
|
else if(agent==='claude')server=JSON.parse(args[args.indexOf('--mcp-config')+1]).mcpServers.diagnose;
|
|
25
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);
|
|
26
|
+
let task,taskPath,taskMode;const initial=agent==='gemini'?args[args.indexOf('--prompt-interactive')+1]:args.at(-1);const marker=initial?.split('\\n').find(x=>x.startsWith('Task snapshot path (JSON): ')||x.startsWith('任务快照路径 (JSON): '));if(marker){taskPath=JSON.parse(marker.slice(marker.indexOf(': ')+2));task=JSON.parse(fs.readFileSync(taskPath,'utf8'));taskMode=fs.statSync(taskPath).mode&511;}
|
|
27
27
|
const {Client}=await import(${JSON.stringify(client)}),{StdioClientTransport}=await import(${JSON.stringify(transport)});
|
|
28
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
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',{});}
|
|
@@ -64,7 +64,7 @@ test('agent forwards termination and cleans the Gemini overlay', { skip: process
|
|
|
64
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
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
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 });
|
|
67
|
+
const result = await run(['agent', agent, '--device', 'alice-pc', '--skill', source, '--', '--model', 'selected-model'], { ...process.env, LC_ALL: 'en_US.UTF-8', HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture });
|
|
68
68
|
assert.equal(result.code, 0, result.output); const captured = JSON.parse(readFileSync(f.capture, 'utf8'));
|
|
69
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
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'));
|
|
@@ -77,6 +77,26 @@ for (const agent of ['codex', 'claude', 'gemini']) test(`agent ${agent} loads th
|
|
|
77
77
|
if (agent === 'gemini') assert.equal(captured.args.at(-2), '--prompt-interactive'); else assert.equal(captured.args.at(-2), '--');
|
|
78
78
|
});
|
|
79
79
|
|
|
80
|
+
test('Codex receives a Chinese startup prompt while its Markdown task is preserved', { skip: process.platform === 'win32', timeout: 15000 }, async () => {
|
|
81
|
+
const f = fixture();
|
|
82
|
+
const source = join(f.root, 'device.md'), body = '# Device task\nCheck the attached port. 保留本文。\n';
|
|
83
|
+
writeFileSync(source, body);
|
|
84
|
+
const env = { ...process.env, LC_ALL: 'zh_CN.UTF-8', HOME: f.root, PATH: f.root + ':' + process.env.PATH, TEST_CAPTURE: f.capture };
|
|
85
|
+
const result = await run(['agent', 'codex', '--skill', source], env);
|
|
86
|
+
assert.equal(result.code, 0, result.output);
|
|
87
|
+
const captured = JSON.parse(readFileSync(f.capture, 'utf8'));
|
|
88
|
+
assert.match(captured.args.at(-1), /默认用中文提问和汇报/);
|
|
89
|
+
assert.match(captured.args.at(-1), /通过 diagnose_\* MCP 工具操作现场电脑/);
|
|
90
|
+
assert.equal(captured.task.instructions, body);
|
|
91
|
+
assert.ok(!captured.args.at(-1).includes(body));
|
|
92
|
+
|
|
93
|
+
const { Cases } = await import('../dist/cases.js');
|
|
94
|
+
const selected = new Cases(join(f.root, '.diagnose', 'cases')).create({ goal: 'Check device logs', target: { name: 'Gateway', interface: 'serial' } });
|
|
95
|
+
const caseResult = await run(['agent', 'codex', '--case', selected.id], env);
|
|
96
|
+
assert.equal(caseResult.code, 0, caseResult.output);
|
|
97
|
+
assert.match(JSON.parse(readFileSync(f.capture, 'utf8')).task.instructions, /读取所选案例/);
|
|
98
|
+
});
|
|
99
|
+
|
|
80
100
|
test('skill directory is accepted, and invalid skills fail before launching an agent', { skip: process.platform === 'win32', timeout: 15000 }, async () => {
|
|
81
101
|
const f = fixture(), skill = join(f.root, 'device-skill'); mkdirSync(skill); writeFileSync(join(skill, 'SKILL.md'), '# Device skill\nInspect first.');
|
|
82
102
|
const env = { ...process.env, HOME: f.root, PATH: f.root + ':' + process.env.PATH, GEMINI_CLI_HOME: f.root, TEST_CAPTURE: f.capture };
|
|
@@ -11,12 +11,12 @@ import { Peer } from '../dist/peer.js';
|
|
|
11
11
|
import { ProbeEngine } from '../dist/engine.js';
|
|
12
12
|
import { Audit } from '../dist/util.js';
|
|
13
13
|
|
|
14
|
-
function helper(action: string, input: Record<string, unknown
|
|
14
|
+
function helper(action: string, input: Record<string, unknown>, onProgress?: (stderr: string) => void): Promise<Record<string, any>> {
|
|
15
15
|
const script = process.env.DIAGNOSE_TEST_SKILL ?? resolve('skills/connect/scripts/run.mjs');
|
|
16
16
|
const child = spawn(process.execPath, [script, action], { stdio: 'pipe' });
|
|
17
17
|
let out = '', err = '';
|
|
18
18
|
child.stdout.setEncoding('utf8').on('data', text => { out += text; });
|
|
19
|
-
child.stderr.setEncoding('utf8').on('data', text => { err += text; });
|
|
19
|
+
child.stderr.setEncoding('utf8').on('data', text => { err += text; onProgress?.(err); });
|
|
20
20
|
child.stdin.end(JSON.stringify(input));
|
|
21
21
|
return new Promise((resolve, reject) => {
|
|
22
22
|
child.on('error', reject);
|
|
@@ -28,7 +28,7 @@ function helper(action: string, input: Record<string, unknown>): Promise<Record<
|
|
|
28
28
|
});
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
test('native Skill helper pairs once, reuses the connection for a repair and closes it', { timeout:
|
|
31
|
+
test('native Skill helper pairs once, runs a shell command, reuses the connection for a repair and closes it', { timeout: 60000 }, async () => {
|
|
32
32
|
const scratch = await mkdtemp(join(tmpdir(), 'diagnose-skill-'));
|
|
33
33
|
const config = join(scratch, 'config.txt');
|
|
34
34
|
await writeFile(config, 'offline\n');
|
|
@@ -36,13 +36,21 @@ test('native Skill helper pairs once, reuses the connection for a repair and clo
|
|
|
36
36
|
const url = 'ws://127.0.0.1:' + await relay.listen();
|
|
37
37
|
const code = createInvitation();
|
|
38
38
|
let pairs = 0;
|
|
39
|
+
let approve!: (value: boolean) => void;
|
|
40
|
+
const approval = new Promise<boolean>(resolve => { approve = resolve; });
|
|
39
41
|
const approvals: Array<string> = [];
|
|
40
|
-
const host = new Peer({ role: 'host', code, relay: url, accept: async () => { pairs++; return
|
|
42
|
+
const host = new Peer({ role: 'host', code, relay: url, approvalTimeoutMs: 5000, accept: async () => { pairs++; return approval; } });
|
|
41
43
|
new ProbeEngine(host, async request => { approvals.push(request.stage); return true; }, new Audit(join(scratch, 'audit')));
|
|
42
44
|
let session: string | undefined;
|
|
43
45
|
try {
|
|
44
46
|
await host.open();
|
|
45
|
-
|
|
47
|
+
let progress = '';
|
|
48
|
+
const opened = await helper('open', { code, label: 'Skill test', relay: url }, stderr => {
|
|
49
|
+
progress = stderr;
|
|
50
|
+
if (stderr.includes('Waiting for it to accept the connection')) approve(true);
|
|
51
|
+
});
|
|
52
|
+
assert.match(progress, /Connecting to the Diagnose relay\.[\s\S]+Connected to the relay\.[\s\S]+Authenticated the on-site probe\.[\s\S]+Paired with the on-site probe\./);
|
|
53
|
+
assert.ok(!progress.includes(code));
|
|
46
54
|
assert.equal(opened.connected, true);
|
|
47
55
|
assert.equal(opened.idleSeconds, 6 * 60 * 60);
|
|
48
56
|
session = opened.session;
|
|
@@ -50,7 +58,12 @@ test('native Skill helper pairs once, reuses the connection for a repair and clo
|
|
|
50
58
|
const call = (tool: string, args: object) => helper('call', { session, tool, arguments: args });
|
|
51
59
|
const run = async (operation: string, args: object) => {
|
|
52
60
|
const { id } = await call('diagnose_start', { operation, arguments: args, reason: 'Test an isolated demo configuration' });
|
|
53
|
-
|
|
61
|
+
const deadline = Date.now() + 25000;
|
|
62
|
+
do {
|
|
63
|
+
const outcome = await call('diagnose_wait', { id, timeoutMs: 5000 });
|
|
64
|
+
if (!outcome.pending) return outcome;
|
|
65
|
+
} while (Date.now() < deadline);
|
|
66
|
+
assert.fail(`${operation} did not return a final result`);
|
|
54
67
|
};
|
|
55
68
|
const forged = session.replace(/.$/, session.endsWith('0') ? '1' : '0');
|
|
56
69
|
await assert.rejects(helper('close', { session: forged }), /Invalid skill session/);
|
|
@@ -58,13 +71,19 @@ test('native Skill helper pairs once, reuses the connection for a repair and clo
|
|
|
58
71
|
const inspection = await run('system.inspect', {});
|
|
59
72
|
assert.equal(inspection.result.data.platform, process.platform);
|
|
60
73
|
assert.ok(Array.isArray(inspection.result.data.serialPorts));
|
|
74
|
+
const command = process.platform === 'win32'
|
|
75
|
+
? { executable: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-Command', '40 + 2'] }
|
|
76
|
+
: { executable: '/bin/sh', args: ['-c', 'printf "%s" "$((40 + 2))"'] };
|
|
77
|
+
const executed = await run('process.run', { ...command, cwd: scratch, timeoutMs: 15000 });
|
|
78
|
+
assert.equal(executed.result.status, 'ok', JSON.stringify(executed.result));
|
|
79
|
+
assert.equal(executed.outputs.stdout.trim(), '42');
|
|
61
80
|
assert.equal((await run('file.read', { path: config })).outputs.file, 'offline\n');
|
|
62
81
|
const expectedSha256 = createHash('sha256').update('offline\n').digest('hex');
|
|
63
82
|
assert.equal((await run('file.write', { path: config, content: 'online\n', expectedSha256 })).result.status, 'ok');
|
|
64
83
|
assert.equal((await run('file.read', { path: config })).outputs.file, 'online\n');
|
|
65
84
|
assert.equal(await readFile(config, 'utf8'), 'online\n');
|
|
66
85
|
assert.equal(pairs, 1);
|
|
67
|
-
assert.deepEqual(approvals, ['execute', 'send', 'execute', 'send', 'execute', 'send', 'execute', 'send']);
|
|
86
|
+
assert.deepEqual(approvals, ['execute', 'send', 'execute', 'send', 'execute', 'send', 'execute', 'send', 'execute', 'send']);
|
|
68
87
|
const handle = session;
|
|
69
88
|
assert.equal((await helper('close', { session })).disconnected, true);
|
|
70
89
|
session = undefined;
|
package/test/skill.test.ts
CHANGED
|
@@ -4,7 +4,18 @@ import { mkdtemp, mkdir, writeFile, realpath } from 'node:fs/promises';
|
|
|
4
4
|
import { tmpdir } from 'node:os';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
import { createHash } from 'node:crypto';
|
|
7
|
-
import { loadSkill } from '../dist/skill.js';
|
|
7
|
+
import { loadSkill, promptLanguage, skillPrompt } from '../dist/skill.js';
|
|
8
|
+
|
|
9
|
+
test('startup prompts follow the local message locale and fall back to English', async () => {
|
|
10
|
+
assert.equal(await promptLanguage({ LC_ALL: 'zh_CN.UTF-8', LC_MESSAGES: 'en_US.UTF-8' }), 'zh');
|
|
11
|
+
assert.equal(await promptLanguage({ LC_ALL: 'C.UTF-8', LC_MESSAGES: 'zh-Hant-TW' }), 'zh');
|
|
12
|
+
assert.equal(await promptLanguage({ LC_ALL: 'fr_FR.UTF-8' }), 'en');
|
|
13
|
+
const path = 'local path with spaces.json';
|
|
14
|
+
assert.match(skillPrompt(path, 'en'), /Use English for questions and reports/);
|
|
15
|
+
const chinese = skillPrompt(path, 'zh', 'workshop-laptop');
|
|
16
|
+
assert.ok(chinese.includes(JSON.stringify(path)));
|
|
17
|
+
assert.match(chinese, /workshop-laptop.+无需索取邀请码/);
|
|
18
|
+
});
|
|
8
19
|
|
|
9
20
|
test('skill loader accepts UTF-8 Markdown and preserves exact instructions and source base', async () => {
|
|
10
21
|
const root = await realpath(await mkdtemp(join(tmpdir(), 'diagnose skill '))), file = join(root, process.platform === 'win32' ? 'device with spaces.md' : 'device "quoted".md'), source = '\uFEFF# Device\nCheck port 11500. Literal $(do-not-execute).\n';
|