dsh-plugin-weapp-gateway 0.8.37 → 0.8.41
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 +40 -10
- package/README.md +24 -9
- package/lib/client.js +104 -10
- package/lib/index.mjs +198 -46
- package/lib/network-diagnostics.mjs +126 -0
- package/lib/session-event-details.mjs +59 -0
- package/lib/tailscale-addresses.mjs +37 -0
- package/package.json +2 -2
- package/relay/agent-connector.js +43 -6
package/PROTOCOL.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
移动端通过经过设备鉴权的 WebSocket 连接与 dsh 通信:订阅 Agent 实时输出、发送文字、图片和文件、查看轮次大纲及编队/子智能体会话、处理 Human-in-the-loop 提问与操作审批、查询会话/工作区/历史、调整会话配置。本插件当前基线为 DSH 0.2.1-rc.2 / Session format 4,移动端实时流接入见 [rc.2 接入说明](docs/dsh-rc2-mobile-integration.md)。插件管理(第 18 节)的 Remote namespace 需 DSH 0.2.0-rc.2 或更新宿主;最新的轮次导航、编队/子会话和文件上传扩展见本文末尾及其 [App 接入指南](docs/turn-outline-app-integration.md)、[编队接入指南](docs/agent-team-app-integration.md)、[文件上传接入指南](docs/file-upload-app-integration.md)。
|
|
4
4
|
|
|
5
5
|
- **本机端点**:`ws://127.0.0.1:3080/ws/mobile`(与 dsh web GUI 同端口)
|
|
6
|
-
- **局域网端点**:`ws://<电脑的私有局域网 IP>:3081/ws/mobile`(插件独立监听,只提供经过鉴权的 WebSocket
|
|
6
|
+
- **局域网端点**:`ws://<电脑的私有局域网 IP>:3081/ws/mobile`(插件独立监听,只提供经过鉴权的 WebSocket);同一 Tailnet 的手机可直接使用 `ws://<Tailscale IP>:3081/ws/mobile`(`100.64.0.0/10` / `fd7a:115c:a1e0::/48` 与私有网络同等放行)。`GET /mgw/status` 的 `tailscale` 字段返回本机检测到的 `addresses` 与可用 `urls`,不推断手机地址,也不等于已登录 tailnet
|
|
7
7
|
- **公网端点**:必须由 TLS 反向代理提供 `wss://<域名>/ws/mobile`
|
|
8
8
|
- **帧格式**:全部为 JSON 文本帧(UTF-8);图片字节及语音 WAV 使用标准 Base64
|
|
9
9
|
- **连接即推送**:连上后服务端立刻发送一条 `hello`,之后 agent 输出以 `event` 帧实时推送
|
|
@@ -74,12 +74,14 @@ const pairingText = Buffer.from(JSON.stringify(payload), 'utf8').toString('base6
|
|
|
74
74
|
|
|
75
75
|
客户端必须先执行严格 Base64URL 解码(只允许 `A-Z a-z 0-9 - _`,不接受 `=` padding、原始 JSON 或普通 Base64),再解析 JSON 并检查 `version` 与 `expiresAt`。
|
|
76
76
|
|
|
77
|
-
首次连接必须请求子协议 `dsh-mobile-v1, dsh-pair.<pairingCode>`,并携带 `X-DSH-Device-ID` 请求头;缺少稳定设备 ID 的配对请求会被拒绝,避免每次重连都创建新的可信设备。该值应为客户端在 Keychain 中持久保存的安装级随机 UUID,仅用于重新配对时复用可信设备记录,不能替代配对码或设备 token
|
|
77
|
+
首次连接必须请求子协议 `dsh-mobile-v1, dsh-pair.<pairingCode>`,并携带 `X-DSH-Device-ID` 请求头;缺少稳定设备 ID 的配对请求会被拒绝,避免每次重连都创建新的可信设备。该值应为客户端在 Keychain 中持久保存的安装级随机 UUID,仅用于重新配对时复用可信设备记录,不能替代配对码或设备 token 完成鉴权。
|
|
78
|
+
|
|
79
|
+
浏览器等无法设置自定义握手头的客户端,可以把同一设备 ID 放进子协议 `dsh-device.<id>`(ID 必须由 RFC 6455 token 字符组成,即 `[A-Za-z0-9._-]{8,128}`),把设备名放进 `dsh-device-name.<base64url>`(与请求头的标准 Base64 等价);设备 ID 仍不是凭证,配对码与长期 token 的要求不变。兼容实现也可把一次性配对码放在 `?pairingCode=`;但子协议不会进入常见的 URL access log,因此优先使用子协议。成功后服务端依次发送:
|
|
78
80
|
|
|
79
81
|
```json
|
|
80
82
|
{ "kind": "paired", "token": "<长期设备 token>",
|
|
81
83
|
"device": { "id": "...", "name": "iPhone", "createdAt": 1787111700000 } }
|
|
82
|
-
{ "kind": "hello", "protocol": 3, "capabilities": ["split-channels", "images", "commands", "tasks", "goals", "turn-outline-v1", "agent-team-v1", "subagent-conversations-v1", "file-upload-v1", "file-references-v1", "session-cancel", "queue-control", "session-archive", "session-rename", "file-downloads"], "authenticated": true,
|
|
84
|
+
{ "kind": "hello", "protocol": 3, "capabilities": ["split-channels", "network-diagnostics-v1", "images", "commands", "tasks", "goals", "turn-outline-v1", "agent-team-v1", "subagent-conversations-v1", "file-upload-v1", "file-references-v1", "llm-model-config-v1", "session-cancel", "queue-control", "session-archive", "session-rename", "file-downloads"], "authenticated": true,
|
|
83
85
|
"device": { "id": "...", "name": "iPhone" }, "port": 3080, "clients": 1 }
|
|
84
86
|
```
|
|
85
87
|
|
|
@@ -109,13 +111,16 @@ const pairingText = Buffer.from(JSON.stringify(payload), 'utf8').toString('base6
|
|
|
109
111
|
|
|
110
112
|
| 字段 | 内容 | 使用方 |
|
|
111
113
|
|---|---|---|
|
|
112
|
-
| `lan` | `ws://`(或 `wss
|
|
114
|
+
| `lan` | `ws://`(或 `wss://`)私网/本机地址(含 Tailscale `100.64.0.0/10` / `fd7a:115c:a1e0::/48`),规范化去重,最多 16 项;物理局域网地址排在 Tailscale 之前 | 小程序与 App |
|
|
113
115
|
| `public` | `wss://` 公网地址(用户自己的域名/反代/Cloudflare Tunnel) | 仅 App |
|
|
114
116
|
| `relay` | `{ relay, nodeId, agentPubKey, gatewayName?, authMode: "gateway" }`;`relay` 必须是公网 `wss://`,`nodeId` 8–128 位 URL 安全字符,`agentPubKey` 为 32 字节 Base64;客户端连接地址为 `relay` 去尾斜杠后拼 `/c/` + `nodeId` | 仅小程序 |
|
|
115
117
|
|
|
116
118
|
选路规则:微信小程序的 socket 必须命中合法域名,运营者自己的公网直连地址基本不可用,因此小程序的公网线路是中继;多端 App 与原生 App 没有合法域名限制、也没有微信登录换不到中继租赁,因此只拨公网直连。两端都以「上次真正连通的地址」为第一候选,中继取不到租赁时继续回退局域网候选(配对码仍然有效)。小程序手动输入的公网地址会被客户端直接拒绝并给出说明,不进入候选链。
|
|
117
119
|
|
|
118
120
|
`miniProgramRoute` 是早期版本给旧小程序的等价字段(`{ mode: "direct", publicUrl, endpoints }` 或 `{ mode: "relay", relay, nodeId, agentPubKey, gatewayName }`),继续随载荷输出;新客户端应优先读取 `routes`。
|
|
121
|
+
|
|
122
|
+
`POST /mgw/pair` 的 `route` 还支持 `tailscale`:只接受 `ws://` + Tailscale IP(未显式给出时使用本机探测到的第一个 Tailscale 地址),局域网入口未监听或地址不是 Tailscale 时返回 409;生成的载荷只把 Tailscale 地址放进 `routes.lan`,不包含公网、中继或其他局域网端点,也不生成 `miniProgramRoute`(微信小程序线上环境要求 wss 域名)。`routes.lan` 中的 Tailscale 地址对客户端与其他私网地址等价,客户端按“物理局域网优先、Tailscale 其后”的顺序尝试即可。
|
|
123
|
+
|
|
119
124
|
本机管理接口 `POST /mgw/gateway` 接受 `{"mode":"disabled|temporary|persistent"}` 中的一个具体值,例如 `{"mode":"persistent"}`。兼容旧 `{"enabled":true}`(临时开启)与 false(关闭);不能同时传 `mode` 和 `enabled`。返回 `gatewayEnabled`、`gatewayMode`、`waitExpiresAt`、`connectedClients`。参数错误返回 400;保存失败返回 500 且不改变当前运行模式。
|
|
120
125
|
|
|
121
126
|
`GET /mgw/status` 增加身份、地址列表及 `gatewayMode`。模式的持久化不影响配对码有效期和文件传输超时。自动超时关闭若遇到磁盘写入失败,会保持当前进程关闭并记录错误;重启可能仍按旧保存模式运行,需修复存储后再次保存选择。
|
|
@@ -317,7 +322,7 @@ Agent 调用 DSH 的 `ask_user_question` 工具时,插件接入 Host 的
|
|
|
317
322
|
"outcome":"answered" }
|
|
318
323
|
```
|
|
319
324
|
|
|
320
|
-
`outcome` 为 `answered` 或 `cancelled
|
|
325
|
+
`outcome` 为 `answered` 或 `cancelled`。网关开启时会登记所有待答提问,并同时保留 WebUI/后续 Host answerer;多台移动设备与 WebUI 中的第一个合法响应获胜。实时广播仍按订阅 Session 过滤,后台会话的提问会在设备首次连接或之后打开对应 Session 时以 `replay: true` 重放;登记时没有移动客户端则立刻回退给 WebUI,不会挂住工具调用。所有移动连接都会收到由移动端完成的最终状态并应关闭对应选择界面;DSH 进程重启则会取消这些仅存在于运行时的问题。
|
|
321
326
|
|
|
322
327
|
---
|
|
323
328
|
|
|
@@ -812,6 +817,28 @@ iOS 用 `Data(base64Encoded:)` 解码并按 `attachment.mediaType` 渲染,建
|
|
|
812
817
|
- 默认每块为 512 KiB、同时最多 4 个下载、单个文件最多 512 MiB。部署方可用 `fileDownloadChunkBytes`、`fileDownloadMaxTransfers`、`fileDownloadMaxBytes`、`fileDownloadIdleMs` 调整;`fileDownloadsEnabled: false` 会关闭该能力,且 `hello.capabilities` 不再包含 `file-downloads`。
|
|
813
818
|
- 绝对路径、空路径(`file-download-open`)、`..` 路径段、NUL 字符、工作目录外的符号链接、目录和其他非普通文件都会被拒绝。`file-list` 不返回符号链接,避免客户端误认为其可下载。
|
|
814
819
|
|
|
820
|
+
### 文件引用解析(`file-resolve`,`file-references-v1`)
|
|
821
|
+
|
|
822
|
+
文件卡片和正文里的文件链接可能只带工作目录相对路径或主机原生绝对路径。`file-resolve` 把它们解析成下载协议需要的相对路径与预览元数据,省去先遍历目录的步骤(文件位于未加载过的 `build/` 等子目录时也能直接打开)。
|
|
823
|
+
|
|
824
|
+
```json
|
|
825
|
+
{ "type": "file-resolve", "requestId": "resolve-1", "sessionId": "session-abc", "path": "build/三亚国庆旅游攻略.pdf" }
|
|
826
|
+
→ {
|
|
827
|
+
"kind": "file-resolved", "requestId": "resolve-1", "sessionId": "session-abc",
|
|
828
|
+
"path": "build/三亚国庆旅游攻略.pdf", "name": "三亚国庆旅游攻略.pdf",
|
|
829
|
+
"mediaType": "application/pdf", "size": 2048000, "modifiedAt": 1787111700000
|
|
830
|
+
}
|
|
831
|
+
```
|
|
832
|
+
|
|
833
|
+
- 必须带非空 `requestId`(响应回显)与 `sessionId`;`path` 可以是工作目录相对路径,也可以是主机原生绝对路径。
|
|
834
|
+
- 绝对路径只在这里接受,且必须落在该 Session 的工作目录内(macOS 的 `/var` 与 `/private/var` 别名会被映射后再做包含校验);`file-download-open` 仍只接受相对路径。
|
|
835
|
+
- 目录、符号链接逃逸、NUL/`..` 路径段、超过 `fileDownloadMaxBytes` 的文件分别返回 `file-not-regular` / `file-not-allowed` / `file-too-large`。
|
|
836
|
+
- 成功后客户端把返回的 `path` 交给 `file-download-open` 即可预览;`hello.capabilities` 包含 `file-references-v1` 且 `fileDownloadsEnabled` 开启时才公布该能力。
|
|
837
|
+
|
|
838
|
+
### 服务端网络检测(`network-diagnostics-v1`)
|
|
839
|
+
|
|
840
|
+
`hello.capabilities` 包含 `network-diagnostics-v1` 表示管理面板支持服务端网络检测:管理接口 `POST /mgw/network-test`(仅本机回环)向每条已鉴权移动连接发一次 WebSocket Ping/Pong,按设备与通道返回协议 RTT、最近一分钟样本、平均值与 P95。该能力只影响 WebUI 面板,移动端不会收到额外帧;经过 Tunnel 或代理时 RTT 可能只反映代理链路,不能当作业务处理耗时。
|
|
841
|
+
|
|
815
842
|
### `session-stats` 详细(输入框统计条)
|
|
816
843
|
```json
|
|
817
844
|
{ "type": "session-stats", "sessionId": "session-abc" }
|
|
@@ -1127,7 +1154,7 @@ Control/旧单连接接收全局模式状态增量,不受所订阅会话过滤
|
|
|
1127
1154
|
| kind | 触发时机 |
|
|
1128
1155
|
|---|---|
|
|
1129
1156
|
| `paired` | 首次配对成功;仅此一次返回长期设备 token |
|
|
1130
|
-
| `hello` | 连接成功:`{ "kind":"hello", "protocol":3, "capabilities":["split-channels","images","commands","tasks","goals","turn-outline-v1","agent-team-v1","subagent-conversations-v1","file-upload-v1","file-references-v1","session-cancel","queue-control","session-archive","session-rename","file-downloads"], "authenticated":true, "port":3080, "clients":1 }` |
|
|
1157
|
+
| `hello` | 连接成功:`{ "kind":"hello", "protocol":3, "capabilities":["split-channels","network-diagnostics-v1","images","commands","tasks","goals","turn-outline-v1","agent-team-v1","subagent-conversations-v1","file-upload-v1","file-references-v1","llm-model-config-v1","session-cancel","queue-control","session-archive","session-rename","file-downloads"], "authenticated":true, "port":3080, "clients":1 }` |
|
|
1131
1158
|
| `event` | 任意会话的 agent 输出(见下) |
|
|
1132
1159
|
| `session-queues` / `session-queue` | Host 队列完整快照 / 单个 Session 队列替换值 |
|
|
1133
1160
|
| `session-archives` | Host 的完整 Session 归档集合在连接初始化或 WebUI/App 归档后变化 |
|
|
@@ -1146,12 +1173,15 @@ Control/旧单连接接收全局模式状态增量,不受所订阅会话过滤
|
|
|
1146
1173
|
`event.type` 覆盖(精炼字段):
|
|
1147
1174
|
- `user/message` → `{text, source, images?: ImageAttachmentRef[], attachments?: MessageAttachment[]}`
|
|
1148
1175
|
- 实时 token 使用独立 `assistant-stream`,不是带持久 seq 的 `assistant/chunk`;详见 [rc.2 接入说明](docs/dsh-rc2-mobile-integration.md)。
|
|
1149
|
-
- `assistant/attempt` → `{turn, step, stream[]}`
|
|
1150
|
-
- `assistant/message` → `{turn, step, text, reasoning, toolCalls[], interrupted?, usage?}`
|
|
1176
|
+
- `assistant/attempt` → `{turn, step, stream[], finish?}`
|
|
1177
|
+
- `assistant/message` → `{turn, step, text, reasoning, toolCalls[], finish?, interrupted?, usage?}`
|
|
1151
1178
|
- `session/title` → `{title, source?}`
|
|
1152
1179
|
- `tool/call` → `{turn, step, callId, name, arguments}`
|
|
1153
|
-
- `tool/result` → `{turn, step, callId, isError, preview(≤400字符)}`
|
|
1154
|
-
- `
|
|
1180
|
+
- `tool/result` → `{turn, step, callId, isError, preview(≤400字符), output(≤16KB 首尾摘要), outputTruncated}`
|
|
1181
|
+
- `llm/retry` → `{turn, step, retryId, retry, provider, mode, maxRetries, delayMs, failure?}`;`llm/retry-started` 只带 `{turn, step, retryId, retry}`
|
|
1182
|
+
- `turn/start|end` / `step/start|end` → `{turn, step, reason?, reasonDetails?}`;`reason` 保持本仓库既有形态(成功为 kind 字符串,错误/中止为 `{kind,error|reason}`,小程序兼容),`reasonDetails` 为上游形态的增量字段
|
|
1183
|
+
|
|
1184
|
+
`finish` 为 `{kind, failure?}`(`failure` 只保留 message/code/name/reason/requestId/status/providerRetryAfterMs),`output` 在超过 16KB 时保留首尾各 8KB 并以 `[…]` 连接,同时给出 `outputTruncated: true`。历史 `history` 响应中的对应事件与实时帧同形。
|
|
1155
1185
|
|
|
1156
1186
|
`MessageAttachment` 的普通文件元素形如 `{kind:"file", name, receiptId?, attachmentId?, bytes?, mediaType?}`,工作区目录元素形如 `{kind:"directory", name, path}`。发送 `message` 时也可带 `{kind:"file"|"directory", path, name?}`,其中 `path` 必须是工作区相对路径;网关拒绝绝对路径、`..` 路径和超过 6 项的请求。当前 DSH Remote 仅提供 `session/prompt`,工作区文件/目录按受校验的上下文引用发送并保留在历史附件元数据中,不伪造 `receiptId`,也不会未经用户操作递归上传目录;原生文件 receipt 上传需宿主提供 `fileUploads.uploadStream` 后再启用。
|
|
1157
1187
|
|
package/README.md
CHANGED
|
@@ -6,6 +6,27 @@
|
|
|
6
6
|
|
|
7
7
|
`dsh-plugin-weapp-gateway` · DeepSeek Harness 移动客户端连接插件
|
|
8
8
|
|
|
9
|
+
### v0.8.41 · Tailscale 参与配对选路
|
|
10
|
+
|
|
11
|
+
- 「配对连接方式」新增 **Tailscale 直连**:只使用本机 Tailscale 地址(`ws://100.x` / IPv6),二维码只包含 Tailscale 端点,不泄露公网或中继;检测不到地址或局域网入口未监听时该选项禁用。
|
|
12
|
+
- **自动选择**与默认配对载荷现在会把 Tailscale 地址作为局域网类候选一并下发(物理局域网地址在前、Tailscale 在后),手机在同一 tailnet 时自动选中。
|
|
13
|
+
- 管理接口 `POST /mgw/pair` 支持 `route: "tailscale"`:校验 `ws://` + Tailscale IP,局域网入口未开启或地址不是 Tailscale 时返回 409;载荷只带 `routes.lan`,不生成 `miniProgramRoute`(小程序线上环境要求 wss 域名,该二维码主要供 DSH App 使用)。
|
|
14
|
+
- 面板帮助文案补充 Tailscale 说明;协议文档更新 `routes.lan` 的 Tailscale 语义。
|
|
15
|
+
- 测试:`test/lan.test.mjs` 覆盖 Tailscale 配对路线(201、端点只含 Tailscale、非 Tailscale 地址 409),全量 36 个测试文件通过。
|
|
16
|
+
### v0.8.40 · Tailscale 直连支持
|
|
17
|
+
|
|
18
|
+
- 新增 [`lib/tailscale-addresses.mjs`](lib/tailscale-addresses.mjs):识别本机 Tailscale 地址(`100.64.0.0/10` 与 `fd7a:115c:a1e0::/48`),并在 `/mgw/status` 新增 `tailscale: { addresses, urls }`(只读本机接口,不推断手机 IP;检测到地址不等于已登录 tailnet)。
|
|
19
|
+
- 局域网监听与配对地址校验对 Tailscale 来源放行:同一 tailnet 的手机可直接使用 `ws://100.x.x.x:3081/ws/mobile` 配对,无需 `tailscale serve`;`tailscale serve` 仍可用于 HTTPS/浏览器场景。
|
|
20
|
+
- 「连接与配对」页展示检测到的 Tailscale 直连地址(未监听时提示先开启局域网入口)。
|
|
21
|
+
- 新增 `test/tailscale-addresses.test.mjs`(地址识别、接口探测、IPv6 括号、无接口不编造),并在 `test/lan.test.mjs`、`test/auth.test.mjs` 补充状态形状与 Tailscale 配对地址断言。
|
|
22
|
+
### v0.8.39 · 同步上游移动网关新功能
|
|
23
|
+
|
|
24
|
+
- **文件引用解析 `file-resolve`**(app 文件卡片预览依赖):把工作目录相对路径或主机原生绝对路径解析成下载协议需要的相对路径与预览元数据(`file-resolved`:`path`/`name`/`mediaType`/`size`/`modifiedAt`),不再需要先遍历目录;绝对路径只在这里接受且必须落在 Session 工作目录内(含 macOS `/var` 与 `/private/var` 别名映射),越界、目录、超限分别返回 `file-not-allowed`/`file-not-regular`/`file-too-large`。属 `file-references-v1` 能力。
|
|
25
|
+
- **服务端网络检测 `network-diagnostics-v1`**:管理接口 `POST /mgw/network-test` 向每条已鉴权移动连接发 WebSocket Ping/Pong,按设备与通道返回协议 RTT、最近一分钟样本、平均值与 P95;面板「通用设置」新增「服务端网络检测」卡片(页面可见时每两秒刷新)。仅本机回环管理接口,移动端没有新增帧。
|
|
26
|
+
- **浏览器设备元数据子协议**:无法设置自定义握手头的浏览器客户端可用 `dsh-device.<id>` 传设备 ID、`dsh-device-name.<base64url>` 传设备名;设备 ID 仍不是凭证,配对码与长期 token 要求不变。
|
|
27
|
+
- **问题/审批重放对齐上游**:网关开启时登记所有待答提问与审批(不再要求当前已有匹配移动连接),设备首次连接或之后打开对应会话时以 `replay: true` 补发;实时广播仍按订阅 Session 过滤,登记时没有移动客户端则立刻回退给 WebUI,不挂住工具调用。
|
|
28
|
+
- **事件详情对齐上游**:`assistant/message`/`assistant/attempt` 增加 `finish`(结束原因与失败摘要),`tool/result` 增加 `output`(≤16KB 首尾摘要)与 `outputTruncated`,新增 `llm/retry`/`llm/retry-started` 实时帧,`turn/*` 增加增量字段 `reasonDetails`;`reason` 保持既有形态,小程序兼容路径不变。
|
|
29
|
+
- 新增 `test/question-replay.test.mjs`、`test/network-diagnostics.test.mjs`,并在 `test/gateway.test.mjs`(`file-resolve` 与事件详情)与 `test/auth.test.mjs`(子协议配对、网络诊断接口、能力列表)补充回归;35 个测试文件全部通过。小程序配对、选路与中继路径未改动。
|
|
9
30
|
### v0.8.37 · 模型发现与模型凭据写入
|
|
10
31
|
|
|
11
32
|
- 新增三个控制连接请求,供小程序「模型 / Provider」页面在配对设备上发现自定义 Provider 的模型、查询并写入模型凭据:`llm-discover-models`(转发 Host `llm/discoverModels`,一次性 `apiKey` 只用于本次探测)、`model-credential-describe`、`model-credential-set`(转发 Host `credentials/describe|set`)。
|
|
@@ -418,16 +439,10 @@ apt-get update && apt-get install -y cloudflared
|
|
|
418
439
|
### Tailscale(推荐长期使用)
|
|
419
440
|
|
|
420
441
|
1. 在电脑和 iPhone 安装 [Tailscale](https://tailscale.com/download),并登录同一个 Tailnet。
|
|
421
|
-
2.
|
|
442
|
+
2. 插件会自动探测本机 Tailscale 接口地址(`100.64.0.0/10` 或 `fd7a:115c:a1e0::/48`)并显示在「连接与配对」页。开启局域网入口后,同一 Tailnet 的手机可以直接使用 `ws://100.x.x.x:3081/ws/mobile` 配对,无需任何转发。
|
|
443
|
+
3. 需要 HTTPS / 浏览器访问时再执行 `tailscale serve --bg 3081`,用 `tailscale serve status` 查看 `https://<设备名>.<tailnet>.ts.net` 地址,把 `wss://<设备名>.<tailnet>.ts.net/ws/mobile` 填入「手动输入地址」后生成二维码。
|
|
422
444
|
|
|
423
|
-
|
|
424
|
-
tailscale serve --bg 3081
|
|
425
|
-
```
|
|
426
|
-
|
|
427
|
-
3. 执行 `tailscale serve status` 查看生成的 `https://<设备名>.<tailnet>.ts.net` 地址。
|
|
428
|
-
4. 将地址改为 `wss://<设备名>.<tailnet>.ts.net/ws/mobile`,填入 WebUI 的“WebSocket 地址”,再生成二维码配对。
|
|
429
|
-
|
|
430
|
-
Tailscale Serve 只允许同一 Tailnet 中符合访问规则的设备连接,并自动提供 HTTPS。可用 `tailscale serve reset` 停止转发。参见 [Tailscale Serve 文档](https://tailscale.com/docs/reference/tailscale-cli/serve)。
|
|
445
|
+
局域网监听对 `100.64.0.0/10` 与 Tailscale IPv6 来源放行,鉴权规则与其他私有网络一致。Tailscale Serve 只允许同一 Tailnet 中符合访问规则的设备连接,并自动提供 HTTPS;可用 `tailscale serve reset` 停止转发。参见 [Tailscale Serve 文档](https://tailscale.com/docs/reference/tailscale-cli/serve)。
|
|
431
446
|
|
|
432
447
|
## 网关配置方式总览
|
|
433
448
|
|
package/lib/client.js
CHANGED
|
@@ -336,6 +336,7 @@ window.__ModuleLoader__.load({
|
|
|
336
336
|
if (route === 'lan') return lanUrl
|
|
337
337
|
if (route === 'relay') return status.relay?.relay || ''
|
|
338
338
|
if (route === 'cloudflare') return tunnelUrl
|
|
339
|
+
if (route === 'tailscale') return status.tailscale?.urls?.[0] || ''
|
|
339
340
|
const statusUrl = status.cloudflare?.enabled && status.cloudflare.publicReady !== true &&
|
|
340
341
|
status.publicUrl === status.cloudflare.publicUrl ? '' : status.publicUrl
|
|
341
342
|
return tunnelUrl || statusUrl || lanUrl || inferredUrl(status.wsPath)
|
|
@@ -351,7 +352,7 @@ window.__ModuleLoader__.load({
|
|
|
351
352
|
status.publicUrl === tunnel.publicUrl)
|
|
352
353
|
const serverReady = status.platform === 'linux' && !!(
|
|
353
354
|
(publicSetup?.configured && publicSetup.publicUrl) || (!statusUrlIsUnreadyTunnel && /^wss:\/\//.test(status.publicUrl || '')))
|
|
354
|
-
const detected = `当前检测:${system};局域网入口${lanReady ? '已就绪' : '未就绪'};${serverReady ? '公网服务器入口已配置' : tunnelReady ? `${tunnel.mode === 'quick' ? 'Quick' : '命名'} Tunnel 已连接` : tunnel?.enabled ? (tunnel.state === 'online' ? '隧道已连接,公网入口未验证或检测失败' : 'Cloudflare Tunnel 连接中') : '外网入口未连接'}。`
|
|
355
|
+
const detected = `当前检测:${system};局域网入口${lanReady ? '已就绪' : '未就绪'};Tailscale 地址${status.tailscale?.urls?.length ? '可用' : '未检测到'};${serverReady ? '公网服务器入口已配置' : tunnelReady ? `${tunnel.mode === 'quick' ? 'Quick' : '命名'} Tunnel 已连接` : tunnel?.enabled ? (tunnel.state === 'online' ? '隧道已连接,公网入口未验证或检测失败' : 'Cloudflare Tunnel 连接中') : '外网入口未连接'}。`
|
|
355
356
|
const local = lanReady
|
|
356
357
|
? 'DSH App 和小程序都可以通过局域网或 VPN 连接;手机与 DSH 同网时可使用局域网地址。'
|
|
357
358
|
: '两种客户端都可使用局域网连接;先确认局域网入口已开启并监听成功。'
|
|
@@ -378,6 +379,76 @@ window.__ModuleLoader__.load({
|
|
|
378
379
|
return device.routes.map((route) => ROUTE_BADGES[route]).filter(Boolean)
|
|
379
380
|
}
|
|
380
381
|
|
|
382
|
+
// 服务端网络检测:向每条已鉴权移动连接发一次 WebSocket ping,展示协议 RTT。
|
|
383
|
+
// 数据来自管理接口 POST /mgw/network-test(loopback);页面可见时每两秒刷新,
|
|
384
|
+
// 进入后台或关闭面板即停止。RTT 只反映网关到手机的协议往返,不是业务处理耗时。
|
|
385
|
+
function ServerNetworkDiagnostics() {
|
|
386
|
+
const [snapshot, setSnapshot] = React.useState(null)
|
|
387
|
+
const [failure, setFailure] = React.useState('')
|
|
388
|
+
const [running, setRunning] = React.useState(typeof document === 'undefined' ? false : !document.hidden)
|
|
389
|
+
React.useEffect(() => {
|
|
390
|
+
if (typeof document === 'undefined') return undefined
|
|
391
|
+
let mounted = true, timer, controller, generation = 0
|
|
392
|
+
const stop = () => { generation++; window.clearTimeout(timer); controller?.abort() }
|
|
393
|
+
const sample = async (lease) => {
|
|
394
|
+
if (!mounted || document.hidden || generation !== lease) return
|
|
395
|
+
controller = new AbortController()
|
|
396
|
+
try {
|
|
397
|
+
const data = await request('/mgw/network-test', { method: 'POST', signal: controller.signal })
|
|
398
|
+
if (mounted && generation === lease) { setSnapshot(data); setFailure('') }
|
|
399
|
+
} catch (cause) {
|
|
400
|
+
if (mounted && generation === lease && cause.name !== 'AbortError') setFailure(cause.message)
|
|
401
|
+
} finally {
|
|
402
|
+
if (mounted && generation === lease && !document.hidden) timer = window.setTimeout(() => sample(lease), 2000)
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
const visibility = () => {
|
|
406
|
+
stop()
|
|
407
|
+
setRunning(!document.hidden)
|
|
408
|
+
if (!document.hidden) { setSnapshot(null); void sample(generation) }
|
|
409
|
+
}
|
|
410
|
+
document.addEventListener('visibilitychange', visibility)
|
|
411
|
+
if (!document.hidden) void sample(generation)
|
|
412
|
+
return () => { mounted = false; stop(); document.removeEventListener('visibilitychange', visibility) }
|
|
413
|
+
}, [])
|
|
414
|
+
const number = (value) => Number.isFinite(value) ? `${value.toFixed(1)} ms` : '—'
|
|
415
|
+
const statusLabel = (value) => ({ ok: '正常', timeout: '探测超时', disconnected: '已断开', error: '检测失败', unavailable: '暂无有效样本', cancelled: '已停止' })[value] || '暂无有效样本'
|
|
416
|
+
const channelLabel = (value) => ({ control: '控制通道', conversation: '会话通道', legacy: '兼容通道' })[value] || '兼容通道'
|
|
417
|
+
const chart = (channel) => {
|
|
418
|
+
const points = channel.samples || []
|
|
419
|
+
const end = snapshot.at
|
|
420
|
+
const maximum = Math.max(1, ...points.map((point) => point.rttMs || 0)) * 1.15
|
|
421
|
+
const paths = []; let segment = []
|
|
422
|
+
const flush = () => { if (segment.length) paths.push(segment.join(' ')); segment = [] }
|
|
423
|
+
for (const point of points) {
|
|
424
|
+
if (!Number.isFinite(point.rttMs)) { flush(); continue }
|
|
425
|
+
segment.push(`${Math.max(0, (point.at - end + 60000) / 60000 * 300)},${70 - point.rttMs / maximum * 65}`)
|
|
426
|
+
}
|
|
427
|
+
flush()
|
|
428
|
+
return React.createElement('svg', { viewBox: '0 0 300 78', preserveAspectRatio: 'none', role: 'img', 'aria-label': '服务端最近一分钟 RTT', style: { width: '100%', height: 86, display: 'block' } },
|
|
429
|
+
[5, 38, 70].map((y) => React.createElement('line', { key: y, x1: 0, x2: 300, y1: y, y2: y, stroke: colors.border, strokeWidth: .6 })),
|
|
430
|
+
paths.map((points, index) => React.createElement('polyline', { key: index, points, fill: 'none', stroke: 'var(--dsw-alias-link, #4176e6)', strokeWidth: 1.5 })),
|
|
431
|
+
(points.filter((point) => Number.isFinite(point.rttMs)).slice(-1)).map((point) => React.createElement('circle', { key: point.at,
|
|
432
|
+
cx: Math.max(0, (point.at - end + 60000) / 60000 * 300), cy: 70 - point.rttMs / maximum * 65, r: 2, fill: 'var(--dsw-alias-link, #4176e6)' })))
|
|
433
|
+
}
|
|
434
|
+
return React.createElement('section', { style: styles.card, 'aria-label': '服务端网络检测' },
|
|
435
|
+
React.createElement('h3', { className: 'mgw-section-title' }, '服务端网络检测'),
|
|
436
|
+
React.createElement('p', { style: styles.muted }, running ? '自动检测已连接设备,每两秒刷新;离开此页或进入后台后停止。' : '后台已暂停检测'),
|
|
437
|
+
React.createElement('p', { style: styles.muted }, '使用 WebSocket 协议 Ping/Pong 测量往返时延;经过 Tunnel 或代理时,RTT 可能只反映代理链路。'),
|
|
438
|
+
failure ? React.createElement('p', { role: 'alert', style: styles.error }, failure) : null,
|
|
439
|
+
!snapshot ? React.createElement('p', { style: styles.muted }, '正在检测…') : snapshot.devices.length === 0
|
|
440
|
+
? React.createElement('p', { style: styles.muted }, '当前没有已连接设备。')
|
|
441
|
+
: snapshot.devices.map((device) => React.createElement('section', { key: device.deviceId, style: { marginTop: 18, paddingTop: 14, borderTop: `1px solid ${colors.border}` } },
|
|
442
|
+
React.createElement('strong', null, device.name || '未命名设备'),
|
|
443
|
+
device.channels.map((channel) => React.createElement('div', { key: channel.connectionId, style: { marginTop: 12 } },
|
|
444
|
+
React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: 8 } },
|
|
445
|
+
React.createElement('span', null, channelLabel(channel.channel), ' · WebSocket'),
|
|
446
|
+
React.createElement('strong', null, 'RTT ', number(channel.rttMs))),
|
|
447
|
+
React.createElement('p', { style: { ...styles.muted, margin: '6px 0' } }, statusLabel(channel.status), ' · 协议 Ping/Pong · 最近一分钟平均 ', number(channel.averageRttMs), ' · P95 ', number(channel.p95RttMs)),
|
|
448
|
+
chart(channel))))),
|
|
449
|
+
snapshot ? React.createElement('p', { style: styles.muted }, '服务端读取时间 ', new Date(snapshot.at).toLocaleTimeString(), ' · 曲线范围:最近一分钟') : null,
|
|
450
|
+
snapshot?.truncated ? React.createElement('p', { style: styles.muted }, '连接数量过多,仅检测前 256 条连接。') : null)
|
|
451
|
+
}
|
|
381
452
|
function DeviceRow({ device, onRevoke, revoking }) {
|
|
382
453
|
const triggerRevoke = (event) => {
|
|
383
454
|
event.preventDefault()
|
|
@@ -1106,6 +1177,7 @@ window.__ModuleLoader__.load({
|
|
|
1106
1177
|
status && !status.requireAuth
|
|
1107
1178
|
? React.createElement('p', { style: { ...styles.error, margin: '12px 0 0' } }, 'Debug 模式:本机 DSH 入口将跳过设备凭证校验;独立局域网入口仍强制鉴权。')
|
|
1108
1179
|
: null),
|
|
1180
|
+
React.createElement(ServerNetworkDiagnostics, null),
|
|
1109
1181
|
React.createElement('section', { style: styles.card },
|
|
1110
1182
|
React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 14, alignItems: 'flex-start' } },
|
|
1111
1183
|
React.createElement('div', null,
|
|
@@ -1161,6 +1233,7 @@ window.__ModuleLoader__.load({
|
|
|
1161
1233
|
connectionHelpOpen ? React.createElement('div', { id: 'mgw-route-help', role: 'tooltip', style: styles.helpBubble },
|
|
1162
1234
|
React.createElement('strong', null, '怎么选连接方式'),
|
|
1163
1235
|
helpLine('局域网直连', 'DSH App 和鲸尾小程序都可使用 ws:// 私有地址;手机与 DSH 位于可互访的局域网或 VPN 时可直连。'),
|
|
1236
|
+
helpLine('Tailscale 直连', '手机与电脑登录同一 tailnet 时,可用本机 Tailscale 地址(ws://100.x 或 IPv6)直接配对,无需 tailscale serve;微信小程序线上环境要求 wss 域名,可能只能供 DSH App 使用。'),
|
|
1164
1237
|
helpLine('Cloudflare Tunnel(命名)', 'PC 主动连接 Cloudflare,DSH App 和小程序都可通过固定域名的 wss:// 公网入口连接;需要 Cloudflare 账户和域名。'),
|
|
1165
1238
|
helpLine('Quick Tunnel', '无需账户或域名,两种客户端都可通过临时 wss:// 地址连接;隧道重建后地址可能变化。'),
|
|
1166
1239
|
helpLine('公网服务器连接', '配置 Linux 服务器公网 WSS 入口,DSH App 和小程序都可使用。'),
|
|
@@ -1187,19 +1260,30 @@ window.__ModuleLoader__.load({
|
|
|
1187
1260
|
value: 'cloudflare',
|
|
1188
1261
|
}, status.cloudflare.enabled && status.cloudflare.publicReady === true && status.cloudflare.publicUrl
|
|
1189
1262
|
? 'Cloudflare 外网' : 'Cloudflare 外网 · 尚未就绪') : null,
|
|
1263
|
+
// 仅在检测到 Tailscale 接口时提供专用路线;局域网入口未监听时禁用。
|
|
1264
|
+
status?.tailscale && Array.isArray(status.tailscale.addresses) && status.tailscale.addresses.length
|
|
1265
|
+
? React.createElement('option', { value: 'tailscale', disabled: !(Array.isArray(status.tailscale.urls) && status.tailscale.urls.length) },
|
|
1266
|
+
Array.isArray(status.tailscale.urls) && status.tailscale.urls.length
|
|
1267
|
+
? 'Tailscale 直连' : 'Tailscale 直连 · 请先开启局域网入口')
|
|
1268
|
+
: null,
|
|
1190
1269
|
React.createElement('option', { value: 'custom' }, '手动输入地址')),
|
|
1191
1270
|
status?.cloudflare?.supported && pairingRoute === 'auto'
|
|
1192
1271
|
? React.createElement('span', { style: { fontSize: 12, lineHeight: 1.5, fontWeight: 500,
|
|
1193
|
-
color: 'var(--dsw-alias-link, #4176e6)' } }, '
|
|
1194
|
-
:
|
|
1272
|
+
color: 'var(--dsw-alias-link, #4176e6)' } }, '自动选择会优先尝试已就绪的公网入口,并同时保留局域网与 Tailscale 地址;DSH App 和小程序都可使用这些候选地址。配置 Cloudflare 请切换到“Cloudflare 外网”。')
|
|
1273
|
+
: pairingRoute === 'tailscale'
|
|
1195
1274
|
? React.createElement('span', { style: { fontSize: 12, lineHeight: 1.5, fontWeight: 500,
|
|
1196
|
-
color: 'var(--dsw-alias-link, #4176e6)' } },
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1275
|
+
color: 'var(--dsw-alias-link, #4176e6)' } }, '只使用本机 Tailscale 地址(ws://100.x 或 IPv6);手机需登录同一 tailnet。微信小程序线上环境要求 wss 域名,可能只能供 DSH App 使用。')
|
|
1276
|
+
: status?.cloudflare?.supported && pairingRoute === 'cloudflare'
|
|
1277
|
+
? React.createElement('span', { style: { fontSize: 12, lineHeight: 1.5, fontWeight: 500,
|
|
1278
|
+
color: 'var(--dsw-alias-link, #4176e6)' } }, cloudflareReady
|
|
1279
|
+
? 'Cloudflare 外网已就绪;DSH App 和小程序都可使用公网入口,也会保留局域网候选地址。'
|
|
1280
|
+
: 'Cloudflare 尚未就绪,可在本页 Cloudflare 设置中开启并完成连通性检测。')
|
|
1281
|
+
: null),
|
|
1200
1282
|
React.createElement('p', { style: { ...styles.muted, margin: '-6px 0 10px' } }, pairingRoute === 'relay'
|
|
1201
1283
|
? '此模式生成仅供鲸尾小程序使用的中继二维码;DSH App 请选“自动选择”或“局域网直连”。'
|
|
1202
|
-
:
|
|
1284
|
+
: pairingRoute === 'tailscale'
|
|
1285
|
+
? '此模式只生成 Tailscale 直连二维码;手机与电脑需登录同一 tailnet。微信小程序线上环境要求 wss 域名,可能无法使用,请改用局域网/公网地址或 tailscale serve。'
|
|
1286
|
+
: '公网 WSS 就绪时,DSH App 和小程序都会尝试公网、局域网与 Tailscale 地址;没有公网入口时,App 使用局域网或 Tailscale,小程序优先使用已注册的鲸尾中继,否则也使用局域网。生成新二维码不会断开已连接设备。'),
|
|
1203
1287
|
// Fork: 中继模式下展示连接器状态与已注册中继信息
|
|
1204
1288
|
(relayInfo || relayConnector?.running || relayConnector?.delegatedTo || relayConnector?.lastError)
|
|
1205
1289
|
? (relayInfo
|
|
@@ -1232,17 +1316,27 @@ window.__ModuleLoader__.load({
|
|
|
1232
1316
|
? `局域网入口已开启${status.lan.urls && status.lan.urls.length ? `:${status.lan.urls.join('、')}` : `,端口 ${status.lan.port}`}`
|
|
1233
1317
|
: '局域网入口启动中…')
|
|
1234
1318
|
: null,
|
|
1319
|
+
// Tailscale 直连:同一 tailnet 的手机可直接连 ws://100.x 地址,无需 tailscale serve。
|
|
1320
|
+
status && status.tailscale && Array.isArray(status.tailscale.urls) && status.tailscale.urls.length
|
|
1321
|
+
? React.createElement('div', { style: { ...styles.muted, margin: '-7px 0 10px', fontWeight: 500, color: colors.success } },
|
|
1322
|
+
`Tailscale 直连可用:${status.tailscale.urls.join('、')}`)
|
|
1323
|
+
: status && status.tailscale && Array.isArray(status.tailscale.addresses) && status.tailscale.addresses.length
|
|
1324
|
+
? React.createElement('div', { style: { ...styles.muted, margin: '-7px 0 10px', fontWeight: 500, color: 'var(--dsw-alias-link, #4176e6)' } },
|
|
1325
|
+
`检测到 Tailscale 地址 ${status.tailscale.addresses.join('、')};开启局域网入口后可直接使用。`)
|
|
1326
|
+
: null,
|
|
1235
1327
|
React.createElement('button', {
|
|
1236
|
-
style: { ...styles.button, ...styles.primary, opacity: busy || !(status && status.gatewayEnabled) || (pairingRoute === 'custom' && !publicUrl.trim()) || (pairingRoute === 'cloudflare' && !cloudflareReady) ? .65 : 1 },
|
|
1328
|
+
style: { ...styles.button, ...styles.primary, opacity: busy || !(status && status.gatewayEnabled) || (pairingRoute === 'custom' && !publicUrl.trim()) || (pairingRoute === 'cloudflare' && !cloudflareReady) || (pairingRoute === 'tailscale' && !(status?.tailscale?.urls?.length)) ? .65 : 1 },
|
|
1237
1329
|
disabled: busy || !(status && status.gatewayEnabled) ||
|
|
1238
1330
|
(pairingRoute === 'custom' && !publicUrl.trim()) ||
|
|
1239
1331
|
(pairingRoute === 'cloudflare' && !cloudflareReady) ||
|
|
1332
|
+
(pairingRoute === 'tailscale' && !(status?.tailscale?.urls?.length)) ||
|
|
1240
1333
|
(pairingRoute === 'relay' && !status?.relay),
|
|
1241
1334
|
onClick: pair,
|
|
1242
1335
|
}, busy ? '正在生成…' : !(status && status.gatewayEnabled) ? '请先开启移动网关'
|
|
1243
1336
|
: pairingRoute === 'cloudflare' && !cloudflareReady
|
|
1244
1337
|
? status?.cloudflare?.enabled ? '等待 Cloudflare 外网就绪' : '先开启 Cloudflare Tunnel'
|
|
1245
|
-
: (pairingRoute === '
|
|
1338
|
+
: (pairingRoute === 'tailscale' && !(status?.tailscale?.urls?.length)) ? '等待 Tailscale 地址'
|
|
1339
|
+
: (pairingRoute === 'custom' && !publicUrl.trim()) ? '等待连接地址' : '生成配对二维码'),
|
|
1246
1340
|
React.createElement('p', { style: { ...styles.muted, margin: '10px 0 0' } }, '配对码仅可使用一次,5 分钟内有效。')),
|
|
1247
1341
|
pairingRoute === 'cloudflare' && status?.cloudflare?.supported
|
|
1248
1342
|
? React.createElement('section', { className: 'mgw-cloudflare-block', style: { ...styles.card, background: colors.card, border: 0, borderRadius: 16, padding: 18, marginTop: 16 } },
|
package/lib/index.mjs
CHANGED
|
@@ -159,6 +159,9 @@ import QRCode from 'qrcode'
|
|
|
159
159
|
import { createHistoryCache, historyCacheKey } from './history-cache.mjs'
|
|
160
160
|
import { parseSessionTarget, TEAM_PROJECTION_KINDS } from './session-target.mjs'
|
|
161
161
|
import { createFileUploadManager, FILE_UPLOAD_REQUEST_TYPES, FILE_UPLOAD_DEFAULTS } from './file-upload.mjs'
|
|
162
|
+
import { assistantFinish, failureDetails, toolResultDetails, turnReasonDetails } from './session-event-details.mjs'
|
|
163
|
+
import { createNetworkDiagnostics } from './network-diagnostics.mjs'
|
|
164
|
+
import { isTailscaleIp, tailscaleInterfaceStatus } from './tailscale-addresses.mjs'
|
|
162
165
|
|
|
163
166
|
const { createRegistry } = devicesModule
|
|
164
167
|
|
|
@@ -433,6 +436,7 @@ function buildWireEvent(session, event) {
|
|
|
433
436
|
}
|
|
434
437
|
return Object.assign(base, {
|
|
435
438
|
event: { type: 'assistant/message', turn: d.turn, step: d.step, text, reasoning, toolCalls,
|
|
439
|
+
...(assistantFinish(d) ? { finish: assistantFinish(d) } : {}),
|
|
436
440
|
...(d.interrupted === true ? { interrupted: true } : {}),
|
|
437
441
|
...(d.usage === undefined ? {} : { usage: d.usage }),
|
|
438
442
|
...(images.length ? { images } : {}),
|
|
@@ -442,7 +446,15 @@ function buildWireEvent(session, event) {
|
|
|
442
446
|
})
|
|
443
447
|
}
|
|
444
448
|
case 'assistant/attempt':
|
|
445
|
-
return Object.assign(base, { event: { type: event.type, turn: d.turn, step: d.step, stream: d.stream
|
|
449
|
+
return Object.assign(base, { event: { type: event.type, turn: d.turn, step: d.step, stream: d.stream,
|
|
450
|
+
...(assistantFinish(d) ? { finish: assistantFinish(d) } : {}) } })
|
|
451
|
+
case 'llm/retry':
|
|
452
|
+
case 'llm/retry-started':
|
|
453
|
+
return Object.assign(base, { event: { type: event.type, turn: d.turn, step: d.step,
|
|
454
|
+
retryId: d.retryId, retry: d.retry,
|
|
455
|
+
...(event.type === 'llm/retry' ? { provider: d.provider, mode: d.mode,
|
|
456
|
+
maxRetries: d.maxRetries, delayMs: d.delayMs, failure: failureDetails(d.failure) } : {}),
|
|
457
|
+
} })
|
|
446
458
|
case 'session/title':
|
|
447
459
|
return Object.assign(base, {
|
|
448
460
|
event: {
|
|
@@ -474,6 +486,7 @@ function buildWireEvent(session, event) {
|
|
|
474
486
|
callId: d.message?.toolCallId ?? d.message?.source?.callId,
|
|
475
487
|
isError: d.message?.isError === true || !!d.error || ((d.message && d.message.content) || []).some(block => block?.type === 'tool-result' && block.isError === true),
|
|
476
488
|
preview,
|
|
489
|
+
...toolResultDetails(d),
|
|
477
490
|
...(d.error ? { error: d.error } : {}),
|
|
478
491
|
},
|
|
479
492
|
})
|
|
@@ -541,7 +554,8 @@ function buildWireEvent(session, event) {
|
|
|
541
554
|
case 'step/start':
|
|
542
555
|
case 'step/end':
|
|
543
556
|
return Object.assign(base, {
|
|
544
|
-
event: { type: event.type, turn: d.turn, step: d.step, reason: wireTurnReason(d.reason)
|
|
557
|
+
event: { type: event.type, turn: d.turn, step: d.step, reason: wireTurnReason(d.reason),
|
|
558
|
+
...(turnReasonDetails(d.reason) ? { reasonDetails: turnReasonDetails(d.reason) } : {}) },
|
|
545
559
|
})
|
|
546
560
|
default:
|
|
547
561
|
return Object.assign(base, { event: { type: event.type } })
|
|
@@ -945,20 +959,31 @@ function createFileTransferManager(api, options) {
|
|
|
945
959
|
if (!stat.isDirectory()) {
|
|
946
960
|
return fileTransferError('file-workspace-unavailable', 'the session working directory is unavailable', requestType, sessionId)
|
|
947
961
|
}
|
|
948
|
-
return { root }
|
|
962
|
+
return { root, inputRoot: path.resolve(item.cwd) }
|
|
949
963
|
} catch {
|
|
950
964
|
return fileTransferError('file-workspace-unavailable', 'the session working directory is unavailable', requestType, sessionId)
|
|
951
965
|
}
|
|
952
966
|
}
|
|
953
967
|
|
|
954
968
|
const resolveWorkspaceTarget = async (sessionId, rawPath, requestType, inputOptions) => {
|
|
955
|
-
|
|
969
|
+
// Only the resolver accepts native absolute paths from recorded deliveries
|
|
970
|
+
// or Markdown links. Download requests remain workspace-relative.
|
|
971
|
+
const absoluteInput = inputOptions?.allowAbsolute === true
|
|
972
|
+
&& typeof rawPath === 'string' && path.isAbsolute(rawPath.trim())
|
|
973
|
+
const requested = absoluteInput
|
|
974
|
+
? (rawPath.includes('\0') || rawPath.trim().split(/[\\/]+/).includes('..') ? null : rawPath.trim())
|
|
975
|
+
: normalizedWorkspaceInput(rawPath, inputOptions)
|
|
956
976
|
if (!requested) {
|
|
957
|
-
return fileTransferError('bad-request', `${requestType} requires a relative workspace path`, requestType, sessionId)
|
|
977
|
+
return fileTransferError('bad-request', `${requestType} requires a valid ${inputOptions?.allowAbsolute ? '' : 'relative '}workspace path`, requestType, sessionId)
|
|
958
978
|
}
|
|
959
979
|
const rootResult = await resolveSessionRoot(sessionId, requestType)
|
|
960
980
|
if (rootResult.kind === 'error') return rootResult
|
|
961
|
-
|
|
981
|
+
// macOS commonly exposes one workspace as both /var/... and /private/var/...
|
|
982
|
+
// (and cwd itself may be a symlink). Map only the known cwd alias before
|
|
983
|
+
// enforcing the canonical root, then still verify the target's realpath.
|
|
984
|
+
const candidate = absoluteInput && isInsideWorkspace(rootResult.inputRoot, requested)
|
|
985
|
+
? path.resolve(rootResult.root, path.relative(rootResult.inputRoot, requested))
|
|
986
|
+
: path.resolve(rootResult.root, requested)
|
|
962
987
|
if (!isInsideWorkspace(rootResult.root, candidate)) {
|
|
963
988
|
return fileTransferError('file-not-allowed', 'path must stay inside the session working directory', requestType, sessionId)
|
|
964
989
|
}
|
|
@@ -1019,6 +1044,30 @@ function createFileTransferManager(api, options) {
|
|
|
1019
1044
|
}
|
|
1020
1045
|
}
|
|
1021
1046
|
|
|
1047
|
+
// 文件卡片与正文文件引用:把工作目录相对路径或主机原生绝对路径解析成
|
|
1048
|
+
// 下载协议需要的相对路径与预览元数据。解析不需要先遍历目录,因此文件位于
|
|
1049
|
+
// build/ 等未加载过的子目录时也能直接打开。
|
|
1050
|
+
const resolveFile = async (msg) => {
|
|
1051
|
+
const session = requireSessionId(msg)
|
|
1052
|
+
if (session.error) return session.error
|
|
1053
|
+
const requestId = typeof msg.requestId === 'string' && msg.requestId.trim() ? msg.requestId.trim() : null
|
|
1054
|
+
if (!requestId) return fileTransferError('bad-request', 'file-resolve requires a requestId', 'file-resolve', session.value)
|
|
1055
|
+
const resolved = await resolveWorkspaceTarget(session.value, msg.path, 'file-resolve', { allowAbsolute: true })
|
|
1056
|
+
if (resolved.kind === 'error') return resolved
|
|
1057
|
+
if (!resolved.stat.isFile()) {
|
|
1058
|
+
return fileTransferError('file-not-regular', 'only regular files can be previewed', 'file-resolve', session.value)
|
|
1059
|
+
}
|
|
1060
|
+
if (resolved.stat.size > options.fileDownloadMaxBytes) {
|
|
1061
|
+
return fileTransferError('file-too-large', 'file exceeds the configured download limit', 'file-resolve', session.value)
|
|
1062
|
+
}
|
|
1063
|
+
return {
|
|
1064
|
+
kind: 'file-resolved', requestId, sessionId: session.value,
|
|
1065
|
+
path: workspaceRelativePath(resolved.root, resolved.target),
|
|
1066
|
+
name: path.basename(resolved.target), mediaType: fileMediaType(resolved.target),
|
|
1067
|
+
size: resolved.stat.size, modifiedAt: resolved.stat.mtimeMs,
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1022
1071
|
const open = async (client, msg) => {
|
|
1023
1072
|
const requestId = typeof msg.requestId === 'string' && msg.requestId.trim() ? msg.requestId.trim() : null
|
|
1024
1073
|
const session = requireSessionId(msg)
|
|
@@ -1160,6 +1209,7 @@ function createFileTransferManager(api, options) {
|
|
|
1160
1209
|
return fileTransferError('file-download-disabled', 'file downloads are disabled by gateway configuration', msg.type)
|
|
1161
1210
|
}
|
|
1162
1211
|
if (msg.type === 'file-list') return fileList(msg)
|
|
1212
|
+
if (msg.type === 'file-resolve') return resolveFile(msg)
|
|
1163
1213
|
if (msg.type === 'file-download-open') return open(client, msg)
|
|
1164
1214
|
if (msg.type === 'file-download-read') return read(client, msg)
|
|
1165
1215
|
if (msg.type === 'file-download-cancel') return cancel(client, msg)
|
|
@@ -1355,12 +1405,14 @@ function trimConversationEvent(event) {
|
|
|
1355
1405
|
case 'assistant/message':
|
|
1356
1406
|
case 'assistant/attempt': {
|
|
1357
1407
|
const { stream, ...data } = event.data || {}
|
|
1358
|
-
|
|
1408
|
+
const finish = assistantFinish(event.data || {})
|
|
1409
|
+
return { ...event, data: { ...data, ...(finish ? { finish } : {}) } }
|
|
1359
1410
|
}
|
|
1360
1411
|
case 'tool/result': {
|
|
1361
1412
|
const d = event.data || {}
|
|
1362
1413
|
const message = d.message
|
|
1363
|
-
|
|
1414
|
+
const details = toolResultDetails(d)
|
|
1415
|
+
if (!message || !Array.isArray(message.content)) return { ...event, data: { ...d, ...details } }
|
|
1364
1416
|
let changed = false
|
|
1365
1417
|
const truncateBlock = (block) => {
|
|
1366
1418
|
if (!block || typeof block !== 'object') return block
|
|
@@ -1374,8 +1426,8 @@ function trimConversationEvent(event) {
|
|
|
1374
1426
|
return block
|
|
1375
1427
|
}
|
|
1376
1428
|
const content = message.content.map(truncateBlock)
|
|
1377
|
-
if (!changed) return event
|
|
1378
|
-
return { ...event, data: { ...d, message: { ...message, content } } }
|
|
1429
|
+
if (!changed) return { ...event, data: { ...d, ...details } }
|
|
1430
|
+
return { ...event, data: { ...d, ...details, message: { ...message, content } } }
|
|
1379
1431
|
}
|
|
1380
1432
|
default:
|
|
1381
1433
|
return event
|
|
@@ -2422,18 +2474,46 @@ function extractCredential(req, allowQueryToken) {
|
|
|
2422
2474
|
return undefined
|
|
2423
2475
|
}
|
|
2424
2476
|
|
|
2477
|
+
const CLIENT_DEVICE_ID_PATTERN = /^[A-Za-z0-9._:-]{8,128}$/
|
|
2478
|
+
// A raw subprotocol must also be a valid RFC 6455 token. In particular, ':'
|
|
2479
|
+
// is valid in the header form but cannot be constructed by browser clients.
|
|
2480
|
+
const CLIENT_DEVICE_ID_SUBPROTOCOL_PATTERN = /^[A-Za-z0-9._-]{8,128}$/
|
|
2481
|
+
const MAX_ENCODED_DEVICE_NAME_LENGTH = 512
|
|
2482
|
+
|
|
2425
2483
|
function extractClientDeviceId(req) {
|
|
2426
|
-
const
|
|
2427
|
-
if (typeof
|
|
2428
|
-
|
|
2429
|
-
|
|
2484
|
+
const header = req.headers['x-dsh-device-id']
|
|
2485
|
+
if (typeof header === 'string') {
|
|
2486
|
+
const normalized = header.trim()
|
|
2487
|
+
if (CLIENT_DEVICE_ID_PATTERN.test(normalized)) return normalized
|
|
2488
|
+
}
|
|
2489
|
+
// 浏览器等客户端无法设置自定义握手头,而子协议是浏览器唯一能自定义的握手元数据。
|
|
2490
|
+
// 让这类客户端把同一安装级设备 ID 放进 `dsh-device.<id>` 子协议即可完成配对。
|
|
2491
|
+
// 设备 ID 不是凭证:配对仍需要一次性配对码,长期 token 仍由 claimPairing() 签发。
|
|
2492
|
+
for (const protocol of parseProtocols(req)) {
|
|
2493
|
+
if (!protocol.startsWith('dsh-device.')) continue
|
|
2494
|
+
const normalized = protocol.slice('dsh-device.'.length).trim()
|
|
2495
|
+
if (CLIENT_DEVICE_ID_SUBPROTOCOL_PATTERN.test(normalized)) return normalized
|
|
2496
|
+
}
|
|
2497
|
+
return undefined
|
|
2430
2498
|
}
|
|
2431
2499
|
|
|
2432
2500
|
function extractClientDeviceName(req) {
|
|
2433
2501
|
const value = req.headers['x-dsh-device-name']
|
|
2434
|
-
if (typeof value
|
|
2435
|
-
|
|
2436
|
-
|
|
2502
|
+
if (typeof value === 'string' && value.length <= MAX_ENCODED_DEVICE_NAME_LENGTH
|
|
2503
|
+
&& /^[A-Za-z0-9+/]*={0,2}$/.test(value)) {
|
|
2504
|
+
const name = Buffer.from(value, 'base64').toString('utf8').trim()
|
|
2505
|
+
if (name && !/[\u0000-\u001f\u007f\ufffd]/.test(name)) return name.slice(0, 80)
|
|
2506
|
+
}
|
|
2507
|
+
// 同理,浏览器把设备名放进 `dsh-device-name.<base64url>`;设备名只用于展示,
|
|
2508
|
+
// 不参与鉴权。
|
|
2509
|
+
for (const protocol of parseProtocols(req)) {
|
|
2510
|
+
if (!protocol.startsWith('dsh-device-name.')) continue
|
|
2511
|
+
const encoded = protocol.slice('dsh-device-name.'.length)
|
|
2512
|
+
if (encoded.length > MAX_ENCODED_DEVICE_NAME_LENGTH || !/^[A-Za-z0-9_-]+$/.test(encoded)) continue
|
|
2513
|
+
const name = Buffer.from(encoded, 'base64url').toString('utf8').trim()
|
|
2514
|
+
if (name && !/[\u0000-\u001f\u007f\ufffd]/.test(name)) return name.slice(0, 80)
|
|
2515
|
+
}
|
|
2516
|
+
return undefined
|
|
2437
2517
|
}
|
|
2438
2518
|
|
|
2439
2519
|
function rejectUpgrade(socket, status, message, probe) {
|
|
@@ -2446,6 +2526,8 @@ function isLocalHostname(hostname) {
|
|
|
2446
2526
|
return normalized === 'localhost' || normalized === '::1' || /^127(?:\.\d{1,3}){3}$/.test(normalized)
|
|
2447
2527
|
}
|
|
2448
2528
|
|
|
2529
|
+
// 与客户端保持一致:只增加 Tailscale 的 100.64.0.0/10,不扩大到整个 100/8。
|
|
2530
|
+
// 这样局域网监听会接受同一 tailnet 的手机来源,ws:// Tailscale 地址也能用于配对。
|
|
2449
2531
|
function isPrivateNetworkHostname(hostname) {
|
|
2450
2532
|
let normalized = hostname.replace(/^\[|\]$/g, '').split('%')[0].toLowerCase()
|
|
2451
2533
|
if (normalized.startsWith('::ffff:')) normalized = normalized.slice('::ffff:'.length)
|
|
@@ -2453,6 +2535,7 @@ function isPrivateNetworkHostname(hostname) {
|
|
|
2453
2535
|
const octets = normalized.split('.').map((part) => Number(part))
|
|
2454
2536
|
if (octets.length === 4 && octets.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)) {
|
|
2455
2537
|
return octets[0] === 10 ||
|
|
2538
|
+
(octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127) ||
|
|
2456
2539
|
(octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) ||
|
|
2457
2540
|
(octets[0] === 192 && octets[1] === 168) ||
|
|
2458
2541
|
(octets[0] === 169 && octets[1] === 254)
|
|
@@ -2798,6 +2881,7 @@ const plugin = {
|
|
|
2798
2881
|
},
|
|
2799
2882
|
})
|
|
2800
2883
|
const clients = new Set()
|
|
2884
|
+
const networkDiagnostics = createNetworkDiagnostics({ clients, devices: () => registry.list() })
|
|
2801
2885
|
const sessionReplay = createSessionReplay()
|
|
2802
2886
|
const pluginInstallOwners = new Map()
|
|
2803
2887
|
const pendingQuestions = new Map()
|
|
@@ -2852,6 +2936,9 @@ const plugin = {
|
|
|
2852
2936
|
...(publicUrl ? [publicUrl] : []),
|
|
2853
2937
|
...(tunnel?.snapshot().publicUrl ? [tunnel.snapshot().publicUrl] : []),
|
|
2854
2938
|
...(lanListening ? lanWebSocketUrls(options, wsPath, lanBoundPort) : []),
|
|
2939
|
+
// Tailscale 直连地址与局域网同等作为候选:手机在同一 tailnet 时可直连,
|
|
2940
|
+
// 不在 tailnet 的客户端会自然失败并回退到其他候选。
|
|
2941
|
+
...(lanListening ? tailscaleInterfaceStatus({ listening: true, host: options.lanHost, port: lanBoundPort, wsPath }).urls : []),
|
|
2855
2942
|
])])
|
|
2856
2943
|
}
|
|
2857
2944
|
|
|
@@ -3280,6 +3367,9 @@ const plugin = {
|
|
|
3280
3367
|
: tunnel?.snapshot().publicUrl || configuredPublicUrl() || null,
|
|
3281
3368
|
platform: process.platform,
|
|
3282
3369
|
cloudflare: tunnel?.snapshot() || null,
|
|
3370
|
+
// 本机 Tailscale 接口地址(100.64/10 或 fd7a:115c:a1e0::/48)。
|
|
3371
|
+
// 只用于面板展示与可选配对地址;检测到接口不等于已登录 tailnet。
|
|
3372
|
+
tailscale: tailscaleInterfaceStatus({ listening: lanListening, host: options.lanHost, port: lanBoundPort, wsPath }),
|
|
3283
3373
|
lan: {
|
|
3284
3374
|
enabled: options.lanEnabled === true,
|
|
3285
3375
|
listening: lanListening,
|
|
@@ -3353,6 +3443,14 @@ const plugin = {
|
|
|
3353
3443
|
if (body.mode === undefined && typeof body.enabled !== 'boolean') throw badRequest('mode or boolean enabled is required')
|
|
3354
3444
|
setGatewayMode(body.mode !== undefined ? body.mode : (body.enabled ? 'temporary' : 'disabled'), 'changed from management UI')
|
|
3355
3445
|
sendJson(res, 200, { gatewayEnabled, gatewayMode, waitExpiresAt, connectedClients: clients.size })
|
|
3446
|
+
} else if (req.method === 'POST' && p === '/mgw/network-test') {
|
|
3447
|
+
const abort = new AbortController()
|
|
3448
|
+
const cancel = () => abort.abort()
|
|
3449
|
+
res.once('close', cancel)
|
|
3450
|
+
try {
|
|
3451
|
+
const result = await networkDiagnostics.measure({ signal: abort.signal })
|
|
3452
|
+
if (!abort.signal.aborted) sendJson(res, 200, result)
|
|
3453
|
+
} finally { res.off('close', cancel) }
|
|
3356
3454
|
} else if (req.method === 'POST' && p === '/mgw/cloudflare') {
|
|
3357
3455
|
const body = await readBody(req)
|
|
3358
3456
|
await tunnel.configure(body)
|
|
@@ -3415,26 +3513,59 @@ const plugin = {
|
|
|
3415
3513
|
throw error
|
|
3416
3514
|
}
|
|
3417
3515
|
const body = await readBody(req)
|
|
3418
|
-
const clientRoute = ['auto', 'lan', 'cloudflare', 'custom'].includes(body.route) ? body.route : null
|
|
3516
|
+
const clientRoute = ['auto', 'lan', 'cloudflare', 'custom', 'tailscale'].includes(body.route) ? body.route : null
|
|
3419
3517
|
const cloudflareStatus = tunnel?.snapshot() || null
|
|
3420
3518
|
const configuredUrl = configuredPublicUrl()
|
|
3421
3519
|
const autoUrl = cloudflareStatus?.enabled && cloudflareStatus.publicReady === true
|
|
3422
3520
|
? cloudflareStatus.publicUrl
|
|
3423
3521
|
: cloudflareStatus?.enabled && cloudflareStatus.publicUrl === configuredUrl && cloudflareStatus.publicReady !== true
|
|
3424
3522
|
? '' : configuredUrl
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3523
|
+
// Tailscale 专用路线:只接受 ws:// + Tailscale IP。未显式给出地址时使用
|
|
3524
|
+
// 本机探测到的第一个地址;探测不到时明确报错,而不是退化成其他路线。
|
|
3525
|
+
const tailscaleUrls = lanListening
|
|
3526
|
+
? tailscaleInterfaceStatus({ listening: true, host: options.lanHost, port: lanBoundPort, wsPath }).urls
|
|
3527
|
+
: []
|
|
3528
|
+
const requestedTailscaleUrl = clientRoute === 'tailscale'
|
|
3529
|
+
? (() => {
|
|
3530
|
+
if (!lanListening) {
|
|
3531
|
+
const error = new Error('enable the LAN listener before generating a Tailscale pairing code')
|
|
3532
|
+
error.status = 409
|
|
3533
|
+
throw error
|
|
3534
|
+
}
|
|
3535
|
+
const candidate = typeof body.publicUrl === 'string' && body.publicUrl.trim()
|
|
3536
|
+
? normalizePublicUrl(body.publicUrl.trim(), req, wsPath)
|
|
3537
|
+
: tailscaleUrls[0] || ''
|
|
3538
|
+
if (!candidate) {
|
|
3539
|
+
const error = new Error('no Tailscale address detected; connect this host to a tailnet and keep the LAN listener enabled')
|
|
3540
|
+
error.status = 409
|
|
3541
|
+
throw error
|
|
3542
|
+
}
|
|
3543
|
+
const parsed = new URL(candidate)
|
|
3544
|
+
if (parsed.protocol !== 'ws:' || !isTailscaleIp(parsed.hostname.replace(/^\[|\]$/g, ''))) {
|
|
3545
|
+
const error = new Error('Tailscale pairing requires a ws:// Tailscale IP address')
|
|
3546
|
+
error.status = 409
|
|
3547
|
+
throw error
|
|
3548
|
+
}
|
|
3549
|
+
return parsed.toString()
|
|
3550
|
+
})()
|
|
3551
|
+
: ''
|
|
3552
|
+
const publicUrl = clientRoute === 'tailscale'
|
|
3553
|
+
? requestedTailscaleUrl
|
|
3554
|
+
: clientRoute === 'auto'
|
|
3555
|
+
? (autoUrl ? normalizePublicUrl(autoUrl, req, wsPath) : '')
|
|
3556
|
+
: normalizePublicUrl(body.publicUrl || configuredUrl, req, wsPath)
|
|
3428
3557
|
if (clientRoute) {
|
|
3429
3558
|
const discoveredLan = lanListening
|
|
3430
3559
|
? lanWebSocketUrls(options, wsPath, lanBoundPort).find(isRoutablePrivateEndpoint)
|
|
3431
3560
|
: ''
|
|
3432
3561
|
const configuredLan = configuredEndpoints.find(isRoutablePrivateEndpoint) || ''
|
|
3433
|
-
const appUrl =
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3562
|
+
const appUrl = clientRoute === 'tailscale'
|
|
3563
|
+
? requestedTailscaleUrl
|
|
3564
|
+
: normalizePublicUrl(
|
|
3565
|
+
body.lanUrl || body.appUrl || discoveredLan || configuredLan || (isRoutablePrivateEndpoint(publicUrl) ? publicUrl : ''),
|
|
3566
|
+
req,
|
|
3567
|
+
wsPath,
|
|
3568
|
+
)
|
|
3438
3569
|
if (!isRoutablePrivateEndpoint(appUrl)) {
|
|
3439
3570
|
const error = new Error('enable or configure a reachable LAN WebSocket address before generating a multi-client QR code')
|
|
3440
3571
|
error.status = 409
|
|
@@ -3449,26 +3580,37 @@ const plugin = {
|
|
|
3449
3580
|
error.status = 409
|
|
3450
3581
|
throw error
|
|
3451
3582
|
}
|
|
3452
|
-
const lanEndpoints =
|
|
3453
|
-
.
|
|
3583
|
+
const lanEndpoints = clientRoute === 'tailscale'
|
|
3584
|
+
? [...new Set([appUrl, ...tailscaleUrls.map((url) => normalizePublicUrl(url, req, wsPath))])]
|
|
3585
|
+
.filter((url) => {
|
|
3586
|
+
try {
|
|
3587
|
+
const parsed = new URL(url)
|
|
3588
|
+
return parsed.protocol === 'ws:' && isTailscaleIp(parsed.hostname.replace(/^\[|\]$/g, ''))
|
|
3589
|
+
} catch { return false }
|
|
3590
|
+
})
|
|
3591
|
+
.slice(0, 16)
|
|
3592
|
+
: advertisedEndpoints(appUrl).filter(isRoutablePrivateEndpoint)
|
|
3454
3593
|
const appEndpoints = [...new Set([
|
|
3455
|
-
...(clientRoute !== 'lan' && hasPublicRoute ? [publicUrl] : []),
|
|
3594
|
+
...(clientRoute !== 'lan' && clientRoute !== 'tailscale' && hasPublicRoute ? [publicUrl] : []),
|
|
3456
3595
|
...lanEndpoints,
|
|
3457
3596
|
])].slice(0, 16)
|
|
3458
3597
|
// 全网络自动选路路由表:客户端按自身能力从 lan/public/relay 中挑选,
|
|
3459
3598
|
// 一个二维码同时覆盖外网与局域网(契约见 dsh-weapp/docs/auto-route-selection.md)。
|
|
3460
|
-
// route=lan
|
|
3461
|
-
|
|
3462
|
-
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3599
|
+
// route=lan / route=tailscale 是运营者明确选择的单一线路:不泄露公网、
|
|
3600
|
+
// 中继或其他局域网地址。
|
|
3601
|
+
const routeTable = clientRoute === 'lan' ? null
|
|
3602
|
+
: clientRoute === 'tailscale' ? { lan: lanEndpoints }
|
|
3603
|
+
: {
|
|
3604
|
+
lan: lanEndpoints,
|
|
3605
|
+
public: hasPublicRoute ? [publicUrl] : [],
|
|
3606
|
+
...(relayState.relay ? { relay: {
|
|
3607
|
+
relay: relayState.relay.relay,
|
|
3608
|
+
nodeId: relayState.relay.nodeId,
|
|
3609
|
+
agentPubKey: relayState.relay.agentPubKey,
|
|
3610
|
+
gatewayName: relayState.relay.gatewayName,
|
|
3611
|
+
authMode: 'gateway'
|
|
3612
|
+
} } : {})
|
|
3613
|
+
}
|
|
3472
3614
|
const primaryUrl = appEndpoints[0] || appUrl
|
|
3473
3615
|
let miniProgramRoute = null
|
|
3474
3616
|
if (clientRoute !== 'lan' && hasPublicRoute) {
|
|
@@ -3613,8 +3755,8 @@ const plugin = {
|
|
|
3613
3755
|
if (credential && credential.kind === 'pairing') {
|
|
3614
3756
|
const clientDeviceId = extractClientDeviceId(req)
|
|
3615
3757
|
if (!clientDeviceId) {
|
|
3616
|
-
log('pairing rejected: missing
|
|
3617
|
-
rejectUpgrade(socket, 400, 'pairing requires X-DSH-Device-ID
|
|
3758
|
+
log('pairing rejected: missing or invalid stable device ID')
|
|
3759
|
+
rejectUpgrade(socket, 400, 'pairing requires a stable device ID via X-DSH-Device-ID or dsh-device.<id>')
|
|
3618
3760
|
return
|
|
3619
3761
|
}
|
|
3620
3762
|
paired = registry.claimPairing(credential.value, clientDeviceId, extractClientDeviceName(req))
|
|
@@ -3640,6 +3782,7 @@ const plugin = {
|
|
|
3640
3782
|
|
|
3641
3783
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
3642
3784
|
const id = ++counter
|
|
3785
|
+
ws.connectionId = id
|
|
3643
3786
|
ws.filterSessionId = undefined
|
|
3644
3787
|
const requestedChannel = req.headers['x-dsh-channel']
|
|
3645
3788
|
ws.mobileChannel = ['control', 'conversation'].includes(requestedChannel) ? requestedChannel : 'legacy'
|
|
@@ -3805,7 +3948,7 @@ const plugin = {
|
|
|
3805
3948
|
return
|
|
3806
3949
|
}
|
|
3807
3950
|
void fileUploads.handle(ws, msg).then(sendFrame)
|
|
3808
|
-
} else if (msg.type === 'file-list' || msg.type === 'file-download-open' ||
|
|
3951
|
+
} else if (msg.type === 'file-list' || msg.type === 'file-resolve' || msg.type === 'file-download-open' ||
|
|
3809
3952
|
msg.type === 'file-download-read' || msg.type === 'file-download-cancel') {
|
|
3810
3953
|
fileTransfers.handle(ws, msg).then((frame) => {
|
|
3811
3954
|
if (frame && ws.readyState === 1) ws.send(stringifyWireFrame(frame))
|
|
@@ -3897,6 +4040,7 @@ const plugin = {
|
|
|
3897
4040
|
historyFormatVersion: SESSION_FORMAT_VERSION,
|
|
3898
4041
|
capabilities: [
|
|
3899
4042
|
'split-channels',
|
|
4043
|
+
'network-diagnostics-v1',
|
|
3900
4044
|
'assistant-stream-v1',
|
|
3901
4045
|
'session-resume-v1',
|
|
3902
4046
|
'history-format-version',
|
|
@@ -4107,7 +4251,10 @@ const plugin = {
|
|
|
4107
4251
|
|
|
4108
4252
|
const disposeQuestions = ctx.on('user-questions/request', (request, next) => {
|
|
4109
4253
|
const sessionId = request?.agent?.id === undefined ? null : String(request.agent.id)
|
|
4110
|
-
|
|
4254
|
+
// 与审批一致:网关开启时登记所有待答提问,让稍后连接或切换会话的设备也能接收重放。
|
|
4255
|
+
// 是否向某个连接实时广播仍由 broadcastInteractionFrame 的 sessionId 过滤器决定;
|
|
4256
|
+
// startDownstreamQuestion 里保留「没有移动客户端时回退给 WebUI」的语义。
|
|
4257
|
+
if (!sessionId || !Array.isArray(request.questions) || !gatewayEnabled) return next()
|
|
4111
4258
|
const rpcId = crypto.randomUUID()
|
|
4112
4259
|
return new Promise((resolve, reject) => {
|
|
4113
4260
|
const requestSignal = request.signal
|
|
@@ -4139,7 +4286,9 @@ const plugin = {
|
|
|
4139
4286
|
|
|
4140
4287
|
const disposeApprovals = ctx.on('approval/request', (request, next) => {
|
|
4141
4288
|
const sessionId = request?.agent?.id === undefined ? null : String(request.agent.id)
|
|
4142
|
-
|
|
4289
|
+
// 控制连接重连期间仍登记待审批,桌面端继续处理同一个请求;
|
|
4290
|
+
// 若桌面端仍在等待,稍后连接的设备可以重放;无可用答复时保持原有回退行为。
|
|
4291
|
+
if (!sessionId || typeof request.toolName !== 'string' || !gatewayEnabled) return next()
|
|
4143
4292
|
const rpcId = crypto.randomUUID()
|
|
4144
4293
|
const approvalId = crypto.randomUUID()
|
|
4145
4294
|
return new Promise((resolve, reject) => {
|
|
@@ -4170,6 +4319,8 @@ const plugin = {
|
|
|
4170
4319
|
pendingApprovals.set(rpcId, pending)
|
|
4171
4320
|
broadcastInteractionFrame(approvalFrameFor(rpcId, pending))
|
|
4172
4321
|
startDownstreamApproval(pending)
|
|
4322
|
+
// 登记时没有移动客户端:立刻交回 WebUI,避免挂住工具调用。
|
|
4323
|
+
if (!hasInteractionClient(sessionId)) fallbackApproval(pending)
|
|
4173
4324
|
log(`approval requested: rpcId=${rpcId} approvalId=${approvalId} session=${sessionId} tool=${request.toolName}`)
|
|
4174
4325
|
})
|
|
4175
4326
|
}, { prepend: true })
|
|
@@ -4347,6 +4498,7 @@ const plugin = {
|
|
|
4347
4498
|
clearInterval(fileTransferExpiryTimer)
|
|
4348
4499
|
backgroundStreamAbort.abort()
|
|
4349
4500
|
speechInput.dispose()
|
|
4501
|
+
networkDiagnostics.dispose()
|
|
4350
4502
|
// Aborts the host Peer every Remote call speaks for, so 0.2.1 hosts end
|
|
4351
4503
|
// the plugin's streams immediately instead of at Peer GC.
|
|
4352
4504
|
api.dispose()
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// 网关侧网络诊断:向每条已鉴权移动连接发一次 WebSocket ping,量出往返时延。
|
|
2
|
+
//
|
|
3
|
+
// 设计取自上游 mobile-gateway(v0.11.2)的 network-diagnostics,但本仓库的
|
|
4
|
+
// 客户端是原生 ws 对象(没有 transport adapter 抽象),所以这里直接对 ws
|
|
5
|
+
// 发 ping;RTC 统计(rtc-ice)不适用,测量方式固定为 websocket-ping。
|
|
6
|
+
//
|
|
7
|
+
// 仅本机管理接口调用:/mgw/network-test(loopback 由 mgw 路由统一把关),
|
|
8
|
+
// 移动端不主动触发测量,避免被当成探测工具。
|
|
9
|
+
import crypto from 'node:crypto'
|
|
10
|
+
|
|
11
|
+
const MAX_CLIENTS = 256
|
|
12
|
+
const CONCURRENCY = 8
|
|
13
|
+
const SAMPLE_WINDOW_MS = 60_000
|
|
14
|
+
const MAX_SAMPLES = 60
|
|
15
|
+
|
|
16
|
+
export function websocketRtt(socket, { signal, timeoutMs = 3000, now = () => performance.now() } = {}) {
|
|
17
|
+
return new Promise(resolve => {
|
|
18
|
+
if (socket.readyState !== 1 || signal?.aborted) { resolve({ status: 'cancelled', rttMs: null }); return }
|
|
19
|
+
const payload = Buffer.from(`mgw-net:${crypto.randomUUID()}`)
|
|
20
|
+
const started = now()
|
|
21
|
+
let timer, finished = false
|
|
22
|
+
const finish = result => {
|
|
23
|
+
if (finished) return
|
|
24
|
+
finished = true
|
|
25
|
+
clearTimeout(timer)
|
|
26
|
+
socket.off('pong', pong); socket.off('close', closed); socket.off('error', failed)
|
|
27
|
+
signal?.removeEventListener('abort', aborted)
|
|
28
|
+
resolve({ ...result, measurement: 'websocket-ping' })
|
|
29
|
+
}
|
|
30
|
+
const pong = data => { if (Buffer.from(data).equals(payload)) finish({ status: 'ok', rttMs: Math.max(0, now() - started) }) }
|
|
31
|
+
const closed = () => finish({ status: 'disconnected', rttMs: null })
|
|
32
|
+
const failed = () => finish({ status: 'error', rttMs: null })
|
|
33
|
+
const aborted = () => finish({ status: 'cancelled', rttMs: null })
|
|
34
|
+
socket.on('pong', pong); socket.once('close', closed); socket.once('error', failed)
|
|
35
|
+
signal?.addEventListener('abort', aborted, { once: true })
|
|
36
|
+
timer = setTimeout(() => finish({ status: 'timeout', rttMs: null }), timeoutMs)
|
|
37
|
+
try { socket.ping(payload, error => { if (error) failed() }) } catch { failed() }
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function abortable(operation, signal, timeoutMs = 3000) {
|
|
42
|
+
const safe = Promise.resolve(operation).catch(() => ({ status: 'error', rttMs: null }))
|
|
43
|
+
if (signal?.aborted) return { status: 'cancelled', rttMs: null }
|
|
44
|
+
let timer, onAbort
|
|
45
|
+
try {
|
|
46
|
+
return await Promise.race([
|
|
47
|
+
safe,
|
|
48
|
+
new Promise(resolve => {
|
|
49
|
+
onAbort = () => resolve({ status: 'cancelled', rttMs: null })
|
|
50
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
51
|
+
timer = setTimeout(() => resolve({ status: 'timeout', rttMs: null }), timeoutMs)
|
|
52
|
+
}),
|
|
53
|
+
])
|
|
54
|
+
} finally { clearTimeout(timer); signal?.removeEventListener('abort', onAbort) }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createNetworkDiagnostics({ clients, devices, now = () => Date.now() }) {
|
|
58
|
+
let busy = false, disposed = false, last = null, activeAbort
|
|
59
|
+
// ws -> [{ at, rttMs }];连接关闭后随对象回收,下一次清理时一并删掉。
|
|
60
|
+
const histories = new WeakMap()
|
|
61
|
+
return {
|
|
62
|
+
async measure({ signal } = {}) {
|
|
63
|
+
if (disposed) throw new Error('network diagnostics disposed')
|
|
64
|
+
if (busy) throw Object.assign(new Error('network diagnostics busy'), { status: 409 })
|
|
65
|
+
if (signal?.aborted) return { at: now(), devices: [] }
|
|
66
|
+
// 1 秒内重复点击复用上一次结果,避免管理面板连点打满 ping。
|
|
67
|
+
if (last && now() - last.at < 1000) return last
|
|
68
|
+
busy = true
|
|
69
|
+
const abort = new AbortController()
|
|
70
|
+
activeAbort = abort
|
|
71
|
+
const cancel = () => abort.abort()
|
|
72
|
+
signal?.addEventListener('abort', cancel, { once: true })
|
|
73
|
+
try {
|
|
74
|
+
const connections = [...clients].filter(client => client.readyState === 1 && client.deviceId).slice(0, MAX_CLIENTS)
|
|
75
|
+
const known = new Map(devices().map(device => [device.id, device]))
|
|
76
|
+
const rows = new Array(connections.length)
|
|
77
|
+
let index = 0
|
|
78
|
+
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, connections.length) }, async () => {
|
|
79
|
+
while (!abort.signal.aborted) {
|
|
80
|
+
const current = index++
|
|
81
|
+
if (current >= connections.length) break
|
|
82
|
+
const client = connections[current]
|
|
83
|
+
let result
|
|
84
|
+
try { result = await abortable(websocketRtt(client, { signal: abort.signal }), abort.signal) }
|
|
85
|
+
catch { result = { status: 'error', rttMs: null } }
|
|
86
|
+
if (!result || typeof result !== 'object') result = { status: 'unavailable', rttMs: null }
|
|
87
|
+
if (client.readyState !== 1 || !clients.has(client)) result = { status: 'disconnected', rttMs: null }
|
|
88
|
+
if (result.status !== 'ok' || !Number.isFinite(result.rttMs) || result.rttMs < 0) result.rttMs = null
|
|
89
|
+
const history = histories.get(client) || []
|
|
90
|
+
if (!abort.signal.aborted && result.status !== 'cancelled') {
|
|
91
|
+
history.push({ at: now(), rttMs: result.rttMs })
|
|
92
|
+
while (history.length && (history.length > MAX_SAMPLES || now() - history[0].at > SAMPLE_WINDOW_MS)) history.shift()
|
|
93
|
+
histories.set(client, history)
|
|
94
|
+
}
|
|
95
|
+
const rtts = history.map(item => item.rttMs).filter(Number.isFinite).sort((a, b) => a - b)
|
|
96
|
+
rows[current] = {
|
|
97
|
+
deviceId: client.deviceId,
|
|
98
|
+
name: known.get(client.deviceId)?.displayName || known.get(client.deviceId)?.name || '',
|
|
99
|
+
connectionId: client.connectionId ?? null,
|
|
100
|
+
channel: client.mobileChannel,
|
|
101
|
+
transport: 'websocket',
|
|
102
|
+
...result,
|
|
103
|
+
samples: history.map(({ at, rttMs }) => ({ at, rttMs })),
|
|
104
|
+
p95RttMs: rtts.length ? rtts[Math.ceil(rtts.length * .95) - 1] : null,
|
|
105
|
+
averageRttMs: rtts.length ? rtts.reduce((a, b) => a + b, 0) / rtts.length : null,
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}))
|
|
109
|
+
const grouped = new Map()
|
|
110
|
+
for (const row of rows.filter(Boolean)) {
|
|
111
|
+
if (!grouped.has(row.deviceId)) grouped.set(row.deviceId, { deviceId: row.deviceId, name: row.name, channels: [] })
|
|
112
|
+
const { deviceId, name, ...channel } = row
|
|
113
|
+
grouped.get(deviceId).channels.push(channel)
|
|
114
|
+
}
|
|
115
|
+
const snapshot = {
|
|
116
|
+
at: now(),
|
|
117
|
+
devices: [...grouped.values()],
|
|
118
|
+
truncated: [...clients].filter(client => client.readyState === 1 && client.deviceId).length > connections.length,
|
|
119
|
+
}
|
|
120
|
+
if (!abort.signal.aborted) last = snapshot
|
|
121
|
+
return snapshot
|
|
122
|
+
} finally { signal?.removeEventListener('abort', cancel); activeAbort = null; busy = false }
|
|
123
|
+
},
|
|
124
|
+
dispose() { disposed = true; activeAbort?.abort(); last = null },
|
|
125
|
+
}
|
|
126
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// 移动端事件详情:在裁剪 token 级回放与工具正文后保留诊断事实。
|
|
2
|
+
// 取自上游 mobile-gateway(v0.11.2)的 session-event-details,字段全部为增量:
|
|
3
|
+
// - assistant/message、assistant/attempt: finish(结束原因与失败摘要)
|
|
4
|
+
// - tool/result: output/outputTruncated(16KB 摘要,保留首尾)
|
|
5
|
+
// - llm/retry: failure 摘要
|
|
6
|
+
// - turn/end: reasonDetails(本仓库仍保留原有的 reason 对象形态,mini-program 兼容)
|
|
7
|
+
|
|
8
|
+
const TOOL_OUTPUT_LIMIT = 16_000
|
|
9
|
+
|
|
10
|
+
export function failureDetails(value) {
|
|
11
|
+
if (!value || typeof value !== 'object') return undefined
|
|
12
|
+
const result = {}
|
|
13
|
+
for (const key of ['message', 'code', 'name', 'reason', 'requestId']) {
|
|
14
|
+
if (typeof value[key] === 'string') result[key] = value[key]
|
|
15
|
+
}
|
|
16
|
+
for (const key of ['status', 'providerRetryAfterMs']) {
|
|
17
|
+
if (Number.isFinite(value[key])) result[key] = value[key]
|
|
18
|
+
}
|
|
19
|
+
return Object.keys(result).length ? result : undefined
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function assistantFinish(data) {
|
|
23
|
+
for (let i = (data.stream?.length || 0) - 1; i >= 0; i--) {
|
|
24
|
+
const record = data.stream[i]
|
|
25
|
+
if (record?.type !== 'chunk' || record.chunk?.type !== 'finish') continue
|
|
26
|
+
const reason = record.chunk.reason
|
|
27
|
+
if (typeof reason?.kind !== 'string') return undefined
|
|
28
|
+
const failure = failureDetails(reason.failure ?? reason.error)
|
|
29
|
+
return { kind: reason.kind, ...(failure ? { failure } : {}) }
|
|
30
|
+
}
|
|
31
|
+
return data.finish
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function toolResultDetails(data) {
|
|
35
|
+
const texts = []
|
|
36
|
+
const visit = (block) => {
|
|
37
|
+
if (block?.type === 'text' && typeof block.text === 'string') texts.push(block.text)
|
|
38
|
+
else if (block?.type === 'tool-result' && Array.isArray(block.content)) block.content.forEach(visit)
|
|
39
|
+
}
|
|
40
|
+
for (const block of data.message?.content || []) visit(block)
|
|
41
|
+
const full = texts.join('')
|
|
42
|
+
const outputTruncated = full.length > TOOL_OUTPUT_LIMIT
|
|
43
|
+
// Retain the terminal status and sandbox hints at the end as well as the start.
|
|
44
|
+
const output = outputTruncated
|
|
45
|
+
? `${full.slice(0, TOOL_OUTPUT_LIMIT / 2)}\n[…]\n${full.slice(-TOOL_OUTPUT_LIMIT / 2)}`
|
|
46
|
+
: full
|
|
47
|
+
return { output, outputTruncated }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function turnReasonDetails(reason) {
|
|
51
|
+
if (!reason || typeof reason.kind !== 'string') return undefined
|
|
52
|
+
const error = failureDetails(reason.error ?? reason.failure)
|
|
53
|
+
return { kind: reason.kind, ...(error ? { error } : {}),
|
|
54
|
+
...(typeof reason.reason?.kind === 'string' ? { reason: {
|
|
55
|
+
kind: reason.reason.kind,
|
|
56
|
+
...(typeof reason.reason.reason === 'string' ? { reason: reason.reason.reason } : {}),
|
|
57
|
+
} } : {}),
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Tailscale 地址识别:100.64.0.0/10(CGNAT,Tailscale 使用其中 100.64–100.127)
|
|
2
|
+
// 与 fd7a:115c:a1e0::/48(Tailscale IPv6)。
|
|
3
|
+
//
|
|
4
|
+
// 只检查本网关进程所在网络命名空间的接口,绝不推断手机 IP;检测到接口地址
|
|
5
|
+
// 也不等于已登录 tailnet 或手机可达。取自上游 mobile-gateway(v0.11.2)。
|
|
6
|
+
import os from 'node:os'
|
|
7
|
+
import { isIP } from 'node:net'
|
|
8
|
+
|
|
9
|
+
export function isTailscaleIp(value) {
|
|
10
|
+
if (typeof value !== 'string') return false
|
|
11
|
+
const address = value.replace(/^\[|\]$/g, '').toLowerCase()
|
|
12
|
+
if (isIP(address) === 4) {
|
|
13
|
+
const parts = address.split('.').map(Number)
|
|
14
|
+
return parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127
|
|
15
|
+
}
|
|
16
|
+
return isIP(address) === 6 && address.startsWith('fd7a:115c:a1e0:')
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// 只读取本机接口;返回 Tailscale 地址列表与可用(已监听且绑定地址匹配)的 WS URL。
|
|
20
|
+
export function tailscaleInterfaceStatus({ listening, host, port, wsPath }, interfaces = os.networkInterfaces()) {
|
|
21
|
+
const addresses = []
|
|
22
|
+
for (const [name, records] of Object.entries(interfaces)) {
|
|
23
|
+
const entries = (records || []).filter((record) => record && !record.internal)
|
|
24
|
+
const knownInterface = /^(tailscale|utun|tun\d)/i.test(name)
|
|
25
|
+
|| entries.some((record) => isIP(record.address) === 6 && isTailscaleIp(record.address))
|
|
26
|
+
if (!knownInterface) continue
|
|
27
|
+
for (const record of entries) {
|
|
28
|
+
if (isTailscaleIp(record.address) && !addresses.includes(record.address)) addresses.push(record.address)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
addresses.sort((a, b) => isIP(a) - isIP(b))
|
|
32
|
+
const boundHost = (host || '').replace(/^\[|\]$/g, '')
|
|
33
|
+
const urls = listening ? addresses.filter((address) =>
|
|
34
|
+
boundHost === '::' || boundHost === address || (boundHost === '0.0.0.0' && isIP(address) === 4))
|
|
35
|
+
.map((address) => `ws://${isIP(address) === 6 ? `[${address}]` : address}:${port}${wsPath}`) : []
|
|
36
|
+
return { addresses, urls }
|
|
37
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-weapp-gateway",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.41",
|
|
4
4
|
"description": "鲸尾网关助手:DeepSeek Harness 移动客户端连接与会话同步,支持安全配对、远程访问、上下文、编队、额度和语音输入",
|
|
5
5
|
"main": "lib/index.mjs",
|
|
6
6
|
"files": [
|
|
@@ -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/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"
|
|
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 test/question-replay.test.mjs && node --test test/network-diagnostics.test.mjs && node --test test/tailscale-addresses.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",
|
package/relay/agent-connector.js
CHANGED
|
@@ -192,11 +192,24 @@ class AgentSession {
|
|
|
192
192
|
}
|
|
193
193
|
|
|
194
194
|
open(packet) {
|
|
195
|
-
|
|
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
|
-
|
|
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)
|
|
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
|
-
|
|
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', () => {
|