@masstensor/diagnose 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DEVELOPMENT_PLAN.md +69 -0
- package/KNOWLEDGE_SECURITY.md +47 -0
- package/PAIRING_PROTOCOL.md +37 -0
- package/README.md +12 -4
- package/USER_GUIDE.md +178 -31
- package/deploy/Caddyfile +1 -1
- package/deploy/ecosystem.config.cjs +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +15 -5
- package/dist/cases.d.ts +118 -0
- package/dist/cases.js +115 -0
- package/dist/cli.js +19 -8
- package/dist/crypto.d.ts +7 -0
- package/dist/crypto.js +16 -1
- package/dist/discover.js +1 -1
- package/dist/engine.d.ts +1 -0
- package/dist/engine.js +12 -5
- package/dist/knowledge-cli.d.ts +2 -0
- package/dist/knowledge-cli.js +164 -0
- package/dist/knowledge-drafts.d.ts +47 -0
- package/dist/knowledge-drafts.js +76 -0
- package/dist/knowledge-mcp.d.ts +5 -0
- package/dist/knowledge-mcp.js +65 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +27 -8
- package/dist/operator.d.ts +2 -0
- package/dist/operator.js +16 -3
- package/dist/peer.d.ts +9 -0
- package/dist/peer.js +78 -9
- package/dist/relay-main.js +1 -1
- package/dist/relay.d.ts +1 -0
- package/dist/relay.js +27 -4
- package/dist/short-pairing.d.ts +25 -0
- package/dist/short-pairing.js +73 -0
- package/dist/skill-library.d.ts +27 -0
- package/dist/skill-library.js +226 -0
- package/dist/skill.d.ts +1 -0
- package/dist/skill.js +1 -0
- package/dist/util.js +1 -0
- package/dist/vault-crypto.d.ts +11 -0
- package/dist/vault-crypto.js +30 -0
- package/dist/vault-server.d.ts +10 -0
- package/dist/vault-server.js +156 -0
- package/dist/vault.d.ts +19 -0
- package/dist/vault.js +72 -0
- package/npm-shrinkwrap.json +12 -2
- package/package.json +6 -2
- package/src/agent.ts +12 -5
- package/src/cases.ts +74 -0
- package/src/cli.ts +11 -7
- package/src/crypto.ts +14 -1
- package/src/discover.ts +1 -1
- package/src/engine.ts +9 -3
- package/src/knowledge-cli.ts +67 -0
- package/src/knowledge-drafts.ts +55 -0
- package/src/knowledge-mcp.ts +35 -0
- package/src/mcp.ts +12 -6
- package/src/operator.ts +10 -3
- package/src/peer.ts +38 -12
- package/src/relay-main.ts +1 -1
- package/src/relay.ts +18 -6
- package/src/short-pairing.ts +57 -0
- package/src/skill-library.ts +162 -0
- package/src/skill.ts +2 -1
- package/src/util.ts +1 -0
- package/src/vault-crypto.ts +25 -0
- package/src/vault-server.ts +72 -0
- package/src/vault.ts +51 -0
- package/test/agent.test.ts +26 -1
- package/test/cli.test.ts +3 -3
- package/test/knowledge-mcp.test.ts +37 -0
- package/test/knowledge.test.ts +112 -0
- package/test/mcp.test.ts +1 -1
- package/test/pairing.test.ts +2 -2
- package/test/review.test.ts +1 -0
- package/test/short-pairing.test.ts +100 -0
- package/test/skill-library.test.ts +62 -0
- package/test/skill.test.ts +1 -1
package/dist/agent.js
CHANGED
|
@@ -6,13 +6,15 @@ 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 {
|
|
9
|
+
import { skillPrompt } from './skill.js';
|
|
10
|
+
import { resolveSkill } from './skill-library.js';
|
|
11
|
+
import { Cases } from './cases.js';
|
|
10
12
|
import { agentCommand } from './agent-command.js';
|
|
11
|
-
export const agentUsage = 'diagnose agent codex|claude|gemini [--device NAME] [--skill FILE.md|DIRECTORY] [--relay URL] [-- agent arguments...]';
|
|
13
|
+
export const agentUsage = 'diagnose agent codex|claude|gemini [--device NAME] [--case ID] [--skill FILE.md|DIRECTORY|library:NAME@REVISION] [--relay URL] [-- agent arguments...]';
|
|
12
14
|
export async function launchAgent(argv) {
|
|
13
15
|
const separator = argv.indexOf('--');
|
|
14
16
|
const extra = separator < 0 ? [] : argv.slice(separator + 1);
|
|
15
|
-
const { positionals, values } = parseArgs({ args: separator < 0 ? argv : argv.slice(0, separator), allowPositionals: true, options: { relay: { type: 'string' }, skill: { type: 'string' }, device: { type: 'string' }, help: { type: 'boolean', short: 'h' } } });
|
|
17
|
+
const { positionals, values } = parseArgs({ args: separator < 0 ? argv : argv.slice(0, separator), allowPositionals: true, options: { relay: { type: 'string' }, skill: { type: 'string' }, device: { type: 'string' }, case: { type: 'string' }, help: { type: 'boolean', short: 'h' } } });
|
|
16
18
|
if (values.help || !positionals.length) {
|
|
17
19
|
console.log(agentUsage);
|
|
18
20
|
return 0;
|
|
@@ -22,7 +24,15 @@ export async function launchAgent(argv) {
|
|
|
22
24
|
throw new Error(agentUsage);
|
|
23
25
|
if (values.device)
|
|
24
26
|
new PairingStore().get(values.device, 'operator');
|
|
25
|
-
const
|
|
27
|
+
const selectedCase = values.case ? new Cases().get(values.case) : undefined;
|
|
28
|
+
if (selectedCase?.host && values.device && selectedCase.host !== values.device)
|
|
29
|
+
throw new Error('Selected case belongs to a different paired computer');
|
|
30
|
+
if (selectedCase?.skill && values.skill && selectedCase.skill !== values.skill)
|
|
31
|
+
throw new Error('Case skill revision differs from selected skill');
|
|
32
|
+
const skillInput = values.skill ?? selectedCase?.skill;
|
|
33
|
+
let skill = skillInput ? await resolveSkill(skillInput) : undefined;
|
|
34
|
+
if (selectedCase && !skill)
|
|
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.' };
|
|
26
36
|
if (skill && agent === 'gemini' && extra.some(arg => ['-p', '--prompt', '-i', '--prompt-interactive'].includes(arg) || arg.startsWith('--prompt=') || arg.startsWith('--prompt-interactive=')))
|
|
27
37
|
throw new Error('--skill supplies the initial task; do not also pass a Gemini prompt option');
|
|
28
38
|
if (values.relay) {
|
|
@@ -33,7 +43,7 @@ export async function launchAgent(argv) {
|
|
|
33
43
|
throw new Error('Relay URL must not contain credentials');
|
|
34
44
|
}
|
|
35
45
|
// Reuse this exact installed version. No global install or extra npx download.
|
|
36
|
-
const server = { command: process.execPath, args: [fileURLToPath(new URL('./cli.js', import.meta.url)), 'mcp', ...(values.relay ? [values.relay] : []), ...(values.device ? ['--device', values.device] : [])] };
|
|
46
|
+
const server = { command: process.execPath, args: [fileURLToPath(new URL('./cli.js', import.meta.url)), 'mcp', ...(values.relay ? [values.relay] : []), ...(values.device ? ['--device', values.device] : []), ...(values.case ? ['--case', values.case] : [])] };
|
|
37
47
|
const env = { ...process.env };
|
|
38
48
|
let directory;
|
|
39
49
|
try {
|
package/dist/cases.d.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const targetSchema: z.ZodObject<{
|
|
3
|
+
name: z.ZodString;
|
|
4
|
+
model: z.ZodOptional<z.ZodString>;
|
|
5
|
+
identity: z.ZodOptional<z.ZodString>;
|
|
6
|
+
interface: z.ZodEnum<{
|
|
7
|
+
host: "host";
|
|
8
|
+
lan: "lan";
|
|
9
|
+
other: "other";
|
|
10
|
+
serial: "serial";
|
|
11
|
+
usb: "usb";
|
|
12
|
+
}>;
|
|
13
|
+
address: z.ZodOptional<z.ZodString>;
|
|
14
|
+
}, z.core.$strict>;
|
|
15
|
+
export declare const caseInputSchema: z.ZodObject<{
|
|
16
|
+
goal: z.ZodString;
|
|
17
|
+
target: z.ZodObject<{
|
|
18
|
+
name: z.ZodString;
|
|
19
|
+
model: z.ZodOptional<z.ZodString>;
|
|
20
|
+
identity: z.ZodOptional<z.ZodString>;
|
|
21
|
+
interface: z.ZodEnum<{
|
|
22
|
+
host: "host";
|
|
23
|
+
lan: "lan";
|
|
24
|
+
other: "other";
|
|
25
|
+
serial: "serial";
|
|
26
|
+
usb: "usb";
|
|
27
|
+
}>;
|
|
28
|
+
address: z.ZodOptional<z.ZodString>;
|
|
29
|
+
}, z.core.$strict>;
|
|
30
|
+
host: z.ZodOptional<z.ZodString>;
|
|
31
|
+
skill: z.ZodOptional<z.ZodString>;
|
|
32
|
+
}, z.core.$strict>;
|
|
33
|
+
export declare const conclusionSchema: z.ZodObject<{
|
|
34
|
+
outcome: z.ZodEnum<{
|
|
35
|
+
"insufficient-evidence": "insufficient-evidence";
|
|
36
|
+
"needs-physical-work": "needs-physical-work";
|
|
37
|
+
resolved: "resolved";
|
|
38
|
+
unresolved: "unresolved";
|
|
39
|
+
}>;
|
|
40
|
+
summary: z.ZodString;
|
|
41
|
+
changes: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
42
|
+
remaining: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
43
|
+
baseline: z.ZodOptional<z.ZodString>;
|
|
44
|
+
verification: z.ZodOptional<z.ZodString>;
|
|
45
|
+
}, z.core.$strict>;
|
|
46
|
+
export type Evidence = {
|
|
47
|
+
id: string;
|
|
48
|
+
at: string;
|
|
49
|
+
kind: string;
|
|
50
|
+
taskId?: string;
|
|
51
|
+
digest: string;
|
|
52
|
+
data: unknown;
|
|
53
|
+
truncated: boolean;
|
|
54
|
+
};
|
|
55
|
+
export type Case = z.infer<typeof caseInputSchema> & {
|
|
56
|
+
id: string;
|
|
57
|
+
createdAt: string;
|
|
58
|
+
conclusion?: z.infer<typeof conclusionSchema>;
|
|
59
|
+
evidence: Evidence[];
|
|
60
|
+
recordingLimited?: boolean;
|
|
61
|
+
};
|
|
62
|
+
export declare function sanitize(value: unknown): unknown;
|
|
63
|
+
export declare class Cases {
|
|
64
|
+
readonly root: string;
|
|
65
|
+
private journal;
|
|
66
|
+
constructor(root?: string);
|
|
67
|
+
create(input: z.infer<typeof caseInputSchema>): Case;
|
|
68
|
+
get(id: string): Case;
|
|
69
|
+
save(value: Case): void;
|
|
70
|
+
list(): {
|
|
71
|
+
id: string;
|
|
72
|
+
goal: string;
|
|
73
|
+
target: {
|
|
74
|
+
name: string;
|
|
75
|
+
model?: string | undefined;
|
|
76
|
+
identity?: string | undefined;
|
|
77
|
+
interface: "host" | "lan" | "other" | "serial" | "usb";
|
|
78
|
+
address?: string | undefined;
|
|
79
|
+
};
|
|
80
|
+
createdAt: string;
|
|
81
|
+
outcome: string;
|
|
82
|
+
evidenceCount: number;
|
|
83
|
+
}[];
|
|
84
|
+
remove(id: string): void;
|
|
85
|
+
claim(id: string): () => void;
|
|
86
|
+
unlock(id: string): void;
|
|
87
|
+
record(id: string, kind: string, data: unknown, taskId?: string): Evidence | undefined;
|
|
88
|
+
finish(id: string, input: z.infer<typeof conclusionSchema>): Case;
|
|
89
|
+
report(id: string): {
|
|
90
|
+
id: string;
|
|
91
|
+
createdAt: string;
|
|
92
|
+
goal: unknown;
|
|
93
|
+
target: {
|
|
94
|
+
name: unknown;
|
|
95
|
+
model: unknown;
|
|
96
|
+
interface: "host" | "lan" | "other" | "serial" | "usb";
|
|
97
|
+
};
|
|
98
|
+
skill: string | undefined;
|
|
99
|
+
conclusion: {
|
|
100
|
+
outcome: "insufficient-evidence" | "needs-physical-work" | "resolved" | "unresolved";
|
|
101
|
+
summary: string;
|
|
102
|
+
changes: string[];
|
|
103
|
+
remaining: string[];
|
|
104
|
+
baseline?: string | undefined;
|
|
105
|
+
verification?: string | undefined;
|
|
106
|
+
} | undefined;
|
|
107
|
+
recordingLimited: boolean;
|
|
108
|
+
evidence: {
|
|
109
|
+
id: string;
|
|
110
|
+
at: string;
|
|
111
|
+
kind: string;
|
|
112
|
+
taskId: string | undefined;
|
|
113
|
+
digest: string;
|
|
114
|
+
truncated: boolean;
|
|
115
|
+
}[];
|
|
116
|
+
note: string;
|
|
117
|
+
};
|
|
118
|
+
}
|
package/dist/cases.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { unlinkSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { Journal } from './journal.js';
|
|
7
|
+
import { redact } from './util.js';
|
|
8
|
+
const text = z.string().min(1).max(4000);
|
|
9
|
+
export const targetSchema = z.object({ name: text, model: text.optional(), identity: text.optional(), interface: z.enum(['usb', 'serial', 'lan', 'host', 'other']), address: text.optional() }).strict();
|
|
10
|
+
export const caseInputSchema = z.object({ goal: text, target: targetSchema, host: z.string().max(120).optional(), skill: z.string().max(4096).optional() }).strict();
|
|
11
|
+
export const conclusionSchema = z.object({ outcome: z.enum(['resolved', 'unresolved', 'needs-physical-work', 'insufficient-evidence']), summary: text, changes: z.array(text).max(100).default([]), remaining: z.array(text).max(100).default([]), baseline: z.string().uuid().optional(), verification: z.string().uuid().optional() }).strict();
|
|
12
|
+
// Structured credentials are excluded before local persistence; arbitrary output is
|
|
13
|
+
// still sensitive. Encryption is at rest with a same-user key, not an OS sandbox.
|
|
14
|
+
export function sanitize(value) {
|
|
15
|
+
if (typeof value === 'string')
|
|
16
|
+
return redact(value).replace(/\bK1\.[A-Za-z0-9_-]{43}\b/g, '[LIBRARY KEY]');
|
|
17
|
+
if (Array.isArray(value))
|
|
18
|
+
return value.map(sanitize);
|
|
19
|
+
if (value && typeof value === 'object')
|
|
20
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, /password|secret|token|authorization|credential|^code$/i.test(key) ? '[REDACTED]' : sanitize(item)]));
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
export class Cases {
|
|
24
|
+
root;
|
|
25
|
+
journal;
|
|
26
|
+
constructor(root = join(homedir(), '.diagnose', 'cases')) {
|
|
27
|
+
this.root = root;
|
|
28
|
+
this.journal = new Journal(root);
|
|
29
|
+
}
|
|
30
|
+
create(input) {
|
|
31
|
+
if (this.journal.list().length >= 100)
|
|
32
|
+
throw new Error('Case limit reached (100); export and remove old cases');
|
|
33
|
+
const value = { ...caseInputSchema.parse(input), id: randomUUID(), createdAt: new Date().toISOString(), evidence: [] };
|
|
34
|
+
this.save(value);
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
get(id) { z.string().uuid().parse(id); return this.journal.load(id).case; }
|
|
38
|
+
save(value) {
|
|
39
|
+
this.journal.save({ id: value.id, kind: 'process', state: 'case', createdAt: value.createdAt, updatedAt: '', ownerPid: 0, tokenHash: '', retainOnDisconnect: false, case: value });
|
|
40
|
+
}
|
|
41
|
+
list() { return this.journal.list().map(meta => { const value = meta.case; return { id: value.id, goal: value.goal, target: value.target, createdAt: value.createdAt, outcome: value.conclusion?.outcome ?? 'open', evidenceCount: value.evidence.length }; }); }
|
|
42
|
+
remove(id) { this.get(id); if (existsSync(join(this.root, id + '.lock')))
|
|
43
|
+
throw new Error('Case is in use; stop its agent before removing it'); unlinkSync(join(this.root, id + '.meta')); }
|
|
44
|
+
claim(id) {
|
|
45
|
+
this.get(id);
|
|
46
|
+
const path = join(this.root, id + '.lock'), token = randomUUID();
|
|
47
|
+
try {
|
|
48
|
+
writeFileSync(path, JSON.stringify({ pid: process.pid, token }), { flag: 'wx', mode: 0o600 });
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error.code === 'EEXIST')
|
|
52
|
+
throw new Error('Case already has a writer. Stop its agent, or use diagnose cases unlock ID after an unclean exit.');
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
return () => { try {
|
|
56
|
+
if (JSON.parse(readFileSync(path, 'utf8')).token === token)
|
|
57
|
+
unlinkSync(path);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (error.code !== 'ENOENT')
|
|
61
|
+
throw error;
|
|
62
|
+
} };
|
|
63
|
+
}
|
|
64
|
+
unlock(id) {
|
|
65
|
+
this.get(id);
|
|
66
|
+
const path = join(this.root, id + '.lock'), lock = JSON.parse(readFileSync(path, 'utf8'));
|
|
67
|
+
if (!Number.isSafeInteger(lock.pid) || lock.pid <= 0)
|
|
68
|
+
throw new Error('Invalid case lock; inspect locally');
|
|
69
|
+
let alive = true;
|
|
70
|
+
try {
|
|
71
|
+
process.kill(lock.pid, 0);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error.code === 'ESRCH')
|
|
75
|
+
alive = false;
|
|
76
|
+
}
|
|
77
|
+
if (alive)
|
|
78
|
+
throw new Error('Case writer is still alive; stop the agent first');
|
|
79
|
+
unlinkSync(path);
|
|
80
|
+
}
|
|
81
|
+
record(id, kind, data, taskId) {
|
|
82
|
+
const value = this.get(id);
|
|
83
|
+
if (value.evidence.length >= 200) {
|
|
84
|
+
value.recordingLimited = true;
|
|
85
|
+
this.save(value);
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
const serialized = JSON.stringify(sanitize(data));
|
|
89
|
+
const truncated = Buffer.byteLength(serialized) > 32768;
|
|
90
|
+
const evidence = { id: randomUUID(), at: new Date().toISOString(), kind, taskId, digest: createHash('sha256').update(serialized).digest('hex'), data: truncated ? { preview: serialized.slice(0, 8000), note: 'Evidence exceeded 32 KiB; only preview retained' } : JSON.parse(serialized), truncated };
|
|
91
|
+
value.evidence.push(evidence);
|
|
92
|
+
this.save(value);
|
|
93
|
+
return evidence;
|
|
94
|
+
}
|
|
95
|
+
finish(id, input) {
|
|
96
|
+
const conclusion = conclusionSchema.parse(input), value = this.get(id);
|
|
97
|
+
if (conclusion.outcome === 'resolved') {
|
|
98
|
+
const baseline = value.evidence.find(item => item.id === conclusion.baseline), verification = value.evidence.find(item => item.id === conclusion.verification);
|
|
99
|
+
const result = verification?.data?.result;
|
|
100
|
+
if (!baseline || baseline.kind !== 'task.result' || !verification || verification.kind !== 'task.result' || baseline.id === verification.id || value.evidence.indexOf(verification) <= value.evidence.indexOf(baseline) || verification.truncated || result?.status !== 'ok')
|
|
101
|
+
throw new Error('Resolved requires distinct baseline and later successful verification evidence IDs from this case');
|
|
102
|
+
}
|
|
103
|
+
for (const reference of [conclusion.baseline, conclusion.verification])
|
|
104
|
+
if (reference && !value.evidence.some(item => item.id === reference))
|
|
105
|
+
throw new Error('Unknown case evidence ID');
|
|
106
|
+
value.conclusion = sanitize(conclusion);
|
|
107
|
+
this.save(value);
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
report(id) {
|
|
111
|
+
const value = this.get(id);
|
|
112
|
+
// Deliberately exclude target addresses, command arguments and result bodies.
|
|
113
|
+
return { id: value.id, createdAt: value.createdAt, goal: sanitize(value.goal), target: { name: sanitize(value.target.name), model: sanitize(value.target.model), interface: value.target.interface }, skill: value.skill, conclusion: value.conclusion, recordingLimited: value.recordingLimited ?? false, evidence: value.evidence.map(({ id, at, kind, taskId, digest, truncated }) => ({ id, at, kind, taskId, digest, truncated })), note: 'Conclusion is an agent/diagnostician assessment, not an independent proof. Review free text for customer details before sharing.' };
|
|
114
|
+
}
|
|
115
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createInterface } from 'node:readline/promises';
|
|
3
3
|
import { stdin, stdout } from 'node:process';
|
|
4
|
-
import { createCode } from './crypto.js';
|
|
4
|
+
import { createCode, createInvitation } from './crypto.js';
|
|
5
5
|
import { Peer } from './peer.js';
|
|
6
6
|
import { ProbeEngine } from './engine.js';
|
|
7
7
|
import { Operator } from './operator.js';
|
|
@@ -19,6 +19,8 @@ import { PairingStore, automatic, RememberedConnection } from './pairing.js';
|
|
|
19
19
|
import { launchAgent, agentUsage } from './agent.js';
|
|
20
20
|
import { History } from './history.js';
|
|
21
21
|
import { cleanupLocal } from './maintenance.js';
|
|
22
|
+
import { skillsCommand, skillsUsage } from './skill-library.js';
|
|
23
|
+
import { knowledgeCommand, knowledgeUsage } from './knowledge-cli.js';
|
|
22
24
|
async function attachTerminal(operator, id) {
|
|
23
25
|
let done = false, cursor = 0;
|
|
24
26
|
const wasRaw = stdin.isRaw;
|
|
@@ -54,11 +56,19 @@ async function attachTerminal(operator, id) {
|
|
|
54
56
|
}
|
|
55
57
|
}
|
|
56
58
|
async function main() {
|
|
59
|
+
if (['cases', 'drafts', 'vault'].includes(process.argv[2])) {
|
|
60
|
+
await knowledgeCommand(process.argv[2], process.argv.slice(3));
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (process.argv[2] === 'skills') {
|
|
64
|
+
await skillsCommand(process.argv.slice(3));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
57
67
|
if (process.argv[2] === 'agent') {
|
|
58
68
|
process.exitCode = await launchAgent(process.argv.slice(3));
|
|
59
69
|
return;
|
|
60
70
|
}
|
|
61
|
-
const { positionals, values } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { 'session-minutes': { type: 'string', default: '60' }, 'idle-minutes': { type: 'string', default: '10' }, device: { type: 'string' }, name: { type: 'string' }, days: { type: 'string', default: '7' }, cursor: { type: 'string', default: '0' } } });
|
|
71
|
+
const { positionals, values } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { 'session-minutes': { type: 'string', default: '60' }, 'idle-minutes': { type: 'string', default: '10' }, device: { type: 'string' }, case: { type: 'string' }, name: { type: 'string' }, days: { type: 'string', default: '7' }, cursor: { type: 'string', default: '0' } } });
|
|
62
72
|
const [command = 'help', relay = 'https://diagnose.fenginwind.com'] = positionals;
|
|
63
73
|
if (command === 'history') {
|
|
64
74
|
console.log(safeText(JSON.stringify(new History().list(), null, 2)));
|
|
@@ -91,11 +101,11 @@ async function main() {
|
|
|
91
101
|
return;
|
|
92
102
|
}
|
|
93
103
|
if (command === 'mcp') {
|
|
94
|
-
await serveMcp(relay, values.device);
|
|
104
|
+
await serveMcp(relay, values.device, values.case);
|
|
95
105
|
return;
|
|
96
106
|
}
|
|
97
107
|
if (!['start', 'connect', 'terminal', 'pair'].includes(command)) {
|
|
98
|
-
console.log(`diagnose start|connect|terminal|mcp [relay-url] [--device NAME]\ndiagnose pair [relay-url] --name NAME\ndiagnose history\ndiagnose show ID [--cursor OFFSET]\ndiagnose cleanup [--days 7]\ndiagnose devices\ndiagnose forget --device NAME\n${agentUsage}\nNode.js >=20.10. Pairing codes are entered interactively, never as arguments.`);
|
|
108
|
+
console.log(`diagnose start|connect|terminal|mcp [relay-url] [--device NAME]\ndiagnose pair [relay-url] --name NAME\ndiagnose history\ndiagnose show ID [--cursor OFFSET]\ndiagnose cleanup [--days 7]\ndiagnose devices\ndiagnose forget --device NAME\n${agentUsage}\n${skillsUsage}\n${knowledgeUsage}\nNode.js >=20.10. Pairing codes are entered interactively, never as arguments.`);
|
|
99
109
|
return;
|
|
100
110
|
}
|
|
101
111
|
if (!stdin.isTTY || !stdout.isTTY)
|
|
@@ -173,7 +183,7 @@ async function main() {
|
|
|
173
183
|
if (shutdown.signal.aborted)
|
|
174
184
|
break;
|
|
175
185
|
const audit = sessions++ === 0 ? firstAudit : new Audit();
|
|
176
|
-
const code = remembered?.code ??
|
|
186
|
+
const code = remembered?.code ?? createInvitation();
|
|
177
187
|
let provision;
|
|
178
188
|
let grantTimer;
|
|
179
189
|
peer = new Peer({ role: 'host', code, relay: remembered?.relay ?? relay, sessionMs: remembered ? 0 : sessionMinutes * 60000, provision: () => provision, accept: async ({ label, fingerprint, signal, remember }) => {
|
|
@@ -346,13 +356,14 @@ async function main() {
|
|
|
346
356
|
rl.on('line', onLocalLine);
|
|
347
357
|
try {
|
|
348
358
|
await peer.open();
|
|
349
|
-
console.log(remembered ? `Remembered diagnostician: ${safeText(remembered.label)}. Waiting for connections. Local commands: pairing, pause, resume, unpair, permissions ask, permissions auto [forever], cancel, jobs, exit. Audit: ${audit.path}` : `Relay: ${relay}\nAudit: ${audit.path}\nPairing code (
|
|
359
|
+
console.log(remembered ? `Remembered diagnostician: ${safeText(remembered.label)}. Waiting for connections. Local commands: pairing, pause, resume, unpair, permissions ask, permissions auto [forever], cancel, jobs, exit. Audit: ${audit.path}` : `Relay: ${relay}\nAudit: ${audit.path}\nPairing code (30 minutes, one-time, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
|
|
350
360
|
console.log(`Session ended: ${safeText(await peer.ended)}`);
|
|
351
361
|
}
|
|
352
362
|
catch (error) {
|
|
363
|
+
const collision = error.message.includes('Invitation locator occupied');
|
|
353
364
|
if (!shutdown.signal.aborted)
|
|
354
|
-
console.log(`Relay unavailable: ${safeText(error.message)}. Retained work remains local; retrying in 3 seconds.`);
|
|
355
|
-
await delay(3000, undefined, { signal: shutdown.signal }).catch(() => { });
|
|
365
|
+
console.log(collision ? 'Choosing another invitation code...' : `Relay unavailable: ${safeText(error.message)}. Retained work remains local; retrying in 3 seconds.`);
|
|
366
|
+
await delay(collision ? 100 : 3000, undefined, { signal: shutdown.signal }).catch(() => { });
|
|
356
367
|
}
|
|
357
368
|
finally {
|
|
358
369
|
clearTimeout(grantTimer);
|
package/dist/crypto.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
export declare const NOISE_PROTOCOL = "Noise_NNpsk0_25519_ChaChaPoly_BLAKE2b";
|
|
2
|
+
export declare const INVITATION_MS: number;
|
|
3
|
+
export declare function createInvitation(): string;
|
|
4
|
+
export declare function parseInvitation(code: string): {
|
|
5
|
+
room: string;
|
|
6
|
+
secret: Buffer;
|
|
7
|
+
short: boolean;
|
|
8
|
+
};
|
|
2
9
|
export declare function createCode(): string;
|
|
3
10
|
export declare function parseCode(code: string): {
|
|
4
11
|
room: string;
|
package/dist/crypto.js
CHANGED
|
@@ -1,7 +1,22 @@
|
|
|
1
|
-
import { randomBytes, createHash } from 'node:crypto';
|
|
1
|
+
import { randomBytes, randomInt, createHash } from 'node:crypto';
|
|
2
2
|
import Noise from 'noise-handshake';
|
|
3
3
|
import Cipher from 'noise-handshake/cipher.js';
|
|
4
4
|
export const NOISE_PROTOCOL = 'Noise_NNpsk0_25519_ChaChaPoly_BLAKE2b';
|
|
5
|
+
export const INVITATION_MS = 30 * 60 * 1000;
|
|
6
|
+
export function createInvitation() {
|
|
7
|
+
const letters = Array.from({ length: 9 }, () => String.fromCharCode(97 + randomInt(26))).join('');
|
|
8
|
+
return letters.match(/.{3}/g).join('-');
|
|
9
|
+
}
|
|
10
|
+
export function parseInvitation(code) {
|
|
11
|
+
if (code.trim().startsWith('D1.'))
|
|
12
|
+
return { ...parseCode(code), short: false };
|
|
13
|
+
const letters = code.replace(/[\s-]/g, '').toLowerCase();
|
|
14
|
+
if (!/^[a-z]{9}$/.test(letters))
|
|
15
|
+
throw new Error('Enter the nine-letter invitation, for example abc-def-ghi');
|
|
16
|
+
// Only the public two-letter locator reaches the relay. Never hash the full
|
|
17
|
+
// code into a public locator: that would permit offline password guessing.
|
|
18
|
+
return { room: `S2.${letters.slice(0, 2)}`, secret: Buffer.from(letters.slice(2)), short: true };
|
|
19
|
+
}
|
|
5
20
|
export function createCode() { return `D1.${randomBytes(12).toString('base64url')}.${randomBytes(32).toString('base64url')}`; }
|
|
6
21
|
export function parseCode(code) {
|
|
7
22
|
const match = /^D1\.([A-Za-z0-9_-]{16})\.([A-Za-z0-9_-]{43})$/.exec(code.trim());
|
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(), protocol: 1, version: '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.7.0', 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/engine.d.ts
CHANGED
package/dist/engine.js
CHANGED
|
@@ -26,6 +26,7 @@ export class ProbeEngine {
|
|
|
26
26
|
sequenced;
|
|
27
27
|
idle;
|
|
28
28
|
lifetime;
|
|
29
|
+
ended = false;
|
|
29
30
|
mode = 'ask';
|
|
30
31
|
owner = randomUUID();
|
|
31
32
|
resources;
|
|
@@ -59,10 +60,16 @@ export class ProbeEngine {
|
|
|
59
60
|
this.notice = notice;
|
|
60
61
|
this.resources = options.resources ?? new SessionResources(join(dirname(audit.path), basename(audit.path) + '.resources'), audit);
|
|
61
62
|
this.resources.setAudit(audit);
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
// Waiting for an invitation/approval is not diagnostic session time.
|
|
64
|
+
// Otherwise the default ten-minute idle timer would cut a 30-minute code short.
|
|
65
|
+
void peer.active.then(() => {
|
|
66
|
+
if (this.ended)
|
|
67
|
+
return;
|
|
68
|
+
if (options.idleMs !== 0)
|
|
69
|
+
this.idle = setTimeout(() => peer.close('Idle timeout'), options.idleMs ?? 600000);
|
|
70
|
+
if (options.lifetimeMs !== 0)
|
|
71
|
+
this.lifetime = setTimeout(() => peer.close('Session lifetime exceeded'), options.lifetimeMs ?? 3600000);
|
|
72
|
+
}).catch(() => { });
|
|
66
73
|
peer.on('message', (message) => {
|
|
67
74
|
this.idle?.refresh();
|
|
68
75
|
if (message.type === 'resource.request') {
|
|
@@ -120,7 +127,7 @@ export class ProbeEngine {
|
|
|
120
127
|
this.jobs.set(task.id, controller);
|
|
121
128
|
void this.run(task, controller);
|
|
122
129
|
});
|
|
123
|
-
peer.on('closed', () => { clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values())
|
|
130
|
+
peer.on('closed', () => { this.ended = true; clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values())
|
|
124
131
|
controller.abort(); void this.resources.disconnect(this.owner).catch(() => { }); try {
|
|
125
132
|
audit.record('session.closed', {});
|
|
126
133
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export declare const knowledgeUsage = "diagnose cases create INPUT.json | list | show ID | export ID | remove ID | unlock ID\ndiagnose drafts create INPUT.json | list | show ID | review ID | accept ID | reject ID | remove ID\ndiagnose vault init BACKUP_FILE | restore BACKUP_FILE | backup NEW_FILE\ndiagnose vault status | push library:NAME@REVISION | pull | revoke | forget [--relay URL]";
|
|
2
|
+
export declare function knowledgeCommand(command: string, argv: string[]): Promise<void>;
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { createInterface } from 'node:readline/promises';
|
|
3
|
+
import { stdin, stdout } from 'node:process';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { Cases, caseInputSchema } from './cases.js';
|
|
6
|
+
import { Drafts, draftInputSchema } from './knowledge-drafts.js';
|
|
7
|
+
import { Vault } from './vault.js';
|
|
8
|
+
import { safeText } from './util.js';
|
|
9
|
+
import { SkillLibrary } from './skill-library.js';
|
|
10
|
+
export const knowledgeUsage = `diagnose cases create INPUT.json | list | show ID | export ID | remove ID | unlock ID
|
|
11
|
+
diagnose drafts create INPUT.json | list | show ID | review ID | accept ID | reject ID | remove ID
|
|
12
|
+
diagnose vault init BACKUP_FILE | restore BACKUP_FILE | backup NEW_FILE
|
|
13
|
+
diagnose vault status | push library:NAME@REVISION | pull | revoke | forget [--relay URL]`;
|
|
14
|
+
async function json(path) { if ((await stat(path)).size > 256 * 1024)
|
|
15
|
+
throw new Error('Input JSON exceeds 256 KiB'); return JSON.parse(await readFile(path, 'utf8')); }
|
|
16
|
+
async function confirm(message) {
|
|
17
|
+
if (!stdin.isTTY || !stdout.isTTY)
|
|
18
|
+
throw new Error('Review requires an interactive diagnostician terminal');
|
|
19
|
+
const rl = createInterface({ input: stdin, output: stdout });
|
|
20
|
+
try {
|
|
21
|
+
return (await rl.question(message + ' [y/N] ')).trim().toLowerCase() === 'y';
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
rl.close();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export async function knowledgeCommand(command, argv) {
|
|
28
|
+
const { positionals, values } = parseArgs({ args: argv, allowPositionals: true, options: { relay: { type: 'string' }, help: { type: 'boolean' } } });
|
|
29
|
+
if (values.help) {
|
|
30
|
+
console.log(knowledgeUsage);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const [action, argument] = positionals;
|
|
34
|
+
if (positionals.length > 2)
|
|
35
|
+
throw new Error(knowledgeUsage);
|
|
36
|
+
const print = (value) => console.log(safeText(typeof value === 'string' ? value : JSON.stringify(value, null, 2)));
|
|
37
|
+
if (command === 'cases') {
|
|
38
|
+
const cases = new Cases();
|
|
39
|
+
if (action === 'list') {
|
|
40
|
+
print(cases.list());
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (action === 'create' && argument) {
|
|
44
|
+
const input = caseInputSchema.parse(await json(argument));
|
|
45
|
+
if (input.skill)
|
|
46
|
+
await new SkillLibrary().load(input.skill);
|
|
47
|
+
print(cases.create(input));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (action === 'show' && argument) {
|
|
51
|
+
print(cases.get(argument));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (action === 'export' && argument) {
|
|
55
|
+
print(cases.report(argument));
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (action === 'unlock' && argument) {
|
|
59
|
+
if (await confirm('Release the lock left by a terminated case writer?'))
|
|
60
|
+
cases.unlock(argument);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (action === 'remove' && argument) {
|
|
64
|
+
if (await confirm('Delete this local case and its retained evidence?'))
|
|
65
|
+
cases.remove(argument);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (command === 'drafts') {
|
|
70
|
+
const drafts = new Drafts();
|
|
71
|
+
if (action === 'list') {
|
|
72
|
+
print(drafts.list());
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (action === 'show' && argument) {
|
|
76
|
+
print(drafts.get(argument));
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (action === 'remove' && argument) {
|
|
80
|
+
if (await confirm('Delete this local draft record? Imported skill versions remain.'))
|
|
81
|
+
await drafts.remove(argument);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (action === 'create' && argument) {
|
|
85
|
+
print(await drafts.create(draftInputSchema.parse(await json(argument))));
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (action === 'review' && argument) {
|
|
89
|
+
print(await drafts.review(argument));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (action === 'accept' && argument) {
|
|
93
|
+
const review = await drafts.review(argument);
|
|
94
|
+
print(review);
|
|
95
|
+
if (await confirm('Have you reviewed all instructions, evidence and privacy, and accept this exact draft?')) {
|
|
96
|
+
if (await drafts.review(argument) !== review)
|
|
97
|
+
throw new Error('Draft changed during review; review again');
|
|
98
|
+
print(await drafts.accept(argument));
|
|
99
|
+
}
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (action === 'reject' && argument) {
|
|
103
|
+
drafts.reject(argument);
|
|
104
|
+
print('Draft rejected; accepted versions unchanged.');
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (command === 'vault') {
|
|
109
|
+
const vault = new Vault(undefined, undefined, values.relay);
|
|
110
|
+
if (action === 'init' && argument) {
|
|
111
|
+
await vault.initialize();
|
|
112
|
+
await vault.backup(argument);
|
|
113
|
+
print('Library initialized. Recovery backup saved privately. Keep it outside this computer; it grants full library access. No data uploaded.');
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (action === 'restore' && argument) {
|
|
117
|
+
if ((await stat(argument)).size > 100)
|
|
118
|
+
throw new Error('Invalid recovery file');
|
|
119
|
+
await vault.initialize((await readFile(argument, 'utf8')).trim());
|
|
120
|
+
print('Recovery key restored. Run diagnose vault pull to download verified versions.');
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (action === 'backup' && argument) {
|
|
124
|
+
await vault.backup(argument);
|
|
125
|
+
print('Private recovery backup saved. Never send it to an agent or put it in command arguments.');
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (action === 'status') {
|
|
129
|
+
print({ objects: await vault.list() });
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (action === 'push' && argument) {
|
|
133
|
+
await new SkillLibrary().load(argument);
|
|
134
|
+
if (await confirm(`Upload the complete ${argument} bundle, including references/scripts, encrypted to ${vault.relay}? Confirm it contains no customer secrets or raw logs.`)) {
|
|
135
|
+
await vault.push(argument);
|
|
136
|
+
print('Encrypted skill version uploaded.');
|
|
137
|
+
}
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (action === 'pull') {
|
|
141
|
+
print({ downloaded: await vault.pull(), note: 'Versions are local; none were executed or selected automatically.' });
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (action === 'revoke') {
|
|
145
|
+
if (await confirm('Permanently delete this relay library and revoke this recovery credential on this relay? Local skills remain.')) {
|
|
146
|
+
await vault.revoke();
|
|
147
|
+
print('Relay library revoked. Use a new key to share again.');
|
|
148
|
+
}
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (action === 'forget') {
|
|
152
|
+
if (await confirm('Remove this computer’s library recovery credential? Ensure you have a backup. This does not revoke other computers.')) {
|
|
153
|
+
await vault.forget();
|
|
154
|
+
print('Local recovery credential removed.');
|
|
155
|
+
}
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (!action || action === 'help' || action === '--help') {
|
|
160
|
+
print(knowledgeUsage);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
throw new Error(knowledgeUsage);
|
|
164
|
+
}
|