dsh-plugin-weapp-gateway 0.8.35 → 0.8.38

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/PROTOCOL.md CHANGED
@@ -972,6 +972,51 @@ WebUI 中的“任务”与“进行中的目标”分别对应 DSH 的 `todos`
972
972
  → { "kind": "select-model", "selected": { "provider": "deepseek", "model": "deepseek-chat", "reasoningEffort": "high" } }
973
973
  ```
974
974
 
975
+ ### 模型发现与模型凭据(llm-model-config-v1)
976
+
977
+ `hello.capabilities` 包含 `llm-model-config-v1` 时,配对设备可以通过控制连接管理自定义 Provider:探测端点上的模型、查询并写入模型凭据。三个请求都必须来自已配对设备(否则返回 `authentication-required`),走 control 连接(conversation 连接上的同名请求返回 `wrong-channel`,legacy 单连接兼容),且必须带非空 `requestId`(响应回显;缺失返回 `bad-request`)。`apiKey` 与凭据值只允许出现在请求帧里,**响应、错误 message 与网关日志都不会回显它们**。
978
+
979
+ | type | 参数 | 说明 |
980
+ |---|---|---|
981
+ | `llm-discover-models` | `requestId`, `ns`, `provider?`, `baseURL?`, `api?`, `apiKey?` | 转发 Host `llm/discoverModels(settingsNs, request)`:`ns` 定位 settings namespace;`provider` / `baseURL` 至少一个;`apiKey` 只用于本次探测,Host 不存储 |
982
+ | `model-credential-describe` | `requestId`, `ref` | 转发 Host `credentials/describe`,返回 `configured` / `writable`(以及可选 `source`),**没有值** |
983
+ | `model-credential-set` | `requestId`, `ref`, `value` | 转发 Host `credentials/set`;值只上行,没有读路径 |
984
+
985
+ 字段约束:
986
+
987
+ - `ns`:非空字符串,≤200;
988
+ - `provider`:非空字符串,≤200(provider 路由名);
989
+ - `baseURL`:≤2048,且必须是绝对的 HTTP(S) URL;
990
+ - `api`:非空字符串,≤80;
991
+ - `apiKey`:≤8192,不得含控制字符;空串视为没有携带;
992
+ - `ref`:必须匹配 `^[A-Za-z_][A-Za-z0-9_]{0,255}$`,并且必须出现在当前 `llm-pi-ai` settings namespace 的 `providers[*].apiKeyEnv` 里,否则 `bad-request`;
993
+ - `value`:非空、≤8192,每个字符都在 `\x21-\x7E`(可打印 ASCII,因此不接受空格、中文和换行)。
994
+
995
+ ```json
996
+ { "type": "llm-discover-models", "requestId": "discover-1", "ns": "llm-pi-ai", "provider": "pi-ai" }
997
+ → { "kind": "llm-discover-models", "requestId": "discover-1",
998
+ "models": [ { "id": "pi-ai/chat", "name": "Pi Chat", "contextWindow": 128000,
999
+ "maxTokens": 16384, "inputModalities": ["text", "image"] } ] }
1000
+ ```
1001
+
1002
+ 模型数组逐项只保留 `id`、`name?`、`contextWindow?`、`maxTokens?`、`inputModalities?` 白名单字段(`inputModalities` 只认 `text` / `image`),丢弃非法与重复的 `id`;第三方 adapter 的附加字段不会下发。
1003
+
1004
+ ```json
1005
+ { "type": "model-credential-describe", "requestId": "cred-1", "ref": "PI_AI_API_KEY" }
1006
+ → { "kind": "model-credential-describe", "requestId": "cred-1", "configured": true, "writable": true, "source": "credentials-file" }
1007
+
1008
+ { "type": "model-credential-set", "requestId": "cred-2", "ref": "PI_AI_API_KEY", "value": "sk-..." }
1009
+ → { "kind": "model-credential-set", "requestId": "cred-2", "saved": true }
1010
+ ```
1011
+
1012
+ 失败帧保留 `requestType` 与 `requestId`,`message` 截断到 500 字符:
1013
+
1014
+ - 探测失败:`{ "kind":"error", "code":"llm-discovery-failed", "message":"..." }`;
1015
+ - 凭据写入失败:`{ "kind":"error", "code":"model-credential-write-failed", "message":"..." }`;
1016
+ - 凭据描述失败:Host 错误码原样透传(例如 `{ "kind":"error", "code":"credentials/unavailable" }`);settings 不可读时为 `model-credentials-unavailable`。
1017
+
1018
+ 如果 Host 的错误信息里包含本次请求的 `apiKey` 或凭据值,网关会先替换为 `[redacted]` 再下发并写日志。
1019
+
975
1020
  ---
976
1021
 
977
1022
  ## 9. 权限控制
package/README.md CHANGED
@@ -2,10 +2,22 @@
2
2
  <img src="docs/assets/whale-girl-ios-app-promo-16x9.png" alt="DeepSeek Harness Mobile 与移动网关" width="100%">
3
3
  </p>
4
4
 
5
- # 鲸尾移动网关
5
+ # 鲸尾网关助手
6
6
 
7
7
  `dsh-plugin-weapp-gateway` · DeepSeek Harness 移动客户端连接插件
8
8
 
9
+ ### v0.8.37 · 模型发现与模型凭据写入
10
+
11
+ - 新增三个控制连接请求,供小程序「模型 / Provider」页面在配对设备上发现自定义 Provider 的模型、查询并写入模型凭据:`llm-discover-models`(转发 Host `llm/discoverModels`,一次性 `apiKey` 只用于本次探测)、`model-credential-describe`、`model-credential-set`(转发 Host `credentials/describe|set`)。
12
+ - `hello.capabilities` 新增 `llm-model-config-v1`;三个请求都必须来自已配对设备且带 `requestId`,未配对连接返回 `authentication-required`。
13
+ - 凭据引用只接受当前 `llm-pi-ai` settings namespace 的 `providers[*].apiKeyEnv` 白名单(`^[A-Za-z_][A-Za-z0-9_]{0,255}$`);凭据值必须是 1–8192 个可打印 ASCII 字符(HTTP header 可安全携带)。
14
+ - 安全:响应帧、错误 message(截断 500 字符)与网关日志都不会出现 `apiKey` 或凭据值;Host 若在错误里回显密钥,网关先替换为 `[redacted]` 再下发。协议细节见 [PROTOCOL.md](PROTOCOL.md#模型发现与模型凭据llm-model-config-v1)。
15
+ - 新增 `test/model-config.test.mjs`,并在 `test/host-adapter.test.mjs`、`test/auth.test.mjs` 补充适配层参数、配对鉴权与端到端断言。33 个测试文件全部通过。
16
+
17
+ ### v0.8.36 · 更名为鲸尾网关助手
18
+
19
+ - 设置入口、管理面板标题及中文插件元数据统一更名为「鲸尾网关助手」;同步更新导航图标和设置页渲染测试、README 与 FnOS 使用指南。协议标识和「移动网关」功能描述保持不变。
20
+
9
21
  ### v0.8.35 · 修复 Windows 上的连接器测试
10
22
 
11
23
  - 插件把 `spawnProcess` 选项转发给内置中继连接器,与 Cloudflare 隧道已有的注入缝一致;默认仍是真实 `spawn`,生产行为不变。测试可用它包住真实子进程并记录启动环境,无需依赖平台专有的进程检查工具。
@@ -27,7 +39,7 @@
27
39
 
28
40
  ### v0.8.33 · 可信设备连接线路徽标
29
41
 
30
- - 「设置 → 鲸尾移动网关 → 可信设备」为每台在线设备添加连接线路徽标:**局域网**(手机与 DSH 同网直连)、**公网**(公网服务器、反向代理或鲸尾中继)、**Cloudflare 外网**(命名 / Quick Tunnel)。徽标跟随手机当前实际连接实时变化,面板 3 秒轮询自动刷新,手机从 Wi-Fi 切到蜂窝即换线路。
42
+ - 「设置 → 鲸尾网关助手 → 可信设备」为每台在线设备添加连接线路徽标:**局域网**(手机与 DSH 同网直连)、**公网**(公网服务器、反向代理或鲸尾中继)、**Cloudflare 外网**(命名 / Quick Tunnel)。徽标跟随手机当前实际连接实时变化,面板 3 秒轮询自动刷新,手机从 Wi-Fi 切到蜂窝即换线路。
31
43
  - 线路由网关按连接入口判定并记账:独立局域网监听、Cloudflare 隧道专属回环监听、主监听分别打上 `lan` / `cloudflare` / `public` 标签;`GET /mgw/devices` 的每个设备新增 `routes` 字段(当前活跃线路数组)。
32
44
  - 徽标为纯展示:不改变配对、鉴权与自动选路逻辑;离线设备不显示线路徽标,旧版本网关返回的设备记录没有 `routes` 时同样不显示。
33
45
 
@@ -115,7 +127,7 @@
115
127
 
116
128
  ### v0.8.9 · 插件在线更新
117
129
 
118
- - 打开「设置 → 鲸尾移动网关」时自动检查 npm 最新版本,并可在面板中一键安装更新。
130
+ - 打开「设置 → 鲸尾网关助手」时自动检查 npm 最新版本,并可在面板中一键安装更新。
119
131
  - DSH 宿主支持插件管理时直接升级;旧版宿主会给出 Terminal 安装命令。构建脚本审批不会自动批准,要求重启时需手动重启 DSH。
120
132
  - 接入小程序订阅通知:通过一次性通知票据,在对应会话轮次结束后回调通知服务,不发送任务正文。
121
133
 
@@ -127,13 +139,13 @@
127
139
 
128
140
  协议与客户端处理约定见 [文件变更接入说明](docs/workspace-changes-mobile-integration.md)。
129
141
 
130
- DeepSeek Harness 的设备鉴权移动连接插件,支持会话与实时事件、排队消息同步及编辑/删除/Steer、Session 归档和重命名的双向同步、停止当前生成并稍后继续、任务列表和当前 Goal 同步及管理、服务端驱动的命令和技能菜单、Human-in-the-loop、图片及文件传输。本 fork 不占用侧边栏:全部管理能力集中在 Harness WebUI 的「设置 → 鲸尾移动网关」页面,可直接开启连接服务、生成配对二维码和管理可信设备;离开该页面即停止轮询,不再有任何悬浮层。
142
+ DeepSeek Harness 的设备鉴权移动连接插件,支持会话与实时事件、排队消息同步及编辑/删除/Steer、Session 归档和重命名的双向同步、停止当前生成并稍后继续、任务列表和当前 Goal 同步及管理、服务端驱动的命令和技能菜单、Human-in-the-loop、图片及文件传输。本 fork 不占用侧边栏:全部管理能力集中在 Harness WebUI 的「设置 → 鲸尾网关助手」页面,可直接开启连接服务、生成配对二维码和管理可信设备;离开该页面即停止轮询,不再有任何悬浮层。
131
143
 
132
144
  > 当前源码以 **DSH 0.2.0-rc.2** 为适配基线,使用 Session format 4;旧版历史游标需重新取得基线。
133
145
  >
134
146
  > 实时流已改为独立 `assistant-stream` 帧,移动端需要按 [rc.2 接入说明](docs/dsh-rc2-mobile-integration.md) 更新订阅、缓存与分页处理。当前修改尚未发布。
135
147
  >
136
- > v0.7.7:同步上游 v0.8.0(DSH 0.1.7-rc.2 / Session format 4、inbox 排队消息同步、Schedule 与 Permission Presets、审批 `displayReason`),管理界面仅保留在「设置 → 鲸尾移动网关」,不再提供侧边栏入口。
148
+ > v0.7.7:同步上游 v0.8.0(DSH 0.1.7-rc.2 / Session format 4、inbox 排队消息同步、Schedule 与 Permission Presets、审批 `displayReason`),管理界面仅保留在「设置 → 鲸尾网关助手」,不再提供侧边栏入口。
137
149
  >
138
150
  > v0.8.6(续):修复 DSH 0.2.1 宿主上所有 Remote 请求崩溃——`Cannot read properties of undefined (reading 'signal')`。0.2.1-alpha 起 `InvokeRemoteRequest.peer` 改为必填(`assertPeerLive` 与 `methodSignal` 都会读 `peer.signal`,流式方法还会并入它),而适配器此前只传 `{namespace, method, args, signal}`;工作区/会话/历史全部不可用,只剩 `default-model`(不走 Remote Gateway)正常。现在适配器以自己的 owner Peer 发言(随插件 dispose 中止),0.1.7/0.2.0 宿主忽略该字段,因此新旧宿主通吃。附 0.2.1 宿主形状的回归测试。
139
151
  >
@@ -164,7 +176,7 @@ DeepSeek Harness 的设备鉴权移动连接插件,支持会话与实时事件
164
176
  > v0.8.4:修复中继模式下打开面板地址栏仍显示 Cloudflare 地址
165
177
  >
166
178
  > v0.8.5:扫码成功后二维码弹窗自动关闭——服务端暴露待用配对码 ID,面板轮询发现自己的码被消费即关闭,不用等 5 分钟过期或手动关。——refresh() 原先只看本地路由 ref(初始 auto),现在先采纳服务端的 pairingMode 再推导地址,打开即显示中继地址。——原先用在捕获阶段 stopPropagation 阻止设置页插件折叠导航,但 React 的 onClick 委托在 document 根,捕获阶段拦截会连自己的 handler 一起掐死。改为 MutationObserver 监听并即时还原折叠,不碰事件。——弹窗导航按钮固定 40px 高度(不再塌成文字高度);点导航不再被设置页插件折叠成汉堡按钮(捕获阶段拦截 + 自我恢复);中继设备自动命名(连接器每次连接都上报手机型号 header,网关据此更新设备名)。——换用上游 client.js 时把 id: 'dsh-plugin-mobile-gateway' 一并带入,加载器按包名找不到注册项,整个插件条目被剔除(设置页消失)。现改回 dsh-plugin-weapp-gateway 并加防回归守卫。
167
- > v0.7.8:同步上游 v0.8.1(PC 端可开启 Cloudflare Quick / 命名 Tunnel、配对面板增加局域网与外网入口选择指引、工具菜单可重启网关或停止 DSH Web),管理界面仅保留在「设置 → 鲸尾移动网关」。
179
+ > v0.7.8:同步上游 v0.8.1(PC 端可开启 Cloudflare Quick / 命名 Tunnel、配对面板增加局域网与外网入口选择指引、工具菜单可重启网关或停止 DSH Web),管理界面仅保留在「设置 → 鲸尾网关助手」。
168
180
  >
169
181
  > v0.7.9:Cloudflare Tunnel 扩展到 Linux 服务器(本 fork 定制):上游仅支持 Windows/macOS 自动下载校验 `cloudflared`,本 fork 允许在 Linux 上使用 Cloudflare 官方 apt 源安装的 `cloudflared`(或配置 `cloudflaredPath` 指向任意可执行文件),隧道机制不变。
170
182
  >
@@ -181,7 +193,7 @@ DeepSeek Harness 的设备鉴权移动连接插件,支持会话与实时事件
181
193
 
182
194
  ## 协议与 DSH 兼容层
183
195
 
184
- 移动端连接的是本项目维护的 `dsh-mobile-v1`,不是 DSH 的内部 Remote 协议。当前 Host Adapter 基线为 DSH 0.2.1-rc.2 / Session format 4;Session、Workspace、Settings、Commands、Goals、Schedule、Permission Presets 与新增上传/子会话路由的 Remote 参数只存在于适配层。旧 Host 不满足本版硬依赖时不能加载此版插件;移动端新增功能仍需按 `hello.capabilities` 判定是否启用。Plugin Manager 系列请求帧经配对设备连接管理插件目录、安装、启停、设置与版本豁免,方案见 [DSH 0.2.0 插件管理对接方案](docs/dsh-0.2.0-rc.2-plugin-management-mobile-integration.md)。
196
+ 移动端连接的是本项目维护的 `dsh-mobile-v1`,不是 DSH 的内部 Remote 协议。当前 Host Adapter 基线为 DSH 0.2.1-rc.2 / Session format 4;Session、Workspace、Settings、Commands、Goals、Schedule、Permission Presets 与新增上传/子会话路由的 Remote 参数只存在于适配层。旧 Host 不满足本版硬依赖时不能加载此版插件;移动端新增功能仍需按 `hello.capabilities` 判定是否启用。Plugin Manager 系列请求帧经配对设备连接管理插件目录、安装、启停、设置与版本豁免,方案见 [DSH 0.2.0 插件管理对接方案](docs/dsh-0.2.0-rc.2-plugin-management-mobile-integration.md)。模型配置请求(`llm-discover-models`、`model-credential-describe`、`model-credential-set`)同样走配对设备控制连接,转发 Host `llm/discoverModels` 与 `credentials/describe|set`;凭据值只上行,响应与日志都不回显,见 [PROTOCOL.md 第 8 节](PROTOCOL.md#模型发现与模型凭据llm-model-config-v1)。
185
197
 
186
198
  配对鉴权和 `dsh-mobile-v1` / `hello.protocol = 3` 保持不变。新版实时 token 不占用持久事件的 `seq`:客户端显式订阅 `assistantStream: true`,接收原子的 `session-snapshot` 和独立增量;普通 `event` 只携带持久事件。未接入新订阅的客户端只能收到持久消息。
187
199
 
@@ -199,7 +211,7 @@ DeepSeek Harness 的设备鉴权移动连接插件,支持会话与实时事件
199
211
 
200
212
  插件提供稳定 `gatewayId`、可配置 `gatewayName`、配对候选地址列表,以及可持久化的“关闭 / 临时开启 / 常驻开启”运行模式。一个 App 可以分别配对不同机器上的网关;客户端多网关管理仍需按 [App 对接说明](docs/multi-gateway-app-integration.md) 实现。本次源码尚未发布新的 npm 版本。
201
213
 
202
- 在“鲸尾移动网关”面板选择“常驻开启”,网关会持续接受已授权设备连接,重启后保持。常驻需要 DSH 进程运行、机器未休眠且网络可达,不提供自动发现或网络中转。
214
+ 在“鲸尾网关助手”面板选择“常驻开启”,网关会持续接受已授权设备连接,重启后保持。常驻需要 DSH 进程运行、机器未休眠且网络可达,不提供自动发现或网络中转。
203
215
 
204
216
  部署配置示例(对应 mobile-gateway 插件的 `config`):
205
217
 
@@ -270,13 +282,13 @@ npx --yes dsh-plugin-weapp-gateway@latest init
270
282
  dsh web
271
283
  ```
