jbc-dssi 1.1.105 → 1.1.107

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/index.js CHANGED
@@ -24,6 +24,7 @@ import { parseUiTuning, formatTuning, resolveRotateConfig } from './lib/ui-tunin
24
24
  import { createRestartAutocheck } from './lib/restart-autocheck.js';
25
25
  import { createGroupsEventBuffer, shouldBufferGroupEvent } from './lib/groups-event-buffer.js';
26
26
  import { createScheduleEngine } from './lib/schedules.js';
27
+ import { createProcEngine } from './lib/proc-commands.js';
27
28
 
28
29
  /*
29
30
  * ★ 协议层与瘦身层**直接引用 core**,本目录不再保有自己的副本。
@@ -405,6 +406,7 @@ export function activateRelay(ctx, opts) {
405
406
  * schedules 的版本,准入一通过就撞上这个 ReferenceError。
406
407
  */
407
408
  schedules,
409
+ proc,
408
410
  log,
409
411
  onChannelReady,
410
412
  onChannelClosed,
@@ -577,6 +579,7 @@ export function activateRelay(ctx, opts) {
577
579
  dssAgent,
578
580
  groups,
579
581
  schedules,
582
+ proc,
580
583
  log,
581
584
  });
582
585
  log('业务通路已就绪');
@@ -1157,8 +1160,39 @@ function activate(ctx, config) {
1157
1160
  } else {
1158
1161
  log('[schedules] 定时任务能力未启用(dssAgent 未启用或配置关闭)');
1159
1162
  }
1163
+ /*
1164
+ * 程序指令(2026-11-09 老谢定):确定性脚本/流程的白名单入口。
1165
+ *
1166
+ * 与 schedules 的区别:定时任务是"到点自动跑",这里是"人点一下就跑"。
1167
+ * 手机只发 指令 id + 参数;脚本、路径、参数白名单全在电脑侧,手机传不了 shell。
1168
+ * 危险指令要一次性 nonce(proc_list 发、proc_run 用、30s 失效),单飞互斥。
1169
+ * 不依赖 dssAgent(体检/重启都不需要它),所以单独初始化、单独开关。
1170
+ */
1171
+ let proc = null;
1172
+ if (config.proc?.enabled !== false) {
1173
+ try {
1174
+ proc = createProcEngine({
1175
+ log,
1176
+ repoRoot: typeof config.proc?.repoRoot === 'string' ? config.proc.repoRoot : '',
1177
+ commandsFile: typeof config.proc?.commandsFile === 'string' ? config.proc.commandsFile : undefined,
1178
+ runsDir: typeof config.proc?.runsDir === 'string' ? config.proc.runsDir : undefined,
1179
+ version: pluginVersion(),
1180
+ // 执行结束(含排程型)走与预览同一个推送口:遍历 live + relayChannels
1181
+ onEvent: pushDssAgentEvent,
1182
+ });
1183
+ log('[proc] 程序指令能力已启用(DSS_AGENT_CMD: proc_*)');
1184
+ } catch (err) {
1185
+ log(`[proc] 初始化失败:${err?.message ?? err}`);
1186
+ proc = null;
1187
+ }
1188
+ } else {
1189
+ log('[proc] 程序指令能力未启用(配置关闭)');
1190
+ }
1160
1191
  // 插件卸载:退订 session/event、清掉 500ms 合并定时器(否则会往死连接写帧)
1161
- if (typeof ctx.effect === 'function') ctx.effect(() => () => dssAgent?.dispose?.());
1192
+ if (typeof ctx.effect === 'function') ctx.effect(() => () => {
1193
+ dssAgent?.dispose?.();
1194
+ proc?.dispose?.();
1195
+ });
1162
1196
 
1163
1197
  /** 待续任务队列文件(groups 写、autocheck 读;默认插件自己的持久目录,不用 /tmp)。 */
1164
1198
  const pendingTasksFile =
@@ -1275,6 +1309,7 @@ function activate(ctx, config) {
1275
1309
  dssAgent,
1276
1310
  groups,
1277
1311
  schedules,
1312
+ proc,
1278
1313
  log,
1279
1314
  });
