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.
package/README.md CHANGED
@@ -55,7 +55,7 @@
55
55
 
56
56
  ### 连接
57
57
 
58
- - 两种连法:经 relay v2 隧道从公网连回来,或者同一个 Wi-Fi 下走局域网直连。
58
+ - 连法有好几条,手机自己挨个试、挑能通的那条:经 relay v2 隧道从公网连回来、同一个 Wi-Fi 下走局域网直连,也能用自建穿透的直连地址、IPv6 直连、TCP 直连和点对点直连。
59
59
  - 局域网默认端口是 **51887**,已有配置沿用保存的端口。占用时先重试原端口;只有所有已配对手机支持局域网发现、且没有固定入口依赖时,才会自动换到可用端口并保存。公网入口另走插件专属回环入口,不再依赖局域网默认端口;被占时自动绕开,绕不开时面板弹窗给指引。
60
60
  - 使用外部穿透软件时,请在端口设置中开启「固定端口」。插件内的穿透配置和手填固定地址会自动保留端口;端口被占时提示释放占用。自带穿透会等待真实监听就绪,并跟随手动端口变更更新本地目标。
61
61
  - 开启地址上报后,插件会把当前地址加密发给总控。APP 前台持续订阅,在地址变化后验证新入口并重新连接;回到前台、目录重连时补取最新快照。仅局域网等明确禁用总控的线路模式仍遵守原有范围。
@@ -76,7 +76,7 @@
76
76
 
77
77
  ## 安全与隐私
78
78
 
79
- 移动端协议 v2 的会话,用的都是从设备主密钥(`deviceKey`)派生的会话密钥做逐请求加密:请求和回包都是密文,签名也只对密文计算。中转在这条路径上只转发密文,看不到会话内容。旧协议、以及还没升级到 v2 的客户端,走的仍是明文传输——这一档不加密,得升到 v2 才算接上。
79
+ 移动端协议 v2 的会话,用的都是从设备主密钥(`deviceKey`)派生的会话密钥做逐请求加密:请求和回包都是密文,签名也只对密文计算。中转在这条路径上只转发密文,看不到会话内容。
80
80
 
81
81
  App 里预置了由项目运营的默认中转地址,开箱就能连;也支持换成自己搭的中转。为了让手机端的高频读(会话列表、工作区等)不用每次都打到电脑上的主进程,会话列表和工作区镜像快照会经中转推送、在这一层缓存做读取隔离。也就是说,这些列表快照会经过中转;v2 加密会话的内容不走这条捷径,仍以密文传输。
82
82
 
@@ -144,7 +144,7 @@ DeepSeek Harness 跑在电脑上,但我不是一直坐在电脑前。出门、
144
144
  - `lib/mobile/` —— 手机要的数据怎么裁:流式事件、会话投影、审批、推送、配对。
145
145
  - `lib/relay/` —— 中转注册、地址上报总控、线路清单、配置与状态落盘。
146
146
  - `lib/remote/` —— 远程电脑:绑定、选路、窗口。
147
- - `lib/zeronews/`、`lib/jdxb/`、`lib/frpc/`、`lib/cloudflared/` —— 已经接好的线路,加新线路照它们的形状写。
147
+ - `lib/zeronews/`、`lib/jdxb/`、`lib/frpc/`、`lib/cloudflared/`、`lib/p2p/`、`lib/tailcat/` —— 已经接好的线路,加新线路照它们的形状写。
148
148
  - `lib/panel/` —— 桌面面板的构建产物;源码在 `React/`,只改源码,产物与源码一起提交。
149
149
  - `config/` —— 预设、随包技能、扩展清单。
150
150
  - `test/` —— `node --test` 的测试,一个文件对一个领域,文件名可以直接当搜索关键词。
@@ -153,7 +153,7 @@ DeepSeek Harness 跑在电脑上,但我不是一直坐在电脑前。出门、
153
153
  ### 文档
154
154
 
155
155
  - [移动端接口契约](docs/mobile-api-contract.md):自己实现一个客户端时读这份,配对、加密信封、端点清单。
156
- - [把一条线路接进插件](docs/line-integration.md):加新线路要改哪几处、老版本 App 怎么兼容。
156
+ - [把一条线路接进插件](docs/line-integration.md):加新线路要改哪几处。
157
157
  - [手机扩展作者须知](docs/extension-authoring.md):写手机里的扩展页,包怎么放、怎么和 App 通信。
