@masstensor/diagnose 0.5.0 → 0.8.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.
Files changed (94) hide show
  1. package/DEVELOPMENT_PLAN.md +69 -0
  2. package/KNOWLEDGE_SECURITY.md +47 -0
  3. package/PAIRING_PROTOCOL.md +37 -0
  4. package/README.md +28 -6
  5. package/USER_GUIDE.md +250 -34
  6. package/deploy/Caddyfile +1 -1
  7. package/deploy/ecosystem.config.cjs +1 -1
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +15 -5
  10. package/dist/cases.d.ts +118 -0
  11. package/dist/cases.js +115 -0
  12. package/dist/cli.js +61 -13
  13. package/dist/crypto.d.ts +7 -0
  14. package/dist/crypto.js +16 -1
  15. package/dist/discover.js +1 -1
  16. package/dist/engine.d.ts +1 -0
  17. package/dist/engine.js +21 -7
  18. package/dist/install-skill.d.ts +2 -0
  19. package/dist/install-skill.js +57 -0
  20. package/dist/knowledge-cli.d.ts +2 -0
  21. package/dist/knowledge-cli.js +164 -0
  22. package/dist/knowledge-drafts.d.ts +47 -0
  23. package/dist/knowledge-drafts.js +76 -0
  24. package/dist/knowledge-mcp.d.ts +5 -0
  25. package/dist/knowledge-mcp.js +65 -0
  26. package/dist/mcp.d.ts +1 -1
  27. package/dist/mcp.js +38 -9
  28. package/dist/operator.d.ts +2 -0
  29. package/dist/operator.js +18 -3
  30. package/dist/peer.d.ts +9 -0
  31. package/dist/peer.js +90 -10
  32. package/dist/relay-main.js +1 -1
  33. package/dist/relay.d.ts +1 -0
  34. package/dist/relay.js +46 -10
  35. package/dist/schema.d.ts +4 -1
  36. package/dist/schema.js +2 -2
  37. package/dist/session-limits.d.ts +3 -0
  38. package/dist/session-limits.js +3 -0
  39. package/dist/short-pairing.d.ts +25 -0
  40. package/dist/short-pairing.js +73 -0
  41. package/dist/skill-library.d.ts +27 -0
  42. package/dist/skill-library.js +226 -0
  43. package/dist/skill-session.d.ts +1 -0
  44. package/dist/skill-session.js +257 -0
  45. package/dist/skill.d.ts +1 -0
  46. package/dist/skill.js +1 -0
  47. package/dist/util.js +1 -0
  48. package/dist/vault-crypto.d.ts +11 -0
  49. package/dist/vault-crypto.js +30 -0
  50. package/dist/vault-server.d.ts +10 -0
  51. package/dist/vault-server.js +156 -0
  52. package/dist/vault.d.ts +19 -0
  53. package/dist/vault.js +72 -0
  54. package/npm-shrinkwrap.json +12 -2
  55. package/package.json +7 -2
  56. package/skills/connect/SKILL.md +60 -0
  57. package/skills/connect/scripts/run.mjs +37 -0
  58. package/src/agent.ts +12 -5
  59. package/src/cases.ts +74 -0
  60. package/src/cli.ts +51 -13
  61. package/src/crypto.ts +14 -1
  62. package/src/discover.ts +1 -1
  63. package/src/engine.ts +17 -4
  64. package/src/install-skill.ts +57 -0
  65. package/src/knowledge-cli.ts +67 -0
  66. package/src/knowledge-drafts.ts +55 -0
  67. package/src/knowledge-mcp.ts +35 -0
  68. package/src/mcp.ts +21 -7
  69. package/src/operator.ts +12 -3
  70. package/src/peer.ts +51 -14
  71. package/src/relay-main.ts +1 -1
  72. package/src/relay.ts +35 -7
  73. package/src/schema.ts +4 -2
  74. package/src/session-limits.ts +3 -0
  75. package/src/short-pairing.ts +57 -0
  76. package/src/skill-library.ts +162 -0
  77. package/src/skill-session.ts +233 -0
  78. package/src/skill.ts +2 -1
  79. package/src/util.ts +1 -0
  80. package/src/vault-crypto.ts +25 -0
  81. package/src/vault-server.ts +72 -0
  82. package/src/vault.ts +51 -0
  83. package/test/agent.test.ts +26 -1
  84. package/test/cli.test.ts +58 -10
  85. package/test/install-skill.test.ts +37 -0
  86. package/test/knowledge-mcp.test.ts +37 -0
  87. package/test/knowledge.test.ts +112 -0
  88. package/test/mcp.test.ts +1 -1
  89. package/test/pairing.test.ts +8 -3
  90. package/test/review.test.ts +17 -0
  91. package/test/short-pairing.test.ts +142 -0
  92. package/test/skill-library.test.ts +62 -0
  93. package/test/skill-session.test.ts +79 -0
  94. package/test/skill.test.ts +1 -1
