@masstensor/diagnose 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Diagnose
2
2
 
3
- 通用、临时、由用户逐次批准的远程 AI 诊断探针。MIT 开源,TypeScript 源码随安装包提供。Node.js **22.18+**。
3
+ 通用、临时、由用户控制权限的远程 AI 诊断探针。支持逐次审批、批量计划和会话自动批准。MIT 开源,TypeScript 源码随安装包提供。Node.js **22.18+**。
4
4
 
5
5
  ## 安装及使用
6
6
 
@@ -19,7 +19,15 @@ diagnose start
19
19
  diagnose connect
20
20
  ```
21
21
 
22
- 交互输入配对码及诊断者/AI 提供商标签。用户核对自报标签与会话指纹后确认。每次任务再分别确认执行与发送结果。代码不经命令行参数传入;不要公开分享代码。两端都主动连接 443,不需要用户开放端口。
22
+ 交互输入配对码及诊断者/AI 提供商标签。用户核对自报标签与会话指纹后选择权限。配对码不经命令行参数传入;不要公开分享代码。两端都主动连接 443,不需要用户开放端口。
23
+
24
+ **权限选择**(只在用户本机决定):
25
+
26
+ - 配对时输入 `y`:每个任务/整批计划各确认一次执行、一次合并结果发送,不按每个子步骤询问。
27
+ - 配对时输入 `a`:明确授权本次会话**自动执行并自动发送**,后续任务不再弹确认。命令有当前OS用户权限;输出会直接提供给诊断者及其AI。终端持续显示任务及发送摘要,审计继续记录。文本脱敏仍不是秘密识别保证,二进制不会自动脱敏。
28
+ - 会话中输入 `permissions` 查看模式;`permissions ask` 撤销自动权限、取消正在运行的任务/整批,后续恢复审批。已发送内容不能撤回。
29
+ - 想在会话中开启自动模式:先输入 `permissions auto` 阅读说明,再在60秒内输入 `permissions allow-auto` 明确确认。远端请求没有切换权限的字段。
30
+ - `cancel` 取消当前任务/整批,保留当前权限模式;`Ctrl+C` 或 `exit` 结束会话。新会话恢复默认逐次审批,不继承自动授权。
23
31
 
24
32
  诊断者终端输入 JSON,请求立即返回任务 ID,使用 `wait <id>` 查看,`cancel <id>` 取消,`exit` 退出:
25
33
 
@@ -32,6 +40,39 @@ diagnose connect
32
40
 
33
41
  所有命令接受可选的中继地址:`diagnose start https://your-relay.example`。远程中继强制 TLS;回环测试允许 ws/http。
34
42
 
43
+ ## 一次提交多个操作或整段脚本
44
+
45
+ 两端均需升级到 **0.2.0+**:`npm install -g @masstensor/diagnose@latest`。长会话超时选项需要新版中继;当前AWS中继随0.3更新。旧版本仍可使用原有单操作协议。
46
+
47
+ 批量JSON示例(交互终端粘贴时压成一行,AI/MCP可直接传结构化参数):
48
+
49
+ ```json
50
+ {
51
+ "operation": "batch.run",
52
+ "reason": "一次采集系统环境和运行时信息",
53
+ "arguments": {
54
+ "steps": [
55
+ {"operation":"system.inspect","arguments":{}},
56
+ {"operation":"process.script","arguments":{"interpreter":"node","script":"const os = require('node:os');\nconsole.log(JSON.stringify({uptime: os.uptime(), freeMemory: os.freemem()}));","timeoutMs":10000}}
57
+ ],
58
+ "stopOnError": true,
59
+ "timeoutMs": 60000
60
+ }
61
+ }
62
+ ```
63
+
64
+ 默认顺序执行,最多32步,不允许嵌套批量;遇错停止,显式设置 `stopOnError:false` 可继续独立步骤。整批总时限最多300秒,全部输出合计最多10MiB。返回每步状态及已完成/未运行数量,输出按 `0.stdout`、`1.file` 等区分。任何批次取消/断线/撤权都会终止当前进程组、释放串口并跳过后续步骤;已发生的修改不会自动回滚。
65
+
66
+ 整段脚本也可以独立提交:
67
+
68
+ ```json
69
+ {"operation":"process.script","arguments":{"interpreter":"/bin/sh","script":"uname -a\nprintf '\\n--- Disk ---\\n'\ndf -h\n","timeoutMs":30000},"reason":"一次采集系统和磁盘信息"}
70
+ ```
71
+
72
+ 必须明确指定解释器(如 `node`、`/bin/sh`)及可选 `args`、`cwd`。脚本通过stdin传入,默认不落临时脚本文件;人工审批时展示完整原文,一次授权整段脚本。脚本本身可以并发采集,但不会逐行审批。Windows应选择可从stdin读取脚本的解释器及对应参数。
73
+
74
+ 批量里的所有 `file.write` 会在整批审批前保存预览与旧文件哈希;若前面步骤修改了该目标,后续写入会因快照变化而拒绝,不会静默覆盖新内容。
75
+
35
76
  ## AI / MCP
