dsh-connect-workbuddy 5.19.1 → 5.20.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,75 @@
1
1
  # Changelog
2
2
 
3
+ ## 5.20.0 (2026-11-06)
4
+
5
+ > **新增一项设置,默认行为一个字节都没变。** 没有破坏性变更;不填就跟以前完全一样。
6
+
7
+ ### 新增:CN 网关主机可配置(issue #220)
8
+
9
+ 企业网络按 **TLS ClientHello 的 SNI** 做黑名单时,CN 网关 `copilot.tencent.com` 会被即时 RST
10
+ (`ECONNRESET`,<100ms),而同一台机器上的 WorkBuddy 桌面客户端**正常**——因为客户端读自己
11
+ `failover.json` 的 `trustedOrigins`,里面还有 `wb.tencentbuddy.com`。插件原先把这个主机**写死**,
12
+ 于是在那种网络里完全不可用,且看起来像插件自己坏了。
13
+
14
+ 现在「能力」栏可以填一个 CN 网关主机;留空即内置。**chat、模型目录、busy 探测、生图/生视频、
15
+ 签到、积分、领取权益**全部跟着走——只修 chat 的半个修复比不修更糟:用户会以为换号成功,
16
+ 而签到和积分仍然打在被拦的主机上。
17
+
18
+ **实测(2026-11-06,本机)**:九条 CN 路由在 `wb.tencentbuddy.com` 与 `copilot.tencent.com`
19
+ 上**状态码逐条相同**;`/v3/config` 的 252 字节信封在四个 CN 主机上逐个相同。详见
20
+ [`docs/CN_GATEWAY_FALLBACK.md`](docs/CN_GATEWAY_FALLBACK.md)。
21
+
22
+ ### 安全:允许清单,而不是「任意 URL」
23
+
24
+ 这个 base 会被拼在每一条带 `Authorization: Bearer <token>` 的请求前面,也包括 refresh token 交换。
25
+ **一个自由的 base 就是一枚凭据外泄原语**:能改设置的人(同步的 profile、共享 dotfile、论坛抄来的
26
+ 「修复」)就能把活 token 重定向到自己的主机,而且请求照样成功、看不出坏了。
27
+
28
+ 所以值必须是 **https**,且主机属于四个 CN 品牌的可注册域之一:`copilot.tencent.com`、
29
+ `tencentbuddy.com`、`workbuddy.cn`、`codebuddy.cn`(按可注册域匹配,子域放行,
30
+ `tencentbuddy.com.evil.example` 这类近似域拒绝)。路径 / 查询 / 锚点 / userinfo 一律丢弃。
31
+
32
+ **不改的东西**:`Origin` / `Referer` 仍然自称 CN 网页端(它们回答的是「来自哪个网页应用」,
33
+ 与连到哪台主机无关);**国际版完全不受影响**——全球 token 按品牌绑定,没有「换一个同构主机」
34
+ 这回事,所以该控件在国际版 tab 上连渲染都不渲染。
35
+
36
+ ### 三处细节,都是「看起来能用、其实是错的」那类
37
+
38
+ - **每次请求现读,不是构造期采样。** `regions` 是 volatile 字段,保存后不重启插件;
39
+ 构造期采样会让「填了没反应」——而那是本设置唯一的用途。
40
+ - **非法值拒绝保存,并按具体规则说明**(不是完整 URL / 必须 https / 不是 CN 品牌)。
41
+ 三种规则需要三种不同修法,一句「无效」等于没说。
42
+ - **诊断栏报告解析后生效的值,不是保存的原文。** 保存了但校验失败的值仍然走内置网关,
43
+ 回显原文会告诉用户「已生效」,而每个请求都去了别处。
44
+
45
+ Host 侧对配置里的坏值**退回内置网关并 warn 一次**(同一个值只警告一次——这条路径在每次请求上,
46
+ 不能把一次误配置变成每个请求一条日志)。
47
+
48
+ ### 新增:`doctor` 也能看到覆盖(`WORKBUDDY_CN_BASE`)
49
+
50
+ `doctor` 跑在自己的进程里,**从不加载插件设置**——所以卡片上填的值它看不见。没有这条通道,
51
+ 用户修好网络后跑 `doctor`,拿到的报告是**对着他那张网络会重置的网关**测的:一个谎报
52
+ 「我探了哪台主机」的诊断工具比没有更糟。这与 `WORKBUDDY_DEVICE_TOKEN_FILE` 是同一个原因、
53
+ 同一个模式,且两者都走同一个 `resolveCnGateway`,校验规则不可能分叉。
54
+
55
+ ### Tests
56
+
57
+ `3169/3169`(3119 → 3169),`skip 2`。新增三个文件 / 一节:
58
+
59
+ - `tests/cn-gateway.spec.ts`(22 条):允许清单与三类拒绝理由。吃重的是**近似域**用例——
60
+ `tencentbuddy.com.evil.example` 必须被拒,而那正是手写 `endsWith` 会放过的形状。
61
+ - `tests/cn-gateway-routes.spec.ts`(12 条):覆盖真的到达**每一条**路由(积分 / 签到读 /
62
+ 签到写 / 目录 / busy)、**每次请求现读**、`Origin`/`Referer` 不变、**国际凭据绝不走 CN 覆盖**、
63
+ token 不在 URL 里、以及不填时与 #220 之前逐字节相同。
64
+ - `tests/cn-base-card.spec.tsx`(11 条):草稿不随输入写盘、非法值零写入、三种拒绝各自措辞、
65
+ 清空即回到内置、国际版 tab 上控件不存在、诊断栏报告**解析后**的值。
66
+ - `tests/region.spec.ts` +5:`cnBase` 与同槽的模型目录/池偏好互不干扰、空串是显式值不是删除、坏值读成空而不抛。
67
+
68
+ **变异验证**:把允许清单改成 `includes()`(2 条失败)、把卡片改成接受非法值(8 条失败)、
69
+ 把 `billingBase` 的区域判断挪到覆盖判断之后(1 条失败——这条变异正是为它写的,
70
+ 其余用例在它下面全绿)。
71
+
72
+
3
73
  ## 5.19.1 (2026-11-06)
4
74
 
5
75
  > 纯显示修复 + 一份新的测量工装,不改任何行为、设置字段与路由。**没有破坏性变更。**
package/README.en.md CHANGED
@@ -93,6 +93,17 @@ Credentials are read (read-only) from the WorkBuddy desktop app's own auth file.
93
93
 
94
94
  **Encrypted credential fields**: newer desktop builds (Windows first) replace the auth file's `accessToken` / `refreshToken` strings with an AES-256-GCM envelope (`{"$wbEncrypted":1,"envelope":"…"}`), and the account's **display name (`nickname`) is encrypted the same way** — left unopened it degrades to a bare uin number. The envelope is sealed with a field key **compiled into the app itself**, not a user secret — so the plugin ships no key copy. When it meets an encrypted document it runs the installed app with `ELECTRON_RUN_AS_NODE` and calls that app's own native binding (`electron_browser_workbuddy_storage.loggerGet()`) to fetch the same payload and derive the key locally: it asks the very build that wrote the file. The key is cached in process memory only — never on disk, never in logs. Plain-string documents (macOS, older Windows builds) take the original path and never spawn a child process. `account.phoneNumber` is encrypted there too, and the plugin deliberately **neither reads nor displays it**. If the app lives somewhere unusual, point `WORKBUDDY_APP_EXECUTABLE` at its executable.
95
95
 
96
+ ## Every model times out on a corporate network?
97
+
98
+ If **every** model times out while the WorkBuddy desktop app works fine on the same machine, the likely cause is a gateway blocked by **TLS SNI**: `copilot.tencent.com` is reset before any HTTP is sent (fails in milliseconds), while the app itself also uses `wb.tencentbuddy.com`.
99
+
100
+ Open **Settings → WorkBuddy → Capabilities** and set **CN gateway host** to `https://wb.tencentbuddy.com`. Leave it empty for the built-in gateway. **Chat, the model catalog, check-in, credits and image generation all follow it** — a chat-only fix is worse than none.
101
+
102
+ Only **https** is accepted, on a subdomain of `copilot.tencent.com`, `tencentbuddy.com`, `workbuddy.cn` or `codebuddy.cn`. That is not pedantry: the value is prefixed onto every request carrying `Authorization: Bearer`, so accepting an arbitrary URL would mean accepting an arbitrary destination for your token. **The international region is unaffected** — its tokens are brand-bound, and a different host only ever 401s. Measurements and design notes: [`docs/CN_GATEWAY_FALLBACK.md`](docs/CN_GATEWAY_FALLBACK.md).
103
+
104
+ > `doctor` runs in its own process and cannot see plugin settings, so that path uses an environment variable: `WORKBUDDY_CN_BASE=https://wb.tencentbuddy.com dsh plugin --profile desktop exec dsh-connect-workbuddy doctor`
105
+
106
+
96
107
  ## Account pool
97
108
 
98
109
  <p align="center">
@@ -194,7 +205,7 @@ One class of state in the pool **does not go through a draft**: probe results, c
194
205
  >
195
206
  > ⚠️ **Do not treat the marketplace's "latest" as the schedule — it reads an index that lags.** The community marketplace serves a periodically built snapshot, collected per package: at the 2026-10-30 15:00 observation this plugin still listed only 5.13.1 while npm `latest` was already 5.14.1, and a desktop host separately flags any release under 24 hours old as "waiting". Trust `npm view dsh-connect-workbuddy version` and [Releases](https://github.com/dingminhua/dsh-connect-workbuddy/releases), and follow [Update](#update) below (pin the **exact version**); or hand [`docs/PINNED-UPGRADE-LAG.md`](docs/PINNED-UPGRADE-LAG.md) §3 to an AI and let it run.
196
207
  >
197
- > The other thing that stops people from upgrading: **pnpm's 24-hour release-age window** (`minimumReleaseAge`) **silently resolves a floating range back to the previous version**. When you need this fixed right now, pin the **exact version**: `dsh-connect-workbuddy@5.19.0`.
208
+ > The other thing that stops people from upgrading: **pnpm's 24-hour release-age window** (`minimumReleaseAge`) **silently resolves a floating range back to the previous version**. When you need this fixed right now, pin the **exact version**: `dsh-connect-workbuddy@5.19.1`.
198
209
 
199
210
  ### Supported host range
200
211
 
@@ -258,7 +269,7 @@ Once installed, the configuration lives in the **WorkBuddy page of the Settings
258
269
  > | exact `5.14.1` + `minimumReleaseAgeExclude: [dsh-connect-workbuddy]` in the profile's `pnpm-workspace.yaml` | **5.14.1** ✅ |
259
270
  > | setting absent (pnpm default) | floating `^5.13.1` → **5.14.1** ✅ |
260
271
  >
261
- > To pick up a new release right away, pin it: `dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.0`; if the window refuses it, see [`docs/PINNED-UPGRADE-LAG.md`](docs/PINNED-UPGRADE-LAG.md) §2 for the two routes (wait out the window, or add that exclude line). A floating range catches up once the window elapses.
272
+ > To pick up a new release right away, pin it: `dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.1`; if the window refuses it, see [`docs/PINNED-UPGRADE-LAG.md`](docs/PINNED-UPGRADE-LAG.md) §2 for the two routes (wait out the window, or add that exclude line). A floating range catches up once the window elapses.
262
273
 
263
274
  The plugin also runs under **Web** and **TUI**; pick the command matching your profile:
264
275
 
@@ -275,7 +286,7 @@ dsh plugin --profile dsh-tui add dsh-connect-workbuddy # TUI
275
286
  **Manual update (one command)**:
276
287
 
277
288
  ```sh
278
- dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.0
289
+ dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.1
279
290
  dsh plugin --profile desktop exec dsh-connect-workbuddy doctor # first line carries the version
280
291
  ```
281
292
 
package/README.md CHANGED
@@ -103,6 +103,24 @@ DSH PiAiAdapter(每个 provider 一套)
103
103
 
104
104
  **加密凭据字段**:新版桌面端(Windows 先行)把 auth 文件里的 `accessToken` / `refreshToken` 从纯字符串改为 `{"$wbEncrypted":1,"envelope":"…"}` 的 AES-256-GCM 信封,**账号昵称 `nickname` 同样被加密**(不解密就会退回成一串 uin 数字)。信封用的是 App **自身构建期内置**的字段密钥,并非用户密钥,因此插件不内置任何密钥副本,而是在需要时用 `ELECTRON_RUN_AS_NODE` 调用已安装 App 的原生绑定(`electron_browser_workbuddy_storage.loggerGet()`)取回同一份载荷并就地派生密钥——也就是「向写下这个文件的那个构建本身询问」。密钥只在本进程内存中缓存,不落盘、不进日志;纯字符串文件(macOS 与旧版 Windows)走原路径,一次子进程都不会启动。其中的 `account.phoneNumber` 虽同样加密,插件**不读取也不显示**。若 App 安装在非常规位置,用 `WORKBUDDY_APP_EXECUTABLE` 指定其可执行文件。