@@ -0,0 +1,118 @@
1
+ import { z } from 'zod';
2
+ export declare const targetSchema: z.ZodObject<{
3
+ name: z.ZodString;
4
+ model: z.ZodOptional<z.ZodString>;
5
+ identity: z.ZodOptional<z.ZodString>;
6
+ interface: z.ZodEnum<{
7
+ host: "host";
8
+ lan: "lan";
9
+ other: "other";
10
+ serial: "serial";
11
+ usb: "usb";
12
+ }>;
13
+ address: z.ZodOptional<z.ZodString>;
14
+ }, z.core.$strict>;
15
+ export declare const caseInputSchema: z.ZodObject<{
16
+ goal: z.ZodString;
17
+ target: z.ZodObject<{
18
+ name: z.ZodString;
19
+ model: z.ZodOptional<z.ZodString>;
20
+ identity: z.ZodOptional<z.ZodString>;
21
+ interface: z.ZodEnum<{
22
+ host: "host";
23
+ lan: "lan";
24
+ other: "other";
25
+ serial: "serial";
26
+ usb: "usb";
27
+ }>;
28
+ address: z.ZodOptional<z.ZodString>;
29
+ }, z.core.$strict>;
30
+ host: z.ZodOptional<z.ZodString>;
31
+ skill: z.ZodOptional<z.ZodString>;
32
+ }, z.core.$strict>;
33
+ export declare const conclusionSchema: z.ZodObject<{
34
+ outcome: z.ZodEnum<{
35
+ "insufficient-evidence": "insufficient-evidence";
36
+ "needs-physical-work": "needs-physical-work";
37
+ resolved: "resolved";
38
+ unresolved: "unresolved";
39
+ }>;
40
+ summary: z.ZodString;
41
+ changes: z.ZodDefault<z.ZodArray<z.ZodString>>;
42
+ remaining: z.ZodDefault<z.ZodArray<z.ZodString>>;
43
+ baseline: z.ZodOptional<z.ZodString>;
44
+ verification: z.ZodOptional<z.ZodString>;
45
+ }, z.core.$strict>;
46
+ export type Evidence = {
47
+ id: string;
48
+ at: string;
49
+ kind: string;
50
+ taskId?: string;
51
+ digest: string;
52
+ data: unknown;
53
+ truncated: boolean;
54
+ };
55
+ export type Case = z.infer<typeof caseInputSchema> & {
56
+ id: string;
57
+ createdAt: string;
58
+ conclusion?: z.infer<typeof conclusionSchema>;
59
+ evidence: Evidence[];
60
+ recordingLimited?: boolean;
61
+ };
62
+ export declare function sanitize(value: unknown): unknown;
63
+ export declare class Cases {
64
+ readonly root: string;
65
+ private journal;
66
+ constructor(root?: string);
67
+ create(input: z.infer<typeof caseInputSchema>): Case;
68
+ get(id: string): Case;
69
+ save(value: Case): void;
70
+ list(): {
71
+ id: string;
72
+ goal: string;
73
+ target: {
74
+ name: string;
75
+ model?: string | undefined;
76
+ identity?: string | undefined;
77
+ interface: "host" | "lan" | "other" | "serial" | "usb";
78
+ address?: string | undefined;
79
+ };
80
+ createdAt: string;
81
+ outcome: string;
82
+ evidenceCount: number;
83
+ }[];
84
+ remove(id: string): void;
85
+ claim(id: string): () => void;
86
+ unlock(id: string): void;
87
+ record(id: string, kind: string, data: unknown, taskId?: string): Evidence | undefined;
88
+ finish(id: string, input: z.infer<typeof conclusionSchema>): Case;
89
+ report(id: string): {
90
+ id: string;
91
+ createdAt: string;
92
+ goal: unknown;
93
+ target: {
94
+ name: unknown;
95
+ model: unknown;
96
+ interface: "host" | "lan" | "other" | "serial" | "usb";
97
+ };
98
+ skill: string | undefined;
99
+ conclusion: {
100
+ outcome: "insufficient-evidence" | "needs-physical-work" | "resolved" | "unresolved";
101
+ summary: string;
102
+ changes: string[];
103
+ remaining: string[];
104
+ baseline?: string | undefined;
105
+ verification?: string | undefined;
106
+ } | undefined;
107
+ recordingLimited: boolean;
108
+ evidence: {
109
+ id: string;
110
+ at: string;
111
+ kind: string;
112
+ taskId: string | undefined;
113
+ digest: string;
114
+ truncated: boolean;
115
+ }[];
116
+ note: string;
117
+ };
118
+ }
package/dist/cases.js ADDED
@@ -0,0 +1,115 @@
1
+ import { randomUUID, createHash } from 'node:crypto';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { unlinkSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
5
+ import { z } from 'zod';
6
+ import { Journal } from './journal.js';
7
+ import { redact } from './util.js';
8
+ const text = z.string().min(1).max(4000);
9
+ export const targetSchema = z.object({ name: text, model: text.optional(), identity: text.optional(), interface: z.enum(['usb', 'serial', 'lan', 'host', 'other']), address: text.optional() }).strict();
10
+ export const caseInputSchema = z.object({ goal: text, target: targetSchema, host: z.string().max(120).optional(), skill: z.string().max(4096).optional() }).strict();
11
+ export const conclusionSchema = z.object({ outcome: z.enum(['resolved', 'unresolved', 'needs-physical-work', 'insufficient-evidence']), summary: text, changes: z.array(text).max(100).default([]), remaining: z.array(text).max(100).default([]), baseline: z.string().uuid().optional(), verification: z.string().uuid().optional() }).strict();
12
+ // Structured credentials are excluded before local persistence; arbitrary output is
13
+ // still sensitive. Encryption is at rest with a same-user key, not an OS sandbox.
14
+ export function sanitize(value) {
15
+ if (typeof value === 'string')
16
+ return redact(value).replace(/\bK1\.[A-Za-z0-9_-]{43}\b/g, '[LIBRARY KEY]');
17
+ if (Array.isArray(value))
18
+ return value.map(sanitize);
19
+ if (value && typeof value === 'object')
20
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, /password|secret|token|authorization|credential|^code$/i.test(key) ? '[REDACTED]' : sanitize(item)]));
21
+ return value;
22
+ }
23
+ export class Cases {
24
+ root;
25
+ journal;
26
+ constructor(root = join(homedir(), '.diagnose', 'cases')) {
27
+ this.root = root;
28
+ this.journal = new Journal(root);
29
+ }
30
+ create(input) {
31
+ if (this.journal.list().length >= 100)
32
+ throw new Error('Case limit reached (100); export and remove old cases');
33
+ const value = { ...caseInputSchema.parse(input), id: randomUUID(), createdAt: new Date().toISOString(), evidence: [] };
34
+ this.save(value);
35
+ return value;
36
+ }
37
+ get(id) { z.string().uuid().parse(id); return this.journal.load(id).case; }
38
+ save(value) {
39
+ this.journal.save({ id: value.id, kind: 'process', state: 'case', createdAt: value.createdAt, updatedAt: '', ownerPid: 0, tokenHash: '', retainOnDisconnect: false, case: value });
40
+ }
41
+ list() { return this.journal.list().map(meta => { const value = meta.case; return { id: value.id, goal: value.goal, target: value.target, createdAt: value.createdAt, outcome: value.conclusion?.outcome ?? 'open', evidenceCount: value.evidence.length }; }); }
42
+ remove(id) { this.get(id); if (existsSync(join(this.root, id + '.lock')))
43
+ throw new Error('Case is in use; stop its agent before removing it'); unlinkSync(join(this.root, id + '.meta')); }
44
+ claim(id) {
45
+ this.get(id);
46
+ const path = join(this.root, id + '.lock'), token = randomUUID();
47
+ try {
48
+ writeFileSync(path, JSON.stringify({ pid: process.pid, token }), { flag: 'wx', mode: 0o600 });
49
+ }
50
+ catch (error) {
51
+ if (error.code === 'EEXIST')
52
+ throw new Error('Case already has a writer. Stop its agent, or use diagnose cases unlock ID after an unclean exit.');
53
+ throw error;
54
+ }
55
+ return () => { try {
56
+ if (JSON.parse(readFileSync(path, 'utf8')).token === token)
57
+ unlinkSync(path);
58
+ }
59
+ catch (error) {
60
+ if (error.code !== 'ENOENT')
61
+ throw error;
62
+ } };
63
+ }
64
+ unlock(id) {
65
+ this.get(id);
66
+ const path = join(this.root, id + '.lock'), lock = JSON.parse(readFileSync(path, 'utf8'));
67
+ if (!Number.isSafeInteger(lock.pid) || lock.pid <= 0)
68
+ throw new Error('Invalid case lock; inspect locally');
69
+ let alive = true;
70
+ try {
71
+ process.kill(lock.pid, 0);
72
+ }
73
+ catch (error) {
74
+ if (error.code === 'ESRCH')
75
+ alive = false;
76
+ }
77
+ if (alive)
78
+ throw new Error('Case writer is still alive; stop the agent first');
79
+ unlinkSync(path);
80
+ }
81
+ record(id, kind, data, taskId) {
82
+ const value = this.get(id);
83
+ if (value.evidence.length >= 200) {
84
+ value.recordingLimited = true;
85
+ this.save(value);
86
+ return undefined;
87
+ }
88
+ const serialized = JSON.stringify(sanitize(data));
89
+ const truncated = Buffer.byteLength(serialized) > 32768;
90
+ const evidence = { id: randomUUID(), at: new Date().toISOString(), kind, taskId, digest: createHash('sha256').update(serialized).digest('hex'), data: truncated ? { preview: serialized.slice(0, 8000), note: 'Evidence exceeded 32 KiB; only preview retained' } : JSON.parse(serialized), truncated };
91
+ value.evidence.push(evidence);
92
+ this.save(value);
93
+ return evidence;
94
+ }
95
+ finish(id, input) {
96
+ const conclusion = conclusionSchema.parse(input), value = this.get(id);
97
+ if (conclusion.outcome === 'resolved') {
98
+ const baseline = value.evidence.find(item => item.id === conclusion.baseline), verification = value.evidence.find(item => item.id === conclusion.verification);
99
+ const result = verification?.data?.result;
100
+ if (!baseline || baseline.kind !== 'task.result' || !verification || verification.kind !== 'task.result' || baseline.id === verification.id || value.evidence.indexOf(verification) <= value.evidence.indexOf(baseline) || verification.truncated || result?.status !== 'ok')
101
+ throw new Error('Resolved requires distinct baseline and later successful verification evidence IDs from this case');
102
+ }
103
+ for (const reference of [conclusion.baseline, conclusion.verification])
104
+ if (reference && !value.evidence.some(item => item.id === reference))
105
+ throw new Error('Unknown case evidence ID');
106
+ value.conclusion = sanitize(conclusion);
107
+ this.save(value);
108
+ return value;
109
+ }
110
+ report(id) {
111
+ const value = this.get(id);
112
+ // Deliberately exclude target addresses, command arguments and result bodies.
113
+ return { id: value.id, createdAt: value.createdAt, goal: sanitize(value.goal), target: { name: sanitize(value.target.name), model: sanitize(value.target.model), interface: value.target.interface }, skill: value.skill, conclusion: value.conclusion, recordingLimited: value.recordingLimited ?? false, evidence: value.evidence.map(({ id, at, kind, taskId, digest, truncated }) => ({ id, at, kind, taskId, digest, truncated })), note: 'Conclusion is an agent/diagnostician assessment, not an independent proof. Review free text for customer details before sharing.' };
114
+ }
115
+ }
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createInterface } from 'node:readline/promises';
3
3
  import { stdin, stdout } from 'node:process';
