dsh-mobile-plugin 0.5.134 → 0.5.136

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.
@@ -1,3 +1,4 @@
1
+ // 2026-11-28:服务商 TCP 线路(FRP)在码里是裸 host:port,自检前补 tcp:// 才拨得通。
1
2
  // 2026-11-26:配对地址自检——把二维码里要带的每条地址真拨一次,拨不通的别写进码里。
2
3
  'use strict';
3
4
 
@@ -70,7 +71,14 @@ function targetsOf(payload) {
70
71
 
71
72
  if (typeof p.relayUrl === 'string' && p.relayUrl) add({ kind: 'relay', url: p.relayUrl });
72
73
  for (const row of Array.isArray(p.routes) ? p.routes : []) {
73
- add({ kind: 'route', url: row && row.url, name: row && row.name, transport: row && row.transport });
74
+ const url = row && typeof row.url === 'string' ? row.url.trim().replace(/\/+$/, '') : '';
75
+ // FRP 这类 TCP 线路在码里是裸 `host:port`(见 provider-lines.cjs),和下面 tcpUrl 那一支
76
+ // 走同一口径补上 scheme,probeTarget 的 new URL 才认得。customRoutes 里可能已带 scheme,
77
+ // 幂等:有 scheme 就不动。
78
+ const normalized = row && row.transport === 'tcp' && url && !/^[a-z][a-z0-9+.-]*:\/\//i.test(url)
79
+ ? `tcp://${url}`
80
+ : url;
81
+ add({ kind: 'route', url: normalized, name: row && row.name, transport: row && row.transport });
74
82
  }
75
83
  if (typeof p.directUrl === 'string' && p.directUrl) add({ kind: 'direct', url: p.directUrl });
76
84
  if (typeof p.tcpUrl === 'string' && p.tcpUrl) add({ kind: 'tcp', url: `tcp://${p.tcpUrl}`, transport: 'tcp' });
@@ -63,9 +63,6 @@ const archiveClean = require('../mobile/archive-clean.js');
63
63
  const sessionLog = require('../mobile/session-log.js');
64
64
  const hostSettings = require('../mobile/host-settings.js');
65
65
  const channels = require('../mobile/channels.js');
66
- // 手机够不着的渠道由电脑代发模型请求(见 mobile/channel-proxy.js):只转发模型调用这一层,
67
- // 会话与工具循环仍在手机上。
68
- const channelProxy = require('../mobile/channel-proxy.js');
69
66
  const modelCaps = require('../mobile/model-caps.js');
70
67
  const deepSeekAccount = require('../mobile/deepseek-account.js');
71
68
  const skills = require('../mobile/skills.js');
@@ -775,13 +772,6 @@ function registerMobileRoutes(deps) {
775
772
  route('/api/mobile/v1/channels/discover', channels.handleChannelDiscover)
776
773
  route('/api/mobile/v1/channels/save', channels.handleChannelSave)
777
774
  route('/api/mobile/v1/channels/delete', channels.handleChannelDelete)
778
- // 把电脑上的一条自建渠道整条交给手机(名字 / 协议 / 地址 / 模型 / Key),给「本机 Agent
779
- // 新增渠道」页的一键导入用。只认自建那一类,只按 id 取用户点名的那一条;同一条响应里
780
- // 附带手机该依次试的地址(本机地址会补上这台电脑的局域网那几个)。
781
- route('/api/mobile/v1/channels/export', channels.handleChannelExport)
782
- // 经电脑转发一次对话(SSE):手机拨不到的渠道(跑在这台电脑上的 Ollama / 内网服务)借
783
- // 电脑的手发请求,地址与 Key 都用宿主自己那份。只收 OpenAI 兼容对话的几样东西,不建会话。
784
- route('/api/mobile/v1/channels/chat', channelProxy.handleChannelChat)
785
775
  // 技能目录(宿主 skill.list 的移动端只读代理)。桌面端敲「/」时命令候选菜单里
786
776
  // 混着技能(@deepseek-ai/dsh-client-ui-skill 注册的 inputTriggers source),
787
777
  // 手机端此前只有 commands.list 的命令目录,技能一个都看不到,见 mobile/skills.js。
@@ -1,3 +1,4 @@
1
+ /** 2026-11-28:两条自检口逐条登记,后半条登记失败时先把已挂的撤掉,不留半截口。 */
1
2
  /**
2
3
  * 宿主半边的自检口:`/api/relay/host-half` 与它的 `/reload`。
3
4
  *
@@ -42,13 +43,13 @@ export function installHostHalf(ctx, runtime, deps = {}) {
42
43
  installedVersion: installedVersion(),
43
44
  shellChanged: installedShellHash() !== null && installedShellHash() !== runningShellHash,
44
45
  })
45
- const offs = [
46
- server.register({
46
+ const specs = [
47
+ {
47
48
  kind: 'exact',
48
49
  path: HOST_HALF_PATH,
49
50
  handler: localOnly('GET', async (_req, res) => sendJson(res, 200, view())),
50
- }),
51
- server.register({
51
+ },
52
+ {
52
53
  kind: 'exact',
53
54
  path: HOST_HALF_RELOAD_PATH,
54
55
  handler: localOnly('POST', async (_req, res) => {
@@ -65,8 +66,19 @@ export function installHostHalf(ctx, runtime, deps = {}) {
65
66
  })
66
67
  }
67
68
  }),
68
- }),
69
- ].filter(off => typeof off === 'function')
69
+ },
70
+ ]
71
+ const offs = []
72
+ try {
73
+ for (const spec of specs) {
74
+ const off = server.register(spec)
75
+ if (typeof off === 'function') offs.push(off)
76
+ }
77
+ } catch (error) {
78
+ // 第二条登记失败(例如撞名)时,第一条已经挂上了:先把已挂的撤掉再抛,别留半截口在宿主上。
79
+ for (const off of offs) { try { off() } catch { /* ignore */ } }
80
+ throw error
81
+ }
70
82
  return () => {
71
83
  for (const off of offs) off()
72
84
  }