36
77
 
37
78
  在诊断者电脑的 MCP 客户端配置中加入(确保其环境 PATH 可找到安装后的 diagnose):
@@ -40,7 +81,44 @@ diagnose connect
40
81
  {"mcpServers":{"diagnose":{"command":"diagnose","args":["mcp"]}}}
41
82
  ```
42
83
 
43
- 工具:`diagnose_pair(code,label)`、`diagnose_start(operation,arguments,reason)`、`diagnose_wait(id,timeoutMs,release)`、`diagnose_cancel(id)`、`diagnose_disconnect()`。等待一次最多 25 秒,pending 时继续轮询。大结果读取后可 release 释放诊断端缓存。MCP 使用本地 stdio,不暴露公网执行端口。配对码由你交给 AI,因此也会进入你所用 AI 的上下文;中继的加密边界不覆盖 AI 提供商。
84
+ 基础工具:`diagnose_pair(code,label)`、`diagnose_start(operation,arguments,reason)`、`diagnose_batch(steps,reason,stopOnError,timeoutMs)`、`diagnose_wait(id,timeoutMs,release)`、`diagnose_cancel(id)`、`diagnose_disconnect()`。AI优先用diagnose_batch提交整份采集计划;整段脚本使用diagnose_start的process.script。批量与脚本都立即返回一个任务ID。等待一次最多 25 秒,pending 时继续轮询。大结果读取后可 release 释放诊断端缓存。MCP 使用本地 stdio,不暴露公网执行端口。配对码由你交给 AI,因此也会进入你所用 AI 的上下文;中继的加密边界不覆盖 AI 提供商。
85
+
86
+ ## 0.3:接近 SSH 的诊断能力
87
+
88
+ 两端升级到0.3+。用户仍执行 `diagnose start`;诊断者可以执行 `diagnose terminal`,输入配对码后打开真正的交互式终端。支持持续的 cwd/环境、stdin、实时 stdout/stderr、终端尺寸调整和信号。Ctrl+C发往远端,Ctrl+]脱离终端;普通退出会关闭未显式保留的进程。
89
+
90
+ AI新增5个MCP工具:
91
+
92
+ | 工具 | 用途 |
93
+ |---|---|
94
+ | diagnose_process | 创建普通进程或PTY;指定cwd/env、timeoutMs、retainOnDisconnect |
95
+ | diagnose_resource | list/status/read/input/resize/signal/close;从返回cursor继续读取,检查ended及exitCode |
96
+ | diagnose_resume | 用原资源ID和resumeToken请求恢复;不重跑命令 |
97
+ | diagnose_transfer | upload/download后台无损传输,status/cancel查询进度;SHA-256校验、续传、显式覆盖 |
98
+ | diagnose_forward | 在获准net.forward句柄上启动、查看或关闭本地端点 |
99
+
100
+ 创建实时资源时,先在本机批准操作及**持续原始输入输出**,之后同一句柄内输入、读取、调整尺寸、信号或连接不逐次弹窗。自动模式仍仅由用户本机开启。创建成功只表示句柄已建立,进程是否成功须查看退出码。
101
+
102
+ 终端JSON示例:
103
+
104
+ ```json
105
+ {"operation":"process.open","arguments":{"executable":"/bin/sh","pty":true,"retainOnDisconnect":true,"timeoutMs":0},"reason":"持续交互诊断,断线后保留原进程"}
106
+ {"operation":"net.forward","arguments":{"direction":"local","host":"192.168.31.217","port":11500},"reason":"访问用户局域网内的网关TCP服务"}
107
+ ```
108
+
109
+ `wait <task>`取得资源ID和恢复凭据后,可使用 `resources`、`read <id> [cursor]`、`input <id> "一行输入\\n"`、`resize <id> 120 40`、`signal <id> SIGINT`、`close <id>`。`forward <id> [localPort]`启动转发。
110
+
111
+ 转发包括local固定远端目标、remote用户侧回环监听转至诊断者目标,以及socks诊断者侧SOCKS5 TCP代理。SOCKS的allowedHosts默认["*"]表示任意目标,应按需求缩小。监听仅限回环;不支持UDP、TUN或公共监听。
112
+
113
+ `upload {"localPath":"/local/file","remotePath":"/remote/file","reason":"上传诊断文件"}`;download交换源/目标含义。MCP同样传路径,不让大段base64进入AI上下文。上传先写私有暂存文件,完整SHA校验及目标旧哈希匹配后替换;下载使用.diagnose.part和0600恢复侧文件,完成校验后替换。文件路径/权限管理另有file.stat/list/mkdir/remove/rename/chmod;rename默认拒绝覆盖。
114
+
115
+ 用户本机 `jobs`查看资源、`recover <id>`重新生成恢复凭据、`secret <id>`向已批准进程输入隐藏本地文本(macOS/Linux;程序仍可能回显)。不要让AI收集系统密码;交互sudo使用本机输入,不自动提权。
116
+
117
+ 断线后探针继续运行并显示**新配对码**;需要用户再次确认,用ID与resumeToken恢复保留资源。普通进程默认不保留,文件传输默认保留。探针自身重启后可恢复加密输出及文件暂存,不能接管原进程的PTY;不会重跑创建命令。Ctrl+C/exit、cancel或permissions ask终止相应资源。恢复凭据与配对码均应私下分享。
118
+
119
+ `diagnose start --session-minutes 240 --idle-minutes 30`调整超时;0关闭端点对应计时,中继最多7天,帧计数安全上限仍生效。实时进程默认1小时,可设timeoutMs:0;每进程输出默认64MiB、最大1GiB,达到上限终止进程。完成输出保存在本机,不自动清理,可结束诊断后自行清理~/.diagnose/resources。
120
+
121
+ 这不是SSH协议服务器,不能直接使用ssh/scp/sftp客户端;不包含SSH证书体系、agent/X11转发、图形桌面或OS服务管理。可用获准脚本调用电脑已有工具。macOS已验收,Windows ConPTY及Linux探针仍需真实环境验收。
44
122
 
45
123
  ## 能力与约束
46
124
 
@@ -48,6 +126,8 @@ diagnose connect
48
126
  |---|---|
49
127
  | system.inspect | `{}`;OS、Node、串口枚举 |
50
128
  | process.run | executable、args、cwd?、timeoutMs?;直接 spawn,不自动加 shell |
129
+ | process.script | interpreter、script、args?、cwd?、timeoutMs?;完整脚本通过stdin交给显式解释器 |
130
+ | batch.run | steps、stopOnError?、timeoutMs?;一次审批整个顺序计划及合并结果 |
51
131
  | file.read | path、offset?、length?;每次最多 1 MiB |
52
132
  | file.write | path、content、expectedSha256?;预览前后内容,核对旧文件哈希,临时文件加 rename |
53
133
  | serial.capture | path、baudRate?、durationMs?;8N1,DTR/RTS=false,可能复位设备 |
@@ -55,7 +135,7 @@ diagnose connect
55
135
 
56
136
  网络/USB 专用诊断程序可通过 process.run 调用,无设备型号预设。任意获准进程拥有当前 OS 用户权限,**不是沙箱**;不自动提权,不安装常驻服务。通用进程的所有副作用无法完整跟踪,也无法通用回滚。文件写入检查可发现通常的编辑竞争,但不提供对恶意本机并发修改的隔离。
57
137
 
58
- 单任务执行;进程 60 秒默认、300 秒上限;串口最多300秒;采集输出10MiB上限;重复任务ID不再执行。10分钟空闲或60分钟会话结束。断线不重放,取消进程组并释放串口,重新诊断需新配对。POSIX进程组以外主动脱离的程序不能保证被终止。
138
+ 最多同时执行4个有限任务或整批计划;批内顺序执行。实时资源另有128个活动句柄上限。进程/脚本60秒默认、300秒上限;整批300秒默认/上限;串口最多300秒;整批合并输出10MiB上限;重复任务ID不再执行。10分钟空闲或60分钟会话结束。断线不重放,有限任务取消、串口释放;显式保留的实时进程和文件传输可在新配对后恢复。POSIX进程组以外主动脱离的程序不能保证被终止。
59
139
 
60
140
  ## 加密、审批与审计
61
141
 
@@ -63,9 +143,9 @@ Noise `NNpsk0_25519_ChaChaPoly_BLAKE2b`,256位随机配对秘密、临时X2551
63
143
 
64
144
  中继只保存内存房间和密文缓冲,不持久化内容、密钥或离线消息。仍可见IP、路由、连接时间及流量大小,也能阻断服务。配对秘密不发送给中继,持码仅证明持有权,标签不等于真实身份。
65
145
 
66
- 本机 `~/.diagnose/audit-*.jsonl` 默认权限0600,记录任务ID、操作类型、目标路径/可执行文件、读取范围/串口参数、完整参数摘要、审批、各输出流采集/发送字节数、取消和结果。工具写入文件时另记录路径、修改前后哈希及字节数。终端展示具体参数、写入前后内容与待发送预览;默认审计不保存内容或完整命令参数,避免落盘秘密。因此历史日志不是完整命令回放或文件修改监控。每次审计写入flush,审计不可写则停止任务。
146
+ 本机 `~/.diagnose/audit-*.jsonl` 默认权限0600,记录任务ID、操作类型、目标路径/可执行文件/解释器、读取范围/串口参数、完整参数摘要、审批、各输出流采集/发送字节数、取消和结果。批内每步有父批次ID和独立结果,自动模式另记权限变更及自动批准的执行/发送阶段。工具写入文件时另记录路径、修改前后哈希及字节数。人工审批终端展示具体参数、完整脚本、写入前后内容与待发送预览;自动模式显示有长度上限的任务/发送摘要。实时资源的原始输出及恢复元数据另存于本机~/.diagnose/resources,使用AES-256-GCM逐条加密;密钥0600保存在同一用户目录,不能防御已控制该OS账号的攻击者。默认审计不保存内容、脚本原文或完整命令参数,避免落盘秘密。因此历史日志不是完整命令回放或文件修改监控。每次审计写入flush,审计不可写则停止任务。
67
147
 
68
- 文本先做常见凭据脱敏并移除终端控制字符,再在本机预览并确认发送。正则不能识别所有秘密;二进制不自动脱敏,明确提示后逐次批准。采集到本机不等于已发送。进程输出在本地有上限地缓冲,批准发送后才传输。Ctrl+C撤销待审请求、取消任务并结束会话。
148
+ 有限任务的采集文本先做常见凭据脱敏并移除终端控制字符;实时终端、文件传输与TCP通道保持原始字节,不脱敏。人工模式在本机合并预览并确认发送;自动模式依据用户本地已授予的会话权限直接发送。正则不能识别所有秘密,二进制不自动脱敏。采集与发送分别审计。进程输出在本地有上限地缓冲,得到本次或会话发送授权后才传输。Ctrl+C撤销待审请求、取消任务并结束会话。
69
149
 
70
150
  ## 开发、测试、部署
71
151
 
package/dist/cli.js CHANGED
@@ -7,53 +7,242 @@ import { ProbeEngine } from './engine.js';
7
7
  import { Operator } from './operator.js';
8
8
  import { Audit, safeText } from './util.js';
9
9
  import { serveMcp } from './mcp.js';
10
+ import { SessionResources } from './resources.js';
11
+ import { homedir } from 'node:os';
12
+ import { join } from 'node:path';
13
+ import { upload, download } from './transfers.js';
14
+ import { forward } from './forward.js';
15
+ import { spawn } from 'node:child_process';
16
+ import { parseArgs } from 'node:util';
17
+ import { setTimeout as delay } from 'node:timers/promises';
18
+ async function attachTerminal(operator, id) {
19
+ let done = false, cursor = 0;
20
+ const wasRaw = stdin.isRaw;
21
+ const input = (bytes) => { const escape = bytes.indexOf(0x1d); if (escape >= 0) {
22
+ done = true;
23
+ bytes = bytes.subarray(0, escape);
24
+ } if (bytes.length)
25
+ void operator.resource({ id, action: 'input', data: bytes.toString('base64') }).catch(() => { done = true; }); };
26
+ const resize = () => { void operator.resource({ id, action: 'resize', cols: Math.max(20, Math.min(500, stdout.columns ?? 100)), rows: Math.max(5, Math.min(200, stdout.rows ?? 30)) }).catch(() => { }); };
27
+ stdin.setRawMode(true);
28
+ stdin.on('data', input);
29
+ stdin.resume();
30
+ stdout.on('resize', resize);
31
+ resize();
32
+ stdout.write('\r\n[Ctrl+] detaches; Ctrl+C is sent to the remote terminal]\r\n');
33
+ try {
34
+ while (!done) {
35
+ const value = await operator.resource({ id, action: 'read', cursor });
36
+ cursor = value.cursor;
37
+ for (const record of value.records)
38
+ stdout.write(Buffer.from(record.data, 'base64'));
39
+ if (value.ended)
40
+ break;
41
+ await new Promise(resolve => setTimeout(resolve, 25));
42
+ }
43
+ }
44
+ finally {
45
+ stdin.off('data', input);
46
+ stdout.off('resize', resize);
47
+ stdin.setRawMode(wasRaw);
48
+ stdin.pause();
49
+ stdout.write('\r\n');
50
+ }
51
+ }
10
52
  async function main() {
11
- const [command = 'help', ...args] = process.argv.slice(2);
12
- const relay = args[0] ?? 'https://diagnose.fenginwind.com';
13
- if (args.length > 1)
14
- throw new Error('Usage: diagnose start|connect|mcp [relay-url]');
53
+ const { positionals, values } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { 'session-minutes': { type: 'string', default: '60' }, 'idle-minutes': { type: 'string', default: '10' } } });
54
+ const [command = 'help', relay = 'https://diagnose.fenginwind.com'] = positionals;
55
+ if (positionals.length > 2)
56
+ throw new Error('Usage: diagnose start|connect|terminal|mcp [relay-url]');
57
+ const sessionMinutes = Number(values['session-minutes']), idleMinutes = Number(values['idle-minutes']);
58
+ if (![sessionMinutes, idleMinutes].every(value => Number.isInteger(value) && value >= 0 && value <= 10080))
59
+ throw new Error('Timeouts must be 0..10080 minutes; 0 disables endpoint timeout (relay maximum 7 days)');
15
60
  if (command === 'mcp') {
16
61
  await serveMcp(relay);
17
62
  return;
18
63
  }
19
- if (!['start', 'connect'].includes(command)) {
20
- console.log('diagnose start|connect|mcp [relay-url]\nNode.js >=22.18. Pairing codes are entered interactively, never as arguments.');
64
+ if (!['start', 'connect', 'terminal'].includes(command)) {
65
+ console.log('diagnose start|connect|terminal|mcp [relay-url]\nNode.js >=22.18. Pairing codes are entered interactively, never as arguments.');
21
66
  return;
22
67
  }
23
68
  if (!stdin.isTTY || !stdout.isTTY)
24
69
  throw new Error('Interactive terminal required. AI clients should use diagnose mcp.');
25
70
  const rl = createInterface({ input: stdin, output: stdout });
26
71
  const shutdown = new AbortController();
27
- let peer;
28
- const stop = () => { shutdown.abort(); peer?.close('User ended session'); rl.close(); };
72
+ let peer, engine;
73
+ const forwards = new Map();
74
+ let resources, promptActive = false, secretPending;
75
+ let localCommand = () => false;
76
+ const stop = () => { shutdown.abort(); peer?.close('User ended session'); void resources?.revoke().catch(() => { }); rl.close(); };
29
77
  rl.on('SIGINT', stop);
78
+ process.once('SIGINT', stop);
30
79
  process.once('SIGTERM', stop);
31
- const ask = async (text, signal = shutdown.signal) => (await rl.question(safeText(text) + ' [y/N] ', { signal })).trim().toLowerCase() === 'y';
80
+ rl.once('close', () => { shutdown.abort(); peer?.close('User terminal closed'); });
81
+ const ask = async (text, signal = shutdown.signal, taskApproval = false) => {
82
+ while (true) {
83
+ let answer;
84
+ promptActive = true;
85
+ try {
86
+ answer = (await rl.question(safeText(text) + ' [y/N] ', { signal })).trim();
87
+ }
88
+ finally {
89
+ promptActive = false;
90
+ }
91
+ if (!localCommand(answer))
92
+ return answer.toLowerCase() === 'y';
93
+ signal.throwIfAborted();
94
+ if (taskApproval && engine?.permissionMode === 'auto')
95
+ return true;
96
+ }
97
+ };
32
98
  try {
33
99
  if (command === 'start') {
34
- const audit = new Audit();
35
- const code = createCode();
36
- peer = new Peer({ role: 'host', code, relay, accept: async ({ label, fingerprint, signal }) => {
37
- console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
38
- const allowed = await ask('Allow this temporary diagnostic session?', signal);
39
- audit.record('session.pairing-decision', { allowed, fingerprint });
40
- return allowed;
41
- } });
42
- new ProbeEngine(peer, async (request) => {
43
- 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`);
44
- 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);
45
- }, audit, message => console.log(safeText(message)));
46
- await peer.open();
47
- console.log(`Relay: ${relay}\nAudit: ${audit.path}\nPairing code (10 minutes, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
48
- console.log(`Session ended: ${safeText(await peer.ended)}`);
100
+ const firstAudit = new Audit();
101
+ resources = new SessionResources(join(homedir(), '.diagnose', 'resources'), firstAudit);
102
+ let sessions = 0;
103
+ while (!shutdown.signal.aborted) {
104
+ const audit = sessions++ === 0 ? firstAudit : new Audit();
105
+ const code = createCode();
106
+ peer = new Peer({ role: 'host', code, relay, sessionMs: sessionMinutes * 60000, accept: async ({ label, fingerprint, signal }) => {
107
+ console.log(`\nRequested by: ${safeText(label)} (self-asserted identity)\nFingerprint: ${fingerprint}\nResults will be available to the diagnostician and their AI provider.`);
108
+ console.log('Choose y: approve each task/batch and its transfer.\nChoose a: grant automatic execution AND transmission for 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.');
109
+ const answer = (await rl.question('Allow this temporary diagnostic session? [y / a=auto / N] ', { signal })).trim().toLowerCase();
110
+ const allowed = answer === 'y' || answer === 'a';
111
+ if (answer === 'a')
112
+ engine.setPermissionMode('auto');
113
+ audit.record('session.pairing-decision', { allowed, fingerprint });
114
+ return allowed;
115
+ } });
116
+ engine = new ProbeEngine(peer, async (request) => {
117
+ 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`);
118
+ 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);
119
+ }, audit, message => console.log(safeText(message)), { resources, idleMs: idleMinutes * 60000, lifetimeMs: sessionMinutes * 60000 });
120
+ let active = false, autoRequestedAt = 0;
121
+ 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.`); });
122
+ localCommand = value => {
123
+ if (!active && !['jobs', 'cancel', 'exit', 'permissions ask'].includes(value) && !value.startsWith('recover ') && !value.startsWith('secret '))
124
+ return false;
125
+ if (value === 'permissions') {
126
+ 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.`);
127
+ return true;
128
+ }
129
+ if (value === 'permissions auto') {
130
+ autoRequestedAt = Date.now();
131
+ console.log('AUTO grants this session 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.');
132
+ return true;
133
+ }
134
+ if (value === 'permissions allow-auto') {
135
+ if (autoRequestedAt && Date.now() - autoRequestedAt < 60000) {
136
+ engine.setPermissionMode('auto');
137
+ autoRequestedAt = 0;
138
+ }
139
+ else
140
+ console.log('No pending grant. First type "permissions auto" and read its explanation.');
141
+ return true;
142
+ }
143
+ if (value === 'permissions ask') {
144
+ autoRequestedAt = 0;
145
+ engine.setPermissionMode('ask');
146
+ void resources.revoke().catch(error => console.error(safeText(error.message)));
147
+ console.log('Approval required. Automatic permissions revoked; any active work is cancelled.');
148
+ return true;
149
+ }
150
+ if (value === 'cancel') {
151
+ engine.cancelAll();
152
+ void resources.revoke().catch(error => console.error(safeText(error.message)));
153
+ console.log('Cancellation requested for the current task/batch and retained resources.');
154
+ return true;
155
+ }
156
+ if (value === 'jobs') {
157
+ console.log(safeText(JSON.stringify(resources.listLocal(), null, 2)));
158
+ return true;
159
+ }
160
+ if (value.startsWith('recover ')) {
161
+ const id = value.slice(8).trim();
162
+ console.log(`Resource: ${id}\nNew recovery credential (share privately): ${resources.renewCredential(id)}`);
163
+ return true;
164
+ }
165
+ if (value.startsWith('secret ')) {
166
+ if (promptActive || secretPending) {
167
+ console.log('Finish the current approval before local hidden input.');
168
+ return true;
169
+ }
170
+ if (process.platform === 'win32') {
171
+ console.log('Hidden local input is not yet validated on Windows; use native local OS authentication.');
172
+ return true;
173
+ }
174
+ const id = value.slice(7).trim();
175
+ secretPending = (async () => {
176
+ console.log('Local input goes directly to the approved process. Use only a trusted foreground program; its output can still be transmitted.');
177
+ const wasRaw = stdin.isRaw;
178
+ rl.pause();
179
+ stdin.setRawMode(false);
180
+ try {
181
+ const value = await new Promise((resolveInput, reject) => { const chunks = []; const child = spawn('/bin/bash', ['-c', 'IFS= read -r -s -p "Hidden local input: " v; printf "%s" "$v"'], { stdio: ['inherit', 'pipe', 'inherit'] }); child.stdout.on('data', bytes => chunks.push(bytes)); child.on('error', reject); child.on('close', code => code === 0 ? resolveInput(Buffer.concat(chunks)) : reject(new Error('Local input cancelled'))); });
182
+ await resources.localInput(id, Buffer.concat([value, Buffer.from('\n')]));
183
+ value.fill(0);
184
+ stdout.write('\nLocal input sent.\n');
185
+ }
186
+ finally {
187
+ stdin.setRawMode(wasRaw);
188
+ rl.resume();
189
+ }
190
+ })().catch(error => console.error(safeText(error.message))).finally(() => { secretPending = undefined; });
191
+ return true;
192
+ }
193
+ if (value === 'exit') {
194
+ stop();
195
+ return true;
196
+ }
197
+ return false;
198
+ };
199
+ const onLocalLine = (value) => { try {
200
+ if (!localCommand(value.trim()))
201
+ console.log('Local commands: permissions, permissions auto, permissions ask, jobs, recover <id>, secret <id>, cancel, exit.');
202
+ }
203
+ catch (error) {
204
+ console.error(safeText(error.message));
205
+ stop();
206
+ } };
207
+ rl.on('line', onLocalLine);
208
+ try {
209
+ await peer.open();
210
+ console.log(`Relay: ${relay}\nAudit: ${audit.path}\nPairing code (10 minutes, share privately):\n${code}\nCtrl+C ends the session and cancels active tasks.`);
211
+ console.log(`Session ended: ${safeText(await peer.ended)}`);
212
+ }
213
+ catch (error) {
214
+ if (!shutdown.signal.aborted)
215
+ console.log(`Relay unavailable: ${safeText(error.message)}. Retained work remains local; retrying in 3 seconds.`);
216
+ await delay(3000, undefined, { signal: shutdown.signal }).catch(() => { });
217
+ }
218
+ finally {
219
+ rl.off('line', onLocalLine);
220
+ }
221
+ active = false;
222
+ if (secretPending)
223
+ await secretPending;
224
+ if (!shutdown.signal.aborted)
225
+ console.log('Probe is still running. Retained resources can be resumed after a NEW pairing and local authorization; commands are never replayed. Ctrl+C closes all resources.');
226
+ }
49
227
  }