158
158
  - [无头部署](docs/headless-deploy.md):没有屏幕的服务器上怎么跑、本机接口怎么用。
159
159
  - [聊天嵌入页顶部栏](docs/chat-embed.md):网页插件怎样在手机聊天页保留顶部栏。
@@ -174,7 +174,7 @@ pnpm install --frozen-lockfile
174
174
  npm test
175
175
  ```
176
176
 
177
- 要接一条新线路,先读[把一条线路接进插件](docs/line-integration.md);它同时写着老版本 App 的兼容口径。
177
+ 要接一条新线路,先读[把一条线路接进插件](docs/line-integration.md)。
178
178
 
179
179
  改过 `React/` 面板源码,先在该目录跑 `pnpm run build`,并把生成的 `lib/panel/index.html` 和源码一起提交。
180
180
 
@@ -34,7 +34,7 @@ token 只进一次本机客户端配置,面板不留存、不显示;之后
34
34
  - **一直停在安装/连接中**:多半是下载官方客户端慢或网络不通。第一次慢属正常,超过一分钟没动静再查网络,别催用户重装。
35
35
  - **连接失败,提示 AuthToken 写入失败**:token 没复制完整(少字符、带了空格)。回「快速开始」页重新复制整串;还不行就换「浏览器登录」那条老路。
36
36
  - **提示等待浏览器确认超时**:浏览器那条路等了 5 分钟没等到登录,让用户改走 AuthToken 那条。
37
- - **提示客户端已连上但没拿到隧道地址**:先等一会儿再点连接;仍没有就去 ZeroNews 控制台看是不是免费额度已经占满了(只有一条),把旧隧道删掉再试。
37
+ - **提示客户端已连上但没拿到隧道地址**:先看概览卡的「最近心跳」和「在线设备」——心跳是空的、在线设备 0,说明本机客户端还没真正连上云端,这种情况先到本页「彻底清理」从头接入一次,往往重登就好了(换过节点、或老身份失效时常见);别一上来就按额度满处理。心跳正常、在线设备也在,仍拿不到地址,再去 ZeroNews 控制台看是不是免费额度已经占满了(只有一条),把旧隧道删掉再试。刚接入的先等一会儿再点连接。
38
38
  - **提示客户端意外退出**:插件会自己安排重连,等它退避重试即可;连续失败再查网络。
39
39
  - **面板显示已连接、手机里没有这条线路**:地址要等下一轮心跳才到手机(通常几十秒),让手机切回 App 前台或重连一次;另外确认电脑这侧没关掉地址上报。
40
40
  - **面板显示未连接、地址也空了**:那是断开后的正常状态,不是掉线;要恢复就点「连接」,不需要再粘 token。
@@ -184,6 +184,7 @@ function createCloudflaredRunner(options = {}) {
184
184
  }
185
185
 
186
186
  async function launch() {
187
+ if (!desired || exists(paths.disabled)) return status();
187
188
  if (child) return status();
188
189
  if (starting) { await starting; return status(); }
189
190
  const token = ++generation;
@@ -194,7 +195,7 @@ function createCloudflaredRunner(options = {}) {
194
195
  let got;
195
196
  try { got = await ensure({}); }
196
197
  catch (err) { got = { ok: false, message: err && err.message ? err.message : String(err) }; }
197
- if (!desired || generation !== token) return;
198
+ if (!desired || generation !== token || exists(paths.disabled)) return;
198
199
  // ensureCloudflared 成功时回 { path, version, source }(没有 ok 字段),失败才抛错;
199
200
  // 这里按「有没有 path」判成功,兼容注入的假实现回 { ok:true, path } 的写法。
200
201
  if (!got || !got.path) {
@@ -325,9 +326,13 @@ function createCloudflaredRunner(options = {}) {
325
326
  return status();
326
327
  }
327
328
 
328
- async function start() {
329
+ // 默认仍是手动操作;自动调用须保留用户的关闭标记。
330
+ async function start({ userInitiated = true } = {}) {
331
+ if (!userInitiated && exists(paths.disabled)) return status();
329
332
  if (!desired) { desired = true; retries = 0; }
330
- try { removeDisabled(); } catch (err) { error = `记录启用状态失败:${err && err.message ? err.message : err}`; }
333
+ if (userInitiated) {
334
+ try { removeDisabled(); } catch (err) { error = `记录启用状态失败:${err && err.message ? err.message : err}`; }
335
+ }
331
336
  if (retryTimer !== null) { clearTimer(retryTimer); retryTimer = null; }
332
337
  return launch();
333
338
  }
@@ -361,13 +366,13 @@ function createCloudflaredRunner(options = {}) {
361
366
  return launch();
362
367
  }
363
368
 
364
- async function stop() {
369
+ async function stop({ userInitiated = true } = {}) {
365
370
  desired = false;
366
371
  stopProcess();
367
372
  requestedLocalPort = 0;
368
373
  waitingForPort = false;
369
374
  // 显式关掉:写关闭标记落盘,下次宿主启动不再自动拉起。
370
- writeDisabled();
375
+ if (userInitiated) writeDisabled();
371
376
  return status();
372
377
  }
373
378
 
@@ -92,10 +92,10 @@ function mountCloudflare(options) {
92
92
  catch (error) { warn('还原手填直连地址失败:%s', error && error.message ? error.message : error); }
93
93
  };
94
94
 
95
- // 控制面开关:start 幂等(runner 自己写 enabled 标记);stop 幂等(runner 删标记、停进程)。
95
+ // 控制面开关默认是手动操作;自动启停不改用户的关闭标记。
96
96
  // 任何一步出错都不许把异常抛回调用方(会变成面板 500 / 甚至未捕获拒绝),只记日志并把状态交回去。
97
- const start = async () => {
98
- try { await runner.start(); }
97
+ const start = async ({ userInitiated = true } = {}) => {
98
+ try { await runner.start({ userInitiated }); }
99
99
  catch (error) { warn('启动 Cloudflare 隧道失败:%s', error && error.message ? error.message : error); }
100
100
  return runner.status();
101
101
  };
@@ -105,8 +105,8 @@ function mountCloudflare(options) {
105
105
  try { await settings.update({ cloudflareUrl: '' }); }
106
106
  catch (error) { warn('撤掉 Cloudflare 地址失败:%s', error && error.message ? error.message : error); }
107
107
  };
108
- const stop = async () => {
109
- try { await runner.stop(); }
108
+ const stop = async ({ userInitiated = true } = {}) => {
109
+ try { await runner.stop({ userInitiated }); }
110
110
  catch (error) { warn('停止 Cloudflare 隧道失败:%s', error && error.message ? error.message : error); }
111
111
  // runner 停进程时会走「地址撤回」,这里再兜一次:面板回包里也不能留旧地址。
112
112
  await clearAddress();
@@ -124,6 +124,7 @@ function mountCloudflare(options) {
124
124
  // 上一次 reconcile 时的协议族策略:变了就重启正在跑的 cloudflared,让 --edge-ip-version 生效。
125
125
  let lastIpVersionPolicy = null;
126
126
  const reconcile = async (initial = false) => {
127
+ if (!runner.shouldAutoStart()) return runner.status();
127
128
  const policy = state.ipVersionPolicy || 'auto';
128
129
  if (lastIpVersionPolicy !== null && policy !== lastIpVersionPolicy && typeof runner.restartForPolicy === 'function') {
129
130
  const now = status();
@@ -134,16 +135,16 @@ function mountCloudflare(options) {
134
135
  if (shouldFallback()) {
135
136
  if (!fallbackOn) { await rememberManual(); fallbackOn = true; }
136
137
  const now = status();
137
- if (!now.running && !now.starting) await start();
138
+ if (!now.running && !now.starting) await start({ userInitiated: false });
138
139
  // 判定落地后纠偏落点:隧道可能在回环判定出来之前就按 lanPort 起了,此时专属入口已就绪,
139
140
  // 但进程仍指着被遮蔽的旧端口。syncLocalPort 幂等,端口没变就不会真重启。
140
141
  else if (now.running) await syncLocalPort();
141
142
  } else if (fallbackOn) {
142
143
  fallbackOn = false;
143
- await stop();
144
+ await stop({ userInitiated: false });
144
145
  } else if (initial && !routeAvailable() && runner.shouldAutoStart()) {
145
146
  const now = status();
146
- if (!now.running && !now.starting) await start();
147
+ if (!now.running && !now.starting) await start({ userInitiated: false });
147
148
  } else if (!initial) {
148
149
  await restoreManual();
149
150
  }
@@ -171,7 +172,7 @@ function mountCloudflare(options) {
171
172
  if (!(host && host.runner)) {
172
173
  mount('cloudflare 隧道进程', () => ctx.effect(() => {
173
174
  if (hasGate) void reconcile(true).catch(error => warn('自动判定 Cloudflare 兜底失败:%s', error && error.message ? error.message : error));
174
- else if (runner.shouldAutoStart()) Promise.resolve(runner.start()).catch((error) => warn('自动启动 Cloudflare 隧道失败:%s', error && error.message ? error.message : error));
175
+ else if (runner.shouldAutoStart()) Promise.resolve(runner.start({ userInitiated: false })).catch((error) => warn('自动启动 Cloudflare 隧道失败:%s', error && error.message ? error.message : error));
175
176
  return () => { void runner.dispose(); void restoreManual(); };
176
177
  }, `${name}: cloudflare runner`));
177
178
  }
package/lib/impl.js CHANGED
@@ -433,7 +433,7 @@ function apply(ctx) {
433
433
  // iOS / APNs 推送出口(完成/失败 + 审批/提问卡):直接请求总控,中转不再管推送。
434
434
  // 鉴权用本机那枚总控设备令牌;还没拿到令牌(没连过总控)就不发,下次收尾再试。
435
435
  pushNotify = createPushNotifier({
436
- controlTarget: () => (state.controlToken && state.instanceId
436
+ controlTarget: () => (state.controlReportEnabled !== false && state.controlToken && state.instanceId
437
437
  ? { baseUrl: CONTROL_BASE_URL, token: state.controlToken, instanceId: state.instanceId }
438
438
  : null),
439
439
  workspaceIdOf: ({ sessionId }) => require('./mobile/workspace-id.js').workspaceIdOf(ctx, { sessionId }),
package/lib/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ /** 2026-11-28:Windows 停不掉隧道助手时,本轮更新不硬装、按重试退避,避免失败重装再回滚。 */
1
2
  /**
2
3
  * 插件入口(**稳定外壳**)。
3
4
  *
@@ -27,7 +28,7 @@
27
28
 
28
29
  import path from 'node:path'
29
30
  import { fileURLToPath } from 'node:url'
30
- import { createRuntime } from './shell/runtime.js'
31
+ import { createRuntime, SHELL_API_VERSION, SHELL_CAPABILITIES } from './shell/runtime.js'
31
32
  import * as updater from './shell/updater.js'
32
33
  import { installedPackageDir, installedVersion, profileNodeModules, snapshotRunningGeneration } from './shell/manager.js'
33
34
  import { createDeviceOta } from './shell/device-ota.js'
@@ -35,6 +36,7 @@ import { installHostHalf } from './shell/half-route.js'
35
36
  import { installTransportHosts } from './shell/transport-host.js'
36
37
  import { createUpdateConsent } from './shell/update-consent.js'
37
38
  import { createAutoUpdater } from './shell/auto-updater.js'
39
+ import { createTailcatGate } from './shell/tailcat-gate.js'
38
40
  import { firstInstallNeedsRestart } from './shell/first-install.js'
39
41
 
40
42
  export const name = 'dsh-mobile-plugin'
@@ -99,47 +101,27 @@ export function apply(ctx) {
99
101
  }
100
102
 
101
103
  /**
102
- * 装包前让隧道助手松开平台包目录:只有 **Windows** 会因为助手占着 exe 导致 pnpm 换不掉
104
+ * 装包前让隧道助手松开平台包:只有 **Windows** 会因为助手占着 exe 导致 pnpm 换不掉
103
105
  * 那个包(连恢复旧版都会一起失败)。其它平台没有这个文件锁,停掉助手只会白白断掉一条
104
- * 直连通道、整段装包时间都不在——所以只在 Windows 上停。停不动就照装(多一层保险,不是
105
- * 前置条件);换代成功时新代会自己起助手,没换过去才在这里拉回来。
106
+ * 直连通道、整段装包时间都不在——所以只在 Windows 上停。停没停成如实交给代那边定夺。
106
107
  */
107
- let tailcatPaused = false
108
- const tailcatCtl = () => hostService('dshMobileTailcatCtl')
109
- const pauseTailcat = async () => {
110
- if (process.platform !== 'win32') return
111
- const ctl = tailcatCtl()
112
- if (!ctl || typeof ctl.stop !== 'function') return
113
- try {
114
- await ctl.stop()
115
- tailcatPaused = true
116
- } catch (error) {
117
- log('warn', 'dsh-mobile-plugin: 更新前停隧道助手失败:%s', error?.message || error)
118
- }
119
- }
120
- const resumeTailcat = async () => {
121
- if (!tailcatPaused) return
122
- tailcatPaused = false
123
- const ctl = tailcatCtl()
124
- if (!ctl || typeof ctl.start !== 'function') return
125
- try {
126
- const state = typeof ctl.status === 'function' ? ctl.status() : null
127
- if (!state || state.running !== true) ctl.start()
128
- } catch (error) {
129
- log('warn', 'dsh-mobile-plugin: 更新后恢复隧道助手失败:%s', error?.message || error)
130
- }
131
- }
108
+ const tailcatGate = createTailcatGate({
109
+ getControl: () => hostService('dshMobileTailcatCtl'),
110
+ log,
111
+ })
132
112
 
133
113
  /**
134
114
  * 装之前把正在跑的那一代备份进回退目录:包管理器一跑就没得备份了。失败不挡更新,只记一句。
135
115
  */
136
116
  const snapshotRunning = async () => {
117
+ // 先停隧道助手:停不掉就别做后面那步备份(每拍白抄一份没意义),把失败交给实现侧定夺。
118
+ const tailcat = await tailcatGate.stop()
119
+ if (!tailcat.ok) return { tailcat }
137
120
  const status = runtime.status()
138
121
  const result = snapshotRunningGeneration(status)
139
122
  if (result?.created) log('info', 'dsh-mobile-plugin: 更新前已把 %s 复制进回退目录', status.version)
140
123
  else if (result?.error) log('warn', 'dsh-mobile-plugin: 回退副本没做成:%s', result.error)
141
- await pauseTailcat()
142
- return result
124
+ return { ...(result || {}), tailcat }
143
125
  }
144
126
 
145
127
  /**
@@ -154,10 +136,10 @@ export function apply(ctx) {
154
136
  const result = await updater.performUpdate({ runtime, base, hostService, updateState, force, auto, log, beforeInstall: snapshotRunning, runningShellHash })
155
137
  // 换代成功后也补一次恢复:这条线路若因指纹未变而沿用了被暂停的旧 door,需要拉回来;
156
138
  // 真重建了/正在跑则 status.running 为真、resume 自动跳过。没换过去也把旧的拉回。
157
- await resumeTailcat()
139
+ await tailcatGate.resume()
158
140
  return result
159
141
  } catch (error) {
160
- await resumeTailcat()
142
+ await tailcatGate.resume()
161
143
  throw error
162
144
  }
163
145
  }
@@ -214,6 +196,9 @@ export function apply(ctx) {
214
196
  ctx.reflect.provide('dshMobilePluginRuntime', {
215
197
  status: () => ({
216
198
  ...runtime.status(),
199
+ /** 外壳能力契约:代据此判断某项功能能不能开(见 shell/runtime.js 的 SHELL_API_VERSION)。 */
200
+ shellApiVersion: SHELL_API_VERSION,
201
+ shellCapabilities: SHELL_CAPABILITIES,
217
202
  /** 盘上装着的版本(市场装完立刻变,和运行中的版本对照就能看出「要不要换」)。 */
218
203
  installedVersion: installedVersion(),
219
204
  runningShellHash,
@@ -21,9 +21,6 @@ const { unwrap } = require('./envelope.js');
21
21
  const { dropSessionModelsForDevice } = require('./session-cache.js');
22
22
  const { unchangedListBody, revisionOf, stableRevision } = require('../shared/list-revision.js');
23
23
  const { lookupModelMeta } = require('./model-meta.js');
24
- // 「本机跑的渠道,手机打电脑的局域网地址能不能通」要这台机器的网卡清单;纯计算,住在代里。
25
- const os = require('node:os');
26
- const { lanInterfaces } = require('../relay/lan-network.cjs');
27
24
 
28
25
  /** 自建渠道写在这个命名空间里;桌面端 `src/custom-channels.js` 的 PI_AI_NS 同值。 */
29
26
  const PI_AI_NS = 'llm-pi-ai';
@@ -124,6 +121,13 @@ function normalizeBaseUrl(raw) {
124
121
  return { url: `${parsed.origin}${pathname === '/' ? '' : pathname}` };
125
122
  }
126
123
 
124
+ /** 渠道地址 → chat/completions 地址。规则与桌面端、手机端同一份:写了 `/v1` 就不再补。 */
125
+ function chatCompletionUrlOf(baseUrl) {
126
+ const root = typeof baseUrl === 'string' ? baseUrl.trim().replace(/\/+$/, '') : '';
127
+ if (root === '') return '';
128
+ return root.endsWith('/v1') ? `${root}/chat/completions` : `${root}/v1/chat/completions`;
129
+ }
130
+
127
131
  /** 模型清单归一:必须至少一条,id 非空且不重复;能力字段缺省按上面那两个常量。 */
128
132
  function normalizeModels(raw) {
129
133
  if (!Array.isArray(raw) || raw.length === 0) return { error: '至少要有 1 个模型' };
@@ -228,35 +232,6 @@ function customChannelOf(id, profile) {
228
232
  }
229
233
 
230
234
  /** 只在这台电脑上成立的主机名:手机拨这些地址一律打到自己身上,永远不通。 */
231
- const LOCAL_ONLY_HOSTS = new Set(['localhost', '127.0.0.1', '0.0.0.0', '::1']);
232
-
233
- /**
234
- * 一条渠道地址 → 手机该依次试的地址。
235
- *
236
- * 头一个是原样。原样是本机 / 通配主机时,再补「这台电脑的每个局域网 IPv4 + 同一个端口」:
237
- * 同一 Wi-Fi 下手机打电脑的局域网地址是通的,本机跑的 Ollama、one-api 就不必绕经电脑转发。
238
- * 只换主机,协议、端口、路径原样保留;地址本身解析不了就只回原样,让手机自己去报地址错。
239
- */
240
- function reachCandidatesOf(baseUrl, interfaces) {
241
- const candidates = [baseUrl];
242
- let parsed;
243
- try {
244
- parsed = new URL(baseUrl);
245
- } catch {
246
- return candidates;
247
- }
248
- const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, '');
249
- if (!LOCAL_ONLY_HOSTS.has(host)) return candidates;
250
- const defaultPort = parsed.protocol === 'https:' ? 443 : 80;
251
- const port = Number(parsed.port) || defaultPort;
252
- const suffix = port === defaultPort ? '' : `:${port}`;
253
- const pathname = parsed.pathname === '/' ? '' : parsed.pathname;
254
- for (const row of lanInterfaces(port, interfaces)) {
255
- candidates.push(`${parsed.protocol}//${row.address}${suffix}${pathname}${parsed.search}`);
256
- }
257
- return candidates;
258
- }
259
-
260
235
  /**
261
236
  * GET /api/mobile/v1/channels —— 这台宿主的渠道清单(自建 + 插件提供)。
262
237
  *
@@ -610,7 +585,7 @@ async function handleChannelDelete(ctx, req, res) {
610
585
  /**
611
586
  * 按 id 取一条自建渠道。
612
587
  *
613
- * 两个调用方:导出给手机(一键导入),以及「经电脑转发」的模型请求(见 channel-proxy.js)。
588
+ * 调用方是导出给手机(一键导入),以及设备画像归纳按 id 取渠道(见 device-profile.js)。
614
589
  * 两边要的是同一份渠道配置——名字、协议、地址、模型——所以查找只写一遍:只认
615
590
  * `llm-pi-ai` 的 `providers`,插件 / 宿主注册的提供方在这里一律找不到。
616
591
  */