@@ -0,0 +1,95 @@
1
+ /** 2026-11-28:可选线路的通用登记表——以后新增线路在代里声明即可,不用再改外壳。 */
2
+ /**
3
+ * 可选线路(按实现指纹「沿用 / 重建」)的通用登记表。
4
+ *
5
+ * 为什么需要它:可选线路是长活进程,必须由外壳跨代持有(否则每次换代都要重连、用户能感觉到断)。
6
+ * 以前 frp / 隧道助手 / 点对点是在 transport-host 里逐条手写的,于是**每加一条线路都要改外壳、
7
+ * 也就意味着要重启 DSH**——这是文档里记的最容易复发的一条。
8
+ *
9
+ * 这个登记表把「一条可选线路」抽象成一份声明:名字 + 指纹 + 取值器(providers)+ 建法(mount)。
10
+ * 外壳只认这份声明、管它的生命周期与换代沿用;线路自己的实现住在代里(可热更)。以后加线路
11
+ * 只需要代里调一次 `adopt(...)`,外壳一行都不用动。
12
+ *
13
+ * 契约(`mount(bag)` 返回一个至少有 `stop` 的对象,可选 `start` / `status`):
14
+ * - `fingerprint` 不变:沿用同一个实例(不重连),只把 `providers` 刷新成新代给的取值器
15
+ * (避免闭包着上一代那个已经失效的 ctx)。
16
+ * - `fingerprint` 变了:先停掉旧实例、按新声明重建(短暂重连,DSH 不重启)。
17
+ * - `bag.mount`:逐块兜住的挂载器;`bag.warn`:告警出口;`bag.provider(name)`:取当前代注入的
18
+ * 取值器;`bag.effect(fn,label)`:登记随这条线路生命周期回收的 effect(重建或卸载时一起撤)。
19
+ *
20
+ * @param {{ctx: object, warn?: Function}} deps 外壳 ctx(用 `ctx.effect` 管生命周期)与告警出口。
21
+ */
22
+ export function createOptionalLineRegistry({ ctx, warn = () => {} } = {}) {
23
+ if (!ctx || typeof ctx.effect !== 'function') throw new Error('可选线路登记表需要外壳 ctx')
24
+
25
+ /** name -> { fingerprint, door, providers, disposers } */
26
+ const lines = new Map()
27
+
28
+ function disposeLine(entry) {
29
+ if (!entry) return
30
+ const { door, disposers } = entry
31
+ entry.door = null
32
+ entry.disposers = []
33
+ for (const dispose of disposers) { try { dispose() } catch { /* 已经撤过 */ } }
34
+ try { if (door && typeof door.stop === 'function') void door.stop() } catch { /* 已经停了 */ }
35
+ }
36
+
37
+ /**
38
+ * 登记/接管一条可选线路。返回这条线路当前的实例(door)。
39
+ * 只传 `providers`(不传 `mount`)时:刷新取值器并返回现有实例。
40
+ */
41
+ function adopt({ name, fingerprint = null, providers = null, mount = null } = {}) {
42
+ if (typeof name !== 'string' || !name) return null
43
+ let entry = lines.get(name) || null
44
+ if (providers && typeof providers === 'object') {
45
+ entry = entry || { fingerprint: null, door: null, providers: {}, disposers: [] }
46
+ entry.providers = { ...entry.providers, ...providers }
47
+ lines.set(name, entry)
48
+ }
49
+ if (typeof mount !== 'function') return entry ? entry.door : null
50
+ // 指纹没变且实例还在:沿用(不断线),providers 上面已经刷新过。
51
+ if (entry && entry.door && fingerprint === entry.fingerprint) return entry.door
52
+ if (entry) disposeLine(entry)
53
+ entry = entry || { providers: {} }
54
+ entry.fingerprint = fingerprint
55
+ entry.disposers = []
56
+ const pick = key => (typeof entry.providers[key] === 'function' ? entry.providers[key] : null)
57
+ const bag = {
58
+ mount: fn => { try { return fn() } catch (error) { warn(`${name} 没挂上:${error && error.message ? error.message : error}`); return undefined } },
59
+ warn,
60
+ provider: pick,
61
+ effect: (fn, label) => {
62
+ const dispose = ctx.effect(fn, label)
63
+ entry.disposers.push(dispose)
64
+ return dispose
65
+ },
66
+ }
67
+ try { entry.door = mount(bag) } catch (error) { entry.door = null; warn(`${name} 建实例失败:${error && error.message ? error.message : error}`) }
68
+ lines.set(name, entry)
69
+ return entry.door
70
+ }
71
+
72
+ /** 取下某条线路当前实例(不建)。 */
73
+ function get(name) {
74
+ const entry = lines.get(name)
75
+ return entry ? entry.door : null
76
+ }
77
+
78
+ /** 某条线路的统一控制面:停 / 起 / 查状态都转发到它当前的实例。 */
79
+ function control(name) {
80
+ const door = () => get(name)
81
+ return {
82
+ stop: () => { const d = door(); return d && typeof d.stop === 'function' ? d.stop() : Promise.resolve() },
83
+ start: () => { const d = door(); return d && typeof d.start === 'function' ? d.start() : undefined },
84
+ status: () => { const d = door(); return d && typeof d.status === 'function' ? d.status() : null },
85
+ }
86
+ }
87
+
88
+ // 外壳卸载时把全部可选线路一起撤掉(每条各自的 effect 也一并收回)。
89
+ ctx.effect(() => () => {
90
+ for (const entry of lines.values()) disposeLine(entry)
91
+ lines.clear()
92
+ }, 'dsh-mobile-plugin: optional line registry')
93
+
94
+ return { adopt, get, control }
95
+ }
@@ -1,3 +1,4 @@
1
+ /** 2026-11-28:卸载时把稳定分派器与分发表一并撤干净,停用后不再把请求转给已卸载的实现。 */
1
2
  /**
2
3
  * 代际运行时:把「外壳」和「某一代实现」缝在一起,并负责换代那一刻的秩序。
3
4
  *
@@ -16,6 +17,25 @@ import { checkGenerationAlive } from './self-check-after-swap.js'
16
17
 
17
18
  /** 换代前等在飞请求归零的上限。 */