272
284
 
273
- 打开 WebUI,进入「设置」确认出现「鲸尾移动网关」页面(侧边栏不会新增入口)。
285
+ 打开 WebUI,进入「设置」确认出现「鲸尾网关助手」页面(侧边栏不会新增入口)。
274
286
 
275
287
  ## 局域网配对
276
288
 
277
289
  适用于 DSH 电脑与 DSH App 或鲸尾小程序位于同一个可互访的局域网。
278
290
 
279
- 1. 在 WebUI 的「设置」中打开“鲸尾移动网关”。
291
+ 1. 在 WebUI 的「设置」中打开“鲸尾网关助手”。
280
292
  2. 将“网关运行模式”设为“常驻开启”(短期配对也可选“临时开启”)。
281
293
  3. 保持“设备鉴权”开启。
282
294
  4. 在“配对连接方式”选择“局域网直连”,确认 WebSocket 地址为 `ws://<电脑局域网 IP>:3081/ws/mobile`。即使 Cloudflare Tunnel 已开启,也无需关闭它。选择框旁的问号会按当前网关环境解释各入口并给出场景建议,不会自动更改选择。
@@ -334,7 +346,7 @@ http://127.0.0.1:<本地端口>
334
346
 
335
347
  ### 4. 在 UI 配置公网入口