105
105
 
106
+ ## 公司网络连不上 CN 网关?
107
+
108
+ 如果插件在某个网络里**全部模型都超时**,而同一台机器上的 WorkBuddy 桌面客户端**正常**,那多半是网关按
109
+ **TLS SNI** 被拦了:`copilot.tencent.com` 会被即时重置(连接在毫秒级就失败),但客户端自己还有一条
110
+ 备选主机 `wb.tencentbuddy.com`。
111
+
112
+ 在**设置 → WorkBuddy → 能力**栏的「CN 网关主机」里填 `https://wb.tencentbuddy.com` 并保存即可,
113
+ 留空则回到内置网关。**chat、模型目录、签到、积分、生图都会跟着走**——只改 chat 的半个修复比不改更糟。
114
+
115
+ 这条设置只接受 **https**,且主机必须是 `copilot.tencent.com` / `tencentbuddy.com` / `workbuddy.cn` /
116
+ `codebuddy.cn` 之一下的子域。这不是为了刁难:这个值会被拼在每一条带 `Authorization: Bearer` 的请求前面,
117
+ 允许任意 URL 就等于允许把 token 转发到任意主机。**国际版不受影响**——全球 token 按品牌绑定,
118
+ 换主机只会 401。技术细节与实测数据见 [`docs/CN_GATEWAY_FALLBACK.md`](docs/CN_GATEWAY_FALLBACK.md)。
119
+
120
+ > `doctor` 跑在独立进程里、读不到插件设置,所以那条路上用环境变量:
121
+ > `WORKBUDDY_CN_BASE=https://wb.tencentbuddy.com dsh plugin --profile desktop exec dsh-connect-workbuddy doctor`
122
+
123
+
106
124
  ## 账号池
107
125
 
108
126
  <p align="center">
@@ -205,7 +223,7 @@ DSH PiAiAdapter(每个 provider 一套)
205
223
  >
206
224
  > ⚠️ **别把插件市场里那个「最新」当日程表——它读的是一份会落后的索引。** 社区市场走定期构建的快照(按包各自收录),2026-10-30 15:00 那次观测里本插件还停在 5.13.1,而当时 npm `latest` 已是 5.14.1;桌面宿主另有「24 小时内发布的版本先标成「新版等待中」」这条规则。以 `npm view dsh-connect-workbuddy version` 与 [Releases](https://github.com/dingminhua/dsh-connect-workbuddy/releases) 为准,按下方[「更新」](#更新)一节做(写**精确版本号**),或者把 [`docs/PINNED-UPGRADE-LAG.md`](docs/PINNED-UPGRADE-LAG.md) §3 那段话丢给 AI 让它替你跑。
207
225
  >
208
- > 另一个会让人升级不到的原因:**pnpm 的 24 小时新版本等待期**(`minimumReleaseAge`)会把浮动范围**静默压回上一个版本**。需要立刻修复时请写**精确版本号**:`dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.0`(原因见下方「刚发布的版本请写精确版本号」那条)。
226
+ > 另一个会让人升级不到的原因:**pnpm 的 24 小时新版本等待期**(`minimumReleaseAge`)会把浮动范围**静默压回上一个版本**。需要立刻修复时请写**精确版本号**:`dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.1`(原因见下方「刚发布的版本请写精确版本号」那条)。
209
227
 
210
228
  ### 受支持的宿主范围
211
229
 
@@ -273,7 +291,7 @@ npm install dsh-connect-workbuddy
273
291
  > | 精确 `5.14.1` + profile `pnpm-workspace.yaml` 里 `minimumReleaseAgeExclude: [dsh-connect-workbuddy]` | **5.14.1** ✅ |
274
292
  > | 不设该项(pnpm 默认) | 浮动 `^5.13.1` → **5.14.1** ✅ |
275
293
  >
276
- > 想立刻用上新版,请写精确版本号:`dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.0`;若被等待期拒绝,见 [`docs/PINNED-UPGRADE-LAG.md`](docs/PINNED-UPGRADE-LAG.md) §2 的两条路(等窗口过去,或加那行 exclude)。过了等待期之后,浮动范围会自然跟上。
294
+ > 想立刻用上新版,请写精确版本号:`dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.1`;若被等待期拒绝,见 [`docs/PINNED-UPGRADE-LAG.md`](docs/PINNED-UPGRADE-LAG.md) §2 的两条路(等窗口过去,或加那行 exclude)。过了等待期之后,浮动范围会自然跟上。
277
295
 
278
296
  插件在 **Web**、**Desktop**、**TUI** 三种界面下均可运行,按你使用的 profile 选择对应命令:
279
297
 
@@ -358,7 +376,7 @@ dsh: plugin command failed; diagnostics: …/operation-xxxx/pnpm.log
358
376
  **手动更新(一条命令)**:
359
377
 
360
378
  ```sh
361
- dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.0
379
+ dsh plugin --profile desktop add dsh-connect-workbuddy@5.19.1
362
380
  dsh plugin --profile desktop exec dsh-connect-workbuddy doctor # 第一行就是版本
363
381
  ```
364
382
 
package/lib/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $t as ensureDeviceSalt, C as FALLBACK_WORKBUDDY_MODELS_GLOBAL, H as legacyWorkbuddyOwnAuthPath, I as defaultDesktopAuthCandidates, J as APP_VERSION, K as workbuddyOwnAuthPath, L as defaultDesktopAuthDirs, M as WORKBUDDY_VAULT_DIRNAME, N as WorkBuddyCredentialStore, Qt as readDeviceTokenFile, S as FALLBACK_WORKBUDDY_MODELS, Z as DEFAULT_WIRE_PROFILE, Zt as WORKBUDDY_DEVICE_TOKEN_FILE_ENV, a as readHostHeartbeat, an as WORKBUDDY_APP_EXECUTABLE_ENV, bn as resolveDshHome, c as WORKBUDDY_CONNECT_VERSION, d as rosterSeenPath, dn as findWorkbuddyAppExecutableWithSource, en as readDeviceSalt, et as WorkBuddyUpstreamClient, f as piAiRuntimeInfo, in as protectCredentialDirectory, it as describeRequestHeaderNames, j as WORKBUDDY_AUTH_FILE_ENV, m as createTuringSdk, o as workbuddyHostHeartbeatPath, q as workbuddyVaultDir, r as isHeartbeatProcessAlive, rn as inspectCredentialDirectory, tn as deriveDeviceId, u as describeRosterSeenPayload, v as readDeviceSettings, yn as hostPeersInfo } from "./host-heartbeat-hEksLFOK.js";
2
+ import { $ as DEFAULT_WIRE_PROFILE, $t as WORKBUDDY_DEVICE_TOKEN_FILE_ENV, F as WorkBuddyCredentialStore, J as workbuddyOwnAuthPath, N as WORKBUDDY_AUTH_FILE_ENV, P as WORKBUDDY_VAULT_DIRNAME, R as defaultDesktopAuthCandidates, Sn as resolveDshHome, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, W as legacyWorkbuddyOwnAuthPath, X as APP_VERSION, Y as workbuddyVaultDir, a as readHostHeartbeat, an as inspectCredentialDirectory, b as readDeviceSettings, c as WORKBUDDY_CONNECT_VERSION, d as rosterSeenPath, en as readDeviceTokenFile, f as WORKBUDDY_CN_BASE_ENV, g as createTuringSdk, m as piAiRuntimeInfo, nn as readDeviceSalt, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, on as protectCredentialDirectory, ot as describeRequestHeaderNames, p as resolveCnGateway, pn as findWorkbuddyAppExecutableWithSource, r as isHeartbeatProcessAlive, rn as deriveDeviceId, sn as WORKBUDDY_APP_EXECUTABLE_ENV, tn as ensureDeviceSalt, u as describeRosterSeenPayload, w as FALLBACK_WORKBUDDY_MODELS, xn as hostPeersInfo, z as defaultDesktopAuthDirs } from "./host-heartbeat-BTTe5VDs.js";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { dirname, join } from "node:path";
5
5
  import { realpathSync } from "node:fs";
