@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
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';
|
|
@@ -15,7 +15,12 @@ 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';
|
|
22
|
+
import { skillsCommand, skillsUsage } from './skill-library.js';
|
|
23
|
+
import { knowledgeCommand, knowledgeUsage } from './knowledge-cli.js';
|
|
19
24
|
async function attachTerminal(operator, id) {
|
|
20
25
|
let done = false, cursor = 0;
|
|
21
26
|
const wasRaw = stdin.isRaw;
|
|
@@ -51,23 +56,56 @@ async function attachTerminal(operator, id) {
|
|
|
51
56
|
}
|
|
52
57
|
}
|
|
53
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
|
+
}
|
|
54
67
|
if (process.argv[2] === 'agent') {
|
|
55
68
|
process.exitCode = await launchAgent(process.argv.slice(3));
|
|
56
69
|
return;
|
|
57
70
|
}
|
|
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' } } });
|
|
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' } } });
|
|
59
72
|
const [command = 'help', relay = 'https://diagnose.fenginwind.com'] = positionals;
|
|
73
|
+
if (command === 'history') {
|
|
74
|
+
console.log(safeText(JSON.stringify(new History().list(), null, 2)));
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (command === 'show') {
|
|
78
|
+
const cursor = Number(values.cursor);
|
|
79
|
+
if (!Number.isSafeInteger(cursor) || cursor < 0)
|
|
80
|
+
throw new Error('Cursor must be a nonnegative integer');
|
|
81
|
+
console.log(safeText(JSON.stringify(new History().show(positionals[1] ?? '', cursor), null, 2)));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (command === 'cleanup') {
|
|
85
|
+
console.log(JSON.stringify(cleanupLocal(Number(values.days)), null, 2));
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
60
88
|
if (positionals.length > 2)
|
|
61
89
|
throw new Error('Usage: diagnose start|connect|terminal|mcp [relay-url]');
|
|
62
90
|
const sessionMinutes = Number(values['session-minutes']), idleMinutes = Number(values['idle-minutes']);
|
|
63
91
|
if (![sessionMinutes, idleMinutes].every(value => Number.isInteger(value) && value >= 0 && value <= 10080))
|
|
64
92
|
throw new Error('Timeouts must be 0..10080 minutes; 0 disables endpoint timeout (relay maximum 7 days)');
|
|
93
|
+
if (command === 'devices') {
|
|
94
|
+
console.log(JSON.stringify(new PairingStore(join(homedir(), '.diagnose', 'pairings')).list('operator').map(({ name, id, relay }) => ({ name, id, relay })), null, 2));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (command === 'forget') {
|
|
98
|
+
const store = new PairingStore(join(homedir(), '.diagnose', 'pairings'));
|
|
99
|
+
store.remove(store.get(values.device ?? '', 'operator').id);
|
|
100
|
+
console.log('Local pairing removed. Revoke on the user computer to invalidate its credential.');
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
65
103
|
if (command === 'mcp') {
|
|
66
|
-
await serveMcp(relay);
|
|
104
|
+
await serveMcp(relay, values.device, values.case);
|
|
67
105
|
return;
|
|
68
106
|
}
|
|
69
|
-
if (!['start', 'connect', 'terminal'].includes(command)) {
|
|
70
|
-
console.log(`diagnose start|connect|terminal|mcp [relay-url]\n${agentUsage}\nNode.js >=
|
|
107
|
+
if (!['start', 'connect', 'terminal', 'pair'].includes(command)) {
|
|
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.`);
|
|
71
109
|
return;
|
|
72
110
|
}
|
|
73
111
|
if (!stdin.isTTY || !stdout.isTTY)
|
|
@@ -102,43 +140,143 @@ async function main() {
|
|
|
102
140
|
};
|
|
103
141
|
try {
|
|
104
142
|
if (command === 'start') {
|
|
143
|
+
const store = new PairingStore();
|
|
144
|
+
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
145
|
const firstAudit = new Audit();
|
|
106
146
|
resources = new SessionResources(join(homedir(), '.diagnose', 'resources'), firstAudit);
|
|
107
147
|
let sessions = 0;
|
|
108
148
|
while (!shutdown.signal.aborted) {
|
|
149
|
+
let remembered = store.list('host')[0];
|
|
150
|
+
if (remembered?.paused) {
|
|
151
|
+
console.log('Remote access is paused. Type resume, unpair, or exit.');
|
|
152
|
+
const controls = (line) => { if (line.trim() === 'resume') {
|
|
153
|
+
remembered.paused = false;
|
|
154
|
+
store.save(remembered);
|
|
155
|
+
firstAudit.record('pairing.resume', { id: remembered.id });
|
|
156
|
+
}
|
|
157
|
+
else if (line.trim() === 'unpair') {
|
|
158
|
+
store.remove(remembered.id);
|
|
159
|
+
firstAudit.record('pairing.revoked', { id: remembered.id });
|
|
160
|
+
remembered = undefined;
|
|
161
|
+
}
|
|
162
|
+
else if (line.trim() === 'permissions ask') {
|
|
163
|
+
remembered.autoUntil = 0;
|
|
164
|
+
store.save(remembered);
|
|
165
|
+
firstAudit.record('permissions.revoked', { id: remembered.id });
|
|
166
|
+
console.log('Automatic permissions revoked; access remains paused.');
|
|
167
|
+
}
|
|
168
|
+
else if (line.trim() === 'exit')
|
|
169
|
+
stop();
|
|
170
|
+
else
|
|
171
|
+
console.log('Access paused. Type resume, unpair, permissions ask, or exit.'); };
|
|
172
|
+
rl.on('line', controls);
|
|
173
|
+
try {
|
|
174
|
+
while (remembered?.paused && !shutdown.signal.aborted) {
|
|
175
|
+
await delay(300, undefined, { signal: shutdown.signal }).catch(() => { });
|
|
176
|
+
remembered = store.list('host')[0];
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
rl.off('line', controls);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (shutdown.signal.aborted)
|
|
184
|
+
break;
|
|
109
185
|
const audit = sessions++ === 0 ? firstAudit : new Audit();
|
|
110
|
-
const code =
|
|
111
|
-
|
|
186
|
+
const code = remembered?.code ?? createInvitation();
|
|
187
|
+
let provision;
|
|
188
|
+
let grantTimer;
|
|
189
|
+
peer = new Peer({ role: 'host', code, relay: remembered?.relay ?? relay, sessionMs: remembered ? 0 : sessionMinutes * 60000, provision: () => provision, accept: async ({ label, fingerprint, signal, remember }) => {
|
|
190
|
+
if (remembered) {
|
|
191
|
+
audit.record('pairing.reconnected', { id: remembered.id });
|
|
192
|
+
return !remembered.paused;
|
|
193
|
+
}
|
|
194
|
+
if (remember)
|
|
195
|
+
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
196
|
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();
|
|
197
|
+
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.');
|
|
198
|
+
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
199
|
const allowed = answer === 'y' || answer === 'a';
|
|
116
|
-
if (
|
|
200
|
+
if (allowed && remember) {
|
|
201
|
+
provision = createCode();
|
|
202
|
+
remembered = store.add({ role: 'host', name: 'diagnostician', label, relay, code: provision });
|
|
203
|
+
audit.record('pairing.remembered', { id: remembered.id });
|
|
204
|
+
}
|
|
205
|
+
if (answer === 'a') {
|
|
117
206
|
engine.setPermissionMode('auto');
|
|
207
|
+
if (remembered) {
|
|
208
|
+
remembered.autoUntil = Date.now() + 3600000;
|
|
209
|
+
store.save(remembered);
|
|
210
|
+
scheduleGrant();
|
|
211
|
+
}
|
|
212
|
+
}
|
|
118
213
|
audit.record('session.pairing-decision', { allowed, fingerprint });
|
|
119
214
|
return allowed;
|
|
120
215
|
} });
|
|
121
216
|
engine = new ProbeEngine(peer, async (request) => {
|
|
122
217
|
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
218
|
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 });
|
|
219
|
+
}, audit, message => console.log(safeText(message)), { resources, idleMs: remembered ? 0 : idleMinutes * 60000, lifetimeMs: remembered ? 0 : sessionMinutes * 60000 });
|
|
220
|
+
const scheduleGrant = () => { clearTimeout(grantTimer); if (remembered && automatic(remembered)) {
|
|
221
|
+
engine.setPermissionMode('auto');
|
|
222
|
+
if (remembered.autoUntil !== null)
|
|
223
|
+
grantTimer = setTimeout(() => { remembered.autoUntil = 0; store.save(remembered); engine.setPermissionMode('ask'); }, Math.max(1, remembered.autoUntil - Date.now()));
|
|
224
|
+
} };
|
|
225
|
+
scheduleGrant();
|
|
125
226
|
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.`); });
|
|
227
|
+
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
228
|
localCommand = value => {
|
|
128
|
-
if (
|
|
229
|
+
if (['pairing', 'pause', 'resume', 'unpair'].includes(value)) {
|
|
230
|
+
if (value === 'pairing') {
|
|
231
|
+
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');
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
if (!remembered) {
|
|
235
|
+
console.log('No remembered diagnostician');
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
if (value === 'unpair') {
|
|
239
|
+
store.remove(remembered.id);
|
|
240
|
+
audit.record('pairing.revoked', { id: remembered.id });
|
|
241
|
+
remembered = undefined;
|
|
242
|
+
engine.cancelAll();
|
|
243
|
+
void resources.revoke();
|
|
244
|
+
peer.close('Pairing revoked locally');
|
|
245
|
+
console.log('Pairing revoked. A new code will be generated.');
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
remembered.paused = value === 'pause';
|
|
249
|
+
store.save(remembered);
|
|
250
|
+
audit.record('pairing.' + value, { id: remembered.id });
|
|
251
|
+
if (remembered.paused) {
|
|
252
|
+
engine.cancelAll();
|
|
253
|
+
void resources.revoke();
|
|
254
|
+
peer.close('Paused locally');
|
|
255
|
+
}
|
|
256
|
+
console.log(value === 'pause' ? 'Remote access paused. Type resume to allow connections.' : 'Remote access resumed.');
|
|
257
|
+
}
|
|
258
|
+
return true;
|
|
259
|
+
}
|
|
260
|
+
if (!active && !value.startsWith('permissions') && !['jobs', 'cancel', 'exit', 'permissions ask'].includes(value) && !value.startsWith('recover ') && !value.startsWith('secret '))
|
|
129
261
|
return false;
|
|
130
262
|
if (value === 'permissions') {
|
|
131
263
|
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
264
|
return true;
|
|
133
265
|
}
|
|
134
|
-
if (value === 'permissions auto') {
|
|
135
|
-
autoRequestedAt = Date.now();
|
|
136
|
-
console.log('AUTO
|
|
266
|
+
if (value === 'permissions auto' || value === 'permissions auto forever') {
|
|
267
|
+
autoRequestedAt = value.endsWith(' forever') ? -Date.now() : Date.now();
|
|
268
|
+
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
269
|
return true;
|
|
138
270
|
}
|
|
139
271
|
if (value === 'permissions allow-auto') {
|
|
140
|
-
if (autoRequestedAt && Date.now() - autoRequestedAt < 60000) {
|
|
272
|
+
if (autoRequestedAt && Date.now() - Math.abs(autoRequestedAt) < 60000) {
|
|
141
273
|
engine.setPermissionMode('auto');
|
|
274
|
+
if (remembered) {
|
|
275
|
+
remembered.autoUntil = autoRequestedAt < 0 ? null : Date.now() + 3600000;
|
|
276
|
+
store.save(remembered);
|
|
277
|
+
scheduleGrant();
|
|
278
|
+
console.log(remembered.autoUntil === null ? 'AUTO persists until revoked locally.' : 'AUTO expires in one hour, including time disconnected.');
|
|
279
|
+
}
|
|
142
280
|
autoRequestedAt = 0;
|
|
143
281
|
}
|
|
144
282
|
else
|
|
@@ -147,7 +285,13 @@ async function main() {
|
|
|
147
285
|
}
|
|
148
286
|
if (value === 'permissions ask') {
|
|
149
287
|
autoRequestedAt = 0;
|
|
288
|
+
clearTimeout(grantTimer);
|
|
289
|
+
if (remembered) {
|
|
290
|
+
remembered.autoUntil = 0;
|
|
291
|
+
store.save(remembered);
|
|
292
|
+
}
|
|
150
293
|
engine.setPermissionMode('ask');
|
|
294
|
+
engine.cancelAll();
|
|
151
295
|
void resources.revoke().catch(error => console.error(safeText(error.message)));
|
|
152
296
|
console.log('Approval required. Automatic permissions revoked; any active work is cancelled.');
|
|
153
297
|
return true;
|
|
@@ -212,29 +356,47 @@ async function main() {
|
|
|
212
356
|
rl.on('line', onLocalLine);
|
|
213
357
|
try {
|
|
214
358
|
await peer.open();
|
|
215
|
-
console.log(`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.`);
|
|
216
360
|
console.log(`Session ended: ${safeText(await peer.ended)}`);
|
|
217
361
|
}
|
|
218
362
|
catch (error) {
|
|
363
|
+
const collision = error.message.includes('Invitation locator occupied');
|
|
219
364
|
if (!shutdown.signal.aborted)
|
|
220
|
-
console.log(`Relay unavailable: ${safeText(error.message)}. Retained work remains local; retrying in 3 seconds.`);
|
|
221
|
-
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(() => { });
|
|
222
367
|
}
|
|
223
368
|
finally {
|
|
369
|
+
clearTimeout(grantTimer);
|
|
224
370
|
rl.off('line', onLocalLine);
|
|
225
371
|
}
|
|
226
372
|
active = false;
|
|
227
373
|
if (secretPending)
|
|
228
374
|
await secretPending;
|
|
229
|
-
if (!shutdown.signal.aborted)
|
|
230
|
-
console.log('Probe is still running.
|
|
375
|
+
if (!shutdown.signal.aborted) {
|
|
376
|
+
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.');
|
|
377
|
+
await delay(300, undefined, { signal: shutdown.signal }).catch(() => { });
|
|
378
|
+
}
|
|
231
379
|
}
|
|
232
380
|
}
|
|
233
381
|
else {
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
382
|
+
const store = new PairingStore(join(homedir(), '.diagnose', 'pairings'));
|
|
383
|
+
if (command === 'pair' && (!values.name || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(values.name)))
|
|
384
|
+
throw new Error('Use pair --name NAME (letters, numbers, underscores or hyphens)');
|
|
385
|
+
if (command === 'pair' && store.list('operator').some(value => value.name === values.name))
|
|
386
|
+
throw new Error('Device name already exists');
|
|
387
|
+
const saved = values.device ? store.get(values.device, 'operator') : undefined;
|
|
388
|
+
const code = saved?.code ?? (await rl.question('Pairing code: ', { signal: shutdown.signal })).trim();
|
|
389
|
+
const label = saved?.label ?? await rl.question('Your label / AI provider: ', { signal: shutdown.signal });
|
|
390
|
+
peer = saved ? (await new RememberedConnection(saved).connect()).peer : new Peer({ role: 'join', code, relay, label, remember: command === 'pair' });
|
|
237
391
|
const operator = new Operator(peer);
|
|
392
|
+
if (command === 'pair') {
|
|
393
|
+
await peer.open();
|
|
394
|
+
if (!peer.rememberedCode)
|
|
395
|
+
throw new Error('Probe did not support or grant remembered pairing; update both endpoints');
|
|
396
|
+
store.add({ role: 'operator', name: values.name, label, relay, code: peer.rememberedCode });
|
|
397
|
+
console.log(`Paired. Start diagnosis with: diagnose agent codex --device ${values.name}`);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
238
400
|
if (command === 'terminal') {
|
|
239
401
|
await peer.open();
|
|
240
402
|
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/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
|
@@ -10,8 +10,11 @@ export declare class ProbeEngine {
|
|
|
10
10
|
private notice;
|
|
11
11
|
private jobs;
|
|
12
12
|
private seen;
|
|
13
|
+
private sequence;
|
|
14
|
+
private sequenced?;
|
|
13
15
|
private idle?;
|
|
14
16
|
private lifetime?;
|
|
17
|
+
private ended;
|
|
15
18
|
private mode;
|
|
16
19
|
private owner;
|
|
17
20
|
readonly resources: SessionResources;
|
package/dist/engine.js
CHANGED
|
@@ -22,8 +22,11 @@ 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;
|
|
29
|
+
ended = false;
|
|
27
30
|
mode = 'ask';
|
|
28
31
|
owner = randomUUID();
|
|
29
32
|
resources;
|
|
@@ -57,10 +60,16 @@ export class ProbeEngine {
|
|
|
57
60
|
this.notice = notice;
|
|
58
61
|
this.resources = options.resources ?? new SessionResources(join(dirname(audit.path), basename(audit.path) + '.resources'), audit);
|
|
59
62
|
this.resources.setAudit(audit);
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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(() => { });
|
|
64
73
|
peer.on('message', (message) => {
|
|
65
74
|
this.idle?.refresh();
|
|
66
75
|
if (message.type === 'resource.request') {
|
|
@@ -83,20 +92,42 @@ export class ProbeEngine {
|
|
|
83
92
|
return;
|
|
84
93
|
}
|
|
85
94
|
const task = message.task;
|
|
86
|
-
|
|
95
|
+
this.sequenced ??= message.sequence !== undefined;
|
|
96
|
+
if (this.sequenced !== (message.sequence !== undefined)) {
|
|
97
|
+
peer.close('Task sequence mode cannot change');
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (message.sequence !== undefined) {
|
|
101
|
+
if (message.sequence <= this.sequence) {
|
|
102
|
+
void this.reply(task.id, { status: 'duplicate' });
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
this.sequence = message.sequence;
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
if (this.seen.has(task.id)) {
|
|
109
|
+
void this.reply(task.id, { status: 'duplicate' });
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (this.seen.size >= 1000) {
|
|
113
|
+
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.' });
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
this.seen.add(task.id);
|
|
117
|
+
}
|
|
118
|
+
if (this.jobs.has(task.id)) {
|
|
87
119
|
void this.reply(task.id, { status: 'duplicate' });
|
|
88
120
|
return;
|
|
89
121
|
}
|
|
90
|
-
if (this.jobs.size >= 4
|
|
91
|
-
void this.reply(task.id, { status: 'error', error: 'Four
|
|
122
|
+
if (this.jobs.size >= 4) {
|
|
123
|
+
void this.reply(task.id, { status: 'error', error: 'Four tasks are active; wait for completion before submitting new work' });
|
|
92
124
|
return;
|
|
93
125
|
}
|
|
94
126
|
const controller = new AbortController();
|
|
95
127
|
this.jobs.set(task.id, controller);
|
|
96
|
-
this.seen.add(task.id);
|
|
97
128
|
void this.run(task, controller);
|
|
98
129
|
});
|
|
99
|
-
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())
|
|
100
131
|
controller.abort(); void this.resources.disconnect(this.owner).catch(() => { }); try {
|
|
101
132
|
audit.record('session.closed', {});
|
|
102
133
|
}
|
|
@@ -111,6 +142,7 @@ export class ProbeEngine {
|
|
|
111
142
|
}
|
|
112
143
|
async decidePermission(request) {
|
|
113
144
|
request.signal.throwIfAborted();
|
|
145
|
+
this.audit.history.event(request.task.id, 'approval-preview', { stage: request.stage, digest: request.digest, preview: request.preview });
|
|
114
146
|
if (this.mode === 'auto') {
|
|
115
147
|
this.audit.record('task.auto-approved', { id: request.task.id, stage: request.stage, digest: request.digest, ...(request.bytes === undefined ? {} : { bytes: request.bytes }) });
|
|
116
148
|
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 +235,7 @@ export class ProbeEngine {
|
|
|
203
235
|
const { signal } = controller;
|
|
204
236
|
const hash = digest(task);
|
|
205
237
|
try {
|
|
238
|
+
this.audit.history.begin(task);
|
|
206
239
|
const steps = task.operation === 'batch.run' ? task.arguments.steps : [task];
|
|
207
240
|
if (task.operation === 'batch.run' && steps.some(step => resourceOperation(step.operation)))
|
|
208
241
|
throw new Error('Open interactive/transfer/forward resources separately; their subsequent actions share one approved scope');
|
|
@@ -232,6 +265,7 @@ export class ProbeEngine {
|
|
|
232
265
|
this.audit.record('task.approved', { id: task.id, digest: hash, mode: this.mode });
|
|
233
266
|
await this.peer.send({ type: 'task.started', id: task.id, digest: hash });
|
|
234
267
|
const execution = task.operation === 'batch.run' ? await this.runBatch(task, signal, writes, hash) : await this.runAtomic(task, signal, writes.get(task.id));
|
|
268
|
+
this.audit.history.collected(task.id, execution);
|
|
235
269
|
const count = execution.outputs.reduce((sum, item) => sum + item.bytes.length, 0);
|
|
236
270
|
if (task.operation === 'batch.run')
|
|
237
271
|
this.audit.record('task.collected', { id: task.id, bytes: count, status: execution.result.status });
|
|
@@ -261,6 +295,12 @@ export class ProbeEngine {
|
|
|
261
295
|
}
|
|
262
296
|
finally {
|
|
263
297
|
this.jobs.delete(task.id);
|
|
298
|
+
try {
|
|
299
|
+
this.audit.history.finish(task.id);
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
this.peer.close('Local history unavailable');
|
|
303
|
+
}
|
|
264
304
|
}
|
|
265
305
|
}
|
|
266
306
|
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;
|