1280
1315
  } catch (err) {
@@ -1366,6 +1401,7 @@ function activate(ctx, config) {
1366
1401
  dssAgent,
1367
1402
  groups,
1368
1403
  schedules,
1404
+ proc,
1369
1405
  deviceAuthFile,
1370
1406
  log,
1371
1407
  // 中继业务通道的登记/摘除回调(界面配置推送要靠它拿到通道)
@@ -1778,6 +1814,8 @@ class BridgeConnection {
1778
1814
  this.botsMeta = opts.botsMeta ?? null;
1779
1815
  this.dssAgent = opts.dssAgent ?? null;
1780
1816
  this.schedules = opts.schedules ?? null;
1817
+ /** 程序指令执行器(2026-11-09):手机 proc_* 命令的电脑侧实现。 */
1818
+ this.proc = opts.proc ?? null;
1781
1819
  /** 群聊能力(GROUPS_* / ROOM_SNAPSHOT 帧);随群模块/配置开关启用。 */
1782
1820
  this.groups = opts.groups ?? null;
1783
1821
  this.botsSeq = 0;
@@ -1803,6 +1841,8 @@ class BridgeConnection {
1803
1841
  ...(this.bots ? ['bots'] : []),
1804
1842
  ...(this.dssAgent ? ['dssAgent'] : []),
1805
1843
  ...(this.groups ? ['groups'] : []),
1844
+ // 程序指令(2026-11-09):手机据此决定「程序指令」页显示列表还是"插件需更新"
1845
+ ...(this.proc ? ['proc'] : []),
1806
1846
  // 模型面板(模型 + 推理强度):电脑侧有 sessionController 就能提供
1807
1847
  ...(this.ctx.get?.('sessionController') ? ['model'] : []),
1808
1848
  // 会话归档:电脑侧有 workspaceRegistry 就能提供
@@ -2299,15 +2339,33 @@ class BridgeConnection {
2299
2339
  }
2300
2340
 
2301
2341
  async #dssAgentCommand(payload) {
2302
- if (!this.dssAgent) {
2303
- this.fail('智能体能力未启用(电脑侧插件需更新或已关闭)');
2304
- return;
2305
- }
2306
2342
  const op = typeof payload?.op === 'string' ? payload.op : '';
2307
2343
  if (op === '') {
2308
2344
  this.fail('dssAgent 命令缺少 op');
2309
2345
  return;
2310
2346
  }
2347
+ /*
2348
+ * 程序指令(2026-11-09):同样复用 DSS_AGENT_CMD 帧、以 `proc_` 前缀路由。
2349
+ * ★ 放在 dssAgent 判空**之前**:体检/重启不依赖 dssAgent,dssAgent 没起来时
2350
+ * 这两条也该能用(那是排查手段本身)。proc 自己判空并给出明确原因。
2351
+ */
2352
+ if (op.startsWith('proc_')) {
2353
+ if (!this.proc) {
2354
+ this.fail('程序指令能力未启用(电脑侧插件需更新,或配置里 proc.enabled=false)');
2355
+ return;
2356
+ }
2357
+ try {
2358
+ const result = await this.proc.command(op, payload);
2359
+ this.send(FRAME.DSS_AGENT_EVENT, { type: 'ack', op, ...(result ?? {}) });
2360
+ } catch (err) {
2361
+ this.fail(`程序指令执行失败:${err?.message ?? err}`);
2362
+ }
2363
+ return;
2364
+ }
2365
+ if (!this.dssAgent) {
2366
+ this.fail('智能体能力未启用(电脑侧插件需更新或已关闭)');
2367
+ return;
2368
+ }
2311
2369
  /*
2312
2370
  * 定时任务(2026-11-08):复用 DSS_AGENT_CMD 帧、以 `schedule_` 前缀路由到
2313
2371
  * schedules 引擎(它再调 DSH Host 的 schedule 服务),不新增帧类型。
@@ -2786,6 +2844,8 @@ class BridgeConnection {
2786
2844
  ...(this.bots ? ['bots'] : []),
2787
2845
  ...(this.dssAgent ? ['dssAgent'] : []),
2788
2846
  ...(this.groups ? ['groups'] : []),
2847
+ // 程序指令(2026-11-09):手机据此决定「程序指令」页显示列表还是"插件需更新"
2848
+ ...(this.proc ? ['proc'] : []),
2789
2849
  // 模型面板(模型 + 推理强度):电脑侧有 sessionController 就能提供
2790
2850
  ...(this.ctx.get?.('sessionController') ? ['model'] : []),
2791
2851
  // 会话归档:电脑侧有 workspaceRegistry 就能提供
@@ -0,0 +1,615 @@
1
+ /**
2
+ * `jbc-dssi/lib/proc-commands.js` —— 「程序指令」执行器(2026-11-09 老谢定)。
3
+ *
4
+ * 定位(与老谢对齐的结论):
5
+ * · **确定性脚本/流程的白名单入口**:手机只发「指令 id + 参数」,
6
+ * 电脑侧按白名单执行本地脚本,回传摘要 + 结果文件路径;完整日志留在电脑。
7
+ * · **手机不能传 shell、路径、可执行文件** —— 白名单里没有的 id 一律拒绝。
8
+ * · 危险指令(发版/重启/停服务…)必须:手机二次确认 + 一次性 nonce(30s、用一次即废)。
9
+ * · **票据按需领取**(2026-11-09 真机修复):nonce 由 `proc_ticket` 在"用户点确认的瞬间"签发,
10
+ * 不是打开页面时预取 —— 否则用户看一眼说明再确认,30 秒早过了,重启永远点不动。
11
+ * · 同一指令单飞;危险级共用一把全局锁(防发版/重启踩踏);到点超时杀进程。
12
+ * · 每次执行留痕:`proc-runs/<runId>.log`(脚本输出)+ `proc-runs/index.jsonl`(一行一条)。
13
+ *
14
+ * 不做什么:
15
+ * · 不做调度(到点执行是 `schedules.js` 的事)、不做权限系统(设备准入已有);
16
+ * · 不把日志/密钥传回手机;不替调用方解释业务结果 —— summary 只是"人话一行"。
17
+ *
18
+ * 一期的两条:
19
+ * · `check.health` 体检 —— 纯 JS 探针(端口 / 配对 / 准入 / 群数据 / 磁盘 / 版本),不依赖仓库;
20
+ * · `env.restart_dsh` 重启dsh —— 调仓库里**冻结**的 `scripts/restart-dsh-web.py`,
21
+ * 属"排程型":先回执再重启(进程会被自己重启掉,结束事件发不出去),
22
+ * 重启后的核验由既有 restart-autocheck 负责回群。
23
+ *
24
+ * 白名单文件:`~/.dsh/jbc-dssi/proc-commands.json`(不进 git;不存在 = 只有内置两条)。
25
+ * 文件格式:`{ "v": 1, "commands": [ {id, name, desc, danger, timeoutMs, args, script} ] }`,
26
+ * 同 id 覆盖内置;`script` 支持 `{rel: "scripts/x.py"}`(需配 repoRoot)或 `{abs: "/abs/x.py"}`。
27
+ */
28
+ import fs from 'node:fs';
29
+ import net from 'node:net';
30
+ import { spawn } from 'node:child_process';
31
+ import { randomBytes } from 'node:crypto';
32
+ import { join, isAbsolute } from 'node:path';
33
+ import { homedir } from 'node:os';
34
+
35
+ /** 高危指令的一次性 nonce 有效期。 */
36
+ export const NONCE_TTL_MS = 30_000;
37
+ /** 参数个数上限(防误传长串)。 */
38
+ const MAX_ARGS = 6;
39
+ /** summary 上限(老谢要求回传是"简短反馈")。 */
40
+ const SUMMARY_MAX = 500;
41
+ /** 默认超时。 */
42
+ const DEFAULT_TIMEOUT_MS = 60_000;
43
+ /** 指令危险级(决定要不要确认/nonce)。 */
44
+ const DANGERS = new Set(['low', 'mid', 'high']);
45
+
46
+ /**
47
+ * 内置指令(一期两条)。白名单文件里同 id 会覆盖这里。
48
+ *
49
+ * 为什么内置而不是全放文件:新装机器"体检"要能直接跑(它不依赖仓库),
50
+ * 否则白名单文件一丢,程序指令页就是空的、连自检入口都没有。
51
+ */
52
+ export const PROC_DEFAULTS = [
53
+ {
54
+ id: 'check.health',
55
+ name: '体检',
56
+ desc: '电脑侧健康检查:DSH 端口 / 插件版本 / 配对 / 准入 / 群数据 / 磁盘',
57
+ danger: 'low',
58
+ timeoutMs: DEFAULT_TIMEOUT_MS,
59
+ args: [],
60
+ builtin: 'health',
61
+ },
62
+ {
63
+ id: 'env.restart_dsh',
64
+ name: '重启dsh',
65
+ desc: '重启电脑侧 dsh web(会短暂断开连接,约 60 秒后自动核验并回群)',
66
+ danger: 'high',
67
+ confirmText: '重启电脑侧 dsh web 会断开当前连接,约 60 秒后自动核验并回群。',
68
+ timeoutMs: 120_000,
69
+ args: [],
70
+ // 排程型:先回执、再(延迟)重启;脚本本身是冻结脚本,一个字都不改
71
+ script: { rel: 'scripts/restart-dsh-web.py', detached: true, delayMs: 1500 },
72
+ },
73
+ ];
74
+
75
+ /** 默认白名单文件(不存在也不影响内置两条)。 */
76
+ export function defaultCommandsFile() {
77
+ return join(homedir(), '.dsh', 'jbc-dssi', 'proc-commands.json');
78
+ }
79
+
80
+ /** 默认执行留痕目录。 */
81
+ export function defaultRunsDir() {
82
+ return join(homedir(), '.dsh', 'jbc-dssi', 'proc-runs');
83
+ }
84
+
85
+ /* ------------------------------------------------------------------ 校验 */
86
+
87
+ /** 一条白名单 spec 是否可用(坏配置跳过,不因此让整个能力失效)。 */
88
+ export function isValidCommandSpec(spec) {
89
+ if (!spec || typeof spec !== 'object') return false;
90
+ if (typeof spec.id !== 'string' || !/^[a-z][a-z0-9._-]{1,63}$/.test(spec.id)) return false;
91
+ if (typeof spec.name !== 'string' || spec.name.trim() === '') return false;
92
+ if (!DANGERS.has(spec.danger)) return false;
93
+ const args = spec.args ?? [];
94
+ if (!Array.isArray(args) || args.length > MAX_ARGS) return false;
95
+ for (const a of args) {
96
+ if (!a || typeof a.name !== 'string' || !/^[a-zA-Z][a-zA-Z0-9_-]{0,31}$/.test(a.name)) return false;
97
+ if (a.pattern != null && typeof a.pattern !== 'string') return false;
98
+ }
99
+ if (spec.builtin == null && spec.script == null) return false;
100
+ return true;
101
+ }
102
+
103
+ /**
104
+ * 参数校验:只认声明过的参数,必填缺一即拒,pattern 按 string 值匹配。
105
+ * 多传的参数**静默忽略**(手机端版本比电脑侧新时,不该因此报错)。
106
+ */
107
+ export function validateArgs(cmd, rawArgs) {
108
+ const given = rawArgs && typeof rawArgs === 'object' && !Array.isArray(rawArgs) ? rawArgs : {};
109
+ const out = {};
110
+ for (const spec of cmd.args ?? []) {
111
+ const v = given[spec.name];
112
+ const has = v !== undefined && v !== null && String(v) !== '';
113
+ if (!has) {
114
+ if (spec.required) throw new Error(`缺少参数:${spec.label ?? spec.name}`);
115
+ continue;
116
+ }
117
+ const s = String(v);
118
+ if (spec.pattern != null && !new RegExp(spec.pattern).test(s)) {
119
+ throw new Error(`参数格式不对:${spec.label ?? spec.name}`);
120
+ }
121
+ out[spec.name] = s;
122
+ }
123
+ return out;
124
+ }
125
+
126
+ /** 脚本路径解析:只认白名单里的 rel/abs,绝不接受手机传来的路径。 */
127
+ export function resolveScript(cmd, repoRoot) {
128
+ const sc = cmd.script;
129
+ if (!sc) return null;
130
+ if (typeof sc === 'string') {
131
+ if (isAbsolute(sc)) return sc;
132
+ return repoRoot ? join(repoRoot, sc) : null;
133
+ }
134
+ if (typeof sc.abs === 'string' && sc.abs !== '') return sc.abs;
135
+ if (typeof sc.rel === 'string' && sc.rel !== '') {
136
+ return repoRoot ? join(repoRoot, sc.rel) : null;
137
+ }
138
+ return null;
139
+ }
140
+
141
+ /* ------------------------------------------------------------ 默认探针 */
142
+
143
+ /** TCP 端口探测(默认实现;测试可注入)。 */
144
+ export function probeTcpPort(port, { host = '127.0.0.1', timeoutMs = 800 } = {}) {
145
+ return new Promise((resolve) => {
146
+ const sock = net.connect({ host, port });
147
+ let done = false;
148
+ const finish = (ok) => {
149
+ if (done) return;
150
+ done = true;
151
+ try { sock.destroy(); } catch { /* 已关 */ }
152
+ resolve(ok);
153
+ };
154
+ sock.setTimeout(timeoutMs, () => finish(false));
155
+ sock.once('connect', () => finish(true));
156
+ sock.once('error', () => finish(false));
157
+ });
158
+ }
159
+
160
+ function readJsonSafe(file) {
161
+ try {
162
+ if (!fs.existsSync(file)) return { exists: false, json: null };
163
+ return { exists: true, json: JSON.parse(fs.readFileSync(file, 'utf8')) };
164
+ } catch {
165
+ return { exists: true, json: null };
166
+ }
167
+ }
168
+
169
+ function bytesToMb(n) {
170
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
171
+ }
172
+
173
+ /* ---------------------------------------------------------------- 引擎 */
174
+
175
+ /**
176
+ * 造「程序指令」引擎。
177
+ *
178
+ * @param {object} opts
179
+ * @param {(line:string)=>void} [opts.log]
180
+ * @param {string} [opts.repoRoot] 产品仓库根(`重启dsh` 等脚本的相对基准)
181
+ * @param {string} [opts.commandsFile] 白名单文件
182
+ * @param {string} [opts.runsDir] 执行留痕目录
183
+ * @param {string} [opts.version] 插件版本(体检里展示)
184
+ * @param {(payload:object)=>void} [opts.onEvent] 执行结束推送(走 DSS_AGENT_EVENT)
185
+ * @param {Function} [opts.spawnFn] 注入用(测试替身)
186
+ * @param {Function} [opts.probePort] 注入用(测试替身)
187
+ * @param {Function} [opts.now] 注入用(测试替身)
188
+ */
189
+ export function createProcEngine(opts = {}) {
190
+ const {
191
+ log = () => {},
192
+ repoRoot = '',
193
+ commandsFile = defaultCommandsFile(),
194
+ runsDir = defaultRunsDir(),
195
+ version = '',
196
+ onEvent = () => {},
197
+ spawnFn = spawn,
198
+ probePort = (p) => probeTcpPort(p),
199
+ now = () => Date.now(),
200
+ homeDir = homedir(),
201
+ } = opts;
202
+
203
+ /** id -> spec(内置 + 白名单文件,文件同 id 覆盖内置)。 */
204
+ let commands = loadCommands();
205
+ let nonce = null;
206
+ /** runId -> 运行记录。 */
207
+ const runs = new Map();
208
+ /** cmdId -> runId(单飞)。 */
209
+ const activeByCmd = new Map();
210
+ /** 当前正在跑的高危 runId(全局锁)。 */
211
+ let activeHigh = null;
212
+
213
+ function loadCommands() {
214
+ const map = new Map();
215
+ for (const spec of PROC_DEFAULTS) map.set(spec.id, spec);
216
+ const { commands: fromFile, exists } = readCommandsFile(commandsFile);
217
+ let added = 0;
218
+ let skipped = 0;
219
+ for (const spec of fromFile) {
220
+ if (!isValidCommandSpec(spec)) { skipped += 1; continue; }
221
+ map.set(spec.id, spec);
222
+ added += 1;
223
+ }
224
+ if (exists) log(`[proc] 白名单已加载:${added} 条(跳过非法 ${skipped} 条)`);
225
+ return map;
226
+ }
227
+
228
+ function readCommandsFile(file) {
229
+ try {
230
+ if (!fs.existsSync(file)) return { commands: [], exists: false };
231
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
232
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.commands) ? parsed.commands : [];
233
+ return { commands: list, exists: true };
234
+ } catch (err) {
235
+ log(`[proc] 读取指令白名单失败(回退内置两条):${err?.message ?? err}`);
236
+ return { commands: [], exists: false };
237
+ }
238
+ }
239
+
240
+ function ensureRunsDir() {
241
+ fs.mkdirSync(runsDir, { recursive: true });
242
+ }
243
+
244
+ /** 手机端看到的清单(只含"可展示"字段,不泄露电脑侧路径细节以外的东西)。 */
245
+ function list() {
246
+ const items = [...commands.values()].map((cmd) => {
247
+ const scriptPath = cmd.builtin ? null : resolveScript(cmd, repoRoot);
248
+ const available = cmd.builtin != null || (scriptPath != null && fs.existsSync(scriptPath));
249
+ return {
250
+ id: cmd.id,
251
+ name: cmd.name,
252
+ desc: cmd.desc ?? '',
253
+ danger: cmd.danger,
254
+ confirmText: cmd.danger === 'low' ? '' : (cmd.confirmText ?? ''),
255
+ args: (cmd.args ?? []).map((a) => ({
256
+ name: a.name,
257
+ label: a.label ?? a.name,
258
+ required: a.required === true,
259
+ pattern: a.pattern ?? '',
260
+ })),
261
+ available,
262
+ unavailableReason: available ? '' : '电脑侧未配置仓库根目录或脚本不存在',
263
+ };
264
+ });
265
+ return {
266
+ commands: items,
267
+ // 兼容老 App(1.1.106):它从 proc_list 取票。新 App 改用 proc_ticket 按需领票。
268
+ nonce: issueNonce(),
269
+ nonceTtlMs: NONCE_TTL_MS,
270
+ version: String(version ?? ''),
271
+ };
272
+ }
273
+
274
+ /**
275
+ * 签一张一次性确认票据。
276
+ *
277
+ * @param {string|null} cmdId 绑定到哪条指令;null = 不绑定(老路径 proc_list 兼容用)。
278
+ * 同时只保留**一张**有效票:新票签发即作废旧票(防止开两个确认弹窗后旧票还能用)。
279
+ */
280
+ function issueNonce(cmdId = null) {
281
+ nonce = { value: randomBytes(16).toString('hex'), expiresAt: now() + NONCE_TTL_MS, cmdId };
282
+ return nonce.value;
283
+ }
284
+
285
+ function consumeNonce(cmdId, given) {
286
+ if (!nonce || now() > nonce.expiresAt) throw new Error('确认已过期,请重新点执行');
287
+ if (nonce.cmdId != null && nonce.cmdId !== cmdId) throw new Error('确认票据与指令不匹配,请重新点执行');
288
+ if (typeof given !== 'string' || given !== nonce.value) throw new Error('确认票据无效,请重新点执行');
289
+ nonce = null;
290
+ }
291
+
292
+ function activeRunCount() {
293
+ return runs.size === 0 ? 0 : [...runs.values()].filter((r) => r.status === 'running').length;
294
+ }
295
+
296
+ function buildRecord(cmd, args) {
297
+ const id = `proc-${now().toString(36)}-${randomBytes(3).toString('hex')}`;
298
+ return {
299
+ runId: id,
300
+ cmdId: cmd.id,
301
+ name: cmd.name,
302
+ args,
303
+ startedAt: new Date(now()).toISOString(),
304
+ status: 'running',
305
+ exitCode: null,
306
+ durationMs: 0,
307
+ summary: '',
308
+ resultPath: '',
309
+ };
310
+ }
311
+
312
+ function appendIndex(record) {
313
+ try {
314
+ ensureRunsDir();
315
+ fs.appendFileSync(join(runsDir, 'index.jsonl'), `${JSON.stringify(record)}\n`);
316
+ } catch (err) {
317
+ log(`[proc] 写执行记录失败:${err?.message ?? err}`);
318
+ }
319
+ }
320
+
321
+ function writeRunLog(record, text) {
322
+ try {
323
+ ensureRunsDir();
324
+ const file = join(runsDir, `${record.runId}.log`);
325
+ fs.writeFileSync(file, text ?? '');
326
+ return file;
327
+ } catch (err) {
328
+ log(`[proc] 写运行日志失败:${err?.message ?? err}`);
329
+ return '';
330
+ }
331
+ }
332
+
333
+ function releaseLocks(record) {
334
+ activeByCmd.delete(record.cmdId);
335
+ if (activeHigh === record.runId) activeHigh = null;
336
+ }
337
+
338
+ function finish(record, { exitCode, summary, resultPath = '', logText = '' }) {
339
+ record.status = 'finished';
340
+ record.exitCode = exitCode;
341
+ record.durationMs = Math.max(0, now() - Date.parse(record.startedAt));
342
+ record.summary = String(summary ?? '').slice(0, SUMMARY_MAX);
343
+ record.resultPath = resultPath || writeRunLog(record, logText);
344
+ record.finishedAt = new Date(now()).toISOString();
345
+ releaseLocks(record);
346
+ appendIndex(record);
347
+ try {
348
+ onEvent({
349
+ type: 'proc_finished',
350
+ runId: record.runId,
351
+ cmdId: record.cmdId,
352
+ name: record.name,
353
+ exitCode: record.exitCode,
354
+ durationMs: record.durationMs,
355
+ summary: record.summary,
356
+ resultPath: record.resultPath,
357
+ startedAt: record.startedAt,
358
+ });
359
+ } catch (err) {
360
+ log(`[proc] 结束事件推送失败:${err?.message ?? err}`);
361
+ }
362
+ }
363
+
364
+ /* ------------------------------------------------------------ 执行体 */
365
+
366
+ async function runHealth() {
367
+ const details = [];
368
+ const okPort = await probePort(3080).catch(() => false);
369
+ details.push({ name: 'dsh 3080', ok: okPort === true, note: okPort ? '已监听' : '未监听' });
370
+
371
+ const home = homeDir;
372
+ const dshDir = join(home, '.dsh', 'jbc-dssi');
373
+ const pairing = readJsonSafe(join(dshDir, 'pairing.json'));
374
+ const pairingOk = pairing.exists && pairing.json != null;
375
+ details.push({ name: '配对', ok: pairingOk, note: pairingOk ? '已配对' : '未配对/文件损坏' });
376
+
377
+ const device = readJsonSafe(join(dshDir, 'authorized-device.json'));
378
+ const deviceOk = device.exists;
379
+ details.push({ name: '设备准入', ok: deviceOk, note: deviceOk ? '已记录' : '无准入记录' });
380
+
381
+ const groups = readJsonSafe(join(home, '.dssAgent', 'jbc-groups', 'groups.json'));
382
+ const groupCount = Array.isArray(groups.json?.groups) ? groups.json.groups.length : null;
383
+ details.push({
384
+ name: '群数据',
385
+ ok: groups.exists && groups.json != null,
386
+ note: groupCount == null ? '无群数据文件' : `${groupCount} 个群`,
387
+ });
388
+
389
+ let versionNote = version ? `插件 ${version}` : '插件版本未知';
390
+ if (repoRoot) {
391
+ const repoPkg = readJsonSafe(join(repoRoot, 'jbc-dssi', 'package.json'));
392
+ if (repoPkg.json?.version) {
393
+ const same = String(repoPkg.json.version) === String(version);
394
+ details.push({ name: '插件版本', ok: same, note: same ? `${version}(与仓库一致)` : `${version}(仓库 ${repoPkg.json.version})` });
395
+ versionNote = details[details.length - 1].note;
396
+ }
397
+ }
398
+
399
+ let diskNote = '磁盘未知';
400
+ try {
401
+ // runsDir 首次执行时可能还不存在:先建再 statfs(statfs 对不存在的路径会抛)
402
+ fs.mkdirSync(runsDir, { recursive: true });
403
+ const st = fs.statfsSync(runsDir);
404
+ const freeMb = (st.bavail * st.bsize) / 1024 / 1024;
405
+ const ok = freeMb > 1024;
406
+ diskNote = `剩余 ${(freeMb / 1024).toFixed(1)} GB`;
407
+ details.push({ name: '磁盘', ok, note: diskNote });
408
+ } catch {
409
+ details.push({ name: '磁盘', ok: true, note: diskNote });
410
+ }
411
+
412
+ const bad = details.filter((d) => d.ok === false);
413
+ const summary = bad.length === 0
414
+ ? `体检通过:3080 已监听 · ${versionNote} · 配对/准入/群数据正常 · ${diskNote}`
415
+ : `体检发现 ${bad.length} 项异常:${bad.map((d) => `${d.name}(${d.note})`).join('、')}`;
416
+ return { ok: bad.length === 0, summary, details };
417
+ }
418
+
419
+ function spawnDetached(cmd, scriptPath, args, delayMs) {
420
+ const quoted = [scriptPath, ...args].map((s) => `'${String(s).replace(/'/g, `'\\''`)}'`).join(' ');
421
+ const inner = `sleep ${(delayMs / 1000).toFixed(2)}; exec python3 ${quoted}`;
422
+ const child = spawnFn('bash', ['-c', inner], {
423
+ cwd: repoRoot || undefined,
424
+ detached: true,
425
+ stdio: 'ignore',
426
+ });
427
+ child.unref?.();
428
+ return child;
429
+ }
430
+
431
+ function spawnForeground(scriptPath, args, record) {
432
+ return new Promise((resolve) => {
433
+ const child = spawnFn('python3', [scriptPath, ...args], {
434
+ cwd: repoRoot || undefined,
435
+ stdio: ['ignore', 'pipe', 'pipe'],
436
+ env: { ...process.env },
437
+ });
438
+ const chunks = [];
439
+ const collect = (buf) => {
440
+ const s = buf.toString();
441
+ chunks.push(s);
442
+ if (chunks.length > 4000) chunks.splice(0, 2000); // 日志上限,防长跑脚本吃内存
443
+ };
444
+ child.stdout?.on('data', collect);
445
+ child.stderr?.on('data', collect);
446
+ const timer = setTimeout(() => {
447
+ try { child.kill('SIGTERM'); } catch { /* 已退出 */ }
448
+ }, Math.max(1000, record.timeoutMs ?? DEFAULT_TIMEOUT_MS));
449
+ child.once('close', (code, signal) => {
450
+ clearTimeout(timer);
451
+ resolve({ exitCode: code == null ? -1 : code, signal: signal ?? '', logText: chunks.join('') });
452
+ });
453
+ child.once('error', (err) => {
454
+ clearTimeout(timer);
455
+ resolve({ exitCode: -1, signal: '', logText: `启动失败:${err?.message ?? err}` });
456
+ });
457
+ });
458
+ }
459
+
460
+ async function execute(record, cmd) {
461
+ try {
462
+ if (cmd.builtin === 'health') {
463
+ const result = await runHealth();
464
+ finish(record, {
465
+ exitCode: result.ok ? 0 : 1,
466
+ summary: result.summary,
467
+ logText: JSON.stringify(result.details, null, 2),
468
+ });
469
+ return;
470
+ }
471
+ const scriptPath = resolveScript(cmd, repoRoot);
472
+ if (!scriptPath) {
473
+ finish(record, {
474
+ exitCode: -1,
475
+ summary: `${cmd.name} 失败:电脑侧未配置仓库根目录(proc.repoRoot)`,
476
+ });
477
+ return;
478
+ }
479
+ if (!fs.existsSync(scriptPath)) {
480
+ finish(record, { exitCode: -1, summary: `${cmd.name} 失败:脚本不存在 ${scriptPath}` });
481
+ return;
482
+ }
483
+ if (cmd.script?.detached === true) {
484
+ const delay = Number.isFinite(cmd.script.delayMs) ? cmd.script.delayMs : 1500;
485
+ spawnDetached(cmd, scriptPath, [], delay);
486
+ finish(record, {
487
+ exitCode: 0,
488
+ summary: `${cmd.name} 已排程:${(delay / 1000).toFixed(1)}s 后执行,电脑侧会短暂断开,约 60 秒后自动核验并回群`,
489
+ logText: `detached: ${scriptPath}\n`,
490
+ });
491
+ return;
492
+ }
493
+ const { exitCode, signal, logText } = await spawnForeground(scriptPath, [], record);
494
+ finish(record, {
495
+ exitCode,
496
+ summary: exitCode === 0
497
+ ? `${cmd.name} 完成`
498
+ : `${cmd.name} 失败(${signal ? `signal ${signal}` : `exit ${exitCode}`})`,
499
+ logText,
500
+ });
501
+ } catch (err) {
502
+ finish(record, { exitCode: -1, summary: `${cmd.name} 异常:${err?.message ?? err}` });
503
+ }
504
+ }
505
+
506
+ /* ------------------------------------------------------------ 命令口 */
507
+
508
+ /** 统一命令入口(`proc_*`)。与 dssAgent 的 command 同形状:同步校验、异步执行。 */
509
+ async function command(op, payload = {}) {
510
+ if (op === 'proc_list') return list();
511
+ if (op === 'proc_ticket') return ticket(payload);
512
+ if (op === 'proc_run') return runCommand(payload);
513
+ if (op === 'proc_status') return status(payload);
514
+ if (op === 'proc_cancel') return cancel(payload);
515
+ throw new Error(`未知的程序指令命令:${op}`);
516
+ }
517
+
518
+ /**
519
+ * 领一张绑定到某条指令的一次性确认票据(用户点"确认"后再领,30 秒内立刻用掉)。
520
+ *
521
+ * 为什么不复用 proc_list 里的票:那张是打开页面时签的,用户看说明、犹豫一下就会过期
522
+ * (2026-11-09 真机反馈:体检能跑、重启报"确认已过期")。票据的生命周期应该从
523
+ * "用户真的决定执行"那一刻开始。
524
+ */
525
+ function ticket(payload) {
526
+ const cmdId = typeof payload?.cmdId === 'string' ? payload.cmdId : '';
527
+ const cmd = commands.get(cmdId);
528
+ if (!cmd) throw new Error(`没有这条程序指令:${cmdId || '(空)'}`);
529
+ if (!cmd.builtin) {
530
+ const scriptPath = resolveScript(cmd, repoRoot);
531
+ if (!scriptPath || !fs.existsSync(scriptPath)) {
532
+ throw new Error('电脑侧未配置仓库根目录或脚本不存在');
533
+ }
534
+ }
535
+ return { nonce: issueNonce(cmd.id), cmdId: cmd.id, ttlMs: NONCE_TTL_MS };
536
+ }
537
+
538
+ function runCommand(payload) {
539
+ const cmdId = typeof payload?.cmdId === 'string' ? payload.cmdId : '';
540
+ const cmd = commands.get(cmdId);
541
+ if (!cmd) throw new Error(`没有这条程序指令:${cmdId || '(空)'}`);
542
+ const args = validateArgs(cmd, payload?.args);
543
+ if (cmd.danger !== 'low') {
544
+ if (payload?.confirm !== true) throw new Error(`「${cmd.name}」需要二次确认`);
545
+ }
546
+ if (cmd.danger === 'high') consumeNonce(cmd.id, payload?.nonce);
547
+ if (activeByCmd.has(cmd.id)) throw new Error(`「${cmd.name}」正在执行中,请等它结束`);
548
+ if (cmd.danger !== 'low' && activeHigh) throw new Error('有其它危险指令正在执行,稍后再试');
549
+ if (!cmd.builtin) {
550
+ const scriptPath = resolveScript(cmd, repoRoot);
551
+ if (!scriptPath || !fs.existsSync(scriptPath)) {
552
+ throw new Error('电脑侧未配置仓库根目录或脚本不存在');
553
+ }
554
+ }
555
+ const record = buildRecord(cmd, args);
556
+ record.timeoutMs = cmd.timeoutMs ?? DEFAULT_TIMEOUT_MS;
557
+ runs.set(record.runId, record);
558
+ activeByCmd.set(cmd.id, record.runId);
559
+ if (cmd.danger === 'high') activeHigh = record.runId;
560
+ void execute(record, cmd).catch((err) => {
561
+ log(`[proc] 执行异常(${cmd.id}):${err?.message ?? err}`);
562
+ releaseLocks(record);
563
+ });
564
+ return { runId: record.runId, cmdId: record.cmdId, name: record.name, startedAt: record.startedAt };
565
+ }
566
+
567
+ function status(payload) {
568
+ const runId = typeof payload?.runId === 'string' ? payload.runId : '';
569
+ if (runId) {
570
+ const record = runs.get(runId);
571
+ if (!record) throw new Error(`没有这次执行记录:${runId}`);
572
+ return { run: publicRun(record) };
573
+ }
574
+ const all = [...runs.values()];
575
+ return { runs: all.slice(-20).map(publicRun), active: activeRunCount() };
576
+ }
577
+
578
+ function cancel(payload) {
579
+ const runId = typeof payload?.runId === 'string' ? payload.runId : '';
580
+ const record = runs.get(runId);
581
+ if (!record) throw new Error(`没有这次执行记录:${runId || '(空)'}`);
582
+ if (record.status !== 'running') return { cancelled: false, run: publicRun(record) };
583
+ // 只有"可中断"的脚本能取消;排程型(重启)已经交出去,取消不了
584
+ if (record.cancellable === false) throw new Error('这条指令已经开始,不能取消');
585
+ record.cancelRequested = true;
586
+ releaseLocks(record);
587
+ record.status = 'finished';
588
+ record.exitCode = -2;
589
+ record.summary = '已取消';
590
+ record.finishedAt = new Date(now()).toISOString();
591
+ appendIndex(record);
592
+ return { cancelled: true, run: publicRun(record) };
593
+ }
594
+
595
+ function publicRun(record) {
596
+ return {
597
+ runId: record.runId,
598
+ cmdId: record.cmdId,
599
+ name: record.name,
600
+ status: record.status,
601
+ exitCode: record.exitCode,
602
+ durationMs: record.durationMs,
603
+ summary: record.summary,
604
+ resultPath: record.resultPath,
605
+ startedAt: record.startedAt,
606
+ };
607
+ }
608
+
609
+ /** 插件卸载/热重载时:不再接受新指令(运行中的子进程按其自身超时退出)。 */
610
+ function dispose() {
611
+ commands = new Map();
612
+ }
613
+
614
+ return { command, list, dispose, reload: () => { commands = loadCommands(); } };
615
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jbc-dssi",
3
- "version": "1.1.105",
3
+ "version": "1.1.107",
4
4
  "type": "module",
5
5
  "description": "鲸编程 - 不只是手机遥控操作电脑,而是将电脑级的Agent能力装进手机",
6
6
  "keywords": [