@@ -246,9 +246,31 @@ function printHelp() {
246
246
  function printJson(value) {
247
247
  process.stdout.write(`${JSON.stringify(value)}\n`);
248
248
  }
249
+ /**
250
+ * The CN gateway override as the CLI can see it (issue #220).
251
+ *
252
+ * `doctor` runs in its own process and never loads the plugin's settings, so the
253
+ * card's field is invisible here. Without this, a user who fixed their network
254
+ * would run `doctor` and get a report measured against the gateway their network
255
+ * resets — a diagnostics tool lying about which host it probed.
256
+ *
257
+ * An invalid value is REPORTED and then ignored rather than silently dropped:
258
+ * `doctor` is where a user goes to find out why nothing works, so "your
259
+ * override was rejected because X" is exactly the answer they need.
260
+ */
261
+ function cliCnBase() {
262
+ const raw = (process.env["WORKBUDDY_CN_BASE"] ?? "").trim();
263
+ if (raw === "") return "";
264
+ const resolved = resolveCnGateway(raw);
265
+ if (!resolved.ok) {
266
+ process.stderr.write(`warning: ignoring ${WORKBUDDY_CN_BASE_ENV}="${raw}" — ${resolved.reason === "malformed" ? "not an absolute URL" : resolved.reason === "insecure" ? "only https is accepted" : "host is not one of the CN brands"}\n`);
267
+ return "";
268
+ }
269
+ return resolved.overridden ? resolved.base : "";
270
+ }
249
271
  /** One region-scoped credential store (its own plugin-owned copy file). */
250
272
  function makeStore(region) {
251
- const client = new WorkBuddyUpstreamClient();
273
+ const client = new WorkBuddyUpstreamClient(void 0, {}, { cnBase: cliCnBase });
252
274
  return new WorkBuddyCredentialStore({
253
275
  region,
254
276
  refresh: (credential) => client.refreshToken(credential)
@@ -256,7 +278,7 @@ function makeStore(region) {
256
278
  }
257
279
  /** The region-unscoped store (reads every plugin-owned copy). */
258
280
  function makeAnyStore() {
259
- const client = new WorkBuddyUpstreamClient();
281
+ const client = new WorkBuddyUpstreamClient(void 0, {}, { cnBase: cliCnBase });
260
282
  return new WorkBuddyCredentialStore({ refresh: (credential) => client.refreshToken(credential) });
261
283
  }
262
284
  /**
@@ -575,7 +597,7 @@ async function doctor(jsonOutput) {
575
597
  /** One region's sign-in and credit summary. */
576
598
  async function regionStatus(region) {
577
599
  const store = makeStore(region);
578
- const client = new WorkBuddyUpstreamClient();
600
+ const client = new WorkBuddyUpstreamClient(void 0, {}, { cnBase: cliCnBase });
579
601
  const authStatus = await store.status();
580
602
  const accounts = await store.accounts();
581
603
  const selected = accounts.find((account) => account.selected);
package/lib/client.js CHANGED
@@ -477,6 +477,34 @@ window.__ModuleLoader__.load({
477
477
  });
478
478
  }
479
479
  /**
480
+ * Build the next `regions` FIELD carrying one region's CN gateway override
481
+ * (issue #220).
482
+ *
483
+ * Same whole-slot merge as every other helper here: only `cnBase` changes, so
484
+ * setting a host cannot drop the model directory, the pool preferences or the
485
+ * switches that share this slot. An empty string is written as-is rather than
486
+ * deleting the key — it means "back to the built-in gateway", which must survive
487
+ * a read-back, and `resolveCnGateway('')` already reads both the same way.
488
+ */
489
+ function nextRegionCnBase(value, region, cnBase) {
490
+ return nextRegionSlots(regionsMapOf(value), region, {
491
+ ...regionSlotOf(value, region),
492
+ cnBase
493
+ });
494
+ }
495
+ /**
496
+ * Read one region's saved CN gateway override, or `''` when it has none.
497
+ *
498
+ * Deliberately tolerant of a non-string: the settings mirror can hold whatever a
499
+ * previous version wrote, and throwing here would take out the whole capabilities
500
+ * panel over one malformed field. A value that is not a string is treated as
501
+ * "not configured", which is exactly how `resolveCnGateway` treats it.
502
+ */
503
+ function regionCnBaseOf(value, region) {
504
+ const raw = regionSlotOf(value, region)["cnBase"];
505
+ return typeof raw === "string" ? raw : "";
506
+ }
507
+ /**
480
508
  * Whether one region's sidebar credit line is shown. Opt-out: only an explicit
481
509
  * `false` hides it, so a config written before this switch existed keeps the
482
510
  * line visible exactly as a fresh install does.
@@ -1296,6 +1324,32 @@ window.__ModuleLoader__.load({
1296
1324
  });
1297
1325
  }
1298
1326
  /**
1327
+ * Write the CN gateway override (issue #220), with the same landed-check as
1328
+ * every other settings write.
1329
+ *
1330
+ * Carries the region's whole slot through untouched — only `cnBase` changes —
1331
+ * so writing a host cannot drop the model directory, the pool preferences or
1332
+ * the switches that live beside it in the same slot.
1333
+ *
1334
+ * Validation is deliberately NOT here: the caller runs `resolveCnGateway` before
1335
+ * calling, because the rejection reason has to be worded for the user ("not a
1336
+ * known CN brand" vs "must be https"), and a bare `WorkBuddySettingsWriteError`
1337
+ * cannot say that. This function's only job is landing the value.
1338
+ *
1339
+ * @param scope - the bound settings scope for this plugin's namespace.
1340
+ * @param region - the region being written (always `cn` today: the international
1341
+ * gateways follow the credential's brand domain and have no counterpart).
1342
+ * @param cnBase - the validated base URL, or `''` to restore the built-in gateway.
1343
+ * @param slot - the region's COMPLETE next slot (caller owns the merge).
1344
+ * @throws {WorkBuddySettingsWriteError} when neither writer persists the value.
1345
+ */
1346
+ async function writeRegionCnBase(scope, region, cnBase, slot) {
1347
+ await writeField(scope, "regions", region, slot, (readBack) => {
1348
+ const stored = readBack;
1349
+ return stored !== null && stored !== void 0 && stored["cnBase"] === cnBase;
1350
+ });
1351
+ }
1352
+ /**
1299
1353
  * Show or hide one region's sidebar credit line, with the same landed-check as
1300
1354
  * every other settings write.
1301
1355
  *
@@ -1420,6 +1474,127 @@ window.__ModuleLoader__.load({
1420
1474
  });
1421
1475
  }
1422
1476
  //#endregion
1477
+ //#region src/cn-gateway.ts
1478
+ /**
1479
+ * The CN region's gateway host, and the ONE place an override is validated.
1480
+ *
1481
+ * ## Why this exists (issue #220)
1482
+ *
1483
+ * The CN chat gateway was the single hard-coded constant
1484
+ * `https://copilot.tencent.com`. In a corporate network that filters on the TLS
1485
+ * ClientHello's SNI, that name is reset before the handshake completes — while
1486
+ * the SAME network lets the WorkBuddy desktop app work, because the app reads a
1487
+ * failover list from its own config and uses `wb.tencentbuddy.com` as well.
1488
+ *
1489
+ * The reporter measured (2026-11-06): `copilot.tencent.com` answers
1490
+ * `ECONNRESET` in <100ms while `wb.tencentbuddy.com` answers a normal
1491
+ * `401 Authorization Required`. This module is what lets such a user point the
1492
+ * plugin at a host their network actually permits.
1493
+ *
1494
+ * ## Why an allowlist, and not "any URL you like"
1495
+ *
1496
+ * The value feeds `Authorization: Bearer <token>` on every CN request, plus the
1497
+ * refresh-token exchange. A free-form base is therefore a **credential
1498
+ * exfiltration primitive**: whoever can edit the settings (a synced profile, a
1499
+ * shared dotfile, a pasted "fix" from a forum post) could redirect a live
1500
+ * WorkBuddy token to a host they run. That is a strictly worse failure than the
1501
+ * timeout it fixes, and it is invisible — the requests would keep succeeding.
1502
+ *
1503
+ * So the override names a HOST from a closed set, never a URL from the open
1504
+ * internet. The set is the CN product's own brand registrable domains, measured
1505
+ * 2026-11-06 to answer the chat, billing, catalog and busy routes identically
1506
+ * (see `docs/CN_GATEWAY_FALLBACK.md`):
1507
+ *
1508
+ * copilot.tencent.com the shipping default
1509
+ * wb.tencentbuddy.com what the desktop app's failover.json lists
1510
+ * www.workbuddy.cn the brand host
1511
+ * www.codebuddy.cn the sibling brand host, also the billing base
1512
+ *
1513
+ * Each is admitted by REGISTRABLE domain, so any subdomain of those brands
1514
+ * qualifies and a lookalike (`wb.tencentbuddy.com.evil.example`) cannot —
1515
+ * the same rule `knownRegionOf` already applies to credential domains.
1516
+ *
1517
+ * ## What an override does NOT change
1518
+ *
1519
+ * `Origin` / `Referer` stay on the billing base (see `originReferer`): they
1520
+ * describe which web app the request comes from, not which socket it reaches.
1521
+ * Rewriting them from the override would make the identity claim disagree with
1522
+ * itself for no benefit — the gateway reads them as "this is the CN web app".
1523
+ *
1524
+ * @module dsh-connect-workbuddy/cn-gateway
1525
+ */
1526
+ /** The CN chat gateway the plugin has always used. */
1527
+ const CN_GATEWAY_DEFAULT = "https://copilot.tencent.com";
1528
+ /**
1529
+ * Hosts an override may name, as registrable domains.
1530
+ *
1531
+ * A closed set is the security boundary described in this module's header. Adding
1532
+ * a host here is a deliberate act that must come with a measurement showing it
1533
+ * answers the CN routes, not with a guess about the brand.
1534
+ */
1535
+ const ALLOWED_CN_DOMAINS = [
1536
+ "copilot.tencent.com",
1537
+ "tencentbuddy.com",
1538
+ "workbuddy.cn",
1539
+ "codebuddy.cn"
1540
+ ];
1541
+ /**
1542
+ * Whether `hostname` belongs to one of the CN brands above.
1543
+ *
1544
+ * Matched on the registrable domain (`host === domain` or `host.endsWith('.' +
1545
+ * domain)`), so `wb.tencentbuddy.com` and `copilot.internal.tencentbuddy.com`
1546
+ * both qualify while `tencentbuddy.com.evil.example` does not.
1547
+ */
1548
+ function isKnownCnHost(hostname) {
1549
+ const lowered = hostname.trim().toLowerCase();
1550
+ if (lowered === "") return false;
1551
+ return ALLOWED_CN_DOMAINS.some((domain) => lowered === domain || lowered.endsWith(`.${domain}`));
1552
+ }
1553
+ /**
1554
+ * Resolve the CN gateway base from an optional user-supplied value.
1555
+ *
1556
+ * An ABSENT or blank value is the normal case and yields the default with
1557
+ * `overridden: false`. A non-blank value must pass every check or the caller
1558
+ * gets `ok: false` and is expected to say so rather than silently falling back:
1559
+ * a user who typed a host and got the default anyway has no way to tell the
1560
+ * setting was ignored, and would keep debugging a network they already fixed.
1561
+ */
1562
+ function resolveCnGateway(value) {
1563
+ const raw = typeof value === "string" ? value.trim() : "";
1564
+ if (raw === "") return {
1565
+ ok: true,
1566
+ base: CN_GATEWAY_DEFAULT,
1567
+ host: "copilot.tencent.com",
1568
+ overridden: false
1569
+ };
1570
+ let parsed;
1571
+ try {
1572
+ parsed = new URL(raw);
1573
+ } catch {
1574
+ return {
1575
+ ok: false,
1576
+ reason: "malformed",
1577
+ value: raw
1578
+ };
1579
+ }
1580
+ if (parsed.protocol !== "https:") return {
1581
+ ok: false,
1582
+ reason: "insecure",
1583
+ value: raw
1584
+ };
1585
+ if (!isKnownCnHost(parsed.hostname)) return {
1586
+ ok: false,
1587
+ reason: "unknown-host",
1588
+ value: raw
1589
+ };
1590
+ return {
1591
+ ok: true,
1592
+ base: `https://${parsed.hostname.toLowerCase()}`,
1593
+ host: parsed.hostname.toLowerCase(),
1594
+ overridden: true
1595
+ };
1596
+ }
1597
+ //#endregion
1423
1598
  //#region src/client/panel-switch.ts
1424
1599
  /**
1425
1600
  * Whether the OPTIONAL sidebar panel is switched on, as the browser half sees
@@ -6330,6 +6505,23 @@ window.__ModuleLoader__.load({
6330
6505
  CONTRAST colour, so a ticked box painted itself as a heavy black pill — the
6331
6506
  loudest object in a section made of plain 13px text. */
6332
6507
  .dsm-workbuddy-pref input{flex:none;cursor:pointer;accent-color:var(--dsw-alias-brand-primary,#5686fe)}
6508
+ /* ── The CN gateway override (issue #220) ─────────────────────────────────────
6509
+ * One bordered block so it does not read as a fifth switch: every other control
6510
+ * in this section is a checkbox that commits on the click, this one is a text
6511
+ * field that needs an explicit Save. Giving it a card of its own is what says
6512
+ * "this answers a different question".
6513
+ *
6514
+ * The row wraps, and the input takes the whole width when it does: a host name is
6515
+ * long (https://wb.tencentbuddy.com is 26 characters) and a half-width input in
6516
+ * the panel column would show about eight of them. */
6517
+ .dsm-workbuddy-cnbase{display:flex;flex-direction:column;gap:8px;padding:10px 12px;border:1px solid var(--dsw-alias-border-l2,#3a3d45);border-radius:10px;background:var(--dsw-alias-bg-layer-2,#24262c)}
6518
+ .dsm-workbuddy-cnbase-row{display:flex;flex-direction:column;gap:8px}
6519
+ .dsm-workbuddy-cnbase-input{box-sizing:border-box;width:100%;padding:6px 10px;border:1px solid var(--dsw-alias-border-l2,#3a3d45);border-radius:8px;background:var(--dsw-alias-bg-layer-3,#2a2c33);color:var(--dsw-alias-label-primary,#e6e6e6);font:inherit;font-size:13px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
6520
+ .dsm-workbuddy-cnbase-input:disabled{opacity:.5;cursor:default}
6521
+ .dsm-workbuddy-cnbase-input:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:1px}
6522
+ .dsm-workbuddy-cnbase-error{margin:0;font-size:12px;line-height:17px;color:var(--dsw-alias-state-error-primary,#ef4444)}
6523
+ .dsm-workbuddy-cnbase-notice{margin:0;font-size:12px;line-height:17px;color:var(--dsw-alias-state-success-primary,#22a06b)}
6524
+ .dsm-workbuddy-cnbase-actions{display:flex;align-items:center;justify-content:flex-end;gap:8px}
6333
6525
  .dsm-workbuddy-pref-check,.dsm-workbuddy-image-tool-check,.dsm-workbuddy-video-tool-check,.dsm-workbuddy-cli-bridge-check,.dsm-workbuddy-sidebar-panel-check,.dsm-workbuddy-upstream-check,.dsm-workbuddy-channel-continue-check{inline-size:15px;block-size:15px;margin:3px 0 0}
6334
6526
  /* The upstream-identity switches are their own group, so they get a divider
6335
6527
  above them instead of relying on spacing alone: they change the request the
@@ -8462,6 +8654,15 @@ window.__ModuleLoader__.load({
8462
8654
  const [sidebarPanelOn, setSidebarPanelOn] = (0, react.useState)(void 0);
8463
8655
  const [sidebarPanelBusy, setSidebarPanelBusy] = (0, react.useState)(false);
8464
8656
  /**
8657
+ * The CN gateway editor's draft (issue #220). `undefined` = "not edited", so
8658
+ * the field shows the SAVED value and a background refresh cannot overwrite
8659
+ * what the user is typing — the same rule the model drafts follow.
8660
+ */
8661
+ const [cnBaseDraft, setCnBaseDraft] = (0, react.useState)(void 0);
8662
+ const [cnBaseSaving, setCnBaseSaving] = (0, react.useState)(false);
8663
+ const [cnBaseError, setCnBaseError] = (0, react.useState)(void 0);
8664
+ const [cnBaseNotice, setCnBaseNotice] = (0, react.useState)(void 0);
8665
+ /**
8465
8666
  * The quick-adjust pins of the CLI route (model, effort, region order) made
8466
8667
  * by THIS card instance.
8467
8668
  *
@@ -10122,6 +10323,117 @@ window.__ModuleLoader__.load({
10122
10323
  * NOT gated on the active tab's provider: the row is a property of the whole
10123
10324
  * plugin, not of one region, and a signed-out card can still turn it on.
10124
10325
  */
10326
+ /**
10327
+ * The CN gateway override editor (issue #220).
10328
+ *
10329
+ * A DRAFT + explicit Save, unlike the switches above it: a host name is typed,
10330
+ * so committing per keystroke would write `https://w`, `https://wb`, … — six
10331
+ * settings writes and six `warn` log lines for one word. The switches commit on
10332
+ * the click precisely because a click IS a complete statement; a text field is
10333
+ * not.
10334
+ *
10335
+ * CN only. The international gateways follow the credential's own brand domain
10336
+ * (`workbuddy.ai` / `codebuddy.ai`), where an override against a host of a
10337
+ * DIFFERENT brand is rejected by the upstream — there is no "equivalent host"
10338
+ * to fall back to, so the control is absent on that tab rather than present and
10339
+ * unusable.
10340
+ *
10341
+ * The draft is validated HERE and not by the Host: the Host falls back to the
10342
+ * built-in gateway and logs, which keeps a running process correct but tells a
10343
+ * half-attending user nothing. Refusing the save with the specific rule it
10344
+ * broke ("not https" vs "not a CN brand") is what makes the setting findable.
10345
+ */
10346
+ const cnBaseSaved = regionCnBaseOf(settingsScope?.getSnapshot().value, "cn");
10347
+ const cnBaseDraftValue = cnBaseDraft ?? cnBaseSaved;
10348
+ const cnBaseDirty = cnBaseDraft !== void 0 && cnBaseDraft.trim() !== cnBaseSaved.trim();
10349
+ const cnBasePreview = resolveCnGateway(cnBaseDraftValue);
10350
+ const saveCnBase = async () => {
10351
+ if (settingsScope === void 0 || cnBaseSaving) return;
10352
+ const resolved = cnBasePreview;
10353
+ if (!resolved.ok) {
10354
+ setCnBaseError(resolved.reason === "malformed" ? t("row.cnBaseInvalidMalformed") : resolved.reason === "insecure" ? t("row.cnBaseInvalidInsecure") : t("row.cnBaseInvalidHost"));
10355
+ return;
10356
+ }
10357
+ setCnBaseSaving(true);
10358
+ setCnBaseError(void 0);
10359
+ try {
10360
+ const next = resolved.overridden ? resolved.base : "";
10361
+ await writeRegionCnBase(settingsScope, "cn", next, nextRegionCnBase(settingsScope.getSnapshot().value, "cn", next));
10362
+ if (mounted.current) {
10363
+ setCnBaseDraft(void 0);
10364
+ setCnBaseNotice(t(next === "" ? "row.cnBaseCleared" : "row.cnBaseSaved"));
10365
+ }
10366
+ await refreshUsage("cn");
10367
+ } catch (error) {
10368
+ if (mounted.current) setCnBaseError(error instanceof Error ? error.message : t("row.requestFailed"));
10369
+ } finally {
10370
+ if (mounted.current) setCnBaseSaving(false);
10371
+ }
10372
+ };
10373
+ const cnBasePreference = activeRegion !== "cn" ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
10374
+ className: "dsm-workbuddy-cnbase",
10375
+ title: t("row.cnBaseHint"),
10376
+ children: [
10377
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
10378
+ className: "dsm-workbuddy-cnbase-row",
10379
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
10380
+ className: "dsm-workbuddy-pref-copy",
10381
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
10382
+ className: "dsm-workbuddy-pref-label",
10383
+ children: t("row.cnBaseLabel")
10384
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
10385
+ className: "dsm-workbuddy-pref-hint",
10386
+ children: t("row.cnBaseHint")
10387
+ })]
10388
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
10389
+ type: "url",
10390
+ className: "dsm-workbuddy-cnbase-input",
10391
+ value: cnBaseDraftValue,
10392
+ placeholder: t("row.cnBasePlaceholder"),
10393
+ disabled: !canWrite || saving || cnBaseSaving,
10394
+ spellCheck: false,
10395
+ autoComplete: "off",
10396
+ onChange: (event) => {
10397
+ setCnBaseDraft(event.target.value);
10398
+ setCnBaseError(void 0);
10399
+ setCnBaseNotice(void 0);
10400
+ }
10401
+ })]
10402
+ }),
10403
+ cnBaseError !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
10404
+ className: "dsm-workbuddy-cnbase-error",
10405
+ role: "alert",
10406
+ children: cnBaseError
10407
+ }) : null,
10408
+ cnBaseError === void 0 && cnBaseNotice !== void 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
10409
+ className: "dsm-workbuddy-cnbase-notice",
10410
+ role: "status",
10411
+ children: cnBaseNotice
10412
+ }) : null,
10413
+ cnBaseDirty ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
10414
+ className: "dsm-workbuddy-cnbase-actions",
10415
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
10416
+ type: "button",
10417
+ className: "dsm-btn dsm-btn-outline",
10418
+ disabled: cnBaseSaving,
10419
+ onClick: () => {
10420
+ setCnBaseDraft(void 0);
10421
+ setCnBaseError(void 0);
10422
+ setCnBaseNotice(void 0);
10423
+ },
10424
+ children: t("row.poolDiscard")
10425
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
10426
+ type: "button",
10427
+ className: "dsm-btn dsm-btn-primary",
10428
+ disabled: cnBaseSaving,
10429
+ onClick: () => {
10430
+ saveCnBase();
10431
+ },
10432
+ children: cnBaseSaving ? t("row.poolSaving") : t("row.poolSaved")
10433
+ })]
10434
+ }) : null
10435
+ ]
10436
+ });
10125
10437
  const sidebarPanelPreference = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("label", {
10126
10438
  className: "dsm-workbuddy-pref",
10127
10439
  title: t("row.sidebarPanelHint"),
@@ -11037,6 +11349,7 @@ window.__ModuleLoader__.load({
11037
11349
  className: "dsm-workbuddy-panel-note",
11038
11350
  children: t("row.panelCapabilitiesHint")
11039
11351
  }),
11352
+ cnBasePreference,
11040
11353
  creditPreferences,
11041
11354
  upstreamSwitches,
11042
11355
  channelRejectContinuePreference,
@@ -11072,6 +11385,19 @@ window.__ModuleLoader__.load({
11072
11385
  children: status.domain === void 0 || status.domain === "" ? t("row.modelUnknown") : status.domain
11073
11386
  })]
11074
11387
  }),