50
228
  else {
51
229
  const code = (await rl.question('Pairing code: ', { signal: shutdown.signal })).trim();
52
230
  const label = await rl.question('Your label / AI provider: ', { signal: shutdown.signal });
53
231
  peer = new Peer({ role: 'join', code, relay, label });
54
232
  const operator = new Operator(peer);
233
+ if (command === 'terminal') {
234
+ await peer.open();
235
+ 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' });
236
+ if (result.result.status !== 'ok')
237
+ throw new Error(result.result.error ?? result.result.status);
238
+ rl.removeAllListeners('SIGINT');
239
+ rl.removeAllListeners('close');
240
+ rl.close();
241
+ await attachTerminal(operator, result.result.data.id);
242
+ return;
243
+ }
55
244
  await peer.open();
56
- console.log(`Connected. Fingerprint: ${peer.fingerprint}\nEnter JSON {"operation":"system.inspect","arguments":{},"reason":"Inspect environment"}.\nOther commands: cancel <task-id>, wait <task-id>, exit. Requests return immediately.`);
245
+ console.log(`Connected. Fingerprint: ${peer.fingerprint}\nEnter task JSON: batch.run, process.script, process.open (pty/stdin), file.transfer, net.forward, resource.resume.\nCommands: cancel <task>, wait <task>, resources, read <resource> [cursor], input <resource> <JSON string>, resize <resource> <cols> <rows>, signal <resource> <SIGINT>, close <resource>, forward <resource> [localPort], upload/download <JSON>, exit.\nLive resources require v0.3+ on both endpoints. diagnose terminal opens a native terminal.`);
57
246
  peer.ended.then(() => stop());
58
247
  while (!shutdown.signal.aborted) {
59
248
  const line = (await rl.question('diagnose> ', { signal: shutdown.signal })).trim();
@@ -66,6 +255,41 @@ async function main() {
66
255
  }
67
256
  else if (line.startsWith('wait '))
68
257
  console.log(safeText(JSON.stringify(await operator.wait(line.slice(5).trim(), 1000), null, 2)));
258
+ else if (line === 'resources')
259
+ console.log(JSON.stringify(await operator.resource({ action: 'list' }), null, 2));
260
+ else if (line.startsWith('read ')) {
261
+ const [, id, cursor] = line.split(/\s+/);
262
+ const value = await operator.resource({ id, action: 'read', cursor: Number(cursor ?? 0) });
263
+ console.log(safeText(JSON.stringify({ ...value, ...(value.records ? { records: value.records.map(record => ({ stream: record.stream, text: Buffer.from(record.data, 'base64').toString() })) } : {}) }, null, 2)));
264
+ }
265
+ else if (line.startsWith('input ')) {
266
+ const match = /^input (\S+) (.+)$/.exec(line);
267
+ if (!match)
268
+ throw new Error('input <id> <JSON string>');
269
+ console.log(await operator.resource({ id: match[1], action: 'input', data: Buffer.from(JSON.parse(match[2])).toString('base64') }));
270
+ }
271
+ else if (/^(resize|signal|close) /.test(line)) {
272
+ const [action, id, a, b] = line.split(/\s+/);
273
+ if (action === 'close' && forwards.has(id)) {
274
+ await forwards.get(id).close();
275
+ forwards.delete(id);
276
+ }
277
+ else
278
+ console.log(await operator.resource({ id, action: action, ...(action === 'resize' ? { cols: Number(a), rows: Number(b) } : action === 'signal' ? { signal: (a ?? 'SIGINT') } : {}) }));
279
+ }
280
+ else if (line.startsWith('forward ')) {
281
+ const [, id, port] = line.split(/\s+/);
282
+ if (forwards.has(id) && !forwards.get(id).closed)
283
+ throw new Error('Forward already open');
284
+ const listener = await forward(operator, id, Number(port ?? 0));
285
+ forwards.set(id, listener);
286
+ console.log(`Forward active: ${listener.direction} ${listener.host}:${listener.port}; close ${id} releases both endpoints.`);
287
+ }
288
+ else if (/^(upload|download) /.test(line)) {
289
+ const separator = line.indexOf(' '), action = line.slice(0, separator), options = JSON.parse(line.slice(separator + 1));
290
+ const settings = { ...options, signal: shutdown.signal, progress: (value) => console.log(safeText(JSON.stringify(value))) };
291
+ console.log(await (action === 'upload' ? upload(operator, options.localPath, options.remotePath, options.reason, settings) : download(operator, options.remotePath, options.localPath, options.reason, settings)));
292
+ }
69
293
  else if (line)
70
294
  console.log(`Task: ${await operator.start(JSON.parse(line))}`);
71
295
  }
@@ -76,7 +300,10 @@ async function main() {
76
300
  }
77
301
  }
