@masstensor/diagnose 0.3.2 → 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 +56 -9
- package/USER_GUIDE.md +460 -20
- package/deploy/Caddyfile +1 -1
- package/deploy/ecosystem.config.cjs +1 -1
- package/dist/agent-command.d.ts +4 -0
- package/dist/agent-command.js +33 -0
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +48 -8
- package/dist/cases.d.ts +118 -0
- package/dist/cases.js +115 -0
- package/dist/cli.js +187 -25
- package/dist/crypto.d.ts +7 -0
- package/dist/crypto.js +16 -1
- package/dist/discover.js +1 -1
- package/dist/engine.d.ts +3 -0
- package/dist/engine.js +49 -9
- package/dist/history.d.ts +13 -0
- package/dist/history.js +57 -0
- package/dist/journal.d.ts +23 -1
- package/dist/journal.js +82 -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/maintenance.d.ts +2 -0
- package/dist/maintenance.js +46 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +42 -20
- package/dist/operator.d.ts +4 -0
- package/dist/operator.js +33 -8
- package/dist/pairing.d.ts +40 -0
- package/dist/pairing.js +92 -0
- package/dist/peer.d.ts +13 -0
- package/dist/peer.js +87 -11
- package/dist/relay-main.js +1 -1
- package/dist/relay.d.ts +1 -0
- package/dist/relay.js +27 -4
- package/dist/resources.js +47 -26
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +2 -2
- 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 +9 -0
- package/dist/skill.js +59 -0
- package/dist/transfers.js +28 -11
- package/dist/util.d.ts +2 -0
- package/dist/util.js +17 -3
- 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/examples/skills/device-troubleshooting/SKILL.md +35 -0
- package/examples/skills/device-troubleshooting/references/device-profile.md +16 -0
- package/examples/skills/owon.md +27 -0
- package/npm-shrinkwrap.json +209 -3
- package/package.json +15 -5
- package/scripts/setup-node.ps1 +54 -0
- package/scripts/setup-node.sh +52 -0
- package/src/agent-command.ts +25 -0
- package/src/agent.ts +37 -7
- package/src/cases.ts +74 -0
- package/src/cli.ts +57 -22
- package/src/crypto.ts +14 -1
- package/src/discover.ts +1 -1
- package/src/engine.ts +28 -7
- package/src/history.ts +43 -0
- package/src/journal.ts +41 -5
- package/src/knowledge-cli.ts +67 -0
- package/src/knowledge-drafts.ts +55 -0
- package/src/knowledge-mcp.ts +35 -0
- package/src/maintenance.ts +30 -0
- package/src/mcp.ts +26 -18
- package/src/operator.ts +25 -9
- package/src/pairing.ts +64 -0
- package/src/peer.ts +42 -14
- package/src/relay-main.ts +1 -1
- package/src/relay.ts +18 -6
- package/src/resources.ts +35 -13
- package/src/schema.ts +4 -4
- package/src/short-pairing.ts +57 -0
- package/src/skill-library.ts +162 -0
- package/src/skill.ts +45 -0
- package/src/transfers.ts +14 -3
- package/src/util.ts +15 -3
- 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 +79 -7
- 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 +124 -0
- package/test/review.test.ts +129 -0
- package/test/setup.test.ts +16 -0
- package/test/short-pairing.test.ts +100 -0
- package/test/skill-library.test.ts +62 -0
- package/test/skill.test.ts +25 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { access, readFile } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve, relative, isAbsolute, dirname } from 'node:path';
|
|
3
|
+
// npm's Windows .cmd wrappers are not executables. Resolve their Node entry
|
|
4
|
+
// point instead of interpolating user prompts or JSON through cmd.exe.
|
|
5
|
+
export async function agentCommand(name, args, env, platform = process.platform) {
|
|
6
|
+
if (platform !== 'win32')
|
|
7
|
+
return { command: name, args };
|
|
8
|
+
const path = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] ?? '';
|
|
9
|
+
for (const directory of path.split(';').filter(Boolean)) {
|
|
10
|
+
for (const extension of ['.exe', '.cmd']) {
|
|
11
|
+
const candidate = join(directory.replace(/^"|"$/g, ''), name + extension);
|
|
12
|
+
try {
|
|
13
|
+
await access(candidate);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
if (extension === '.exe')
|
|
19
|
+
return { command: candidate, args };
|
|
20
|
+
const wrapper = await readFile(candidate, 'utf8');
|
|
21
|
+
const match = /"%dp0%[\\/]([^"\r\n]+\.(?:cjs|mjs|js))"/i.exec(wrapper);
|
|
22
|
+
if (!match)
|
|
23
|
+
throw new Error(`Unsupported ${name}.cmd launcher. Install the official npm package or native executable; Diagnose will not pass prompts through a shell.`);
|
|
24
|
+
const entry = resolve(dirname(candidate), match[1].replace(/\\/g, '/'));
|
|
25
|
+
const diff = relative(dirname(candidate), entry);
|
|
26
|
+
if (diff.startsWith('..') || isAbsolute(diff))
|
|
27
|
+
throw new Error('Agent npm entry point is outside its installation directory');
|
|
28
|
+
await access(entry);
|
|
29
|
+
return { command: process.execPath, args: [entry, ...args] };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
throw new Error(`${name} was not found on PATH. Install and sign in to its CLI first.`);
|
|
33
|
+
}
|
package/dist/agent.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const agentUsage = "diagnose agent codex|claude|gemini [--relay URL] [-- agent arguments...]";
|
|
1
|
+
export declare const agentUsage = "diagnose agent codex|claude|gemini [--device NAME] [--case ID] [--skill FILE.md|DIRECTORY|library:NAME@REVISION] [--relay URL] [-- agent arguments...]";
|
|
2
2
|
export declare function launchAgent(argv: string[]): Promise<number>;
|
package/dist/agent.js
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { constants } from 'node:os';
|
|
3
|
-
import { mkdtemp, readFile, writeFile, rm, mkdir, readdir, symlink } from 'node:fs/promises';
|
|
3
|
+
import { mkdtemp, readFile, writeFile, rm, mkdir, readdir, symlink, stat, copyFile } from 'node:fs/promises';
|
|
4
4
|
import { tmpdir, homedir } from 'node:os';
|
|
5
5
|
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';
|
|
10
|
+
import { resolveSkill } from './skill-library.js';
|
|
11
|
+
import { Cases } from './cases.js';
|
|
12
|
+
import { agentCommand } from './agent-command.js';
|
|
13
|
+
export const agentUsage = 'diagnose agent codex|claude|gemini [--device NAME] [--case ID] [--skill FILE.md|DIRECTORY|library:NAME@REVISION] [--relay URL] [-- agent arguments...]';
|
|
9
14
|
export async function launchAgent(argv) {
|
|
10
15
|
const separator = argv.indexOf('--');
|
|
11
16
|
const extra = separator < 0 ? [] : argv.slice(separator + 1);
|
|
12
|
-
const { positionals, values } = parseArgs({ args: separator < 0 ? argv : argv.slice(0, separator), allowPositionals: true, options: { relay: { 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' } } });
|
|
13
18
|
if (values.help || !positionals.length) {
|
|
14
19
|
console.log(agentUsage);
|
|
15
20
|
return 0;
|
|
@@ -17,6 +22,19 @@ export async function launchAgent(argv) {
|
|
|
17
22
|
const [agent] = positionals;
|
|
18
23
|
if (positionals.length !== 1 || !['codex', 'claude', 'gemini'].includes(agent))
|
|
19
24
|
throw new Error(agentUsage);
|
|
25
|
+
if (values.device)
|
|
26
|
+
new PairingStore().get(values.device, 'operator');
|
|
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.' };
|
|
36
|
+
if (skill && agent === 'gemini' && extra.some(arg => ['-p', '--prompt', '-i', '--prompt-interactive'].includes(arg) || arg.startsWith('--prompt=') || arg.startsWith('--prompt-interactive=')))
|
|
37
|
+
throw new Error('--skill supplies the initial task; do not also pass a Gemini prompt option');
|
|
20
38
|
if (values.relay) {
|
|
21
39
|
const url = new URL(values.relay);
|
|
22
40
|
if (!['https:', 'wss:'].includes(url.protocol) && !(['http:', 'ws:'].includes(url.protocol) && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))
|
|
@@ -25,10 +43,20 @@ export async function launchAgent(argv) {
|
|
|
25
43
|
throw new Error('Relay URL must not contain credentials');
|
|
26
44
|
}
|
|
27
45
|
// Reuse this exact installed version. No global install or extra npx download.
|
|
28
|
-
const server = { command: process.execPath, args: [fileURLToPath(new URL('./cli.js', import.meta.url)), 'mcp', ...(values.relay ? [values.relay] : [])] };
|
|
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] : [])] };
|
|
29
47
|
const env = { ...process.env };
|
|
30
48
|
let directory;
|
|
31
49
|
try {
|
|
50
|
+
let prompt, taskDirectory;
|
|
51
|
+
if (skill) {
|
|
52
|
+
directory = await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
|
|
53
|
+
taskDirectory = join(directory, 'task');
|
|
54
|
+
await mkdir(taskDirectory, { mode: 0o700 });
|
|
55
|
+
const snapshot = join(taskDirectory, 'task.json');
|
|
56
|
+
await writeFile(snapshot, JSON.stringify(skill), { mode: 0o600 });
|
|
57
|
+
prompt = skillPrompt(snapshot) + (values.device ? '\nDiagnose MCP is already configured for the saved device ' + JSON.stringify(values.device) + '. Use its tools directly; do not ask for a pairing code. If unavailable, ask the user to start or resume their probe.' : '');
|
|
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
|
+
}
|
|
32
60
|
let args;
|
|
33
61
|
if (agent === 'codex')
|
|
34
62
|
args = ['-c', `mcp_servers.diagnose.command=${JSON.stringify(server.command)}`, '-c', `mcp_servers.diagnose.args=${JSON.stringify(server.args)}`, ...extra];
|
|
@@ -49,7 +77,7 @@ export async function launchAgent(argv) {
|
|
|
49
77
|
}
|
|
50
78
|
if (!settings || typeof settings !== 'object' || Array.isArray(settings))
|
|
51
79
|
throw new Error('Gemini user settings must be a JSON object');
|
|
52
|
-
directory
|
|
80
|
+
directory ??= await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
|
|
53
81
|
const configRoot = join(directory, '.gemini');
|
|
54
82
|
await mkdir(configRoot, { mode: 0o700 });
|
|
55
83
|
let entries = [];
|
|
@@ -61,15 +89,27 @@ export async function launchAgent(argv) {
|
|
|
61
89
|
throw error;
|
|
62
90
|
}
|
|
63
91
|
for (const name of entries)
|
|
64
|
-
if (name !== 'settings.json')
|
|
65
|
-
|
|
92
|
+
if (name !== 'settings.json') {
|
|
93
|
+
const source = join(originalRoot, name), target = join(configRoot, name);
|
|
94
|
+
if (process.platform === 'win32') {
|
|
95
|
+
if ((await stat(source)).isDirectory())
|
|
96
|
+
await symlink(source, target, 'junction');
|
|
97
|
+
else
|
|
98
|
+
await copyFile(source, target);
|
|
99
|
+
}
|
|
100
|
+
else
|
|
101
|
+
await symlink(source, target);
|
|
102
|
+
}
|
|
66
103
|
const path = join(configRoot, 'settings.json');
|
|
67
104
|
await writeFile(path, JSON.stringify({ ...settings, mcpServers: { ...(settings.mcpServers ?? {}), diagnose: server } }), { mode: 0o600 });
|
|
68
105
|
env.GEMINI_CLI_HOME = directory;
|
|
69
106
|
args = extra;
|
|
70
107
|
}
|
|
108
|
+
if (prompt)
|
|
109
|
+
args = agent === 'gemini' ? [...args, '--include-directories', taskDirectory, '--prompt-interactive', prompt] : [...args, '--add-dir', taskDirectory, '--', prompt];
|
|
110
|
+
const command = await agentCommand(agent, args, env);
|
|
71
111
|
return await new Promise((resolveExit, reject) => {
|
|
72
|
-
const child = spawn(
|
|
112
|
+
const child = spawn(command.command, command.args, { env, stdio: 'inherit', shell: false });
|
|
73
113
|
const interrupt = () => { child.kill('SIGINT'); }, terminate = () => { child.kill('SIGTERM'); };
|
|
74
114
|
process.on('SIGINT', interrupt);
|
|
75
115
|
process.on('SIGTERM', terminate);
|
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
|
+
}
|