4
- import { createCode } from './crypto.js';
4
+ import { createCode, createInvitation } from './crypto.js';
5
5
  import { Peer } from './peer.js';
6
6
  import { ProbeEngine } from './engine.js';
7
7
  import { Operator } from './operator.js';
@@ -19,6 +19,9 @@ import { PairingStore, automatic, RememberedConnection } from './pairing.js';
19
19
  import { launchAgent, agentUsage } from './agent.js';
20
20
  import { History } from './history.js';
21
21
  import { cleanupLocal } from './maintenance.js';
22
+ import { skillsCommand, skillsUsage } from './skill-library.js';
23
+ import { knowledgeCommand, knowledgeUsage } from './knowledge-cli.js';
24
+ import { DEFAULT_IDLE_MS } from './session-limits.js';
22
25
  async function attachTerminal(operator, id) {
23
26
  let done = false, cursor = 0;
24
27
  const wasRaw = stdin.isRaw;
@@ -54,11 +57,27 @@ async function attachTerminal(operator, id) {
54
57
  }
55
58
  }
56
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
+ }
68
+ if (['cases', 'drafts', 'vault'].includes(process.argv[2])) {
69
+ await knowledgeCommand(process.argv[2], process.argv.slice(3));
70
+ return;
71
+ }
72
+ if (process.argv[2] === 'skills') {
73
+ await skillsCommand(process.argv.slice(3));
74
+ return;
75
+ }
57
76
  if (process.argv[2] === 'agent') {
58
77
  process.exitCode = await launchAgent(process.argv.slice(3));
59
78
  return;
60
79
  }
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' } } });
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' } } });
62
81
  const [command = 'help', relay = 'https://diagnose.fenginwind.com'] = positionals;