@@ -629,92 +604,18 @@ async function customChannelById(ctx, id) {
629
604
  return { channel };
630
605
  }
631
606
 
632
- /**
633
- * 按 provider id 取它的模型清单(`llm.models` 的 groups)。
634
- *
635
- * 只给内置官方渠道的导出用:自建那批的模型在它自己的 profile 里,不走这里。
636
- */
637
- async function modelsOfProvider(ctx, id) {
638
- const catalog = unwrap(await ctx.apiProxy.llm.models({
639
- rpcId: 'mobile',
640
- method: 'llm.models',
641
- payload: {},
642
- }));
643
- if (catalog.error) return [];
644
- const groups = Array.isArray(catalog.value && catalog.value.groups) ? catalog.value.groups : [];
645
- const group = groups.find((entry) => entry && entry.id === id);
646
- return (Array.isArray(group && group.models) ? group.models : [])
647
- .map((model) => {
648
- if (!model || typeof model !== 'object') return null;
649
- const modelId = typeof model.id === 'string' ? model.id.trim() : '';
650
- if (!modelId) return null;
651
- return { id: modelId, name: typeof model.name === 'string' && model.name.trim() ? model.name.trim() : modelId };
652
- })
653
- .filter(Boolean);
654
- }
655
-
656
- /**
657
- * 内置官方渠道 → 可导出的那一条;不是这类 id 回 `null`,是这类但宿主上没注册回 `{ error }`。
658
- */
659
- async function builtinImportableChannel(ctx, id) {
660
- const spec = importableBuiltinOf(id);
661
- if (!spec) return null;
662
- const listed = unwrap(await ctx.apiProxy.llm.providers({
663
- rpcId: 'mobile',
664
- method: 'llm.providers',
665
- payload: {},
666
- }));
667
- if (listed.error) return { error: listed.error };
668
- const registered = Array.isArray(listed.value && listed.value.providers) ? listed.value.providers : [];
669
- if (!registered.some((item) => item && item.provider === id)) {
670
- return { error: { code: 'channel-not-found', message: '这台电脑上没有这条渠道' }, status: 404 };
671
- }
672
- const models = await modelsOfProvider(ctx, id);
673
- return { channel: { id, name: spec.name, protocol: spec.protocol, baseUrl: spec.baseUrl, models } };
674
- }
675
-
676
- /**
677
- * POST /api/mobile/v1/channels/export(token){ id }
678
- * → { ok, channel, candidates }
679
- *
680
- * 把电脑上这条渠道交给手机,给「本机 Agent 新增渠道」页的一键导入用:名字、协议、
681
- * 地址、模型。Key 不经过这条接口,手机侧自己填。
682
- *
683
- * 两类可导:`llm-pi-ai` 里的自建渠道,以及宿主自带的官方 DeepSeek(映射成 OpenAI 兼容
684
- * 地址,见 `IMPORTABLE_BUILTINS`)。其它插件 / 宿主注册的提供方没有可搬的地址,
685
- * 一律 404。
686
- *
687
- * `candidates` 是手机该依次试的地址(见 reachCandidatesOf):本机地址会多出局域网那几个,
688
- * 手机探通哪个用哪个,全不通就说明这条渠道只有电脑够得着。
689
- */
690
- async function handleChannelExport(ctx, req, res) {
691
- const body = await readJsonBody(req, 8 * 1024);
692
- const id = body && typeof body.id === 'string' ? body.id.trim() : '';
693
- if (!CHANNEL_ID_PATTERN.test(id)) {
694
- return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要渠道 id' } });
695
- }
696
- const found = (await builtinImportableChannel(ctx, id)) || await customChannelById(ctx, id);
697
- if (found.error) return sendJson(res, found.status || 400, { ok: false, error: found.error });
698
- sendJson(res, 200, {
699
- ok: true,
700
- channel: found.channel,
701
- candidates: reachCandidatesOf(found.channel.baseUrl, os.networkInterfaces()),
702
- });
703
- }
704
-
705
607
  module.exports = {
706
608
  handleChannels,
707
609
  handleChannelDiscover,
708
610
  handleChannelSave,
709
611
  handleChannelDelete,
710
- handleChannelExport,
711
612
  customChannelById,
712
613
  credentialRefOf,
713
614
  providerIdOf,
714
615
  normalizeBaseUrl,
616
+ chatCompletionUrlOf,
715
617
  normalizeModels,
716
618
  profileOf,
717
619
  discoverCandidates,
718
- reachCandidatesOf,
719
620
  PI_AI_NS,
720
621
  };