336
348
 
337
- 在 WebUI「设置 → 鲸尾移动网关」中打开面板,在“公网接入”填写云厂商控制台提供的公网 IPv4,然后点击“配置公网接入”或“更新公网配置”。Helper 会自动读取当前 `dsh web` 端口并配置 Nginx、TLS 证书和 `wss://<公网 IP>/ws/mobile`。
349
+ 在 WebUI「设置 → 鲸尾网关助手」中打开面板,在“公网接入”填写云厂商控制台提供的公网 IPv4,然后点击“配置公网接入”或“更新公网配置”。Helper 会自动读取当前 `dsh web` 端口并配置 Nginx、TLS 证书和 `wss://<公网 IP>/ws/mobile`。
338
350
 
339
351
  <p align="center">
340
352
  <img src="docs/assets/public-access-ui.png" alt="在移动设备面板配置公网接入" width="420">
@@ -359,7 +371,7 @@ http://127.0.0.1:<本地端口>
359
371
 
360
372
  ### Cloudflare Quick Tunnel(一键临时接入)
361
373
 
362
- 在「鲸尾移动网关 → 连接与配对」展开 Cloudflare 外网设置,选择「Quick Tunnel · 无需域名」并点击「一键开启」。面板连接后会取得随机的 `wss://<名称>.trycloudflare.com/ws/mobile`。生成“自动选择”二维码后,DSH App 会自动尝试公网 WSS 与局域网候选地址;小程序则走鲸尾中继或局域网。原有“鲸尾公网 · 小程序”专用中继选项仍可单独使用。关闭开关会停止隧道;DSH 再次启动时会恢复已开启的 Quick 模式并取得**新的随机地址**。
374
+ 在「鲸尾网关助手 → 连接与配对」展开 Cloudflare 外网设置,选择「Quick Tunnel · 无需域名」并点击「一键开启」。面板连接后会取得随机的 `wss://<名称>.trycloudflare.com/ws/mobile`。生成“自动选择”二维码后,DSH App 会自动尝试公网 WSS 与局域网候选地址;小程序则走鲸尾中继或局域网。原有“鲸尾公网 · 小程序”专用中继选项仍可单独使用。关闭开关会停止隧道;DSH 再次启动时会恢复已开启的 Quick 模式并取得**新的随机地址**。
363
375
 
364
376
  Quick Tunnel 无需 Cloudflare 账户、Token 或自己的公网域名,但地址在 DSH 重启或隧道重连后可能变化。若隧道地址变化,重新生成二维码供 DSH App 或小程序配对;**仅凭 PC 在线不能保证旧地址继续可用**。Cloudflare 将 Quick Tunnel 定位于测试和开发,当前有并发请求上限且不提供可用性保证。参见 [Cloudflare Quick Tunnel 文档](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/)。
365
377
 
@@ -367,7 +379,7 @@ Quick Tunnel 无需 Cloudflare 账户、Token 或自己的公网域名,但地
367
379
 
368
380
  ### Cloudflare 命名 Tunnel(固定地址)
369
381
 
