jbc-dssi 1.1.115 → 1.1.117

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
@@ -25,6 +25,8 @@ 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
27
  import { createProcEngine } from './lib/proc-commands.js';
28
+ import { createAppReleaseWatch } from './lib/app-release-watch.js';
29
+ import { MAX_FILE_BYTES, mimeOfFile, resolveWorkspaceFilePath } from './lib/workspace-bytes.js';
28
30
 
29
31
  /*
30
32
  * ★ 协议层与瘦身层**直接引用 core**,本目录不再保有自己的副本。
@@ -151,21 +153,6 @@ const PROTOCOL_VERSION = 1;
151
153
  */
152
154
  const MAX_IMAGE_BYTES = 2 * 1024 * 1024;
153
155
 
154
- /** 按扩展名判图片类型;不是图片返回 null(这是"只读图片"那道闸门的判据)。 */
155
- function mimeOfImage(p) {
156
- const m = /\.([a-z0-9]+)$/i.exec(p);
157
- if (!m) return null;
158
- switch (m[1].toLowerCase()) {
159
- case 'png': return 'image/png';
160
- case 'jpg':
161
- case 'jpeg': return 'image/jpeg';
162
- case 'gif': return 'image/gif';
163
- case 'webp': return 'image/webp';
164
- case 'bmp': return 'image/bmp';
165
- default: return null;
166
- }
167
- }
168
-
169
156
  /** 手机上没人回答时,最多等这么久就把审批交回浏览器处理。 */
170
157
  const APPROVAL_TIMEOUT_MS = 5 * 60 * 1000;
171
158
 
@@ -1203,8 +1190,64 @@ function activate(ctx, config) {
1203
1190
  } else {
1204
1191
  log('[proc] 程序指令能力未启用(配置关闭)');
1205
1192
  }
1193
+ /*
1194
+ * 发版推送(2026-11-15 老谢定):发版脚本在本机写完 version.json 后,
1195
+ * 几秒内把新版本**主动推给正在连着的手机**,手机立刻弹升级窗 —— 不用等轮询。
1196
+ *
1197
+ * 监听目录用产品仓库根(与 proc 的 repoRoot 同一个配置,零新增配置项);
1198
+ * 手机连上/重连时额外补发一条当前快照,覆盖"发版时手机没在线"。
1199
+ */
1200
+ let appRelease = null;
1201
+
1202
+ /** 发版广播:live(直连)+ relayChannels(中继)都要遍历到,和预览/群事件同一个坑。 */
1203
+ function pushAppRelease(info) {
1204
+ if (info === null || info === undefined) return;
1205
+ const targets = new Set(live);
1206
+ for (const channel of relayChannels) targets.add(channel);
1207
+ for (const conn of targets) {
1208
+ try {
1209
+ conn.send(FRAME.APP_RELEASE, info);
1210
+ } catch (err) {
1211
+ log(`[release] 发版帧发送失败(单条连接):${err?.message ?? err}`);
1212
+ }
1213
+ }
1214
+ }
1215
+
1216
+ /** 新手机连上时补发当前版本快照(发版时没在线的手机,连上就能弹)。 */
1217
+ function pushAppReleaseTo(target) {
1218
+ const info = appRelease?.current?.();
1219
+ if (info === null || info === undefined) return;
1220
+ try {
1221
+ target.send(FRAME.APP_RELEASE, info);
1222
+ } catch {
1223
+ /* 单条连接发送失败不影响其它手机 */
1224
+ }
1225
+ }
1226
+
1227
+ {
1228
+ const repoRoot =
1229
+ typeof config.releaseWatch?.repoRoot === 'string' && config.releaseWatch.repoRoot.length > 0
1230
+ ? config.releaseWatch.repoRoot
1231
+ : typeof config.proc?.repoRoot === 'string'
1232
+ ? config.proc.repoRoot
1233
+ : '';
1234
+ if (repoRoot !== '') {
1235
+ try {
1236
+ appRelease = createAppReleaseWatch({ repoRoot, log, onRelease: pushAppRelease });
1237
+ appRelease.start();
1238
+ log(`[release] 发版推送已启用(监听 ${repoRoot}/version.json)`);
1239
+ } catch (err) {
1240
+ log(`[release] 初始化失败:${err?.message ?? err}`);
1241
+ appRelease = null;
1242
+ }
1243
+ } else {
1244
+ log('[release] 未配置仓库根,发版推送未启用');
1245
+ }
1246
+ }
1247
+
1206
1248
  // 插件卸载:退订 session/event、清掉 500ms 合并定时器(否则会往死连接写帧)