18
19
  const DRAIN_TIMEOUT_MS = 2000
20
+
21
+ /**
22
+ * 外壳对外承诺的「接口版本」:只增不改。
23
+ *
24
+ * 代(可热更)通过外壳服务读到它,判断当前跑着的外壳支持到哪一版;新代需要更新的外壳能力时,
25
+ * 先看这个版本,够就开、不够就把那项先收起来(降级)并如实报「重启 DSH 后启用」,绝不因为
26
+ * 外壳旧就整代崩掉。这样少数真得改外壳的改动,也只是「某个新功能晚到一次自然重启」,不会
27
+ * 变成用户那边的一次故障。新增或改变外壳对外能力时,把这个数字加一并同步下面的能力名。
28
+ */
29
+ export const SHELL_API_VERSION = 1
30
+ /** 这一版外壳真实提供的能力名(只增不删;代按名字判断某项功能能不能开)。 */
31
+ export const SHELL_CAPABILITIES = [
32
+ 'route-dispatch',
33
+ 'transport-hosts',
34
+ 'update-orchestration',
35
+ 'host-half',
36
+ 'device-ota',
37
+ 'tailcat-pause-gate',
38
+ ]
19
39
  /**
20
40
  * 等一代装载完成的上限。装载卡住(依赖永远不来)时不能把整个外壳拖死。
21
41
  *
@@ -624,7 +644,23 @@ export function createRuntime() {
624
644
  const oldFiber = fiber
625
645
  fiber = null
626
646
  current = null
627
- if (oldFiber) await oldFiber.dispose()
647
+ // 停用/卸载这一层时,光停当前这一代不够:给每条路径挂的稳定分派器、以及它们读的 live 表
648
+ // 都还留在宿主上,于是请求继续被转给已卸载的实现,再启用时新分派器又因撞名挂不上。
649
+ // 这里把分派器和分发表一并撤干净;撤之前先让在飞请求排空,别把正在服务的 handler 抽走。
650
+ try {
651
+ await drain()
652
+ if (oldFiber) await oldFiber.dispose()
653
+ } finally {
654
+ for (const unregister of httpDispatchers.values()) { try { unregister() } catch { /* ignore */ } }
655
+ for (const unregister of upDispatchers.values()) { try { unregister() } catch { /* ignore */ } }
656
+ httpDispatchers.clear()
657
+ upDispatchers.clear()
658
+ liveHttp = new Map()
659
+ liveUp = new Map()
660
+ stageHttp = null
661
+ stageUp = null
662
+ applying = false
663
+ }
628
664
  }
629
665
 