370
- 面板(「鲸尾移动网关 → Cloudflare Tunnel」选「命名 Tunnel」)里内置了两个跳转链接:
382
+ 面板(「鲸尾网关助手 → Cloudflare Tunnel」选「命名 Tunnel」)里内置了两个跳转链接:
371
383
  [Cloudflare 控制台 → 隧道](https://dash.cloudflare.com/?to=/:account/tunnels) 和
372
384
  [官方创建教程](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/get-started/create-remote-tunnel/)。
373
385
 
@@ -393,7 +405,7 @@ echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudf
393
405
  apt-get update && apt-get install -y cloudflared
394
406
  ```
395
407
 
396
- 安装后「鲸尾移动网关 → Cloudflare Tunnel」分组即出现在面板(与 Windows/macOS 相同)。插件按以下顺序定位程序:profile 配置里的 `cloudflaredPath`(绝对路径优先),否则在 PATH 中查找 `cloudflared`;都不存在时面板会提示上面的安装命令。其余行为(Quick / 命名模式、配对地址自动填入、Token 保存、`/ws/mobile` 之外一律 404)与 PC 完全一致;Linux 同样不会监听 DSH WebUI 或 `/mgw` 的对外路径。
408
+ 安装后「鲸尾网关助手 → Cloudflare Tunnel」分组即出现在面板(与 Windows/macOS 相同)。插件按以下顺序定位程序:profile 配置里的 `cloudflaredPath`(绝对路径优先),否则在 PATH 中查找 `cloudflared`;都不存在时面板会提示上面的安装命令。其余行为(Quick / 命名模式、配对地址自动填入、Token 保存、`/ws/mobile` 之外一律 404)与 PC 完全一致;Linux 同样不会监听 DSH WebUI 或 `/mgw` 的对外路径。
397
409
 
398
410
  #### 公网入口检测与状态含义
399
411
 
@@ -469,11 +481,11 @@ sudo env "PATH=$PATH" npx --yes dsh-plugin-weapp-gateway@latest remove-helper
469
481
 
470
482
  | 现象 | 处理方式 |
471
483
  |---|---|
472
- | 「设置」里没有“鲸尾移动网关” | 确认安装在 `web` profile,并完整重启 `dsh web` |
484
+ | 「设置」里没有“鲸尾网关助手” | 确认安装在 `web` profile,并完整重启 `dsh web` |
473
485
  | iOS 收到 `503` | 回到 WebUI 开启“允许移动设备连接” |
474
486
  | iOS 收到 `401` | 在 WebUI 重新生成二维码并配对 |
475
487
  | Linux 服务器公网连接超时 | 检查云安全组、服务器防火墙和 TCP `80/443` |
476
- | Linux 服务器公网地址没有显示 | 在“鲸尾移动网关 → 公网接入”填写公网 IPv4 并点击更新 |
488
+ | Linux 服务器公网地址没有显示 | 在“鲸尾网关助手 → 公网接入”填写公网 IPv4 并点击更新 |
477
489
  | Cloudflare 下载失败 | 检查 PC 到 GitHub Releases 的连接;也可自行安装 cloudflared,并把 `cloudflaredPath` 设为可执行文件的绝对路径 |
478
490
  | Quick Tunnel 重启后 App 无法连接 | Quick 地址可能已变化,在面板重新生成二维码并让 App 扫码更新配对;需要固定地址时改用命名 Tunnel |
479
491
  | 面板提示未找到 cloudflared(Linux) | 按上文 apt 命令安装 Cloudflare 官方 `cloudflared`,或把 `cloudflaredPath` 指向已有可执行文件后重启 |
package/lib/client.js CHANGED
@@ -252,7 +252,7 @@ window.__ModuleLoader__.load({
252
252
  // so a throwing glyph leaves the shell's own icon in place rather than
253
253
  // blanking the cell.
254
254
  // --------------------------------------------------------------------------
255
- const NAV_LABEL = '鲸尾移动网关'
255
+ const NAV_LABEL = '鲸尾网关助手'
256
256
  const NAV_ICON_MARK = 'data-mgw-nav-icon'
257
257
 
258
258
  function navGlyph() {
@@ -1011,10 +1011,10 @@ window.__ModuleLoader__.load({
1011
1011
  pairingTokenCopied ? React.createElement('div', { style: { ...styles.muted, color: colors.success, marginBottom: 8 } }, '已复制到剪贴板') : null,
1012
1012
  copyNotice ? React.createElement('div', { role: 'alert', style: { ...styles.muted, color: colors.danger, marginBottom: 8 } }, copyNotice) : null,
1013
1013
  React.createElement('div', { style: styles.muted }, `有效期至 ${new Date(qr.pairing.expiresAt).toLocaleTimeString()};扫码成功后此二维码立即失效。`)))) : null,
1014
- React.createElement('aside', { className: 'mobile-gateway-panel', inert: qr ? true : undefined, 'aria-hidden': qr ? true : undefined, style: styles.panel, onMouseDown: (event) => { event.stopPropagation(); setToolsOpen(false) }, role: 'dialog', 'aria-modal': true, 'aria-label': '鲸尾移动网关管理' },
1014
+ React.createElement('aside', { className: 'mobile-gateway-panel', inert: qr ? true : undefined, 'aria-hidden': qr ? true : undefined, style: styles.panel, onMouseDown: (event) => { event.stopPropagation(); setToolsOpen(false) }, role: 'dialog', 'aria-modal': true, 'aria-label': '鲸尾网关助手管理' },
1015
1015
  React.createElement('div', { style: styles.header },
1016
1016
  React.createElement('div', null,
1017
- React.createElement('h2', { style: styles.title }, '鲸尾移动网关'),
1017
+ React.createElement('h2', { style: styles.title }, '鲸尾网关助手'),
1018
1018
  React.createElement('div', { style: styles.muted }, !status ? '正在加载网关状态…' : status.gatewayEnabled ? `移动网关已开启 · ${status.requireAuth ? '设备鉴权已开启' : '本机设备鉴权已关闭'}` : '移动网关已关闭 · 普通 WebUI 模式')),
1019
1019
  React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
1020
1020
  React.createElement('div', { style: { position: 'relative' }, onMouseDown: (event) => event.stopPropagation() },
@@ -1043,7 +1043,7 @@ window.__ModuleLoader__.load({
1043
1043
  React.createElement('svg', { width: 20, height: 20, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2.2, strokeLinecap: 'round', 'aria-hidden': true },
1044
1044
  React.createElement('path', { d: 'M6 6l12 12M18 6L6 18' }))))),
1045
1045
  React.createElement('div', { className: 'mgw-body' },
1046
- React.createElement('nav', { ref: navRef, className: 'mgw-nav', 'aria-label': '鲸尾移动网关设置分组' },
1046
+ React.createElement('nav', { ref: navRef, className: 'mgw-nav', 'aria-label': '鲸尾网关助手设置分组' },
1047
1047
  [['general', '通用设置'], ['pairing', '连接与配对'], ['devices', '可信设备']].map(([id, label]) =>
1048
1048
  React.createElement('button', { key: id, type: 'button', 'aria-current': activeSection === id ? 'page' : undefined,
1049
1049
  onClick: () => { setActiveSection(id); setConnectionHelpOpen(false); setToolsOpen(false) } }, label))),
@@ -439,6 +439,13 @@ export function createDshHostAdapter(typertGateway, connection) {
439
439
  const providers = await invoke('llm', 'listConfigurableProviders', {}, signal)
440
440
  return { providers: requireArray(providers, 'llm/listConfigurableProviders') }
441
441
  },
442
+ // One draft-provider interrogation against the endpoint a settings page is
443
+ // editing. `settingsNs` lets the Host resolve the route's stored profile
444
+ // without the mobile client ever reading it; a supplied apiKey is used for
445
+ // this call only and is never persisted by the Host.
446
+ discoverModels: (settingsNs, request, signal) => invoke(
447
+ 'llm', 'discoverModels', { settingsNs, request }, signal,
448
+ ),
442
449
  },
443
450
  goals: {
444
451
  async edit(payload) {
package/lib/index.mjs CHANGED
@@ -70,6 +70,9 @@ import { stringifyWireFrame } from './wire-json.mjs'
70
70
  // { "type": "goal-pause"|"goal-resume"|"goal-clear", "sessionId", "ref" }
71
71
  // { "type": "plugin-catalog"|"plugin-inspect"|"plugin-install"|"plugin-settings"|..., "requestId", ... }
72
72
  // -> paired control connection; see PROTOCOL.md section 18
73
+ // { "type": "llm-discover-models", "requestId", "ns", "provider"?, "baseURL"?, "api"?, "apiKey"? }
74
+ // { "type": "model-credential-describe"|"model-credential-set", "requestId", "ref", ("value")? }
75
+ // -> paired control connection; see PROTOCOL.md section 8
73
76
  // { "type": "agent-presets" } -> preset roster (+ isDefault)
74
77
  // { "type": "defaults" } -> default agent preset + default permission
75
78
  // { "type": "set-default", "target": "agent-preset"|"permission", "value" }
@@ -77,7 +80,7 @@ import { stringifyWireFrame } from './wire-json.mjs'
77
80
  // { "type": "question-cancel", "rpcId", "sessionId" }
78
81
  // { "type": "approval-response", "rpcId", "sessionId", "approvalId",
79
82
  // "outcome": "allowed-once"|"rejected" }
80
- // server -> client: { "kind": "hello", "protocol": 3, "capabilities": ["images", "commands", "tasks", "goals", "plugin-management-v1", "session-cancel", "queue-control", "session-archive", "session-rename", "file-downloads"],
83
+ // server -> client: { "kind": "hello", "protocol": 3, "capabilities": ["images", "commands", "tasks", "goals", "plugin-management-v1", "llm-model-config-v1", "session-cancel", "queue-control", "session-archive", "session-rename", "file-downloads"],
81
84
  // "authenticated", "device"?, "port", "clients" }
82
85
  // { "kind": "pong", "at" }
83
86
  // { "kind": "subscribed", "sessionId" }
@@ -134,6 +137,7 @@ import devicesModule from './devices.js'
134
137
  import { createDshHostAdapter, DSH_VERSION, SESSION_FORMAT_VERSION } from './dsh-host-adapter.mjs'
135
138
  import { createSpeechInputManager, SPEECH_REQUEST_TYPES } from './speech-input.mjs'
136
139
  import { handlePluginQuery, PLUGIN_REQUEST_TYPES } from './plugin-management.mjs'
140
+ import { handleModelConfigQuery, MODEL_CONFIG_REQUEST_TYPES } from './model-config.mjs'
137
141
  import { handleWorkspaceChanges, WORKSPACE_CHANGES_TYPES } from './workspace-changes-bridge.mjs'
138
142
  import { handleContextQuery, handleContextFleet, handleContextContent, handleContextInsights, handleContextComms, registerContextProjection, registerContextServices, CONTEXT_REQUEST_TYPES } from './context-bridge.mjs'
139
143
  import { handleCostMeter, COST_METER_REQUEST_TYPES, registerCostMeterProjection, registerCostMeterServices } from './cost-meter-bridge.mjs'
@@ -1738,6 +1742,7 @@ async function handleQuery(api, host, agentDefaultModel, msg, pluginContext) {
1738
1742
  if (CONTEXT_REQUEST_TYPES.has(msg.type)) return handleContextQuery(api, msg)
1739
1743
  if (ACCOUNT_REQUEST_TYPES.has(msg.type)) return handleAccount(api, msg)
1740
1744
  if (PLUGIN_REQUEST_TYPES.has(msg.type)) return handlePluginQuery(api, msg, pluginContext)
1745
+ if (MODEL_CONFIG_REQUEST_TYPES.has(msg.type)) return handleModelConfigQuery(api, msg, { log })
1741
1746
  if (msg.type === 'agent-team' || msg.type === 'subagents') {
1742
1747
  const target = sessionTargetFromMessage(msg)
1743
1748
  const requestIdentity = typeof msg.requestId === 'string' ? { requestId: msg.requestId } : {}
@@ -3831,13 +3836,15 @@ const plugin = {
3831
3836
  msg.type === 'goal-pause' || msg.type === 'goal-resume' || msg.type === 'goal-clear' ||
3832
3837
  msg.type === 'schedule-catalog' || msg.type === 'schedule-list' || msg.type === 'schedule-history' ||
3833
3838
  msg.type === 'schedule-update' || msg.type === 'schedule-delete' ||
3834
- ACCOUNT_REQUEST_TYPES.has(msg.type) || COST_METER_REQUEST_TYPES.has(msg.type) || WORKSPACE_CHANGES_TYPES.has(msg.type) || CONTEXT_REQUEST_TYPES.has(msg.type) || PLUGIN_REQUEST_TYPES.has(msg.type)) {
3835
- if ((ACCOUNT_REQUEST_TYPES.has(msg.type) || COST_METER_REQUEST_TYPES.has(msg.type) || WORKSPACE_CHANGES_TYPES.has(msg.type) || CONTEXT_REQUEST_TYPES.has(msg.type) || PLUGIN_REQUEST_TYPES.has(msg.type) || msg.type === 'clawbot-control') && !ws.deviceId) {
3839
+ ACCOUNT_REQUEST_TYPES.has(msg.type) || COST_METER_REQUEST_TYPES.has(msg.type) || WORKSPACE_CHANGES_TYPES.has(msg.type) || CONTEXT_REQUEST_TYPES.has(msg.type) || PLUGIN_REQUEST_TYPES.has(msg.type) || MODEL_CONFIG_REQUEST_TYPES.has(msg.type)) {
3840
+ if ((ACCOUNT_REQUEST_TYPES.has(msg.type) || COST_METER_REQUEST_TYPES.has(msg.type) || WORKSPACE_CHANGES_TYPES.has(msg.type) || CONTEXT_REQUEST_TYPES.has(msg.type) || PLUGIN_REQUEST_TYPES.has(msg.type) || MODEL_CONFIG_REQUEST_TYPES.has(msg.type) || msg.type === 'clawbot-control') && !ws.deviceId) {
3836
3841
  sendFrame({ kind: 'error', code: 'authentication-required', requestType: msg.type,
3837
3842
  ...(typeof msg.requestId === 'string' ? { requestId: msg.requestId } : {}),
3838
3843
  message: msg.type === 'clawbot-control'
3839
3844
  ? 'ClawBot control requires a paired device'
3840
- : 'Plugin management requires a paired device' })
3845
+ : MODEL_CONFIG_REQUEST_TYPES.has(msg.type)
3846
+ ? 'Model configuration requires a paired device'
3847
+ : 'Plugin management requires a paired device' })
3841
3848
  return
3842
3849
  }
3843
3850
  if (msg.type === 'plugin-install' && pluginInstallOwners.has(msg.requestId)) {
@@ -3906,6 +3913,7 @@ const plugin = {
3906
3913
  'goals',
3907
3914
  'schedule-management',
3908
3915
  'plugin-management-v1',
3916
+ 'llm-model-config-v1',
3909
3917
  ...(device ? ['speech-input-v1'] : []),
3910
3918
  ...(device && options.fileUploadsEnabled && api.files?.available() ? ['file-upload-v1'] : []),
3911
3919
  'session-cancel',
@@ -0,0 +1,267 @@
1
+ // 小程序「模型 / Provider」页面的三个控制请求:模型发现、模型凭据描述与写入。
2
+ //
3
+ // 它们与 plugin-* 请求走同一条已配对控制连接。网关只做参数校验、转发和字段
4
+ // 白名单化,真正的网络探测与凭据存储都在 Host 侧:
5
+ // - llm-discover-models -> Host llm/discoverModels(apiKey 只用于这一次
6
+ // 探测,Host 不存储)
7
+ // - model-credential-describe -> Host credentials/describe
8
+ // - model-credential-set -> Host credentials/set(值只上行,没有读路径)
9
+ //
10
+ // 安全底线:apiKey 与凭据值只允许出现在发往 Host 的调用参数里。响应帧、错误
11
+ // message 与日志都不回显它们;失败 message 先脱敏再截断到 500 字符。
12
+ //
13
+ // 凭据引用只能是当前 llm-pi-ai settings namespace 里 providers[*].apiKeyEnv
14
+ // 声明的名字,因此移动端无法写入 Host 从未声明的任意引用。
15
+
16
+ export const MODEL_CONFIG_REQUEST_TYPES = new Set([
17
+ 'llm-discover-models',
18
+ 'model-credential-describe',
19
+ 'model-credential-set',
20
+ ])
21
+
22
+ // pi-ai 多 Provider 双胞胎的 settings namespace;该 namespace 的 value 形如
23
+ // { providers: { <route>: { apiKeyEnv?, api, baseURL, models, ... } } }。
24
+ const MODEL_SETTINGS_NS = 'llm-pi-ai'
25
+ const CREDENTIAL_REF = /^[A-Za-z_][A-Za-z0-9_]{0,255}$/
26
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/
27
+ // 凭据值最终会作为 HTTP header 发出,只接受可打印 ASCII(不含空格)。
28
+ const PRINTABLE_HEADER_VALUE = /^[\x21-\x7e]+$/
29
+ const MAX_ID = 200
30
+ const MAX_NAMESPACE = 200
31
+ const MAX_PROVIDER = 200
32
+ const MAX_BASE_URL = 2048
33
+ const MAX_API = 80
34
+ const MAX_API_KEY = 8192
35
+ const MAX_CREDENTIAL_VALUE = 8192
36
+ const MAX_ERROR_MESSAGE = 500
37
+
38
+ function record(value) {
39
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
40
+ }
41
+
42
+ function badRequest(type, requestId, message) {
43
+ return { kind: 'error', code: 'bad-request', message, requestType: type,
44
+ ...(requestId === undefined ? {} : { requestId }) }
45
+ }
46
+
47
+ function failure(type, requestId, code, message) {
48
+ return { kind: 'error', code, message, requestType: type,
49
+ ...(requestId === undefined ? {} : { requestId }) }
50
+ }
51
+
52
+ // 宿主错误的可下发文本:先抹掉本次请求携带的密钥,再截断。任何密钥都不允许
53
+ // 经由 message 回到移动端或日志里。
54
+ function sanitizeError(error, secrets) {
55
+ const raw = error && typeof error.message === 'string' && error.message !== ''
56
+ ? error.message
57
+ : typeof error === 'string' && error !== '' ? error : 'unknown error'
58
+ let message = raw
59
+ for (const secret of secrets) {
60
+ if (typeof secret === 'string' && secret !== '') message = message.split(secret).join('[redacted]')
61
+ }
62
+ return message.length > MAX_ERROR_MESSAGE ? message.slice(0, MAX_ERROR_MESSAGE) : message
63
+ }
64
+
65
+ function isHttpURL(value) {
66
+ try {
67
+ const url = new URL(value)
68
+ return url.protocol === 'http:' || url.protocol === 'https:'
69
+ } catch {
70
+ return false
71
+ }
72
+ }
73
+
74
+ // llm-discover-models 的请求体:只把校验过的字段交给 Host。
75
+ function discoveryRequest(msg, type, requestId) {
76
+ const ns = typeof msg.ns === 'string' ? msg.ns.trim() : ''
77
+ if (ns === '' || ns.length > MAX_NAMESPACE) {
78
+ return { error: badRequest(type, requestId, `ns must be a non-empty namespace of at most ${MAX_NAMESPACE} characters`) }
79
+ }
80
+ const request = {}
81
+ let hasEndpoint = false
82
+ if (msg.provider !== undefined) {
83
+ const provider = typeof msg.provider === 'string' ? msg.provider.trim() : ''
84
+ if (provider === '' || provider.length > MAX_PROVIDER) {
85
+ return { error: badRequest(type, requestId, `provider must be a non-empty route name of at most ${MAX_PROVIDER} characters`) }
86
+ }
87
+ request.provider = provider
88
+ hasEndpoint = true
89
+ }
90
+ if (msg.baseURL !== undefined) {
91
+ const baseURL = typeof msg.baseURL === 'string' ? msg.baseURL.trim() : ''
92
+ if (baseURL === '' || baseURL.length > MAX_BASE_URL || !isHttpURL(baseURL)) {
93
+ return { error: badRequest(type, requestId, 'baseURL must be an absolute HTTP(S) URL') }
94
+ }
95
+ request.baseURL = baseURL
96
+ hasEndpoint = true
97
+ }
98
+ if (!hasEndpoint) {
99
+ return { error: badRequest(type, requestId, `${type} requires a provider or a baseURL`) }
100
+ }
101
+ if (msg.api !== undefined) {
102
+ const api = typeof msg.api === 'string' ? msg.api.trim() : ''
103
+ if (api === '' || api.length > MAX_API) {
104
+ return { error: badRequest(type, requestId, `api must be a non-empty protocol name of at most ${MAX_API} characters`) }
105
+ }
106
+ request.api = api
107
+ }
108
+ if (msg.apiKey !== undefined) {
109
+ if (typeof msg.apiKey !== 'string' || msg.apiKey.length > MAX_API_KEY || CONTROL_CHARACTERS.test(msg.apiKey)) {
110
+ return { error: badRequest(type, requestId, `apiKey must be a string of at most ${MAX_API_KEY} characters without control characters`) }
111
+ }
112
+ // 空串等同于「没有携带一次性凭据」;不要把空 header 传给 Host。
113
+ if (msg.apiKey.length > 0) request.apiKey = msg.apiKey
114
+ }
115
+ return { ns, request }
116
+ }
117
+
118
+ // Host 的发现结果是数组;只保留白名单字段,丢弃非法/重复 id(Host 与移动端
119
+ // 之间允许出现旧版本或第三方 adapter 的额外字段)。
120
+ function sanitizeModels(value) {
121
+ const models = []
122
+ const seen = new Set()
123
+ for (const entry of Array.isArray(value) ? value : []) {
124
+ if (!record(entry)) continue
125
+ const id = typeof entry.id === 'string' ? entry.id.trim() : ''
126
+ if (id === '' || id.length > MAX_ID || seen.has(id)) continue
127
+ seen.add(id)
128
+ const model = { id }
129
+ if (typeof entry.name === 'string' && entry.name.trim() !== '') model.name = entry.name
130
+ if (typeof entry.contextWindow === 'number' && Number.isFinite(entry.contextWindow) && entry.contextWindow > 0) {
131
+ model.contextWindow = entry.contextWindow
132
+ }
133
+ if (typeof entry.maxTokens === 'number' && Number.isFinite(entry.maxTokens) && entry.maxTokens > 0) {
134
+ model.maxTokens = entry.maxTokens
135
+ }
136
+ if (Array.isArray(entry.inputModalities)) {
137
+ const modalities = [...new Set(entry.inputModalities.filter(item => item === 'text' || item === 'image'))]
138
+ if (modalities.length > 0) model.inputModalities = modalities
139
+ }
140
+ models.push(model)
141
+ }
142
+ return models
143
+ }
144
+
145
+ // 当前 llm-pi-ai namespace 里被 profile 引用的凭据名(apiKeyEnv)。providers 在
146
+ // Host 里是 route -> profile 的字典;数组形状也接受,避免旧 profile 形状差异。
147
+ async function modelCredentialScopes(api) {
148
+ if (typeof api.settings?.describe !== 'function') {
149
+ throw Object.assign(new Error('settings are unavailable'), { code: 'model-credentials-unavailable' })
150
+ }
151
+ const described = await api.settings.describe()
152
+ if (!record(described) || !Array.isArray(described.namespaces)) {
153
+ throw Object.assign(new Error('settings/describe returned an invalid response'), { code: 'model-credentials-unavailable' })
154
+ }
155
+ const namespace = described.namespaces.find(item => record(item) && item.ns === MODEL_SETTINGS_NS)
156
+ const providers = namespace?.value?.providers
157
+ const profiles = Array.isArray(providers)
158
+ ? providers
159
+ : record(providers) ? Object.values(providers) : []
160
+ const refs = new Set()
161
+ for (const profile of profiles) {
162
+ if (!record(profile)) continue
163
+ if (typeof profile.apiKeyEnv === 'string' && profile.apiKeyEnv !== '') refs.add(profile.apiKeyEnv)
164
+ }
165
+ return { refs }
166
+ }
167
+
168
+ function credentialRefOf(msg, type, requestId) {
169
+ const ref = typeof msg.ref === 'string' ? msg.ref : ''
170
+ if (!CREDENTIAL_REF.test(ref)) {
171
+ return { error: badRequest(type, requestId, 'invalid credential reference') }
172
+ }
173
+ return { ref }
174
+ }
175
+
176
+ async function discoverModels(api, msg, type, requestId, log) {
177
+ const built = discoveryRequest(msg, type, requestId)
178
+ if (built.error) return built.error
179
+ const { ns, request } = built
180
+ const secrets = request.apiKey === undefined ? [] : [request.apiKey]
181
+ try {
182
+ if (typeof api.llm?.discoverModels !== 'function') {
183
+ throw new Error('the Host does not expose model discovery')
184
+ }
185
+ const discovered = await api.llm.discoverModels(ns, request)
186
+ const models = sanitizeModels(discovered)
187
+ log?.(`llm discovery: ns=${ns}${request.provider === undefined ? '' : ` provider=${request.provider}`} models=${models.length}`)
188
+ return { kind: type, requestId, models }
189
+ } catch (error) {
190
+ const message = sanitizeError(error, secrets)
191
+ log?.(`llm discovery failed: ns=${ns} -> ${message}`)
192
+ return failure(type, requestId, 'llm-discovery-failed', message)
193
+ }
194
+ }
195
+
196
+ async function describeCredential(api, msg, type, requestId, log) {
197
+ const checked = credentialRefOf(msg, type, requestId)
198
+ if (checked.error) return checked.error
199
+ const { ref } = checked
200
+ try {
201
+ const scopes = await modelCredentialScopes(api)
202
+ if (!scopes.refs.has(ref)) {
203
+ return badRequest(type, requestId, 'reference is not used by a model provider')
204
+ }
205
+ const described = await api.pluginConfiguration.credentialDescribe(ref)
206
+ const view = record(described) ? described[ref] : undefined
207
+ const configured = record(view) && view.configured === true
208
+ // 可写性来自凭据库本身(credentials/describe 的 writable),不是 settings
209
+ // 文档的可写位:凭据值存在凭据库里,与 settings 是否只读无关。
210
+ const writable = record(view) && view.writable === true
211
+ log?.(`model credential described: ref=${ref} configured=${configured} writable=${writable}`)
212
+ return {
213
+ kind: type,
214
+ requestId,
215
+ configured,
216
+ writable,
217
+ // source 只是凭据来源层名称(env/file 等),不是凭据值;有就透传。
218
+ ...(record(view) && typeof view.source === 'string' && view.source !== '' ? { source: view.source } : {}),
219
+ }
220
+ } catch (error) {
221
+ const message = sanitizeError(error, [])
222
+ log?.(`model credential describe failed: ref=${ref} -> ${message}`)
223
+ return failure(type, requestId, (error && typeof error.code === 'string' && error.code) || 'model-credentials-unavailable', message)
224
+ }
225
+ }
226
+
227
+ async function setCredential(api, msg, type, requestId, log) {
228
+ const checked = credentialRefOf(msg, type, requestId)
229
+ if (checked.error) return checked.error
230
+ const { ref } = checked
231
+ const value = typeof msg.value === 'string' ? msg.value : ''
232
+ if (value === '' || value.length > MAX_CREDENTIAL_VALUE || !PRINTABLE_HEADER_VALUE.test(value) || value.trim() === '') {
233
+ return badRequest(type, requestId, `value must be non-empty printable ASCII of at most ${MAX_CREDENTIAL_VALUE} characters`)
234
+ }
235
+ try {
236
+ const scopes = await modelCredentialScopes(api)
237
+ if (!scopes.refs.has(ref)) {
238
+ return badRequest(type, requestId, 'reference is not used by a model provider')
239
+ }
240
+ await api.pluginConfiguration.credentialSet(ref, value)
241
+ log?.(`model credential saved: ref=${ref}`)
242
+ return { kind: type, requestId, saved: true }
243
+ } catch (error) {
244
+ // 值本身也要脱敏:宿主错误里可能回显它。
245
+ const message = sanitizeError(error, [value])
246
+ log?.(`model credential write failed: ref=${ref} -> ${message}`)
247
+ return failure(type, requestId, 'model-credential-write-failed', message)
248
+ }
249
+ }
250
+
251
+ /**
252
+ * The mobile wire owns its request names and correlation ids; the Host adapter
253
+ * owns Remote endpoint names. Every request here requires a paired device and a
254
+ * non-empty requestId (the caller enforces pairing before dispatching).
255
+ */
256
+ export async function handleModelConfigQuery(api, msg, { log } = {}) {
257
+ const type = msg?.type
258
+ if (!MODEL_CONFIG_REQUEST_TYPES.has(type)) return null
259
+ const requestId = typeof msg.requestId === 'string' && msg.requestId.trim() !== '' && msg.requestId.length <= 128
260
+ ? msg.requestId.trim()
261
+ : undefined
262
+ if (requestId === undefined) return { kind: 'error', code: 'bad-request',
263
+ message: `${type} requires a requestId`, requestType: type }
264
+ if (type === 'llm-discover-models') return discoverModels(api, msg, type, requestId, log)
265
+ if (type === 'model-credential-describe') return describeCredential(api, msg, type, requestId, log)
266
+ return setCredential(api, msg, type, requestId, log)
267
+ }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "鲸尾移动网关",
3
+ "title": "鲸尾网关助手",
4
4
  "description": "连接 DSH 与鲸尾移动客户端,支持安全配对、远程访问、上下文、编队、额度和语音输入。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-plugin-weapp-gateway",
3
- "version": "0.8.35",
4
- "description": "鲸尾移动网关:DeepSeek Harness 移动客户端连接与会话同步,支持安全配对、远程访问、上下文、编队、额度和语音输入",
3
+ "version": "0.8.38",
4
+ "description": "鲸尾网关助手:DeepSeek Harness 移动客户端连接与会话同步,支持安全配对、远程访问、上下文、编队、额度和语音输入",
5
5
  "main": "lib/index.mjs",
6
6
  "files": [
7
7
  "bin",
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "bin": "bin/setup-ip.mjs",
31
31
  "scripts": {
32
- "test": "node test/wire-json.test.mjs && node --test test/history-cache.test.mjs && node test/session-target.test.mjs && node test/setup-ip.test.mjs && node test/host-adapter.test.mjs && node test/file-upload-adapter.test.mjs && node test/file-upload.test.mjs && node test/agent-team.test.mjs && node test/account-bridge.test.mjs && node test/context-bridge.test.mjs && node test/cost-meter.test.mjs && node --test test/cost-meter-dashboard.test.mjs && node test/clawbot-service.test.mjs && node test/speech-input.test.mjs && node test/speech-official.test.mjs && node test/plugin-management.test.mjs && node test/plugin-updates.test.mjs && node test/session-preset.test.mjs && node test/session-follower.test.mjs && node test/completion-notifications.test.mjs && node --test test/workspace-changes.test.mjs && node test/gateway.test.mjs && node test/auth.test.mjs && node test/lan.test.mjs && node test/cloudflared-binary.test.mjs && node test/cloudflare-tunnel.test.mjs && node --test test/public-endpoint-check.test.mjs && node test/gateway-tools.test.mjs && node test/relay-connector.test.mjs && node test/restart-reconnect.test.mjs && node test/cloudflare-linux.test.mjs && node test/multi-gateway.test.mjs"
32
+ "test": "node test/wire-json.test.mjs && node --test test/history-cache.test.mjs && node test/session-target.test.mjs && node test/setup-ip.test.mjs && node test/host-adapter.test.mjs && node test/file-upload-adapter.test.mjs && node test/file-upload.test.mjs && node test/agent-team.test.mjs && node test/account-bridge.test.mjs && node test/context-bridge.test.mjs && node test/cost-meter.test.mjs && node --test test/cost-meter-dashboard.test.mjs && node test/clawbot-service.test.mjs && node test/speech-input.test.mjs && node test/speech-official.test.mjs && node test/plugin-management.test.mjs && node test/model-config.test.mjs && node test/plugin-updates.test.mjs && node test/session-preset.test.mjs && node test/session-follower.test.mjs && node test/completion-notifications.test.mjs && node --test test/workspace-changes.test.mjs && node test/gateway.test.mjs && node test/auth.test.mjs && node test/lan.test.mjs && node test/cloudflared-binary.test.mjs && node test/cloudflare-tunnel.test.mjs && node --test test/public-endpoint-check.test.mjs && node test/gateway-tools.test.mjs && node test/relay-connector.test.mjs && node test/restart-reconnect.test.mjs && node test/cloudflare-linux.test.mjs && node test/multi-gateway.test.mjs"
33
33
  },
34
34
  "exports": {
35
35
  ".": "./lib/index.mjs",
@@ -192,11 +192,24 @@ class AgentSession {
192
192
  }
193
193
 
194
194
  open(packet) {
195
- if (!this.ready || !packet || packet.length < 9 + 17 || packet[0] !== PACKET_SEALED) return null;
195
+ this.lastOpenFailure = null;
196
+ if (!this.ready) { this.lastOpenFailure = 'not-ready'; return null; }
197
+ if (!packet || packet.length < 9 + 17 || packet[0] !== PACKET_SEALED) {
198
+ this.lastOpenFailure = 'format';
199
+ return null;
200
+ }
196
201
  const counter = readCounter(packet, 1);
197
- if (counter < this.rxCounter) return null;
202
+ // 重复帧(这条管道已经处理过该 counter)不是密钥错误:排队/回放/重连边界
203
+ // 上都可能发生。丢弃即可,绝不能因此关闭整条管道。
204
+ if (counter < this.rxCounter) {
205
+ this.lastOpenFailure = 'duplicate';
206
+ return null;
207
+ }
198
208
  const clear = nacl.secretbox.open(packet.subarray(9), concat(this.rxPrefix, counterBytes(counter)), this.key);
199
- if (!clear || clear.length < 1 || clear[0] !== CLEAR_DATA) return null;
209
+ if (!clear || clear.length < 1 || clear[0] !== CLEAR_DATA) {
210
+ this.lastOpenFailure = 'decrypt';
211
+ return null;
212
+ }
200
213
  this.rxCounter = counter + 1;
201
214
  return utf8Decode(clear.subarray(1));
202
215
  }
@@ -395,7 +408,7 @@ async function handleClientOpen(frame, agentWs) {
395
408
  });
396
409
 
397
410
  gateway.on('close', (code, reason) => {
398
- log(`管道 ${bridgeId}: 本地网关关闭 ${code} ${reason.toString()}`);
411
+ log(`管道 ${bridgeId}: 本地网关关闭 ${code} ${reason ? reason.toString() : ''}`.trimEnd());
399
412
  pipes.delete(bridgeId);
400
413
  if (agentWs.readyState === WebSocket.OPEN) {
401
414
  agentWs.send(JSON.stringify({ kind: 'client-close', bridgeId }), { binary: false });
@@ -471,8 +484,10 @@ function authenticateGateway(pipe, bridgeId, frame) {
471
484
  }
472
485
  sendPipeFrame(pipe.agentWs, bridgeId, pipe.session.seal(text));
473
486
  });
474
- gateway.on('close', () => {
487
+ gateway.on('close', (code, reason) => {
475
488
  clearTimeout(pipe.authTimer); pipes.delete(bridgeId);
489
+ rejectedFrameLog.delete(bridgeId);
490
+ log(`管道 ${bridgeId}: 本地网关关闭 ${code} ${reason ? reason.toString() : ''}`.trimEnd());
476
491
  if (pipe.agentWs.readyState === WebSocket.OPEN) pipe.agentWs.send(JSON.stringify({ kind: 'client-close', bridgeId }));
477
492
  });
478
493
  gateway.on('error', () => {
@@ -502,7 +517,14 @@ function handleRelayBinary(data) {
502
517
  if (pipe.session.ready && packet[0] === PACKET_SEALED) {
503
518
  const text = pipe.session.open(packet);
504
519
  if (text === null) {
505
- log(`管道 ${bridgeId}: 密文解密失败,关闭管道`);
520
+ const reason = pipe.session.lastOpenFailure;
521
+ // 重复帧/残帧只丢弃,不关管道:把它们当“解密失败”会把一条健康连接直接
522
+ // 掐断,手机侧看到 4001 gateway-closed,表现就是打开会话/切页面就掉线。
523
+ if (reason === 'duplicate' || reason === 'format' || reason === 'not-ready') {
524
+ logRejectedFrame(bridgeId, reason, packet.length);
525
+ return;
526
+ }
527
+ log(`管道 ${bridgeId}: 密文解密失败,关闭管道(${reason || 'unknown'})`);
506
528
  try { pipe.gateway.close(4002, 'e2ee-decrypt-failed'); } catch (error) { /* ignore */ }
507
529
  pipes.delete(bridgeId);
508
530
  return;
@@ -576,6 +598,21 @@ function log(message) {
576
598
  console.log(`[connector ${new Date().toISOString()}] ${message}`);
577
599
  }
578
600
 
601
+ // 重复/残帧可能成串出现(例如重连后旧会话的残留帧),按管道限流汇总,
602
+ // 避免日志刷屏同时保留“确实在丢帧”的可见性。
603
+ const rejectedFrameLog = new Map();
604
+ function logRejectedFrame(bridgeId, reason, length) {
605
+ const now = Date.now();
606
+ const entry = rejectedFrameLog.get(bridgeId) || { at: now, count: 0 };
607
+ entry.count += 1;
608
+ if (now - entry.at >= 2000) {
609
+ log(`管道 ${bridgeId}: 丢弃 ${entry.count} 个重复/残帧(${reason},len=${length})`);
610
+ rejectedFrameLog.set(bridgeId, { at: now, count: 0 });
611
+ return;
612
+ }
613
+ rejectedFrameLog.set(bridgeId, entry);
614
+ }
615
+
579
616
  // ---------- 主流程 ----------
580
617
 
581
618
  process.on('SIGINT', () => {