63
82
  if (command === 'history') {
64
83
  console.log(safeText(JSON.stringify(new History().list(), null, 2)));
@@ -79,7 +98,7 @@ async function main() {
79
98
  throw new Error('Usage: diagnose start|connect|terminal|mcp [relay-url]');
80
99
  const sessionMinutes = Number(values['session-minutes']), idleMinutes = Number(values['idle-minutes']);
81
100
  if (![sessionMinutes, idleMinutes].every(value => Number.isInteger(value) && value >= 0 && value <= 10080))
82
- throw new Error('Timeouts must be 0..10080 minutes; 0 disables endpoint timeout (relay maximum 7 days)');
101
+ throw new Error('Timeouts must be 0..10080 minutes; 0 disables that endpoint timeout');
83
102
  if (command === 'devices') {
84
103
  console.log(JSON.stringify(new PairingStore(join(homedir(), '.diagnose', 'pairings')).list('operator').map(({ name, id, relay }) => ({ name, id, relay })), null, 2));
85
104
  return;
@@ -91,11 +110,11 @@ async function main() {
91
110
  return;
92
111
  }
93
112
  if (command === 'mcp') {
94
- await serveMcp(relay, values.device);
113
+ await serveMcp(relay, values.device, values.case);
95
114
  return;
96
115
  }
97
116
  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.`);
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.`);
99
118
  return;
100
119
  }
101
120
  if (!stdin.isTTY || !stdout.isTTY)
@@ -132,6 +151,16 @@ async function main() {
132
151
  if (command === 'start') {
133
152
  const store = new PairingStore();
134
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
+ }
135
164
  const firstAudit = new Audit();
136
165
  resources = new SessionResources(join(homedir(), '.diagnose', 'resources'), firstAudit);
137
166
  let sessions = 0;
@@ -173,7 +202,7 @@ async function main() {
173
202
  if (shutdown.signal.aborted)
174
203
  break;
175
204
  const audit = sessions++ === 0 ? firstAudit : new Audit();
176
- const code = remembered?.code ?? createCode();
205
+ const code = remembered?.code ?? createInvitation();
177
206
  let provision;
178
207
  let grantTimer;
179
208
  peer = new Peer({ role: 'host', code, relay: remembered?.relay ?? relay, sessionMs: remembered ? 0 : sessionMinutes * 60000, provision: () => provision, accept: async ({ label, fingerprint, signal, remember }) => {
@@ -184,15 +213,30 @@ async function main() {
184
213
  if (remember)
185
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.');
186
215
  console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
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();
189
- const allowed = answer === 'y' || answer === 'a';
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';
190
234
  if (allowed && remember) {
191
235
  provision = createCode();
192
236
  remembered = store.add({ role: 'host', name: 'diagnostician', label, relay, code: provision });
193
237
  audit.record('pairing.remembered', { id: remembered.id });
194
238
  }
195
- if (answer === 'a') {
239
+ if (auto) {
196
240
  engine.setPermissionMode('auto');
197
241
  if (remembered) {
198
242
  remembered.autoUntil = Date.now() + 3600000;
@@ -274,6 +318,7 @@ async function main() {
274
318
  return true;
275
319
  }
276
320
  if (value === 'permissions ask') {
321
+ nextSessionApproval = 'review';
277
322
  autoRequestedAt = 0;
278
323
  clearTimeout(grantTimer);
279
324
  if (remembered) {
@@ -346,13 +391,16 @@ async function main() {
346
391
  rl.on('line', onLocalLine);
347
392
  try {
348
393
  await peer.open();
349
- console.log(remembered ? `Remembered diagnostician: ${safeText(remembered.label)}. Waiting for connections. Local commands: pairing, pause, resume, unpair, permissions ask, permissions auto [forever], cancel, jobs, exit. Audit: ${audit.path}` : `Relay: ${relay}\nAudit: ${audit.path}\nPairing code (10 minutes, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
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.`);
350
395
  console.log(`Session ended: ${safeText(await peer.ended)}`);
396
+ if (nextSessionApproval === 'everything')
397
+ nextSessionApproval = 'review';
351
398
  }
352
399
  catch (error) {
400
+ const collision = error.message.includes('Invitation locator occupied');
353
401
  if (!shutdown.signal.aborted)
354
- console.log(`Relay unavailable: ${safeText(error.message)}. Retained work remains local; retrying in 3 seconds.`);
355
- await delay(3000, undefined, { signal: shutdown.signal }).catch(() => { });
402
+ console.log(collision ? 'Choosing another invitation code...' : `Relay unavailable: ${safeText(error.message)}. Retained work remains local; retrying in 3 seconds.`);
403
+ await delay(collision ? 100 : 3000, undefined, { signal: shutdown.signal }).catch(() => { });
356
404
  }
357
405
  finally {
358
406
  clearTimeout(grantTimer);
package/dist/crypto.d.ts CHANGED
@@ -1,4 +1,11 @@
1
1
  export declare const NOISE_PROTOCOL = "Noise_NNpsk0_25519_ChaChaPoly_BLAKE2b";
2
+ export declare const INVITATION_MS: number;
3
+ export declare function createInvitation(): string;
4
+ export declare function parseInvitation(code: string): {
5
+ room: string;
6
+ secret: Buffer;
7
+ short: boolean;
8
+ };
2
9
  export declare function createCode(): string;
3
10
  export declare function parseCode(code: string): {
4
11
  room: string;
package/dist/crypto.js CHANGED
@@ -1,7 +1,22 @@
1
- import { randomBytes, createHash } from 'node:crypto';
1
+ import { randomBytes, randomInt, createHash } from 'node:crypto';
2
2
  import Noise from 'noise-handshake';
3
3
  import Cipher from 'noise-handshake/cipher.js';
4
4
  export const NOISE_PROTOCOL = 'Noise_NNpsk0_25519_ChaChaPoly_BLAKE2b';
5
+ export const INVITATION_MS = 30 * 60 * 1000;
6
+ export function createInvitation() {
7
+ const letters = Array.from({ length: 9 }, () => String.fromCharCode(97 + randomInt(26))).join('');
8
+ return letters.match(/.{3}/g).join('-');
9
+ }
10
+ export function parseInvitation(code) {
11
+ if (code.trim().startsWith('D1.'))
12
+ return { ...parseCode(code), short: false };
13
+ const letters = code.replace(/[\s-]/g, '').toLowerCase();
14
+ if (!/^[a-z]{9}$/.test(letters))
15
+ throw new Error('Enter the nine-letter invitation, for example abc-def-ghi');
16
+ // Only the public two-letter locator reaches the relay. Never hash the full
17
+ // code into a public locator: that would permit offline password guessing.
18
+ return { room: `S2.${letters.slice(0, 2)}`, secret: Buffer.from(letters.slice(2)), short: true };
19
+ }
5
20
  export function createCode() { return `D1.${randomBytes(12).toString('base64url')}.${randomBytes(32).toString('base64url')}`; }
6
21
  export function parseCode(code) {
7
22
  const match = /^D1\.([A-Za-z0-9_-]{16})\.([A-Za-z0-9_-]{43})$/.exec(code.trim());
package/dist/discover.js CHANGED
@@ -19,5 +19,5 @@ export async function inspectSystem() {
19
19
  }
20
20
  }
21
21
  const elevated = process.platform === 'win32' ? /S-1-16-(12288|16384)/.test(spawnSync('whoami', ['/groups'], { encoding: 'utf8', timeout: 3000, windowsHide: true }).stdout ?? '') : process.geteuid?.() === 0;
22
- return { platform: process.platform, arch: process.arch, release: os.release(), node: process.version, hostname: os.hostname(), cwd: process.cwd(), home: os.homedir(), username: os.userInfo().username, elevated, shell: process.platform === 'win32' ? process.env.ComSpec ?? 'cmd.exe' : process.env.SHELL ?? '/bin/sh', commands, serialPorts: await SerialPort.list(), protocol: 1, version: '0.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'] };
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.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
@@ -14,6 +14,7 @@ export declare class ProbeEngine {
14
14
  private sequenced?;
15
15
  private idle?;
16
16
  private lifetime?;
17
+ private ended;
17
18
  private mode;
18
19
  private owner;
19
20
  readonly resources: SessionResources;
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'));
@@ -26,6 +27,7 @@ export class ProbeEngine {
26
27
  sequenced;
27
28
  idle;
28
29
  lifetime;
30
+ ended = false;
29
31
  mode = 'ask';
30
32
  owner = randomUUID();
31
33
  resources;
@@ -59,12 +61,24 @@ export class ProbeEngine {
59
61
  this.notice = notice;
60
62
  this.resources = options.resources ?? new SessionResources(join(dirname(audit.path), basename(audit.path) + '.resources'), audit);
61
63
  this.resources.setAudit(audit);
62
- if (options.idleMs !== 0)
63
- this.idle = setTimeout(() => peer.close('Idle timeout'), options.idleMs ?? 600000);
64
- if (options.lifetimeMs !== 0)
65
- this.lifetime = setTimeout(() => peer.close('Session lifetime exceeded'), options.lifetimeMs ?? 3600000);
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
+ };
71
+ // Waiting for an invitation/approval is not diagnostic session time.
72
+ void peer.active.then(() => {
73
+ if (this.ended)
74
+ return;
75
+ refreshIdle();
76
+ if (options.lifetimeMs)
77
+ this.lifetime = setTimeout(() => peer.close('Session lifetime exceeded'), options.lifetimeMs);
78
+ }).catch(() => { });
79
+ peer.on('activity', refreshIdle);
66
80
  peer.on('message', (message) => {
67
- this.idle?.refresh();
81
+ refreshIdle();
68
82
  if (message.type === 'resource.request') {
69
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(() => { });
70
84
  return;
@@ -120,9 +134,9 @@ export class ProbeEngine {
120
134
  this.jobs.set(task.id, controller);
121
135
  void this.run(task, controller);
122
136
  });
123
- peer.on('closed', () => { 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())
124
138
  controller.abort(); void this.resources.disconnect(this.owner).catch(() => { }); try {
125
- audit.record('session.closed', {});
139
+ audit.record('session.closed', { reason: reason && redact(reason) });
126
140
  }
127
141
  catch { /* Session is already closed. */ } });
128
142
  }
@@ -0,0 +1,2 @@
1
+ export declare const installSkillUsage = "diagnose install-skill claude|codex|gemini";
2
+ export declare function installSkill(args: string[]): Promise<void>;
@@ -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
+ }
@@ -0,0 +1,2 @@
1
+ export declare const knowledgeUsage = "diagnose cases create INPUT.json | list | show ID | export ID | remove ID | unlock ID\ndiagnose drafts create INPUT.json | list | show ID | review ID | accept ID | reject ID | remove ID\ndiagnose vault init BACKUP_FILE | restore BACKUP_FILE | backup NEW_FILE\ndiagnose vault status | push library:NAME@REVISION | pull | revoke | forget [--relay URL]";
2
+ export declare function knowledgeCommand(command: string, argv: string[]): Promise<void>;