630
666
  return {
@@ -0,0 +1,55 @@
1
+ /** 2026-11-28:更新前让隧道助手松开 Windows 平台包;停不掉就拦下这一轮,不硬装再回滚。 */
2
+ /**
3
+ * 更新前对隧道助手(tailcat)的处理。
4
+ *
5
+ * 为什么要有这道闸:Windows 上隧道助手的平台包(exe)正在跑时,pnpm 换不掉那个目录,装完
6
+ * 会被判「安装不完整」再回滚;回滚把盘上版本退回旧版、registry 还是那一版,于是下一次检查
7
+ * 又说有新版,形成「每两分钟失败重装再回滚」的死循环,全程还握着 profile 写锁。
8
+ *
9
+ * 所以这里做成「停得掉就继续、停不掉就把失败如实返回」,由调用方(热更的实现侧)决定是否
10
+ * 放弃这一轮、按重试退避。其它平台没有这个文件锁,停掉助手只会白白断一条直连、整段装包时间
11
+ * 都不在 —— 直接放行、不碰它。
12
+ *
13
+ * 只依赖注入进来的「取控制服务」与日志出口,不读外壳的 ctx,也便于单测。
14
+ *
15
+ * @param {{getControl?: () => any, log?: (level: string, message: string, ...rest: any[]) => void,
16
+ * platform?: string}} [options]
17
+ */
18
+ export function createTailcatGate({ getControl = () => null, log = () => {}, platform = process.platform } = {}) {
19
+ let paused = false
20
+
21
+ return {
22
+ /**
23
+ * 停隧道助手。不是 Windows、没有控制服务、或已经停过都当作「不用停」,返回 `{ ok: true }`;
24
+ * 真去停并且失败时返回 `{ ok: false, error }`,由调用方据此拦下这一轮。
25
+ */
26
+ async stop() {
27
+ if (platform !== 'win32') return { ok: true, stopped: false }
28
+ if (paused) return { ok: true, stopped: false }
29
+ const ctl = getControl()
30
+ if (!ctl || typeof ctl.stop !== 'function') return { ok: true, stopped: false }
31
+ try {
32
+ await ctl.stop()
33
+ paused = true
34
+ return { ok: true, stopped: true }
35
+ } catch (error) {
36
+ log('warn', 'dsh-mobile-plugin: 更新前停隧道助手失败:%s', error?.message || error)
37
+ return { ok: false, error }
38
+ }
39
+ },
40
+
41
+ /** 装完/失败后把之前停掉的助手拉回来;没停过就什么都不做。 */
42
+ async resume() {
43
+ if (!paused) return
44
+ paused = false
45
+ const ctl = getControl()
46
+ if (!ctl || typeof ctl.start !== 'function') return
47
+ try {
48
+ const state = typeof ctl.status === 'function' ? ctl.status() : null
49
+ if (!state || state.running !== true) ctl.start()
50
+ } catch (error) {
51
+ log('warn', 'dsh-mobile-plugin: 更新后恢复隧道助手失败:%s', error?.message || error)
52
+ }
53
+ },
54
+ }
55
+ }
@@ -23,6 +23,7 @@
23
23
  * 外壳(`lib/index.js`)只调一次 `installTransportHosts(ctx)`,业务逻辑全在这个文件里。
24
24
  */
25
25
  import crypto from 'node:crypto'
26
+ import { createOptionalLineRegistry } from './optional-lines.js'
26
27
 
27
28
  /** 门面:每次现取当前实例;属性读当前值,方法转发;换代事务期把配置/注册类方法暂存起来。 */
28
29
  function makeFacade(getHandle, { props = [], stageMethods = [], stage = null } = {}) {
@@ -317,8 +318,19 @@ export function installTransportHosts(ctx) {
317
318
  ctx.effect(() => () => { if (controlCurrent) { try { controlCurrent.client.stop() } catch { /* ignore */ } } }, 'dsh-mobile-plugin: control transport host')
318
319
  ctx.effect(() => () => { if (muxCurrent) { try { muxCurrent.service.dropAll?.() } catch { /* ignore */ } } }, 'dsh-mobile-plugin: mux transport host')
319
320
 
320
- // ── 隧道助手(直连隧道,可选线路:按指纹沿用/重建) ────────────────
321
+ // ── 可选线路的通用登记表(新线路走这里,不再逐条改外壳) ─────────────
321
322
  const looseMount = (label, fn) => { try { return fn() } catch (error) { warn(`${label} 没挂上:${error && error.message ? error.message : error}`); return undefined } }
323
+
324
+ // 通用登记表:以后新增可选线路由代调 `adopt` 声明,外壳一行都不用动(见 optional-lines.js)。
325
+ // frp / 隧道助手 / 点对点仍走各自的老挂法,等它们下次改动再迁过来即可,迁不迁不影响新线路。
326
+ const extraLines = createOptionalLineRegistry({ ctx, warn })
327
+ ctx.reflect.provide('dshMobileTransportExtraLines', {
328
+ adopt: spec => extraLines.adopt(spec),
329
+ get: name => extraLines.get(name),
330
+ control: name => extraLines.control(name),
331
+ })
332
+
333
+ // ── 隧道助手(直连隧道,可选线路:按指纹沿用/重建) ────────────────
322
334
  let tailcatDoor = null
323
335
  let tailcatProviders = {}
324
336
  let tailcatFingerprint = null
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+ // 2026-11-28:代读外壳能力契约的读取端;旧外壳不报版本时按「legacy」处理并降级。
3
+ /**
4
+ * 外壳能力契约的**读取端**(住在代里,可热更)。
5
+ *
6
+ * 背景:外壳在启动时被 Node 冻住,改它要重启 DSH;而代是可热换的。所以真到必须改外壳时,
7
+ * 新代得能在**旧外壳**上照常跑:先问外壳「你支持到哪一版、有哪些能力」,够的才开、不够的
8
+ * 就把那项先收起来(降级)并如实报「重启 DSH 后可启用」,绝不让整代因为外壳旧就崩。
9
+ *
10
+ * 这份读法必须极稳:外壳服务可能不存在(无头部署 / 被直接挂载)、可能是老的(没有这两个
11
+ * 字段,即本机制之前的外壳)、也可能字段是脏的。任何解析不出来的情况都退成
12
+ * `apiVersion: 0`、`legacy: true`、`has() === false`,让调用方走降级,而不是抛错。
13
+ *
14
+ * @param {object|null} runtime 外壳服务(`ctx.get('dshMobilePluginRuntime')`),或它 status() 的结果。
15
+ */
16
+ function readShellCompat(runtime) {
17
+ let raw = runtime || null;
18
+ if (raw && typeof raw.status === 'function') {
19
+ try { raw = raw.status() || {}; } catch { raw = {}; }
20
+ }
21
+ if (!raw || typeof raw !== 'object') raw = {};
22
+ const version = Number.isInteger(raw.shellApiVersion) && raw.shellApiVersion >= 0 ? raw.shellApiVersion : 0;
23
+ const list = Array.isArray(raw.shellCapabilities) ? raw.shellCapabilities.filter((name) => typeof name === 'string') : [];
24
+ const capabilities = new Set(list);
25
+ return {
26
+ /** 运行中外壳的接口版本;0 = 没报(本机制之前的老外壳)。 */
27
+ apiVersion: version,
28
+ /** 老外壳:读不到能力契约,只能按最保守的功能集跑。 */
29
+ legacy: version === 0,
30
+ /** 外壳是否提供某项能力。 */
31
+ has: (name) => capabilities.has(name),
32
+ /** 外壳接口版本是否达到某一级。 */
33
+ atLeast: (need) => version >= (Number(need) || 0),
34
+ /** 读到(并过滤过)的能力清单,便于诊断/上报。 */
35
+ capabilities: [...capabilities],
36
+ };
37
+ }
38
+
39
+ module.exports = { readShellCompat };
@@ -1,3 +1,4 @@
1
+ /** 2026-11-28:装前停不掉隧道助手时不跑包管理器,报可重试,避免 Windows 上失败重装再回滚。 */
1
2
  /** 更新后核对插件依赖,失败时通过原包管理器恢复上一版完整安装。 */
2
3
  /**
3
4
  * 失败结论里给「文件被占用」附一句能照着做的提示:手机与面板只显示这一句话。
@@ -862,10 +863,31 @@ async function installLatest({
862
863
  const previousComplete = beforeVersion !== null && installationProblem(profileNodeModules, name, beforeVersion) === null;
863
864
  // 备份正在跑的那一代:包的活就落在下面那一行 spawn 上,它一跑旧目录就没了。
864
865
  // 备份失败不该挡住更新(那是多一层保险),所以这里吞掉它的异常,由调用方记日志。
866
+ // 但「装前准备」里停隧道助手停不掉是另一回事:Windows 上平台包被运行中的 exe 占住时,
867
+ // pnpm 换不掉它,装完会被判不完整再回滚,回滚又让下一轮重新发现新版 —— 死循环还长期握着
868
+ // profile 写锁。所以这时**不跑包管理器**,如实报成可重试,下个 tick 再来。
865
869
  if (typeof beforeInstall === 'function') {
870
+ let prep = null;
866
871
  try {
867
- await beforeInstall({ beforeVersion, command: null });
872
+ prep = await beforeInstall({ beforeVersion, command: null });
868
873
  } catch { /* 备份失败不挡更新 */ }
874
+ if (prep && prep.tailcat && prep.tailcat.ok === false) {
875
+ emit({ phase: 'tailcat-busy', version });
876
+ return {
877
+ installed: false,
878
+ skipped: true,
879
+ retryable: true,
880
+ beforeVersion,
881
+ installedVersion: installedVersion(profileNodeModules, name),
882
+ source: declaredSource(profileDir, name),
883
+ command: null,
884
+ output: '',
885
+ failure: {
886
+ code: 'TAILCAT_BUSY',
887
+ message: '更新前停不掉隧道助手(平台包被占用),这一轮先不装,稍后会自动重试;也可以先手动退出隧道助手再点更新。',
888
+ },
889
+ };
890
+ }
869
891
  }
870
892
 
871
893
  // 一律带上:自动更新是「一检测到就装」,手动点的那一下同样是「现在就要」,没理由先让这道
@@ -6,13 +6,16 @@
6
6
  * · `status --json` —— 登录 / 连接状态、client_id、节点、主机、版本、最近心跳、套餐名、账号;
7
7
  * · `show devices --json` —— 账号下所有设备(在线、版本、系统、IP、接入时间……);
8
8
  * · `show tunnels --json` —— 账号下所有隧道(域名、协议、带宽、状态、转发到本机哪个端口……);
9
- * · `show domains --json` —— 账号下的域名(默认域名 / 自有域名)。
9
+ * · `show domains --json` —— 账号下的域名(默认域名 / 自有域名);
10
+ * · `show traffic --json` —— 本计费周期的流量用量(4.1.1 起才有)。
10
11
  *
11
12
  * 这里只做「读 + 归一」,全部字段按官方 JSON 的真实形状挑,缺字段就给空值,不让界面出现 undefined。
12
13
  * 定位可执行文件走 provision 的 locate(只找不下),客户端没装就如实回 available:false,绝不顺手下载。
13
14
  *
14
- * 官方 CLI 与本地 API 都没暴露「套餐配额上限」(能建多少条隧道 / 多少台设备),只有套餐名与已用数量,
15
- * 所以这里也只给「套餐名 + 已用数量」,不编造上限。所有命令 / 定位都可注入,守卫用假体走完整条分支。
15
+ * 官方 CLI 与本地 API 都没暴露「隧道 / 设备」的配额上限,只有套餐名与已用数量,所以这两项只给
16
+ * 「套餐名 + 已用数量」,不编造上限。流量那格反过来:CLI 直接给总量与已用量,照原样透出,
17
+ * 只在两个数都读得出时标一下是否已经超出(超出会被限速,是「连上了却很慢」最常见的解释)。
18
+ * 所有命令 / 定位都可注入,守卫用假体走完整条分支。
16
19
  */
17
20
 
18
21
  const { execFile } = require('node:child_process');
@@ -75,6 +78,36 @@ function totalOf(page, items) {
75
78
  return items.length;
76
79
  }
77
80
 
81
+ /** 流量字符串里的单位换算成字节数:`1.41 GiB` → 1513975972。认不出就 0。 */
82
+ const SIZE_UNITS = {
83
+ B: 1, KB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12,
84
+ KIB: 1024, MIB: 1024 ** 2, GIB: 1024 ** 3, TIB: 1024 ** 4,
85
+ };
86
+
87
+ function sizeBytes(value) {
88
+ const match = /^\s*([\d.]+)\s*([A-Za-z]+)\s*$/.exec(String(value || ''));
89
+ if (!match) return 0;
90
+ const unit = SIZE_UNITS[match[2].toUpperCase()];
91
+ const amount = Number(match[1]);
92
+ if (!unit || !Number.isFinite(amount)) return 0;
93
+ return Math.round(amount * unit);
94
+ }
95
+
96
+ /**
97
+ * `show traffic --json` 归一。官方回的键是中文(`总流量` / `已使用流量`),值自带单位,
98
+ * 照原样显示,别自己换算成别的单位。老客户端没有这条命令、或键名变了,一律给 null,
99
+ * 面板据此不显示这一行。
100
+ */
101
+ function normalizeTraffic(raw) {
102
+ if (!raw || typeof raw !== 'object') return null;
103
+ const total = str(raw['总流量']).trim();
104
+ const used = str(raw['已使用流量']).trim();
105
+ if (!total && !used) return null;
106
+ const totalBytes = sizeBytes(total);
107
+ const usedBytes = sizeBytes(used);
108
+ return { total, used, totalBytes, usedBytes, over: totalBytes > 0 && usedBytes > totalBytes };
109
+ }
110
+
78
111
  /** status --json 归一到面板用的字段。 */
79
112
  function normalizeClient(raw) {
80
113
  if (!raw || typeof raw !== 'object') return null;
@@ -207,6 +240,7 @@ function emptySnapshot(extra = {}) {
207
240
  client: null,
208
241
  account: { planName: '', userId: '', userTel: '' },
209
242
  counts: { tunnels: 0, devices: 0, domains: 0 },
243
+ traffic: null,
210
244
  tunnels: [],
211
245
  devices: [],
212
246
  domains: [],
@@ -257,11 +291,14 @@ function createZeroNewsAccountReader(options = {}) {
257
291
  resourcesLoaded: false,
258
292
  });
259
293
  }
260
- // 三张清单彼此独立,一起拉;某一张读失败就空着,不把整页带崩。
261
- const [devicesRes, tunnelsRes, domainsRes] = await Promise.all([
294
+ // 几张清单彼此独立,一起拉;某一张读失败就空着,不把整页带崩。
295
+ // 流量是 4.1.1 才有的命令,老客户端执行它只会打帮助文本、照样退 0;
296
+ // 读不出就 traffic 为空,面板不显示这一行,别让它把「清单读失败」的提示带出来。
297
+ const [devicesRes, tunnelsRes, domainsRes, trafficRes] = await Promise.all([
262
298
  runJson(binary, ['show', 'devices', '--json']),
263
299
  runJson(binary, ['show', 'tunnels', '--json']),
264
300
  runJson(binary, ['show', 'domains', '--json']),
301
+ runJson(binary, ['show', 'traffic', '--json']),
265
302
  ]);
266
303
  const deviceItems = itemsOf(devicesRes.parsed);
267
304
  const tunnelItems = itemsOf(tunnelsRes.parsed);
@@ -280,6 +317,7 @@ function createZeroNewsAccountReader(options = {}) {
280
317
  tunnels: totalOf(tunnelsRes.parsed, tunnelItems),
281
318
  domains: totalOf(domainsRes.parsed, domainItems),
282
319
  },
320
+ traffic: normalizeTraffic(trafficRes.parsed),
283
321
  devices: compact(deviceItems.map(normalizeDevice)),
284
322
  tunnels: compact(tunnelItems.map(normalizeTunnel)),
285
323
  domains: compact(domainItems.map(normalizeDomain)),
@@ -291,5 +329,6 @@ function createZeroNewsAccountReader(options = {}) {
291
329
 
292
330
  module.exports = {
293
331
  DEFAULT_TIMEOUT_MS, parseJson, normalizeClient, normalizeAccount, normalizeDevice,
294
- normalizeTunnel, normalizeDomain, tunnelLocal, tunnelDomain, createZeroNewsAccountReader,
332
+ normalizeTunnel, normalizeDomain, normalizeTraffic, sizeBytes, tunnelLocal, tunnelDomain,
333
+ createZeroNewsAccountReader,
295
334
  };
@@ -1,3 +1,4 @@
1
+ // 2026-11-28:补 downloadClientTo:换代时把新版下到 <bin>.next,旁边在跑的那份原样不动。
1
2
  // ZeroNews 客户端获取层:自带 → 系统 PATH → 缓存 → 官方地址下载,四平台固定路径。
2
3
  'use strict';
3
4
 
@@ -9,8 +10,8 @@
9
10
  * macOS arm64 https://download.zeronews.cc/macos/arm/zeronews
10
11
  * macOS x64 https://download.zeronews.cc/macos/amd/zeronews
11
12
  * Windows x64 https://download.zeronews.cc/windows/x64/zeronews.exe
12
- * Linux x64 https://download.v2.zeronews.cc/linux/x86_x64/zeronews-linux-4.1.0.tar (包内 zeronews/zeronews)
13
- * Linux arm64 https://download.v2.zeronews.cc/linux/arm64/zeronews-linux-4.1.0.tar
13
+ * Linux x64 https://download.v2.zeronews.cc/linux/x86_x64/zeronews-linux-4.1.1.tar (包内 zeronews/zeronews)
14
+ * Linux arm64 https://download.v2.zeronews.cc/linux/arm64/zeronews-linux-4.1.1.tar
14
15
  *
15
16
  * 三条来源按优先级:环境变量 / PATH 里已有 → 缓存 → 下载。Linux 下官方给的是 .tar,
16
17
  * 这里只挑出里面的 zeronews 可执行文件落盘。所有 I/O 都可注入,守卫用假体走完整条分支。
@@ -20,7 +21,7 @@ const fs = require('node:fs');
20
21
  const path = require('node:path');
21
22
  const { dshHome } = require('../shared/paths.js');
22
23
 
23
- const VERSION = '4.1.0';
24
+ const VERSION = '4.1.1';
24
25
  const DOWNLOADS = {
25
26
  'darwin-arm64': 'https://download.zeronews.cc/macos/arm/zeronews',
26
27
  'darwin-x64': 'https://download.zeronews.cc/macos/amd/zeronews',
@@ -88,6 +89,12 @@ function locateZeroNews(options = {}) {
88
89
 
89
90
  const explicit = readEnv('DSHM_ZERONEWS_BIN');
90
91
  if (explicit && exists(explicit)) return { ok: true, path: explicit, source: 'env' };
92
+ // 用户自己装的客户端在只读位置时,换代会把它搬到插件目录并在这里记一笔;之后一律用这一份。
93
+ const active = typeof options.active === 'function' ? options.active() : options.active;
94
+ const activePath = typeof active === 'string' && active ? active : (() => {
95
+ try { return String(fsImpl.readFileSync(activeMarkerPath(options), 'utf8')).trim(); } catch { return ''; }
96
+ })();
97
+ if (activePath && exists(activePath)) return { ok: true, path: activePath, source: 'active' };
91
98
  // macOS 上官方默认装到 /Applications/zeronews/zeronews(那份可能已经登录),优先复用,别另起一份未登录的。
92
99
  if ((plat.platform || process.platform) === 'darwin') {
93
100
  const systemInstalled = path.join('/Applications/zeronews', binName);
@@ -101,6 +108,73 @@ function locateZeroNews(options = {}) {
101
108
  return { ok: false, path: '', source: '', code: 'not-installed' };
102
109
  }
103
110
 
111
+ function permissionCode(error) {
112
+ const code = error && typeof error.code === 'string' ? error.code : '';
113
+ return code === 'EACCES' || code === 'EPERM' || code === 'EROFS' || code === 'EBUSY' || code === 'ENOTDIR';
114
+ }
115
+
116
+ /** 插件自己那份客户端的落点(换代时搬到这里,位置一定可写)。 */
117
+ function ownBinaryPath(options = {}) {
118
+ const binName = (options.platform && options.platform.platform ? options.platform.platform : process.platform) === 'win32' ? 'zeronews.exe' : 'zeronews';
119
+ return path.join(runDir(options.root), binName);
120
+ }
121
+
122
+ /**
123
+ * 插件自己选定的那份客户端(搬到自己目录之后用):内容是一行绝对路径。
124
+ * 放文件而不是塞进设置,是为了不扩移动端设置契约 —— 它只影响本机用哪个可执行文件。
125
+ */
126
+ function activeMarkerPath(options = {}) {
127
+ return path.join(runDir(options.root), '.active-binary');
128
+ }
129
+
130
+ /**
131
+ * 把官方客户端下载到指定路径(换代用:落到 `<bin>.next`,正在跑的那份原样不动)。
132
+ *
133
+ * 先写 `dest.download` 再改名:中途断网只会留下一个临时文件,不会出现半截可执行文件被当成新版。
134
+ * 平台认不出 / 没网 / 下载失败都如实回,绝不覆盖调用方已有的东西。
135
+ *
136
+ * @param {string} dest 目标文件路径
137
+ * @param {object} [options] 与 ensureZeroNews 同一组注入点
138
+ * @returns {Promise<{ok:boolean, path:string, code?:string}>}
139
+ */
140
+ async function downloadClientTo(dest, options = {}) {
141
+ const doFetch = typeof options.fetchImpl === 'function'
142
+ ? options.fetchImpl
143
+ : (typeof globalThis.fetch === 'function' ? globalThis.fetch : null);
144
+ const plat = options.platform || {};
145
+ const key = platformId(plat.platform, plat.arch);
146
+ if (!key) return { ok: false, path: '', code: 'unsupported-platform' };
147
+ if (!doFetch || !dest) return { ok: false, path: '', code: 'download-failed' };
148
+ const fsImpl = options.fsImpl || fs;
149
+ const staging = `${dest}.download`;
150
+ // 换代这条路跑在体检定时器里:下载要是挂住,后面的体检也跟着停。给个上限,超时当这次没下成。
151
+ const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 180_000;
152
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
153
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
154
+ try {
155
+ const response = await doFetch(DOWNLOADS[key], controller ? { signal: controller.signal } : undefined);
156
+ if (!response || response.ok !== true) return { ok: false, path: '', code: 'download-failed' };
157
+ let bytes = Buffer.from(await response.arrayBuffer());
158
+ if (TAR_PLATFORMS.has(key)) {
159
+ const extracted = extractFromTar(bytes);
160
+ if (!extracted) return { ok: false, path: '', code: 'extract-failed' };
161
+ bytes = extracted;
162
+ }
163
+ fsImpl.mkdirSync(path.dirname(dest), { recursive: true });
164
+ fsImpl.writeFileSync(staging, bytes, { mode: 0o755 });
165
+ fsImpl.rmSync(dest, { force: true });
166
+ fsImpl.renameSync(staging, dest);
167
+ return { ok: true, path: dest };
168
+ } catch (error) {
169
+ try { fsImpl.rmSync(staging, { force: true }); } catch { /* 清不掉也不影响返回 */ }
170
+ // 只读安装位置(用户自己装在 /usr/local/bin、Program Files 这种)与「没网」要分开:
171
+ // 前者只能换到插件自己的目录去升级,后者等下一轮再试就行。
172
+ return { ok: false, path: '', code: permissionCode(error) ? 'no-permission' : 'download-failed' };
173
+ } finally {
174
+ if (timer) clearTimeout(timer);
175
+ }
176
+ }
177
+
104
178
  /**
105
179
  * @param {object} options
106
180
  * @param {() => string} [options.env] 读环境变量(PATH / DSHM_ZERONEWS_BIN)
@@ -147,4 +221,5 @@ async function ensureZeroNews(options = {}) {
147
221
 
148
222
  module.exports = {
149
223
  VERSION, DOWNLOADS, platformId, downloadUrlOf, runDir, extractFromTar, locateZeroNews, ensureZeroNews,
224
+ downloadClientTo, ownBinaryPath, activeMarkerPath,
150
225
  };
@@ -17,7 +17,7 @@ const fs = require('node:fs');
17
17
  const os = require('node:os');
18
18
  const path = require('node:path');
19
19
  const { execFile } = require('node:child_process');
20
- const { locateZeroNews, runDir } = require('./provision.cjs');
20
+ const { locateZeroNews, runDir, activeMarkerPath } = require('./provision.cjs');
21
21
 
22
22
  /** 卸载系统服务 + 删配置可能比普通命令慢,给足一分半。 */
23
23
  const RESET_TIMEOUT_MS = 90_000;
@@ -124,6 +124,8 @@ async function purgeZeroNews(options = {}) {
124
124
  }
125
125
 
126
126
  // 只删插件自己下载的缓存二进制;系统安装 / PATH 上那份不归我们管。
127
+ // 搬到自己目录时留的那行标记也一起清掉,否则下次会指着一个已经删掉的文件。
128
+ try { fsImpl.rmSync(activeMarkerPath({ root: options.root }), { force: true }); } catch { /* 没标记就算了 */ }
127
129
  try {
128
130
  fsImpl.rmSync(cached, { force: true });
129
131
  result.cacheRemoved = true;