@masstensor/diagnose 0.7.0 → 0.8.1
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/PAIRING_PROTOCOL.md +1 -1
- package/README.md +22 -8
- package/USER_GUIDE.md +33 -649
- package/dist/cli.js +44 -7
- package/dist/discover.js +1 -1
- package/dist/engine.js +15 -8
- package/dist/install-skill.d.ts +2 -0
- package/dist/install-skill.js +57 -0
- package/dist/mcp.js +27 -4
- package/dist/operator.js +2 -0
- package/dist/peer.d.ts +1 -0
- package/dist/peer.js +24 -3
- package/dist/relay.js +21 -8
- package/dist/schema.d.ts +4 -1
- package/dist/schema.js +2 -2
- package/dist/session-limits.d.ts +3 -0
- package/dist/session-limits.js +3 -0
- package/dist/skill-session.d.ts +1 -0
- package/dist/skill-session.js +272 -0
- package/docs/guide/automation.md +184 -0
- package/docs/guide/diagnose.md +93 -0
- package/docs/guide/on-site.md +139 -0
- package/docs/guide/procedures.md +183 -0
- package/docs/guide/reconnect.md +58 -0
- package/docs/guide/troubleshooting.md +77 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -1
- package/skills/connect/SKILL.md +66 -0
- package/skills/connect/scripts/run.mjs +37 -0
- package/src/cli.ts +42 -8
- package/src/discover.ts +1 -1
- package/src/engine.ts +12 -5
- package/src/install-skill.ts +57 -0
- package/src/mcp.ts +25 -5
- package/src/operator.ts +2 -0
- package/src/peer.ts +24 -4
- package/src/relay.ts +20 -4
- package/src/schema.ts +4 -2
- package/src/session-limits.ts +3 -0
- package/src/skill-session.ts +245 -0
- package/test/cli.test.ts +55 -7
- package/test/install-skill.test.ts +37 -0
- package/test/pairing.test.ts +6 -1
- package/test/review.test.ts +16 -0
- package/test/short-pairing.test.ts +42 -0
- package/test/skill-session.test.ts +93 -0
package/dist/cli.js
CHANGED
|
@@ -21,6 +21,7 @@ import { History } from './history.js';
|
|
|
21
21
|
import { cleanupLocal } from './maintenance.js';
|
|
22
22
|
import { skillsCommand, skillsUsage } from './skill-library.js';
|
|
23
23
|
import { knowledgeCommand, knowledgeUsage } from './knowledge-cli.js';
|
|
24
|
+
import { DEFAULT_IDLE_MS } from './session-limits.js';
|
|
24
25
|
async function attachTerminal(operator, id) {
|
|
25
26
|
let done = false, cursor = 0;
|
|
26
27
|
const wasRaw = stdin.isRaw;
|
|
@@ -56,6 +57,14 @@ async function attachTerminal(operator, id) {
|
|
|
56
57
|
}
|
|
57
58
|
}
|
|
58
59
|
async function main() {
|
|
60
|
+
if (process.argv[2] === 'install-skill') {
|
|
61
|
+
await (await import('./install-skill.js')).installSkill(process.argv.slice(3));
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (process.argv[2] === 'skill-session') {
|
|
65
|
+
await (await import('./skill-session.js')).skillSessionCommand(process.argv.slice(3));
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
59
68
|
if (['cases', 'drafts', 'vault'].includes(process.argv[2])) {
|
|
60
69
|
await knowledgeCommand(process.argv[2], process.argv.slice(3));
|
|
61
70
|
return;
|
|
@@ -68,7 +77,7 @@ async function main() {
|
|
|
68
77
|
process.exitCode = await launchAgent(process.argv.slice(3));
|
|
69
78
|
return;
|
|
70
79
|
}
|
|
71
|
-
const { positionals, values } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { 'session-minutes': { type: 'string', default: '
|
|
80
|
+
const { positionals, values } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { 'session-minutes': { type: 'string', default: '0' }, 'idle-minutes': { type: 'string', default: String(DEFAULT_IDLE_MS / 60_000) }, device: { type: 'string' }, case: { type: 'string' }, name: { type: 'string' }, days: { type: 'string', default: '7' }, cursor: { type: 'string', default: '0' } } });
|
|
72
81
|
const [command = 'help', relay = 'https://diagnose.fenginwind.com'] = positionals;
|
|
73
82
|
if (command === 'history') {
|
|
74
83
|
console.log(safeText(JSON.stringify(new History().list(), null, 2)));
|
|
@@ -89,7 +98,7 @@ async function main() {
|
|
|
89
98
|
throw new Error('Usage: diagnose start|connect|terminal|mcp [relay-url]');
|
|
90
99
|
const sessionMinutes = Number(values['session-minutes']), idleMinutes = Number(values['idle-minutes']);
|
|
91
100
|
if (![sessionMinutes, idleMinutes].every(value => Number.isInteger(value) && value >= 0 && value <= 10080))
|
|
92
|
-
throw new Error('Timeouts must be 0..10080 minutes; 0 disables endpoint timeout
|
|
101
|
+
throw new Error('Timeouts must be 0..10080 minutes; 0 disables that endpoint timeout');
|
|
93
102
|
if (command === 'devices') {
|
|
94
103
|
console.log(JSON.stringify(new PairingStore(join(homedir(), '.diagnose', 'pairings')).list('operator').map(({ name, id, relay }) => ({ name, id, relay })), null, 2));
|
|
95
104
|
return;
|
|
@@ -105,7 +114,7 @@ async function main() {
|
|
|
105
114
|
return;
|
|
106
115
|
}
|
|
107
116
|
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.`);
|
|
117
|
+
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${(await import('./install-skill.js')).installSkillUsage}\n${skillsUsage}\n${knowledgeUsage}\nNode.js >=20.10. Pairing codes are entered interactively, never as arguments.`);
|
|
109
118
|
return;
|
|
110
119
|
}
|
|
111
120
|
if (!stdin.isTTY || !stdout.isTTY)
|
|
@@ -142,6 +151,16 @@ async function main() {
|
|
|
142
151
|
if (command === 'start') {
|
|
143
152
|
const store = new PairingStore();
|
|
144
153
|
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.');
|
|
154
|
+
let nextSessionApproval = 'review';
|
|
155
|
+
if (!store.list('host').length) {
|
|
156
|
+
console.log('Auto approval lets the diagnostician run tasks with your OS permissions and receive results without further prompts.');
|
|
157
|
+
console.log('Approve everything also lets anyone with the next one-time invitation connect without confirmation. Share that invitation privately.');
|
|
158
|
+
const choice = (await rl.question('Task approval for the next session? [Enter=review / a=auto tasks only / e=approve everything] ', { signal: shutdown.signal })).trim().toLowerCase();
|
|
159
|
+
nextSessionApproval = choice === 'e' ? 'everything' : choice === 'a' ? 'tasks' : 'review';
|
|
160
|
+
console.log(nextSessionApproval === 'everything' ? 'Approve everything selected for this temporary invitation: connection, task execution, and result transmission.'
|
|
161
|
+
: nextSessionApproval === 'tasks' ? 'Auto approval selected for the next temporary session, subject to your pairing confirmation.'
|
|
162
|
+
: 'You will review task execution and result transfers.');
|
|
163
|
+
}
|
|
145
164
|
const firstAudit = new Audit();
|
|
146
165
|
resources = new SessionResources(join(homedir(), '.diagnose', 'resources'), firstAudit);
|
|
147
166
|
let sessions = 0;
|
|
@@ -194,15 +213,30 @@ async function main() {
|
|
|
194
213
|
if (remember)
|
|
195
214
|
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.');
|
|
196
215
|
console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
216
|
+
if (!remember && nextSessionApproval === 'everything') {
|
|
217
|
+
signal.throwIfAborted();
|
|
218
|
+
nextSessionApproval = 'review';
|
|
219
|
+
audit.record('session.pairing-decision', { allowed: true, fingerprint, approval: 'everything' });
|
|
220
|
+
engine.setPermissionMode('auto');
|
|
221
|
+
console.log('Connection approved by your startup selection (Approve everything).');
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
const preselectedAuto = nextSessionApproval === 'tasks' && !remember;
|
|
225
|
+
console.log(preselectedAuto ? 'You selected auto approval at startup. Choose y to confirm it or r to connect with per-task review.' : 'Choose y: approve each task/batch and its transfer.\nChoose a: grant automatic execution AND transmission (one hour if remembered; otherwise this temporary session).');
|
|
226
|
+
console.log('AUTO: 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.');
|
|
227
|
+
const prompt = preselectedAuto ? 'Allow this temporary session with auto approval? [y / r=review / N] '
|
|
228
|
+
: remember ? 'Remember and allow this diagnostician? [y / a=auto for 1 hour / N] ' : 'Allow this temporary diagnostic session? [y / a=auto / N] ';
|
|
229
|
+
const answer = (await rl.question(prompt, { signal })).trim().toLowerCase();
|
|
230
|
+
const auto = preselectedAuto ? answer === 'y' : answer === 'a';
|
|
231
|
+
const allowed = answer === 'y' || (preselectedAuto ? answer === 'r' : auto);
|
|
232
|
+
if (allowed)
|
|
233
|
+
nextSessionApproval = 'review';
|
|
200
234
|
if (allowed && remember) {
|
|
201
235
|
provision = createCode();
|
|
202
236
|
remembered = store.add({ role: 'host', name: 'diagnostician', label, relay, code: provision });
|
|
203
237
|
audit.record('pairing.remembered', { id: remembered.id });
|
|
204
238
|
}
|
|
205
|
-
if (
|
|
239
|
+
if (auto) {
|
|
206
240
|
engine.setPermissionMode('auto');
|
|
207
241
|
if (remembered) {
|
|
208
242
|
remembered.autoUntil = Date.now() + 3600000;
|
|
@@ -284,6 +318,7 @@ async function main() {
|
|
|
284
318
|
return true;
|
|
285
319
|
}
|
|
286
320
|
if (value === 'permissions ask') {
|
|
321
|
+
nextSessionApproval = 'review';
|
|
287
322
|
autoRequestedAt = 0;
|
|
288
323
|
clearTimeout(grantTimer);
|
|
289
324
|
if (remembered) {
|
|
@@ -358,6 +393,8 @@ async function main() {
|
|
|
358
393
|
await peer.open();
|
|
359
394
|
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.`);
|
|
360
395
|
console.log(`Session ended: ${safeText(await peer.ended)}`);
|
|
396
|
+
if (nextSessionApproval === 'everything')
|
|
397
|
+
nextSessionApproval = 'review';
|
|
361
398
|
}
|
|
362
399
|
catch (error) {
|
|
363
400
|
const collision = error.message.includes('Invitation locator occupied');
|
package/dist/discover.js
CHANGED
|
@@ -19,5 +19,5 @@ export async function inspectSystem() {
|
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
21
|
const elevated = process.platform === 'win32' ? /S-1-16-(12288|16384)/.test(spawnSync('whoami', ['/groups'], { encoding: 'utf8', timeout: 3000, windowsHide: true }).stdout ?? '') : process.geteuid?.() === 0;
|
|
22
|
-
return { platform: process.platform, arch: process.arch, release: os.release(), node: process.version, hostname: os.hostname(), cwd: process.cwd(), home: os.homedir(), username: os.userInfo().username, elevated, shell: process.platform === 'win32' ? process.env.ComSpec ?? 'cmd.exe' : process.env.SHELL ?? '/bin/sh', commands, serialPorts: await SerialPort.list(), networkInterfaces: os.networkInterfaces(), protocol: 1, version: '0.
|
|
22
|
+
return { platform: process.platform, arch: process.arch, release: os.release(), node: process.version, hostname: os.hostname(), cwd: process.cwd(), home: os.homedir(), username: os.userInfo().username, elevated, shell: process.platform === 'win32' ? process.env.ComSpec ?? 'cmd.exe' : process.env.SHELL ?? '/bin/sh', commands, serialPorts: await SerialPort.list(), networkInterfaces: os.networkInterfaces(), protocol: 1, version: '0.8.1', 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.js
CHANGED
|
@@ -4,6 +4,7 @@ import { digest, redact, safeText } from './util.js';
|
|
|
4
4
|
import { SessionResources, resourceOperation } from './resources.js';
|
|
5
5
|
import { randomUUID } from 'node:crypto';
|
|
6
6
|
import { dirname, join, basename } from 'node:path';
|
|
7
|
+
import { DEFAULT_IDLE_MS } from './session-limits.js';
|
|
7
8
|
function aborted(promise, signal) {
|
|
8
9
|
return new Promise((resolve, reject) => {
|
|
9
10
|
const cancel = () => reject(new Error('Task cancelled'));
|
|
@@ -60,18 +61,24 @@ export class ProbeEngine {
|
|
|
60
61
|
this.notice = notice;
|
|
61
62
|
this.resources = options.resources ?? new SessionResources(join(dirname(audit.path), basename(audit.path) + '.resources'), audit);
|
|
62
63
|
this.resources.setAudit(audit);
|
|
64
|
+
const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
|
|
65
|
+
const refreshIdle = () => {
|
|
66
|
+
if (!idleMs || this.ended)
|
|
67
|
+
return;
|
|
68
|
+
clearTimeout(this.idle);
|
|
69
|
+
this.idle = setTimeout(() => peer.close('Idle timeout'), idleMs);
|
|
70
|
+
};
|
|
63
71
|
// 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
72
|
void peer.active.then(() => {
|
|
66
73
|
if (this.ended)
|
|
67
74
|
return;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
this.lifetime = setTimeout(() => peer.close('Session lifetime exceeded'), options.lifetimeMs ?? 3600000);
|
|
75
|
+
refreshIdle();
|
|
76
|
+
if (options.lifetimeMs)
|
|
77
|
+
this.lifetime = setTimeout(() => peer.close('Session lifetime exceeded'), options.lifetimeMs);
|
|
72
78
|
}).catch(() => { });
|
|
79
|
+
peer.on('activity', refreshIdle);
|
|
73
80
|
peer.on('message', (message) => {
|
|
74
|
-
|
|
81
|
+
refreshIdle();
|
|
75
82
|
if (message.type === 'resource.request') {
|
|
76
83
|
void this.resources.control(this.owner, message.request).then(value => this.peer.send({ type: 'resource.result', requestId: message.requestId, value }), error => this.peer.send({ type: 'resource.result', requestId: message.requestId, error: redact(error.message).slice(0, 2000) })).catch(() => { });
|
|
77
84
|
return;
|
|
@@ -127,9 +134,9 @@ export class ProbeEngine {
|
|
|
127
134
|
this.jobs.set(task.id, controller);
|
|
128
135
|
void this.run(task, controller);
|
|
129
136
|
});
|
|
130
|
-
peer.on('closed', () => { this.ended = true; clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values())
|
|
137
|
+
peer.on('closed', (reason) => { this.ended = true; clearTimeout(this.idle); clearTimeout(this.lifetime); for (const controller of this.jobs.values())
|
|
131
138
|
controller.abort(); void this.resources.disconnect(this.owner).catch(() => { }); try {
|
|
132
|
-
audit.record('session.closed', {});
|
|
139
|
+
audit.record('session.closed', { reason: reason && redact(reason) });
|
|
133
140
|
}
|
|
134
141
|
catch { /* Session is already closed. */ } });
|
|
135
142
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
export const installSkillUsage = 'diagnose install-skill claude|codex|gemini';
|
|
7
|
+
const locations = new Map([
|
|
8
|
+
['claude', { directory: '.claude', invocation: '/diagnose' }],
|
|
9
|
+
['codex', { directory: '.agents', invocation: '$diagnose' }],
|
|
10
|
+
['gemini', { directory: '.gemini', invocation: 'Use the Diagnose skill' }],
|
|
11
|
+
]);
|
|
12
|
+
export async function installSkill(args) {
|
|
13
|
+
const agent = args.length === 1 ? locations.get(args[0]) : undefined;
|
|
14
|
+
if (!agent)
|
|
15
|
+
throw new Error('Usage: ' + installSkillUsage);
|
|
16
|
+
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
17
|
+
const source = join(root, 'skills', 'connect');
|
|
18
|
+
const library = join(homedir(), agent.directory, 'skills');
|
|
19
|
+
const target = join(library, 'diagnose');
|
|
20
|
+
const [skill, helper] = await Promise.all([
|
|
21
|
+
readFile(join(source, 'SKILL.md'), 'utf8'),
|
|
22
|
+
readFile(join(source, 'scripts/run.mjs')),
|
|
23
|
+
]);
|
|
24
|
+
const files = new Map([
|
|
25
|
+
['SKILL.md', Buffer.from(skill.replace(/^name: connect$/m, 'name: diagnose'))],
|
|
26
|
+
['scripts/run.mjs', helper],
|
|
27
|
+
]);
|
|
28
|
+
const runtime = 'scripts/local-runtime.json';
|
|
29
|
+
if (existsSync(join(root, '.git'))) {
|
|
30
|
+
files.set(runtime, Buffer.from(JSON.stringify({ cli: join(root, 'dist', 'cli.js') }) + '\n'));
|
|
31
|
+
}
|
|
32
|
+
await mkdir(library, { recursive: true, mode: 0o700 });
|
|
33
|
+
try {
|
|
34
|
+
await mkdir(target, { mode: 0o700 });
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error.code !== 'EEXIST')
|
|
38
|
+
throw error;
|
|
39
|
+
const sameFiles = (await Promise.all([...files].map(async ([file, bytes]) => (await readFile(join(target, file)).catch(() => undefined))?.equals(bytes) === true))).every(Boolean) && (files.has(runtime) || !existsSync(join(target, runtime)));
|
|
40
|
+
if (!sameFiles)
|
|
41
|
+
throw new Error('A different Skill already exists at ' + target + '. Move it before installing.');
|
|
42
|
+
console.log('Diagnose Skill is already installed at ' + target);
|
|
43
|
+
console.log('In a new agent session, use ' + agent.invocation + '.');
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
await mkdir(join(target, 'scripts'), { mode: 0o700 });
|
|
48
|
+
for (const [file, bytes] of files)
|
|
49
|
+
await writeFile(join(target, file), bytes, { mode: 0o600, flag: 'wx' });
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
await rm(target, { recursive: true, force: true });
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
console.log('Installed Diagnose Skill at ' + target);
|
|
56
|
+
console.log('In a new agent session, use ' + agent.invocation + '.');
|
|
57
|
+
}
|
package/dist/mcp.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
2
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import { Peer } from './peer.js';
|
|
4
|
+
import { Peer, pairingProgress } from './peer.js';
|
|
5
5
|
import { Operator } from './operator.js';
|
|
6
6
|
import { atomicOperationNames, batchOperationNames, resourceRequestSchema } from './schema.js';
|
|
7
7
|
import { upload, download } from './transfers.js';
|
|
@@ -11,7 +11,7 @@ import { PairingStore, RememberedConnection } from './pairing.js';
|
|
|
11
11
|
import { safeText } from './util.js';
|
|
12
12
|
import { registerKnowledge } from './knowledge-mcp.js';
|
|
13
13
|
export async function serveMcp(relay, device, caseId) {
|
|
14
|
-
const server = new McpServer({ name: 'diagnose', version: '0.
|
|
14
|
+
const server = new McpServer({ name: 'diagnose', version: '0.8.1' });
|
|
15
15
|
let operator;
|
|
16
16
|
let remembered = device ? new RememberedConnection(new PairingStore().get(device, 'operator')) : undefined;
|
|
17
17
|
const transfers = new Map(), forwards = new Map();
|
|
@@ -35,14 +35,24 @@ export async function serveMcp(relay, device, caseId) {
|
|
|
35
35
|
connectionState = 'unavailable';
|
|
36
36
|
throw error;
|
|
37
37
|
} };
|
|
38
|
-
server.registerTool('diagnose_pair', { description: 'Connect using the user-shared nine-letter invitation (abc-def-ghi; case, spaces and hyphens ignored). Legacy D1 codes are also accepted. The
|
|
38
|
+
server.registerTool('diagnose_pair', { description: 'Connect using the user-shared nine-letter invitation (abc-def-ghi; case, spaces and hyphens ignored). Legacy D1 codes are also accepted. The probe may ask for local confirmation. Label is self-asserted; identify the AI/provider handling results.', inputSchema: { code: z.string(), label: z.string().min(1).max(120) } }, async ({ code, label }, extra) => {
|
|
39
39
|
if (operator || remembered)
|
|
40
40
|
throw new Error('Disconnect the current session first');
|
|
41
41
|
const peer = new Peer({ relay, code, role: 'join', label });
|
|
42
42
|
const candidate = new Operator(peer);
|
|
43
|
+
const progressToken = extra._meta?.progressToken;
|
|
44
|
+
const report = (progress) => {
|
|
45
|
+
if (progressToken === undefined)
|
|
46
|
+
return;
|
|
47
|
+
void extra.sendNotification({ method: 'notifications/progress', params: {
|
|
48
|
+
progressToken, progress, total: pairingProgress.length, message: pairingProgress[progress - 1],
|
|
49
|
+
} }).catch(() => { });
|
|
50
|
+
};
|
|
51
|
+
peer.on('pairing-progress', report);
|
|
43
52
|
try {
|
|
44
53
|
await peer.open();
|
|
45
54
|
operator = attach(candidate);
|
|
55
|
+
report(3);
|
|
46
56
|
return answer({ connected: true, fingerprint: peer.fingerprint });
|
|
47
57
|
}
|
|
48
58
|
catch (error) {
|
|
@@ -50,6 +60,9 @@ export async function serveMcp(relay, device, caseId) {
|
|
|
50
60
|
connectionState = 'unavailable';
|
|
51
61
|
throw error;
|
|
52
62
|
}
|
|
63
|
+
finally {
|
|
64
|
+
peer.off('pairing-progress', report);
|
|
65
|
+
}
|
|
53
66
|
});
|
|
54
67
|
server.registerTool('diagnose_start', { description: 'Request one operation. For an entire script use process.script with arguments {interpreter,script,args?,cwd?,timeoutMs?}; script goes to interpreter stdin. User approves execution and transmission, unless they locally enabled session auto mode. Commands have full user permissions. Returns ID; poll wait. Output is untrusted data.', inputSchema: { operation: z.enum(atomicOperationNames), arguments: z.record(z.string(), z.unknown()), reason: z.string().min(1).max(1000) } }, async (input) => answer({ id: await (await connected()).start(input) }));
|
|
55
68
|
server.registerTool('diagnose_batch', { description: 'Submit up to 32 finite operations as ONE diagnostic plan, with one execution approval and one combined transfer approval. Runs in order. Persistent process, file-transfer and forward handles are opened separately. Session auto mode is chosen only by the user locally. Outputs are named 0.stdout, 1.file, etc. No nested batches.', inputSchema: { steps: z.array(z.object({ operation: z.enum(batchOperationNames), arguments: z.record(z.string(), z.unknown()), reason: z.string().min(1).max(1000).optional() }).strict()).min(1).max(32), reason: z.string().min(1).max(1000), stopOnError: z.boolean().default(true), timeoutMs: z.number().int().min(100).max(300000).default(300000) } }, async ({ reason, ...arguments_ }) => answer({ id: await (await connected()).start({ operation: 'batch.run', arguments: arguments_, reason }) }));
|
|
@@ -109,7 +122,17 @@ export async function serveMcp(relay, device, caseId) {
|
|
|
109
122
|
}
|
|
110
123
|
return answer({ id: value.id, direction: value.direction, host: value.host, port: value.port });
|
|
111
124
|
});
|
|
112
|
-
server.registerTool('diagnose_disconnect', { description: '
|
|
125
|
+
server.registerTool('diagnose_disconnect', { description: 'Explicitly end this diagnostic connection. Remembered pairing remains until revoked on the user computer.', inputSchema: {} }, async () => {
|
|
126
|
+
remembered?.close();
|
|
127
|
+
remembered = undefined;
|
|
128
|
+
const peer = operator?.peer;
|
|
129
|
+
operator = undefined;
|
|
130
|
+
if (peer) {
|
|
131
|
+
await peer.send({ type: 'session.closed', reason: 'Diagnostician ended session' }).catch(() => { });
|
|
132
|
+
peer.close();
|
|
133
|
+
}
|
|
134
|
+
return answer({ disconnected: true });
|
|
135
|
+
});
|
|
113
136
|
let stopped = false;
|
|
114
137
|
const stop = () => { if (stopped)
|
|
115
138
|
return; stopped = true; for (const transfer of transfers.values())
|
package/dist/operator.js
CHANGED
|
@@ -86,6 +86,8 @@ export class Operator {
|
|
|
86
86
|
const job = this.jobs.get(id);
|
|
87
87
|
if (!job)
|
|
88
88
|
throw new Error('Unknown or expired task result; completed results are bounded to 128 tasks / 32 MiB. Do not replay modifications; inspect remote state or local history.');
|
|
89
|
+
// Polling a real task is diagnostic activity even though the result is cached locally.
|
|
90
|
+
void this.peer.send({ type: 'ping', activity: true }).catch(() => { });
|
|
89
91
|
let timer;
|
|
90
92
|
try {
|
|
91
93
|
return await Promise.race([job.promise, new Promise(resolve => { timer = setTimeout(() => resolve({ id, pending: true }), timeoutMs); })]);
|
package/dist/peer.d.ts
CHANGED
|
@@ -17,6 +17,7 @@ export type PeerOptions = {
|
|
|
17
17
|
sessionMs?: number;
|
|
18
18
|
invitationMs?: number;
|
|
19
19
|
};
|
|
20
|
+
export declare const pairingProgress: readonly ['Connected to the relay. Verifying the on-site probe.', 'Authenticated the on-site probe. Waiting for it to accept the connection. Approve on site if prompted.', 'Paired with the on-site probe.'];
|
|
20
21
|
export declare function relayUrl(value: string): string;
|
|
21
22
|
export declare class Peer extends EventEmitter {
|
|
22
23
|
private options;
|
package/dist/peer.js
CHANGED
|
@@ -4,6 +4,12 @@ import { Handshake, parseCode, parseInvitation, INVITATION_MS } from './crypto.j
|
|
|
4
4
|
import { CHUNK_SIZE, MAX_FRAME, parseMessage } from './schema.js';
|
|
5
5
|
import { safeText } from './util.js';
|
|
6
6
|
import { InvitationHost, InvitationJoin } from './short-pairing.js';
|
|
7
|
+
import { LEGACY_RELAY_MAX_MS } from './session-limits.js';
|
|
8
|
+
export const pairingProgress = [
|
|
9
|
+
'Connected to the relay. Verifying the on-site probe.',
|
|
10
|
+
'Authenticated the on-site probe. Waiting for it to accept the connection. Approve on site if prompted.',
|
|
11
|
+
'Paired with the on-site probe.',
|
|
12
|
+
];
|
|
7
13
|
function deferred() { let resolve; let reject; const promise = new Promise((a, b) => { resolve = a; reject = b; }); promise.catch(() => { }); return { promise, resolve, reject }; }
|
|
8
14
|
export function relayUrl(value) {
|
|
9
15
|
const url = new URL(value);
|
|
@@ -64,9 +70,17 @@ export class Peer extends EventEmitter {
|
|
|
64
70
|
this.connectionTimer = setTimeout(() => this.close('Relay registration timeout'), 12000);
|
|
65
71
|
if (short && options.role === 'host')
|
|
66
72
|
this.invitationTimer = setTimeout(() => this.close('Invitation expired; generate a new code'), Math.min(options.invitationMs ?? INVITATION_MS, INVITATION_MS));
|
|
67
|
-
this.ws.on('open', () =>
|
|
73
|
+
this.ws.on('open', () => {
|
|
74
|
+
this.ws.send(JSON.stringify({ version: short ? 2 : 1, role: options.role, room }));
|
|
75
|
+
if (options.role === 'join')
|
|
76
|
+
this.emit('pairing-progress', 1);
|
|
77
|
+
});
|
|
68
78
|
this.ws.on('error', () => this.close('Relay connection failed'));
|
|
69
|
-
this.ws.on('close', (_code, reason) =>
|
|
79
|
+
this.ws.on('close', (_code, reason) => {
|
|
80
|
+
const message = reason.toString();
|
|
81
|
+
this.close(message === 'Invitation locator occupied' ? 'Invitation locator occupied; generating a new code'
|
|
82
|
+
: message === 'Session expired' ? 'Relay session expired' : 'Relay disconnected');
|
|
83
|
+
});
|
|
70
84
|
this.ws.on('message', (bytes, binary) => {
|
|
71
85
|
try {
|
|
72
86
|
if (binary)
|
|
@@ -184,7 +198,9 @@ export class Peer extends EventEmitter {
|
|
|
184
198
|
this.close('User declined pairing');
|
|
185
199
|
return;
|
|
186
200
|
}
|
|
187
|
-
this.ws.send(JSON.stringify(
|
|
201
|
+
this.ws.send(JSON.stringify(this.options.sessionMs
|
|
202
|
+
? { type: 'lock', ttlMs: this.options.sessionMs }
|
|
203
|
+
: { type: 'lock', sliding: true, ttlMs: LEGACY_RELAY_MAX_MS }));
|
|
188
204
|
this.approved = true;
|
|
189
205
|
await this.send({ type: 'session.accepted', label: safeText(this.options.label ?? 'User probe'), fingerprint: this.fingerprint, ...(hello.remember === true && this.options.provision?.() ? { credential: this.options.provision() } : {}) });
|
|
190
206
|
this.activate();
|
|
@@ -194,6 +210,7 @@ export class Peer extends EventEmitter {
|
|
|
194
210
|
this.cipher = this.handshake.split();
|
|
195
211
|
this.handshake = undefined;
|
|
196
212
|
this.fingerprint = this.cipher.fingerprint;
|
|
213
|
+
this.emit('pairing-progress', 2);
|
|
197
214
|
}
|
|
198
215
|
return;
|
|
199
216
|
}
|
|
@@ -231,6 +248,8 @@ export class Peer extends EventEmitter {
|
|
|
231
248
|
if (!this.approved)
|
|
232
249
|
throw new Error('Not authorized');
|
|
233
250
|
if (message.type === 'ping') {
|
|
251
|
+
if (message.activity && this.options.role === 'host')
|
|
252
|
+
this.emit('activity');
|
|
234
253
|
void this.send({ type: 'pong' }).catch(() => this.close('Heartbeat failed'));
|
|
235
254
|
return;
|
|
236
255
|
}
|
|
@@ -272,6 +291,8 @@ export class Peer extends EventEmitter {
|
|
|
272
291
|
// Bound sustained traffic below the relay's shared per-room frame budget.
|
|
273
292
|
await new Promise(resolve => setTimeout(resolve, 10));
|
|
274
293
|
}
|
|
294
|
+
if (message.type.startsWith('task.') || message.type.startsWith('resource.'))
|
|
295
|
+
this.emit('activity');
|
|
275
296
|
}).finally(() => { this.queuedBytes -= payload.length; });
|
|
276
297
|
this.queue = operation.catch(() => this.close('Encrypted transport failed'));
|
|
277
298
|
return operation;
|
package/dist/relay.js
CHANGED
|
@@ -4,11 +4,17 @@ import { WebSocket, WebSocketServer } from 'ws';
|
|
|
4
4
|
import { MAX_FRAME } from './schema.js';
|
|
5
5
|
import { INVITATION_MS } from './crypto.js';
|
|
6
6
|
import { VaultServer } from './vault-server.js';
|
|
7
|
+
import { DEFAULT_IDLE_MS, LEGACY_RELAY_MAX_MS } from './session-limits.js';
|
|
7
8
|
const control = (ws, type, extra = {}) => { if (ws.readyState === WebSocket.OPEN)
|
|
8
9
|
ws.send(JSON.stringify({ type, ...extra })); };
|
|
9
10
|
export function createRelay(options = {}) {
|
|
10
11
|
const vault = options.vaultPath ? new VaultServer(options.vaultPath) : undefined;
|
|
11
12
|
const rooms = new Map();
|
|
13
|
+
const expireRoom = (id, room) => {
|
|
14
|
+
rooms.delete(id);
|
|
15
|
+
room.host.close(1000, 'Session expired');
|
|
16
|
+
room.peer?.close(1000, 'Session expired');
|
|
17
|
+
};
|
|
12
18
|
const clients = new Map();
|
|
13
19
|
const connectionsByIp = new Map();
|
|
14
20
|
const connectionRates = new Map();
|
|
@@ -110,8 +116,12 @@ export function createRelay(options = {}) {
|
|
|
110
116
|
return;
|
|
111
117
|
}
|
|
112
118
|
const room = rooms.get(state.room);
|
|
113
|
-
if (!room
|
|
119
|
+
if (!room)
|
|
114
120
|
throw new Error();
|
|
121
|
+
if (room.expires <= Date.now()) {
|
|
122
|
+
expireRoom(state.room, room);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
115
125
|
if (binary) {
|
|
116
126
|
if (Date.now() - room.window > 1000) {
|
|
117
127
|
room.window = Date.now();
|
|
@@ -127,6 +137,10 @@ export function createRelay(options = {}) {
|
|
|
127
137
|
buffered += client.bufferedAmount;
|
|
128
138
|
if (buffered > 64 * 1024 * 1024)
|
|
129
139
|
throw new Error();
|
|
140
|
+
// The relay can see ciphertext traffic, not diagnostic activity. The
|
|
141
|
+
// probe enforces the real idle timeout without counting heartbeats.
|
|
142
|
+
if (room.renewMs)
|
|
143
|
+
room.expires = Date.now() + room.renewMs;
|
|
130
144
|
options.observeCiphertext?.(bytes);
|
|
131
145
|
target.send(bytes, { binary: true });
|
|
132
146
|
return;
|
|
@@ -136,10 +150,12 @@ export function createRelay(options = {}) {
|
|
|
136
150
|
const msg = JSON.parse(bytes.toString());
|
|
137
151
|
if (msg.type === 'lock' && !room.locked) {
|
|
138
152
|
const requested = msg.ttlMs;
|
|
139
|
-
if (requested !== undefined && (!Number.isInteger(requested) || requested < 60000 || requested >
|
|
153
|
+
if (requested !== undefined && (!Number.isInteger(requested) || requested < 60000 || requested > LEGACY_RELAY_MAX_MS))
|
|
140
154
|
throw new Error();
|
|
141
155
|
room.locked = true;
|
|
142
|
-
|
|
156
|
+
if (msg.sliding === true)
|
|
157
|
+
room.renewMs = options.sessionMs ?? DEFAULT_IDLE_MS;
|
|
158
|
+
room.expires = Date.now() + (room.renewMs ?? requested ?? options.sessionMs ?? DEFAULT_IDLE_MS);
|
|
143
159
|
}
|
|
144
160
|
else if (msg.type === 'reject' && !room.locked) {
|
|
145
161
|
const peer = room.peer;
|
|
@@ -178,11 +194,8 @@ export function createRelay(options = {}) {
|
|
|
178
194
|
});
|
|
179
195
|
const sweep = setInterval(() => {
|
|
180
196
|
for (const [id, room] of rooms)
|
|
181
|
-
if (room.expires
|
|
182
|
-
|
|
183
|
-
room.host.close(1000, 'Session expired');
|
|
184
|
-
room.peer?.close(1000, 'Session expired');
|
|
185
|
-
}
|
|
197
|
+
if (room.expires <= Date.now())
|
|
198
|
+
expireRoom(id, room);
|
|
186
199
|
for (const [ws, state] of clients) {
|
|
187
200
|
if (!state.alive)
|
|
188
201
|
ws.terminate();
|
package/dist/schema.d.ts
CHANGED
|
@@ -773,6 +773,9 @@ export type WireMessage = {
|
|
|
773
773
|
value?: unknown;
|
|
774
774
|
error?: string;
|
|
775
775
|
} | {
|
|
776
|
-
type: 'ping'
|
|
776
|
+
type: 'ping';
|
|
777
|
+
activity?: true;
|
|
778
|
+
} | {
|
|
779
|
+
type: 'pong';
|
|
777
780
|
};
|
|
778
781
|
export declare function parseMessage(value: unknown): WireMessage;
|
package/dist/schema.js
CHANGED
|
@@ -35,8 +35,8 @@ export function parseMessage(value) {
|
|
|
35
35
|
case 'task.cancel': return { type: basic.type, id: z.string().uuid().parse(basic.id) };
|
|
36
36
|
case 'resource.request': return { type: basic.type, requestId: z.string().uuid().parse(basic.requestId), request: resourceRequestSchema.parse(basic.request) };
|
|
37
37
|
case 'resource.result': return z.object({ type: z.literal('resource.result'), requestId: z.string().uuid(), value: z.unknown().optional(), error: z.string().max(2000).optional() }).strict().parse(value);
|
|
38
|
-
case 'ping':
|
|
39
|
-
case 'pong': return { type:
|
|
38
|
+
case 'ping': return basic.activity === true ? { type: 'ping', activity: true } : { type: 'ping' };
|
|
39
|
+
case 'pong': return { type: 'pong' };
|
|
40
40
|
case 'session.accepted': return z.object({ type: z.literal('session.accepted'), label: z.string().max(120), fingerprint: z.string().max(100), credential: z.string().regex(/^D1\.[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{43}$/).optional() }).strict().parse(value);
|
|
41
41
|
case 'session.closed': return z.object({ type: z.literal('session.closed'), reason: z.string().max(200) }).strict().parse(value);
|
|
42
42
|
case 'task.started': return z.object({ type: z.literal('task.started'), id: z.string().uuid(), digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict().parse(value);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function skillSessionCommand(args: string[]): Promise<void>;
|