@masstensor/diagnose 0.3.2 → 0.5.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/README.md +46 -7
- package/USER_GUIDE.md +305 -12
- 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 +38 -8
- package/dist/cli.js +173 -22
- package/dist/discover.js +1 -1
- package/dist/engine.d.ts +2 -0
- package/dist/engine.js +37 -4
- 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/maintenance.d.ts +2 -0
- package/dist/maintenance.js +46 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +21 -18
- package/dist/operator.d.ts +2 -0
- package/dist/operator.js +17 -5
- package/dist/pairing.d.ts +40 -0
- package/dist/pairing.js +92 -0
- package/dist/peer.d.ts +4 -0
- package/dist/peer.js +10 -3
- package/dist/resources.js +47 -26
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +2 -2
- package/dist/skill.d.ts +8 -0
- package/dist/skill.js +58 -0
- package/dist/transfers.js +28 -11
- package/dist/util.d.ts +2 -0
- package/dist/util.js +16 -3
- 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 +199 -3
- package/package.json +11 -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 +30 -7
- package/src/cli.ts +51 -20
- package/src/discover.ts +1 -1
- package/src/engine.ts +19 -4
- package/src/history.ts +43 -0
- package/src/journal.ts +41 -5
- package/src/maintenance.ts +30 -0
- package/src/mcp.ts +18 -16
- package/src/operator.ts +15 -6
- package/src/pairing.ts +64 -0
- package/src/peer.ts +6 -4
- package/src/resources.ts +35 -13
- package/src/schema.ts +4 -4
- package/src/skill.ts +44 -0
- package/src/transfers.ts +14 -3
- package/src/util.ts +14 -3
- package/test/agent.test.ts +53 -6
- package/test/pairing.test.ts +124 -0
- package/test/review.test.ts +128 -0
- package/test/setup.test.ts +16 -0
- package/test/skill.test.ts +25 -0
package/dist/agent.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
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 { loadSkill, skillPrompt } from './skill.js';
|
|
10
|
+
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...]';
|
|
9
12
|
export async function launchAgent(argv) {
|
|
10
13
|
const separator = argv.indexOf('--');
|
|
11
14
|
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' } } });
|
|
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' } } });
|
|
13
16
|
if (values.help || !positionals.length) {
|
|
14
17
|
console.log(agentUsage);
|
|
15
18
|
return 0;
|
|
@@ -17,6 +20,11 @@ export async function launchAgent(argv) {
|
|
|
17
20
|
const [agent] = positionals;
|
|
18
21
|
if (positionals.length !== 1 || !['codex', 'claude', 'gemini'].includes(agent))
|
|
19
22
|
throw new Error(agentUsage);
|
|
23
|
+
if (values.device)
|
|
24
|
+
new PairingStore().get(values.device, 'operator');
|
|
25
|
+
const skill = values.skill === undefined ? undefined : await loadSkill(values.skill);
|
|
26
|
+
if (skill && agent === 'gemini' && extra.some(arg => ['-p', '--prompt', '-i', '--prompt-interactive'].includes(arg) || arg.startsWith('--prompt=') || arg.startsWith('--prompt-interactive=')))
|
|
27
|
+
throw new Error('--skill supplies the initial task; do not also pass a Gemini prompt option');
|
|
20
28
|
if (values.relay) {
|
|
21
29
|
const url = new URL(values.relay);
|
|
22
30
|
if (!['https:', 'wss:'].includes(url.protocol) && !(['http:', 'ws:'].includes(url.protocol) && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)))
|
|
@@ -25,10 +33,20 @@ export async function launchAgent(argv) {
|
|
|
25
33
|
throw new Error('Relay URL must not contain credentials');
|
|
26
34
|
}
|
|
27
35
|
// 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] : [])] };
|
|
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] : [])] };
|
|
29
37
|
const env = { ...process.env };
|
|
30
38
|
let directory;
|
|
31
39
|
try {
|
|
40
|
+
let prompt, taskDirectory;
|
|
41
|
+
if (skill) {
|
|
42
|
+
directory = await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
|
|
43
|
+
taskDirectory = join(directory, 'task');
|
|
44
|
+
await mkdir(taskDirectory, { mode: 0o700 });
|
|
45
|
+
const snapshot = join(taskDirectory, 'task.json');
|
|
46
|
+
await writeFile(snapshot, JSON.stringify(skill), { mode: 0o600 });
|
|
47
|
+
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.' : '');
|
|
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.');
|
|
49
|
+
}
|
|
32
50
|
let args;
|
|
33
51
|
if (agent === 'codex')
|
|
34
52
|
args = ['-c', `mcp_servers.diagnose.command=${JSON.stringify(server.command)}`, '-c', `mcp_servers.diagnose.args=${JSON.stringify(server.args)}`, ...extra];
|
|
@@ -49,7 +67,7 @@ export async function launchAgent(argv) {
|
|
|
49
67
|
}
|
|
50
68
|
if (!settings || typeof settings !== 'object' || Array.isArray(settings))
|
|
51
69
|
throw new Error('Gemini user settings must be a JSON object');
|
|
52
|
-
directory
|
|
70
|
+
directory ??= await mkdtemp(join(tmpdir(), 'diagnose-agent-'));
|
|
53
71
|
const configRoot = join(directory, '.gemini');
|
|
54
72
|
await mkdir(configRoot, { mode: 0o700 });
|
|
55
73
|
let entries = [];
|
|
@@ -61,15 +79,27 @@ export async function launchAgent(argv) {
|
|
|
61
79
|
throw error;
|
|
62
80
|
}
|
|
63
81
|
for (const name of entries)
|
|
64
|
-
if (name !== 'settings.json')
|
|
65
|
-
|
|
82
|
+
if (name !== 'settings.json') {
|
|
83
|
+
const source = join(originalRoot, name), target = join(configRoot, name);
|
|
84
|
+
if (process.platform === 'win32') {
|
|
85
|
+
if ((await stat(source)).isDirectory())
|
|
86
|
+
await symlink(source, target, 'junction');
|
|
87
|
+
else
|
|
88
|
+
await copyFile(source, target);
|
|
89
|
+
}
|
|
90
|
+
else
|
|
91
|
+
await symlink(source, target);
|
|
92
|
+
}
|
|
66
93
|
const path = join(configRoot, 'settings.json');
|
|
67
94
|
await writeFile(path, JSON.stringify({ ...settings, mcpServers: { ...(settings.mcpServers ?? {}), diagnose: server } }), { mode: 0o600 });
|
|
68
95
|
env.GEMINI_CLI_HOME = directory;
|
|
69
96
|
args = extra;
|
|
70
97
|
}
|
|
98
|
+
if (prompt)
|
|
99
|
+
args = agent === 'gemini' ? [...args, '--include-directories', taskDirectory, '--prompt-interactive', prompt] : [...args, '--add-dir', taskDirectory, '--', prompt];
|
|
100
|
+
const command = await agentCommand(agent, args, env);
|
|
71
101
|
return await new Promise((resolveExit, reject) => {
|
|
72
|
-
const child = spawn(
|
|
102
|
+
const child = spawn(command.command, command.args, { env, stdio: 'inherit', shell: false });
|
|
73
103
|
const interrupt = () => { child.kill('SIGINT'); }, terminate = () => { child.kill('SIGTERM'); };
|
|
74
104
|
process.on('SIGINT', interrupt);
|
|
75
105
|
process.on('SIGTERM', terminate);
|
package/dist/cli.js
CHANGED
|
@@ -15,7 +15,10 @@ import { forward } from './forward.js';
|
|
|
15
15
|
import { spawn } from 'node:child_process';
|
|
16
16
|
import { parseArgs } from 'node:util';
|
|
17
17
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
18
|
+
import { PairingStore, automatic, RememberedConnection } from './pairing.js';
|
|
18
19
|
import { launchAgent, agentUsage } from './agent.js';
|
|
20
|
+
import { History } from './history.js';
|
|
21
|
+
import { cleanupLocal } from './maintenance.js';
|
|
19
22
|
async function attachTerminal(operator, id) {
|
|
20
23
|
let done = false, cursor = 0;
|
|
21
24
|
const wasRaw = stdin.isRaw;
|
|
@@ -55,19 +58,44 @@ async function main() {
|
|
|
55
58
|
process.exitCode = await launchAgent(process.argv.slice(3));
|
|
56
59
|
return;
|
|
57
60
|
}
|
|
58
|
-
const { positionals, values } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { 'session-minutes': { type: 'string', default: '60' }, 'idle-minutes': { type: 'string', default: '10' } } });
|
|
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' } } });
|
|
59
62
|
const [command = 'help', relay = 'https://diagnose.fenginwind.com'] = positionals;
|
|
63
|
+
if (command === 'history') {
|
|
64
|
+
console.log(safeText(JSON.stringify(new History().list(), null, 2)));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (command === 'show') {
|
|
68
|
+
const cursor = Number(values.cursor);
|
|
69
|
+
if (!Number.isSafeInteger(cursor) || cursor < 0)
|
|
70
|
+
throw new Error('Cursor must be a nonnegative integer');
|
|
71
|
+
console.log(safeText(JSON.stringify(new History().show(positionals[1] ?? '', cursor), null, 2)));
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (command === 'cleanup') {
|
|
75
|
+
console.log(JSON.stringify(cleanupLocal(Number(values.days)), null, 2));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
60
78
|
if (positionals.length > 2)
|
|
61
79
|
throw new Error('Usage: diagnose start|connect|terminal|mcp [relay-url]');
|
|
62
80
|
const sessionMinutes = Number(values['session-minutes']), idleMinutes = Number(values['idle-minutes']);
|
|
63
81
|
if (![sessionMinutes, idleMinutes].every(value => Number.isInteger(value) && value >= 0 && value <= 10080))
|
|
64
82
|
throw new Error('Timeouts must be 0..10080 minutes; 0 disables endpoint timeout (relay maximum 7 days)');
|
|
83
|
+
if (command === 'devices') {
|
|
84
|
+
console.log(JSON.stringify(new PairingStore(join(homedir(), '.diagnose', 'pairings')).list('operator').map(({ name, id, relay }) => ({ name, id, relay })), null, 2));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (command === 'forget') {
|
|
88
|
+
const store = new PairingStore(join(homedir(), '.diagnose', 'pairings'));
|
|
89
|
+
store.remove(store.get(values.device ?? '', 'operator').id);
|
|
90
|
+
console.log('Local pairing removed. Revoke on the user computer to invalidate its credential.');
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
65
93
|
if (command === 'mcp') {
|
|
66
|
-
await serveMcp(relay);
|
|
94
|
+
await serveMcp(relay, values.device);
|
|
67
95
|
return;
|
|
68
96
|
}
|
|
69
|
-
if (!['start', 'connect', 'terminal'].includes(command)) {
|
|
70
|
-
console.log(`diagnose start|connect|terminal|mcp [relay-url]\n${agentUsage}\nNode.js >=
|
|
97
|
+
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.`);
|
|
71
99
|
return;
|
|
72
100
|
}
|
|
73
101
|
if (!stdin.isTTY || !stdout.isTTY)
|
|
@@ -102,43 +130,143 @@ async function main() {
|
|
|
102
130
|
};
|
|
103
131
|
try {
|
|
104
132
|
if (command === 'start') {
|
|
133
|
+
const store = new PairingStore();
|
|
134
|
+
console.log('Task details and collected results are saved in encrypted local history for up to 7 days (256 MiB budget). View with diagnose history / diagnose show ID; remove inactive records with diagnose cleanup --days 0. Scripts may contain sensitive data.');
|
|
105
135
|
const firstAudit = new Audit();
|
|
106
136
|
resources = new SessionResources(join(homedir(), '.diagnose', 'resources'), firstAudit);
|
|
107
137
|
let sessions = 0;
|
|
108
138
|
while (!shutdown.signal.aborted) {
|
|
139
|
+
let remembered = store.list('host')[0];
|
|
140
|
+
if (remembered?.paused) {
|
|
141
|
+
console.log('Remote access is paused. Type resume, unpair, or exit.');
|
|
142
|
+
const controls = (line) => { if (line.trim() === 'resume') {
|
|
143
|
+
remembered.paused = false;
|
|
144
|
+
store.save(remembered);
|
|
145
|
+
firstAudit.record('pairing.resume', { id: remembered.id });
|
|
146
|
+
}
|
|
147
|
+
else if (line.trim() === 'unpair') {
|
|
148
|
+
store.remove(remembered.id);
|
|
149
|
+
firstAudit.record('pairing.revoked', { id: remembered.id });
|
|
150
|
+
remembered = undefined;
|
|
151
|
+
}
|
|
152
|
+
else if (line.trim() === 'permissions ask') {
|
|
153
|
+
remembered.autoUntil = 0;
|
|
154
|
+
store.save(remembered);
|
|
155
|
+
firstAudit.record('permissions.revoked', { id: remembered.id });
|
|
156
|
+
console.log('Automatic permissions revoked; access remains paused.');
|
|
157
|
+
}
|
|
158
|
+
else if (line.trim() === 'exit')
|
|
159
|
+
stop();
|
|
160
|
+
else
|
|
161
|
+
console.log('Access paused. Type resume, unpair, permissions ask, or exit.'); };
|
|
162
|
+
rl.on('line', controls);
|
|
163
|
+
try {
|
|
164
|
+
while (remembered?.paused && !shutdown.signal.aborted) {
|
|
165
|
+
await delay(300, undefined, { signal: shutdown.signal }).catch(() => { });
|
|
166
|
+
remembered = store.list('host')[0];
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
rl.off('line', controls);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (shutdown.signal.aborted)
|
|
174
|
+
break;
|
|
109
175
|
const audit = sessions++ === 0 ? firstAudit : new Audit();
|
|
110
|
-
const code = createCode();
|
|
111
|
-
|
|
176
|
+
const code = remembered?.code ?? createCode();
|
|
177
|
+
let provision;
|
|
178
|
+
let grantTimer;
|
|
179
|
+
peer = new Peer({ role: 'host', code, relay: remembered?.relay ?? relay, sessionMs: remembered ? 0 : sessionMinutes * 60000, provision: () => provision, accept: async ({ label, fingerprint, signal, remember }) => {
|
|
180
|
+
if (remembered) {
|
|
181
|
+
audit.record('pairing.reconnected', { id: remembered.id });
|
|
182
|
+
return !remembered.paused;
|
|
183
|
+
}
|
|
184
|
+
if (remember)
|
|
185
|
+
console.log('REMEMBER THIS DIAGNOSTICIAN: this computer will accept future connections using a new private credential until you type "unpair". Task approval remains enabled. AUTO lasts one hour, across reconnects.');
|
|
112
186
|
console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
|
|
113
|
-
console.log('Choose y: approve each task/batch and its transfer.\nChoose a: grant automatic execution AND transmission
|
|
114
|
-
const answer = (await rl.question('Allow this temporary diagnostic session? [y / a=auto / N] ', { signal })).trim().toLowerCase();
|
|
187
|
+
console.log('Choose y: approve each task/batch and its transfer.\nChoose a: grant automatic execution AND transmission (one hour if remembered; otherwise this temporary session).\nAUTO: commands have your OS permissions; results go to the diagnostician and their AI without further prompts. Raw terminal, file and tunnel channels are NOT redacted. A channel grant includes continuing input/output within its scope.\nRevoke locally with "permissions ask", cancel with "cancel", or end with Ctrl+C. Already transmitted data cannot be recalled.');
|
|
188
|
+
const answer = (await rl.question(remember ? 'Remember and allow this diagnostician? [y / a=auto for 1 hour / N] ' : 'Allow this temporary diagnostic session? [y / a=auto / N] ', { signal })).trim().toLowerCase();
|
|
115
189
|
const allowed = answer === 'y' || answer === 'a';
|
|
116
|
-
if (
|
|
190
|
+
if (allowed && remember) {
|
|
191
|
+
provision = createCode();
|
|
192
|
+
remembered = store.add({ role: 'host', name: 'diagnostician', label, relay, code: provision });
|
|
193
|
+
audit.record('pairing.remembered', { id: remembered.id });
|
|
194
|
+
}
|
|
195
|
+
if (answer === 'a') {
|
|
117
196
|
engine.setPermissionMode('auto');
|
|
197
|
+
if (remembered) {
|
|
198
|
+
remembered.autoUntil = Date.now() + 3600000;
|
|
199
|
+
store.save(remembered);
|
|
200
|
+
scheduleGrant();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
118
203
|
audit.record('session.pairing-decision', { allowed, fingerprint });
|
|
119
204
|
return allowed;
|
|
120
205
|
} });
|
|
121
206
|
engine = new ProbeEngine(peer, async (request) => {
|
|
122
207
|
console.log(`\n[${request.stage === 'execute' ? 'EXECUTION APPROVAL' : 'TRANSFER APPROVAL'}] ${request.task.operation}\nTask: ${request.task.id}\nSHA256: ${request.digest}\n${safeText(request.preview)}\n`);
|
|
123
208
|
return ask(request.stage === 'execute' ? 'Allow exactly this operation? Commands run with your OS permissions.' : `Send these results (${request.bytes ?? 0} output bytes plus metadata)?`, request.signal, true);
|
|
124
|
-
}, audit, message => console.log(safeText(message)), { resources, idleMs: idleMinutes * 60000, lifetimeMs: sessionMinutes * 60000 });
|
|
209
|
+
}, audit, message => console.log(safeText(message)), { resources, idleMs: remembered ? 0 : idleMinutes * 60000, lifetimeMs: remembered ? 0 : sessionMinutes * 60000 });
|
|
210
|
+
const scheduleGrant = () => { clearTimeout(grantTimer); if (remembered && automatic(remembered)) {
|
|
211
|
+
engine.setPermissionMode('auto');
|
|
212
|
+
if (remembered.autoUntil !== null)
|
|
213
|
+
grantTimer = setTimeout(() => { remembered.autoUntil = 0; store.save(remembered); engine.setPermissionMode('ask'); }, Math.max(1, remembered.autoUntil - Date.now()));
|
|
214
|
+
} };
|
|
215
|
+
scheduleGrant();
|
|
125
216
|
let active = false, autoRequestedAt = 0;
|
|
126
|
-
peer.on('active', () => { active = true; console.log(`Session permissions: ${engine.permissionMode}. Local commands: permissions, permissions auto, permissions ask, jobs, recover <id>, secret <id>, cancel, exit.`); });
|
|
217
|
+
peer.on('active', () => { active = true; console.log(`Session permissions: ${engine.permissionMode}. Local commands: pairing, pause, resume, unpair, permissions, permissions auto [forever], permissions ask, jobs, recover <id>, secret <id>, cancel, exit.`); });
|
|
127
218
|
localCommand = value => {
|
|
128
|
-
if (
|
|
219
|
+
if (['pairing', 'pause', 'resume', 'unpair'].includes(value)) {
|
|
220
|
+
if (value === 'pairing') {
|
|
221
|
+
console.log(remembered ? `Paired with: ${safeText(remembered.label)} (${remembered.id}); ${remembered.paused ? 'paused' : 'available'}; auto: ${automatic(remembered) ? remembered.autoUntil === null ? 'until revoked' : new Date(remembered.autoUntil).toISOString() : 'off'}` : 'No remembered diagnostician');
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
if (!remembered) {
|
|
225
|
+
console.log('No remembered diagnostician');
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
if (value === 'unpair') {
|
|
229
|
+
store.remove(remembered.id);
|
|
230
|
+
audit.record('pairing.revoked', { id: remembered.id });
|
|
231
|
+
remembered = undefined;
|
|
232
|
+
engine.cancelAll();
|
|
233
|
+
void resources.revoke();
|
|
234
|
+
peer.close('Pairing revoked locally');
|
|
235
|
+
console.log('Pairing revoked. A new code will be generated.');
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
remembered.paused = value === 'pause';
|
|
239
|
+
store.save(remembered);
|
|
240
|
+
audit.record('pairing.' + value, { id: remembered.id });
|
|
241
|
+
if (remembered.paused) {
|
|
242
|
+
engine.cancelAll();
|
|
243
|
+
void resources.revoke();
|
|
244
|
+
peer.close('Paused locally');
|
|
245
|
+
}
|
|
246
|
+
console.log(value === 'pause' ? 'Remote access paused. Type resume to allow connections.' : 'Remote access resumed.');
|
|
247
|
+
}
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
if (!active && !value.startsWith('permissions') && !['jobs', 'cancel', 'exit', 'permissions ask'].includes(value) && !value.startsWith('recover ') && !value.startsWith('secret '))
|
|
129
251
|
return false;
|
|
130
252
|
if (value === 'permissions') {
|
|
131
253
|
console.log(`Permission mode: ${engine.permissionMode}. AUTO means automatic execution AND transmission to the diagnostician/AI. Use permissions ask to revoke and cancel active work.`);
|
|
132
254
|
return true;
|
|
133
255
|
}
|
|
134
|
-
if (value === 'permissions auto') {
|
|
135
|
-
autoRequestedAt = Date.now();
|
|
136
|
-
console.log('AUTO
|
|
256
|
+
if (value === 'permissions auto' || value === 'permissions auto forever') {
|
|
257
|
+
autoRequestedAt = value.endsWith(' forever') ? -Date.now() : Date.now();
|
|
258
|
+
console.log((remembered ? (autoRequestedAt < 0 ? 'AUTO UNTIL REVOKED, including future connections and probe restarts. ' : 'AUTO FOR ONE HOUR, including future connections and probe restarts. ') : 'AUTO FOR THIS TEMPORARY SESSION. ') + 'Grants automatic execution with your OS permissions AND automatic result transmission. Binary output is not redacted. Type "permissions allow-auto" within 60 seconds to grant, or "permissions ask" to decline.');
|
|
137
259
|
return true;
|
|
138
260
|
}
|
|
139
261
|
if (value === 'permissions allow-auto') {
|
|
140
|
-
if (autoRequestedAt && Date.now() - autoRequestedAt < 60000) {
|
|
262
|
+
if (autoRequestedAt && Date.now() - Math.abs(autoRequestedAt) < 60000) {
|
|
141
263
|
engine.setPermissionMode('auto');
|
|
264
|
+
if (remembered) {
|
|
265
|
+
remembered.autoUntil = autoRequestedAt < 0 ? null : Date.now() + 3600000;
|
|
266
|
+
store.save(remembered);
|
|
267
|
+
scheduleGrant();
|
|
268
|
+
console.log(remembered.autoUntil === null ? 'AUTO persists until revoked locally.' : 'AUTO expires in one hour, including time disconnected.');
|
|
269
|
+
}
|
|
142
270
|
autoRequestedAt = 0;
|
|
143
271
|
}
|
|
144
272
|
else
|
|
@@ -147,7 +275,13 @@ async function main() {
|
|
|
147
275
|
}
|
|
148
276
|
if (value === 'permissions ask') {
|
|
149
277
|
autoRequestedAt = 0;
|
|
278
|
+
clearTimeout(grantTimer);
|
|
279
|
+
if (remembered) {
|
|
280
|
+
remembered.autoUntil = 0;
|
|
281
|
+
store.save(remembered);
|
|
282
|
+
}
|
|
150
283
|
engine.setPermissionMode('ask');
|
|
284
|
+
engine.cancelAll();
|
|
151
285
|
void resources.revoke().catch(error => console.error(safeText(error.message)));
|
|
152
286
|
console.log('Approval required. Automatic permissions revoked; any active work is cancelled.');
|
|
153
287
|
return true;
|
|
@@ -212,7 +346,7 @@ async function main() {
|
|
|
212
346
|
rl.on('line', onLocalLine);
|
|
213
347
|
try {
|
|
214
348
|
await peer.open();
|
|
215
|
-
console.log(`Relay: ${relay}\nAudit: ${audit.path}\nPairing code (10 minutes, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
|
|
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 (10 minutes, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
|
|
216
350
|
console.log(`Session ended: ${safeText(await peer.ended)}`);
|
|
217
351
|
}
|
|
218
352
|
catch (error) {
|
|
@@ -221,20 +355,37 @@ async function main() {
|
|
|
221
355
|
await delay(3000, undefined, { signal: shutdown.signal }).catch(() => { });
|
|
222
356
|
}
|
|
223
357
|
finally {
|
|
358
|
+
clearTimeout(grantTimer);
|
|
224
359
|
rl.off('line', onLocalLine);
|
|
225
360
|
}
|
|
226
361
|
active = false;
|
|
227
362
|
if (secretPending)
|
|
228
363
|
await secretPending;
|
|
229
|
-
if (!shutdown.signal.aborted)
|
|
230
|
-
console.log('Probe is still running.
|
|
364
|
+
if (!shutdown.signal.aborted) {
|
|
365
|
+
console.log('Probe is still running. Remembered pairing survives reconnects; commands are never replayed. Ctrl+C stops access and closes resources; trust remains until unpair.');
|
|
366
|
+
await delay(300, undefined, { signal: shutdown.signal }).catch(() => { });
|
|
367
|
+
}
|
|
231
368
|
}
|
|
232
369
|
}
|
|
233
370
|
else {
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
371
|
+
const store = new PairingStore(join(homedir(), '.diagnose', 'pairings'));
|
|
372
|
+
if (command === 'pair' && (!values.name || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(values.name)))
|
|
373
|
+
throw new Error('Use pair --name NAME (letters, numbers, underscores or hyphens)');
|
|
374
|
+
if (command === 'pair' && store.list('operator').some(value => value.name === values.name))
|
|
375
|
+
throw new Error('Device name already exists');
|
|
376
|
+
const saved = values.device ? store.get(values.device, 'operator') : undefined;
|
|
377
|
+
const code = saved?.code ?? (await rl.question('Pairing code: ', { signal: shutdown.signal })).trim();
|
|
378
|
+
const label = saved?.label ?? await rl.question('Your label / AI provider: ', { signal: shutdown.signal });
|
|
379
|
+
peer = saved ? (await new RememberedConnection(saved).connect()).peer : new Peer({ role: 'join', code, relay, label, remember: command === 'pair' });
|
|
237
380
|
const operator = new Operator(peer);
|
|
381
|
+
if (command === 'pair') {
|
|
382
|
+
await peer.open();
|
|
383
|
+
if (!peer.rememberedCode)
|
|
384
|
+
throw new Error('Probe did not support or grant remembered pairing; update both endpoints');
|
|
385
|
+
store.add({ role: 'operator', name: values.name, label, relay, code: peer.rememberedCode });
|
|
386
|
+
console.log(`Paired. Start diagnosis with: diagnose agent codex --device ${values.name}`);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
238
389
|
if (command === 'terminal') {
|
|
239
390
|
await peer.open();
|
|
240
391
|
const result = await operator.run({ operation: 'process.open', arguments: { pty: true }, reason: 'Open an interactive terminal with continuing raw input/output and persistent shell context' });
|
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(), protocol: 1, version: '0.4.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
|
@@ -22,6 +22,8 @@ export class ProbeEngine {
|
|
|
22
22
|
notice;
|
|
23
23
|
jobs = new Map();
|
|
24
24
|
seen = new Set();
|
|
25
|
+
sequence = 0;
|
|
26
|
+
sequenced;
|
|
25
27
|
idle;
|
|
26
28
|
lifetime;
|
|
27
29
|
mode = 'ask';
|
|
@@ -83,17 +85,39 @@ export class ProbeEngine {
|
|
|
83
85
|
return;
|
|
84
86
|
}
|
|
85
87
|
const task = message.task;
|
|
86
|
-
|
|
88
|
+
this.sequenced ??= message.sequence !== undefined;
|
|
89
|
+
if (this.sequenced !== (message.sequence !== undefined)) {
|
|
90
|
+
peer.close('Task sequence mode cannot change');
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (message.sequence !== undefined) {
|
|
94
|
+
if (message.sequence <= this.sequence) {
|
|
95
|
+
void this.reply(task.id, { status: 'duplicate' });
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
this.sequence = message.sequence;
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
if (this.seen.has(task.id)) {
|
|
102
|
+
void this.reply(task.id, { status: 'duplicate' });
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (this.seen.size >= 1000) {
|
|
106
|
+
void this.reply(task.id, { status: 'error', error: 'Legacy client task limit: reconnect and update both endpoints to 0.5.0+. This request was not executed.' });
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
this.seen.add(task.id);
|
|
110
|
+
}
|
|
111
|
+
if (this.jobs.has(task.id)) {
|
|
87
112
|
void this.reply(task.id, { status: 'duplicate' });
|
|
88
113
|
return;
|
|
89
114
|
}
|
|
90
|
-
if (this.jobs.size >= 4
|
|
91
|
-
void this.reply(task.id, { status: 'error', error: 'Four
|
|
115
|
+
if (this.jobs.size >= 4) {
|
|
116
|
+
void this.reply(task.id, { status: 'error', error: 'Four tasks are active; wait for completion before submitting new work' });
|
|
92
117
|
return;
|
|
93
118
|
}
|
|
94
119
|
const controller = new AbortController();
|
|
95
120
|
this.jobs.set(task.id, controller);
|
|
96
|
-
this.seen.add(task.id);
|
|
97
121
|
void this.run(task, controller);
|
|
98
122
|
});
|
|
99
123
|
peer.on('closed', () => { clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values())
|
|
@@ -111,6 +135,7 @@ export class ProbeEngine {
|
|
|
111
135
|
}
|
|
112
136
|
async decidePermission(request) {
|
|
113
137
|
request.signal.throwIfAborted();
|
|
138
|
+
this.audit.history.event(request.task.id, 'approval-preview', { stage: request.stage, digest: request.digest, preview: request.preview });
|
|
114
139
|
if (this.mode === 'auto') {
|
|
115
140
|
this.audit.record('task.auto-approved', { id: request.task.id, stage: request.stage, digest: request.digest, ...(request.bytes === undefined ? {} : { bytes: request.bytes }) });
|
|
116
141
|
this.notice(`[AUTO ${request.stage}] ${request.task.operation} ${request.task.id}\n${safeText(request.preview.slice(0, 8192))}${request.preview.length > 8192 ? '\n[Terminal preview truncated; task digest and byte counts are audited.]' : ''}`);
|
|
@@ -203,6 +228,7 @@ export class ProbeEngine {
|
|
|
203
228
|
const { signal } = controller;
|
|
204
229
|
const hash = digest(task);
|
|
205
230
|
try {
|
|
231
|
+
this.audit.history.begin(task);
|
|
206
232
|
const steps = task.operation === 'batch.run' ? task.arguments.steps : [task];
|
|
207
233
|
if (task.operation === 'batch.run' && steps.some(step => resourceOperation(step.operation)))
|
|
208
234
|
throw new Error('Open interactive/transfer/forward resources separately; their subsequent actions share one approved scope');
|
|
@@ -232,6 +258,7 @@ export class ProbeEngine {
|
|
|
232
258
|
this.audit.record('task.approved', { id: task.id, digest: hash, mode: this.mode });
|
|
233
259
|
await this.peer.send({ type: 'task.started', id: task.id, digest: hash });
|
|
234
260
|
const execution = task.operation === 'batch.run' ? await this.runBatch(task, signal, writes, hash) : await this.runAtomic(task, signal, writes.get(task.id));
|
|
261
|
+
this.audit.history.collected(task.id, execution);
|
|
235
262
|
const count = execution.outputs.reduce((sum, item) => sum + item.bytes.length, 0);
|
|
236
263
|
if (task.operation === 'batch.run')
|
|
237
264
|
this.audit.record('task.collected', { id: task.id, bytes: count, status: execution.result.status });
|
|
@@ -261,6 +288,12 @@ export class ProbeEngine {
|
|
|
261
288
|
}
|
|
262
289
|
finally {
|
|
263
290
|
this.jobs.delete(task.id);
|
|
291
|
+
try {
|
|
292
|
+
this.audit.history.finish(task.id);
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
this.peer.close('Local history unavailable');
|
|
296
|
+
}
|
|
264
297
|
}
|
|
265
298
|
}
|
|
266
299
|
async transfer(id, execution, signal) {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Journal } from './journal.js';
|
|
2
|
+
import type { Task } from './schema.js';
|
|
3
|
+
import type { Execution } from './executor.js';
|
|
4
|
+
export declare class History {
|
|
5
|
+
readonly journal: Journal;
|
|
6
|
+
constructor(root?: string);
|
|
7
|
+
begin(task: Task): void;
|
|
8
|
+
event(id: string, event: string, details: unknown): void;
|
|
9
|
+
collected(id: string, execution: Execution): void;
|
|
10
|
+
finish(id: string): void;
|
|
11
|
+
list(): unknown[];
|
|
12
|
+
show(id: string, resourceCursor?: number): unknown;
|
|
13
|
+
}
|
package/dist/history.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
import { Journal, retention } from './journal.js';
|
|
6
|
+
// Local-only evidence. Never exposed as a remote MCP tool. Exact task contents
|
|
7
|
+
// may contain secrets; payloads are encrypted and expire under a bounded budget.
|
|
8
|
+
export class History {
|
|
9
|
+
journal;
|
|
10
|
+
constructor(root = join(homedir(), '.diagnose', 'history')) { this.journal = new Journal(root, retention); }
|
|
11
|
+
begin(task) {
|
|
12
|
+
const now = new Date().toISOString();
|
|
13
|
+
const request = task.operation === 'resource.resume' ? { ...task, arguments: { ...task.arguments, resumeToken: '[RECOVERY CREDENTIAL OMITTED]' } } : task;
|
|
14
|
+
this.journal.save({ id: task.id, kind: 'process', state: 'running', createdAt: now, updatedAt: now, ownerPid: process.pid, tokenHash: '', retainOnDisconnect: false, operation: task.operation, reason: task.reason, request });
|
|
15
|
+
}
|
|
16
|
+
event(id, event, details) {
|
|
17
|
+
if (!this.journal.exists(id))
|
|
18
|
+
return;
|
|
19
|
+
this.journal.append(id, 'events', Buffer.from(JSON.stringify({ at: new Date().toISOString(), event, details }) + '\n'));
|
|
20
|
+
}
|
|
21
|
+
collected(id, execution) {
|
|
22
|
+
const result = structuredClone(execution.result);
|
|
23
|
+
if (result.data && typeof result.data === 'object')
|
|
24
|
+
delete result.data.resumeToken;
|
|
25
|
+
this.event(id, 'collected', { result, streams: execution.outputs.map(({ stream, encoding }) => ({ stream, encoding })) });
|
|
26
|
+
for (const output of execution.outputs)
|
|
27
|
+
this.journal.append(id, output.stream, output.bytes);
|
|
28
|
+
}
|
|
29
|
+
finish(id) { if (this.journal.exists(id)) {
|
|
30
|
+
const meta = this.journal.load(id);
|
|
31
|
+
meta.state = 'completed';
|
|
32
|
+
this.journal.save(meta);
|
|
33
|
+
} }
|
|
34
|
+
list() { return this.journal.list().sort((a, b) => b.createdAt.localeCompare(a.createdAt)).map(({ id, createdAt, operation, reason, state }) => ({ id, createdAt, operation, reason, state })); }
|
|
35
|
+
show(id, resourceCursor = 0) {
|
|
36
|
+
const resourceRoot = join(dirname(this.journal.root), 'resources');
|
|
37
|
+
const resources = existsSync(resourceRoot) ? new Journal(resourceRoot) : undefined;
|
|
38
|
+
const resource = resources?.exists(id) ? resources.load(id) : undefined;
|
|
39
|
+
const meta = this.journal.exists(id) ? this.journal.load(id) : resource;
|
|
40
|
+
if (!meta)
|
|
41
|
+
throw new Error('Unknown or expired history ID');
|
|
42
|
+
const streams = {};
|
|
43
|
+
let cursor = 0;
|
|
44
|
+
while (true) {
|
|
45
|
+
const page = this.journal.read(id, cursor);
|
|
46
|
+
for (const record of page.records)
|
|
47
|
+
(streams[record.stream] ??= []).push(Buffer.from(record.data, 'base64'));
|
|
48
|
+
cursor = page.cursor;
|
|
49
|
+
if (!page.hasMore)
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
const events = Buffer.concat(streams.events ?? []).toString('utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line));
|
|
53
|
+
delete streams.events;
|
|
54
|
+
const collected = events.find(item => item.event === 'collected');
|
|
55
|
+
return { id, createdAt: meta.createdAt, state: meta.state, request: meta.request, events, ...(resource?.kind === 'process' ? { resourceOutput: resources.read(id, resourceCursor) } : {}), outputs: Object.fromEntries(Object.entries(streams).map(([name, chunks]) => { const encoding = collected?.details.streams.find((stream) => stream.stream === name)?.encoding ?? 'base64'; return [name, { encoding, data: Buffer.concat(chunks).toString(encoding === 'utf8' ? 'utf8' : 'base64') }]; })) };
|
|
56
|
+
}
|
|
57
|
+
}
|
package/dist/journal.d.ts
CHANGED
|
@@ -13,10 +13,32 @@ export type OutputRecord = {
|
|
|
13
13
|
stream: string;
|
|
14
14
|
data: string;
|
|
15
15
|
};
|
|
16
|
+
export declare const retention: {
|
|
17
|
+
maxBytes: number;
|
|
18
|
+
maxEntries: number;
|
|
19
|
+
maxAgeMs: number;
|
|
20
|
+
};
|
|
21
|
+
export type JournalLimits = typeof retention;
|
|
22
|
+
export declare function live(meta: ResourceMeta): boolean;
|
|
16
23
|
export declare class Journal {
|
|
17
24
|
readonly root: string;
|
|
25
|
+
private limits?;
|
|
18
26
|
private key;
|
|
19
|
-
|
|
27
|
+
private bytes;
|
|
28
|
+
private entries;
|
|
29
|
+
private checkedAt;
|
|
30
|
+
constructor(root: string, limits?: JournalLimits | undefined);
|
|
31
|
+
list(): ResourceMeta[];
|
|
32
|
+
cleanup(limits?: {
|
|
33
|
+
maxBytes: number;
|
|
34
|
+
maxEntries: number;
|
|
35
|
+
maxAgeMs: number;
|
|
36
|
+
}, keep?: string): {
|
|
37
|
+
removed: number;
|
|
38
|
+
bytes: number;
|
|
39
|
+
entries: number;
|
|
40
|
+
};
|
|
41
|
+
private reserve;
|
|
20
42
|
private path;
|
|
21
43
|
private seal;
|
|
22
44
|
private unseal;
|