1207
1249
  if (typeof ctx.effect === 'function') ctx.effect(() => () => {
1250
+ appRelease?.stop?.();
1208
1251
  dssAgent?.dispose?.();
1209
1252
  proc?.dispose?.();
1210
1253
  });
@@ -1300,6 +1343,7 @@ function activate(ctx, config) {
1300
1343
  function onRelayChannelReady(channel) {
1301
1344
  relayChannels.add(channel);
1302
1345
  pushUiConfigTo(channel);
1346
+ pushAppReleaseTo(channel);
1303
1347
  replayGroupsEvents(channel);
1304
1348
  }
1305
1349
 
@@ -1341,6 +1385,8 @@ function activate(ctx, config) {
1341
1385
  } catch {
1342
1386
  /* 忽略 */
1343
1387
  }
1388
+ // 发版快照:手机连上就知道"有没有新版本",不必等下一次发版或轮询
1389
+ pushAppReleaseTo(conn);
1344
1390
  // 直连模式下同样补发断线期间的群事件(中继模式在 onRelayChannelReady 里补发)
1345
1391
  replayGroupsEvents(conn);
1346
1392
  };
@@ -2257,6 +2303,14 @@ class BridgeConnection {
2257
2303
  this.#fire('read-image', this.#readImage(payload));
2258
2304
  break;
2259
2305
 
2306
+ /*
2307
+ * 工作区文件原始字节(2026-11-15 老谢定):手机内嵌看 PDF / Excel / Word
2308
+ * 与「用其他应用打开」共用这一条 —— 只传字节,解析在手机侧。
2309
+ */
2310
+ case FRAME.READ_FILE_BYTES:
2311
+ this.#fire('read-file-bytes', this.#readFileBytes(payload));
2312
+ break;
2313
+
2260
2314
  case FRAME.FOCUS: {
2261
2315
  this.focused = payload?.active === true;
2262
2316
  /*
@@ -3404,6 +3458,55 @@ class BridgeConnection {
3404
3458
  }
3405
3459
  }
3406
3460
 
3461
+ /**
3462
+ * 读一个工作区文件的原始字节(2026-11-15 老谢定)。
3463
+ *
3464
+ * 用途一:手机内嵌看 PDF / Excel / Word —— 这三类不是文本,
3465
+ * `read_workspace_file` 只回元数据,解析全在手机侧(不引第三方渲染库)。
3466
+ * 用途二:「用其他应用打开」—— 手机把字节落缓存再交给系统的 WPS/Office。
3467
+ *
3468
+ * 安全:与 read-image 同一个思路,但更严 —— 绝对路径也必须在工作区内。
3469
+ */
3470
+ async #readFileBytes(payload) {
3471
+ const raw = typeof payload?.path === 'string' ? payload.path.trim() : '';
3472
+ const resolved = resolveWorkspaceFilePath({
3473
+ workspacesDir: this.dssAgent?.workspacesDir,
3474
+ entityId: payload?.entityId,
3475
+ raw,
3476
+ });
3477
+ if (resolved.error) {
3478
+ this.send(FRAME.FILE_BYTES, { path: raw, error: resolved.error });
3479
+ return;
3480
+ }
3481
+ const abs = resolved.path;
3482
+ try {
3483
+ const st = await fs.promises.stat(abs);
3484
+ if (!st.isFile()) {
3485
+ this.send(FRAME.FILE_BYTES, { path: raw, error: '不是文件' });
3486
+ return;
3487
+ }
3488
+ if (st.size > MAX_FILE_BYTES) {
3489
+ const mb = (st.size / 1024 / 1024).toFixed(1);
3490
+ this.send(FRAME.FILE_BYTES, {
3491
+ path: raw,
3492
+ error: `文件太大(${mb} MB),超过 5 MB 请在电脑上打开`,
3493
+ });
3494
+ return;
3495
+ }
3496
+ const buf = await fs.promises.readFile(abs);
3497
+ const name = abs.split('/').pop();
3498
+ this.send(FRAME.FILE_BYTES, {
3499
+ path: raw,
3500
+ name,
3501
+ mime: mimeOfFile(name),
3502
+ size: st.size,
3503
+ data: buf.toString('base64'),
3504
+ });
3505
+ } catch (err) {
3506
+ this.send(FRAME.FILE_BYTES, { path: raw, error: `读取失败:${err?.message ?? err}` });
3507
+ }
3508
+ }
3509
+
3407
3510
  async #readEarlier(payload) {
3408
3511
  const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId.trim() : '';
3409
3512
  if (sessionId === '') {
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 发版监听(2026-11-15 老谢定:"发版后主动推一次,别等轮询")。
3
+ *
4
+ * 为什么放电脑侧:发版脚本就在这台电脑上跑(`release-fast.sh` 最后写 `version.json`),
5
+ * 文件一变,插件几秒内就能通过**已有桥接通道**把新版本推给正在连着的手机;
6
+ * 不依赖轮询、不依赖改服务端 / relay。
7
+ *
8
+ * 设计要点:
9
+ * · 只认 **versionCode 增大**(回滚 / 同版本重写不推,避免手机被回滚提示);
10
+ * · 监听的是**目录**不是单个文件 —— 发版是"写临时文件再 rename",盯文件会在 rename 后丢 watch;
11
+ * · fs.watch 不可用(部分平台)时退回 5 秒轮询,功能不受影响;
12
+ * · 去抖 1 秒:发版一次可能连着写好几次,只推最后一版;
13
+ * · 手机连上/重连时由调用方用 [createAppReleaseWatch.current] 补一条快照 ——
14
+ * 覆盖"发版时手机没在线、之后才连上"的场景(连上立刻弹,不用等下一次发版)。
15
+ */
16
+ import { promises as fs, watch as fsWatchImpl } from 'node:fs';
17
+ import { join } from 'node:path';
18
+
19
+ /** 解析 version.json 文本;坏 JSON / 缺版本号返回 null(绝不因坏文件影响推送主流程)。 */
20
+ export function parseReleaseJson(text) {
21
+ let json;
22
+ try {
23
+ json = JSON.parse(String(text ?? ''));
24
+ } catch {
25
+ return null;
26
+ }
27
+ if (json === null || typeof json !== 'object') return null;
28
+ const versionCode = Number(json.versionCode);
29
+ if (!Number.isFinite(versionCode) || versionCode <= 0) return null;
30
+ return {
31
+ versionName: typeof json.versionName === 'string' ? json.versionName : '',
32
+ versionCode,
33
+ url: typeof json.url === 'string' ? json.url : '',
34
+ changelog: typeof json.changelog === 'string' ? json.changelog : '',
35
+ sha256: typeof json.sha256 === 'string' ? json.sha256.trim() : '',
36
+ sizeBytes: Number.isFinite(Number(json.sizeBytes)) ? Number(json.sizeBytes) : 0,
37
+ minVersionCode: Number.isFinite(Number(json.minVersionCode)) ? Number(json.minVersionCode) : 0,
38
+ };
39
+ }
40
+
41
+ /** 该不该推:新的 versionCode 必须比上次推过的更大(回滚/重写不推)。 */
42
+ export function shouldAnnounce(prevVersionCode, nextVersionCode) {
43
+ return Number.isFinite(nextVersionCode) && nextVersionCode > (Number(prevVersionCode) || 0);
44
+ }
45
+
46
+ /**
47
+ * 建一个发版监听器。
48
+ *
49
+ * @param {object} opts
50
+ * @param {string} opts.repoRoot 产品仓库根(version.json 所在目录)
51
+ * @param {Function} opts.onRelease 回调:参数为解析后的版本信息
52
+ * @param {Function} [opts.log]
53
+ * @param {number} [opts.debounceMs=1000] 去抖时长
54
+ * @param {number} [opts.pollMs=5000] fs.watch 不可用时的兜底轮询间隔
55
+ */
56
+ export function createAppReleaseWatch({ repoRoot, onRelease, log, debounceMs = 1000, pollMs = 5000 }) {
57
+ const dir = String(repoRoot ?? '').trim();
58
+ const file = join(dir, 'version.json');
59
+ let current = null;
60
+ let lastAnnounced = 0;
61
+ let timer = null;
62
+ let watcher = null;
63
+ let poller = null;
64
+ let stopped = false;
65
+
66
+ async function readOnce({ announce }) {
67
+ if (stopped) return;
68
+ let text = null;
69
+ try {
70
+ text = await fs.readFile(file, 'utf8');
71
+ } catch {
72
+ return; // 文件不存在(没发过版)就静默
73
+ }
74
+ const info = parseReleaseJson(text);
75
+ if (info === null) return;
76
+ current = info;
77
+ if (announce && shouldAnnounce(lastAnnounced, info.versionCode)) {
78
+ lastAnnounced = info.versionCode;
79
+ try {
80
+ onRelease?.(info);
81
+ } catch (err) {
82
+ log?.(`[release] 推送回调失败:${err?.message ?? err}`);
83
+ }
84
+ } else if (info.versionCode > lastAnnounced) {
85
+ // 启动时的首读只记水位,不推(手机连上时会单独补快照)
86
+ lastAnnounced = info.versionCode;
87
+ }
88
+ }
89
+
90
+ function schedule(announce = true) {
91
+ if (stopped) return;
92
+ if (timer !== null) clearTimeout(timer);
93
+ timer = setTimeout(() => {
94
+ timer = null;
95
+ void readOnce({ announce });
96
+ }, debounceMs);
97
+ if (typeof timer?.unref === 'function') timer.unref();
98
+ }
99
+
100
+ function start() {
101
+ // 先读一次定水位(不推:老版本信息不该在插件刚启动时炸弹窗)
102
+ void readOnce({ announce: false });
103
+ try {
104
+ watcher = fsWatch(dir, () => schedule(true));
105
+ log?.(`[release] 监听 ${file}(目录 watch)`);
106
+ } catch (err) {
107
+ log?.(`[release] fs.watch 不可用(${err?.message ?? err}),退回 ${pollMs}ms 轮询`);
108
+ poller = setInterval(() => schedule(true), pollMs);
109
+ if (typeof poller?.unref === 'function') poller.unref();
110
+ }
111
+ }
112
+
113
+ function stop() {
114
+ stopped = true;
115
+ if (timer !== null) clearTimeout(timer);
116
+ timer = null;
117
+ try {
118
+ watcher?.close?.();
119
+ } catch {
120
+ /* 忽略 */
121
+ }
122
+ watcher = null;
123
+ if (poller !== null) clearInterval(poller);
124
+ poller = null;
125
+ }
126
+
127
+ /** 当前已知的最新版本(手机连上时补一条)。可能为 null(还没读到过版本文件)。 */
128
+ function getCurrent() {
129
+ return current;
130
+ }
131
+
132
+ return { start, stop, current: getCurrent };
133
+ }
134
+
135
+ /*
136
+ * 目录 watch 包一层:只关心 version.json(部分平台 filename 可能为 null,此时照样触发去抖)。
137
+ * watch 本身抛错由 start() 捕获后退回轮询 —— 行为可预期。
138
+ */
139
+ function fsWatch(dir, listener) {
140
+ return fsWatchImpl(dir, (event, filename) => {
141
+ if (filename === null || filename === undefined || String(filename) === 'version.json') {
142
+ listener(event, filename);
143
+ }
144
+ });
145
+ }
package/lib/protocol.js CHANGED
@@ -91,6 +91,32 @@ export const FRAME = {
91
91
  * 超了直接回 error,不让一帧把整个连接堵住。
92
92
  */
93
93
  IMAGE_DATA: 0x3b,
94
+ /**
95
+ * 发版推送(2026-11-15 老谢定):{ versionName, versionCode, url, changelog,
96
+ * sha256, sizeBytes, minVersionCode }。
97
+ *
98
+ * 电脑侧监听本机仓库 `version.json`:发版脚本写完后**几秒内**广播给已连手机;
99
+ * 手机连上/重连时另外补发一条当前快照(覆盖"发版时手机没在线")。
100
+ * 手机收到后按 `versionCode > 本机` 判断是否弹升级窗,**无需再上网拉一次**。
101
+ *
102
+ * 与 HEALTH 类帧一样:业务失败不发;内容来自本机文件,不是手机可控输入。
103
+ */
104
+ APP_RELEASE: 0x3c,
105
+ /**
106
+ * 请求一个「工作区文件」的原始字节:{ path, entityId } -> FILE_BYTES。
107
+ *
108
+ * 为什么需要它(2026-11-15 老谢定:手机上要能看 PDF / Excel / Word):
109
+ * 这三类都不是文本,`read_workspace_file` 只回元数据;手机要内嵌解析,
110
+ * 就必须先把原始字节拿到手。「用其他应用打开」同理(先落手机缓存再交系统)。
111
+ *
112
+ * 与 READ_IMAGE 的分工:
113
+ * · READ_IMAGE 只放行图片扩展名、上限 2 MB(看图场景);
114
+ * · 本条放行 PDF / Office / 其它文档,上限 5 MB(base64 后 ≈6.7 MB,在 8 MB 帧内)。
115
+ * ⚠️ 电脑侧必须自己校验:路径必须落在**该智能体工作区**内、拒绝 `..` 穿越。
116
+ */
117
+ READ_FILE_BYTES: 0x3d,
118
+ /** 文件字节回应:{ path, name, mime, size, data(base64) };失败 { path, error }。 */
119
+ FILE_BYTES: 0x3e,
94
120
  FORK_DONE: 0x35,
95
121
  /**
96
122
  * 团队快照(bots 模块):{ v, seq, asOf, teams:[...] }。
@@ -0,0 +1,78 @@
1
+ /**
2
+ * 工作区文件字节通道的纯逻辑(2026-11-15 老谢定:手机上能看 PDF / Excel / Word)。
3
+ *
4
+ * 抽成独立模块的理由:**路径校验是这条通道唯一的安全边界**,
5
+ * "只放开该智能体工作区、拒绝 `..`、绝对路径也要在界内"这三条必须能被单测钉死
6
+ * (见 `test/workspace-bytes.test.mjs`),不能躺在 index.js 的私有方法里靠人读。
7
+ *
8
+ * 分工:index.js 只管读文件与发帧,这里的函数不碰 fs、不碰连接。
9
+ */
10
+ import { join, resolve, sep } from 'node:path';
11
+
12
+ /**
13
+ * 单个文件字节上限(5 MB 原文件)。
14
+ *
15
+ * 为什么是 5 MB:帧上限 8 MB,base64 再胀 1.33 倍 → 5 MB 原文件 ≈ 6.7 MB 帧;
16
+ * 再大就在电脑上打开 —— 一帧 8 MB 在 4G 上要十几秒,期间所有消息排在它后面。
17
+ */
18
+ export const MAX_FILE_BYTES = 5 * 1024 * 1024;
19
+
20
+ /** 按扩展名给文档一个 MIME(「用其他应用打开」靠它挑 App);认不出给 octet-stream。 */
21
+ export function mimeOfFile(p) {
22
+ const m = /\.([a-z0-9]+)$/i.exec(String(p ?? ''));
23
+ if (!m) return 'application/octet-stream';
24
+ switch (m[1].toLowerCase()) {
25
+ case 'pdf': return 'application/pdf';
26
+ case 'doc': return 'application/msword';
27
+ case 'docx': return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
28
+ case 'xls': return 'application/vnd.ms-excel';
29
+ case 'xlsx': return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
30
+ case 'ppt': return 'application/vnd.ms-powerpoint';
31
+ case 'pptx': return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
32
+ case 'csv': return 'text/csv';
33
+ case 'txt':
34
+ case 'md':
35
+ case 'markdown': return 'text/plain';
36
+ case 'zip': return 'application/zip';
37
+ default: return 'application/octet-stream';
38
+ }
39
+ }
40
+
41
+ /**
42
+ * 把手机传来的路径解析成工作区内的绝对路径。
43
+ *
44
+ * 支持:工作区相对路径(`artifacts/x.pdf`)、工作区内的绝对路径、`file://` 形式。
45
+ * 拒绝:空路径、`..` 穿越、跨工作区、不合法的 entityId、电脑侧工作区未就绪。
46
+ *
47
+ * @param {object} opts
48
+ * @param {string} opts.workspacesDir 电脑侧工作区根(通常 `<dssAgent root>/workspaces`)
49
+ * @param {string} opts.entityId 智能体 id(必须是合法的简单 id)
50
+ * @param {string} opts.raw 手机传来的原始路径
51
+ * @returns {{path: string} | {error: string}}
52
+ */
53
+ export function resolveWorkspaceFilePath({ workspacesDir, entityId, raw }) {
54
+ let p = String(raw ?? '').trim();
55
+ if (p === '') return { error: '缺少文件路径' };
56
+ if (p.toLowerCase().startsWith('file://')) {
57
+ p = p.slice('file://'.length);
58
+ try {
59
+ p = decodeURIComponent(p);
60
+ } catch {
61
+ // 解码失败按原样处理,交给后面校验
62
+ }
63
+ }
64
+ p = p.replace(/\\/gu, '/');
65
+ if (p.split('/').some((seg) => seg === '..')) return { error: '文件路径不合法' };
66
+ const ws = String(workspacesDir ?? '').trim();
67
+ if (ws === '') return { error: '电脑侧工作区还没就绪' };
68
+ const id = String(entityId ?? '').trim();
69
+ if (!/^[A-Za-z0-9-]{1,64}$/u.test(id)) {
70
+ return { error: '需要智能体 id(请在智能体会话里打开)' };
71
+ }
72
+ const root = resolve(ws, id);
73
+ const abs = p.startsWith('/') ? resolve(p) : resolve(join(root, p));
74
+ if (abs !== root && !abs.startsWith(`${root}${sep}`)) {
75
+ return { error: '只能查看这个智能体工作区里的文件' };
76
+ }
77
+ return { path: abs };
78
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jbc-dssi",
3
- "version": "1.1.115",
3
+ "version": "1.1.117",
4
4
  "type": "module",
5
5
  "description": "鲸编程 - 不只是手机遥控操作电脑,而是将电脑级的Agent能力装进手机",
6
6
  "keywords": [