78
302
  finally {
303
+ for (const value of forwards.values())
304
+ await value.close();
79
305
  stop();
306
+ await resources?.revoke();
80
307
  }
81
308
  }
82
309
  main().catch(error => { console.error(safeText(error.name === 'AbortError' ? 'Session ended' : error.message)); process.exitCode = 1; });
@@ -0,0 +1 @@
1
+ export declare function inspectSystem(): Promise<Record<string, unknown>>;
@@ -0,0 +1,23 @@
1
+ import os from 'node:os';
2
+ import { access } from 'node:fs/promises';
3
+ import { constants } from 'node:fs';
4
+ import { delimiter, join } from 'node:path';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { SerialPort } from 'serialport';
7
+ export async function inspectSystem() {
8
+ const commands = {};
9
+ for (const name of ['node', 'sh', 'bash', 'zsh', 'pwsh', 'powershell', 'cmd', 'python3', 'git', 'curl', 'sudo', 'ssh']) {
10
+ outer: for (const directory of (process.env.PATH ?? '').split(delimiter))
11
+ for (const suffix of process.platform === 'win32' ? ['', '.exe', '.cmd', '.bat'] : ['']) {
12
+ const path = join(directory, name + suffix);
13
+ try {
14
+ await access(path, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
15
+ commands[name] = path;
16
+ break outer;
17
+ }
18
+ catch { }
19
+ }
20
+ }
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.3.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
+ }
package/dist/engine.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { Peer } from './peer.js';
2
2
  import { type ApprovalHandler } from './schema.js';
3
3
  import { Audit } from './util.js';
4
+ import { SessionResources } from './resources.js';
5
+ export type PermissionMode = 'ask' | 'auto';
4
6
  export declare class ProbeEngine {
5
7
  private peer;
6
8
  private approve;
@@ -8,12 +10,27 @@ export declare class ProbeEngine {
8
10
  private notice;
9
11
  private jobs;
10
12
  private seen;
11
- private idle;
12
- private lifetime;
13
- constructor(peer: Peer, approve: ApprovalHandler, audit: Audit, notice?: (message: string) => void);
13
+ private idle?;
14
+ private lifetime?;
15
+ private mode;
16
+ private owner;
17
+ readonly resources: SessionResources;
18
+ private approvalQueue;
19
+ get permissionMode(): PermissionMode;
20
+ setPermissionMode(mode: PermissionMode): void;
21
+ cancelAll(): void;
22
+ constructor(peer: Peer, approve: ApprovalHandler, audit: Audit, notice?: (message: string) => void, options?: {
23
+ resources?: SessionResources;
24
+ idleMs?: number;
25
+ lifetimeMs?: number;
26
+ });
14
27
  private reply;
15
28
  private finish;
16
29
  private permission;
30
+ private decidePermission;
31
+ private recordRequest;
32
+ private runAtomic;
33
+ private runBatch;
17
34
  private run;
18
35
  private transfer;
19
36
  }