@masstensor/diagnose 0.8.1 → 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 +17 -16
- package/USER_GUIDE.md +13 -2
- package/dist/agent.js +8 -8
- package/dist/discover.js +1 -1
- package/dist/mcp.js +1 -1
- package/dist/skill.d.ts +8 -1
- package/dist/skill.js +48 -2
- package/docs/guide/automation.md +1 -1
- package/docs/guide/diagnose.md +6 -11
- package/docs/guide/examples.md +69 -0
- package/docs/guide/on-site.md +1 -1
- package/docs/guide/procedures.md +2 -0
- package/docs/guide/troubleshooting.md +2 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/skills/connect/scripts/run.mjs +1 -1
- package/src/agent.ts +8 -7
- package/src/discover.ts +1 -1
- package/src/mcp.ts +1 -1
- package/src/skill.ts +47 -2
- package/test/agent.test.ts +22 -2
- package/test/skill-session.test.ts +9 -4
- package/test/skill.test.ts +12 -1
package/README.md
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
|
|
5
5
|
Diagnose is an open-source tool for agent-led remote troubleshooting and problem resolution. It gives Codex, Claude Code, Gemini CLI, or another MCP client the remote tools to investigate gateways, controllers and other devices reachable from an on-site computer, apply authorized fixes, and verify the result. A user-controlled probe and an end-to-end encrypted relay provide the connection.
|
|
6
6
|
|
|
7
|
-
[
|
|
7
|
+
[Quick start](USER_GUIDE.md#quick-start) · [Diagnostic walkthroughs](docs/guide/examples.md) · [npm](https://www.npmjs.com/package/@masstensor/diagnose) · [Website](https://diagnose.fenginwind.com)
|
|
8
8
|
|
|
9
9
|
Requires **Node.js 20.10+**. MIT licensed. TypeScript source is included in the npm package. macOS probes and the Linux relay have been tested. CI covers macOS/Linux and targeted Windows regressions; Windows interactive terminals and physical USB/serial behavior still need real-environment validation.
|
|
10
10
|
|
|
11
11
|
## Quick start
|
|
12
12
|
|
|
13
|
-
On the computer
|
|
13
|
+
On the on-site computer connected to the device:
|
|
14
14
|
|
|
15
15
|
```sh
|
|
16
16
|
npx @masstensor/diagnose@latest start
|
|
@@ -18,9 +18,9 @@ npx @masstensor/diagnose@latest start
|
|
|
18
18
|
|
|
19
19
|
In v0.8+, press Enter to review tasks and results, choose `a` to approve tasks and results automatically after confirming the connection, or choose `e` to preapprove all three for this one-time invitation. Keep the terminal open and privately share its nine-letter invitation, such as `abc-def-ghi`, with the diagnostician.
|
|
20
20
|
|
|
21
|
-
###
|
|
21
|
+
### Manual agent mode (recommended for a first session)
|
|
22
22
|
|
|
23
|
-
Install once from this GitHub repository. The native Skill uses Diagnose 0.8.
|
|
23
|
+
Install once from this GitHub repository. The native Skill uses Diagnose 0.8.2 and starts the local runtime on demand through Node.js and npm.
|
|
24
24
|
|
|
25
25
|
| Agent | Install | Use |
|
|
26
26
|
| --- | --- | --- |
|
|
@@ -28,31 +28,30 @@ Install once from this GitHub repository. The native Skill uses Diagnose 0.8.1 a
|
|
|
28
28
|
| Codex CLI | `codex plugin marketplace add zkwasm/diagnose`, then `codex plugin add diagnose@diagnose` | `$diagnose:connect` in a new session. |
|
|
29
29
|
| Gemini CLI | `gemini skills install https://github.com/zkwasm/diagnose.git --path skills/connect` | Ask Gemini to use the `connect` skill. |
|
|
30
30
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
On the diagnostician's computer, use the npm launcher when a script or job needs to start and configure an agent:
|
|
31
|
+
Open your agent, give it the private invitation and the device symptom, then guide the next checks in chat. You can also start an interactive session with Diagnose MCP already configured:
|
|
34
32
|
|
|
35
33
|
```sh
|
|
36
34
|
npx @masstensor/diagnose@latest agent codex
|
|
37
35
|
# Or: agent claude / agent gemini
|
|
38
36
|
```
|
|
39
37
|
|
|
40
|
-
The
|
|
38
|
+
The launcher loads Diagnose MCP for this session. Tell the agent what to check:
|
|
39
|
+
|
|
40
|
+
> Use Diagnose with invitation abc-def-ghi. The OWON gateway is connected to the on-site computer by USB serial. Plug readings have stopped. Confirm the interface and look for relevant logs. Explain the evidence before proposing a change. We can verify recovery when fresh readings reach the dashboard.
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
Diagnose 0.8.1 reports pairing progress. Check the [first device check](docs/guide/diagnose.md#run-a-diagnostic-session) for how to distinguish a connected probe, an identified interface, and an actual response from the device.
|
|
43
43
|
|
|
44
44
|
The user grants permission locally, either when the connection arrives or in advance with **Approve everything**. Automatic task approval includes both execution and result transmission. Possessing a pairing code does not establish the diagnostician's real identity.
|
|
45
45
|
|
|
46
|
-
|
|
46
|
+
### Start automatically with a device procedure
|
|
47
|
+
|
|
48
|
+
If you have a Markdown procedure, pass its path when launching the agent:
|
|
47
49
|
|
|
48
50
|
```sh
|
|
49
|
-
|
|
50
|
-
diagnose start
|
|
51
|
-
# On the diagnostician's machine:
|
|
52
|
-
diagnose agent codex
|
|
51
|
+
npx @masstensor/diagnose@latest agent codex --skill ./device.md
|
|
53
52
|
```
|
|
54
53
|
|
|
55
|
-
Short invitations require **0.7.0+ on both endpoints** and
|
|
54
|
+
Short invitations require **0.7.0+ on both endpoints** and a compatible relay. They last 30 minutes and are consumed by successful pairing. The site user authorizes pairing at the prompt or in advance by choosing **Approve everything**. Existing remembered pairings remain valid. See the [protocol design](PAIRING_PROTOCOL.md).
|
|
56
55
|
|
|
57
56
|
For a custom automation client, run `diagnose mcp` as a stdio subprocess. See the [native setup](docs/guide/diagnose.md#use-diagnose-as-a-native-agent-skill) and [automation setup](docs/guide/automation.md#direct-cli-and-other-mcp-clients) for the two entry points.
|
|
58
57
|
|
|
@@ -101,6 +100,8 @@ This is an agent-guided workflow using the existing tools and permission model.
|
|
|
101
100
|
|
|
102
101
|
## Remote tools
|
|
103
102
|
|
|
103
|
+
The [native skill](docs/guide/diagnose.md#what-the-native-skill-can-do) supports temporary pairing, progress updates, system inspection, serial diagnostics, bounded file operations, single shell commands, and batches. The full launcher and stdio MCP provide the wider tool set below, including whole scripts, live terminals, file transfers, and remembered connections.
|
|
104
|
+
|
|
104
105
|
| Capability | Interface |
|
|
105
106
|
| --- | --- |
|
|
106
107
|
| Inspect OS, runtime, commands, privileges, and serial ports | `system.inspect` |
|
|
@@ -140,7 +141,7 @@ npm pack
|
|
|
140
141
|
|
|
141
142
|
Tests exercise the actual encrypted protocol, approval boundaries, native terminals, transfers, forwarding, recovery, and the stdio MCP interface. The Noise tests include a public Cacophony interoperability vector. Hardware acceptance scripts and device logs are not distributed.
|
|
142
143
|
|
|
143
|
-
The `site/` directory contains the static landing page, a small TypeScript interaction module, and a build script that renders the guide. Run `npm run build:site` and `npm run check:site`; serve `.site-dist/` to preview. No analytics, third-party scripts, or cookies are required. The
|
|
144
|
+
The `site/` directory contains the static landing page, a small TypeScript interaction module, and a build script that renders the guide. Run `npm run build:site` and `npm run check:site`; serve `.site-dist/` to preview. No analytics, third-party scripts, or cookies are required. The 60-second English animation illustrates a USB gateway diagnosis using the native agent skill, local approval, and a fresh dashboard reading to verify recovery. Reproduce it with `npm run video:render`. [Video documentation](https://github.com/zkwasm/diagnose/blob/main/video/README.md)
|
|
144
145
|
|
|
145
146
|
## Relay deployment
|
|
146
147
|
|
package/USER_GUIDE.md
CHANGED
|
@@ -4,11 +4,22 @@ Diagnose lets a remote AI agent inspect and troubleshoot a device through a comp
|
|
|
4
4
|
|
|
5
5
|
## Choose your scenario
|
|
6
6
|
|
|
7
|
+
Pick the closest example. Each one shows what to prepare on site, what to ask the agent, and how to tell whether the problem is fixed.
|
|
8
|
+
|
|
9
|
+
| What you see | Walkthrough |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| The IoT gateway has power, but its USB serial logs are missing. | [Find out why a USB gateway is silent](docs/guide/examples.md#a-usb-gateway-is-silent) |
|
|
12
|
+
| A device on the local network appears offline in an app. | [Check whether the device or its app is offline](docs/guide/examples.md#a-network-device-appears-offline) |
|
|
13
|
+
| A machine is running, but new readings stopped reaching the factory dashboard. | [Trace missing readings through an industrial PC](docs/guide/examples.md#factory-readings-stopped-arriving) |
|
|
14
|
+
| An application on the on-site computer fails after a configuration change. | [Check a failed application startup](docs/guide/examples.md#an-application-wont-start) |
|
|
15
|
+
|
|
16
|
+
## Choose your setup or workflow
|
|
17
|
+
|
|
7
18
|
| If you want to… | Go to |
|
|
8
19
|
| --- | --- |
|
|
9
20
|
| Connect for the first time | [Quick start](#quick-start) |
|
|
10
21
|
| Get help with your device | [Receive remote help](docs/guide/on-site.md) |
|
|
11
|
-
|
|
|
22
|
+
| Set up Claude Code, Codex, or Gemini to diagnose a device | [Diagnose a remote device](docs/guide/diagnose.md) |
|
|
12
23
|
| Reconnect without exchanging a new invitation | [Return to a saved device](docs/guide/reconnect.md) |
|
|
13
24
|
| Load a device procedure or learn from a completed diagnosis | [Reuse and improve procedures](docs/guide/procedures.md) |
|
|
14
25
|
| Start Diagnose from a script or use your own MCP client | [Automation and tool reference](docs/guide/automation.md) |
|
|
@@ -83,7 +94,7 @@ The agent loads the procedure and starts working through it. If it needs an invi
|
|
|
83
94
|
|
|
84
95
|
Unless the on-site user chose **Approve everything**, they check the diagnostician's label and connection fingerprint before approving. The probe shows which permissions each choice grants. Auto approval covers both execution and result transmission. Commands run with the user's OS permissions, and results can reach the diagnostician and their AI provider.
|
|
85
96
|
|
|
86
|
-
The agent reports [pairing status and the first device check](docs/guide/diagnose.md#run-a-diagnostic-session) separately. Ask it to start with a read-only check, explain what it finds, and verify the original symptom after any authorized repair. See [what the skill can do](docs/guide/diagnose.md#what-the-native-skill-can-do) and [a
|
|
97
|
+
The agent reports [pairing status and the first device check](docs/guide/diagnose.md#run-a-diagnostic-session) separately. Ask it to start with a read-only check, explain what it finds, and verify the original symptom after any authorized repair. See [what the skill can do](docs/guide/diagnose.md#what-the-native-skill-can-do) and [choose a diagnostic walkthrough](docs/guide/examples.md).
|
|
87
98
|
|
|
88
99
|
The user can type `permissions ask` to revoke automatic approval or `exit` to stop access. See [how to review what was collected and sent](docs/guide/troubleshooting.md#review-local-history-and-clean-up).
|
|
89
100
|
|
package/dist/agent.js
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';
|
|
@@ -30,10 +30,8 @@ export async function launchAgent(argv) {
|
|
|
30
30
|
if (selectedCase?.skill && values.skill && selectedCase.skill !== values.skill)
|
|
31
31
|
throw new Error('Case skill revision differs from selected skill');
|
|
32
32
|
const skillInput = values.skill ?? selectedCase?.skill;
|
|
33
|
-
|
|
34
|
-
if (selectedCase &&
|
|
35
|
-
skill = { sourceFile: '', baseDirectory: process.cwd(), sha256: '', instructions: '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
|
-
if (skill && agent === 'gemini' && extra.some(arg => ['-p', '--prompt', '-i', '--prompt-interactive'].includes(arg) || arg.startsWith('--prompt=') || arg.startsWith('--prompt-interactive=')))
|
|
33
|
+
const skill = skillInput ? await resolveSkill(skillInput) : undefined;
|
|
34
|
+
if ((skill || selectedCase) && agent === 'gemini' && extra.some(arg => ['-p', '--prompt', '-i', '--prompt-interactive'].includes(arg) || arg.startsWith('--prompt=') || arg.startsWith('--prompt-interactive=')))
|
|
37
35
|
throw new Error('--skill supplies the initial task; do not also pass a Gemini prompt option');
|
|
38
36
|
if (values.relay) {
|
|
39
37
|
const url = new URL(values.relay);
|
|
@@ -48,13 +46,15 @@ export async function launchAgent(argv) {
|
|
|
48
46
|
let directory;
|
|
49
47
|
try {
|
|
50
48
|
let prompt, taskDirectory;
|
|
51
|
-
if (skill) {
|
|
49
|
+
if (skill || selectedCase) {
|
|
50
|
+
const language = await promptLanguage();
|
|
52
51
|
directory = await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
|
|
53
52
|
taskDirectory = join(directory, 'task');
|
|
54
53
|
await mkdir(taskDirectory, { mode: 0o700 });
|
|
55
54
|
const snapshot = join(taskDirectory, 'task.json');
|
|
56
|
-
|
|
57
|
-
|
|
55
|
+
const task = skill ?? { sourceFile: '', baseDirectory: process.cwd(), sha256: '', instructions: caseInstructions[language] };
|
|
56
|
+
await writeFile(snapshot, JSON.stringify(task), { mode: 0o600 });
|
|
57
|
+
prompt = skillPrompt(snapshot, language, values.device);
|
|
58
58
|
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.');
|
|
59
59
|
}
|
|
60
60
|
let args;
|
package/dist/discover.js
CHANGED
|
@@ -19,5 +19,5 @@ export async function inspectSystem() {
|
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
21
|
const elevated = process.platform === 'win32' ? /S-1-16-(12288|16384)/.test(spawnSync('whoami', ['/groups'], { encoding: 'utf8', timeout: 3000, windowsHide: true }).stdout ?? '') : process.geteuid?.() === 0;
|
|
22
|
-
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.
|
|
22
|
+
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'] };
|
|
23
23
|
}
|
package/dist/mcp.js
CHANGED
|
@@ -11,7 +11,7 @@ import { PairingStore, RememberedConnection } from './pairing.js';
|
|
|
11
11
|
import { safeText } from './util.js';
|
|
12
12
|
import { registerKnowledge } from './knowledge-mcp.js';
|
|
13
13
|
export async function serveMcp(relay, device, caseId) {
|
|
14
|
-
const server = new McpServer({ name: 'diagnose', version: '0.8.
|
|
14
|
+
const server = new McpServer({ name: 'diagnose', version: '0.8.2' });
|
|
15
15
|
let operator;
|
|
16
16
|
let remembered = device ? new RememberedConnection(new PairingStore().get(device, 'operator')) : undefined;
|
|
17
17
|
const transfers = new Map(), forwards = new Map();
|
package/dist/skill.d.ts
CHANGED
|
@@ -5,5 +5,12 @@ export type SessionSkill = {
|
|
|
5
5
|
instructions: string;
|
|
6
6
|
libraryReference?: string;
|
|
7
7
|
};
|
|
8
|
+
type PromptLanguage = 'en' | 'zh';
|
|
9
|
+
export declare function promptLanguage(env?: NodeJS.ProcessEnv): Promise<PromptLanguage>;
|
|
10
|
+
export declare const caseInstructions: {
|
|
11
|
+
en: string;
|
|
12
|
+
zh: string;
|
|
13
|
+
};
|
|
8
14
|
export declare function loadSkill(input: string): Promise<SessionSkill>;
|
|
9
|
-
export declare function skillPrompt(snapshot: string): string;
|
|
15
|
+
export declare function skillPrompt(snapshot: string, language: PromptLanguage, device?: string): string;
|
|
16
|
+
export {};
|
package/dist/skill.js
CHANGED
|
@@ -2,7 +2,37 @@ 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
|
const MAX_SKILL = 256 * 1024;
|
|
8
|
+
const readLocale = promisify(execFile);
|
|
9
|
+
export async function promptLanguage(env = process.env) {
|
|
10
|
+
let locale = [env.LC_ALL, env.LC_MESSAGES].map(value => value?.trim())
|
|
11
|
+
.find(value => value && !/^(?:C|POSIX)(?:[.@]|$)/i.test(value));
|
|
12
|
+
if (!locale) {
|
|
13
|
+
const options = { timeout: 3000, windowsHide: true };
|
|
14
|
+
try {
|
|
15
|
+
if (process.platform === 'darwin') {
|
|
16
|
+
const { stdout } = await readLocale('/usr/bin/defaults', ['read', '-g', 'AppleLanguages'], options);
|
|
17
|
+
locale = /^\s*\(\s*"?([\w-]+)/.exec(stdout)?.[1];
|
|
18
|
+
}
|
|
19
|
+
else if (process.platform === 'win32') {
|
|
20
|
+
const executable = join(env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
21
|
+
const { stdout } = await readLocale(executable, ['-NoProfile', '-NonInteractive', '-Command', '(Get-UICulture).Name'], options);
|
|
22
|
+
locale = stdout.trim();
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
locale = env.LANGUAGE?.split(':')[0]?.trim() || env.LANG?.trim();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
catch { /* A missing or restricted OS locale reader falls back to the runtime locale. */ }
|
|
29
|
+
}
|
|
30
|
+
return /^zh(?:[-_.@]|$)/i.test(locale || Intl.DateTimeFormat().resolvedOptions().locale) ? 'zh' : 'en';
|
|
31
|
+
}
|
|
32
|
+
export const caseInstructions = {
|
|
33
|
+
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.',
|
|
34
|
+
zh: '调用 diagnose_case show 读取所选案例。确认外接设备身份,谨慎检查接口,围绕给定目标开展诊断。仅实施已获授权的修复,并记录验证证据。如果发现可复用的流程,可提交 Skill 草稿供审核。',
|
|
35
|
+
};
|
|
6
36
|
export async function loadSkill(input) {
|
|
7
37
|
if (!input.trim())
|
|
8
38
|
throw new Error('--skill requires a non-empty path');
|
|
@@ -43,9 +73,24 @@ export async function loadSkill(input) {
|
|
|
43
73
|
await file.close();
|
|
44
74
|
}
|
|
45
75
|
}
|
|
46
|
-
export function skillPrompt(snapshot) {
|
|
76
|
+
export function skillPrompt(snapshot, language, device) {
|
|
77
|
+
if (language === 'zh')
|
|
78
|
+
return [
|
|
79
|
+
'现在开始诊断者选定的远程诊断任务。默认用中文提问和汇报,用户指定其他语言时采用其选择。',
|
|
80
|
+
`任务快照路径 (JSON): ${JSON.stringify(snapshot)}`,
|
|
81
|
+
'先用本地文件工具读取此 UTF-8 JSON 文件。立即按 instructions 字段执行本会话的任务。',
|
|
82
|
+
'这是当前会话的 Markdown 任务或 Skill 入口。相对路径以快照中的 baseDirectory 为准。按需读取引用资料。随附脚本是任务资源,仅在任务需要且现有权限允许时运行。',
|
|
83
|
+
'引用的文件和脚本初始位于诊断者电脑。若需在现场电脑运行脚本,经授权后提交脚本内容或传输文件,再执行。',
|
|
84
|
+
'通过 diagnose_* MCP 工具操作现场电脑。常规 shell 和文件工具访问的是诊断者电脑。',
|
|
85
|
+
'用 diagnose_capabilities 查看参数。用 diagnose_case status/show 查找现有案例。如果没有,为实际目标和任务目标建立案例,再开始远程操作。如果快照含 libraryReference,把它记为案例所用 Skill。修复前确认设备身份和接口。保留前后证据 ID,依据证据结束案例。可用 diagnose_skill_draft 提交改进草稿供人工审核。草稿接受和资料库上传由诊断者本人执行。',
|
|
86
|
+
'缺少邀请码、目标身份或必要信息时,先向诊断者询问再继续。命令参数和报告中应省略邀请码与凭据。',
|
|
87
|
+
'配对后按现场用户的授权开展远程操作,同时遵循 Agent 自身的权限设置。',
|
|
88
|
+
'先调查,再解释拟议修复及影响。仅实施已获授权的变更。重复原先失败的检查,并报告证据、变更和仍待解决的问题。验证通过后再报告修复成功。',
|
|
89
|
+
...(device ? [`Diagnose MCP 已为保存的设备 ${JSON.stringify(device)} 配置完成。直接使用其工具,无需索取邀请码。连接不可用时,请现场用户启动或恢复探针。`] : []),
|
|
90
|
+
].join('\n');
|
|
47
91
|
return [
|
|
48
92
|
'Start the remote troubleshooting task selected by the diagnostician now.',
|
|
93
|
+
'Use English for questions and reports unless the user asks for another language.',
|
|
49
94
|
`Task snapshot path (JSON): ${JSON.stringify(snapshot)}`,
|
|
50
95
|
'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.',
|
|
51
96
|
'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.',
|
|
@@ -54,6 +99,7 @@ export function skillPrompt(snapshot) {
|
|
|
54
99
|
'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.',
|
|
55
100
|
'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.',
|
|
56
101
|
'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.',
|
|
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.'
|
|
102
|
+
'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.',
|
|
103
|
+
...(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.`] : []),
|
|
58
104
|
].join('\n');
|
|
59
105
|
}
|
package/docs/guide/automation.md
CHANGED
|
@@ -155,7 +155,7 @@ SOCKS defaults to `allowedHosts:["*"]`, which permits any target. Narrow it when
|
|
|
155
155
|
| Active live resource handles | 128 |
|
|
156
156
|
| Live process | 1 hour by default; `timeoutMs:0` removes its timer |
|
|
157
157
|
| Retained output per live process | 64 MiB by default; 1 GiB maximum; reaching the cap terminates the process |
|
|
158
|
-
| Relay session |
|
|
158
|
+
| Relay session | Relays running 0.8+ renew active rooms. The hosted relay currently runs 0.7 and caps a room at seven days with a 0.8+ probe using default session settings. |
|
|
159
159
|
|
|
160
160
|
```sh
|
|
161
161
|
diagnose start --session-minutes 240 --idle-minutes 30
|
package/docs/guide/diagnose.md
CHANGED
|
@@ -11,7 +11,7 @@ Use this guide if a person on site has shared a nine-letter invitation. Choose t
|
|
|
11
11
|
|
|
12
12
|
## Use Diagnose as a native agent skill
|
|
13
13
|
|
|
14
|
-
Install the skill once through your agent's GitHub installation flow. All three agents use the same `skills/connect/` directory in the repository. The helper runs Diagnose 0.8.
|
|
14
|
+
Install the skill once through your agent's GitHub installation flow. All three agents use the same `skills/connect/` directory in the repository. The helper runs Diagnose 0.8.2 locally on demand with `npx` and needs Node.js 20.10 or later. There is no separate global Diagnose CLI installation for this workflow.
|
|
15
15
|
|
|
16
16
|
### Claude Code
|
|
17
17
|
|
|
@@ -62,7 +62,7 @@ The agent uses these operations on the **on-site computer** through the probe. T
|
|
|
62
62
|
|
|
63
63
|
| What you can ask the agent to do | Operation |
|
|
64
64
|
| --- | --- |
|
|
65
|
-
|
|
|
65
|
+
| Report the on-site OS, processor architecture, available shells and tools, and visible serial ports. | `system.inspect` |
|
|
66
66
|
| Find a known log or configuration file, inspect its metadata, and read the relevant contents. | `file.list`, `file.stat`, `file.read` |
|
|
67
67
|
| Capture output from a confirmed serial port at the device's baud rate. | `serial.capture` |
|
|
68
68
|
| Send a documented request to the device over serial and read its reply. | `serial.exchange` |
|
|
@@ -71,6 +71,8 @@ The agent uses these operations on the **on-site computer** through the probe. T
|
|
|
71
71
|
|
|
72
72
|
The agent submits one operation with `diagnose_start` or groups related operations with `diagnose_batch`. It uses `diagnose_wait` to get the result and `diagnose_cancel` to request cancellation of work in progress. Cancellation does not undo changes already made. You can describe the check in plain language. The agent selects the operation and waits for any approval the probe requires.
|
|
73
73
|
|
|
74
|
+
For a quick first check, ask “Use Diagnose to identify the on-site operating system, available shell, and visible serial ports.” `system.inspect` also collects the hostname, user paths, and network interfaces. In review mode, the on-site user reviews the collected report before sending it. A serial port listing gives the agent candidates to confirm with the person on site.
|
|
75
|
+
|
|
74
76
|
The native skill supports temporary pairing and finite operations. For live terminals, file transfers, remembered pairings, or case management, [launch the agent with Diagnose MCP](automation.md#launch-an-agent-with-diagnose-mcp). A [device procedure](procedures.md#start-with-a-device-skill-or-markdown-task) can tell the agent which checks and verification steps to use for a particular model.
|
|
75
77
|
|
|
76
78
|
### Run a shell command on the on-site computer
|
|
@@ -81,13 +83,6 @@ For shell syntax such as pipes and conditionals, the agent names the shell expli
|
|
|
81
83
|
|
|
82
84
|
## From a reported problem to a verified result
|
|
83
85
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
> The OWON gateway stopped reporting plug readings. Start with read-only checks. Confirm which serial port belongs to the gateway, look for recent readings or errors, and tell me what the evidence supports. Ask before changing anything. We’ll consider it fixed when fresh readings appear again.
|
|
87
|
-
|
|
88
|
-
1. **Identify the interface.** The agent can list serial ports with `system.inspect`. If several ports match, confirm the right one and the baud rate with the person on site before opening it.
|
|
89
|
-
2. **Collect a baseline and follow the evidence.** Use `serial.capture` for a short sample. If the sample is silent, check whether the port, baud rate, or cable is correct. If the gateway responds but readings are still absent, inspect the relevant collector logs with `file.read` if available. Reuse the same session to ask for another check.
|
|
90
|
-
3. **Review one proposed change.** If the evidence points to a setting, ask the agent to show the current value, explain the proposed edit, and describe how to restore the original value. The [probe's permissions](on-site.md#choose-and-change-permissions) govern execution and result sharing. You can end the diagnosis after the read-only findings.
|
|
91
|
-
4. **Repeat the original check.** After an authorized repair, use the same capture or status check to look for fresh readings. If they are still missing, use that result to choose the next check. Ask the agent to summarize the evidence, changes, and any remaining uncertainty.
|
|
86
|
+
Start with the actual symptom, where the device is connected, and what you need to see working. Have the agent collect read-only evidence and explain the next check. For a proposed change, ask what it will affect and how to restore the original setting. The [probe's permissions](on-site.md#choose-and-change-permissions) govern execution and result sharing. Repeat the original check after an authorized repair and ask the agent to summarize the result.
|
|
92
87
|
|
|
93
|
-
|
|
88
|
+
The [diagnostic walkthroughs](examples.md) show this conversation for a USB gateway, a network device, a factory data collector, and an application on the on-site computer. Each includes a prompt you can adapt and examples of how to follow the evidence.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# Diagnostic walkthroughs
|
|
2
|
+
|
|
3
|
+
Choose the example closest to what you see. These are illustrative sessions. The readings, logs, and outcomes in your session will depend on the actual device.
|
|
4
|
+
|
|
5
|
+
For any example, the **person on site** connects the device to a computer that can reach it, starts the probe, and shares the invitation privately. The **diagnostician** opens their agent, connects with the invitation, and starts with the suggested prompt. [Follow Quick start to get both sides connected](../../USER_GUIDE.md#quick-start).
|
|
6
|
+
|
|
7
|
+
## A USB gateway is silent
|
|
8
|
+
|
|
9
|
+
**What you see.** An OWON gateway powers on, but its readings stopped arriving. The manufacturer exposes diagnostic logs over a USB serial connection.
|
|
10
|
+
|
|
11
|
+
**Prepare on site.** Connect the gateway with a USB data cable. Share the model and which cable goes to the gateway. If you know the serial settings or which port belongs to the gateway, share those too. Agree on when it is safe to open the port, since opening a serial port can reset some devices.
|
|
12
|
+
|
|
13
|
+
**Ask the agent.**
|
|
14
|
+
|
|
15
|
+
> The OWON gateway stopped reporting plug readings. It is connected to the on-site Mac by USB. Identify the serial interface, then take a short passive log sample if the port and settings are confirmed. Tell me separately whether the probe is connected, which device interface you can identify, and whether the gateway produced recognizable output.
|
|
16
|
+
|
|
17
|
+
**Follow the evidence.** If the computer lists two USB serial ports, the person on site can identify the right cable or provide the port name before the agent opens either one. If the capture returns zero bytes, check the documented baud rate and when the gateway normally emits logs. Arrange a second sample during a normal reporting event. If the gateway logs show fresh readings but the dashboard stays stale, check the application that consumes those readings next.
|
|
18
|
+
|
|
19
|
+
> The gateway normally reports once a minute. Once we've confirmed the port settings, sample across one reporting interval and tell me whether you see a new reading.
|
|
20
|
+
|
|
21
|
+
**Verify recovery.** Observe a new reading and confirm that the same reading reaches the intended dashboard. Recognizable gateway output confirms the interface and gives you evidence for the next diagnostic step.
|
|
22
|
+
|
|
23
|
+
## A network device appears offline
|
|
24
|
+
|
|
25
|
+
**What you see.** A smart device appears offline in its app while the device still has power. The manufacturer documents a local status page or query.
|
|
26
|
+
|
|
27
|
+
**Prepare on site.** Put the on-site computer on a network that can reach the device. Share the known local address and the documented status page or approved vendor utility. If the tool needs a login, arrange for the on-site person to enter credentials locally.
|
|
28
|
+
|
|
29
|
+
**Ask the agent.**
|
|
30
|
+
|
|
31
|
+
> The app says the device is offline. From the on-site laptop, check the device's documented local status endpoint and tell me whether it responds with the expected device status. Only check the address I provided. If local status works, help me work out where the app path fails.
|
|
32
|
+
|
|
33
|
+
**Follow the evidence.** A normal status response confirms local access from that computer. Ask which app or service is supposed to receive the status, then inspect its configured address or relevant logs if available. If the documented service times out, ask the person on site to confirm the current address and network connection, then retry the same check.
|
|
34
|
+
|
|
35
|
+
**Verify recovery.** Repeat the local status check and reopen the app or refresh its device view. Confirm that it shows a current value for the correct device.
|
|
36
|
+
|
|
37
|
+
## Factory readings stopped arriving
|
|
38
|
+
|
|
39
|
+
**What you see.** The machine operator sees normal operation, but the dashboard has stopped showing new telemetry. A collector on an industrial PC reads from the controller and sends measurements to the dashboard.
|
|
40
|
+
|
|
41
|
+
**Prepare on site.** Put the probe on the industrial PC or an approved maintenance computer that can access the relevant collector diagnostics. Give the agent the name of the collector, the path to its logs if known, and the time of the last good reading. Agree with the operator on which read-only checks are allowed and how to verify a new measurement.
|
|
42
|
+
|
|
43
|
+
**Ask the agent.**
|
|
44
|
+
|
|
45
|
+
> The line is running, but the dashboard has shown the same reading since 10 a.m. Check the collector logs around that time and compare the last successful controller read with the last successful dashboard send. Keep the machine and controller in their current state. Tell me which link in the data path the evidence points to.
|
|
46
|
+
|
|
47
|
+
**Follow the evidence.** Recent controller reads plus repeated dashboard-send errors point to the collector-to-dashboard link. Check the collector's configured destination against the approved value. If they differ, ask the agent to show the current and proposed values and the steps to restore the original value. Schedule an authorized change to the collector with the operator. If controller reads have stopped instead, ask for the manufacturer's permitted status check and involve the on-site operator.
|
|
48
|
+
|
|
49
|
+
> The collector shows fresh controller readings and send failures. Compare the configured dashboard destination with the approved value and explain what would need to change.
|
|
50
|
+
|
|
51
|
+
**Verify recovery.** Confirm a new measurement in the collector and a matching timestamp or value in the dashboard. Record which component changed and which check confirmed recovery.
|
|
52
|
+
|
|
53
|
+
## An application won't start
|
|
54
|
+
|
|
55
|
+
**What you see.** An application on the on-site computer exits on startup after a settings change.
|
|
56
|
+
|
|
57
|
+
**Prepare on site.** Start the probe on that computer. Share the application name, the exact startup error if visible, and which settings changed. Identify whether someone is actively using the service before approving a restart.
|
|
58
|
+
|
|
59
|
+
**Ask the agent.**
|
|
60
|
+
|
|
61
|
+
> This application exits on startup after a configuration edit. Read only the relevant startup log and settings first. Show me which setting the evidence points to and how to restore its previous value. After I approve the change, repeat the same startup check.
|
|
62
|
+
|
|
63
|
+
**Follow the evidence.** If the log names an invalid setting, compare it with the last known good configuration or documented value. Review the targeted change before applying it. If the application still exits, collect the new startup error and update the diagnosis.
|
|
64
|
+
|
|
65
|
+
**Verify recovery.** Start it the same way the user normally does and perform one real operation, such as opening its status page or loading a sample record.
|
|
66
|
+
|
|
67
|
+
## Use the diagnosis again
|
|
68
|
+
|
|
69
|
+
If the same site needs follow-up, [save the pairing](reconnect.md#keep-a-device-paired-for-future-diagnosis). When you return, check which equipment is currently attached and repeat the same verification. If you want to repeat the workflow on another device of the same kind, [record the diagnosis and review a reusable procedure](procedures.md#record-a-device-diagnosis-and-improve-your-procedures).
|
package/docs/guide/on-site.md
CHANGED
|
@@ -132,7 +132,7 @@ Type these into the user's probe terminal:
|
|
|
132
132
|
| `cancel` | Cancel current work and retained resources without changing the permission mode. |
|
|
133
133
|
| `exit` or `Ctrl+C` | End the probe and close its resources. |
|
|
134
134
|
|
|
135
|
-
Only the user can enable automatic mode.
|
|
135
|
+
Only the user can enable automatic mode. For each new invitation, choose per-task review, `a` for automatic tasks and results with a pairing prompt, or `e` to preapprove the connection too. Already transmitted data cannot be recalled. Completed changes are not automatically rolled back.
|
|
136
136
|
|
|
137
137
|
Do not ask the AI to collect OS passwords. For interactive authentication, the user can use local hidden input with a trusted foreground program; Diagnose does not automatically elevate privileges. Hidden input has not been validated on Windows. On macOS/Linux, ordinary descendants in a managed process group are terminated when its leader exits or the resource is closed. This is not OS sandbox containment: a deliberately detached daemon can escape that group; Windows process-tree termination still requires real-device validation.
|
|
138
138
|
|
package/docs/guide/procedures.md
CHANGED
|
@@ -37,6 +37,8 @@ The launcher reads and validates the entry before starting the agent, saves a pr
|
|
|
37
37
|
|
|
38
38
|
The agent follows the entry, reads references as needed, and works toward diagnosis, authorized repair, and verification. If a pairing code, target identity, or necessary detail is missing, it asks before continuing. Do not store pairing codes, credentials, or other secrets in reusable task files; selected instructions and referenced material that the agent reads can enter the AI provider's context.
|
|
39
39
|
|
|
40
|
+
Starting with Diagnose 0.8.2, the launcher chooses Chinese or English for the startup prompt using the diagnostician computer's language settings. Other languages fall back to English. The Markdown procedure stays in its original language. You can ask the agent to use a different language in chat.
|
|
41
|
+
|
|
40
42
|
Relative references resolve against the original entry directory, not the temporary snapshot. Keep that directory available during the session. Only the entry is snapshotted; referenced files are read from the original directory. Scripts are not executed by the launcher merely because they exist. The agent runs them only as required by the task and existing permissions.
|
|
41
43
|
|
|
42
44
|
Referenced scripts initially live on the diagnostician computer. To use one remotely, the agent must explicitly submit its contents or transfer it to the user's computer with authorization. A path on one endpoint is not automatically a path on the other.
|
|
@@ -62,7 +62,7 @@ Both endpoints at 0.5.0+ use increasing task sequence numbers, so a connection c
|
|
|
62
62
|
|
|
63
63
|
### Saved output and recovery data
|
|
64
64
|
|
|
65
|
-
Raw live output and recovery metadata are stored under `~/.diagnose/resources` using AES-256-GCM records. The local key has mode `0600` in the same account's directory. This protects stored ciphertext from casual inspection, not an attacker who controls that OS account and can read the key.
|
|
65
|
+
Raw live output and recovery metadata are stored under `~/.diagnose/resources` using AES-256-GCM records. The local key has mode `0600` in the same account's directory. This protects stored ciphertext from casual inspection, not an attacker who controls that OS account and can read the key. Inactive saved output follows the resource journal retention limits above. Use `diagnose cleanup` to remove eligible records on demand.
|
|
66
66
|
|
|
67
67
|
Finite text results receive best-effort common-credential redaction and terminal-control filtering. Regexes cannot identify every secret. Live terminals, exact file transfers, and TCP channels retain raw data and are not redacted. Collection and transmission are audited separately.
|
|
68
68
|
|
|
@@ -74,4 +74,4 @@ Commands run with the current user's OS permissions. Diagnose neither provides a
|
|
|
74
74
|
|
|
75
75
|
The public relay is hosted at `diagnose.fenginwind.com`. You can self-host using the deployment templates in the repository. Keep local credentials, hardware logs, firmware, and resource journals out of server deployments and public packages.
|
|
76
76
|
|
|
77
|
-
The
|
|
77
|
+
The English walkthrough illustrates a USB gateway diagnosis, from sharing a nine-letter invitation to confirming that fresh readings reach the dashboard. It shows the native agent skill and includes narration and captions. [Watch the one-minute walkthrough](https://diagnose.fenginwind.com/#walkthrough)
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@masstensor/diagnose",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.2",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@masstensor/diagnose",
|
|
9
|
-
"version": "0.8.
|
|
9
|
+
"version": "0.8.2",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "MIT",
|
|
12
12
|
"dependencies": {
|
package/package.json
CHANGED
|
@@ -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
|
@@ -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>();
|
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 };
|
|
@@ -28,7 +28,7 @@ function helper(action: string, input: Record<string, unknown>, onProgress?: (st
|
|
|
28
28
|
});
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
test('native Skill helper pairs once, runs a shell command, 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');
|
|
@@ -58,7 +58,12 @@ test('native Skill helper pairs once, runs a shell command, reuses the connectio
|
|
|
58
58
|
const call = (tool: string, args: object) => helper('call', { session, tool, arguments: args });
|
|
59
59
|
const run = async (operation: string, args: object) => {
|
|
60
60
|
const { id } = await call('diagnose_start', { operation, arguments: args, reason: 'Test an isolated demo configuration' });
|
|
61
|
-
|
|
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`);
|
|
62
67
|
};
|
|
63
68
|
const forged = session.replace(/.$/, session.endsWith('0') ? '1' : '0');
|
|
64
69
|
await assert.rejects(helper('close', { session: forged }), /Invalid skill session/);
|
|
@@ -69,8 +74,8 @@ test('native Skill helper pairs once, runs a shell command, reuses the connectio
|
|
|
69
74
|
const command = process.platform === 'win32'
|
|
70
75
|
? { executable: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-Command', '40 + 2'] }
|
|
71
76
|
: { executable: '/bin/sh', args: ['-c', 'printf "%s" "$((40 + 2))"'] };
|
|
72
|
-
const executed = await run('process.run', { ...command, cwd: scratch, timeoutMs:
|
|
73
|
-
assert.equal(executed.result.status, 'ok');
|
|
77
|
+
const executed = await run('process.run', { ...command, cwd: scratch, timeoutMs: 15000 });
|
|
78
|
+
assert.equal(executed.result.status, 'ok', JSON.stringify(executed.result));
|
|
74
79
|
assert.equal(executed.outputs.stdout.trim(), '42');
|
|
75
80
|
assert.equal((await run('file.read', { path: config })).outputs.file, 'offline\n');
|
|
76
81
|
const expectedSha256 = createHash('sha256').update('offline\n').digest('hex');
|
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';
|