11388
+ status.region === "cn" ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11389
+ className: "dsm-workbuddy-diag-row",
11390
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
11391
+ className: "dsm-workbuddy-diag-label",
11392
+ children: t("row.diagCnBase")
11393
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
11394
+ className: "dsm-workbuddy-diag-value dsm-workbuddy-diag-mono",
11395
+ children: (() => {
11396
+ const resolved = resolveCnGateway(regionCnBaseOf(settingsScope?.getSnapshot().value, "cn"));
11397
+ return resolved.ok && resolved.overridden ? resolved.base : t("row.diagCnBaseDefault");
11398
+ })()
11399
+ })]
11400
+ }) : null,
11075
11401
  /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
11076
11402
  className: "dsm-workbuddy-diag-row",
11077
11403
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
@@ -13102,7 +13428,7 @@ window.__ModuleLoader__.load({
13102
13428
  "row.panelAccounts": "Accounts",
13103
13429
  "row.panelModels": "Models",
13104
13430
  "row.panelCapabilities": "Capabilities",
13105
- "row.panelCapabilitiesHint": "What the plugin may do on your behalf. Each switch takes effect on the click — there is no Save button in this section.",
13431
+ "row.panelCapabilitiesHint": "What the plugin may do on your behalf. The switches take effect on the click — there is no Save button for them. The one field at the top (the CN gateway) is a draft and saves on its own button, because a half-typed host must never become the live one.",
13106
13432
  "row.panelDiag": "Diagnostics",
13107
13433
  "row.panelAria": "Card sections",
13108
13434
  "row.diagHint": "What this card actually read, so a report can quote it. Nothing here changes a setting.",
@@ -13473,6 +13799,16 @@ window.__ModuleLoader__.load({
13473
13799
  "row.channelRejectContinueText": "Text sent:",
13474
13800
  "row.cliBridgeLabel": "Let the local CodeBuddy CLI do the work",
13475
13801
  "row.cliBridgeHint": "Adds the codebuddy_ask tool and the /codebuddy command. Each call spends CodeBuddy quota. injectResult only affects /codebuddy — its result is injected back into the session, costing one DSH turn when the session is idle; tool calls never read it. Rate-limited: 6 turns per session per hour, 20 per process per hour, one turn at a time. Off by default.",
13802
+ "row.cnBaseLabel": "CN gateway host",
13803
+ "row.cnBaseHint": "Leave empty to use copilot.tencent.com. Set it only if your network resets that host by TLS SNI (connection fails in milliseconds while the WorkBuddy desktop app still works) — the app itself falls back to wb.tencentbuddy.com. Accepted hosts: any subdomain of copilot.tencent.com, tencentbuddy.com, workbuddy.cn or codebuddy.cn, over https. Chat, billing, catalog and check-in all follow it; your account and region do not change.",
13804
+ "row.cnBasePlaceholder": "https://wb.tencentbuddy.com",
13805
+ "row.cnBaseInvalidMalformed": "That is not a full URL. Include https:// and the host, e.g. https://wb.tencentbuddy.com",
13806
+ "row.cnBaseInvalidInsecure": "Only https is accepted — a plaintext host would send your token in the clear.",
13807
+ "row.cnBaseInvalidHost": "That host is not one of the CN brands. Use a subdomain of copilot.tencent.com, tencentbuddy.com, workbuddy.cn or codebuddy.cn.",
13808
+ "row.cnBaseSaved": "CN gateway saved. New requests use it; originals/CORS headers keep naming the CN web app.",
13809
+ "row.cnBaseCleared": "Back to the built-in CN gateway.",
13810
+ "row.diagCnBase": "CN gateway",
13811
+ "row.diagCnBaseDefault": "built-in (copilot.tencent.com)",
13476
13812
  "row.sidebarPanelLabel": "Show WorkBuddy in the sidebar",
13477
13813
  "row.sidebarPanelHint": "Adds a WorkBuddy row to the DSH sidebar that opens this card as a full page. Off by default: the row takes a global sidebar slot shared by every installed plugin, and the Plugins page already reaches the same content. Takes effect on the click — no Save needed — and switching it off while the page is open returns you to the conversation.",
13478
13814
  "row.cliBridgeModelLabel": "CLI model",
@@ -13626,7 +13962,7 @@ window.__ModuleLoader__.load({
13626
13962
  "row.panelAccounts": "账号",
13627
13963
  "row.panelModels": "模型",
13628
13964
  "row.panelCapabilities": "能力",
13629
- "row.panelCapabilitiesHint": "插件可以替你做什么。这些开关点一下立即生效 —— 这一区里没有保存按钮。",
13965
+ "row.panelCapabilitiesHint": "插件可以替你做什么。这些开关点一下立即生效 —— 开关没有保存按钮。顶上那个「CN 网关主机」是草稿,由它自己的按钮保存:一个打到一半的主机名绝不该成为生效值。",
13630
13966
  "row.panelDiag": "诊断",
13631
13967
  "row.panelAria": "卡片分区",
13632
13968
  "row.diagHint": "这张卡片实际读到了什么,方便贴进问题反馈。这里没有任何会改动设置的控件。",
@@ -13997,6 +14333,16 @@ window.__ModuleLoader__.load({
13997
14333
  "row.channelRejectContinueText": "发送的文本:",
13998
14334
  "row.cliBridgeLabel": "允许调用本机 CodeBuddy CLI 干活",
13999
14335
  "row.cliBridgeHint": "开启后多出 codebuddy_ask 工具与 /codebuddy 指令;每次调用花 CodeBuddy 配额。injectResult 只影响 /codebuddy:其结果回注会话,会话空闲时多花一次 DSH 回合;工具调用不读它。限流:每会话每小时 6 回合、每进程每小时 20 回合、同时只跑一个回合。默认关闭。",
14336
+ "row.cnBaseLabel": "CN 网关主机",
14337
+ "row.cnBaseHint": "留空即用 copilot.tencent.com。只有当你的网络按 TLS SNI 重置这个域名时才需要填(连接在毫秒级就失败,而同一台机器上的 WorkBuddy 桌面端正常——客户端自己会退回 wb.tencentbuddy.com)。可填 copilot.tencent.com、tencentbuddy.com、workbuddy.cn、codebuddy.cn 任一域名下的子域,且必须是 https。聊天、计费、模型目录、签到都会跟着走;账号与区域不会变。",
14338
+ "row.cnBasePlaceholder": "https://wb.tencentbuddy.com",
14339
+ "row.cnBaseInvalidMalformed": "这不是一个完整 URL。请带上 https:// 与主机名,例如 https://wb.tencentbuddy.com",
14340
+ "row.cnBaseInvalidInsecure": "只接受 https——明文主机会把你的 token 裸发出去。",
14341
+ "row.cnBaseInvalidHost": "这个主机不在 CN 品牌里。请用 copilot.tencent.com、tencentbuddy.com、workbuddy.cn、codebuddy.cn 下的子域。",
14342
+ "row.cnBaseSaved": "CN 网关已保存,新请求即刻使用它;Origin/Referer 仍然自称 CN 网页端。",
14343
+ "row.cnBaseCleared": "已回到内置 CN 网关。",
14344
+ "row.diagCnBase": "CN 网关",
14345
+ "row.diagCnBaseDefault": "内置(copilot.tencent.com)",
14000
14346
  "row.sidebarPanelLabel": "在侧边栏显示 WorkBuddy",
14001
14347
  "row.sidebarPanelHint": "在 DSH 侧边栏加一个 WorkBuddy 行,点开就是这张卡片的整页版。默认关闭:这一行占的是所有插件共用的全局侧边栏座位,而「插件」页本来就能看到同样的内容。点一下即生效,不用保存;页面开着时关掉它,会直接回到对话。",
14002
14348
  "row.cliBridgeModelLabel": "CLI 模型",
@@ -3978,11 +3978,27 @@ function globalBase(domain) {
3978
3978
  if (lowered === "codebuddy.ai" || lowered.endsWith(".codebuddy.ai")) return "https://www.codebuddy.ai";
3979
3979
  return GLOBAL_BASE;
3980
3980
  }
3981
- function chatBase(credential) {
3982
- return regionOf(credential.domain) === "global" ? globalBase(credential.domain) : CN_CHAT_BASE;
3981
+ /**
3982
+ * The CN gateway base for this process, resolved ONCE at construction.
3983
+ *
3984
+ * Empty means "no override", and then the constant is used — the pre-#220
3985
+ * behaviour, byte for byte. A non-empty value has already passed
3986
+ * `resolveCnGateway`'s allowlist, so this is a validated host and not whatever
3987
+ * happened to be in the settings file.
3988
+ *
3989
+ * Deliberately injected rather than read from config at each call site: the CN
3990
+ * base feeds a Bearer token, so "which host" must be decided in exactly one
3991
+ * place that can be pointed at and audited, not re-derived by ten request
3992
+ * builders. The class also swaps it when the setting changes (the mount
3993
+ * reconstructs the client on a volatile update).
3994
+ */
3995
+ function chatBase(credential, cnBase) {
3996
+ if (regionOf(credential.domain) === "global") return globalBase(credential.domain);
3997
+ return cnBase === void 0 || cnBase === "" ? CN_CHAT_BASE : cnBase;
3983
3998
  }
3984
- function billingBase(credential) {
3985
- return regionOf(credential.domain) === "global" ? globalBase(credential.domain) : CN_BILLING_BASE;
3999
+ function billingBase(credential, cnBase) {
4000
+ if (regionOf(credential.domain) === "global") return globalBase(credential.domain);
4001
+ return cnBase === void 0 || cnBase === "" ? CN_BILLING_BASE : cnBase;
3986
4002
  }
3987
4003
  function originReferer(credential) {
3988
4004
  return regionOf(credential.domain) === "global" ? globalBase(credential.domain) : CN_BILLING_BASE;
@@ -5878,8 +5894,17 @@ var WorkBuddyUpstreamClient = class {
5878
5894
  deviceProfiles;
5879
5895
  /** 真实值档的 token 源(本机安装的桌面端 SDK);未接线时为 undefined。 */
5880
5896
  realDevice;
5897
+ /**
5898
+ * CN 网关 base(issue #220)。空 = 用内置常量,即 #220 之前的行为逐字节不变。
5899
+ *
5900
+ * 只影响 CN 区域:国际版仍然跟随凭据自己的域(`workbuddy.ai` /
5901
+ * `codebuddy.ai`),因为国际 token 跨品牌互不通用,那里没有"换一个同构主机"
5902
+ * 这回事。返回值必须已由 `resolveCnGateway` 的允许清单校验过,这个类不重新校验。
5903
+ */
5904
+ cnBaseOf;
5881
5905
  constructor(onFallback, identity = {}, options = {}) {
5882
5906
  this.onFallback = onFallback;
5907
+ this.cnBaseOf = options.cnBase === void 0 ? () => "" : options.cnBase;
5883
5908
  this.baseIdentity = resolveWireIdentity(identity);
5884
5909
  this.deviceProfiles = options.deviceProfiles;
5885
5910
  this.realDevice = options.realDevice;
@@ -5955,7 +5980,7 @@ var WorkBuddyUpstreamClient = class {
5955
5980
  kind: "server",
5956
5981
  message: "cancelled before send"
5957
5982
  };
5958
- response = await fetch(`${chatBase(credential)}/v2/chat/completions`, {
5983
+ response = await fetch(`${chatBase(credential, this.cnBaseOf())}/v2/chat/completions`, {
5959
5984
  method: "POST",
5960
5985
  headers,
5961
5986
  body: bodyJson,
@@ -6033,7 +6058,7 @@ var WorkBuddyUpstreamClient = class {
6033
6058
  ceiling.abort(/* @__PURE__ */ new Error(`no response within ${PROBE_TIMEOUT_MS}ms`));
6034
6059
  }, PROBE_TIMEOUT_MS);
6035
6060
  try {
6036
- response = await fetch(`${chatBase(credential)}/v2/chat/completions`, {
6061
+ response = await fetch(`${chatBase(credential, this.cnBaseOf())}/v2/chat/completions`, {
6037
6062
  method: "POST",
6038
6063
  headers,
6039
6064
  body: bodyJson,
@@ -6066,7 +6091,7 @@ var WorkBuddyUpstreamClient = class {
6066
6091
  }
6067
6092
  /** POST the token-refresh endpoint; the caller merges the outcome. */
6068
6093
  async refreshToken(credential) {
6069
- const response = await fetch(`${chatBase(credential)}/v2/plugin/auth/token/refresh`, {
6094
+ const response = await fetch(`${chatBase(credential, this.cnBaseOf())}/v2/plugin/auth/token/refresh`, {
6070
6095
  method: "POST",
6071
6096
  headers: refreshHeaders(credential),
6072
6097
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
@@ -6132,7 +6157,7 @@ var WorkBuddyUpstreamClient = class {
6132
6157
  return withPromos(selectCliModels(data["models"], data["agents"], keepModelIds), data);
6133
6158
  }
6134
6159
  const readCatalog = async (path) => {
6135
- const response = await fetch(`${chatBase(credential)}${path}`, {
6160
+ const response = await fetch(`${chatBase(credential, this.cnBaseOf())}${path}`, {
6136
6161
  headers: {
6137
6162
  "Authorization": `Bearer ${credential.accessToken}`,
6138
6163
  "Accept": "application/json",
@@ -6168,7 +6193,7 @@ var WorkBuddyUpstreamClient = class {
6168
6193
  async fetchModelBusy(credential, modelIds, signal) {
6169
6194
  const levels = /* @__PURE__ */ new Map();
6170
6195
  for (const batch of batchModelIds(modelIds)) {
6171
- const response = await fetch(`${chatBase(credential)}${MODEL_BUSY_PATH}`, {
6196
+ const response = await fetch(`${chatBase(credential, this.cnBaseOf())}${MODEL_BUSY_PATH}`, {
6172
6197
  method: "POST",
6173
6198
  headers: {
6174
6199
  ...legacyCommonHeaders(credential),
@@ -6210,7 +6235,7 @@ var WorkBuddyUpstreamClient = class {
6210
6235
  */
6211
6236
  async fetchMediaModels(credential, signal) {
6212
6237
  const readMedia = async (path) => {
6213
- const response = await fetch(`${chatBase(credential)}${path}`, {
6238
+ const response = await fetch(`${chatBase(credential, this.cnBaseOf())}${path}`, {
6214
6239
  headers: {
6215
6240
  "Authorization": `Bearer ${credential.accessToken}`,
6216
6241
  "Accept": "application/json",
@@ -6245,7 +6270,7 @@ var WorkBuddyUpstreamClient = class {
6245
6270
  * HTTP 200 但信封 `code !== 0` 由 {@link parseImageResponse} 处理。
6246
6271
  */
6247
6272
  async generateImage(credential, request, signal) {
6248
- const response = await fetch(`${chatBase(credential)}${IMAGE_GENERATIONS_PATH}`, {
6273
+ const response = await fetch(`${chatBase(credential, this.cnBaseOf())}${IMAGE_GENERATIONS_PATH}`, {
6249
6274
  method: "POST",
6250
6275
  headers: imageHeaders(credential, await this.wireIdentity(credential)),
6251
6276
  body: JSON.stringify(buildImageBody(request)),
@@ -6274,7 +6299,7 @@ var WorkBuddyUpstreamClient = class {
6274
6299
  */
6275
6300
  async editImage(credential, request, signal) {
6276
6301
  if (request.image.length === 0) throw new WorkBuddyImageError("workbuddy image: 改图请求缺少输入图(image 数组为空)。", "INVALID_ARGS");
6277
- const response = await fetch(`${chatBase(credential)}${IMAGE_EDITS_PATH}`, {
6302
+ const response = await fetch(`${chatBase(credential, this.cnBaseOf())}${IMAGE_EDITS_PATH}`, {
6278
6303
  method: "POST",
6279
6304
  headers: imageHeaders(credential, await this.wireIdentity(credential)),
6280
6305
  body: JSON.stringify(buildEditBody(request)),
@@ -6315,7 +6340,7 @@ var WorkBuddyUpstreamClient = class {
6315
6340
  aspectRatio: request.aspectRatio,
6316
6341
  enableAudio: request.enableAudio
6317
6342
  }, isImageToVideo);
6318
- const response = await fetch(`${chatBase(credential)}${VIDEO_GENERATIONS_PATH}`, {
6343
+ const response = await fetch(`${chatBase(credential, this.cnBaseOf())}${VIDEO_GENERATIONS_PATH}`, {
6319
6344
  method: "POST",
6320
6345
  headers: imageHeaders(credential, await this.wireIdentity(credential)),
6321
6346
  body: JSON.stringify(body),
@@ -6351,7 +6376,7 @@ var WorkBuddyUpstreamClient = class {
6351
6376
  if (Date.now() - startedAt > VIDEO_POLL_TIMEOUT_MS) throw new WorkBuddyVideoError(`workbuddy video: 轮询超过 ${VIDEO_POLL_TIMEOUT_MS / 1e3} 秒仍未完成(task ${taskId})。`, "POLL_TIMEOUT");
6352
6377
  let payload;
6353
6378
  try {
6354
- const response = await fetch(`${chatBase(credential)}${VIDEO_TASKS_PATH}`, {
6379
+ const response = await fetch(`${chatBase(credential, this.cnBaseOf())}${VIDEO_TASKS_PATH}`, {
6355
6380
  method: "POST",
6356
6381
  headers: imageHeaders(credential, await this.wireIdentity(credential)),
6357
6382
  body: JSON.stringify({ task_id: taskId }),
@@ -6409,7 +6434,7 @@ var WorkBuddyUpstreamClient = class {
6409
6434
  }
6410
6435
  /** Query today's check-in status without changing account state. */
6411
6436
  async fetchCheckinStatus(credential) {
6412
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/checkin-activity-status`, {
6437
+ const response = await fetch(`${billingBase(credential, this.cnBaseOf())}/v2/billing/meter/checkin-activity-status`, {
6413
6438
  method: "POST",
6414
6439
  headers: billingHeaders(credential, await this.wireIdentity(credential)),
6415
6440
  body: "{}",
@@ -6462,7 +6487,7 @@ var WorkBuddyUpstreamClient = class {
6462
6487
  }
6463
6488
  /** One benefit status endpoint. Throws on anything that is not a clean `code: 0`. */
6464
6489
  async readBenefitStatus(kind, credential, path) {
6465
- const response = await fetch(`${billingBase(credential)}${path}`, {
6490
+ const response = await fetch(`${billingBase(credential, this.cnBaseOf())}${path}`, {
6466
6491
  method: "POST",
6467
6492
  headers: billingHeaders(credential, await this.wireIdentity(credential)),
6468
6493
  body: "{}",
@@ -6507,7 +6532,7 @@ var WorkBuddyUpstreamClient = class {
6507
6532
  * that silently did nothing still cannot leave the card saying 待领取.
6508
6533
  */
6509
6534
  async claimBenefit(credential, kind) {
6510
- const response = await fetch(`${billingBase(credential)}${BENEFIT_CLAIM_PATHS[kind]}`, {
6535
+ const response = await fetch(`${billingBase(credential, this.cnBaseOf())}${BENEFIT_CLAIM_PATHS[kind]}`, {
6511
6536
  method: "POST",
6512
6537
  headers: billingHeaders(credential, await this.wireIdentity(credential)),
6513
6538
  body: "{}",
@@ -6518,7 +6543,7 @@ var WorkBuddyUpstreamClient = class {
6518
6543
  }
6519
6544
  /** Claim today's check-in reward. The browser route guards this mutation. */
6520
6545
  async claimDailyCheckin(credential) {
6521
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/daily-checkin`, {
6546
+ const response = await fetch(`${billingBase(credential, this.cnBaseOf())}/v2/billing/meter/daily-checkin`, {
6522
6547
  method: "POST",
6523
6548
  headers: billingHeaders(credential, await this.wireIdentity(credential)),
6524
6549
  body: "{}",
@@ -6555,7 +6580,7 @@ var WorkBuddyUpstreamClient = class {
6555
6580
  * reporting zero).
6556
6581
  */
6557
6582
  async fetchEnterpriseCredits(credential) {
6558
- const response = await fetch(`${billingBase(credential)}/billing/meter/get-enterprise-user-usage`, {
6583
+ const response = await fetch(`${billingBase(credential, this.cnBaseOf())}/billing/meter/get-enterprise-user-usage`, {
6559
6584
  method: "POST",
6560
6585
  headers: billingHeaders(credential, await this.wireIdentity(credential)),
6561
6586
  body: JSON.stringify({}),
@@ -6604,7 +6629,7 @@ var WorkBuddyUpstreamClient = class {
6604
6629
  date.getMinutes().toString().padStart(2, "0"),
6605
6630
  date.getSeconds().toString().padStart(2, "0")
6606
6631
  ].join(":");
6607
- const response = await fetch(`${billingBase(credential)}/v2/billing/meter/get-user-resource`, {
6632
+ const response = await fetch(`${billingBase(credential, this.cnBaseOf())}/v2/billing/meter/get-user-resource`, {
6608
6633
  method: "POST",
6609
6634
  headers: billingHeaders(credential, await this.wireIdentity(credential)),
6610
6635
  body: JSON.stringify({
@@ -9846,6 +9871,141 @@ function generationOf(version) {
9846
9871
  if (match === null) return "legacy";
9847
9872
  return Number(match[1]) >= 87 ? "modern" : "legacy";
9848
9873
  }
9874
+ //#endregion
9875
+ //#region src/cn-gateway.ts
9876
+ /**
9877
+ * The CN region's gateway host, and the ONE place an override is validated.
9878
+ *
9879
+ * ## Why this exists (issue #220)
9880
+ *
9881
+ * The CN chat gateway was the single hard-coded constant
9882
+ * `https://copilot.tencent.com`. In a corporate network that filters on the TLS
9883
+ * ClientHello's SNI, that name is reset before the handshake completes — while
9884
+ * the SAME network lets the WorkBuddy desktop app work, because the app reads a
9885
+ * failover list from its own config and uses `wb.tencentbuddy.com` as well.
9886
+ *
9887
+ * The reporter measured (2026-11-06): `copilot.tencent.com` answers
9888
+ * `ECONNRESET` in <100ms while `wb.tencentbuddy.com` answers a normal
9889
+ * `401 Authorization Required`. This module is what lets such a user point the
9890
+ * plugin at a host their network actually permits.
9891
+ *
9892
+ * ## Why an allowlist, and not "any URL you like"
9893
+ *
9894
+ * The value feeds `Authorization: Bearer <token>` on every CN request, plus the
9895
+ * refresh-token exchange. A free-form base is therefore a **credential
9896
+ * exfiltration primitive**: whoever can edit the settings (a synced profile, a
9897
+ * shared dotfile, a pasted "fix" from a forum post) could redirect a live
9898
+ * WorkBuddy token to a host they run. That is a strictly worse failure than the
9899
+ * timeout it fixes, and it is invisible — the requests would keep succeeding.
9900
+ *
9901
+ * So the override names a HOST from a closed set, never a URL from the open
9902
+ * internet. The set is the CN product's own brand registrable domains, measured
9903
+ * 2026-11-06 to answer the chat, billing, catalog and busy routes identically
9904
+ * (see `docs/CN_GATEWAY_FALLBACK.md`):
9905
+ *
9906
+ * copilot.tencent.com the shipping default
9907
+ * wb.tencentbuddy.com what the desktop app's failover.json lists
9908
+ * www.workbuddy.cn the brand host
9909
+ * www.codebuddy.cn the sibling brand host, also the billing base
9910
+ *
9911
+ * Each is admitted by REGISTRABLE domain, so any subdomain of those brands
9912
+ * qualifies and a lookalike (`wb.tencentbuddy.com.evil.example`) cannot —
9913
+ * the same rule `knownRegionOf` already applies to credential domains.
9914
+ *
9915
+ * ## What an override does NOT change
9916
+ *
9917
+ * `Origin` / `Referer` stay on the billing base (see `originReferer`): they
9918
+ * describe which web app the request comes from, not which socket it reaches.
9919
+ * Rewriting them from the override would make the identity claim disagree with
9920
+ * itself for no benefit — the gateway reads them as "this is the CN web app".
9921
+ *
9922
+ * @module dsh-connect-workbuddy/cn-gateway
9923
+ */
9924
+ /** The CN chat gateway the plugin has always used. */
9925
+ const CN_GATEWAY_DEFAULT = "https://copilot.tencent.com";
9926
+ /**
9927
+ * Environment override for `doctor`, mirroring the settings field.
9928
+ *
9929
+ * WHY THIS EXISTS. `dsh plugin exec … doctor` runs in its own process, which
9930
+ * never loads the plugin's settings — the same reason `WORKBUDDY_DEVICE_TOKEN_FILE`
9931
+ * already exists as the CLI's way to see what the plugin sees. Without it, a
9932
+ * user who fixed their network via the card's field would run `doctor` and get a
9933
+ * report measured against the gateway their network RESETS: a diagnostics tool
9934
+ * that lies about which host it probed is worse than no tool.
9935
+ *
9936
+ * The plugin reads the settings field; `doctor` reads this. Both go through
9937
+ * `resolveCnGateway`, so the allowlist cannot diverge between them.
9938
+ */
9939
+ const WORKBUDDY_CN_BASE_ENV = "WORKBUDDY_CN_BASE";
9940
+ /**
9941
+ * Hosts an override may name, as registrable domains.
9942
+ *
9943
+ * A closed set is the security boundary described in this module's header. Adding
9944
+ * a host here is a deliberate act that must come with a measurement showing it
9945
+ * answers the CN routes, not with a guess about the brand.
9946
+ */
9947
+ const ALLOWED_CN_DOMAINS = [
9948
+ "copilot.tencent.com",
9949
+ "tencentbuddy.com",
9950
+ "workbuddy.cn",
9951
+ "codebuddy.cn"
9952
+ ];
9953
+ /**
9954
+ * Whether `hostname` belongs to one of the CN brands above.
9955
+ *
9956
+ * Matched on the registrable domain (`host === domain` or `host.endsWith('.' +
9957
+ * domain)`), so `wb.tencentbuddy.com` and `copilot.internal.tencentbuddy.com`
9958
+ * both qualify while `tencentbuddy.com.evil.example` does not.
9959
+ */
9960
+ function isKnownCnHost(hostname) {
9961
+ const lowered = hostname.trim().toLowerCase();
9962
+ if (lowered === "") return false;
9963
+ return ALLOWED_CN_DOMAINS.some((domain) => lowered === domain || lowered.endsWith(`.${domain}`));
9964
+ }
9965
+ /**
9966
+ * Resolve the CN gateway base from an optional user-supplied value.
9967
+ *
9968
+ * An ABSENT or blank value is the normal case and yields the default with
9969
+ * `overridden: false`. A non-blank value must pass every check or the caller
9970
+ * gets `ok: false` and is expected to say so rather than silently falling back:
9971
+ * a user who typed a host and got the default anyway has no way to tell the
9972
+ * setting was ignored, and would keep debugging a network they already fixed.
9973
+ */
9974
+ function resolveCnGateway(value) {
9975
+ const raw = typeof value === "string" ? value.trim() : "";
9976
+ if (raw === "") return {
9977
+ ok: true,
9978
+ base: CN_GATEWAY_DEFAULT,
9979
+ host: "copilot.tencent.com",
9980
+ overridden: false
9981
+ };
9982
+ let parsed;
9983
+ try {
9984
+ parsed = new URL(raw);
9985
+ } catch {
9986
+ return {
9987
+ ok: false,
9988
+ reason: "malformed",
9989
+ value: raw
9990
+ };
9991
+ }
9992
+ if (parsed.protocol !== "https:") return {
9993
+ ok: false,
9994
+ reason: "insecure",
9995
+ value: raw
9996
+ };
9997
+ if (!isKnownCnHost(parsed.hostname)) return {
9998
+ ok: false,
9999
+ reason: "unknown-host",
10000
+ value: raw
10001
+ };
10002
+ return {
10003
+ ok: true,
10004
+ base: `https://${parsed.hostname.toLowerCase()}`,
10005
+ host: parsed.hostname.toLowerCase(),
10006
+ overridden: true
10007
+ };
10008
+ }
9849
10009
  /** The versions this build can read (add a new one on upgrade, keep old ones). */
9850
10010
  const KNOWN_ROSTER_SEEN_VERSIONS = Object.freeze([1]);
9851
10011
  /**
@@ -10060,7 +10220,7 @@ function describeRosterSeenPayload(raw) {
10060
10220
  //#endregion
10061
10221
  //#region src/version.ts
10062
10222
  /** The npm package version this build was produced from. */
10063
- const WORKBUDDY_CONNECT_VERSION = "5.19.1";
10223
+ const WORKBUDDY_CONNECT_VERSION = "5.20.0";
10064
10224
  //#endregion
10065
10225
  //#region src/host-heartbeat.ts
10066
10226
  /**
@@ -10271,4 +10431,4 @@ async function clearHostHeartbeat() {
10271
10431
  await rm(workbuddyHostHeartbeatPath(), { force: true });
10272
10432
  }
10273
10433
  //#endregion
10274
- export { WorkBuddyCredentialRejectedError as $, ensureDeviceSalt as $t, WORKBUDDY_AUTH_FILENAME as A, VIDEO_TAG_TEXT_TO_VIDEO as At, isEncryptedCredentialError as B, imageMimeForPath as Bt, FALLBACK_WORKBUDDY_MODELS_GLOBAL as C, defaultOffModelIds as Ct, fallbackModelsFor as D, recordRefusal as Dt, deriveCatalog as E, offRefused as Et, authFileName as F, IMAGE_TAG_IMAGE_TO_IMAGE as Ft, workbuddyAccountId as G, parseQueueAnswer as Gt, legacyWorkbuddyOwnAuthPath as H, parseImageDataUrl as Ht, defaultDesktopAuthCandidates as I, IMAGE_TAG_TEXT_TO_IMAGE as It, APP_VERSION as J, NATIVE_MODALITY_BY_MODEL_ID as Jt, workbuddyOwnAuthPath as K, queueNoticeText as Kt, defaultDesktopAuthDirs as L, MAX_INPUT_IMAGE_BYTES as Lt, WORKBUDDY_VAULT_DIRNAME as M, parseSupportedSecondsRange as Mt, WorkBuddyCredentialStore as N, pickVideoModel as Nt, withoutRouters as O, withEffectiveOff as Ot, WorkBuddyEncryptedCredentialError as P, resolveVideoParams as Pt, WORKBUDDY_FALLBACK_SYSTEM_PROMPT as Q, readDeviceTokenFile as Qt, defaultDesktopAuthPath as R, WorkBuddyImageError as Rt, FALLBACK_WORKBUDDY_MODELS as S, writeFileAtomic as Sn, REFUSES_OFF_MODEL_IDS as St, applyContextBudgets as T, offDefaultFor as Tt, parseWorkBuddyAuth as U, pickMediaModel as Ut, isVaultAccountId as V, isBareBase64Image as Vt, preferredAccountName as W, sniffImageMime as Wt, CREDENTIAL_REJECTED_CODE as X, nativeModalityOf as Xt, CONTEXT_OVERFLOW_MARKER as Y, imageDefaultFor as Yt, DEFAULT_WIRE_PROFILE as Z, WORKBUDDY_DEVICE_TOKEN_FILE_ENV as Zt, isDeviceMode as _, readAtRestKey as _n, prepareChatBody as _t, readHostHeartbeat as a, WORKBUDDY_APP_EXECUTABLE_ENV as an, forceNeutralHead as at, saveDeviceSdkSettings as b, resolveDshHome as bn, rewriteSessionTitleModel as bt, WORKBUDDY_CONNECT_VERSION as c, deriveAtRestKeyId as cn, isCredentialRejectedError as ct, rosterSeenPath as d, findWorkbuddyAppExecutableWithSource as dn, modelIdOfBody as dt, readDeviceSalt as en, WorkBuddyUpstreamClient as et, piAiRuntimeInfo as f, isEncryptedFieldWrapper as fn, openingEvidenceOfBody as ft, describeDerivedDevices as g, openEncryptedField as gn, perturbChannelFingerprints as gt, createDeviceProfileLookup as h, macosNestedAppBundles as hn, parseUpstreamModel as ht, processStartTimeMs as i, protectCredentialDirectory as in, describeRequestHeaderNames as it, WORKBUDDY_AUTH_FILE_ENV as j, WorkBuddyVideoError as jt, ENCRYPTED_CREDENTIAL_CODE as k, VIDEO_TAG_IMAGE_TO_VIDEO as kt, createFileRosterSeenStore as l, fetchAtRestKeyPayload as ln, isFirstMessageGateBody as lt, createTuringSdk as m, macosBundleExecutable as mn, parseReasoning as mt, clearHostHeartbeat as n, isDeviceId as nn, classifyUpstreamError as nt, workbuddyHostHeartbeatPath as o, clearAtRestKeyCache as on, isContextTooLongBody as ot, createDeviceSdkPort as p, isWorkbuddyBundle as pn, parseCreditMultiplier as pt, workbuddyVaultDir as q, pruneTempDir as qt, isHeartbeatProcessAlive as r, inspectCredentialDirectory as rn, declaredTools as rt, writeHostHeartbeat as s, deriveAtRestKey as sn, isConversationIdGateBody as st, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, deriveDeviceId as tn, channelGateMemberOf as tt, describeRosterSeenPayload as u, findWorkbuddyAppExecutable as un, knownRegionOf as ut, readDeviceSettings as v, workbuddyAppExecutableCandidates as vn, regionOf as vt, WorkBuddyCatalog as w, lastRefusalFor as wt, setDeviceMode as x, withFileLock as xn, attachBusyLevels as xt, saveDeviceProfile as y, hostPeersInfo as yn, requestEvidenceOf as yt, hasEncryptedCredentialFields as z, imageDataUrl as zt };
10434
+ export { DEFAULT_WIRE_PROFILE as $, WORKBUDDY_DEVICE_TOKEN_FILE_ENV as $t, withoutRouters as A, withEffectiveOff as At, defaultDesktopAuthPath as B, WorkBuddyImageError as Bt, setDeviceMode as C, withFileLock as Cn, attachBusyLevels as Ct, applyContextBudgets as D, offDefaultFor as Dt, WorkBuddyCatalog as E, lastRefusalFor as Et, WorkBuddyCredentialStore as F, pickVideoModel as Ft, parseWorkBuddyAuth as G, pickMediaModel as Gt, isEncryptedCredentialError as H, imageMimeForPath as Ht, WorkBuddyEncryptedCredentialError as I, resolveVideoParams as It, workbuddyOwnAuthPath as J, queueNoticeText as Jt, preferredAccountName as K, sniffImageMime as Kt, authFileName as L, IMAGE_TAG_IMAGE_TO_IMAGE as Lt, WORKBUDDY_AUTH_FILENAME as M, VIDEO_TAG_TEXT_TO_VIDEO as Mt, WORKBUDDY_AUTH_FILE_ENV as N, WorkBuddyVideoError as Nt, deriveCatalog as O, offRefused as Ot, WORKBUDDY_VAULT_DIRNAME as P, parseSupportedSecondsRange as Pt, CREDENTIAL_REJECTED_CODE as Q, nativeModalityOf as Qt, defaultDesktopAuthCandidates as R, IMAGE_TAG_TEXT_TO_IMAGE as Rt, saveDeviceSdkSettings as S, resolveDshHome as Sn, rewriteSessionTitleModel as St, FALLBACK_WORKBUDDY_MODELS_GLOBAL as T, defaultOffModelIds as Tt, isVaultAccountId as U, isBareBase64Image as Ut, hasEncryptedCredentialFields as V, imageDataUrl as Vt, legacyWorkbuddyOwnAuthPath as W, parseImageDataUrl as Wt, APP_VERSION as X, NATIVE_MODALITY_BY_MODEL_ID as Xt, workbuddyVaultDir as Y, pruneTempDir as Yt, CONTEXT_OVERFLOW_MARKER as Z, imageDefaultFor as Zt, createDeviceProfileLookup as _, macosNestedAppBundles as _n, parseUpstreamModel as _t, readHostHeartbeat as a, inspectCredentialDirectory as an, declaredTools as at, readDeviceSettings as b, workbuddyAppExecutableCandidates as bn, regionOf as bt, WORKBUDDY_CONNECT_VERSION as c, clearAtRestKeyCache as cn, isContextTooLongBody as ct, rosterSeenPath as d, fetchAtRestKeyPayload as dn, isFirstMessageGateBody as dt, readDeviceTokenFile as en, WORKBUDDY_FALLBACK_SYSTEM_PROMPT as et, WORKBUDDY_CN_BASE_ENV as f, findWorkbuddyAppExecutable as fn, knownRegionOf as ft, createTuringSdk as g, macosBundleExecutable as gn, parseReasoning as gt, createDeviceSdkPort as h, isWorkbuddyBundle as hn, parseCreditMultiplier as ht, processStartTimeMs as i, isDeviceId as in, classifyUpstreamError as it, ENCRYPTED_CREDENTIAL_CODE as j, VIDEO_TAG_IMAGE_TO_VIDEO as jt, fallbackModelsFor as k, recordRefusal as kt, createFileRosterSeenStore as l, deriveAtRestKey as ln, isConversationIdGateBody as lt, piAiRuntimeInfo as m, isEncryptedFieldWrapper as mn, openingEvidenceOfBody as mt, clearHostHeartbeat as n, readDeviceSalt as nn, WorkBuddyUpstreamClient as nt, workbuddyHostHeartbeatPath as o, protectCredentialDirectory as on, describeRequestHeaderNames as ot, resolveCnGateway as p, findWorkbuddyAppExecutableWithSource as pn, modelIdOfBody as pt, workbuddyAccountId as q, parseQueueAnswer as qt, isHeartbeatProcessAlive as r, deriveDeviceId as rn, channelGateMemberOf as rt, writeHostHeartbeat as s, WORKBUDDY_APP_EXECUTABLE_ENV as sn, forceNeutralHead as st, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, ensureDeviceSalt as tn, WorkBuddyCredentialRejectedError as tt, describeRosterSeenPayload as u, deriveAtRestKeyId as un, isCredentialRejectedError as ut, describeDerivedDevices as v, openEncryptedField as vn, perturbChannelFingerprints as vt, FALLBACK_WORKBUDDY_MODELS as w, writeFileAtomic as wn, REFUSES_OFF_MODEL_IDS as wt, saveDeviceProfile as x, hostPeersInfo as xn, requestEvidenceOf as xt, isDeviceMode as y, readAtRestKey as yn, prepareChatBody as yt, defaultDesktopAuthDirs as z, MAX_INPUT_IMAGE_BYTES as zt };
package/lib/index.d.ts CHANGED
@@ -1852,6 +1852,14 @@ declare class WorkBuddyUpstreamClient {
1852
1852
  private readonly deviceProfiles;
1853
1853
  /** 真实值档的 token 源(本机安装的桌面端 SDK);未接线时为 undefined。 */
1854
1854
  private readonly realDevice;
1855
+ /**
1856
+ * CN 网关 base(issue #220)。空 = 用内置常量,即 #220 之前的行为逐字节不变。
1857
+ *
1858
+ * 只影响 CN 区域:国际版仍然跟随凭据自己的域(`workbuddy.ai` /
1859
+ * `codebuddy.ai`),因为国际 token 跨品牌互不通用,那里没有"换一个同构主机"
1860
+ * 这回事。返回值必须已由 `resolveCnGateway` 的允许清单校验过,这个类不重新校验。
1861
+ */
1862
+ private readonly cnBaseOf;
1855
1863
  constructor(onFallback?: ((message: string) => void) | undefined, identity?: WorkBuddyWireIdentity, options?: {
1856
1864
  /** `deviceToken.file`:裸值或 A 的 `{token,ts}` 信封都可。 */
1857
1865
  deviceTokenFile?: string;
@@ -1861,6 +1869,15 @@ declare class WorkBuddyUpstreamClient {
1861
1869
  deviceProfiles?: WorkBuddyDeviceProfileLookup;
1862
1870
  /** 真实值档的 token 源(`src/turing-sdk.ts`)。 */
1863
1871
  realDevice?: TuringTokenSource;
1872
+ /**
1873
+ * CN 网关 base 覆盖(issue #220)的**读取器**,不是值。
1874
+ *
1875
+ * 为什么是函数:`regions` 是 volatile 字段,用户改完不必重启插件。若这里收
1876
+ * 一个字符串,改设置在进程生命周期内不会生效——用户会认为「填了没反应」,
1877
+ * 而这恰好是本设置唯一的用途。每次请求现问一次,与 `regionEnabled` 读活值
1878
+ * 同一条规则。返回空串表示用内置网关。
1879
+ */
1880
+ cnBase?: () => string;
1864
1881
  });
1865
1882
  /**
1866
1883
  * 本次请求的完整身份:底座(盐)+ 当前有效的真 token + 这个账号的覆盖值。
@@ -5666,6 +5683,28 @@ interface WorkBuddyRegionState {
5666
5683
  * decides, and which refuses to name a tier the model does not declare.
5667
5684
  */
5668
5685
  defaultThinkingEfforts?: Record<string, string>;
5686
+ /**
5687
+ * An alternative CN gateway host (issue #220).
5688
+ *
5689
+ * Only the CN region reads it; the international gateways follow the
5690
+ * credential's own brand domain and have no equivalent setting.
5691
+ *
5692
+ * EXISTS FOR ONE CASE: a corporate network that filters on the TLS
5693
+ * ClientHello's SNI. `copilot.tencent.com` is then reset before any HTTP is
5694
+ * sent (`ECONNRESET`, <100ms) while the WorkBuddy desktop app keeps working,
5695
+ * because the app reads a failover list from its own config and also uses
5696
+ * `wb.tencentbuddy.com`. Without this field the plugin is simply unusable on
5697
+ * such a network, and looks broken rather than filtered.
5698
+ *
5699
+ * The value is a HOST, validated against a closed allowlist by
5700
+ * `resolveCnGateway` (`src/cn-gateway.ts`) — never a free-form URL. That
5701
+ * allowlist is the security boundary, not a convenience: this base carries
5702
+ * `Authorization: Bearer <token>` on every CN request, so accepting an
5703
+ * arbitrary host would turn a settings file into a token-exfiltration
5704
+ * primitive. Empty/absent means the built-in gateway, i.e. the behaviour
5705
+ * before #220.
5706
+ */
5707
+ cnBase?: string;
5669
5708
  /** This region's account-pool preferences (opt-in; see {@link WorkBuddyPoolPreferences}). */
5670
5709
  pool?: WorkBuddyPoolPreferences;
5671
5710
  }
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as WorkBuddyCredentialRejectedError, A as WORKBUDDY_AUTH_FILENAME, At as VIDEO_TAG_TEXT_TO_VIDEO, B as isEncryptedCredentialError, Bt as imageMimeForPath, C as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Ct as defaultOffModelIds, D as fallbackModelsFor, Dt as recordRefusal, E as deriveCatalog, Et as offRefused, F as authFileName, Ft as IMAGE_TAG_IMAGE_TO_IMAGE, G as workbuddyAccountId, Gt as parseQueueAnswer, H as legacyWorkbuddyOwnAuthPath, Ht as parseImageDataUrl, I as defaultDesktopAuthCandidates, It as IMAGE_TAG_TEXT_TO_IMAGE, J as APP_VERSION, Jt as NATIVE_MODALITY_BY_MODEL_ID, K as workbuddyOwnAuthPath, Kt as queueNoticeText, L as defaultDesktopAuthDirs, Lt as MAX_INPUT_IMAGE_BYTES, Mt as parseSupportedSecondsRange, N as WorkBuddyCredentialStore, Nt as pickVideoModel, O as withoutRouters, Ot as withEffectiveOff, P as WorkBuddyEncryptedCredentialError, Pt as resolveVideoParams, Q as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, R as defaultDesktopAuthPath, Rt as WorkBuddyImageError, S as FALLBACK_WORKBUDDY_MODELS, Sn as writeFileAtomic, St as REFUSES_OFF_MODEL_IDS, T as applyContextBudgets, Tt as offDefaultFor, U as parseWorkBuddyAuth, Ut as pickMediaModel, V as isVaultAccountId, Vt as isBareBase64Image, W as preferredAccountName, Wt as sniffImageMime, X as CREDENTIAL_REJECTED_CODE, Xt as nativeModalityOf, Y as CONTEXT_OVERFLOW_MARKER, Yt as imageDefaultFor, _ as isDeviceMode, _n as readAtRestKey, _t as prepareChatBody, a as readHostHeartbeat, an as WORKBUDDY_APP_EXECUTABLE_ENV, at as forceNeutralHead, b as saveDeviceSdkSettings, bn as resolveDshHome, bt as rewriteSessionTitleModel, c as WORKBUDDY_CONNECT_VERSION, cn as deriveAtRestKeyId, ct as isCredentialRejectedError, dt as modelIdOfBody, et as WorkBuddyUpstreamClient, f as piAiRuntimeInfo, fn as isEncryptedFieldWrapper, ft as openingEvidenceOfBody, g as describeDerivedDevices, gn as openEncryptedField, gt as perturbChannelFingerprints, h as createDeviceProfileLookup, hn as macosNestedAppBundles, ht as parseUpstreamModel, i as processStartTimeMs, j as WORKBUDDY_AUTH_FILE_ENV, jt as WorkBuddyVideoError, k as ENCRYPTED_CREDENTIAL_CODE, kt as VIDEO_TAG_IMAGE_TO_VIDEO, l as createFileRosterSeenStore, ln as fetchAtRestKeyPayload, lt as isFirstMessageGateBody, m as createTuringSdk, mn as macosBundleExecutable, mt as parseReasoning, n as clearHostHeartbeat, nn as isDeviceId, nt as classifyUpstreamError, o as workbuddyHostHeartbeatPath, on as clearAtRestKeyCache, ot as isContextTooLongBody, p as createDeviceSdkPort, pn as isWorkbuddyBundle, pt as parseCreditMultiplier, qt as pruneTempDir, r as isHeartbeatProcessAlive, rt as declaredTools, s as writeHostHeartbeat, sn as deriveAtRestKey, st as isConversationIdGateBody, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as channelGateMemberOf, un as findWorkbuddyAppExecutable, ut as knownRegionOf, v as readDeviceSettings, vn as workbuddyAppExecutableCandidates, vt as regionOf, w as WorkBuddyCatalog, wt as lastRefusalFor, x as setDeviceMode, xn as withFileLock, xt as attachBusyLevels, y as saveDeviceProfile, yt as requestEvidenceOf, z as hasEncryptedCredentialFields, zt as imageDataUrl } from "./host-heartbeat-hEksLFOK.js";
1
+ import { A as withoutRouters, At as withEffectiveOff, B as defaultDesktopAuthPath, Bt as WorkBuddyImageError, C as setDeviceMode, Cn as withFileLock, Ct as attachBusyLevels, D as applyContextBudgets, Dt as offDefaultFor, E as WorkBuddyCatalog, Et as lastRefusalFor, F as WorkBuddyCredentialStore, Ft as pickVideoModel, G as parseWorkBuddyAuth, Gt as pickMediaModel, H as isEncryptedCredentialError, Ht as imageMimeForPath, I as WorkBuddyEncryptedCredentialError, It as resolveVideoParams, J as workbuddyOwnAuthPath, Jt as queueNoticeText, K as preferredAccountName, Kt as sniffImageMime, L as authFileName, Lt as IMAGE_TAG_IMAGE_TO_IMAGE, M as WORKBUDDY_AUTH_FILENAME, Mt as VIDEO_TAG_TEXT_TO_VIDEO, N as WORKBUDDY_AUTH_FILE_ENV, Nt as WorkBuddyVideoError, O as deriveCatalog, Ot as offRefused, Pt as parseSupportedSecondsRange, Q as CREDENTIAL_REJECTED_CODE, Qt as nativeModalityOf, R as defaultDesktopAuthCandidates, Rt as IMAGE_TAG_TEXT_TO_IMAGE, S as saveDeviceSdkSettings, Sn as resolveDshHome, St as rewriteSessionTitleModel, T as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Tt as defaultOffModelIds, U as isVaultAccountId, Ut as isBareBase64Image, V as hasEncryptedCredentialFields, Vt as imageDataUrl, W as legacyWorkbuddyOwnAuthPath, Wt as parseImageDataUrl, X as APP_VERSION, Xt as NATIVE_MODALITY_BY_MODEL_ID, Yt as pruneTempDir, Z as CONTEXT_OVERFLOW_MARKER, Zt as imageDefaultFor, _ as createDeviceProfileLookup, _n as macosNestedAppBundles, _t as parseUpstreamModel, a as readHostHeartbeat, at as declaredTools, b as readDeviceSettings, bn as workbuddyAppExecutableCandidates, bt as regionOf, c as WORKBUDDY_CONNECT_VERSION, cn as clearAtRestKeyCache, ct as isContextTooLongBody, dn as fetchAtRestKeyPayload, dt as isFirstMessageGateBody, et as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, fn as findWorkbuddyAppExecutable, ft as knownRegionOf, g as createTuringSdk, gn as macosBundleExecutable, gt as parseReasoning, h as createDeviceSdkPort, hn as isWorkbuddyBundle, ht as parseCreditMultiplier, i as processStartTimeMs, in as isDeviceId, it as classifyUpstreamError, j as ENCRYPTED_CREDENTIAL_CODE, jt as VIDEO_TAG_IMAGE_TO_VIDEO, k as fallbackModelsFor, kt as recordRefusal, l as createFileRosterSeenStore, ln as deriveAtRestKey, lt as isConversationIdGateBody, m as piAiRuntimeInfo, mn as isEncryptedFieldWrapper, mt as openingEvidenceOfBody, n as clearHostHeartbeat, nt as WorkBuddyUpstreamClient, o as workbuddyHostHeartbeatPath, p as resolveCnGateway, pt as modelIdOfBody, q as workbuddyAccountId, qt as parseQueueAnswer, r as isHeartbeatProcessAlive, rt as channelGateMemberOf, s as writeHostHeartbeat, sn as WORKBUDDY_APP_EXECUTABLE_ENV, st as forceNeutralHead, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as WorkBuddyCredentialRejectedError, un as deriveAtRestKeyId, ut as isCredentialRejectedError, v as describeDerivedDevices, vn as openEncryptedField, vt as perturbChannelFingerprints, w as FALLBACK_WORKBUDDY_MODELS, wn as writeFileAtomic, wt as REFUSES_OFF_MODEL_IDS, x as saveDeviceProfile, xt as requestEvidenceOf, y as isDeviceMode, yn as readAtRestKey, yt as prepareChatBody, z as defaultDesktopAuthDirs, zt as MAX_INPUT_IMAGE_BYTES } from "./host-heartbeat-BTTe5VDs.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { appendFile, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -12543,6 +12543,18 @@ const regionStateConfig = z.object({
12543
12543
  enabledModelIds: z.array(z.string()).default([]),
12544
12544
  imageModelIds: z.array(z.string()).default([]),
12545
12545
  /**
12546
+ * Alternative CN gateway host (issue #220); see the interface field of the
12547
+ * same name. Empty = the built-in gateway.
12548
+ *
12549
+ * A plain string rather than a `union` of the allowed hosts on purpose: the
12550
+ * allowlist lives in `src/cn-gateway.ts` and is enforced there with an
12551
+ * explicit reason the card can word ("not a known CN host" vs "not https").
12552
+ * Encoding it in the schema too would produce a validation error the settings
12553
+ * layer reports as a generic schema failure, and the user would be told their
12554
+ * value is invalid without being told which rule it broke.
12555
+ */
12556
+ cnBase: z.string().default("").description("Alternative CN gateway host for networks that filter copilot.tencent.com by TLS SNI (issue #220). Must be an https URL on one of the CN brands: copilot.tencent.com, wb.tencentbuddy.com, www.workbuddy.cn, www.codebuddy.cn (any subdomain of those registrable domains). Empty keeps the built-in gateway. Chat, billing, catalog and check-in all follow it; Origin/Referer keep naming the CN web app. CONNECTION-LAYER failures only — set it after a filter, not to change your account or region."),
12557
+ /**
12546
12558
  * Whether the model may call the image-generation tool (opt-IN, default off).
12547
12559
  *
12548
12560
  * Per-REGION like the credit switches, and it now means the same thing on both
@@ -12953,6 +12965,28 @@ function apply(ctx, config) {
12953
12965
  ctx.effect(() => () => {
12954
12966
  turing.stopAutoRefresh();
12955
12967
  });
12968
+ /**
12969
+ * Announce a CN gateway override, ONCE per distinct value / failure.
12970
+ *
12971
+ * The reader runs on every CN request, so logging unconditionally would turn
12972
+ * one misconfiguration into a warn per request. Keyed on the VALUE rather than
12973
+ * a plain boolean, so fixing the setting and breaking it again both get said —
12974
+ * a user who is iterating on hosts needs to see each attempt acknowledged.
12975
+ */
12976
+ let announcedCnBase;
12977
+ let announcedCnBaseFailure;
12978
+ const warnCnBaseOnce = (base) => {
12979
+ if (announcedCnBase === base) return;
12980
+ announcedCnBase = base;
12981
+ ctx.logger.warn(`dsh-connect-workbuddy: CN gateway overridden to ${base} (issue #220). Chat, billing, catalog and check-in follow it; Origin/Referer still name the CN web app.`);
12982
+ };
12983
+ const warnCnBaseInvalidOnce = (reason, value) => {
12984
+ const key = `${reason}:${value}`;
12985
+ if (announcedCnBaseFailure === key) return;
12986
+ announcedCnBaseFailure = key;
12987
+ const why = reason === "malformed" ? "it is not an absolute URL" : reason === "insecure" ? "only https is accepted (a plaintext base would put the bearer token on the wire in clear)" : "its host is not one of the CN brands (copilot.tencent.com, wb.tencentbuddy.com, workbuddy.cn, codebuddy.cn)";
12988
+ ctx.logger.warn(`dsh-connect-workbuddy: ignoring regions.cn.cnBase "${value}" — ${why}. Using the built-in CN gateway.`);
12989
+ };
12956
12990
  const client = new WorkBuddyUpstreamClient((message) => {
12957
12991
  ctx.logger.warn(`dsh-connect-workbuddy: ${message}`);
12958
12992
  }, {
@@ -12965,7 +12999,28 @@ function apply(ctx, config) {
12965
12999
  deviceTokenFile: configured !== "" ? configured : (process.env["WORKBUDDY_DEVICE_TOKEN_FILE"] ?? "").trim(),
12966
13000
  ...typeof token?.ttlMs === "number" ? { deviceTokenTtlMs: token.ttlMs } : {},
12967
13001
  deviceProfiles,
12968
- realDevice: turing.tokens
13002
+ realDevice: turing.tokens,
13003
+ /**
13004
+ * CN 网关覆盖(issue #220):**每次请求现读**,不是一个采样值。
13005
+ *
13006
+ * `regions` 是 volatile 字段,用户保存后不重启插件;这里若在构造期采样
13007
+ * 一次,改设置就只有重启才生效,而「填了没反应」正是本设置唯一的用途。
13008
+ *
13009
+ * 只对 CN 生效,且只有 `resolveCnGateway` 通过时才返回覆盖值:
13010
+ * 校验失败一律退回内置网关并记一条 warn。**退回而不是抛**,因为这条
13011
+ * 路径在每一请求上;但绝不静默——用户填了个不被接受的 host 却一直用着
13012
+ * 默认网关,会让他继续怀疑是网络,而不是自己填错。
13013
+ */
13014
+ cnBase: () => {
13015
+ const raw = regionStateOf(current(), "cn").cnBase;
13016
+ const resolved = resolveCnGateway(raw);
13017
+ if (resolved.ok) {
13018
+ if (resolved.overridden) warnCnBaseOnce(resolved.base);
13019
+ return resolved.overridden ? resolved.base : "";
13020
+ }
13021
+ warnCnBaseInvalidOnce(resolved.reason, resolved.value);
13022
+ return "";
13023
+ }
12969
13024
  };
12970
13025
  })());
12971
13026
  /**
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-connect-workbuddy",
3
3
  "displayName": "DSH Connect WorkBuddy",
4
4
  "description": "把本机登录的 WorkBuddy 模型(国内版与国际版)接入 DeepSeek Harness:每次刷新按上游目录自动读取每个模型的积分倍率,支持逐模型图片输入开关、多账号切换与账号池自动换号,并提供每日签到、卡片与输入框里的胶囊积分读数等只读积分概览。",
5
- "version": "5.19.1",
5
+ "version": "5.20.0",
6
6
  "author": "dingminhua",
7
7
  "copyright": "Copyright (c) 2026 LaoDing",
8
8
  "license": "MIT",