@@ -19,8 +19,7 @@ const { stableRevision } = require('../shared/list-revision.js');
19
19
  const { unwrap } = require('./envelope.js');
20
20
  const { callSessions } = require('./rpc.js');
21
21
  const { listTitle } = require('./history-derive.js');
22
- const { customChannelById, PI_AI_NS } = require('./channels.js');
23
- const { chatCompletionUrlOf } = require('./channel-proxy.js');
22
+ const { customChannelById, PI_AI_NS, chatCompletionUrlOf } = require('./channels.js');
24
23
  const { deviceProfileRefreshStateOf } = require('./session-cache.js');
25
24
 
26
25
  /** 画像与开关都落在 dshHome 下,固定文件名;与移动端其它插件状态互不干扰。 */
@@ -218,11 +218,6 @@ const MAP = Object.freeze({
218
218
  '/api/mobile/v1/channels/discover': V.CONFIG,
219
219
  '/api/mobile/v1/channels/save': V.CONFIG,
220
220
  '/api/mobile/v1/channels/delete': V.CONFIG,
221
- // 导入一条:读出来的是渠道配置**与它那把 Key**。归「改模型 / 渠道配置」这一档,
222
- // 与保存 / 删除同权 —— 能改这条渠道的设备本来就能给它换一把新的 Key。
223
- '/api/mobile/v1/channels/export': V.CONFIG,
224
- // 经电脑转发一次对话:动的是这条渠道的 Key 与它的额度,归同一档。
225
- '/api/mobile/v1/channels/chat': V.CONFIG,
226
221
  '/api/mobile/v1/plugins': V.VIEW,
227
222
  '/api/mobile/v1/skills': V.VIEW,
228
223
  '/api/mobile/v1/narration': { GET: V.VIEW, POST: V.FILES_WRITE },
@@ -434,7 +429,7 @@ const MAP = Object.freeze({
434
429
  '/api/mobile/v1/magpie/web': V.CONFIG,
435
430
 
436
431
  // ── 学习画像与开关(契约 B 块):读画像 / 读开关归 view;刷新画像、写开关与归纳归 config。
437
- // study 会花电脑侧渠道的额度,按「花额度的 config」与 channels/chat 同档,不放给只读设备。
432
+ // study 会花电脑侧渠道的额度,按「花额度的 config」一档,不放给只读设备。
438
433
  '/api/mobile/v1/device-profile': V.VIEW,
439
434
  '/api/mobile/v1/device-profile/refresh': V.CONFIG,
440
435
  '/api/mobile/v1/device-profile/study': V.CONFIG,
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  const { sendJson, readJsonBody } = require('../shared/http-util');
15
+ const { readShellCompat } = require('../shell-compat.cjs');
15
16
 
16
17
  /** 一次更新结果的合法状态(外壳给的 `state` 只有这几种取值,别的一律当未知)。 */
17
18
  const APPLY_STATES = new Set([
@@ -94,6 +95,9 @@ function snapshot(ctx) {
94
95
  shellChanged: false,
95
96
  autoUpdate: false,
96
97
  autoIntervalMs: null,
98
+ /** 没有外壳就谈不上能力契约,按最老的外壳降级处理。 */
99
+ shellApiVersion: 0,
100
+ shellLegacy: true,
97
101
  /** 没有外壳就读不到这个标记;按「不用提示」处理。 */
98
102
  firstInstallPendingRestart: false,
99
103
  };
@@ -105,6 +109,7 @@ function snapshot(ctx) {
105
109
  raw = {};
106
110
  }
107
111
  const source = textOrNull(raw.source, 32);
112
+ const shellApi = readShellCompat(raw);
108
113
  return {
109
114
  supported: typeof runtime.apply === 'function',
110
115
  runningVersion: textOrNull(raw.version, 64),
@@ -114,6 +119,9 @@ function snapshot(ctx) {
114
119
  lastApply: applyView(raw.lastApply),
115
120
  /** 这个版本连外壳一起改了:换得掉实现,外壳那部分要等下次启动 DSH。 */
116
121
  shellChanged: raw.shellChanged === true,
122
+ /** 外壳能力契约:版本为 0 / legacy,说明跑着的外壳比当前代旧(某些新功能要等自然重启)。 */
123
+ shellApiVersion: shellApi.apiVersion,
124
+ shellLegacy: shellApi.legacy,
117
125
  autoUpdate: raw.autoUpdate === true,
118
126
  autoIntervalMs: typeof raw.autoIntervalMs === 'number' && Number.isFinite(raw.autoIntervalMs) ? raw.autoIntervalMs : null,
119
127
  /** 第一次装进一台正在跑的 DSH、还没重启过:App 据此要求用户回电脑重启一次。 */